// The personal-workspace pointer, in its own leaf module. // // Both the Slack routing resolvers and the Slack access-request path need it, // and this keeps that from becoming an import cycle between them. import { sql } from "drizzle-orm"; import { rawRows, withRlsContext, type Database } from "./database"; import { listSelfOrganizationMemberships } from "./organization-membership-lifecycle"; import { rlsSubjectIdOrEmpty } from "./workspace-authority"; /** * The subject's own personal workspace in one organization, or null. * * Only an `active` membership counts, and only that membership's own * `personalWorkspaceId` pointer is read - never a default workspace, a * `created_by`, or current access. * * Non-`user:` subjects (API keys, delegated service principals, configured and * local principals) can never own an organization membership, so they * short-circuit rather than tripping `list_self_organization_memberships`' * `42501` guard. * * ORACLE, NOT AN AUTHORIZATION. This answers "which workspace is this named * subject's own" for whatever subject it is handed; it does not establish that * the caller IS that subject. Pass only a subject authenticated out of band - * for Slack, one named by a durable `slack_bot_user_links` row. Never pass a * subject taken from a request payload. */ export async function namedSubjectPersonalWorkspaceId( db: Database, input: { accountId: string; subjectId: string }, ): Promise { if (!input.subjectId.startsWith("user:")) return null; return await activeMembershipPersonalWorkspaceId(db, input); } /** * The same pointer for an external user of the organization (an * `external_user:` subject, such as a person in an embedded chat): their own * workspace, named by their active organization membership. Null for every * other subject. The same oracle caveat applies: it does not establish that * the caller is that person. */ export async function externalPersonPersonalWorkspaceId( db: Database, input: { accountId: string; subjectId: string }, ): Promise { if (!input.subjectId.startsWith("external_user:")) return null; return await activeMembershipPersonalWorkspaceId(db, input); } /** * Organization roles that make someone a full member. Listed rather than * excluded, so a role added later (a guest role, say) counts only once it is * deliberately added here. */ const FULL_ORGANIZATION_MEMBER_ROLES: ReadonlySet = new Set(["owner", "admin", "member"]); /** * Whether a named person is an active, full member of one organization: a * `user:` subject (a managed human, never an API key, service principal or an * embedded product's `external_user:`) whose membership there is `active` * (not provisioning, suspended or revoked) with a full-member role. * * Read live on every call, never cached. The same oracle caveat as * `namedSubjectPersonalWorkspaceId` applies: pass only a subject authenticated * out of band, such as one named by a durable `slack_bot_user_links` row. */ export async function namedSubjectIsActiveOrganizationMember( db: Database, input: { accountId: string; subjectId: string }, ): Promise { if (!input.subjectId.startsWith("user:")) return false; const membership = await activeSelfOrganizationMembership(db, input); return membership !== null && FULL_ORGANIZATION_MEMBER_ROLES.has(membership.role); } async function activeMembershipPersonalWorkspaceId( db: Database, input: { accountId: string; subjectId: string }, ): Promise { const membership = await activeSelfOrganizationMembership(db, input); return membership?.personalWorkspaceId ?? null; } async function activeSelfOrganizationMembership( db: Database, input: { accountId: string; subjectId: string }, ): Promise<{ role: string; personalWorkspaceId: string } | null> { // `listSelfOrganizationMemberships` opens its own scope and sets // `opengeni.subject_id` to the probed subject. Under drizzle a nested // transaction is a SAVEPOINT, and releasing a savepoint does NOT undo a // transaction-local `set_config`, so without this the probed subject would // leak out and silently re-scope the rest of a caller-owned transaction. // `namedSubjectHasLiveWorkspaceAuthority` guards the same hazard the same // way; empty string is the canonical "unset" because `current_subject_id()` // is `nullif(current_setting(...), '')`. const priorSubjectId = await rlsSubjectIdOrEmpty(db); let completed = false; try { const memberships = await listSelfOrganizationMemberships(db, input.subjectId); const membership = memberships.find( (candidate) => candidate.status === "active" && candidate.organizationId === input.accountId && candidate.personalWorkspaceId !== null, ); completed = true; return membership?.personalWorkspaceId ? { role: membership.role, personalWorkspaceId: membership.personalWorkspaceId } : null; } finally { const restore = db.execute( sql`select set_config('opengeni.subject_id', ${priorSubjectId}, true)`, ); if (completed) { await restore; } else { // A failed statement can leave a caller-owned transaction aborted. // Preserve the original diagnostic rather than replacing it with the // restore's `25P02`. await restore.catch(() => undefined); } } } function deniedAuthority(error: unknown): boolean { for (let current: unknown = error, depth = 0; current && depth < 4; depth += 1) { if ((current as { code?: unknown }).code === "42501") return true; current = (current as { cause?: unknown }).cause; } return false; } /** * True only when `workspaceId` is a Personal workspace of `accountId` and its * pointer names exactly `subjectId` (a `user:` or `external_user:` subject). * * Shared workspaces stop at the workspace-kind check, before any membership * read. A subject the membership oracle refuses (for example an external user * with no Personal workspace of their own) is not the owner, so its `42501` is * a plain false; the probe runs in its own scope (a savepoint inside a caller's * transaction), so the refusal never aborts the caller. The same oracle caveat * as `namedSubjectPersonalWorkspaceId` applies. */ export async function isSubjectOwnPersonalWorkspace( db: Database, input: { accountId: string; workspaceId: string; subjectId: string }, ): Promise { if (!input.subjectId.startsWith("user:") && !input.subjectId.startsWith("external_user:")) return false; try { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scoped) => { const [row] = await rawRows<{ kind: string | null }>( scoped, sql`select get_workspace_kind(${input.accountId}::uuid, ${input.workspaceId}::uuid) as kind`, ); if (row?.kind !== "personal") return false; const pointer = input.subjectId.startsWith("user:") ? await namedSubjectPersonalWorkspaceId(scoped, input) : await externalPersonPersonalWorkspaceId(scoped, input); return pointer === input.workspaceId; }, undefined, "none", ); } catch (error) { if (deniedAuthority(error)) return false; throw error; } }