@jskit-ai/workspaces-core 0.2.52 → 0.2.54
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 +1 -0
- package/locales/en.json +1 -0
- package/package.json +3 -3
- package/src/server/common/repositories/workspacesRepository.js +92 -2
- package/src/server/workspaceDirectory/workspaceDirectoryActions.js +2 -1
- package/test/support/transferOwnershipCases.js +373 -0
- package/test/transferOwnership.mysql.test.js +5 -0
- package/test/transferOwnership.postgres.test.js +5 -0
- package/test/transferOwnership.test.js +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- `workspaces.transferOwnership({ workspaceId, toUserId, previousOwnerRoleSid = "admin" }, options)` hands a workspace to another of its active members, in the caller's transaction when `options` carries one and in one of its own otherwise. It locks the workspace's row and reads the workspace through that lock, then locks the new and the previous owner's memberships in one locking read, so two transfers of one workspace take turns and the second moves it on from the owner the first left. `owner_user_id` becomes `toUserId` and `updatedAt` moves; the new owner's membership takes the `owner` role; the previous owner's takes `previousOwnerRoleSid` and stays active, or is created active with it when they had none. A personal workspace stops being personal (`is_personal` false): the new owner's own personal workspace stays theirs, and where personal workspaces are provisioned the previous owner is given a new one at their next provisioning. A `toUserId` who already owns it writes nothing and answers `changed: false`. A missing or deleted workspace is 404 `workspaces.workspace.notFound` and a `toUserId` with no active membership 409 `workspaces.member.newOwnerNotActive` (new, "The new owner must be an active member of the workspace."), with nothing written; ids that are no record ids and a `previousOwnerRoleSid` that is not the text of a role other than `owner` are a TypeError before any statement. It answers the workspace as `findById` answers it, plus `previousOwnerUserId` and `changed`, sends the same statements however many members the workspace has, and publishes no event: an application keeping its own copy of workspace facts updates it from the answer.
|
|
5
6
|
- `createStandaloneRoleContext({ resources, config })` (`@jskit-ai/workspaces-core/server/standaloneRoleContext`) gives code outside a JSKIT server, such as a migration or seed script that owns its tables through `createStandaloneResources`, `workspaces.core`'s `roleContext`: the same function, built by the same code (`createWorkspaceDirectory`, which `createWorkspacesRuntime` now uses too) from the application's runtime config, on the handles of the script's standalone runtime, which owns `ROLE_CONTEXT_TABLES` (the workspaces and users tables, exported beside it) with its own tables: `createStandaloneResources({ knex, feature, owns: [...ROLE_CONTEXT_TABLES, ...seedTables], systemScope })`. It takes the same arguments, answers the same context and refuses the same calls, with the script's own system context; resources that lack one of those tables are a `TypeError` naming them. On a server's Knex client `createStandaloneResources` refuses those tables (`DuplicateOwnerError`): code there takes `workspaces.core`'s.
|
|
6
7
|
- **Breaking:** a provided `workspaces.invite-mailer` sends as `APP_ENV` says (`createAppEnvironmentInviteMailer`, replacing the simulated mailer): production sends each invitation; staging sends it only to `STAGING_EMAIL_TO`, its message marked with the address it was for; development, test and staging without `STAGING_EMAIL_TO` log it and answer `status: "simulated"` (`workspaces.invite.simulated`, "Outside production the invitation email was logged, not sent. Copy the invite link to share it."). A role grant no action requires refuses to start in development and test and is logged in staging and production, by `APP_ENV`, not `NODE_ENV`.
|
|
7
8
|
- `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.
|
package/locales/en.json
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"notFound": "Member not found.",
|
|
22
22
|
"ownerRoleLocked": "Cannot change workspace owner role.",
|
|
23
23
|
"ownerNotRemovable": "Cannot remove workspace owner.",
|
|
24
|
+
"newOwnerNotActive": "The new owner must be an active member of the workspace.",
|
|
24
25
|
"cursorInvalid": "This list's cursor is not one it answered."
|
|
25
26
|
},
|
|
26
27
|
"invite": {
|
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.54",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"@jskit-ai/resource-core": "0.1.218",
|
|
28
28
|
"@jskit-ai/resource-crud-core": "0.1.220",
|
|
29
|
-
"@jskit-ai/users-core": "0.2.
|
|
29
|
+
"@jskit-ai/users-core": "0.2.54",
|
|
30
30
|
"json-rest-schema": "^1.0.20"
|
|
31
31
|
},
|
|
32
32
|
"description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
|
|
@@ -220,6 +220,6 @@
|
|
|
220
220
|
"@jskit-ai/database-runtime": "0.1.276",
|
|
221
221
|
"@jskit-ai/http-runtime": "0.2.27",
|
|
222
222
|
"@jskit-ai/kernel": "0.2.27",
|
|
223
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
223
|
+
"@jskit-ai/resource-runtime": "0.2.40"
|
|
224
224
|
}
|
|
225
225
|
}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { isLostDuplicateInsertRace, toIsoString } from "@jskit-ai/database-runtime/shared";
|
|
2
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
3
|
import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
4
|
import { isSystemContext } from "@jskit-ai/resource-runtime/server";
|
|
5
|
+
import { ADMIN_ROLE_ID, OWNER_ROLE_ID } from "../../../shared/roles.js";
|
|
6
|
+
import { normalizeMembershipRecord } from "./workspaceMembershipsRepository.js";
|
|
4
7
|
|
|
5
8
|
function normalizeWorkspaceRecord(payload = null) {
|
|
6
9
|
if (!payload || typeof payload !== "object") {
|
|
@@ -36,7 +39,7 @@ function byId(left, right) {
|
|
|
36
39
|
* @param {object} dependencies
|
|
37
40
|
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} dependencies.workspaces The workspaces table's handle.
|
|
38
41
|
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} dependencies.workspaceMemberships
|
|
39
|
-
* The workspace_memberships table's handle, for a user's workspaces.
|
|
42
|
+
* The workspace_memberships table's handle, for a user's workspaces and the roles an ownership transfer changes.
|
|
40
43
|
*/
|
|
41
44
|
function createRepository({ workspaces, workspaceMemberships }) {
|
|
42
45
|
async function queryFirst(filters, options) {
|
|
@@ -265,6 +268,92 @@ function createRepository({ workspaces, workspaceMemberships }) {
|
|
|
265
268
|
return row ? { id: normalizeRecordId(row.id, { fallback: null }) } : null;
|
|
266
269
|
}
|
|
267
270
|
|
|
271
|
+
/**
|
|
272
|
+
* Hands a workspace to another of its active members, in the caller's transaction when `options` carries one (the
|
|
273
|
+
* txOptions of withTransaction), otherwise in one of its own. It locks the workspace's row first and reads the
|
|
274
|
+
* workspace through that lock, then locks the new and the previous owner's memberships, so two transfers of one
|
|
275
|
+
* workspace take turns and the second moves it on from the owner the first left. `owner_user_id` becomes `toUserId`
|
|
276
|
+
* and `updatedAt` moves; the new owner's membership takes the owner role; the previous owner's takes
|
|
277
|
+
* `previousOwnerRoleSid` (the admin role unless given) and stays active, or is created active with it when they had
|
|
278
|
+
* none. It sends the same statements however many members the workspace has.
|
|
279
|
+
*
|
|
280
|
+
* A personal workspace stops being personal: it was the one provisioned for its previous owner, and the new owner's
|
|
281
|
+
* own personal workspace stays theirs. Where the application provisions personal workspaces, the previous owner is
|
|
282
|
+
* given a new one at their next provisioning.
|
|
283
|
+
*
|
|
284
|
+
* A `toUserId` who already owns the workspace writes nothing and answers `changed: false`. A missing or deleted
|
|
285
|
+
* workspace is 404 `workspaces.workspace.notFound`, and a `toUserId` with no active membership (never a member,
|
|
286
|
+
* invited only, removed) is 409 `workspaces.member.newOwnerNotActive`; neither writes anything. Ids that are no
|
|
287
|
+
* record ids, and a `previousOwnerRoleSid` that is not the text of a role other than the owner's, are a TypeError
|
|
288
|
+
* before any statement. The role is stored lowercased as given: the role catalog is not checked here.
|
|
289
|
+
*
|
|
290
|
+
* It publishes no event: the `workspace.workspaces.create` and `workspace.workspaces.update` actions publish
|
|
291
|
+
* `entity.changed` on `runtime.events`, and this is no action. An application that keeps its own copy of workspace
|
|
292
|
+
* facts updates it from the answer.
|
|
293
|
+
* @param {{ workspaceId: unknown, toUserId: unknown, previousOwnerRoleSid?: string }} transfer
|
|
294
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
|
|
295
|
+
* @returns {Promise<{ id: string, slug: string, name: string, ownerUserId: string, isPersonal: boolean, avatarUrl: string,
|
|
296
|
+
* createdAt: string | null, updatedAt: string | null, deletedAt: string | null, previousOwnerUserId: string, changed: boolean }>}
|
|
297
|
+
* The workspace as findById answers it, the owner it had before the call, and whether the call changed it.
|
|
298
|
+
*/
|
|
299
|
+
async function transferOwnership({ workspaceId, toUserId, previousOwnerRoleSid = ADMIN_ROLE_ID }, options = {}) {
|
|
300
|
+
const id = normalizeRecordId(workspaceId, { fallback: null });
|
|
301
|
+
const newOwnerUserId = normalizeRecordId(toUserId, { fallback: null });
|
|
302
|
+
if (!id || !newOwnerUserId) {
|
|
303
|
+
throw new TypeError(
|
|
304
|
+
"workspaces.transferOwnership() requires workspaceId and toUserId, each a record id. " +
|
|
305
|
+
`Received: ${String(workspaceId)} and ${String(toUserId)}`
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
const previousOwnerRole = typeof previousOwnerRoleSid === "string" ? normalizeLowerText(previousOwnerRoleSid) : "";
|
|
309
|
+
if (!previousOwnerRole || previousOwnerRole === OWNER_ROLE_ID) {
|
|
310
|
+
throw new TypeError(
|
|
311
|
+
`workspaces.transferOwnership() previousOwnerRoleSid is the previous owner's new role: a role id other than "${OWNER_ROLE_ID}". ` +
|
|
312
|
+
`Received: ${String(previousOwnerRoleSid)}`
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return workspaces.withTransaction(options, async (txOptions) => {
|
|
317
|
+
// A locking read sees the row as last committed, where a plain read inside a caller's transaction on MySQL and
|
|
318
|
+
// MariaDB could see the snapshot of the caller's earlier read.
|
|
319
|
+
const workspace = normalizeWorkspaceRecord(await workspaces.lock(id, { ...txOptions, missing: "skip" }));
|
|
320
|
+
if (!workspace || workspace.deletedAt) {
|
|
321
|
+
throw new AppError(404, "Workspace not found.", { code: "workspaces.workspace.notFound" });
|
|
322
|
+
}
|
|
323
|
+
const previousOwnerUserId = workspace.ownerUserId;
|
|
324
|
+
if (previousOwnerUserId === newOwnerUserId) {
|
|
325
|
+
return { ...workspace, previousOwnerUserId, changed: false };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const memberships = (await workspaceMemberships.lockWhere(
|
|
329
|
+
{ workspace: id, users: [newOwnerUserId, previousOwnerUserId] },
|
|
330
|
+
txOptions
|
|
331
|
+
)).map(normalizeMembershipRecord);
|
|
332
|
+
const newOwner = memberships.find(({ userId }) => userId === newOwnerUserId);
|
|
333
|
+
if (newOwner?.status !== "active") {
|
|
334
|
+
throw new AppError(409, "The new owner must be an active member of the workspace.", {
|
|
335
|
+
code: "workspaces.member.newOwnerNotActive"
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
const previousOwner = memberships.find(({ userId }) => userId === previousOwnerUserId);
|
|
339
|
+
|
|
340
|
+
const transferred = await updateById(id, { ownerUserId: newOwnerUserId, isPersonal: false }, txOptions);
|
|
341
|
+
const changedAt = new Date().toISOString();
|
|
342
|
+
const write = { ...txOptions, returning: "none" };
|
|
343
|
+
await workspaceMemberships.patch(newOwner.id, { roleSid: OWNER_ROLE_ID, updatedAt: changedAt }, write);
|
|
344
|
+
const previousOwnerMembership = { roleSid: previousOwnerRole, status: "active", updatedAt: changedAt };
|
|
345
|
+
if (previousOwner) {
|
|
346
|
+
await workspaceMemberships.patch(previousOwner.id, previousOwnerMembership, write);
|
|
347
|
+
} else {
|
|
348
|
+
await workspaceMemberships.create(
|
|
349
|
+
{ ...previousOwnerMembership, workspaceId: id, userId: previousOwnerUserId, createdAt: changedAt },
|
|
350
|
+
write
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
return { ...transferred, previousOwnerUserId, changed: true };
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
268
357
|
return Object.freeze({
|
|
269
358
|
withTransaction: workspaces.withTransaction,
|
|
270
359
|
// The workspaces as a join source for another owner's report, which reads them in its own statement: the handle's
|
|
@@ -280,7 +369,8 @@ function createRepository({ workspaces, workspaceMemberships }) {
|
|
|
280
369
|
insert,
|
|
281
370
|
updateById,
|
|
282
371
|
listForUserId,
|
|
283
|
-
lock
|
|
372
|
+
lock,
|
|
373
|
+
transferOwnership
|
|
284
374
|
});
|
|
285
375
|
}
|
|
286
376
|
|
|
@@ -11,7 +11,8 @@ function workspaceAssistantSummary({ id, slug, name, ownerUserId, avatarUrl }) {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
// A workspace made or changed (its name, its avatar) is an entity change of the workspace itself, for the application's
|
|
14
|
-
// listeners on runtime.events; the workspace's id is the action's answer's.
|
|
14
|
+
// listeners on runtime.events; the workspace's id is the action's answer's. The `workspaces` capability's
|
|
15
|
+
// transferOwnership is no action and publishes nothing: its caller updates its own copy of workspace facts from its answer.
|
|
15
16
|
const workspaceChanged = (operation) => Object.freeze([createEntityChangedActionEvent({
|
|
16
17
|
source: "workspace",
|
|
17
18
|
entity: "workspace",
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
4
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
5
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
6
|
+
import { expectFlatQueries, startTestFeatures } from "@jskit-ai/resource-runtime/test";
|
|
7
|
+
import { UsersExtensionsProvider } from "@jskit-ai/users-core/server/UsersExtensionsProvider";
|
|
8
|
+
import { UsersIdentityProvider } from "@jskit-ai/users-core/server/UsersIdentityProvider";
|
|
9
|
+
import usersInitial from "../../../users-core/migrations/users_core_generic_initial.cjs";
|
|
10
|
+
import usersUsername from "../../../users-core/migrations/users_core_profile_username.cjs";
|
|
11
|
+
import usersUpdatedAt from "../../../users-core/migrations/users_core_profile_updated_at.cjs";
|
|
12
|
+
import workspacesInitial from "../../migrations/workspaces_core_initial.cjs";
|
|
13
|
+
import workspaceSettingsMigration from "../../migrations/workspaces_core_workspace_settings_single_name_source.cjs";
|
|
14
|
+
import workspaceColorMigration from "../../migrations/workspaces_core_workspaces_drop_color.cjs";
|
|
15
|
+
import { WORKSPACES_TABLES, createWorkspaceRecords } from "../../src/server/workspacesRuntime.js";
|
|
16
|
+
import { createRepository as createInvitesRepository } from "../../src/server/common/repositories/workspaceInvitesRepository.js";
|
|
17
|
+
import { buildWorkspaceName, createService as createDirectoryService } from "../../src/server/common/services/workspaceDirectoryService.js";
|
|
18
|
+
import { noWorkspaceCreatedParticipant } from "../../src/server/workspaceDirectory/noWorkspaceCreatedParticipant.js";
|
|
19
|
+
import { createRepository as createSettingsRepository } from "../../src/server/workspaceSettings/workspaceSettingsRepository.js";
|
|
20
|
+
import { createWorkspaceRoleCatalog } from "../../src/shared/roles.js";
|
|
21
|
+
import { resolveTenancyProfile } from "../../src/shared/tenancyProfile.js";
|
|
22
|
+
|
|
23
|
+
// workspaces.transferOwnership on the migrated users and workspaces tables: the moves it makes, what it refuses with
|
|
24
|
+
// nothing changed, the caller's transaction, two transfers at once and its statements among few and many members.
|
|
25
|
+
|
|
26
|
+
const MIGRATIONS = [usersInitial, usersUsername, usersUpdatedAt, workspacesInitial, workspaceSettingsMigration, workspaceColorMigration];
|
|
27
|
+
const NOT_ACTIVE = "workspaces.member.newOwnerNotActive";
|
|
28
|
+
const NOT_FOUND = "workspaces.workspace.notFound";
|
|
29
|
+
// expectFlatQueries() runs only against a test database, which TEST_DB_NAME names: SQLite's in-memory one is one.
|
|
30
|
+
const IN_MEMORY_TEST_DATABASE = Object.freeze({ TEST_DB_NAME: "transfer_ownership" });
|
|
31
|
+
// Statements that change rows. SQLite has no row lock: a lock there is an update that matches no row (`where 0 = 1`),
|
|
32
|
+
// sent for the database's write lock, so it changes nothing.
|
|
33
|
+
const WRITE = /^\s*(?:insert|update|delete)\b(?![\s\S]*\bwhere 0 = 1$)/iu;
|
|
34
|
+
|
|
35
|
+
// The run's result and the statements it sent.
|
|
36
|
+
async function statementsOf(knex, run) {
|
|
37
|
+
const sql = [];
|
|
38
|
+
const listener = (query) => sql.push(String(query?.sql || ""));
|
|
39
|
+
knex.on("query", listener);
|
|
40
|
+
try {
|
|
41
|
+
const result = await run();
|
|
42
|
+
return { result, statements: sql.length, sql };
|
|
43
|
+
} finally {
|
|
44
|
+
knex.removeListener("query", listener);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The id of the database connection a transaction runs on.
|
|
49
|
+
async function connectionId(dialect, trx) {
|
|
50
|
+
if (dialect === "postgres") return (await trx.raw("SELECT pg_backend_pid() AS id")).rows[0].id;
|
|
51
|
+
return (await trx.raw("SELECT CONNECTION_ID() AS id"))[0][0].id;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Resolves once the connection waits for a lock: on PostgreSQL its wait event says so; on MariaDB/MySQL, whose test
|
|
55
|
+
// user sees its own connections in the process list without the PROCESS privilege, a statement running for a second.
|
|
56
|
+
async function untilWaiting(knex, dialect, id) {
|
|
57
|
+
const deadline = Date.now() + 10_000;
|
|
58
|
+
while (Date.now() < deadline) {
|
|
59
|
+
const waiting = dialect === "postgres"
|
|
60
|
+
? (await knex.raw("SELECT count(*)::int AS n FROM pg_stat_activity WHERE pid = ? AND wait_event_type = 'Lock'", [id])).rows[0].n
|
|
61
|
+
: (await knex.raw(
|
|
62
|
+
"SELECT COUNT(*) AS n FROM information_schema.PROCESSLIST WHERE ID = ? AND COMMAND = 'Query' AND TIME >= 1",
|
|
63
|
+
[id]
|
|
64
|
+
))[0][0].n;
|
|
65
|
+
if (Number(waiting) > 0) return;
|
|
66
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
67
|
+
}
|
|
68
|
+
throw new Error(`Connection ${id} waited for no lock within 10 s.`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function refusedWith(status, code) {
|
|
72
|
+
return (error) => {
|
|
73
|
+
assert.ok(error instanceof AppError, error?.stack);
|
|
74
|
+
assert.deepEqual([error.status, error.code], [status, code]);
|
|
75
|
+
return true;
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Registers workspaces.transferOwnership's tests on the empty database `open(t)` answers.
|
|
81
|
+
* @param {(t: import("node:test").TestContext) => Promise<import("knex").Knex>} open
|
|
82
|
+
* @param {{ dialect: "sqlite" | "postgres" | "mysql", database?: boolean, skip?: string | false }} options
|
|
83
|
+
*/
|
|
84
|
+
function transferOwnershipCases(open, { dialect, database = true, skip = false }) {
|
|
85
|
+
const native = dialect !== "sqlite";
|
|
86
|
+
|
|
87
|
+
test(`workspaces.transferOwnership (${dialect})`, { skip }, async (t) => {
|
|
88
|
+
if (database) requireTestDatabase(process.env);
|
|
89
|
+
const knex = await open(t);
|
|
90
|
+
if (!native) await knex.raw("PRAGMA foreign_keys = ON");
|
|
91
|
+
for (const migration of MIGRATIONS) await migration.up(knex);
|
|
92
|
+
const started = await startTestFeatures({
|
|
93
|
+
knex,
|
|
94
|
+
logger: silentLogger,
|
|
95
|
+
features: [UsersExtensionsProvider, UsersIdentityProvider],
|
|
96
|
+
requires: { profiles: "users.profiles" }
|
|
97
|
+
});
|
|
98
|
+
t.after(started.stop);
|
|
99
|
+
const { profiles } = started.capabilities;
|
|
100
|
+
const resources = await started.resources.own("workspaces.core", WORKSPACES_TABLES);
|
|
101
|
+
const { workspaces, memberships } = createWorkspaceRecords(resources);
|
|
102
|
+
const invites = createInvitesRepository({ workspaceInvites: resources.workspaceInvites, workspaces });
|
|
103
|
+
const settings = createSettingsRepository({
|
|
104
|
+
workspaceSettings: resources.workspaceSettings, defaultInvitesEnabled: true, defaultColorSettings: {}
|
|
105
|
+
});
|
|
106
|
+
const transfer = (input, options) => workspaces.transferOwnership(input, options);
|
|
107
|
+
|
|
108
|
+
let sequence = 0;
|
|
109
|
+
const person = (name) => profiles.upsert({
|
|
110
|
+
authProvider: "local", authProviderUserSid: `transfer-${name}`, email: `${name}@example.test`, displayName: name
|
|
111
|
+
});
|
|
112
|
+
// A workspace owned by `owner`, with its owner membership unless `ownerMembership` is false, and `members` active.
|
|
113
|
+
async function team(owner, members = [], { ownerMembership = true, isPersonal = false } = {}) {
|
|
114
|
+
sequence += 1;
|
|
115
|
+
const workspace = await workspaces.insert({ slug: `team-${sequence}`, name: `Team ${sequence}`, ownerUserId: owner.id, isPersonal });
|
|
116
|
+
if (ownerMembership) await memberships.ensureOwnerMembership(workspace.id, owner.id);
|
|
117
|
+
for (const member of members) await memberships.addMember({ workspaceId: workspace.id, userId: member.id });
|
|
118
|
+
return workspace;
|
|
119
|
+
}
|
|
120
|
+
// The workspace's row and its memberships' rows as stored.
|
|
121
|
+
const stored = async (workspaceId) => JSON.stringify({
|
|
122
|
+
workspace: await knex("workspaces").where({ id: workspaceId }).first(),
|
|
123
|
+
memberships: await knex("workspace_memberships").where({ workspace_id: workspaceId }).orderBy("id")
|
|
124
|
+
});
|
|
125
|
+
// Each membership's [user, role, status], by user id.
|
|
126
|
+
const rolesOf = async (workspaceId) => (await knex("workspace_memberships").where({ workspace_id: workspaceId }).orderBy("user_id"))
|
|
127
|
+
.map((row) => [String(row.user_id), row.role_sid, row.status]);
|
|
128
|
+
const byUser = (rows) => [...rows].sort(([left], [right]) => Number(left) - Number(right));
|
|
129
|
+
const ownerRows = async (workspaceId) => knex("workspace_memberships").where({ workspace_id: workspaceId, role_sid: "owner" });
|
|
130
|
+
|
|
131
|
+
await t.test("a transfer makes the member the owner and the previous owner an active admin, and moves updatedAt", async () => {
|
|
132
|
+
const ada = await person("ada-1");
|
|
133
|
+
const grace = await person("grace-1");
|
|
134
|
+
const workspace = await team(ada, [grace]);
|
|
135
|
+
await knex("workspaces").where({ id: workspace.id }).update({ updated_at: "2001-02-03 04:05:06" });
|
|
136
|
+
|
|
137
|
+
const answer = await transfer({ workspaceId: workspace.id, toUserId: grace.id });
|
|
138
|
+
|
|
139
|
+
const { previousOwnerUserId, changed, ...moved } = answer;
|
|
140
|
+
assert.deepEqual({ previousOwnerUserId, changed }, { previousOwnerUserId: ada.id, changed: true });
|
|
141
|
+
assert.deepEqual(moved, await workspaces.findById(workspace.id), "The workspace as findById answers it");
|
|
142
|
+
assert.equal(moved.ownerUserId, grace.id);
|
|
143
|
+
assert.ok(moved.updatedAt > "2001-02-03T04:05:06.000Z", `updatedAt moved: ${moved.updatedAt}`);
|
|
144
|
+
assert.deepEqual(await rolesOf(workspace.id), byUser([[ada.id, "admin", "active"], [grace.id, "owner", "active"]]));
|
|
145
|
+
assert.deepEqual((await memberships.listActiveByWorkspaceId(workspace.id)).map(({ userId }) => userId).sort(), [ada.id, grace.id].sort());
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
await t.test("the previous owner takes previousOwnerRoleSid, and is made an active member when they had no active membership", async () => {
|
|
149
|
+
const ada = await person("ada-2");
|
|
150
|
+
const grace = await person("grace-2");
|
|
151
|
+
const named = await team(ada, [grace]);
|
|
152
|
+
assert.equal((await transfer({ workspaceId: named.id, toUserId: grace.id, previousOwnerRoleSid: " Member " })).changed, true);
|
|
153
|
+
assert.deepEqual(await rolesOf(named.id), byUser([[ada.id, "member", "active"], [grace.id, "owner", "active"]]));
|
|
154
|
+
|
|
155
|
+
const unjoined = await team(ada, [grace], { ownerMembership: false });
|
|
156
|
+
await transfer({ workspaceId: unjoined.id, toUserId: grace.id });
|
|
157
|
+
assert.deepEqual(await rolesOf(unjoined.id), byUser([[ada.id, "admin", "active"], [grace.id, "owner", "active"]]));
|
|
158
|
+
|
|
159
|
+
const removed = await team(ada, [grace]);
|
|
160
|
+
await memberships.upsertMembership(removed.id, ada.id, { status: "revoked" });
|
|
161
|
+
await transfer({ workspaceId: removed.id, toUserId: grace.id });
|
|
162
|
+
assert.deepEqual(await rolesOf(removed.id), byUser([[ada.id, "admin", "active"], [grace.id, "owner", "active"]]));
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
await t.test("no active member, a missing workspace and a deleted one are refused, and nothing changes", async () => {
|
|
166
|
+
const ada = await person("ada-3");
|
|
167
|
+
const workspace = await team(ada);
|
|
168
|
+
const stranger = await person("stranger-3");
|
|
169
|
+
const invited = await person("invited-3");
|
|
170
|
+
await invites.insert({ workspaceId: workspace.id, email: invited.email, tokenHash: "transfer-invited-3" });
|
|
171
|
+
const pending = await person("pending-3");
|
|
172
|
+
await memberships.upsertMembership(workspace.id, pending.id, { roleSid: "member", status: "pending" });
|
|
173
|
+
const removed = await person("removed-3");
|
|
174
|
+
await memberships.addMember({ workspaceId: workspace.id, userId: removed.id });
|
|
175
|
+
await memberships.upsertMembership(workspace.id, removed.id, { status: "revoked" });
|
|
176
|
+
const before = await stored(workspace.id);
|
|
177
|
+
for (const candidate of [stranger, invited, pending, removed]) {
|
|
178
|
+
const { sql } = await statementsOf(knex, () => assert.rejects(
|
|
179
|
+
transfer({ workspaceId: workspace.id, toUserId: candidate.id }),
|
|
180
|
+
refusedWith(409, NOT_ACTIVE)
|
|
181
|
+
));
|
|
182
|
+
assert.deepEqual(sql.filter((statement) => WRITE.test(statement)), [], `${candidate.displayName} wrote nothing`);
|
|
183
|
+
assert.equal(await stored(workspace.id), before, `${candidate.displayName} changed nothing`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const grace = await person("grace-3");
|
|
187
|
+
const deleted = await team(ada, [grace]);
|
|
188
|
+
await workspaces.updateById(deleted.id, { deletedAt: new Date().toISOString() });
|
|
189
|
+
const deletedBefore = await stored(deleted.id);
|
|
190
|
+
await assert.rejects(transfer({ workspaceId: deleted.id, toUserId: grace.id }), refusedWith(404, NOT_FOUND));
|
|
191
|
+
assert.equal(await stored(deleted.id), deletedBefore);
|
|
192
|
+
const counts = async () => Promise.all(["workspaces", "workspace_memberships"].map(async (table) => Number((await knex(table).count({ n: "*" }).first()).n)));
|
|
193
|
+
const countsBefore = await counts();
|
|
194
|
+
await assert.rejects(transfer({ workspaceId: "999999999", toUserId: grace.id }), refusedWith(404, NOT_FOUND));
|
|
195
|
+
assert.deepEqual(await counts(), countsBefore);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
await t.test("the owner as toUserId writes nothing and answers changed: false", async () => {
|
|
199
|
+
const ada = await person("ada-4");
|
|
200
|
+
const workspace = await team(ada, [await person("grace-4")]);
|
|
201
|
+
const before = await stored(workspace.id);
|
|
202
|
+
const { result, sql } = await statementsOf(knex, () => transfer({ workspaceId: workspace.id, toUserId: ada.id }));
|
|
203
|
+
assert.deepEqual(result, { ...(await workspaces.findById(workspace.id)), previousOwnerUserId: ada.id, changed: false });
|
|
204
|
+
assert.deepEqual(sql.filter((statement) => WRITE.test(statement)), []);
|
|
205
|
+
assert.equal(await stored(workspace.id), before);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
await t.test("a personal workspace stops being personal: the new owner keeps their own, the previous owner is provisioned a new one", async () => {
|
|
209
|
+
const directory = createDirectoryService({
|
|
210
|
+
tenancyProfile: resolveTenancyProfile({ tenancyMode: "personal" }),
|
|
211
|
+
roleCatalog: createWorkspaceRoleCatalog(),
|
|
212
|
+
personalWorkspaceName: buildWorkspaceName,
|
|
213
|
+
createdParticipant: noWorkspaceCreatedParticipant,
|
|
214
|
+
workspacesRepository: workspaces,
|
|
215
|
+
workspaceMembershipsRepository: memberships,
|
|
216
|
+
workspaceSettingsRepository: settings
|
|
217
|
+
});
|
|
218
|
+
const ada = await person("ada-5");
|
|
219
|
+
const grace = await person("grace-5");
|
|
220
|
+
const adas = await directory.ensureProvisionedWorkspaceForAuthenticatedUser(ada);
|
|
221
|
+
const graces = await directory.ensureProvisionedWorkspaceForAuthenticatedUser(grace);
|
|
222
|
+
assert.equal(adas.isPersonal, true);
|
|
223
|
+
await memberships.addMember({ workspaceId: adas.id, userId: grace.id });
|
|
224
|
+
|
|
225
|
+
const answer = await transfer({ workspaceId: adas.id, toUserId: grace.id });
|
|
226
|
+
|
|
227
|
+
assert.deepEqual([answer.ownerUserId, answer.isPersonal], [grace.id, false]);
|
|
228
|
+
assert.equal((await workspaces.findById(adas.id)).isPersonal, false);
|
|
229
|
+
assert.equal((await workspaces.findPersonalByOwnerUserId(grace.id)).id, graces.id, "The new owner's own personal workspace stays theirs");
|
|
230
|
+
assert.equal(await workspaces.findPersonalByOwnerUserId(ada.id), null);
|
|
231
|
+
assert.equal((await directory.ensureProvisionedWorkspaceForAuthenticatedUser(grace)).id, graces.id);
|
|
232
|
+
const fresh = await directory.ensureProvisionedWorkspaceForAuthenticatedUser(ada);
|
|
233
|
+
assert.notEqual(fresh.id, adas.id);
|
|
234
|
+
assert.deepEqual([fresh.ownerUserId, fresh.isPersonal], [ada.id, true]);
|
|
235
|
+
assert.deepEqual(
|
|
236
|
+
(await workspaces.listForUserId(ada.id)).map(({ id, roleSid }) => [id, roleSid]),
|
|
237
|
+
[[fresh.id, "owner"], [adas.id, "admin"]]
|
|
238
|
+
);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
await t.test("in the caller's transaction it sees the caller's work and rolls back with it", async () => {
|
|
242
|
+
const ada = await person("ada-6");
|
|
243
|
+
const grace = await person("grace-6");
|
|
244
|
+
const workspace = await team(ada, [grace], { isPersonal: true });
|
|
245
|
+
const hal = await person("hal-6");
|
|
246
|
+
const before = await stored(workspace.id);
|
|
247
|
+
await assert.rejects(workspaces.withTransaction({}, async (txOptions) => {
|
|
248
|
+
await memberships.addMember({ workspaceId: workspace.id, userId: hal.id }, txOptions);
|
|
249
|
+
assert.equal((await transfer({ workspaceId: workspace.id, toUserId: hal.id }, txOptions)).changed, true);
|
|
250
|
+
assert.equal((await workspaces.findById(workspace.id, txOptions)).ownerUserId, hal.id);
|
|
251
|
+
throw new Error("Abort the caller's transaction");
|
|
252
|
+
}), /Abort the caller's transaction/u);
|
|
253
|
+
assert.equal(await stored(workspace.id), before);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
await t.test("in a caller's transaction that read the workspace first, it moves it on from the owner last committed", { skip: native ? false : "SQLite runs one transaction at a time" }, async () => {
|
|
257
|
+
const ada = await person("ada-7");
|
|
258
|
+
const grace = await person("grace-7");
|
|
259
|
+
const hal = await person("hal-7");
|
|
260
|
+
const workspace = await team(ada, [grace, hal]);
|
|
261
|
+
const moved = await workspaces.withTransaction({}, async (txOptions) => {
|
|
262
|
+
// On MariaDB/MySQL this plain read fixes the transaction's snapshot.
|
|
263
|
+
assert.equal((await workspaces.findById(workspace.id, txOptions)).ownerUserId, ada.id);
|
|
264
|
+
await transfer({ workspaceId: workspace.id, toUserId: grace.id });
|
|
265
|
+
return transfer({ workspaceId: workspace.id, toUserId: hal.id }, txOptions);
|
|
266
|
+
});
|
|
267
|
+
assert.deepEqual([moved.previousOwnerUserId, moved.ownerUserId], [grace.id, hal.id]);
|
|
268
|
+
assert.deepEqual(await rolesOf(workspace.id), byUser([[ada.id, "admin", "active"], [grace.id, "admin", "active"], [hal.id, "owner", "active"]]));
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
await t.test("two transfers of one workspace at once end with one owner and one owner membership", async () => {
|
|
272
|
+
const ada = await person("ada-8");
|
|
273
|
+
const grace = await person("grace-8");
|
|
274
|
+
const hal = await person("hal-8");
|
|
275
|
+
const workspace = await team(ada, [grace, hal]);
|
|
276
|
+
let first;
|
|
277
|
+
let second;
|
|
278
|
+
if (native) {
|
|
279
|
+
// The first holds its transaction open after its transfer until the second waits for a lock.
|
|
280
|
+
const held = Promise.withResolvers();
|
|
281
|
+
const release = Promise.withResolvers();
|
|
282
|
+
const waiter = Promise.withResolvers();
|
|
283
|
+
const firstRun = workspaces.withTransaction({}, async (txOptions) => {
|
|
284
|
+
const answer = await transfer({ workspaceId: workspace.id, toUserId: grace.id }, txOptions);
|
|
285
|
+
held.resolve();
|
|
286
|
+
await release.promise;
|
|
287
|
+
return answer;
|
|
288
|
+
});
|
|
289
|
+
firstRun.catch(() => held.resolve());
|
|
290
|
+
await held.promise;
|
|
291
|
+
const secondRun = workspaces.withTransaction({}, async (txOptions) => {
|
|
292
|
+
waiter.resolve(await connectionId(dialect, txOptions.trx));
|
|
293
|
+
return transfer({ workspaceId: workspace.id, toUserId: hal.id }, txOptions);
|
|
294
|
+
});
|
|
295
|
+
secondRun.catch(() => {});
|
|
296
|
+
try {
|
|
297
|
+
await untilWaiting(knex, dialect, await waiter.promise);
|
|
298
|
+
} finally {
|
|
299
|
+
release.resolve();
|
|
300
|
+
}
|
|
301
|
+
[first, second] = await Promise.all([firstRun, secondRun]);
|
|
302
|
+
} else {
|
|
303
|
+
[first, second] = await Promise.all([
|
|
304
|
+
transfer({ workspaceId: workspace.id, toUserId: grace.id }),
|
|
305
|
+
transfer({ workspaceId: workspace.id, toUserId: hal.id })
|
|
306
|
+
]);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
assert.deepEqual([first.changed, first.previousOwnerUserId], [true, ada.id]);
|
|
310
|
+
assert.deepEqual([second.changed, second.previousOwnerUserId], [true, grace.id], "The second moves it on from the owner the first left");
|
|
311
|
+
assert.equal((await workspaces.findById(workspace.id)).ownerUserId, hal.id);
|
|
312
|
+
assert.deepEqual((await ownerRows(workspace.id)).map((row) => String(row.user_id)), [hal.id], "Exactly one owner membership, the owner's");
|
|
313
|
+
assert.deepEqual(await rolesOf(workspace.id), byUser([[ada.id, "admin", "active"], [grace.id, "admin", "active"], [hal.id, "owner", "active"]]));
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
await t.test("ids that are no record ids and a previousOwnerRoleSid that is no role but the owner's are a TypeError before any statement", async () => {
|
|
317
|
+
const ada = await person("ada-9");
|
|
318
|
+
const grace = await person("grace-9");
|
|
319
|
+
const workspace = await team(ada, [grace]);
|
|
320
|
+
const refusals = [
|
|
321
|
+
...["", "abc", "0", null, undefined, {}].map((workspaceId) => [{ workspaceId, toUserId: grace.id }, /requires workspaceId and toUserId/u]),
|
|
322
|
+
...["", "-1", null, undefined].map((toUserId) => [{ workspaceId: workspace.id, toUserId }, /requires workspaceId and toUserId/u]),
|
|
323
|
+
...["", " ", "owner", " OWNER ", null, 7, {}].map((previousOwnerRoleSid) => [
|
|
324
|
+
{ workspaceId: workspace.id, toUserId: grace.id, previousOwnerRoleSid }, /previousOwnerRoleSid is the previous owner's new role/u
|
|
325
|
+
])
|
|
326
|
+
];
|
|
327
|
+
for (const [input, message] of refusals) {
|
|
328
|
+
const { statements, sql } = await statementsOf(knex, () => assert.rejects(transfer(input), (error) => {
|
|
329
|
+
assert.equal(error.name, "TypeError", `${JSON.stringify(input)}: ${error.stack}`);
|
|
330
|
+
assert.match(error.message, message);
|
|
331
|
+
return true;
|
|
332
|
+
}));
|
|
333
|
+
assert.equal(statements, 0, `${JSON.stringify(input)} sent ${sql.join(" | ")}`);
|
|
334
|
+
}
|
|
335
|
+
assert.equal((await workspaces.findById(workspace.id)).ownerUserId, ada.id);
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
await t.test("a transfer's statements do not grow with the workspace's members", async (st) => {
|
|
339
|
+
const owner = await person("owner-10");
|
|
340
|
+
await knex.batchInsert("users", Array.from({ length: 200 }, (_, index) => ({
|
|
341
|
+
auth_provider: "local",
|
|
342
|
+
auth_provider_user_sid: `transfer-crowd-${index}`,
|
|
343
|
+
email: `crowd-${index}@example.test`,
|
|
344
|
+
username: `transfer-crowd-${index}`,
|
|
345
|
+
display_name: `Crowd ${index}`
|
|
346
|
+
})), 100);
|
|
347
|
+
const crowd = (await knex("users").where("username", "like", "transfer-crowd-%").orderBy("id").select("id"))
|
|
348
|
+
.map(({ id }) => String(id));
|
|
349
|
+
// MariaDB and MySQL read a table's indexes once per process and set of filtered columns: not this measure.
|
|
350
|
+
await transfer({ workspaceId: (await team(owner, [{ id: crowd[0] }])).id, toUserId: crowd[0] });
|
|
351
|
+
|
|
352
|
+
const moved = [];
|
|
353
|
+
const counts = await expectFlatQueries({
|
|
354
|
+
environment: database ? process.env : IN_MEMORY_TEST_DATABASE,
|
|
355
|
+
knex,
|
|
356
|
+
sizes: [2, 200],
|
|
357
|
+
// A workspace of its own for each size, whose owner has that many active members besides themselves.
|
|
358
|
+
seed: async (size) => {
|
|
359
|
+
const workspace = await team(owner);
|
|
360
|
+
await knex.batchInsert("workspace_memberships", crowd.slice(0, size).map((id) => ({
|
|
361
|
+
workspace_id: workspace.id, user_id: id, role_sid: "member", status: "active"
|
|
362
|
+
})), 100);
|
|
363
|
+
return { workspace, toUserId: crowd[size - 1] };
|
|
364
|
+
},
|
|
365
|
+
run: async ({ workspace, toUserId }) => moved.push(await transfer({ workspaceId: workspace.id, toUserId }))
|
|
366
|
+
});
|
|
367
|
+
st.diagnostic(`transferOwnership statements: ${counts.map(({ size, count }) => `${count} among ${size} members`).join(", ")}`);
|
|
368
|
+
assert.deepEqual(moved.map(({ ownerUserId, changed }) => [ownerUserId, changed]), [[crowd[1], true], [crowd[199], true]]);
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export { transferOwnershipCases };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { openMysql } from "./support/indexesByUserCases.js";
|
|
2
|
+
import { transferOwnershipCases } from "./support/transferOwnershipCases.js";
|
|
3
|
+
|
|
4
|
+
// workspaces.transferOwnership on MariaDB/MySQL, where two transfers at once wait for each other's row locks.
|
|
5
|
+
transferOwnershipCases(openMysql("ws_transfer"), { dialect: "mysql" });
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { POSTGRES_ELSEWHERE, openPostgres } from "./support/indexesByUserCases.js";
|
|
2
|
+
import { transferOwnershipCases } from "./support/transferOwnershipCases.js";
|
|
3
|
+
|
|
4
|
+
// workspaces.transferOwnership on PostgreSQL, where two transfers at once wait for each other's row locks.
|
|
5
|
+
transferOwnershipCases(openPostgres("ws_transfer"), { dialect: "postgres", skip: POSTGRES_ELSEWHERE });
|