@jskit-ai/workspaces-core 0.2.39 → 0.2.40
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 +2 -0
- package/package.json +9 -9
- package/src/server/common/contributors/workspaceRouteVisibilityResolver.js +3 -1
- package/src/server/common/repositories/workspacesRepository.js +38 -0
- package/src/server/common/services/workspaceDirectoryService.js +34 -7
- package/src/server/common/services/workspaceMemberContext.js +90 -0
- package/src/server/workspacesRuntime.js +6 -2
- package/src/shared/resources/workspaceResource.js +3 -1
- package/test/repositories.integration.test.js +328 -1
- package/test/resourcesCanonical.test.js +3 -1
- package/test/workspaceRequestContextQueries.test.js +131 -19
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- `workspaces.core` gains `memberContext({ workspaceId, userId }, { context: systemContext(reason), trx? })`, the context of one member of one workspace for background work done as that member: a record started for the person it is assigned to, a notification for one recipient, a member's template setup, a submission synced for the person who made it. It is resolved as the member's own request on a `workspace_user` route is, by the same reads (the workspace, the active membership with the owner's ensured, the role's permissions and the settings), now shared with that request's resolution through the directory service's new `resolveMemberWorkspaceContextById(user, workspaceId, options)`, and refused as it is: 404 `workspaces.workspace.notFound` for a missing or deleted workspace, 403 `workspaces.workspace.accessDenied` for a user who is no active member (removed, inactive, never one, or no user), 403 `workspaces.workspace.contextDisabled` without workspaces. The context signs the member in (`actor`, so `resolveActorId` answers them and an action checks their `permissions`), carries `workspace`, `membership`, `permissions`, the `workspace_user` visibility context and `requestMeta.resolvedWorkspaceContext`, and is no system context or job: request row limits apply, other owners' hidden fields stay hidden and a row policy is told `caller.kind` "user". Only a system context makes one; any other context, a `forWorkspace` job's too, and ids that are no record ids are a TypeError before any statement. An action runs in it with `actions.execute({ actionId, input, context: { ...member, surface: "app" } })` and sees what the member's request on that route sees. JSKIT keeps no disabled flag on users, so it reads no sign-in state: an account its auth provider refuses at sign-in is still resolved.
|
|
6
|
+
- `workspaces.listForSystem({ afterId, limit }, { context: systemContext(reason) })` answers one page of the workspaces that are not deleted, `{ id, slug }` in id order, after `afterId` (from the first when it is null) and at most `limit` (1 to `pageLimits().request`, 100 by default), for a background job that visits every workspace. A page is one statement however many workspaces there are: among 10 workspaces and among 200 alike. Any context that is not a system context, a `forWorkspace` or `forUser` job's included, an `afterId` that is no workspace id and a `limit` out of range are a TypeError before any statement. The workspaces table resource's search gains `idAfter` (`id > value`) for it.
|
|
5
7
|
- An invitation's response carries whatever delivery status its invite mailer answers, such as `held` for an email the application keeps until its email is set up. The create-invite output's `inviteDelivery.status` and the invite assistant tool's `deliveryStatus` allowed only `sent`, `simulated`, `failed` and `mailer_unconfigured`, so an invitation the assistant made through a mailer answering another status was saved and then failed with "Assistant tool output validation failed.", and the API contract did not describe the status it sent. Both are now any non-empty string. `WorkspaceInviteMailer`'s documentation names the statuses the members panel words itself and says it shows the result's `message` for any other.
|
|
6
8
|
- `workspaces.memberships.lockByWorkspaceIdAndUserId` locks its membership with `lockWhere`'s `limit: 1` (the workspace and the user are the table's unique key): one statement on PostgreSQL, where it sent two, and with json-rest-api 3.1.8 one on MariaDB and MySQL as well, whose read of the connection's schema and of the membership's links (to public tables whose foreign keys protect them) it no longer needs, as the membership's `lock(id)` costs, among 10 members and among 200.
|
|
7
9
|
- `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.
|
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.40",
|
|
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.215",
|
|
27
|
+
"@jskit-ai/resource-crud-core": "0.1.217",
|
|
28
|
+
"@jskit-ai/users-core": "0.2.40",
|
|
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.25",
|
|
215
|
+
"@jskit-ai/database-runtime": "0.1.273",
|
|
216
|
+
"@jskit-ai/http-runtime": "0.2.24",
|
|
217
|
+
"@jskit-ai/kernel": "0.2.24",
|
|
218
|
+
"@jskit-ai/resource-runtime": "0.2.31"
|
|
219
219
|
}
|
|
220
220
|
}
|
|
@@ -2,6 +2,8 @@ import { normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/suppor
|
|
|
2
2
|
import { normalizeSurfaceId } from "@jskit-ai/kernel/shared/surface/registry";
|
|
3
3
|
import { resolveActor, resolveActorId } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
|
|
4
4
|
|
|
5
|
+
// A workspace route's visibility context, before the HTTP runtime adds its visibility: a member context
|
|
6
|
+
// (workspaceMemberContext.js) has a `workspace_user` route's.
|
|
5
7
|
function buildVisibilityContribution({ visibility, scopeOwnerId = null, userId = null } = {}) {
|
|
6
8
|
const requiresActorScope = visibility === "workspace_user";
|
|
7
9
|
const contribution = {
|
|
@@ -79,4 +81,4 @@ function createWorkspaceRouteVisibilityResolver({ workspaceService, workspaceMem
|
|
|
79
81
|
});
|
|
80
82
|
}
|
|
81
83
|
|
|
82
|
-
export { createWorkspaceRouteVisibilityResolver };
|
|
84
|
+
export { buildVisibilityContribution, createWorkspaceRouteVisibilityResolver };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isLostDuplicateInsertRace, toIsoString } from "@jskit-ai/database-runtime/shared";
|
|
2
2
|
import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
|
+
import { isSystemContext } from "@jskit-ai/resource-runtime/server";
|
|
3
4
|
|
|
4
5
|
function normalizeWorkspaceRecord(payload = null) {
|
|
5
6
|
if (!payload || typeof payload !== "object") {
|
|
@@ -98,6 +99,42 @@ function createRepository({ workspaces, workspaceMemberships }) {
|
|
|
98
99
|
return rows.map((row) => normalizeWorkspaceRecord(row)).filter(Boolean).sort(byId);
|
|
99
100
|
}
|
|
100
101
|
|
|
102
|
+
/**
|
|
103
|
+
* One page of the workspaces that are not deleted, for background work across all of them: in id order, those after
|
|
104
|
+
* `afterId` (from the first when it is null or left out), at most `limit`, each as `{ id, slug }`. Work over every
|
|
105
|
+
* workspace passes the last id of each page as the next page's `afterId`; a page shorter than `limit` is the last.
|
|
106
|
+
* Each page is one statement, however many workspaces there are. Only a system context calls it (`{ context:
|
|
107
|
+
* systemContext(reason) }`): any other context, one that forWorkspace or its kin derived too, is refused before any
|
|
108
|
+
* statement, as are an `afterId` that is no workspace id and a `limit` that is not a whole number from 1 to the
|
|
109
|
+
* workspaces' page limit (pageLimits().request, 100 unless the application sets another).
|
|
110
|
+
* @param {{ afterId?: unknown, limit: number }} page
|
|
111
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
|
|
112
|
+
* @returns {Promise<Array<{ id: string, slug: string }>>}
|
|
113
|
+
*/
|
|
114
|
+
async function listForSystem({ afterId = null, limit } = {}, options = {}) {
|
|
115
|
+
if (!isSystemContext(options.context)) {
|
|
116
|
+
throw new TypeError("workspaces.listForSystem() runs only in a system context: pass { context: systemContext(reason) }.");
|
|
117
|
+
}
|
|
118
|
+
const pageLimit = workspaces.pageLimits().request;
|
|
119
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > pageLimit) {
|
|
120
|
+
throw new TypeError(`workspaces.listForSystem() limit is a whole number from 1 to ${pageLimit}. Received: ${String(limit)}`);
|
|
121
|
+
}
|
|
122
|
+
const after = normalizeRecordId(afterId, { fallback: null });
|
|
123
|
+
if (afterId !== null && !after) {
|
|
124
|
+
throw new TypeError(
|
|
125
|
+
"workspaces.listForSystem() afterId is the id of the last workspace of the page before, or null for the first page. " +
|
|
126
|
+
`Received: ${String(afterId)}`
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
const { records } = await workspaces.query({
|
|
130
|
+
filters: after ? { deletedAt: null, idAfter: after } : { deletedAt: null },
|
|
131
|
+
sort: ["id"],
|
|
132
|
+
fields: ["slug"],
|
|
133
|
+
page: { size: limit }
|
|
134
|
+
}, options);
|
|
135
|
+
return records.map((record) => ({ id: normalizeRecordId(record.id, { fallback: null }), slug: normalizeText(record.slug) }));
|
|
136
|
+
}
|
|
137
|
+
|
|
101
138
|
async function findPersonalByOwnerUserId(userId, options = {}) {
|
|
102
139
|
const normalizedUserId = normalizeRecordId(userId, { fallback: null });
|
|
103
140
|
if (!normalizedUserId) {
|
|
@@ -236,6 +273,7 @@ function createRepository({ workspaces, workspaceMemberships }) {
|
|
|
236
273
|
joinSource: workspaces.joinSource,
|
|
237
274
|
findById,
|
|
238
275
|
listByIds,
|
|
276
|
+
listForSystem,
|
|
239
277
|
findBySlug,
|
|
240
278
|
listSlugsIn,
|
|
241
279
|
findPersonalByOwnerUserId,
|
|
@@ -268,7 +268,11 @@ function createService({
|
|
|
268
268
|
throw new AppError(401, "Authentication required.", { code: "workspaces.auth.required" });
|
|
269
269
|
}
|
|
270
270
|
const workspaceContext = await readRequestWorkspaceContext(user, workspaceSlug, options);
|
|
271
|
-
|
|
271
|
+
return requireMembership ? requireMember(workspaceContext) : workspaceContext;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function requireMember(workspaceContext) {
|
|
275
|
+
if (!workspaceContext.membership) {
|
|
272
276
|
throw new AppError(403, "You do not have access to this workspace.", { code: "workspaces.workspace.accessDenied" });
|
|
273
277
|
}
|
|
274
278
|
return workspaceContext;
|
|
@@ -291,24 +295,46 @@ function createService({
|
|
|
291
295
|
return reads.get(key);
|
|
292
296
|
}
|
|
293
297
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
298
|
+
/**
|
|
299
|
+
* The workspace context of one member of the workspace with this id, for background work done as that member: what
|
|
300
|
+
* resolveWorkspaceContextForUserBySlug resolves for the member's request on a surface that requires membership, by
|
|
301
|
+
* the same reads and checks. A deleted or missing workspace is 404 `workspaces.workspace.notFound`, as an unknown
|
|
302
|
+
* slug is, and a user who is no active member of it (removed, inactive, never one, or no user at all) 403
|
|
303
|
+
* `workspaces.workspace.accessDenied`; the owner's membership is ensured, as at the owner's request.
|
|
304
|
+
* @param {{ id?: unknown } | null} user
|
|
305
|
+
* @param {unknown} workspaceId
|
|
306
|
+
* @param {object} [options]
|
|
307
|
+
*/
|
|
308
|
+
async function resolveMemberWorkspaceContextById(user, workspaceId, options = {}) {
|
|
309
|
+
requireWorkspaceContext();
|
|
310
|
+
const workspace = await workspacesRepository.findById(workspaceId, options);
|
|
311
|
+
// findById keeps a deleted workspace, which findBySlug does not find.
|
|
312
|
+
return requireMember(await readWorkspaceContextForUser(user, workspace?.deletedAt ? null : workspace, options));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function requireWorkspaceContext() {
|
|
297
316
|
if (resolvedTenancyMode === TENANCY_MODE_NONE) {
|
|
298
317
|
throw new AppError(403, "Workspace context is disabled.", { code: "workspaces.workspace.contextDisabled" });
|
|
299
318
|
}
|
|
319
|
+
}
|
|
300
320
|
|
|
321
|
+
async function readWorkspaceContextForUserBySlug(user, workspaceSlug, options = {}) {
|
|
322
|
+
requireWorkspaceContext();
|
|
301
323
|
const normalizedWorkspaceSlug = normalizeLowerText(workspaceSlug);
|
|
302
324
|
if (!normalizedWorkspaceSlug) {
|
|
303
325
|
throw new AppError(400, "workspaceSlug is required.", { code: "workspaces.workspace.slugRequired" });
|
|
304
326
|
}
|
|
327
|
+
return readWorkspaceContextForUser(user, await workspacesRepository.findBySlug(normalizedWorkspaceSlug, options), options);
|
|
328
|
+
}
|
|
305
329
|
|
|
306
|
-
|
|
307
|
-
|
|
330
|
+
// The workspace (404 when it is null), the user's active membership (null for an anonymous visitor or a non-member)
|
|
331
|
+
// with its role's permissions, and the settings: every workspace context, a request's and a member's, is this one.
|
|
332
|
+
async function readWorkspaceContextForUser(user, workspace, options) {
|
|
308
333
|
if (!workspace) {
|
|
309
334
|
throw new AppError(404, "Workspace not found.", { code: "workspaces.workspace.notFound" });
|
|
310
335
|
}
|
|
311
336
|
|
|
337
|
+
const normalizedUserId = normalizeRecordId(user?.id, { fallback: null });
|
|
312
338
|
let membership = normalizedUserId
|
|
313
339
|
? await workspaceMembershipsRepository.findByWorkspaceIdAndUserId(workspace.id, normalizedUserId, options)
|
|
314
340
|
: null;
|
|
@@ -343,7 +369,8 @@ function createService({
|
|
|
343
369
|
updateWorkspaceForAuthenticatedUser,
|
|
344
370
|
listWorkspacesForUser,
|
|
345
371
|
listWorkspacesForAuthenticatedUser,
|
|
346
|
-
resolveWorkspaceContextForUserBySlug
|
|
372
|
+
resolveWorkspaceContextForUserBySlug,
|
|
373
|
+
resolveMemberWorkspaceContextById
|
|
347
374
|
});
|
|
348
375
|
}
|
|
349
376
|
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { normalizeAuthActor } from "@jskit-ai/auth-core/server/authActor";
|
|
2
|
+
import { normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
|
+
import { normalizeVisibilityContext, ROUTE_VISIBILITY_WORKSPACE_USER } from "@jskit-ai/kernel/shared/support/visibility";
|
|
4
|
+
import { isSystemContext } from "@jskit-ai/resource-runtime/server";
|
|
5
|
+
import { buildVisibilityContribution } from "../contributors/workspaceRouteVisibilityResolver.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The actor of a signed-in request by the user this profile is, as every auth provider that keeps users' profiles
|
|
9
|
+
* builds it from its own account and the profile.
|
|
10
|
+
* @param {{ id: string, authProvider: string, authProviderUserSid: string, email: string, displayName: string }} profile
|
|
11
|
+
*/
|
|
12
|
+
function memberActorOf(profile) {
|
|
13
|
+
return normalizeAuthActor({
|
|
14
|
+
provider: profile.authProvider,
|
|
15
|
+
providerUserId: profile.authProviderUserSid,
|
|
16
|
+
email: profile.email,
|
|
17
|
+
displayName: profile.displayName,
|
|
18
|
+
appUserId: profile.id,
|
|
19
|
+
profileSource: "users"
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The `memberContext` of `workspaces.core`.
|
|
25
|
+
* @param {object} dependencies
|
|
26
|
+
* @param {import("../../types.js").WorkspaceDirectoryService} dependencies.workspaceService
|
|
27
|
+
* @param {import("@jskit-ai/users-core/server/types").UsersProfiles} dependencies.userProfiles
|
|
28
|
+
*/
|
|
29
|
+
function createWorkspaceMemberContexts({ workspaceService, userProfiles }) {
|
|
30
|
+
/**
|
|
31
|
+
* The context of one member of one workspace, for background work done as that member (a record started for the
|
|
32
|
+
* person it is assigned to, a notification for one recipient, a submission synced for the person who made it): the
|
|
33
|
+
* context the member's own request on a `workspace_user` route runs its action in, resolved by the same reads and
|
|
34
|
+
* checks. Its `actor` is the member, as a signed-in request's (`resolveActorId` answers them, an action's permission
|
|
35
|
+
* check reads their `permissions`, a row policy is told `caller.kind` "user"); `workspace`, `membership` and
|
|
36
|
+
* `permissions` are their workspace context's, which `requestMeta.resolvedWorkspaceContext` holds with the
|
|
37
|
+
* settings; its scope is the workspace and the member, so an event it publishes reaches that member there. It is no
|
|
38
|
+
* system context and no job: request row limits apply, and other owners' hidden fields stay hidden, as at the
|
|
39
|
+
* member's request.
|
|
40
|
+
*
|
|
41
|
+
* Only a system context makes one (`{ context: systemContext(reason) }`, with `trx` to read in the caller's
|
|
42
|
+
* transaction): any other context, a forWorkspace job's too, is a TypeError, as are ids that are no record ids. A
|
|
43
|
+
* missing or deleted workspace is 404 `workspaces.workspace.notFound`, and a user who is no active member of it
|
|
44
|
+
* (removed, inactive, never one, or no user at all) 403 `workspaces.workspace.accessDenied`, as for the member's
|
|
45
|
+
* request; the owner's membership is ensured, as at the owner's request. It reads no sign-in state: an account its
|
|
46
|
+
* auth provider refuses at sign-in is still resolved. An action it runs names the surface the member's request
|
|
47
|
+
* would: `actions.execute({ actionId, input, context: { ...member, surface: "app" } })`.
|
|
48
|
+
* @param {{ workspaceId: unknown, userId: unknown }} member
|
|
49
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
|
|
50
|
+
*/
|
|
51
|
+
async function memberContext({ workspaceId, userId } = {}, options = {}) {
|
|
52
|
+
if (!isSystemContext(options.context)) {
|
|
53
|
+
throw new TypeError("workspaces.memberContext() runs only in a system context: pass { context: systemContext(reason) }.");
|
|
54
|
+
}
|
|
55
|
+
const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
|
|
56
|
+
const normalizedUserId = normalizeRecordId(userId, { fallback: null });
|
|
57
|
+
if (!normalizedWorkspaceId || !normalizedUserId) {
|
|
58
|
+
throw new TypeError(
|
|
59
|
+
"workspaces.memberContext() takes { workspaceId, userId }, the ids of a workspace and of its member. " +
|
|
60
|
+
`Received: ${String(workspaceId)}, ${String(userId)}`
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
// A user id that names no one is no member, which the membership check refuses.
|
|
64
|
+
const profile = await userProfiles.findById(normalizedUserId, options);
|
|
65
|
+
const resolvedWorkspaceContext = await workspaceService.resolveMemberWorkspaceContextById(profile, normalizedWorkspaceId, options);
|
|
66
|
+
return Object.freeze({
|
|
67
|
+
actor: memberActorOf(profile),
|
|
68
|
+
workspace: resolvedWorkspaceContext.workspace,
|
|
69
|
+
membership: resolvedWorkspaceContext.membership,
|
|
70
|
+
permissions: resolvedWorkspaceContext.permissions,
|
|
71
|
+
// An action it runs resolves its visibility as that route's request does, to this visibility context.
|
|
72
|
+
routeVisibility: ROUTE_VISIBILITY_WORKSPACE_USER,
|
|
73
|
+
visibilityContext: normalizeVisibilityContext({
|
|
74
|
+
visibility: ROUTE_VISIBILITY_WORKSPACE_USER,
|
|
75
|
+
...buildVisibilityContribution({
|
|
76
|
+
visibility: ROUTE_VISIBILITY_WORKSPACE_USER,
|
|
77
|
+
scopeOwnerId: resolvedWorkspaceContext.workspace.id,
|
|
78
|
+
userId: profile.id
|
|
79
|
+
})
|
|
80
|
+
}),
|
|
81
|
+
requestMeta: Object.freeze({ resolvedWorkspaceContext })
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return Object.freeze({
|
|
86
|
+
memberContext
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export { createWorkspaceMemberContexts };
|
|
@@ -10,6 +10,7 @@ import { createRepository as createWorkspaceMembershipsRepository } from "./comm
|
|
|
10
10
|
import { createRepository as createWorkspaceMemberPagesRepository } from "./common/repositories/workspaceMemberPagesRepository.js";
|
|
11
11
|
import { createRepository as createWorkspacesRepository } from "./common/repositories/workspacesRepository.js";
|
|
12
12
|
import { createService as createWorkspaceService } from "./common/services/workspaceDirectoryService.js";
|
|
13
|
+
import { createWorkspaceMemberContexts } from "./common/services/workspaceMemberContext.js";
|
|
13
14
|
import { createWorkspacesServerI18n } from "./i18n.js";
|
|
14
15
|
import { createWorkspaceInviteUrlBuilder } from "./workspaceMembers/workspaceInviteUrls.js";
|
|
15
16
|
import { createService as createWorkspaceMembersService } from "./workspaceMembers/workspaceMembersService.js";
|
|
@@ -70,8 +71,8 @@ function createWorkspaceRecords(resources) {
|
|
|
70
71
|
}
|
|
71
72
|
|
|
72
73
|
/**
|
|
73
|
-
* The `workspaces.core` capability: the workspace services
|
|
74
|
-
* settings repositories
|
|
74
|
+
* The `workspaces.core` capability: the workspace services, the invite and
|
|
75
|
+
* settings repositories and `memberContext`, built from the runtime config.
|
|
75
76
|
* @param {object} dependencies
|
|
76
77
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} dependencies.appRoot
|
|
77
78
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} dependencies.config
|
|
@@ -158,11 +159,14 @@ function createWorkspacesRuntime({
|
|
|
158
159
|
workspaceInvitationsEnabled: invitationsEnabled,
|
|
159
160
|
roleCatalog
|
|
160
161
|
});
|
|
162
|
+
const memberContexts = createWorkspaceMemberContexts({ workspaceService, userProfiles });
|
|
161
163
|
|
|
162
164
|
return Object.freeze({
|
|
163
165
|
enabled: tenancyProfile.workspace.enabled === true,
|
|
164
166
|
invitationsEnabled,
|
|
165
167
|
selfCreateEnabled: tenancyProfile.workspace.allowSelfCreate === true,
|
|
168
|
+
// The context of one member of one workspace, for background work done as that member.
|
|
169
|
+
memberContext: memberContexts.memberContext,
|
|
166
170
|
// The workspace route support the assistant runtime reads.
|
|
167
171
|
scope: Object.freeze({
|
|
168
172
|
params: workspaceSlugParamsValidator,
|
|
@@ -82,7 +82,9 @@ const workspaceResource = defineTableResource({
|
|
|
82
82
|
slug: { type: "string", actualField: "slug", filterOperator: "=" },
|
|
83
83
|
slugs: { type: "array", actualField: "slug", filterOperator: "in", items: { type: "string" } },
|
|
84
84
|
owner: { type: "id", actualField: "owner_user_id", filterOperator: "=" },
|
|
85
|
-
isPersonal: { type: "boolean", actualField: "is_personal", filterOperator: "=" }
|
|
85
|
+
isPersonal: { type: "boolean", actualField: "is_personal", filterOperator: "=" },
|
|
86
|
+
// The workspaces after one id: the next page of workspaces.listForSystem.
|
|
87
|
+
idAfter: { type: "id", actualField: "id", filterOperator: ">" }
|
|
86
88
|
},
|
|
87
89
|
schema: {
|
|
88
90
|
slug: {
|
|
@@ -4,8 +4,9 @@ import knexLib from "knex";
|
|
|
4
4
|
import { findDuplicateEntryError } from "@jskit-ai/database-runtime/shared";
|
|
5
5
|
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
6
6
|
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
7
|
+
import { resolveActorId } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
|
|
7
8
|
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
8
|
-
import { checkForeignKeys } from "@jskit-ai/resource-runtime/server";
|
|
9
|
+
import { checkForeignKeys, isSystemContext } from "@jskit-ai/resource-runtime/server";
|
|
9
10
|
import { startTestFeatures } from "@jskit-ai/resource-runtime/test";
|
|
10
11
|
import { userProfileTableResource } from "@jskit-ai/users-core/shared/resources/userProfileResource";
|
|
11
12
|
import { userSettingsTableResource } from "@jskit-ai/users-core/shared/resources/userSettingsResource";
|
|
@@ -27,6 +28,7 @@ import { unconfiguredWorkspaceInviteMailer } from "../src/server/workspaceMember
|
|
|
27
28
|
import { createWorkspaceInviteUrlBuilder } from "../src/server/workspaceMembers/workspaceInviteUrls.js";
|
|
28
29
|
import { createService as createMembersService } from "../src/server/workspaceMembers/workspaceMembersService.js";
|
|
29
30
|
import { buildWorkspaceName, createService as createDirectoryService } from "../src/server/common/services/workspaceDirectoryService.js";
|
|
31
|
+
import { createWorkspaceMemberContexts } from "../src/server/common/services/workspaceMemberContext.js";
|
|
30
32
|
import { noWorkspaceCreatedParticipant } from "../src/server/workspaceDirectory/noWorkspaceCreatedParticipant.js";
|
|
31
33
|
import { resolveTenancyProfile } from "../src/shared/tenancyProfile.js";
|
|
32
34
|
import { createWorkspacesServerI18n } from "../src/server/i18n.js";
|
|
@@ -91,6 +93,7 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
|
|
|
91
93
|
let workspaces;
|
|
92
94
|
let memberships;
|
|
93
95
|
let membershipTable;
|
|
96
|
+
let workspaceTable;
|
|
94
97
|
let invites;
|
|
95
98
|
let memberPages;
|
|
96
99
|
let settings;
|
|
@@ -132,6 +135,7 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
|
|
|
132
135
|
({ profiles, userSettings, profileProjector, usersExtensions } = capabilities);
|
|
133
136
|
const resources = await runtime.own("workspaces.core", WORKSPACES_TABLES);
|
|
134
137
|
membershipTable = resources.workspaceMemberships;
|
|
138
|
+
workspaceTable = resources.workspaces;
|
|
135
139
|
({ workspaces, memberships } = createWorkspaceRecords(resources));
|
|
136
140
|
invites = createInvitesRepository({ workspaceInvites: resources.workspaceInvites, workspaces });
|
|
137
141
|
memberPages = createMemberPagesRepository({ workspaceMemberships: resources.workspaceMemberships, userProfiles: profiles });
|
|
@@ -314,6 +318,329 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
|
|
|
314
318
|
);
|
|
315
319
|
});
|
|
316
320
|
|
|
321
|
+
// The system context of a test job that walks every workspace.
|
|
322
|
+
const walkContext = () => runtime.declareSystemScope("test.workspace-walk", "walk every workspace")("list every workspace a page at a time");
|
|
323
|
+
|
|
324
|
+
// `count` workspaces `${prefix}-000`, `${prefix}-001`, ... owned by one user, inserted in that order.
|
|
325
|
+
async function insertNamedWorkspaces(prefix, count, ownerUserId) {
|
|
326
|
+
await insertRows("workspaces", Array.from({ length: count }, (_, index) => ({
|
|
327
|
+
slug: `${prefix}-${String(index).padStart(3, "0")}`,
|
|
328
|
+
name: `${prefix} ${index}`,
|
|
329
|
+
owner_user_id: ownerUserId,
|
|
330
|
+
is_personal: false
|
|
331
|
+
})));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Every page listForSystem answers, from the first, each page's last id the next page's afterId.
|
|
335
|
+
async function walkWorkspaces(limit, options) {
|
|
336
|
+
const pages = [];
|
|
337
|
+
for (let afterId = null; ;) {
|
|
338
|
+
const page = await workspaces.listForSystem({ afterId, limit }, options);
|
|
339
|
+
pages.push(page);
|
|
340
|
+
if (page.length < limit) return pages;
|
|
341
|
+
afterId = page.at(-1).id;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
test("workspaces.listForSystem answers the workspaces that are not deleted, in id order, a page at a time, inside a transaction too", async () => {
|
|
346
|
+
const ownerUserId = (await insertUsers(["walker"])).get("walker");
|
|
347
|
+
await insertNamedWorkspaces("walk", 12, ownerUserId);
|
|
348
|
+
const all = (await knex("workspaces").orderBy("id").select("id", "slug")).map(({ id, slug }) => ({ id: String(id), slug }));
|
|
349
|
+
const deletedSlugs = ["walk-003", "walk-007"];
|
|
350
|
+
for (const { id } of all.filter(({ slug }) => deletedSlugs.includes(slug))) {
|
|
351
|
+
await workspaces.updateById(id, { deletedAt: new Date().toISOString() });
|
|
352
|
+
}
|
|
353
|
+
const kept = all.filter(({ slug }) => !deletedSlugs.includes(slug));
|
|
354
|
+
const system = { context: walkContext() };
|
|
355
|
+
|
|
356
|
+
const pages = await walkWorkspaces(4, system);
|
|
357
|
+
assert.deepEqual(pages.map((page) => page.length), [4, 4, 2]);
|
|
358
|
+
assert.deepEqual(pages.flat(), kept, "Every workspace that is not deleted, once, in id order, as { id, slug }");
|
|
359
|
+
assert.deepEqual(await workspaces.listForSystem({ afterId: kept.at(-1).id, limit: 4 }, system), []);
|
|
360
|
+
assert.deepEqual(await workspaces.listForSystem({ limit: 2 }, system), kept.slice(0, 2), "No afterId is the first page");
|
|
361
|
+
// An afterId naming a deleted workspace answers the workspaces after it.
|
|
362
|
+
assert.deepEqual(await workspaces.listForSystem({ afterId: all[3].id, limit: 2 }, system), kept.slice(3, 5));
|
|
363
|
+
|
|
364
|
+
await workspaces.withTransaction(system, async (txOptions) => {
|
|
365
|
+
const created = await workspaces.insert({ slug: "walk-new", name: "Walk new", ownerUserId }, txOptions);
|
|
366
|
+
const page = await workspaces.listForSystem({ afterId: kept.at(-1).id, limit: 4 }, txOptions);
|
|
367
|
+
assert.deepEqual(page, [{ id: created.id, slug: "walk-new" }]);
|
|
368
|
+
});
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
test("workspaces.listForSystem reads one page in one statement among 10 workspaces and among 200", async (t) => {
|
|
372
|
+
const ownerUserId = (await insertUsers(["walker"])).get("walker");
|
|
373
|
+
const system = { context: walkContext() };
|
|
374
|
+
const limit = workspaceTable.pageLimits().request;
|
|
375
|
+
// A first page, and the page after the third workspace.
|
|
376
|
+
const pageReads = async () => {
|
|
377
|
+
const ids = (await knex("workspaces").orderBy("id").select("id")).map(({ id }) => String(id));
|
|
378
|
+
const first = await statementsOf(() => workspaces.listForSystem({ limit }, system));
|
|
379
|
+
const later = await statementsOf(() => workspaces.listForSystem({ afterId: ids[2], limit }, system));
|
|
380
|
+
assert.deepEqual(first.result.map(({ id }) => id), ids.slice(0, limit));
|
|
381
|
+
assert.deepEqual(later.result.map(({ id }) => id), ids.slice(3, 3 + limit));
|
|
382
|
+
return { first, later };
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
await insertNamedWorkspaces("few", 10, ownerUserId);
|
|
386
|
+
const few = await pageReads();
|
|
387
|
+
await insertNamedWorkspaces("many", 190, ownerUserId);
|
|
388
|
+
const many = await pageReads();
|
|
389
|
+
t.diagnostic(
|
|
390
|
+
`listForSystem (limit ${limit}): a first page sends ${few.first.statements} statement(s) among 10 workspaces and ` +
|
|
391
|
+
`${many.first.statements} among 200, a later page ${few.later.statements} and ${many.later.statements}: ${many.later.sql.join(" | ")}`
|
|
392
|
+
);
|
|
393
|
+
assert.equal(few.first.result.length, 10);
|
|
394
|
+
assert.equal(many.first.result.length, limit);
|
|
395
|
+
assert.equal(many.first.statements, few.first.statements, "A first page costs the same among 10 workspaces and among 200");
|
|
396
|
+
assert.equal(many.later.statements, few.later.statements, "A later page costs the same among 10 workspaces and among 200");
|
|
397
|
+
assert.equal(many.first.statements, 1, many.first.sql.join(" | "));
|
|
398
|
+
assert.equal(many.later.statements, 1, many.later.sql.join(" | "));
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
test("workspaces.listForSystem refuses a context that is not a system context, an afterId that is no workspace id and a limit out of range, before any statement", async () => {
|
|
402
|
+
const owner = await createProfile("Ada");
|
|
403
|
+
const workspace = await workspaces.insert({ slug: "only", name: "Only", ownerUserId: owner.id });
|
|
404
|
+
const systemContext = walkContext();
|
|
405
|
+
const pageLimit = workspaceTable.pageLimits().request;
|
|
406
|
+
const notSystem = /runs only in a system context/u;
|
|
407
|
+
const refusals = [
|
|
408
|
+
["no context", { limit: 10 }, {}, notSystem],
|
|
409
|
+
["no options", { limit: 10 }, undefined, notSystem],
|
|
410
|
+
["a signed-in request's context", { limit: 10 }, { context: { actor: { id: owner.id } } }, notSystem],
|
|
411
|
+
["a workspace job's context", { limit: 10 }, { context: systemContext.forWorkspace(workspace.id) }, notSystem],
|
|
412
|
+
["a user job's context", { limit: 10 }, { context: systemContext.forUser(owner.id) }, notSystem],
|
|
413
|
+
...[undefined, null, 0, -1, 1.5, "10", Number.NaN, Number.POSITIVE_INFINITY, pageLimit + 1].map((limit) => [
|
|
414
|
+
`limit ${String(limit)}`, { limit }, { context: systemContext }, /limit is a whole number from 1 to /u
|
|
415
|
+
]),
|
|
416
|
+
...["", "abc", "0", "-1", "1.5", 0, -1, 1.5, true, {}].map((afterId) => [
|
|
417
|
+
`afterId ${JSON.stringify(afterId)}`, { afterId, limit: 10 }, { context: systemContext }, /afterId is the id of the last workspace/u
|
|
418
|
+
])
|
|
419
|
+
];
|
|
420
|
+
for (const [label, page, options, message] of refusals) {
|
|
421
|
+
const { statements, sql } = await statementsOf(() => assert.rejects(workspaces.listForSystem(page, options), (error) => {
|
|
422
|
+
assert.ok(error instanceof TypeError, `${label}: ${error}`);
|
|
423
|
+
assert.match(error.message, message, label);
|
|
424
|
+
return true;
|
|
425
|
+
}));
|
|
426
|
+
assert.equal(statements, 0, `${label} is refused before any statement: ${sql.join(" | ")}`);
|
|
427
|
+
}
|
|
428
|
+
const page = await workspaces.listForSystem({ afterId: null, limit: pageLimit }, { context: systemContext });
|
|
429
|
+
assert.deepEqual(page, [{ id: workspace.id, slug: "only" }]);
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
// The system context of a test job that acts for each member of a workspace.
|
|
433
|
+
const memberJobContext = () => runtime.declareSystemScope("test.member-jobs", "act for members of every workspace")("start each member's assigned records");
|
|
434
|
+
|
|
435
|
+
// The directory service as workspacesRuntime builds it, with roles that grant different permissions, and its member
|
|
436
|
+
// contexts.
|
|
437
|
+
function memberDirectory(tenancyMode = "workspaces") {
|
|
438
|
+
const directory = createDirectoryService({
|
|
439
|
+
tenancyProfile: resolveTenancyProfile({ tenancyMode }),
|
|
440
|
+
roleCatalog: createWorkspaceRoleCatalog({
|
|
441
|
+
roleCatalog: {
|
|
442
|
+
roles: {
|
|
443
|
+
owner: { permissions: ["*"] },
|
|
444
|
+
admin: { assignable: true, permissions: ["workspace.members.view", "crud.notes.patch"] },
|
|
445
|
+
member: { assignable: true, permissions: ["crud.notes.list"] }
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}),
|
|
449
|
+
personalWorkspaceName: buildWorkspaceName,
|
|
450
|
+
createdParticipant: noWorkspaceCreatedParticipant,
|
|
451
|
+
workspacesRepository: workspaces,
|
|
452
|
+
workspaceMembershipsRepository: memberships,
|
|
453
|
+
workspaceSettingsRepository: settings
|
|
454
|
+
});
|
|
455
|
+
return { directory, ...createWorkspaceMemberContexts({ workspaceService: directory, userProfiles: profiles }) };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// A signed-in request's actor for a profile, as the local sign-in provider builds it.
|
|
459
|
+
const requestActorOf = (profile) => ({
|
|
460
|
+
id: profile.id,
|
|
461
|
+
authIdentityId: `local:${profile.authProviderUserSid}`,
|
|
462
|
+
provider: "local",
|
|
463
|
+
providerUserId: profile.authProviderUserSid,
|
|
464
|
+
email: profile.email.toLowerCase(),
|
|
465
|
+
displayName: profile.displayName,
|
|
466
|
+
appUserId: profile.id,
|
|
467
|
+
profileSource: "users"
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
test("memberContext resolves a member's workspace context by the workspace's id as the member's request resolves it by its slug, inside the caller's transaction too", async () => {
|
|
471
|
+
const { directory, memberContext } = memberDirectory();
|
|
472
|
+
const owner = await createProfile("Ada");
|
|
473
|
+
const admin = await createProfile("Grace");
|
|
474
|
+
const member = await createProfile("Linus");
|
|
475
|
+
const workspace = await workspaces.insert({ slug: "team", name: "Team", ownerUserId: owner.id });
|
|
476
|
+
await memberships.ensureOwnerMembership(workspace.id, owner.id);
|
|
477
|
+
await memberships.addMember({ workspaceId: workspace.id, userId: admin.id, roleSid: "admin" });
|
|
478
|
+
await memberships.addMember({ workspaceId: workspace.id, userId: member.id });
|
|
479
|
+
// The workspace's first resolution writes its settings, which every later one reads.
|
|
480
|
+
await directory.resolveWorkspaceContextForUserBySlug(owner, workspace.slug);
|
|
481
|
+
const system = { context: memberJobContext() };
|
|
482
|
+
|
|
483
|
+
for (const [person, roleSid] of [[owner, "owner"], [admin, "admin"], [member, "member"]]) {
|
|
484
|
+
const context = await memberContext({ workspaceId: workspace.id, userId: person.id }, system);
|
|
485
|
+
const request = await directory.resolveWorkspaceContextForUserBySlug(person, workspace.slug);
|
|
486
|
+
assert.deepEqual(context.requestMeta.resolvedWorkspaceContext, request, `${roleSid}: the workspace context of the member's request`);
|
|
487
|
+
assert.deepEqual(
|
|
488
|
+
{ workspace: context.workspace, membership: context.membership, permissions: context.permissions },
|
|
489
|
+
{ workspace: request.workspace, membership: request.membership, permissions: request.permissions }
|
|
490
|
+
);
|
|
491
|
+
assert.equal(context.membership.roleSid, roleSid);
|
|
492
|
+
assert.ok(context.permissions.length > 0, roleSid);
|
|
493
|
+
assert.deepEqual(context.actor, requestActorOf(person), `${roleSid}: signed in as the member`);
|
|
494
|
+
assert.equal(resolveActorId(context), person.id);
|
|
495
|
+
assert.equal(isSystemContext(context), false, "A member context is no system context");
|
|
496
|
+
assert.equal(context.routeVisibility, "workspace_user");
|
|
497
|
+
assert.deepEqual(context.visibilityContext, {
|
|
498
|
+
visibility: "workspace_user",
|
|
499
|
+
scopeKind: "workspace_user",
|
|
500
|
+
requiresActorScope: true,
|
|
501
|
+
scopeOwnerId: workspace.id,
|
|
502
|
+
userId: person.id
|
|
503
|
+
});
|
|
504
|
+
assert.ok(Object.isFrozen(context));
|
|
505
|
+
}
|
|
506
|
+
assert.notDeepEqual(
|
|
507
|
+
(await memberContext({ workspaceId: workspace.id, userId: admin.id }, system)).permissions,
|
|
508
|
+
(await memberContext({ workspaceId: workspace.id, userId: member.id }, system)).permissions,
|
|
509
|
+
"Each member's role decides their permissions"
|
|
510
|
+
);
|
|
511
|
+
|
|
512
|
+
// The owner's membership is ensured, as at the owner's request.
|
|
513
|
+
await memberships.upsertMembership(workspace.id, owner.id, { status: "revoked" });
|
|
514
|
+
const ownerContext = await memberContext({ workspaceId: workspace.id, userId: owner.id }, system);
|
|
515
|
+
assert.equal(ownerContext.membership.status, "active");
|
|
516
|
+
assert.equal(ownerContext.membership.roleSid, "owner");
|
|
517
|
+
|
|
518
|
+
// In the caller's transaction it reads what the transaction wrote.
|
|
519
|
+
const joiner = await createProfile("Barbara");
|
|
520
|
+
await memberships.withTransaction(system, async (txOptions) => {
|
|
521
|
+
await memberships.addMember({ workspaceId: workspace.id, userId: joiner.id }, txOptions);
|
|
522
|
+
const context = await memberContext({ workspaceId: workspace.id, userId: joiner.id }, txOptions);
|
|
523
|
+
assert.equal(context.membership.userId, joiner.id);
|
|
524
|
+
assert.equal(context.actor.id, joiner.id);
|
|
525
|
+
});
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
test("memberContext refuses a missing or deleted workspace, a non-member, a removed or inactive membership and a user id naming no one, as the member's request does", async () => {
|
|
529
|
+
const { directory, memberContext } = memberDirectory();
|
|
530
|
+
const owner = await createProfile("Ada");
|
|
531
|
+
const member = await createProfile("Grace");
|
|
532
|
+
const removed = await createProfile("Linus");
|
|
533
|
+
const inactive = await createProfile("Barbara");
|
|
534
|
+
const outsider = await createProfile("Alan");
|
|
535
|
+
const workspace = await workspaces.insert({ slug: "team", name: "Team", ownerUserId: owner.id });
|
|
536
|
+
await memberships.ensureOwnerMembership(workspace.id, owner.id);
|
|
537
|
+
for (const person of [member, removed, inactive]) {
|
|
538
|
+
await memberships.addMember({ workspaceId: workspace.id, userId: person.id });
|
|
539
|
+
}
|
|
540
|
+
await memberships.upsertMembership(workspace.id, removed.id, { status: "revoked" });
|
|
541
|
+
await memberships.upsertMembership(workspace.id, inactive.id, { status: "inactive" });
|
|
542
|
+
const deleted = await workspaces.insert({ slug: "gone", name: "Gone", ownerUserId: owner.id });
|
|
543
|
+
await memberships.ensureOwnerMembership(deleted.id, owner.id);
|
|
544
|
+
await memberships.addMember({ workspaceId: deleted.id, userId: member.id });
|
|
545
|
+
await workspaces.updateById(deleted.id, { deletedAt: new Date().toISOString() });
|
|
546
|
+
const system = { context: memberJobContext() };
|
|
547
|
+
const notFound = [404, "workspaces.workspace.notFound"];
|
|
548
|
+
const accessDenied = [403, "workspaces.workspace.accessDenied"];
|
|
549
|
+
const refuses = ([status, code], label) => (error) => {
|
|
550
|
+
assert.ok(error instanceof AppError, `${label}: ${error}`);
|
|
551
|
+
assert.deepEqual([error.status, error.code], [status, code], label);
|
|
552
|
+
return true;
|
|
553
|
+
};
|
|
554
|
+
// [label, member asked for, refusal, the member's request (user and slug) that the same refusal answers]
|
|
555
|
+
const refusals = [
|
|
556
|
+
["a workspace id naming no workspace", { workspaceId: "999999", userId: member.id }, notFound, [member, "no-such-workspace"]],
|
|
557
|
+
["a deleted workspace's member", { workspaceId: deleted.id, userId: member.id }, notFound, [member, "gone"]],
|
|
558
|
+
["a deleted workspace's owner", { workspaceId: deleted.id, userId: owner.id }, notFound, [owner, "gone"]],
|
|
559
|
+
["a user who was never a member", { workspaceId: workspace.id, userId: outsider.id }, accessDenied, [outsider, "team"]],
|
|
560
|
+
["a removed member", { workspaceId: workspace.id, userId: removed.id }, accessDenied, [removed, "team"]],
|
|
561
|
+
["an inactive member", { workspaceId: workspace.id, userId: inactive.id }, accessDenied, [inactive, "team"]],
|
|
562
|
+
["a user id naming no one", { workspaceId: workspace.id, userId: "999999" }, accessDenied, [{ id: "999999" }, "team"]]
|
|
563
|
+
];
|
|
564
|
+
for (const [label, asked, refusal, [user, slug]] of refusals) {
|
|
565
|
+
await assert.rejects(memberContext(asked, system), refuses(refusal, label));
|
|
566
|
+
await assert.rejects(directory.resolveWorkspaceContextForUserBySlug(user, slug), refuses(refusal, `${label}'s request`));
|
|
567
|
+
}
|
|
568
|
+
const { memberContext: noTenancyMemberContext } = memberDirectory("none");
|
|
569
|
+
await assert.rejects(
|
|
570
|
+
noTenancyMemberContext({ workspaceId: workspace.id, userId: member.id }, system),
|
|
571
|
+
refuses([403, "workspaces.workspace.contextDisabled"], "an application without workspaces")
|
|
572
|
+
);
|
|
573
|
+
// The member's own context still resolves.
|
|
574
|
+
assert.equal((await memberContext({ workspaceId: workspace.id, userId: member.id }, system)).membership.userId, member.id);
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
test("memberContext refuses a context that is not a system context, and ids that are no record ids, before any statement", async () => {
|
|
578
|
+
const { memberContext } = memberDirectory();
|
|
579
|
+
const owner = await createProfile("Ada");
|
|
580
|
+
const workspace = await workspaces.insert({ slug: "team", name: "Team", ownerUserId: owner.id });
|
|
581
|
+
await memberships.ensureOwnerMembership(workspace.id, owner.id);
|
|
582
|
+
const systemContext = memberJobContext();
|
|
583
|
+
const asked = { workspaceId: workspace.id, userId: owner.id };
|
|
584
|
+
const ownerContext = await memberContext(asked, { context: systemContext });
|
|
585
|
+
const notSystem = /runs only in a system context/u;
|
|
586
|
+
const badIds = /takes \{ workspaceId, userId \}/u;
|
|
587
|
+
const refusals = [
|
|
588
|
+
["no options", asked, undefined, notSystem],
|
|
589
|
+
["no context", asked, {}, notSystem],
|
|
590
|
+
["a signed-in request's context", asked, { context: { actor: { id: owner.id } } }, notSystem],
|
|
591
|
+
["a workspace job's context", asked, { context: systemContext.forWorkspace(workspace.id) }, notSystem],
|
|
592
|
+
["a job for that person", asked, { context: systemContext.forWorkspaceUser(workspace.id, owner.id, { actorId: owner.id }) }, notSystem],
|
|
593
|
+
["a member context", asked, { context: ownerContext }, notSystem],
|
|
594
|
+
["no ids", {}, { context: systemContext }, badIds],
|
|
595
|
+
["no userId", { workspaceId: workspace.id }, { context: systemContext }, badIds],
|
|
596
|
+
["no workspaceId", { userId: owner.id }, { context: systemContext }, badIds],
|
|
597
|
+
...["", "abc", "0", -1, 1.5, {}].flatMap((id) => [
|
|
598
|
+
[`workspaceId ${JSON.stringify(id)}`, { workspaceId: id, userId: owner.id }, { context: systemContext }, badIds],
|
|
599
|
+
[`userId ${JSON.stringify(id)}`, { workspaceId: workspace.id, userId: id }, { context: systemContext }, badIds]
|
|
600
|
+
])
|
|
601
|
+
];
|
|
602
|
+
for (const [label, member, options, message] of refusals) {
|
|
603
|
+
const { statements, sql } = await statementsOf(() => assert.rejects(memberContext(member, options), (error) => {
|
|
604
|
+
assert.ok(error instanceof TypeError, `${label}: ${error}`);
|
|
605
|
+
assert.match(error.message, message, label);
|
|
606
|
+
return true;
|
|
607
|
+
}));
|
|
608
|
+
assert.equal(statements, 0, `${label} is refused before any statement: ${sql.join(" | ")}`);
|
|
609
|
+
}
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
test("memberContext costs the same statements among 10 members and among 200", async (t) => {
|
|
613
|
+
const usernames = Array.from({ length: 211 }, (_, index) => `crew-${String(index).padStart(3, "0")}`);
|
|
614
|
+
const users = await insertUsers(usernames);
|
|
615
|
+
const ownerId = users.get("crew-000");
|
|
616
|
+
const small = await workspaces.insert({ slug: "small-crew", name: "Small crew", ownerUserId: ownerId });
|
|
617
|
+
const large = await workspaces.insert({ slug: "large-crew", name: "Large crew", ownerUserId: ownerId });
|
|
618
|
+
const membership = (workspaceId, username) => ({
|
|
619
|
+
workspace_id: workspaceId,
|
|
620
|
+
user_id: users.get(username),
|
|
621
|
+
role_sid: username === "crew-000" ? "owner" : "member",
|
|
622
|
+
status: "active"
|
|
623
|
+
});
|
|
624
|
+
// Small: crew 0-9. Large: crew 0 and 11-209.
|
|
625
|
+
await insertRows("workspace_memberships", [
|
|
626
|
+
...usernames.slice(0, 10).map((username) => membership(small.id, username)),
|
|
627
|
+
...["crew-000", ...usernames.slice(11, 210)].map((username) => membership(large.id, username))
|
|
628
|
+
]);
|
|
629
|
+
const { memberContext } = memberDirectory();
|
|
630
|
+
const system = { context: memberJobContext() };
|
|
631
|
+
const asked = [{ workspaceId: small.id, userId: users.get("crew-005") }, { workspaceId: large.id, userId: users.get("crew-150") }];
|
|
632
|
+
// Each workspace's first resolution writes its settings.
|
|
633
|
+
for (const member of asked) await memberContext(member, system);
|
|
634
|
+
|
|
635
|
+
const few = await statementsOf(() => memberContext(asked[0], system));
|
|
636
|
+
const many = await statementsOf(() => memberContext(asked[1], system));
|
|
637
|
+
assert.equal(few.result.membership.userId, users.get("crew-005"));
|
|
638
|
+
assert.equal(many.result.membership.userId, users.get("crew-150"));
|
|
639
|
+
t.diagnostic(`memberContext: ${few.statements} statements among 10 members, ${many.statements} among 200: ${many.sql.join(" | ")}`);
|
|
640
|
+
assert.equal(many.statements, few.statements);
|
|
641
|
+
assert.ok(many.sql.every((sql) => /^select\b/iu.test(sql.trim())), "A member's resolution after the first writes nothing");
|
|
642
|
+
});
|
|
643
|
+
|
|
317
644
|
test("workspaces.lock and memberships.lockByWorkspaceIdAndUserId take lockMode share, and refuse another mode before any statement", async () => {
|
|
318
645
|
const owner = await createProfile("Ada");
|
|
319
646
|
const workspace = await workspaces.insert({ slug: "shared", name: "Shared", ownerUserId: owner.id });
|
|
@@ -60,11 +60,13 @@ test("each workspaces-core table is one table resource, and only workspaces and
|
|
|
60
60
|
|
|
61
61
|
// Their id filter is every handle's own, which takes one id or a list.
|
|
62
62
|
test("workspaces-core repository filters are declared on canonical resources", () => {
|
|
63
|
-
assert.deepEqual(Object.keys(workspaceResource.searchSchema), ["slug", "slugs", "owner", "isPersonal"]);
|
|
63
|
+
assert.deepEqual(Object.keys(workspaceResource.searchSchema), ["slug", "slugs", "owner", "isPersonal", "idAfter"]);
|
|
64
64
|
assert.equal(workspaceResource.searchSchema.slug.actualField, "slug");
|
|
65
65
|
assert.equal(workspaceResource.searchSchema.slugs.actualField, "slug");
|
|
66
66
|
assert.equal(workspaceResource.searchSchema.slugs.filterOperator, "in");
|
|
67
67
|
assert.equal(workspaceResource.searchSchema.owner.actualField, "owner_user_id");
|
|
68
|
+
assert.equal(workspaceResource.searchSchema.idAfter.actualField, "id");
|
|
69
|
+
assert.equal(workspaceResource.searchSchema.idAfter.filterOperator, ">");
|
|
68
70
|
|
|
69
71
|
assert.deepEqual(Object.keys(workspaceMembershipsResource.searchSchema), ["workspace", "user", "users", "status"]);
|
|
70
72
|
assert.equal(workspaceMembershipsResource.searchSchema.workspace.actualField, "workspace_id");
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import test from "node:test";
|
|
3
3
|
import Fastify from "fastify";
|
|
4
|
+
import { normalizeAuthActor } from "@jskit-ai/auth-core/server/authActor";
|
|
4
5
|
import { AuthExtensionsProvider } from "@jskit-ai/auth-core/server/providers/AuthExtensionsProvider";
|
|
5
6
|
import { AuthPolicyProvider } from "@jskit-ai/auth-core/server/providers/AuthPolicyProvider";
|
|
6
7
|
import { CrudContractsProvider } from "@jskit-ai/crud-core/server/crudContracts";
|
|
7
8
|
import { defineCrudFeature } from "@jskit-ai/crud-core/server/defineCrudFeature";
|
|
8
9
|
import { countQueries } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
10
|
+
import { jsonApiResultValue } from "@jskit-ai/http-runtime/shared/validators/jsonApiResult";
|
|
11
|
+
import { resolveActorId } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
|
|
9
12
|
import { defineFeature } from "@jskit-ai/kernel/server/features";
|
|
10
13
|
import { HttpProvider } from "@jskit-ai/kernel/server/http";
|
|
11
14
|
import { createBootstrapRuntime } from "@jskit-ai/kernel/server/runtime";
|
|
@@ -103,20 +106,79 @@ const config = Object.freeze({
|
|
|
103
106
|
}
|
|
104
107
|
});
|
|
105
108
|
|
|
106
|
-
//
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
109
|
+
// A workspace_user route whose action answers what a member's code reads from its context, to set a member context's
|
|
110
|
+
// beside the request's.
|
|
111
|
+
const ACTION_READ_CONTEXT = "test.workspace-context.read";
|
|
112
|
+
const ContextFeature = defineFeature({
|
|
113
|
+
id: "test.workspace-context",
|
|
114
|
+
requires: { http: "runtime.http" },
|
|
115
|
+
setup({ http }) {
|
|
116
|
+
http.router.register(
|
|
117
|
+
"GET",
|
|
118
|
+
"/api/w/:workspaceSlug/context",
|
|
119
|
+
{
|
|
120
|
+
auth: "required",
|
|
121
|
+
surface: "app",
|
|
122
|
+
visibility: "workspace_user",
|
|
123
|
+
meta: { summary: "Reads the member's context." },
|
|
124
|
+
params: workspaceSlugParamsValidator
|
|
125
|
+
},
|
|
126
|
+
async function readContext(request, reply) {
|
|
127
|
+
reply.code(200).send(await request.executeAction({ actionId: ACTION_READ_CONTEXT, input: request.input.params }));
|
|
128
|
+
}
|
|
129
|
+
);
|
|
130
|
+
return {};
|
|
131
|
+
},
|
|
132
|
+
actions: [
|
|
133
|
+
Object.freeze({
|
|
134
|
+
id: ACTION_READ_CONTEXT,
|
|
135
|
+
version: 1,
|
|
136
|
+
kind: "query",
|
|
137
|
+
channels: ["api", "internal"],
|
|
138
|
+
surfaces: ["app"],
|
|
139
|
+
input: workspaceSlugParamsValidator,
|
|
140
|
+
output: null,
|
|
141
|
+
execute: (_input, context) => ({
|
|
142
|
+
actorId: resolveActorId(context),
|
|
143
|
+
actor: context.actor,
|
|
144
|
+
workspace: context.workspace,
|
|
145
|
+
membership: context.membership,
|
|
146
|
+
permissions: context.permissions,
|
|
147
|
+
visibilityContext: context.visibilityContext,
|
|
148
|
+
requestVisibilityContext: context.requestMeta.visibilityContext,
|
|
149
|
+
resolvedWorkspaceContext: context.requestMeta.resolvedWorkspaceContext
|
|
150
|
+
})
|
|
151
|
+
})
|
|
152
|
+
]
|
|
114
153
|
});
|
|
115
154
|
|
|
155
|
+
// The signed-in user is the profile the test names in a header, as a session would name it, with the actor the local
|
|
156
|
+
// sign-in provider builds from its account and the profile.
|
|
157
|
+
function headerAuthService(signedIn) {
|
|
158
|
+
return Object.freeze({
|
|
159
|
+
async authenticateRequest(request) {
|
|
160
|
+
const profile = signedIn.get(String(request.headers["x-test-user"] || ""));
|
|
161
|
+
if (!profile) {
|
|
162
|
+
return { authenticated: false, actor: null, transientFailure: false };
|
|
163
|
+
}
|
|
164
|
+
const actor = normalizeAuthActor({
|
|
165
|
+
provider: "local",
|
|
166
|
+
providerUserId: profile.authProviderUserSid,
|
|
167
|
+
email: profile.email,
|
|
168
|
+
displayName: profile.displayName,
|
|
169
|
+
appUserId: profile.id,
|
|
170
|
+
profileSource: "users"
|
|
171
|
+
});
|
|
172
|
+
return { authenticated: true, actor, transientFailure: false };
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
116
177
|
async function issuesApp(t) {
|
|
117
178
|
const knex = await createPackageTestKnex(t, { environment: process.env });
|
|
118
179
|
const app = Fastify();
|
|
119
180
|
t.after(() => app.close());
|
|
181
|
+
const signedIn = new Map();
|
|
120
182
|
const started = await startTestFeatures({
|
|
121
183
|
knex,
|
|
122
184
|
createTables: true,
|
|
@@ -130,11 +192,12 @@ async function issuesApp(t) {
|
|
|
130
192
|
WorkspacesIntegrationsProvider,
|
|
131
193
|
CrudContractsProvider,
|
|
132
194
|
IssuesFeature,
|
|
133
|
-
NoticeFeature
|
|
195
|
+
NoticeFeature,
|
|
196
|
+
ContextFeature
|
|
134
197
|
],
|
|
135
|
-
requires: { profiles: "users.profiles", workspaces: "workspaces.core", memberships: "workspaces.memberships" },
|
|
198
|
+
requires: { profiles: "users.profiles", workspaces: "workspaces.core", memberships: "workspaces.memberships", actions: "runtime.actions" },
|
|
136
199
|
inputs: {
|
|
137
|
-
"auth.service": headerAuthService,
|
|
200
|
+
"auth.service": headerAuthService(signedIn),
|
|
138
201
|
"runtime.app-root": process.cwd(),
|
|
139
202
|
"runtime.bootstrap": createBootstrapRuntime(),
|
|
140
203
|
"runtime.config": config,
|
|
@@ -143,13 +206,17 @@ async function issuesApp(t) {
|
|
|
143
206
|
}
|
|
144
207
|
});
|
|
145
208
|
t.after(started.stop);
|
|
146
|
-
const { profiles, workspaces, memberships } = started.capabilities;
|
|
147
|
-
const person = (name) =>
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
209
|
+
const { profiles, workspaces, memberships, actions } = started.capabilities;
|
|
210
|
+
const person = async (name) => {
|
|
211
|
+
const profile = await profiles.upsert({
|
|
212
|
+
authProvider: "local",
|
|
213
|
+
authProviderUserSid: `identity-${name}`,
|
|
214
|
+
email: `${name}@example.com`,
|
|
215
|
+
displayName: name
|
|
216
|
+
});
|
|
217
|
+
signedIn.set(profile.id, profile);
|
|
218
|
+
return profile;
|
|
219
|
+
};
|
|
153
220
|
const owner = await person("owner");
|
|
154
221
|
const member = await person("member");
|
|
155
222
|
const guest = await person("guest");
|
|
@@ -174,7 +241,17 @@ async function issuesApp(t) {
|
|
|
174
241
|
}
|
|
175
242
|
const list = (user, slug = workspace.slug) => get(user, slug, "issues");
|
|
176
243
|
const notice = (user, slug = workspace.slug) => get(user, slug, "notice");
|
|
177
|
-
|
|
244
|
+
const context = (user, slug = workspace.slug) => get(user, slug, "context");
|
|
245
|
+
// A background job of a feature with a system scope, running one action as a member of the workspace.
|
|
246
|
+
const systemContext = started.resources.declareSystemScope("test.member-jobs", "act for members of every workspace");
|
|
247
|
+
async function runAsMember(user, actionId) {
|
|
248
|
+
const member = await workspaces.memberContext(
|
|
249
|
+
{ workspaceId: workspace.id, userId: user.id },
|
|
250
|
+
{ context: systemContext("run a member's action") }
|
|
251
|
+
);
|
|
252
|
+
return countQueries(knex, () => actions.execute({ actionId, input: { workspaceSlug: workspace.slug }, context: { ...member, surface: "app" } }));
|
|
253
|
+
}
|
|
254
|
+
return { list, notice, context, runAsMember, owner, member, guest, outsider, workspace };
|
|
178
255
|
}
|
|
179
256
|
|
|
180
257
|
// The statements of one read of the workspace context, whatever the database quotes its names with: the workspace by
|
|
@@ -245,3 +322,38 @@ test("a route whose auth policy and action context differ in requiring membershi
|
|
|
245
322
|
assert.equal(response.body.includes("workspaces.workspace.accessDenied"), true, response.body);
|
|
246
323
|
assert.equal(reading(queries, "workspace").length, 1, queries.join("\n"));
|
|
247
324
|
});
|
|
325
|
+
|
|
326
|
+
test("a member context runs an action in the context the member's own request runs it in", async (t) => {
|
|
327
|
+
const { context, runAsMember, owner, member, guest } = await issuesApp(t);
|
|
328
|
+
|
|
329
|
+
for (const [user, roleSid] of [[owner, "owner"], [member, "member"], [guest, "guest"]]) {
|
|
330
|
+
const { response } = await context(user);
|
|
331
|
+
assert.equal(response.statusCode, 200, response.body);
|
|
332
|
+
const request = response.json();
|
|
333
|
+
assert.equal(request.actorId, user.id);
|
|
334
|
+
assert.equal(request.membership.roleSid, roleSid);
|
|
335
|
+
assert.equal(request.visibilityContext.userId, user.id);
|
|
336
|
+
const { result } = await runAsMember(user, ACTION_READ_CONTEXT);
|
|
337
|
+
// The actor, the workspace, the membership, its permissions, the visibility and the whole resolution, as JSON.
|
|
338
|
+
assert.deepEqual(JSON.parse(JSON.stringify(result)), request, `${roleSid}: the member context's action sees the request's context`);
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
test("a member context lists the member's workspace's rows as the member's request does, and is refused where the request is", async (t) => {
|
|
343
|
+
const { list, runAsMember, owner, member, guest } = await issuesApp(t);
|
|
344
|
+
|
|
345
|
+
for (const user of [owner, member]) {
|
|
346
|
+
const { response } = await list(user);
|
|
347
|
+
assert.equal(response.statusCode, 200, response.body);
|
|
348
|
+
// The list action answers a tagged JSON:API document, which the route's transport sends without its links.
|
|
349
|
+
const document = jsonApiResultValue((await runAsMember(user, "crud.issues.list")).result);
|
|
350
|
+
const records = (data) => data.map(({ type, id, attributes }) => ({ type, id, attributes }));
|
|
351
|
+
assert.deepEqual(document.data.map((record) => record.attributes.title).sort(), ["Door sticks", "Lamp flickers"]);
|
|
352
|
+
assert.deepEqual(records(JSON.parse(JSON.stringify(document.data))), records(response.json().data));
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const { response } = await list(guest);
|
|
356
|
+
assert.equal(response.statusCode, 403, response.body);
|
|
357
|
+
assert.equal(response.body.includes("ACTION_PERMISSION_DENIED"), true, response.body);
|
|
358
|
+
await assert.rejects(runAsMember(guest, "crud.issues.list"), (error) => error.status === 403 && error.code === "ACTION_PERMISSION_DENIED");
|
|
359
|
+
});
|