@jskit-ai/workspaces-core 0.2.31 → 0.2.33
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 +4 -0
- package/package.json +9 -9
- package/src/server/common/services/workspaceDirectoryService.js +29 -29
- package/src/server/types.js +4 -3
- package/src/server/workspaceMembers/workspaceMembersRoutes.js +16 -10
- package/src/server/workspaceMembers/workspaceMembersService.js +1 -0
- package/test/repositories.integration.test.js +31 -0
- package/test/workspaceDirectoryService.mysql.test.js +5 -4
- package/test/workspaceMemberListRoutes.test.js +191 -0
- package/test/workspaceMembersService.test.js +3 -0
- package/test/workspaceRequestContextQueries.test.js +69 -4
- package/test/workspaceService.test.js +4 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- `GET .../members` and `GET .../invites` (`workspace.members.list` and `workspace.invites.list`) answer a request that leaves out `page[cursor]` or `page[limit]` again, such as every first page the members screen reads (`page[limit]=20`). Since 0.2.25 those answered 400 `ACTION_VALIDATION_FAILED`, "Value could not be cast to the required type." at `/data/attributes/cursor` (and at `/data/attributes/limit` when no limit was named), so the members screen showed no members and no invitations in any workspace. The routes handed their action `cursor` and `limit` by name, undefined when the query left one out, and an action's input refuses a field that is present but undefined; they now hand on only the fields the query sends. A route test reads both lists, first and next pages, through Fastify, the auth policy, the list actions and the JSON:API transport and serializer.
|
|
6
|
+
|
|
7
|
+
- A workspace route whose auth policy and action context differ in requiring membership (`contextPolicy: "optional"` on a route with `visibility: "workspace"`) reads its workspace context once per request instead of twice. The per-request cache keyed its reads by the membership requirement as well as the user and slug, so the two callers read the workspace, the membership and the settings each. Reads are now cached per user and slug, and each caller checks membership against the shared result: 401 `workspaces.auth.required` signed out, 403 `workspaces.workspace.accessDenied` for a non-member where membership is required, as before.
|
|
8
|
+
- The workspace invite mailer's `sendWorkspaceInvite` receives the invitation's id as `inviteId`, beside `email`, `inviteUrl`, `workspace` (with its `id`), `inviter`, `roleSid`, `expiresAt`, `locale` and `message`, so a mailer can record which invitation each email delivers.
|
|
5
9
|
- 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
10
|
- 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
11
|
- 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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/workspaces-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.33",
|
|
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.
|
|
27
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
28
|
-
"@jskit-ai/users-core": "0.2.
|
|
26
|
+
"@jskit-ai/resource-core": "0.1.212",
|
|
27
|
+
"@jskit-ai/resource-crud-core": "0.1.214",
|
|
28
|
+
"@jskit-ai/users-core": "0.2.33",
|
|
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.
|
|
215
|
-
"@jskit-ai/database-runtime": "0.1.
|
|
216
|
-
"@jskit-ai/http-runtime": "0.2.
|
|
217
|
-
"@jskit-ai/kernel": "0.2.
|
|
218
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
214
|
+
"@jskit-ai/auth-core": "0.2.21",
|
|
215
|
+
"@jskit-ai/database-runtime": "0.1.270",
|
|
216
|
+
"@jskit-ai/http-runtime": "0.2.21",
|
|
217
|
+
"@jskit-ai/kernel": "0.2.21",
|
|
218
|
+
"@jskit-ai/resource-runtime": "0.2.26"
|
|
219
219
|
}
|
|
220
220
|
}
|
|
@@ -248,48 +248,52 @@ 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, its route visibility and its
|
|
252
|
-
//
|
|
253
|
-
//
|
|
254
|
-
//
|
|
255
|
-
// its own.
|
|
251
|
+
// The checks that run before a request's handler (its auth policy, its route visibility and its action context) each
|
|
252
|
+
// need the request's workspace context, some requiring membership and some not (a route with contextPolicy
|
|
253
|
+
// "optional" and no permission). They pass the request and share one read of the workspace, the user's membership
|
|
254
|
+
// and the settings for the same user and slug; each call then applies its own membership requirement. A call
|
|
255
|
+
// without a request reads on its own.
|
|
256
256
|
const requestWorkspaceContexts = new WeakMap();
|
|
257
257
|
|
|
258
258
|
/**
|
|
259
|
+
* A surface that requires membership refuses an anonymous visitor (401) and a non-member (403); one that does not (a
|
|
260
|
+
* public payment link) resolves the workspace for them with no membership and no permissions.
|
|
259
261
|
* @param {{ id?: unknown } | null} user
|
|
260
262
|
* @param {string} workspaceSlug
|
|
261
263
|
* @param {{ request?: object, requireMembership?: boolean }} [options]
|
|
262
264
|
*/
|
|
263
|
-
function resolveWorkspaceContextForUserBySlug(user, workspaceSlug, options = {}) {
|
|
265
|
+
async function resolveWorkspaceContextForUserBySlug(user, workspaceSlug, options = {}) {
|
|
266
|
+
const requireMembership = options.requireMembership !== false;
|
|
267
|
+
if (requireMembership && !normalizeRecordId(user?.id, { fallback: null })) {
|
|
268
|
+
throw new AppError(401, "Authentication required.", { code: "workspaces.auth.required" });
|
|
269
|
+
}
|
|
270
|
+
const workspaceContext = await readRequestWorkspaceContext(user, workspaceSlug, options);
|
|
271
|
+
if (requireMembership && !workspaceContext.membership) {
|
|
272
|
+
throw new AppError(403, "You do not have access to this workspace.", { code: "workspaces.workspace.accessDenied" });
|
|
273
|
+
}
|
|
274
|
+
return workspaceContext;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function readRequestWorkspaceContext(user, workspaceSlug, options) {
|
|
264
278
|
const request = options.request;
|
|
265
279
|
if (!request || typeof request !== "object") {
|
|
266
280
|
return readWorkspaceContextForUserBySlug(user, workspaceSlug, options);
|
|
267
281
|
}
|
|
268
|
-
const key =
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
let resolutions = requestWorkspaceContexts.get(request);
|
|
274
|
-
if (!resolutions) {
|
|
275
|
-
resolutions = new Map();
|
|
276
|
-
requestWorkspaceContexts.set(request, resolutions);
|
|
282
|
+
const key = `${normalizeRecordId(user?.id, { fallback: "" })}\0${normalizeLowerText(workspaceSlug)}`;
|
|
283
|
+
let reads = requestWorkspaceContexts.get(request);
|
|
284
|
+
if (!reads) {
|
|
285
|
+
reads = new Map();
|
|
286
|
+
requestWorkspaceContexts.set(request, reads);
|
|
277
287
|
}
|
|
278
|
-
if (!
|
|
279
|
-
|
|
288
|
+
if (!reads.has(key)) {
|
|
289
|
+
reads.set(key, readWorkspaceContextForUserBySlug(user, workspaceSlug, options));
|
|
280
290
|
}
|
|
281
|
-
return
|
|
291
|
+
return reads.get(key);
|
|
282
292
|
}
|
|
283
293
|
|
|
284
|
-
//
|
|
285
|
-
// resolves the workspace for them with no membership and no permissions, as it does for a signed-in non-member.
|
|
294
|
+
// The workspace, the user's active membership (null for an anonymous visitor or a non-member) and the settings.
|
|
286
295
|
async function readWorkspaceContextForUserBySlug(user, workspaceSlug, options = {}) {
|
|
287
|
-
const requireMembership = options.requireMembership !== false;
|
|
288
296
|
const normalizedUserId = normalizeRecordId(user?.id, { fallback: null });
|
|
289
|
-
if (!normalizedUserId && requireMembership) {
|
|
290
|
-
throw new AppError(401, "Authentication required.", { code: "workspaces.auth.required" });
|
|
291
|
-
}
|
|
292
|
-
|
|
293
297
|
if (resolvedTenancyMode === TENANCY_MODE_NONE) {
|
|
294
298
|
throw new AppError(403, "Workspace context is disabled.", { code: "workspaces.workspace.contextDisabled" });
|
|
295
299
|
}
|
|
@@ -316,10 +320,6 @@ function createService({
|
|
|
316
320
|
membership = await workspaceMembershipsRepository.ensureOwnerMembership(workspace.id, normalizedUserId, options);
|
|
317
321
|
}
|
|
318
322
|
|
|
319
|
-
if ((!membership || normalizeLowerText(membership.status) !== "active") && requireMembership) {
|
|
320
|
-
throw new AppError(403, "You do not have access to this workspace.", { code: "workspaces.workspace.accessDenied" });
|
|
321
|
-
}
|
|
322
|
-
|
|
323
323
|
if (!membership || normalizeLowerText(membership.status) !== "active") {
|
|
324
324
|
membership = null;
|
|
325
325
|
}
|
package/src/server/types.js
CHANGED
|
@@ -30,10 +30,11 @@
|
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
32
|
* The `workspaces.invite-mailer` capability: a feature that provides it sends
|
|
33
|
-
* workspace invitation email.
|
|
34
|
-
*
|
|
33
|
+
* workspace invitation email. It is told which saved invitation it sends
|
|
34
|
+
* (`inviteId`, its `workspace_invites` row, in `workspace.id`'s workspace).
|
|
35
|
+
* Its result is the delivery outcome; the status defaults to "sent".
|
|
35
36
|
* @typedef {object} WorkspaceInviteMailer
|
|
36
|
-
* @property {(message: { email: string, inviteUrl: string, workspace:
|
|
37
|
+
* @property {(message: { inviteId: string, email: string, inviteUrl: string, workspace: { id: string, slug: string, name: string, ownerUserId: string, avatarUrl: string }, inviter: object | null, roleSid: string, expiresAt: string, locale: string, message: object }, options?: object) => Promise<{ status?: string, message?: string, messageCode?: string, messageParams?: object, providerMessageId?: string } | void>} sendWorkspaceInvite
|
|
37
38
|
*/
|
|
38
39
|
|
|
39
40
|
/**
|
|
@@ -15,6 +15,20 @@ import {
|
|
|
15
15
|
} from "../common/validators/routeParamsValidator.js";
|
|
16
16
|
import { resolveDefaultWorkspaceRouteSurfaceIdFromAppConfig } from "../support/workspaceActionSurfaces.js";
|
|
17
17
|
|
|
18
|
+
/**
|
|
19
|
+
* A members or invites list request's action input: its workspace, and the cursor and limit its query sends, each only
|
|
20
|
+
* when sent. An action's input refuses a field that is present but undefined, so naming an absent one refused every
|
|
21
|
+
* first page with 400.
|
|
22
|
+
* @param {{ params: { workspaceSlug: string }, query: { cursor?: string, limit?: number } }} input The request's input.
|
|
23
|
+
*/
|
|
24
|
+
function listPageActionInput({ params, query }) {
|
|
25
|
+
return {
|
|
26
|
+
workspaceSlug: params.workspaceSlug,
|
|
27
|
+
...(Object.hasOwn(query, "cursor") ? { cursor: query.cursor } : {}),
|
|
28
|
+
...(Object.hasOwn(query, "limit") ? { limit: query.limit } : {})
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
18
32
|
/**
|
|
19
33
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router
|
|
20
34
|
* @param {{ config: import("@jskit-ai/kernel/server/types").RuntimeConfig, workspaceInvitationsEnabled: boolean }} options
|
|
@@ -77,11 +91,7 @@ function registerWorkspaceMembersRoutes(router, { config, workspaceInvitationsEn
|
|
|
77
91
|
async function (request, reply) {
|
|
78
92
|
const response = await request.executeAction({
|
|
79
93
|
actionId: "workspace.members.list",
|
|
80
|
-
input:
|
|
81
|
-
workspaceSlug: request.input.params.workspaceSlug,
|
|
82
|
-
cursor: request.input.query.cursor,
|
|
83
|
-
limit: request.input.query.limit
|
|
84
|
-
}
|
|
94
|
+
input: listPageActionInput(request.input)
|
|
85
95
|
});
|
|
86
96
|
reply.code(200).send(response);
|
|
87
97
|
}
|
|
@@ -179,11 +189,7 @@ function registerWorkspaceMembersRoutes(router, { config, workspaceInvitationsEn
|
|
|
179
189
|
async function (request, reply) {
|
|
180
190
|
const response = await request.executeAction({
|
|
181
191
|
actionId: "workspace.invites.list",
|
|
182
|
-
input:
|
|
183
|
-
workspaceSlug: request.input.params.workspaceSlug,
|
|
184
|
-
cursor: request.input.query.cursor,
|
|
185
|
-
limit: request.input.query.limit
|
|
186
|
-
}
|
|
192
|
+
input: listPageActionInput(request.input)
|
|
187
193
|
});
|
|
188
194
|
reply.code(200).send(response);
|
|
189
195
|
}
|
|
@@ -175,6 +175,7 @@ function createService({
|
|
|
175
175
|
t: (key, params) => i18n.t(locale, key, params)
|
|
176
176
|
});
|
|
177
177
|
const result = await workspaceInviteMailer.sendWorkspaceInvite({
|
|
178
|
+
inviteId: normalizeRecordId(invite.id, { fallback: "" }),
|
|
178
179
|
email: invite.email,
|
|
179
180
|
inviteUrl,
|
|
180
181
|
workspace: mapMembersWorkspace(workspace),
|
|
@@ -312,6 +312,37 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
|
|
|
312
312
|
);
|
|
313
313
|
});
|
|
314
314
|
|
|
315
|
+
test("workspaces.lock and memberships.lockByWorkspaceIdAndUserId take lockMode share, and refuse another mode before any statement", async () => {
|
|
316
|
+
const owner = await createProfile("Ada");
|
|
317
|
+
const workspace = await workspaces.insert({ slug: "shared", name: "Shared", ownerUserId: owner.id });
|
|
318
|
+
await memberships.ensureOwnerMembership(workspace.id, owner.id);
|
|
319
|
+
// A read check that needs the workspace and the membership unchanged until it commits holds them shared.
|
|
320
|
+
const { result, sql } = await statementsOf(() => workspaces.withTransaction({}, async (txOptions) => {
|
|
321
|
+
const shared = { ...txOptions, lockMode: "share" };
|
|
322
|
+
return [
|
|
323
|
+
await workspaces.lock(workspace.id, shared),
|
|
324
|
+
(await memberships.lockByWorkspaceIdAndUserId(workspace.id, owner.id, shared))?.userId
|
|
325
|
+
];
|
|
326
|
+
}));
|
|
327
|
+
assert.deepEqual(result, [{ id: workspace.id }, owner.id]);
|
|
328
|
+
const locking = sql.filter((statement) => /\bfor (?:update|share|no key update)\b|\block in share mode\b/iu.test(statement));
|
|
329
|
+
const clause = { pg: /\bfor share\b/iu, mysql2: /\block in share mode\b/iu }[configuration.client];
|
|
330
|
+
if (clause) {
|
|
331
|
+
// PostgreSQL's lockWhere reads its rows again after the lock, so the membership's lock may be two statements.
|
|
332
|
+
assert.ok(locking.some((statement) => /\bfrom [`"]?workspaces[`"]? /u.test(statement)), sql.join(" | "));
|
|
333
|
+
assert.ok(locking.some((statement) => /\bfrom [`"]?workspace_memberships[`"]? /u.test(statement)), sql.join(" | "));
|
|
334
|
+
assert.ok(locking.every((statement) => clause.test(statement)), locking.join(" | "));
|
|
335
|
+
} else {
|
|
336
|
+
assert.deepEqual(locking, [], "SQLite takes its write lock, not a row lock");
|
|
337
|
+
}
|
|
338
|
+
const refused = await statementsOf(() => workspaces.withTransaction({}, async (txOptions) => {
|
|
339
|
+
const exclusive = { ...txOptions, lockMode: "exclusive" };
|
|
340
|
+
await assert.rejects(workspaces.lock(workspace.id, exclusive), { name: "TypeError", message: /lockMode is "update" \(the default\), "noKeyUpdate" or "share"/u });
|
|
341
|
+
await assert.rejects(memberships.lockByWorkspaceIdAndUserId(workspace.id, owner.id, exclusive), { name: "TypeError", message: /lockMode is "update" \(the default\), "noKeyUpdate" or "share"/u });
|
|
342
|
+
}));
|
|
343
|
+
assert.equal(refused.sql.filter((statement) => /^\s*select\b/iu.test(statement)).length, 0, refused.sql.join(" | "));
|
|
344
|
+
});
|
|
345
|
+
|
|
315
346
|
test("another owner's report joins the workspaces' and memberships' join sources in one statement, each keeping its filters and the report its scope", async (t) => {
|
|
316
347
|
// Another feature's workspace-owned table, whose report reads each row's workspace slug and active membership.
|
|
317
348
|
await knex.schema.createTable("test_reminders", (table) => {
|
|
@@ -218,10 +218,11 @@ test("the workspace context answers a member's workspace, membership, permission
|
|
|
218
218
|
errorWith(403, "workspaces.workspace.contextDisabled", "Workspace context is disabled."));
|
|
219
219
|
|
|
220
220
|
const request = {};
|
|
221
|
-
const shared =
|
|
222
|
-
|
|
223
|
-
"
|
|
224
|
-
|
|
221
|
+
const [shared, again] = await Promise.all([
|
|
222
|
+
directory.resolveWorkspaceContextForUserBySlug(owner, "context-team", { request }),
|
|
223
|
+
directory.resolveWorkspaceContextForUserBySlug(owner, "Context-Team", { request })
|
|
224
|
+
]);
|
|
225
|
+
assert.equal(again, shared, "one request reads one context for the same user and slug");
|
|
225
226
|
});
|
|
226
227
|
|
|
227
228
|
test("get and update read the context first and save only the patchable fields", async () => {
|
|
@@ -0,0 +1,191 @@
|
|
|
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 { HttpProvider } from "@jskit-ai/kernel/server/http";
|
|
7
|
+
import { createBootstrapRuntime } from "@jskit-ai/kernel/server/runtime";
|
|
8
|
+
import { createPackageTestKnex, startTestFeatures } from "@jskit-ai/resource-runtime/test";
|
|
9
|
+
import { UsersExtensionsProvider } from "@jskit-ai/users-core/server/UsersExtensionsProvider";
|
|
10
|
+
import { UsersIdentityProvider } from "@jskit-ai/users-core/server/UsersIdentityProvider";
|
|
11
|
+
import { WorkspacesFeature } from "../src/server/WorkspacesFeature.js";
|
|
12
|
+
import { WorkspacesIntegrationsProvider } from "../src/server/WorkspacesIntegrationsProvider.js";
|
|
13
|
+
|
|
14
|
+
// The members and invites lists as the members screen reads them: GET .../members and GET .../invites through
|
|
15
|
+
// Fastify, the auth policy, the routes' query validation, the list actions and the JSON:API serializer. The service
|
|
16
|
+
// tests call the service directly, so a route that handed its action a bad input went unseen: every first page,
|
|
17
|
+
// which names no cursor, answered 400 "Value could not be cast" pointing at /data/attributes/cursor.
|
|
18
|
+
|
|
19
|
+
const config = Object.freeze({
|
|
20
|
+
appPublicUrl: "http://localhost:5173",
|
|
21
|
+
tenancyMode: "workspaces",
|
|
22
|
+
tenancyPolicy: { workspace: { allowSelfCreate: true } },
|
|
23
|
+
workspaceInvitations: { enabled: true },
|
|
24
|
+
workspaceMembers: { defaults: { inviteExpiresInMs: 86400000 } },
|
|
25
|
+
workspaceSettings: { defaults: { invitesEnabled: true } },
|
|
26
|
+
surfaceDefaultId: "app",
|
|
27
|
+
surfaceDefinitions: { app: { id: "app", requiresWorkspace: true, accessPolicyId: "workspace_member" } },
|
|
28
|
+
surfaceAccessPolicies: { workspace_member: { requireWorkspaceMembership: true } },
|
|
29
|
+
roleCatalog: {
|
|
30
|
+
workspace: { defaultInviteRole: "member" },
|
|
31
|
+
roles: {
|
|
32
|
+
owner: { permissions: ["*"] },
|
|
33
|
+
member: { assignable: true, permissions: ["workspace.members.view"] },
|
|
34
|
+
guest: { assignable: true, permissions: [] }
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// The signed-in user is the profile the test names in a header, as a session would name it.
|
|
40
|
+
const headerAuthService = Object.freeze({
|
|
41
|
+
async authenticateRequest(request) {
|
|
42
|
+
const id = String(request.headers["x-test-user"] || "");
|
|
43
|
+
return id
|
|
44
|
+
? { authenticated: true, actor: { id, email: `${id}@example.com`, displayName: id }, transientFailure: false }
|
|
45
|
+
: { authenticated: false, actor: null, transientFailure: false };
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
async function membersApp(t) {
|
|
50
|
+
const knex = await createPackageTestKnex(t, { environment: process.env });
|
|
51
|
+
const app = Fastify();
|
|
52
|
+
t.after(() => app.close());
|
|
53
|
+
const started = await startTestFeatures({
|
|
54
|
+
knex,
|
|
55
|
+
createTables: true,
|
|
56
|
+
features: [
|
|
57
|
+
HttpProvider,
|
|
58
|
+
AuthExtensionsProvider,
|
|
59
|
+
AuthPolicyProvider,
|
|
60
|
+
UsersExtensionsProvider,
|
|
61
|
+
UsersIdentityProvider,
|
|
62
|
+
WorkspacesFeature,
|
|
63
|
+
WorkspacesIntegrationsProvider
|
|
64
|
+
],
|
|
65
|
+
requires: { profiles: "users.profiles", workspaces: "workspaces.core", memberships: "workspaces.memberships" },
|
|
66
|
+
inputs: {
|
|
67
|
+
"auth.service": headerAuthService,
|
|
68
|
+
"runtime.app-root": process.cwd(),
|
|
69
|
+
"runtime.bootstrap": createBootstrapRuntime(),
|
|
70
|
+
"runtime.config": config,
|
|
71
|
+
"runtime.env": {},
|
|
72
|
+
"runtime.fastify": app
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
t.after(started.stop);
|
|
76
|
+
const { profiles, workspaces, memberships } = started.capabilities;
|
|
77
|
+
const person = (name) => profiles.upsert({
|
|
78
|
+
authProvider: "local",
|
|
79
|
+
authProviderUserSid: `identity-${name}`,
|
|
80
|
+
email: `${name}@example.com`,
|
|
81
|
+
displayName: name
|
|
82
|
+
});
|
|
83
|
+
const owner = await person("owner");
|
|
84
|
+
const member = await person("member");
|
|
85
|
+
const guest = await person("guest");
|
|
86
|
+
const outsider = await person("outsider");
|
|
87
|
+
const workspace = await workspaces.services.directory.ensurePersonalWorkspaceForUser(owner);
|
|
88
|
+
await workspaces.services.directory.ensurePersonalWorkspaceForUser(outsider);
|
|
89
|
+
await memberships.addMember({ workspaceId: workspace.id, userId: member.id });
|
|
90
|
+
await memberships.addMember({ workspaceId: workspace.id, userId: guest.id, roleSid: "guest" });
|
|
91
|
+
for (const email of ["ivy@example.com", "jon@example.com", "kim@example.com"]) {
|
|
92
|
+
await workspaces.services.members.createInvite(workspace, owner, { email, roleSid: "member" });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const get = (user, path, { query = {}, slug = workspace.slug } = {}) => app.inject({
|
|
96
|
+
method: "GET",
|
|
97
|
+
url: `/api/w/${slug}/${path}`,
|
|
98
|
+
query,
|
|
99
|
+
headers: user ? { "x-test-user": user.id } : {}
|
|
100
|
+
});
|
|
101
|
+
return { get, owner, member, guest, outsider, workspace };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// A page's query as the JSON:API transport sends it: http-web's useList names its limit (20 unless the screen says
|
|
105
|
+
// otherwise) and, from the second page on, the previous page's nextCursor.
|
|
106
|
+
const page = (limit, cursor) => ({
|
|
107
|
+
query: {
|
|
108
|
+
...(limit === undefined ? {} : { "page[limit]": String(limit) }),
|
|
109
|
+
...(cursor === undefined ? {} : { "page[cursor]": cursor })
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
// A list response's attributes, after checking it answered 200 as a workspace record of its JSON:API type.
|
|
114
|
+
function listAttributes(response, type, workspace) {
|
|
115
|
+
assert.equal(response.statusCode, 200, response.body);
|
|
116
|
+
const { data } = response.json();
|
|
117
|
+
assert.equal(data.type, type, response.body);
|
|
118
|
+
assert.equal(data.id, String(workspace.id), response.body);
|
|
119
|
+
return data.attributes;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const displayNames = (attributes) => attributes.members.map(({ displayName }) => displayName);
|
|
123
|
+
const inviteEmails = (attributes) => attributes.invites.map(({ email }) => email).sort();
|
|
124
|
+
|
|
125
|
+
test("the members list answers its first page and each next page through its route", async (t) => {
|
|
126
|
+
const { get, owner, member, workspace } = await membersApp(t);
|
|
127
|
+
|
|
128
|
+
// The members screen's first page, and a caller that names no page at all.
|
|
129
|
+
for (const user of [owner, member]) {
|
|
130
|
+
for (const request of [page(20), page()]) {
|
|
131
|
+
const all = listAttributes(await get(user, "members", request), "workspace-members", workspace);
|
|
132
|
+
assert.deepEqual(displayNames(all), ["guest", "member", "owner"]);
|
|
133
|
+
assert.equal(all.nextCursor, null);
|
|
134
|
+
assert.equal(all.workspace.slug, workspace.slug);
|
|
135
|
+
assert.ok(all.roleCatalog.roles.length > 0);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const first = listAttributes(await get(owner, "members", page(2)), "workspace-members", workspace);
|
|
140
|
+
assert.deepEqual(displayNames(first), ["guest", "member"]);
|
|
141
|
+
assert.equal(typeof first.nextCursor, "string");
|
|
142
|
+
const last = listAttributes(await get(owner, "members", page(2, first.nextCursor)), "workspace-members", workspace);
|
|
143
|
+
assert.deepEqual(displayNames(last), ["owner"]);
|
|
144
|
+
assert.equal(last.nextCursor, null);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test("the invites list answers its first page and each next page through its route", async (t) => {
|
|
148
|
+
const { get, owner, member, workspace } = await membersApp(t);
|
|
149
|
+
|
|
150
|
+
// The members screen's first page, and a caller that names no page at all.
|
|
151
|
+
for (const user of [owner, member]) {
|
|
152
|
+
for (const request of [page(20), page()]) {
|
|
153
|
+
const all = listAttributes(await get(user, "invites", request), "workspace-invites", workspace);
|
|
154
|
+
assert.deepEqual(inviteEmails(all), ["ivy@example.com", "jon@example.com", "kim@example.com"]);
|
|
155
|
+
assert.equal(all.nextCursor, null);
|
|
156
|
+
assert.equal(all.workspace.slug, workspace.slug);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const first = listAttributes(await get(owner, "invites", page(2)), "workspace-invites", workspace);
|
|
161
|
+
assert.equal(first.invites.length, 2);
|
|
162
|
+
assert.equal(typeof first.nextCursor, "string");
|
|
163
|
+
const last = listAttributes(await get(owner, "invites", page(2, first.nextCursor)), "workspace-invites", workspace);
|
|
164
|
+
assert.equal(last.invites.length, 1);
|
|
165
|
+
assert.equal(last.nextCursor, null);
|
|
166
|
+
assert.deepEqual([...first.invites, ...last.invites].map(({ email }) => email).sort(),
|
|
167
|
+
["ivy@example.com", "jon@example.com", "kim@example.com"]);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test("the members and invites list routes refuse as strictly as before", async (t) => {
|
|
171
|
+
const { get, owner, guest, outsider } = await membersApp(t);
|
|
172
|
+
|
|
173
|
+
for (const path of ["members", "invites"]) {
|
|
174
|
+
const refusals = [
|
|
175
|
+
["signed out", await get(null, path, page(20)), 401, "auth.session.required"],
|
|
176
|
+
["not a member", await get(outsider, path, page(20)), 403, "workspaces.workspace.accessDenied"],
|
|
177
|
+
["a member without workspace.members.view", await get(guest, path, page(20)), 403, "ACTION_PERMISSION_DENIED"],
|
|
178
|
+
["an unknown workspace", await get(owner, path, { ...page(20), slug: "no-such-workspace" }), 404,
|
|
179
|
+
"workspaces.workspace.notFound"],
|
|
180
|
+
["a limit over 100", await get(owner, path, page(101)), 400, "limit"]
|
|
181
|
+
];
|
|
182
|
+
for (const [label, response, statusCode, text] of refusals) {
|
|
183
|
+
assert.equal(response.statusCode, statusCode, `${path}, ${label}: ${response.body}`);
|
|
184
|
+
assert.equal(response.body.includes(text), true, `${path}, ${label}: ${response.body}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
// A cursor the members list never answered, with no limit named.
|
|
188
|
+
const unknownCursor = await get(owner, "members", page(undefined, "not-a-cursor"));
|
|
189
|
+
assert.equal(unknownCursor.statusCode, 400, unknownCursor.body);
|
|
190
|
+
assert.equal(unknownCursor.body.includes("workspaces.member.cursorInvalid"), true, unknownCursor.body);
|
|
191
|
+
});
|
|
@@ -351,6 +351,9 @@ test("workspaceMembersService.createInvite sends generated invite URLs through t
|
|
|
351
351
|
assert.equal(templateCalls[0].inviteUrl, response.inviteUrl);
|
|
352
352
|
assert.equal(templateCalls[0].locale, "en");
|
|
353
353
|
assert.equal(mailerCalls.length, 1);
|
|
354
|
+
// The mailer is told which saved invitation it sends, and in which workspace.
|
|
355
|
+
assert.equal(mailerCalls[0].payload.inviteId, "88");
|
|
356
|
+
assert.equal(mailerCalls[0].payload.workspace.id, "7");
|
|
354
357
|
assert.equal(mailerCalls[0].payload.locale, "en");
|
|
355
358
|
assert.equal(mailerCalls[0].payload.email, "invitee@example.com");
|
|
356
359
|
assert.equal(mailerCalls[0].payload.inviteUrl, response.inviteUrl);
|
|
@@ -6,6 +6,7 @@ import { AuthPolicyProvider } from "@jskit-ai/auth-core/server/providers/AuthPol
|
|
|
6
6
|
import { CrudContractsProvider } from "@jskit-ai/crud-core/server/crudContracts";
|
|
7
7
|
import { defineCrudFeature } from "@jskit-ai/crud-core/server/defineCrudFeature";
|
|
8
8
|
import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
9
|
+
import { defineFeature } from "@jskit-ai/kernel/server/features";
|
|
9
10
|
import { HttpProvider } from "@jskit-ai/kernel/server/http";
|
|
10
11
|
import { createBootstrapRuntime } from "@jskit-ai/kernel/server/runtime";
|
|
11
12
|
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
@@ -16,6 +17,7 @@ import { UsersIdentityProvider } from "@jskit-ai/users-core/server/UsersIdentity
|
|
|
16
17
|
import { WorkspacesFeature } from "../src/server/WorkspacesFeature.js";
|
|
17
18
|
import { WorkspacesIntegrationsProvider } from "../src/server/WorkspacesIntegrationsProvider.js";
|
|
18
19
|
import { WORKSPACE_CRUD_SCOPE } from "../src/server/support/workspaceCrud.js";
|
|
20
|
+
import { workspaceSlugParamsValidator } from "../src/server/common/validators/routeParamsValidator.js";
|
|
19
21
|
|
|
20
22
|
// A workspace CRUD list served as an application serves it: Fastify, the auth policy plugin, the HTTP runtime's
|
|
21
23
|
// visibility resolvers, the action context contributors and a CRUD feature on a workspace surface, over the users and
|
|
@@ -43,6 +45,44 @@ const IssuesFeature = defineCrudFeature({
|
|
|
43
45
|
scope: WORKSPACE_CRUD_SCOPE
|
|
44
46
|
});
|
|
45
47
|
|
|
48
|
+
// A hand-written route with contextPolicy "optional" and no permission: the auth policy resolves the workspace context
|
|
49
|
+
// without requiring membership, and the action's context contributor resolves it again requiring it.
|
|
50
|
+
const ACTION_READ_NOTICE = "test.workspace-notice.read";
|
|
51
|
+
const NoticeFeature = defineFeature({
|
|
52
|
+
id: "test.workspace-notice",
|
|
53
|
+
requires: { http: "runtime.http" },
|
|
54
|
+
setup({ http }) {
|
|
55
|
+
http.router.register(
|
|
56
|
+
"GET",
|
|
57
|
+
"/api/w/:workspaceSlug/notice",
|
|
58
|
+
{
|
|
59
|
+
auth: "required",
|
|
60
|
+
surface: "app",
|
|
61
|
+
visibility: "workspace",
|
|
62
|
+
contextPolicy: "optional",
|
|
63
|
+
meta: { summary: "Reads the workspace's notice." },
|
|
64
|
+
params: workspaceSlugParamsValidator
|
|
65
|
+
},
|
|
66
|
+
async function readNotice(request, reply) {
|
|
67
|
+
reply.code(200).send(await request.executeAction({ actionId: ACTION_READ_NOTICE, input: request.input.params }));
|
|
68
|
+
}
|
|
69
|
+
);
|
|
70
|
+
return {};
|
|
71
|
+
},
|
|
72
|
+
actions: [
|
|
73
|
+
Object.freeze({
|
|
74
|
+
id: ACTION_READ_NOTICE,
|
|
75
|
+
version: 1,
|
|
76
|
+
kind: "query",
|
|
77
|
+
channels: ["api"],
|
|
78
|
+
surfaces: ["app"],
|
|
79
|
+
input: workspaceSlugParamsValidator,
|
|
80
|
+
output: null,
|
|
81
|
+
execute: (_input, context) => ({ workspaceId: context.workspace.id, roleSid: context.membership.roleSid })
|
|
82
|
+
})
|
|
83
|
+
]
|
|
84
|
+
});
|
|
85
|
+
|
|
46
86
|
const config = Object.freeze({
|
|
47
87
|
appPublicUrl: "http://localhost:5173",
|
|
48
88
|
tenancyMode: "workspaces",
|
|
@@ -89,7 +129,8 @@ async function issuesApp(t) {
|
|
|
89
129
|
WorkspacesFeature,
|
|
90
130
|
WorkspacesIntegrationsProvider,
|
|
91
131
|
CrudContractsProvider,
|
|
92
|
-
IssuesFeature
|
|
132
|
+
IssuesFeature,
|
|
133
|
+
NoticeFeature
|
|
93
134
|
],
|
|
94
135
|
requires: { profiles: "users.profiles", workspaces: "workspaces.core", memberships: "workspaces.memberships" },
|
|
95
136
|
inputs: {
|
|
@@ -123,15 +164,17 @@ async function issuesApp(t) {
|
|
|
123
164
|
{ workspace_id: other.id, title: "Another workspace's issue" }
|
|
124
165
|
]);
|
|
125
166
|
|
|
126
|
-
async function
|
|
167
|
+
async function get(user, slug, suffix) {
|
|
127
168
|
const { result: response, queries } = await countQueries(knex, () => app.inject({
|
|
128
169
|
method: "GET",
|
|
129
|
-
url: `/api/w/${slug}
|
|
170
|
+
url: `/api/w/${slug}/${suffix}`,
|
|
130
171
|
headers: user ? { "x-test-user": user.id } : {}
|
|
131
172
|
}));
|
|
132
173
|
return { response, queries };
|
|
133
174
|
}
|
|
134
|
-
|
|
175
|
+
const list = (user, slug = workspace.slug) => get(user, slug, "issues");
|
|
176
|
+
const notice = (user, slug = workspace.slug) => get(user, slug, "notice");
|
|
177
|
+
return { list, notice, owner, member, guest, outsider, workspace };
|
|
135
178
|
}
|
|
136
179
|
|
|
137
180
|
// The statements of one read of the workspace context, whatever the database quotes its names with: the workspace by
|
|
@@ -180,3 +223,25 @@ test("a workspace CRUD list request refuses as strictly as before", async (t) =>
|
|
|
180
223
|
assert.ok(reading(queries, "workspace").length <= 1, `${label} reads the workspace at most once: ${queries.join("\n")}`);
|
|
181
224
|
}
|
|
182
225
|
});
|
|
226
|
+
|
|
227
|
+
test("a route whose auth policy and action context differ in requiring membership reads the context once", async (t) => {
|
|
228
|
+
const { notice, owner, member, outsider, workspace } = await issuesApp(t);
|
|
229
|
+
|
|
230
|
+
for (const [user, roleSid] of [[owner, "owner"], [member, "member"]]) {
|
|
231
|
+
const { response, queries } = await notice(user);
|
|
232
|
+
assert.equal(response.statusCode, 200, response.body);
|
|
233
|
+
assert.deepEqual(response.json(), { workspaceId: workspace.id, roleSid });
|
|
234
|
+
const statements = queries.join("\n");
|
|
235
|
+
t.diagnostic(`a contextPolicy "optional" request for the ${roleSid} sends ${queries.length} statements`);
|
|
236
|
+
// Before, the auth policy's read (membership optional) and the action context's (membership required) were two.
|
|
237
|
+
assert.equal(reading(queries, "workspace").length, 1, statements);
|
|
238
|
+
assert.equal(reading(queries, "membership").length, 1, statements);
|
|
239
|
+
assert.equal(reading(queries, "settings").length, 1, statements);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// The shared read still refuses a non-member where membership is required.
|
|
243
|
+
const { response, queries } = await notice(outsider);
|
|
244
|
+
assert.equal(response.statusCode, 403, response.body);
|
|
245
|
+
assert.equal(response.body.includes("workspaces.workspace.accessDenied"), true, response.body);
|
|
246
|
+
assert.equal(reading(queries, "workspace").length, 1, queries.join("\n"));
|
|
247
|
+
});
|
|
@@ -802,11 +802,12 @@ test("one request's auth policy and action context share one workspace context r
|
|
|
802
802
|
await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha");
|
|
803
803
|
assert.equal(calls.findBySlug, 4, "A call without a request resolves each time");
|
|
804
804
|
const request = {};
|
|
805
|
-
await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request });
|
|
806
|
-
await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request, requireMembership: false });
|
|
805
|
+
const required = await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request });
|
|
806
|
+
const optional = await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request, requireMembership: false });
|
|
807
|
+
assert.equal(optional, required, "Another membership requirement shares the read");
|
|
807
808
|
await service.resolveWorkspaceContextForUserBySlug({ ...user, id: "8" }, "team-alpha", { request });
|
|
808
809
|
await service.resolveWorkspaceContextForUserBySlug(user, "team-alpha", { request });
|
|
809
|
-
assert.equal(calls.findBySlug,
|
|
810
|
+
assert.equal(calls.findBySlug, 6, "Another user resolves on its own");
|
|
810
811
|
});
|
|
811
812
|
|
|
812
813
|
test("workspaceService.getWorkspaceForAuthenticatedUser resolves workspace from slug context", async () => {
|