Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Check the acting administrator again where roles change
Claude4e6223ef11c1
diff --git a/src/app/api/admin/people/[id]/route.ts b/src/app/api/admin/people/[id]/route.tsindex 6087c43..f16afab 100644--- a/src/app/api/admin/people/[id]/route.ts+++ b/src/app/api/admin/people/[id]/route.ts@@ -63,7 +63,7 @@ export async function PATCH(request: Request, context: PersonRouteContext) {}try {- const person = await setPersonRole(id, role);+ const person = await setPersonRole(session.user.id, id, role);logSecurityEvent("info", {category: "people_role_changed",diff --git a/src/components/settings/people-panel.tsx b/src/components/settings/people-panel.tsxindex c234691..ff8edc4 100644--- a/src/components/settings/people-panel.tsx+++ b/src/components/settings/people-panel.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import type { PeopleList, Person, PersonRole } from "@/lib/people";@@ -42,6 +42,14 @@ export function PeoplePanel() {const [filter, setFilter] = useState("");// What the list on screen was asked for: `filter`, once typing has paused.const [search, setSearch] = useState("");+ // Counts up to have the list asked for again with the same search.+ const [reloads, setReloads] = useState(0);+ // The search as it stands now, for an answer that arrives after it moved.+ const latestSearch = useRef(search);++ useEffect(() => {+ latestSearch.current = search;+ }, [search]);useEffect(() => {const timer = window.setTimeout(@@ -84,7 +92,7 @@ export function PeoplePanel() {});return () => controller.abort();- }, [search]);+ }, [search, reloads]);async function changeRole(person: Person, role: PersonRole) {if (pendingId) {@@ -119,6 +127,13 @@ export function PeoplePanel() {return;}+ // The search moved on while this was being saved. The list that came+ // back answers the old one, so the list is asked for again.+ if (latestSearch.current !== search) {+ setReloads((count) => count + 1);+ return;+ }+setList(changed);} catch {setError(GENERIC_ERROR_MESSAGE);diff --git a/src/lib/people.dbtest.ts b/src/lib/people.dbtest.tsindex 0f8dc9e..216c1d2 100644--- a/src/lib/people.dbtest.ts+++ b/src/lib/people.dbtest.ts@@ -71,6 +71,27 @@ async function resetRoles() {);}+/** Waits until this many sessions are held up behind a lock. */+async function waitForLockWaiters(count: number) {+ for (let attempt = 0; attempt < 300; attempt += 1) {+ const result = await database.query<{ waiting: number }>(+ `+ select count(*)::int as waiting+ from pg_stat_activity+ where datname = current_database() and wait_event_type = 'Lock'+ `,+ );++ if ((result.rows[0]?.waiting ?? 0) >= count) {+ return;+ }++ await new Promise((resolve) => setTimeout(resolve, 10));+ }++ throw new Error(`Expected ${count} sessions to be waiting behind a lock.`);+}+function refusedWith(statusCode: number, pattern: RegExp) {return (error: unknown) => {assert.ok(error instanceof PeopleError);@@ -87,18 +108,34 @@ test("an administrator can be added and removed, but never the last one", asyncconst second = await createUser();await assert.rejects(- setPersonRole(first, "user", database),+ setPersonRole(first, first, "user", database),refusedWith(409, /at least one administrator/),);assert.equal(await roleOf(first), "admin");- assert.equal((await setPersonRole(second, "admin", database)).role, "admin");- assert.equal((await setPersonRole(first, "user", database)).role, "user");+ assert.equal(+ (await setPersonRole(first, second, "admin", database)).role,+ "admin",+ );+ assert.equal(+ (await setPersonRole(first, first, "user", database)).role,+ "user",+ );assert.equal(await roleOf(first), "user");assert.equal(await roleOf(second), "admin");// Asking for the role an account already has changes nothing.- assert.equal((await setPersonRole(second, "admin", database)).role, "admin");+ assert.equal(+ (await setPersonRole(second, second, "admin", database)).role,+ "admin",+ );++ // Having given the role up, the first account can no longer hand it out.+ await assert.rejects(+ setPersonRole(first, first, "admin", database),+ refusedWith(403, /Only an administrator/),+ );+ assert.equal(await roleOf(first), "user");const listed = await listPeople({}, database);const mine = listed.people.filter((person) =>@@ -116,8 +153,8 @@ test("two administrators removing each other at once leaves one", async () => {const left = await createUser({ role: "admin" });const right = await createUser({ role: "admin" });const results = await Promise.allSettled([- setPersonRole(left, "user", database),- setPersonRole(right, "user", database),+ setPersonRole(right, left, "user", database),+ setPersonRole(left, right, "user", database),]);assert.deepEqual(results.map((result) => result.status).sort(), [@@ -130,6 +167,45 @@ test("two administrators removing each other at once leaves one", async () => {]);});+test("a request already under way does not outlive its administrator's role", async () => {+ await resetRoles();++ const staying = await createUser({ role: "admin" });+ const removed = await createUser({ role: "admin" });+ const holder = await database.connect();++ try {+ // Holds the removal up at the account it is about to change, which is+ // after it has taken its turn among role changes.+ await holder.query("begin");+ await holder.query(`select 1 from public."user" where id = $1 for update`, [+ removed,+ ]);++ const removal = setPersonRole(staying, removed, "user", database);++ removal.catch(() => undefined);+ await waitForLockWaiters(1);++ // Sent while still an administrator, as the route had checked. It now+ // waits its turn behind the removal.+ const late = setPersonRole(removed, removed, "admin", database);++ late.catch(() => undefined);+ await waitForLockWaiters(2);+ await holder.query("commit");++ assert.equal((await removal).role, "user");+ await assert.rejects(late, refusedWith(403, /Only an administrator/));+ } finally {+ await holder.query("rollback").catch(() => undefined);+ holder.release();+ }++ assert.equal(await roleOf(removed), "user");+ assert.equal(await roleOf(staying), "admin");+});+test("an administrator whose account is closing does not count as the one that stays", async () => {await resetRoles();@@ -146,7 +222,7 @@ test("an administrator whose account is closing does not count as the one that s);await assert.rejects(- setPersonRole(staying, "user", database),+ setPersonRole(staying, staying, "user", database),refusedWith(409, /at least one administrator/),);@@ -159,7 +235,8 @@ test("an administrator whose account is closing does not count as the one that stest("only a confirmed account that is staying can become an administrator", async () => {await resetRoles();- await createUser({ role: "admin" });++ const administrator = await createUser({ role: "admin" });const unverified = await createUser({ verified: false });const closing = await createUser();@@ -174,15 +251,15 @@ test("only a confirmed account that is staying can become an administrator", asy);await assert.rejects(- setPersonRole(unverified, "admin", database),+ setPersonRole(administrator, unverified, "admin", database),refusedWith(409, /not confirmed their email/),);await assert.rejects(- setPersonRole(closing, "admin", database),+ setPersonRole(administrator, closing, "admin", database),refusedWith(409, /being closed/),);await assert.rejects(- setPersonRole(randomUUID(), "admin", database),+ setPersonRole(administrator, randomUUID(), "admin", database),refusedWith(404, /no longer exists/),);});@@ -254,5 +331,8 @@ test("an account past the end of the list can still be found and made an adminis(await listPeople({ search: "nobody at all" }, database)).total,0,);- assert.equal((await setPersonRole(last, "admin", database)).role, "admin");+ assert.equal(+ (await setPersonRole(administrator, last, "admin", database)).role,+ "admin",+ );});diff --git a/src/lib/people.ts b/src/lib/people.tsindex 404f106..535cfdb 100644--- a/src/lib/people.ts+++ b/src/lib/people.ts@@ -137,10 +137,18 @@ export function parsePersonRole(value: unknown): PersonRole | null {}/**- * Makes an account an administrator, or an ordinary account again.- * Returns the account as it now is.+ * Makes an account an administrator, or an ordinary account again, for the+ * administrator `actingUserId`. Returns the account as it now is.+ *+ * Whoever calls this has already checked that the acting account is an+ * administrator, but that was before this waited its turn. Another+ * administrator may have taken the role away in the meantime, so it is+ * looked at again here, where no role can change underneath it. Without+ * that, a request already under way would let someone who has just been+ * removed put themselves back.*/export async function setPersonRole(+ actingUserId: string,targetUserId: string,role: PersonRole,database: DbPool = getDb(),@@ -148,6 +156,16 @@ export async function setPersonRole(return withTransaction(async (tx) => {await tx.query("SELECT pg_advisory_xact_lock($1)", [ROLE_CHANGE_LOCK_ID]);+ const actor = await queryOne<{ role: string }>(+ tx,+ `SELECT u.role FROM "user" u WHERE u.id = $1`,+ [actingUserId],+ );++ if (actor?.role !== "admin") {+ throw new PeopleError("Only an administrator can do this.", 403);+ }+const target = await queryOne<PersonRow>(tx,`SELECT ${PERSON_COLUMNS} FROM "user" u WHERE u.id = $1 FOR UPDATE OF u`,diff --git a/src/lib/settings.ts b/src/lib/settings.tsindex c299244..66d185a 100644--- a/src/lib/settings.ts+++ b/src/lib/settings.ts@@ -85,39 +85,44 @@ type AppSettingsRow = {terms_url: string | null;};-const SETTINGS_COLUMNS = `- allowed_email_domains,- brand_color,- email_ready_at,- logo_hash,- organization_name,- privacy_url,- retention_days,- sender_address,- setup_completed_at,- signup_mode,- support_address,- terms_url-`;-// The columns the settings table was created with, who may sign up among-// them. A database that is behind this version is still read for these.-const FIRST_SETTINGS_COLUMNS = `- allowed_email_domains,- email_ready_at,- organization_name,- privacy_url,- sender_address,- setup_completed_at,- signup_mode,- support_address,- terms_url-`;--type FirstSettingsRow = Omit<- AppSettingsRow,- "brand_color" | "logo_hash" | "retention_days"->;+// them.+const FIRST_SETTINGS_COLUMNS = [+ "allowed_email_domains",+ "email_ready_at",+ "organization_name",+ "privacy_url",+ "sender_address",+ "setup_completed_at",+ "signup_mode",+ "support_address",+ "terms_url",+] as const;++// What each migration since has added, oldest first. A database that is+// behind this version is read in the newest of these shapes it has, so+// what it does hold still counts. A migration that adds a column the app+// reads adds a line here.+const LATER_SETTINGS_COLUMNS = [+ ["retention_days"], // 20261113090000_signature_evidence+ ["brand_color", "logo_hash"], // 20261114120000_branding+] as const;++type LaterSettingsColumn = (typeof LATER_SETTINGS_COLUMNS)[number][number];++/** A row read from a table that may not have every later column yet. */+type StoredSettingsRow = Omit<AppSettingsRow, LaterSettingsColumn> &+ Partial<Pick<AppSettingsRow, LaterSettingsColumn>>;++/** The columns of the table after this many of the later migrations. */+function settingsColumnsAfter(laterMigrations: number): string {+ return [+ ...FIRST_SETTINGS_COLUMNS,+ ...LATER_SETTINGS_COLUMNS.slice(0, laterMigrations).flat(),+ ].join(", ");+}++const SETTINGS_COLUMNS = settingsColumnsAfter(LATER_SETTINGS_COLUMNS.length);// How an install behaves before it has a settings row. This is what the app// did before settings existed, so an upgraded deployment does not change@@ -186,15 +191,15 @@ function readErrorCode(error: unknown): unknown {: undefined;}-function mapSettingsRow(row: AppSettingsRow): AppSettings {+function mapSettingsRow(row: StoredSettingsRow): AppSettings {return {allowedEmailDomains: row.allowed_email_domains ?? [],- brandColor: row.brand_color,+ brandColor: row.brand_color ?? null,emailReadyAt: row.email_ready_at,- logoVersion: row.logo_hash,+ logoVersion: row.logo_hash ?? null,organizationName: row.organization_name,privacyUrl: row.privacy_url,- retentionDays: row.retention_days,+ retentionDays: row.retention_days ?? null,senderAddress: row.sender_address,setupCompletedAt: row.setup_completed_at,signupMode: row.signup_mode,@@ -207,54 +212,43 @@ function mapSettingsRow(row: AppSettingsRow): AppSettings {* Reads the stored row. Null when there is none (or no table for it yet).** A table that is there but behind this version, because a migration has- * not run, is still read for the columns it has always had. Taking it for- * "no row" would swap the sign-up rule an administrator chose for the open- * default of an install that never had settings.+ * not run, is read in the newest shape it does have, and what it lacks is+ * taken as not set. Taking it for "no row" would swap the sign-up rule an+ * administrator chose for the open default of an install that never had+ * settings, and drop the retention period along with it.*/export async function readStoredSettings(database: DbExecutor = getDb(),): Promise<AppSettings | null> {- try {- const row = await queryOne<AppSettingsRow>(- database,- `select ${SETTINGS_COLUMNS} from public.app_settings where id`,- );-- return row ? mapSettingsRow(row) : null;- } catch (error) {- if (isMissingColumnError(error)) {- return readFirstSettings(database);- }-- if (isMissingSchemaError(error)) {- return null;+ const newest = LATER_SETTINGS_COLUMNS.length;++ for (let laterMigrations = newest; ; laterMigrations -= 1) {+ try {+ const row = await queryOne<StoredSettingsRow>(+ database,+ `select ${settingsColumnsAfter(laterMigrations)} from public.app_settings where id`,+ );++ return row ? mapSettingsRow(row) : null;+ } catch (error) {+ // One migration further back. Past the table as it was created there+ // is nothing left to try.+ if (isMissingColumnError(error) && laterMigrations > 0) {+ continue;+ }++ if (laterMigrations === newest && isMissingSchemaError(error)) {+ return null;+ }++ // Anything else reaches the caller, and so does a second failure+ // (inside a transaction, the first one has already ended it). Nobody+ // is let in on the strength of a guess.+ throw error;}-- throw error;}}-// Nothing is caught here. If even this cannot be read (inside a-// transaction the failed query above has already ended it), the caller-// gets the error, and nobody is let in on the strength of a guess.-async function readFirstSettings(- database: DbExecutor,-): Promise<AppSettings | null> {- const row = await queryOne<FirstSettingsRow>(- database,- `select ${FIRST_SETTINGS_COLUMNS} from public.app_settings where id`,- );-- return row- ? mapSettingsRow({- ...row,- brand_color: null,- logo_hash: null,- retention_days: null,- })- : null;-}-async function getStoredSettings(): Promise<AppSettings | null> {const now = Date.now();diff --git a/src/lib/setup.dbtest.ts b/src/lib/setup.dbtest.tsindex c39689a..a333d93 100644--- a/src/lib/setup.dbtest.ts+++ b/src/lib/setup.dbtest.ts@@ -212,30 +212,50 @@ test("a database that is behind this version still applies its sign-up rule", asawait saveSettings({organizationName: "Acme Corp",+ retentionDays: 365,setupCompletedAt: 1,signupMode: "closed",},database,);- // The settings table as it was before an install could have its own- // color: a column this version reads is not there. Whatever happens- // below, the column is put back.- await database.query(- "alter table public.app_settings rename column brand_color to brand_color_later",- );+ // Takes a column this version reads out of the table, as if its+ // migration had not run. Whatever happens below, it is put back.+ const hidden: string[] = [];+ const hide = async (column: string) => {+ await database.query(+ `alter table public.app_settings rename column ${column} to ${column}_later`,+ );+ hidden.push(column);+ };try {- const stored = await readStoredSettings(database);+ // The table as it was before an install could have its own color.+ await hide("brand_color");++ const beforeBranding = await readStoredSettings(database);- assert.equal(stored?.signupMode, "closed");- assert.equal(stored?.organizationName, "Acme Corp");- assert.equal(stored?.brandColor, null);+ assert.equal(beforeBranding?.signupMode, "closed");+ assert.equal(beforeBranding?.organizationName, "Acme Corp");+ assert.equal(beforeBranding?.brandColor, null);+ // What that table does hold still counts.+ assert.equal(beforeBranding?.retentionDays, 365);+ assert.equal((await signUp("[email protected]")).allowed, false);++ // And as it was created, before a retention period could be set.+ await hide("retention_days");++ const asCreated = await readStoredSettings(database);++ assert.equal(asCreated?.signupMode, "closed");+ assert.equal(asCreated?.retentionDays, null);assert.equal((await signUp("[email protected]")).allowed, false);} finally {- await database.query(- "alter table public.app_settings rename column brand_color_later to brand_color",- );+ for (const column of hidden.reverse()) {+ await database.query(+ `alter table public.app_settings rename column ${column}_later to ${column}`,+ );+ }}});