@jskit-ai/workspaces-core 0.2.46 → 0.2.48
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 +3 -0
- package/package.json +3 -3
- package/src/server/common/contributors/workspaceActionContextContributor.js +14 -6
- package/src/server/common/services/workspaceDirectoryService.js +27 -1
- package/src/server/common/services/workspaceMemberContext.js +85 -19
- package/src/server/workspacesRuntime.js +4 -2
- package/test/repositories.integration.test.js +123 -10
- package/test/workspaceActionContextContributor.test.js +37 -0
- package/test/workspaceRequestContextQueries.test.js +38 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- `workspaces.core` gains `roleContext({ workspaceId, userId, role, reason }, { context: systemContext(reason), trx? })`, the context of installer and seed work done in one workspace as a user in a role of the role catalog that they are not given there: required records a workspace gets for the platform's owner, who is normally no member of a self-created workspace, or a seed's starter data. It has exactly a member context's shape (`actor`, `workspace`, `membership`, `permissions`, the `workspace_user` visibility context and `requestMeta.resolvedWorkspaceContext`) with the membership `{ workspaceId, userId, roleSid, status: "active" }`, which is never saved and replaces any membership the user has there, and the role's permissions, so a permission check and a row policy decide as for a member in that role; it also records `reason`, which a row policy reads as `caller.reason` and which grants nothing. It is no system context and no job: request row limits apply and other owners' hidden fields stay hidden. Only a system context makes one, with a non-empty reason; any other context, a missing reason, ids that are no record ids and a role the catalog lacks are a TypeError before any statement, a missing or deleted workspace is 404 `workspaces.workspace.notFound`, a user id naming no one 404 `users.profile.notFound`, and an application without workspaces 403 `workspaces.workspace.contextDisabled`. It reads the user, the workspace and its settings, and writes nothing (no settings, no owner membership). The directory service's new `resolveRoleWorkspaceContextById(user, workspaceId, roleSid, options)` builds it. `memberContext` is unchanged and still means real membership only.
|
|
6
|
+
- An action run in a context that already carries the resolved context of the action's workspace (`requestMeta.resolvedWorkspaceContext` with that workspace's slug, as a member context and a role context carry it) keeps it: the workspace action context contributor no longer reads the workspace, the membership and the settings again, so a role context's unsaved membership survives into the action, and a member context's action no longer repeats its reads.
|
|
7
|
+
|
|
5
8
|
- A new PostgreSQL or SQLite database migrates again with workspaces-core. In 0.2.80 its first `db:migrate` failed with `migration file "workspaces_core_indexes_by_user.cjs" failed` (`relation "workspace_memberships" does not exist` on PostgreSQL, `no such table` on SQLite): Knex runs a package's migrations in file name order, which put the new index migration before `workspaces_core_initial`, the one that makes the tables. `workspaces_core_indexes_by_user` now does nothing when the tables do not exist yet, and the new `workspaces_core_person_indexes`, which runs after `workspaces_core_initial`, adds `ix_workspace_memberships_user` and `ix_workspaces_owner` when they are missing. A database that already ran `workspaces_core_indexes_by_user` keeps its two indexes, and the new migration adds no second copy. MariaDB and MySQL were not affected and nothing changes there. Run `db:migrate`.
|
|
6
9
|
- Making a workspace (`workspace.workspaces.create`) and changing its name or avatar (`workspace.workspaces.update`) publish an entity change of the workspace itself on `runtime.events`: `type` "entity.changed", `source` "workspace", `entity` "workspace", `operation` "created" or "updated", `entityId` the workspace's id from the action's answer. Before, neither action published anything, so an application keeping its own copy of workspace facts (a directory, an index of names) heard of a member or a settings change but never of a new or renamed workspace. The events carry no realtime delivery; no browser is told.
|
|
7
10
|
|
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.48",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"@jskit-ai/resource-core": "0.1.217",
|
|
27
27
|
"@jskit-ai/resource-crud-core": "0.1.219",
|
|
28
|
-
"@jskit-ai/users-core": "0.2.
|
|
28
|
+
"@jskit-ai/users-core": "0.2.48",
|
|
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.",
|
|
@@ -215,6 +215,6 @@
|
|
|
215
215
|
"@jskit-ai/database-runtime": "0.1.275",
|
|
216
216
|
"@jskit-ai/http-runtime": "0.2.26",
|
|
217
217
|
"@jskit-ai/kernel": "0.2.26",
|
|
218
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
218
|
+
"@jskit-ai/resource-runtime": "0.2.36"
|
|
219
219
|
}
|
|
220
220
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { resolveRequest } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
|
|
2
|
-
import { normalizeObject } from "@jskit-ai/kernel/shared/support/normalize";
|
|
2
|
+
import { normalizeLowerText, normalizeObject } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
3
|
import { normalizeSurfaceId } from "@jskit-ai/kernel/shared/surface/registry";
|
|
4
4
|
import {
|
|
5
5
|
checkRouteVisibility,
|
|
@@ -54,11 +54,19 @@ function createWorkspaceActionContextContributor({
|
|
|
54
54
|
resolveOptions.requireMembership = false;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
)
|
|
57
|
+
// A context that already carries this workspace's resolved context, as a member context and a role context do
|
|
58
|
+
// (workspaces.memberContext, workspaces.roleContext), keeps it: a role context's membership is never saved, so no
|
|
59
|
+
// read finds it.
|
|
60
|
+
const carried = context?.requestMeta?.resolvedWorkspaceContext;
|
|
61
|
+
const carriesWorkspace = Boolean(carried?.workspace?.slug) &&
|
|
62
|
+
normalizeLowerText(carried.workspace.slug) === normalizeLowerText(payload.workspaceSlug);
|
|
63
|
+
const resolvedWorkspaceContext = carriesWorkspace
|
|
64
|
+
? carried
|
|
65
|
+
: await workspaceService.resolveWorkspaceContextForUserBySlug(
|
|
66
|
+
resolveActionUser(context, payload),
|
|
67
|
+
payload.workspaceSlug,
|
|
68
|
+
resolveOptions
|
|
69
|
+
);
|
|
62
70
|
|
|
63
71
|
const contribution = {
|
|
64
72
|
requestMeta: {
|
|
@@ -312,6 +312,31 @@ function createService({
|
|
|
312
312
|
return requireMember(await readWorkspaceContextForUser(user, workspace?.deletedAt ? null : workspace, options));
|
|
313
313
|
}
|
|
314
314
|
|
|
315
|
+
/**
|
|
316
|
+
* The workspace context of a user acting in the workspace with this id in a role of the role catalog, for installer
|
|
317
|
+
* and seed work (the `roleContext` of `workspaces.core`): the workspace, an active membership of the user in that
|
|
318
|
+
* role, which is never saved and replaces any membership the user has there, the role's permissions and the
|
|
319
|
+
* workspace's settings as stored. It writes nothing. A deleted or missing workspace is 404
|
|
320
|
+
* `workspaces.workspace.notFound`, as for resolveMemberWorkspaceContextById.
|
|
321
|
+
* @param {{ id: string }} user
|
|
322
|
+
* @param {unknown} workspaceId
|
|
323
|
+
* @param {string} roleSid The id of a role of the role catalog.
|
|
324
|
+
* @param {object} [options]
|
|
325
|
+
*/
|
|
326
|
+
async function resolveRoleWorkspaceContextById(user, workspaceId, roleSid, options = {}) {
|
|
327
|
+
requireWorkspaceContext();
|
|
328
|
+
const workspace = await workspacesRepository.findById(workspaceId, options);
|
|
329
|
+
if (!workspace || workspace.deletedAt) {
|
|
330
|
+
throw new AppError(404, "Workspace not found.", { code: "workspaces.workspace.notFound" });
|
|
331
|
+
}
|
|
332
|
+
return {
|
|
333
|
+
workspace,
|
|
334
|
+
membership: Object.freeze({ workspaceId: workspace.id, userId: user.id, roleSid, status: "active" }),
|
|
335
|
+
permissions: listCatalogRolePermissions(roleCatalog, roleSid),
|
|
336
|
+
workspaceSettings: await workspaceSettingsRepository.findByWorkspaceId(workspace.id, options)
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
315
340
|
function requireWorkspaceContext() {
|
|
316
341
|
if (resolvedTenancyMode === TENANCY_MODE_NONE) {
|
|
317
342
|
throw new AppError(403, "Workspace context is disabled.", { code: "workspaces.workspace.contextDisabled" });
|
|
@@ -370,7 +395,8 @@ function createService({
|
|
|
370
395
|
listWorkspacesForUser,
|
|
371
396
|
listWorkspacesForAuthenticatedUser,
|
|
372
397
|
resolveWorkspaceContextForUserBySlug,
|
|
373
|
-
resolveMemberWorkspaceContextById
|
|
398
|
+
resolveMemberWorkspaceContextById,
|
|
399
|
+
resolveRoleWorkspaceContextById
|
|
374
400
|
});
|
|
375
401
|
}
|
|
376
402
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { normalizeAuthActor } from "@jskit-ai/auth-core/server/authActor";
|
|
2
|
-
import {
|
|
2
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
3
|
+
import { normalizeLowerText, normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
4
|
import { normalizeVisibilityContext, ROUTE_VISIBILITY_WORKSPACE_USER } from "@jskit-ai/kernel/shared/support/visibility";
|
|
4
5
|
import { isSystemContext } from "@jskit-ai/resource-runtime/server";
|
|
5
6
|
import { buildVisibilityContribution } from "../contributors/workspaceRouteVisibilityResolver.js";
|
|
@@ -21,12 +22,39 @@ function memberActorOf(profile) {
|
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
/**
|
|
24
|
-
* The
|
|
25
|
+
* The context of the user this profile is in a resolved workspace context, as their request on a `workspace_user`
|
|
26
|
+
* route carries it.
|
|
27
|
+
* @param {{ id: string, authProvider: string, authProviderUserSid: string, email: string, displayName: string }} profile
|
|
28
|
+
* @param {{ workspace: { id: string }, membership: object, permissions: string[] }} resolvedWorkspaceContext
|
|
29
|
+
*/
|
|
30
|
+
function workspaceUserContextOf(profile, resolvedWorkspaceContext) {
|
|
31
|
+
return {
|
|
32
|
+
actor: memberActorOf(profile),
|
|
33
|
+
workspace: resolvedWorkspaceContext.workspace,
|
|
34
|
+
membership: resolvedWorkspaceContext.membership,
|
|
35
|
+
permissions: resolvedWorkspaceContext.permissions,
|
|
36
|
+
// An action it runs resolves its visibility as that route's request does, to this visibility context.
|
|
37
|
+
routeVisibility: ROUTE_VISIBILITY_WORKSPACE_USER,
|
|
38
|
+
visibilityContext: normalizeVisibilityContext({
|
|
39
|
+
visibility: ROUTE_VISIBILITY_WORKSPACE_USER,
|
|
40
|
+
...buildVisibilityContribution({
|
|
41
|
+
visibility: ROUTE_VISIBILITY_WORKSPACE_USER,
|
|
42
|
+
scopeOwnerId: resolvedWorkspaceContext.workspace.id,
|
|
43
|
+
userId: profile.id
|
|
44
|
+
})
|
|
45
|
+
}),
|
|
46
|
+
requestMeta: Object.freeze({ resolvedWorkspaceContext })
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The `memberContext` and `roleContext` of `workspaces.core`.
|
|
25
52
|
* @param {object} dependencies
|
|
26
53
|
* @param {import("../../types.js").WorkspaceDirectoryService} dependencies.workspaceService
|
|
27
54
|
* @param {import("@jskit-ai/users-core/server/types").UsersProfiles} dependencies.userProfiles
|
|
55
|
+
* @param {import("../../types.js").WorkspaceRoleCatalog} dependencies.roleCatalog
|
|
28
56
|
*/
|
|
29
|
-
function createWorkspaceMemberContexts({ workspaceService, userProfiles }) {
|
|
57
|
+
function createWorkspaceMemberContexts({ workspaceService, userProfiles, roleCatalog }) {
|
|
30
58
|
/**
|
|
31
59
|
* The context of one member of one workspace, for background work done as that member (a record started for the
|
|
32
60
|
* person it is assigned to, a notification for one recipient, a submission synced for the person who made it): the
|
|
@@ -63,27 +91,65 @@ function createWorkspaceMemberContexts({ workspaceService, userProfiles }) {
|
|
|
63
91
|
// A user id that names no one is no member, which the membership check refuses.
|
|
64
92
|
const profile = await userProfiles.findById(normalizedUserId, options);
|
|
65
93
|
const resolvedWorkspaceContext = await workspaceService.resolveMemberWorkspaceContextById(profile, normalizedWorkspaceId, options);
|
|
94
|
+
return Object.freeze(workspaceUserContextOf(profile, resolvedWorkspaceContext));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The context of a user acting in one workspace in a role of the role catalog that they are not given there, for
|
|
99
|
+
* installer and seed work the platform does for a person who is no member, or a member in another role: required
|
|
100
|
+
* modules installed for the platform's owner in each workspace, say. It has exactly a member context's shape: the
|
|
101
|
+
* user is its `actor`, `membership` is an active membership of theirs in that role
|
|
102
|
+
* (`{ workspaceId, userId, roleSid, status: "active" }`), which is never saved and replaces any membership they
|
|
103
|
+
* have there, and `permissions` are the role's, so a permission check or a row policy that reads them decides as for
|
|
104
|
+
* a member in that role. It is no system context and no job: request row limits apply, other owners' hidden fields
|
|
105
|
+
* stay hidden, and a row policy is told `caller.kind` "user", with the `reason` the context records as
|
|
106
|
+
* `caller.reason`, which grants nothing. Work done as a real member takes `memberContext`, which refuses anyone who
|
|
107
|
+
* is not one.
|
|
108
|
+
*
|
|
109
|
+
* Only a system context makes one (`{ context: systemContext(reason) }`, with `trx` to read in the caller's
|
|
110
|
+
* transaction), and only with the reason this work acts in a role: any other context, a missing or blank reason,
|
|
111
|
+
* ids that are no record ids and a role the catalog does not have are a TypeError, before any statement. A missing
|
|
112
|
+
* or deleted workspace is 404 `workspaces.workspace.notFound`, a user id that names no one 404
|
|
113
|
+
* `users.profile.notFound`, and an application without workspaces 403 `workspaces.workspace.contextDisabled`. It
|
|
114
|
+
* reads the user, the workspace and its settings, and writes nothing.
|
|
115
|
+
* @param {{ workspaceId: unknown, userId: unknown, role: unknown, reason: unknown }} acting
|
|
116
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
|
|
117
|
+
*/
|
|
118
|
+
async function roleContext({ workspaceId, userId, role, reason } = {}, options = {}) {
|
|
119
|
+
if (!isSystemContext(options.context)) {
|
|
120
|
+
throw new TypeError("workspaces.roleContext() runs only in a system context: pass { context: systemContext(reason) }.");
|
|
121
|
+
}
|
|
122
|
+
const normalizedReason = typeof reason === "string" ? reason.trim() : "";
|
|
123
|
+
if (!normalizedReason) {
|
|
124
|
+
throw new TypeError("workspaces.roleContext() needs { reason }: why this work acts in a role the user is not given in the workspace.");
|
|
125
|
+
}
|
|
126
|
+
const normalizedWorkspaceId = normalizeRecordId(workspaceId, { fallback: null });
|
|
127
|
+
const normalizedUserId = normalizeRecordId(userId, { fallback: null });
|
|
128
|
+
if (!normalizedWorkspaceId || !normalizedUserId) {
|
|
129
|
+
throw new TypeError(
|
|
130
|
+
"workspaces.roleContext() takes { workspaceId, userId }, the ids of a workspace and of the user who acts in it. " +
|
|
131
|
+
`Received: ${String(workspaceId)}, ${String(userId)}`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
const roleSid = normalizeLowerText(role);
|
|
135
|
+
const roleIds = roleCatalog.roles.map((entry) => entry.id);
|
|
136
|
+
if (!roleIds.includes(roleSid)) {
|
|
137
|
+
throw new TypeError(`workspaces.roleContext() takes a role of the role catalog (${roleIds.join(", ")}). Received: ${String(role)}`);
|
|
138
|
+
}
|
|
139
|
+
const profile = await userProfiles.findById(normalizedUserId, options);
|
|
140
|
+
if (!profile) {
|
|
141
|
+
throw new AppError(404, "User profile was not found.", { code: "users.profile.notFound" });
|
|
142
|
+
}
|
|
143
|
+
const resolvedWorkspaceContext = await workspaceService.resolveRoleWorkspaceContextById(profile, normalizedWorkspaceId, roleSid, options);
|
|
66
144
|
return Object.freeze({
|
|
67
|
-
|
|
68
|
-
|
|
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 })
|
|
145
|
+
...workspaceUserContextOf(profile, resolvedWorkspaceContext),
|
|
146
|
+
reason: normalizedReason
|
|
82
147
|
});
|
|
83
148
|
}
|
|
84
149
|
|
|
85
150
|
return Object.freeze({
|
|
86
|
-
memberContext
|
|
151
|
+
memberContext,
|
|
152
|
+
roleContext
|
|
87
153
|
});
|
|
88
154
|
}
|
|
89
155
|
|
|
@@ -72,7 +72,7 @@ function createWorkspaceRecords(resources) {
|
|
|
72
72
|
|
|
73
73
|
/**
|
|
74
74
|
* The `workspaces.core` capability: the workspace services, the invite and
|
|
75
|
-
* settings repositories and `
|
|
75
|
+
* settings repositories, `memberContext` and `roleContext`, built from the runtime config.
|
|
76
76
|
* @param {object} dependencies
|
|
77
77
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} dependencies.appRoot
|
|
78
78
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} dependencies.config
|
|
@@ -159,7 +159,7 @@ function createWorkspacesRuntime({
|
|
|
159
159
|
workspaceInvitationsEnabled: invitationsEnabled,
|
|
160
160
|
roleCatalog
|
|
161
161
|
});
|
|
162
|
-
const memberContexts = createWorkspaceMemberContexts({ workspaceService, userProfiles });
|
|
162
|
+
const memberContexts = createWorkspaceMemberContexts({ workspaceService, userProfiles, roleCatalog });
|
|
163
163
|
|
|
164
164
|
return Object.freeze({
|
|
165
165
|
enabled: tenancyProfile.workspace.enabled === true,
|
|
@@ -167,6 +167,8 @@ function createWorkspacesRuntime({
|
|
|
167
167
|
selfCreateEnabled: tenancyProfile.workspace.allowSelfCreate === true,
|
|
168
168
|
// The context of one member of one workspace, for background work done as that member.
|
|
169
169
|
memberContext: memberContexts.memberContext,
|
|
170
|
+
// The context of a user acting in one workspace in a role they are not given there, for installer and seed work.
|
|
171
|
+
roleContext: memberContexts.roleContext,
|
|
170
172
|
// The workspace route support the assistant runtime reads.
|
|
171
173
|
scope: Object.freeze({
|
|
172
174
|
params: workspaceSlugParamsValidator,
|
|
@@ -435,24 +435,25 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
|
|
|
435
435
|
// The directory service as workspacesRuntime builds it, with roles that grant different permissions, and its member
|
|
436
436
|
// contexts.
|
|
437
437
|
function memberDirectory(tenancyMode = "workspaces") {
|
|
438
|
+
const roleCatalog = createWorkspaceRoleCatalog({
|
|
439
|
+
roleCatalog: {
|
|
440
|
+
roles: {
|
|
441
|
+
owner: { permissions: ["*"] },
|
|
442
|
+
admin: { assignable: true, permissions: ["workspace.members.view", "crud.notes.patch"] },
|
|
443
|
+
member: { assignable: true, permissions: ["crud.notes.list"] }
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
});
|
|
438
447
|
const directory = createDirectoryService({
|
|
439
448
|
tenancyProfile: resolveTenancyProfile({ tenancyMode }),
|
|
440
|
-
roleCatalog
|
|
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
|
+
roleCatalog,
|
|
449
450
|
personalWorkspaceName: buildWorkspaceName,
|
|
450
451
|
createdParticipant: noWorkspaceCreatedParticipant,
|
|
451
452
|
workspacesRepository: workspaces,
|
|
452
453
|
workspaceMembershipsRepository: memberships,
|
|
453
454
|
workspaceSettingsRepository: settings
|
|
454
455
|
});
|
|
455
|
-
return { directory, ...createWorkspaceMemberContexts({ workspaceService: directory, userProfiles: profiles }) };
|
|
456
|
+
return { directory, ...createWorkspaceMemberContexts({ workspaceService: directory, userProfiles: profiles, roleCatalog }) };
|
|
456
457
|
}
|
|
457
458
|
|
|
458
459
|
// A signed-in request's actor for a profile, as the local sign-in provider builds it.
|
|
@@ -641,6 +642,118 @@ describe(`users and workspaces repositories on migrated ${databaseLabel}`, () =>
|
|
|
641
642
|
assert.ok(many.sql.every((sql) => /^select\b/iu.test(sql.trim())), "A member's resolution after the first writes nothing");
|
|
642
643
|
});
|
|
643
644
|
|
|
645
|
+
test("roleContext gives a user a role of the catalog in a workspace, a member context's shape with an unsaved membership and the reason, and writes nothing", async () => {
|
|
646
|
+
const { directory, memberContext, roleContext } = memberDirectory();
|
|
647
|
+
const owner = await createProfile("Ada");
|
|
648
|
+
const member = await createProfile("Grace");
|
|
649
|
+
const outsider = await createProfile("Linus");
|
|
650
|
+
const workspace = await workspaces.insert({ slug: "team", name: "Team", ownerUserId: owner.id });
|
|
651
|
+
await memberships.ensureOwnerMembership(workspace.id, owner.id);
|
|
652
|
+
await memberships.addMember({ workspaceId: workspace.id, userId: member.id });
|
|
653
|
+
// The workspace's first request writes its settings; a workspace no request has opened has none yet.
|
|
654
|
+
await directory.resolveWorkspaceContextForUserBySlug(owner, workspace.slug);
|
|
655
|
+
const unopened = await workspaces.insert({ slug: "new", name: "New", ownerUserId: owner.id });
|
|
656
|
+
const system = { context: memberJobContext() };
|
|
657
|
+
const reason = "install the required modules for the platform's owner";
|
|
658
|
+
|
|
659
|
+
for (const [person, role] of [[outsider, "admin"], [member, "admin"], [owner, "member"]]) {
|
|
660
|
+
const { result: context, sql } = await statementsOf(() => roleContext({ workspaceId: workspace.id, userId: person.id, role, reason }, system));
|
|
661
|
+
assert.ok(sql.every((statement) => /^select\b/iu.test(statement.trim())), `${role} for ${person.displayName} writes nothing: ${sql.join(" | ")}`);
|
|
662
|
+
assert.deepEqual(context.membership, { workspaceId: workspace.id, userId: person.id, roleSid: role, status: "active" });
|
|
663
|
+
assert.deepEqual(context.permissions, role === "admin" ? ["workspace.members.view", "crud.notes.patch"] : ["crud.notes.list"]);
|
|
664
|
+
assert.deepEqual(context.actor, requestActorOf(person), "signed in as the user it names");
|
|
665
|
+
assert.equal(resolveActorId(context), person.id);
|
|
666
|
+
assert.equal(context.reason, reason);
|
|
667
|
+
assert.equal(isSystemContext(context), false, "A role context is no system context");
|
|
668
|
+
assert.equal(Object.isFrozen(context), true);
|
|
669
|
+
// A member context's shape, with the reason: the same workspace, visibility and settings as the member's request.
|
|
670
|
+
const request = await directory.resolveWorkspaceContextForUserBySlug(owner, workspace.slug);
|
|
671
|
+
assert.deepEqual(Object.keys(context).sort(), [...Object.keys(await memberContext({ workspaceId: workspace.id, userId: owner.id }, system)), "reason"].sort());
|
|
672
|
+
assert.deepEqual(context.workspace, request.workspace);
|
|
673
|
+
assert.equal(context.routeVisibility, "workspace_user");
|
|
674
|
+
assert.deepEqual(context.visibilityContext, {
|
|
675
|
+
visibility: "workspace_user",
|
|
676
|
+
scopeKind: "workspace_user",
|
|
677
|
+
requiresActorScope: true,
|
|
678
|
+
scopeOwnerId: workspace.id,
|
|
679
|
+
userId: person.id
|
|
680
|
+
});
|
|
681
|
+
assert.deepEqual(context.requestMeta.resolvedWorkspaceContext, {
|
|
682
|
+
workspace: request.workspace,
|
|
683
|
+
membership: context.membership,
|
|
684
|
+
permissions: context.permissions,
|
|
685
|
+
workspaceSettings: request.workspaceSettings
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
// The users' real memberships are as they were: none for the outsider, and the member's own role.
|
|
689
|
+
assert.equal(await memberships.findByWorkspaceIdAndUserId(workspace.id, outsider.id), null);
|
|
690
|
+
assert.equal((await memberships.findByWorkspaceIdAndUserId(workspace.id, member.id)).roleSid, "member");
|
|
691
|
+
assert.equal((await memberContext({ workspaceId: workspace.id, userId: member.id }, system)).membership.roleSid, "member");
|
|
692
|
+
await assert.rejects(memberContext({ workspaceId: workspace.id, userId: outsider.id }, system), (error) => error.status === 403);
|
|
693
|
+
|
|
694
|
+
// A workspace no request has opened has no settings yet, and the role context writes none, nor the owner's
|
|
695
|
+
// membership a member context ensures.
|
|
696
|
+
const { result: fresh, sql } = await statementsOf(() => roleContext({ workspaceId: unopened.id, userId: owner.id, role: "OWNER", reason }, system));
|
|
697
|
+
assert.ok(sql.every((statement) => /^select\b/iu.test(statement.trim())), sql.join(" | "));
|
|
698
|
+
assert.equal(fresh.requestMeta.resolvedWorkspaceContext.workspaceSettings, null);
|
|
699
|
+
assert.equal(fresh.membership.roleSid, "owner");
|
|
700
|
+
assert.equal(await knex("workspace_settings").where({ workspace_id: unopened.id }).first(), undefined);
|
|
701
|
+
assert.equal(await memberships.findByWorkspaceIdAndUserId(unopened.id, owner.id), null);
|
|
702
|
+
|
|
703
|
+
// In the caller's transaction it reads what the transaction wrote.
|
|
704
|
+
await memberships.withTransaction(system, async (txOptions) => {
|
|
705
|
+
const joiner = await createProfile("Barbara", txOptions);
|
|
706
|
+
const context = await roleContext({ workspaceId: workspace.id, userId: joiner.id, role: "member", reason }, txOptions);
|
|
707
|
+
assert.equal(context.actor.id, joiner.id);
|
|
708
|
+
});
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
test("roleContext refuses no system context, a missing reason, ids that are no record ids and a role the catalog lacks before any statement, and a missing workspace or user with 404", async () => {
|
|
712
|
+
const { roleContext } = memberDirectory();
|
|
713
|
+
const owner = await createProfile("Ada");
|
|
714
|
+
const workspace = await workspaces.insert({ slug: "team", name: "Team", ownerUserId: owner.id });
|
|
715
|
+
await memberships.ensureOwnerMembership(workspace.id, owner.id);
|
|
716
|
+
const deleted = await workspaces.insert({ slug: "gone", name: "Gone", ownerUserId: owner.id });
|
|
717
|
+
await workspaces.updateById(deleted.id, { deletedAt: new Date().toISOString() });
|
|
718
|
+
const systemContext = memberJobContext();
|
|
719
|
+
const asked = { workspaceId: workspace.id, userId: owner.id, role: "admin", reason: "seed the workspace's starter records" };
|
|
720
|
+
assert.equal((await roleContext(asked, { context: systemContext })).membership.roleSid, "admin");
|
|
721
|
+
const notSystem = /roleContext\(\) runs only in a system context/u;
|
|
722
|
+
const noReason = /roleContext\(\) needs \{ reason \}/u;
|
|
723
|
+
const badIds = /roleContext\(\) takes \{ workspaceId, userId \}/u;
|
|
724
|
+
const badRole = /roleContext\(\) takes a role of the role catalog \(owner, admin, member\)/u;
|
|
725
|
+
const refusals = [
|
|
726
|
+
["no options", asked, undefined, notSystem],
|
|
727
|
+
["a signed-in request's context", asked, { context: { actor: { id: owner.id } } }, notSystem],
|
|
728
|
+
["a workspace job's context", asked, { context: systemContext.forWorkspace(workspace.id) }, notSystem],
|
|
729
|
+
["a role context", asked, { context: await roleContext(asked, { context: systemContext }) }, notSystem],
|
|
730
|
+
...[undefined, "", " ", 7, {}].map((reason) => [`reason ${JSON.stringify(reason)}`, { ...asked, reason }, { context: systemContext }, noReason]),
|
|
731
|
+
["no workspaceId", { ...asked, workspaceId: undefined }, { context: systemContext }, badIds],
|
|
732
|
+
["userId \"abc\"", { ...asked, userId: "abc" }, { context: systemContext }, badIds],
|
|
733
|
+
...[undefined, "", "superuser", "admins"].map((role) => [`role ${JSON.stringify(role)}`, { ...asked, role }, { context: systemContext }, badRole])
|
|
734
|
+
];
|
|
735
|
+
for (const [label, acting, options, message] of refusals) {
|
|
736
|
+
const { statements, sql } = await statementsOf(() => assert.rejects(roleContext(acting, options), (error) => {
|
|
737
|
+
assert.ok(error instanceof TypeError, `${label}: ${error}`);
|
|
738
|
+
assert.match(error.message, message, label);
|
|
739
|
+
return true;
|
|
740
|
+
}));
|
|
741
|
+
assert.equal(statements, 0, `${label} is refused before any statement: ${sql.join(" | ")}`);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
const refuses = ([status, code], label) => (error) => {
|
|
745
|
+
assert.ok(error instanceof AppError, `${label}: ${error}`);
|
|
746
|
+
assert.deepEqual([error.status, error.code], [status, code], label);
|
|
747
|
+
return true;
|
|
748
|
+
};
|
|
749
|
+
const system = { context: systemContext };
|
|
750
|
+
await assert.rejects(roleContext({ ...asked, workspaceId: "999999" }, system), refuses([404, "workspaces.workspace.notFound"], "a workspace id naming no workspace"));
|
|
751
|
+
await assert.rejects(roleContext({ ...asked, workspaceId: deleted.id }, system), refuses([404, "workspaces.workspace.notFound"], "a deleted workspace"));
|
|
752
|
+
await assert.rejects(roleContext({ ...asked, userId: "999999" }, system), refuses([404, "users.profile.notFound"], "a user id naming no one"));
|
|
753
|
+
const { roleContext: noTenancyRoleContext } = memberDirectory("none");
|
|
754
|
+
await assert.rejects(noTenancyRoleContext(asked, system), refuses([403, "workspaces.workspace.contextDisabled"], "an application without workspaces"));
|
|
755
|
+
});
|
|
756
|
+
|
|
644
757
|
test("workspaces.lock and memberships.lockByWorkspaceIdAndUserId take lockMode share, and refuse another mode before any statement", async () => {
|
|
645
758
|
const owner = await createProfile("Ada");
|
|
646
759
|
const workspace = await workspaces.insert({ slug: "shared", name: "Shared", ownerUserId: owner.id });
|
|
@@ -383,3 +383,40 @@ test("workspace action context contributor permits missing membership only for a
|
|
|
383
383
|
assert.equal(contribution.membership, null);
|
|
384
384
|
assert.deepEqual(contribution.permissions, []);
|
|
385
385
|
});
|
|
386
|
+
|
|
387
|
+
test("workspace action context contributor keeps the resolved context a member or role context carries for the action's workspace", async () => {
|
|
388
|
+
const calls = [];
|
|
389
|
+
const contributor = createWorkspaceActionContextContributor({
|
|
390
|
+
workspaceService: {
|
|
391
|
+
async resolveWorkspaceContextForUserBySlug(user, workspaceSlug) {
|
|
392
|
+
calls.push(workspaceSlug);
|
|
393
|
+
return { workspace: { id: 11, slug: workspaceSlug }, membership: null, permissions: [] };
|
|
394
|
+
}
|
|
395
|
+
},
|
|
396
|
+
workspaceSurfaceIds: ["app"]
|
|
397
|
+
});
|
|
398
|
+
// A role context's membership, which no read finds.
|
|
399
|
+
const carried = {
|
|
400
|
+
workspace: { id: 10, slug: "acme" },
|
|
401
|
+
membership: { workspaceId: "10", userId: "42", roleSid: "owner", status: "active" },
|
|
402
|
+
permissions: ["*"]
|
|
403
|
+
};
|
|
404
|
+
const context = {
|
|
405
|
+
actor: { id: 42 },
|
|
406
|
+
workspace: carried.workspace,
|
|
407
|
+
membership: carried.membership,
|
|
408
|
+
permissions: carried.permissions,
|
|
409
|
+
requestMeta: { resolvedWorkspaceContext: carried }
|
|
410
|
+
};
|
|
411
|
+
const contribute = (workspaceSlug) => contributor.contribute({
|
|
412
|
+
definition: { id: "templates.install", surfaces: ["app"] },
|
|
413
|
+
input: { workspaceSlug },
|
|
414
|
+
context
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
assert.deepEqual(await contribute("ACME"), { requestMeta: { resolvedWorkspaceContext: carried } });
|
|
418
|
+
assert.deepEqual(calls, [], "the carried context of the same workspace is not resolved again");
|
|
419
|
+
// Another workspace's slug is resolved as before.
|
|
420
|
+
assert.deepEqual((await contribute("other")).requestMeta.resolvedWorkspaceContext.workspace, { id: 11, slug: "other" });
|
|
421
|
+
assert.deepEqual(calls, ["other"]);
|
|
422
|
+
});
|
|
@@ -251,7 +251,15 @@ async function issuesApp(t) {
|
|
|
251
251
|
);
|
|
252
252
|
return countQueries(knex, () => actions.execute({ actionId, input: { workspaceSlug: workspace.slug }, context: { ...member, surface: "app" } }));
|
|
253
253
|
}
|
|
254
|
-
|
|
254
|
+
// The same job running one action as a user in a role of the catalog, for installer work.
|
|
255
|
+
async function runInRole(user, role, actionId) {
|
|
256
|
+
const acting = await workspaces.roleContext(
|
|
257
|
+
{ workspaceId: workspace.id, userId: user.id, role, reason: "install the workspace's required records" },
|
|
258
|
+
{ context: systemContext("install each workspace's required records") }
|
|
259
|
+
);
|
|
260
|
+
return countQueries(knex, () => actions.execute({ actionId, input: { workspaceSlug: workspace.slug }, context: { ...acting, surface: "app" } }));
|
|
261
|
+
}
|
|
262
|
+
return { list, notice, context, runAsMember, runInRole, owner, member, guest, outsider, workspace };
|
|
255
263
|
}
|
|
256
264
|
|
|
257
265
|
// The statements of one read of the workspace context, whatever the database quotes its names with: the workspace by
|
|
@@ -357,3 +365,32 @@ test("a member context lists the member's workspace's rows as the member's reque
|
|
|
357
365
|
assert.equal(response.body.includes("ACTION_PERMISSION_DENIED"), true, response.body);
|
|
358
366
|
await assert.rejects(runAsMember(guest, "crud.issues.list"), (error) => error.status === 403 && error.code === "ACTION_PERMISSION_DENIED");
|
|
359
367
|
});
|
|
368
|
+
|
|
369
|
+
test("a role context runs an action as a member in that role would, for a user who is no member or a member in another role, and writes nothing", async (t) => {
|
|
370
|
+
const { context, list, runInRole, member, guest, outsider } = await issuesApp(t);
|
|
371
|
+
|
|
372
|
+
// The action sees what a member in that role sees at their own request, with an unsaved membership.
|
|
373
|
+
const request = (await context(member)).response.json();
|
|
374
|
+
for (const user of [outsider, guest]) {
|
|
375
|
+
const { result, queries } = await runInRole(user, "member", ACTION_READ_CONTEXT);
|
|
376
|
+
const seen = JSON.parse(JSON.stringify(result));
|
|
377
|
+
assert.deepEqual(seen.membership, { workspaceId: request.workspace.id, userId: user.id, roleSid: "member", status: "active" });
|
|
378
|
+
assert.equal(seen.actorId, user.id);
|
|
379
|
+
assert.deepEqual(seen.permissions, request.permissions, "the role's permissions");
|
|
380
|
+
assert.deepEqual(seen.workspace, request.workspace);
|
|
381
|
+
assert.deepEqual(seen.visibilityContext, { ...request.visibilityContext, userId: user.id });
|
|
382
|
+
assert.ok(queries.every((sql) => /^select\b/iu.test(sql.trim())), `nothing is written: ${queries.join("\n")}`);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// The permission check passes as the role: the member role lists the workspace's issues, which the outsider's and
|
|
386
|
+
// the guest's own requests may not, and the guest role is refused as a guest's request is.
|
|
387
|
+
assert.equal((await list(outsider)).response.statusCode, 403);
|
|
388
|
+
assert.equal((await list(guest)).response.statusCode, 403);
|
|
389
|
+
const memberTitles = (await list(member)).response.json().data.map((record) => record.attributes.title).sort();
|
|
390
|
+
for (const user of [outsider, guest]) {
|
|
391
|
+
const { result, queries } = await runInRole(user, "member", "crud.issues.list");
|
|
392
|
+
assert.deepEqual(jsonApiResultValue(result).data.map((record) => record.attributes.title).sort(), memberTitles);
|
|
393
|
+
assert.ok(queries.every((sql) => /^select\b/iu.test(sql.trim())), `nothing is written: ${queries.join("\n")}`);
|
|
394
|
+
}
|
|
395
|
+
await assert.rejects(runInRole(member, "guest", "crud.issues.list"), (error) => error.status === 403 && error.code === "ACTION_PERMISSION_DENIED");
|
|
396
|
+
});
|