@mistriwork/mistri 1.0.0-rc.52 → 1.0.0-rc.53

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/docs/status.md +3 -3
  4. package/dist/embed/react/headless.js +1 -1
  5. package/dist/embed/react/index.js +1 -1
  6. package/dist/server/app/appSearchRuntime.d.ts +9 -0
  7. package/dist/server/app/appSearchRuntime.js +21 -3
  8. package/dist/server/cli/apps.d.ts +2 -0
  9. package/dist/server/cli/apps.js +14 -0
  10. package/dist/server/cli/mistriMain.js +13 -1
  11. package/dist/server/cli/reindex.js +15 -2
  12. package/dist/server/stores/commandStores.d.ts +6 -1
  13. package/dist/server/stores/commandStores.js +2 -1
  14. package/dist/server/tenant/tenantAdministration.js +2 -1
  15. package/dist/server/tenant/tenantAuthenticatedHttp.js +3 -1
  16. package/dist/server/tenant/tenantBackstopOwner.d.ts +20 -0
  17. package/dist/server/tenant/tenantBackstopOwner.js +37 -0
  18. package/dist/server/tenant/tenantConnections.d.ts +23 -2
  19. package/dist/server/tenant/tenantConnections.js +39 -3
  20. package/dist/server/tenant/tenantEnrollment.d.ts +8 -0
  21. package/dist/server/tenant/tenantEnrollment.js +40 -4
  22. package/dist/server/tenant/tenantLive.d.ts +6 -0
  23. package/dist/server/tenant/tenantLive.js +18 -1
  24. package/dist/server/tenant/tenantLocalAccess.js +16 -2
  25. package/dist/server/tenant/tenantNames.d.ts +1 -1
  26. package/dist/server/tenant/tenantPostgresCatalog.d.ts +14 -0
  27. package/dist/server/tenant/tenantPostgresCatalog.js +45 -0
  28. package/dist/server/tenant/tenantReadSource.d.ts +4 -187
  29. package/dist/server/tenant/tenantReadSource.js +110 -693
  30. package/dist/server/tenant/tenantReadSourceShared.d.ts +213 -0
  31. package/dist/server/tenant/tenantReadSourceShared.js +176 -0
  32. package/dist/server/tenant/tenantReadSourceSqlite.d.ts +6 -0
  33. package/dist/server/tenant/tenantReadSourceSqlite.js +498 -0
  34. package/dist/server/tenant/tenantSearch.d.ts +2 -30
  35. package/dist/server/tenant/tenantSearch.js +17 -2
  36. package/dist/server/tenant/tenantStartup.js +13 -2
  37. package/dist/server/tenant/tenantSupportOperations.js +2 -1
  38. package/dist/server/tenant/tenantValidationRecord.js +2 -0
  39. package/dist/server/tenant/tenantWriteSource.d.ts +8 -1
  40. package/dist/server/tenant/tenantWriteSource.js +79 -14
  41. package/dist/ssr/render.js +1 -1
  42. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  The 1.0 release candidates of `@mistriwork/mistri`. Every earlier release is in the full changelog.
4
4
 
5
+ ## 1.0.0-rc.53
6
+
7
+ - **A tenant App's Postgres connection can run under the row-security backstop.** A connection that says `"backstop": "rls"` and names its `owner` serves every tenant transaction through the runtime role it connects as, with `mistri.tenant` set in the flight that begins it, and keeps a small pool (five connections) as the owner for what is cross-tenant by design: migrations, enrollment, the tenant directory, the platform realm, support reads and due timers. A runtime transaction that does not say its tenant is refused rather than sent. Without `backstop` nothing changes.
8
+ - **The roles are attested when the server starts.** The runtime role must not be a superuser, hold `BYPASSRLS`, be a member of the owner role or be the owner itself; a replica's role is held to the same. Any of these refuses to start.
9
+ - **Search and `--reindex` read as the owner under the backstop**, so indexing a write reads the rows it indexes rather than seeing none and removing the documents it should keep. Each document still carries its tenant, and a search still answers only from the person's own.
10
+ - **A non-tenant App, or the Workbench, refuses a backstop connection** with a message saying the backstop is for tenant Apps: either would run as the runtime role with no tenant and read nothing.
11
+ - **The store check allows the backstop's runtime role** to read and write the store's tables, and the PostgreSQL guide has a section on setting the backstop up: the roles, the grants, the pinned policy, and what runs as which role.
12
+
5
13
  ## 1.0.0-rc.52
6
14
 
7
15
  - **A Postgres transaction can carry its tenant into the database.** An adapter opened with `rowSecurity` sets `mistri.tenant` for the life of each tenant transaction, in the same flight as `BEGIN`, so a row policy can read it and nothing costs a round trip. Reads, writes, the journal and a pinned read snapshot all carry it; an autocommit read, which could not, refuses on such an adapter rather than returning nothing. A tenant value that is empty or holds a NUL or a backslash is refused before it is sent. Nothing turns this on yet: the next candidates route a tenant App's runtime role through it and add the command that writes the policies.
package/README.md CHANGED
@@ -30,7 +30,7 @@ App build to run on the supported Node 24 runtime; TypeScript examples also
30
30
  have an explicit typecheck (TypeScript 7 or later, the native compiler), and `mistri build` is the optional production
31
31
  step that runs it, validates the App and bundles it — see
32
32
  [Build and deploy an App](https://mistriwork.dev/docs/build-and-deploy/).
33
- These App features ship in mistri 1.0.0-rc.52; the
33
+ These App features ship in mistri 1.0.0-rc.53; the
34
34
  [status page](https://mistriwork.dev/docs/status/) says what is stable
35
35
  and what comes next. Start with the sample catalog (`examples/apps/README.md`),
36
36
  written for people and coding agents, then the [App DSL reference](https://mistriwork.dev/docs/app-dsl/) (the same pages read offline with `npx @mistriwork/mistri docs`).
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  title: Status & roadmap
3
- description: The 1.0.0-rc.52 scope, stable and preview features, current limitations and planned work.
3
+ description: The 1.0.0-rc.53 scope, stable and preview features, current limitations and planned work.
4
4
  ---
5
5
 
6
6
  The scope of this release, stable and preview features, current limitations and planned work.
@@ -10,7 +10,7 @@ npx @mistriwork/mistri check --app .
10
10
  # preview: This App uses Preview features (…). They work as documented and may change in any 1.x release.
11
11
  ```
12
12
 
13
- This site describes **mistri 1.0.0-rc.52**, a release candidate. Since rc.2, the first release under the mistri name,
13
+ This site describes **mistri 1.0.0-rc.53**, a release candidate. Since rc.2, the first release under the mistri name,
14
14
  the App framework is split out of tablewalk, which stays the standalone database browser. A save is a fixed number of
15
15
  database round trips, the runtime forgets what it wrote about an App after the App's own retention windows, and on
16
16
  PostgreSQL the runtime lives in one schema named `mistri`. There is no upgrade from a tablewalk 0.9 App database.
@@ -171,7 +171,7 @@ entry points above:
171
171
  "version": "1.0.0",
172
172
  "type": "module",
173
173
  "exports": { ".": "./src/index.ts" },
174
- "peerDependencies": { "@mistriwork/mistri": "^1.0.0-rc.52" }
174
+ "peerDependencies": { "@mistriwork/mistri": "^1.0.0-rc.53" }
175
175
  }
176
176
  ```
177
177
 
@@ -4302,7 +4302,7 @@ async function ci(e, t, n, r, i) {
4302
4302
  if (!o.ok) throw Error(s?.error ?? `The surface "${r}" could not be opened (${o.status}).`);
4303
4303
  return s?.signedIn && s.surface ? s.surface : void 0;
4304
4304
  }
4305
- var li = "1.0.0-rc.52";
4305
+ var li = "1.0.0-rc.53";
4306
4306
  function ui({ endpoint: e, auth: t, app: n, surface: r, basePath: c, navigator: d, version: f = li, fallback: m, children: h }) {
4307
4307
  let g = e.replace(/\/+$/, ""), _ = o(t);
4308
4308
  _.current = t;
@@ -4,7 +4,7 @@ import { n as s, r as c, t as l } from "./chunks/router-CAJxIEw4.js";
4
4
  import { createContext as u, useContext as d, useEffect as f, useMemo as p, useRef as m, useState as h } from "react";
5
5
  import { jsx as g } from "react/jsx-runtime";
6
6
  // packages/mistri/src/embed/index.tsx
7
- var _ = "1.0.0-rc.52", v = u(null), y;
7
+ var _ = "1.0.0-rc.53", v = u(null), y;
8
8
  async function b(n, i, a) {
9
9
  let o = i?.authorization(), s = a ? `?${new URLSearchParams({
10
10
  app: a.app,
@@ -84,6 +84,7 @@ declare class SearchIndexer {
84
84
  private draining?;
85
85
  private waiting;
86
86
  private readonly ensured;
87
+ private readonly readers;
87
88
  constructor(registry: Registry, retryMs?: readonly number[]);
88
89
  /** A committed write to `tableId` in `app`: re-index that record soon. A
89
90
  * tenant-owned resource names its tenant column, whose value each document keeps. */
@@ -109,6 +110,14 @@ declare class SearchIndexer {
109
110
  private ensure;
110
111
  private enqueue;
111
112
  private drain;
113
+ /**
114
+ * Read `connection`'s rows through `open` instead of the registry's adapter (undefined takes it back). Under the
115
+ * row-security backstop the registry's adapter is the runtime role, which reads no tenant row with no tenant set:
116
+ * `apply` would find none and remove the record's document on every write, and a reindex would index nothing. The
117
+ * indexer reads as the owner, across tenants by design, and each document keeps its row's tenant.
118
+ */
119
+ readThrough(connection: string, open: (() => Adapter) | undefined): void;
120
+ private source;
112
121
  private apply;
113
122
  /**
114
123
  * The reverse step of a path: a write to a row a searched path points at
@@ -329,6 +329,8 @@ class SearchIndexer {
329
329
  draining;
330
330
  waiting = 0;
331
331
  ensured = new Set();
332
+ /* A connection's reader where the registry's own cannot read its rows (readThrough). */
333
+ readers = new Map();
332
334
  constructor(registry, retryMs = RETRY_MS) {
333
335
  this.registry = registry;
334
336
  this.retryMs = retryMs;
@@ -376,7 +378,7 @@ class SearchIndexer {
376
378
  continue;
377
379
  if ('problem' in target)
378
380
  throw new Error(`resources "${name}" cannot be indexed on this connection: ${target.problem}`);
379
- const { adapter, schema } = await this.registry.open(target.connection);
381
+ const { adapter, schema } = await this.source(target.connection);
380
382
  const found = searchedAt(app, schema, target);
381
383
  const table = schema.tables.find((candidate) => candidate.id === target.physical);
382
384
  if (!found)
@@ -460,10 +462,26 @@ class SearchIndexer {
460
462
  }
461
463
  }
462
464
  }
465
+ /**
466
+ * Read `connection`'s rows through `open` instead of the registry's adapter (undefined takes it back). Under the
467
+ * row-security backstop the registry's adapter is the runtime role, which reads no tenant row with no tenant set:
468
+ * `apply` would find none and remove the record's document on every write, and a reindex would index nothing. The
469
+ * indexer reads as the owner, across tenants by design, and each document keeps its row's tenant.
470
+ */
471
+ readThrough(connection, open) {
472
+ if (open)
473
+ this.readers.set(connection, open);
474
+ else
475
+ this.readers.delete(connection);
476
+ }
477
+ async source(connection) {
478
+ const opened = await this.registry.open(connection);
479
+ return { adapter: this.readers.get(connection)?.() ?? opened.adapter, schema: opened.schema };
480
+ }
463
481
  async apply(job) {
464
482
  if (job.dependents)
465
483
  return this.applyDependents(job);
466
- const { adapter, schema } = await this.registry.open(job.connection);
484
+ const { adapter, schema } = await this.source(job.connection);
467
485
  const found = searchedAt(job.app, schema, job);
468
486
  if (!found)
469
487
  return;
@@ -499,7 +517,7 @@ class SearchIndexer {
499
517
  * by the reference column, in key order, at most MAX_DEPENDENTS of them.
500
518
  */
501
519
  async applyDependents(job) {
502
- const { adapter, schema } = await this.registry.open(job.connection);
520
+ const { adapter, schema } = await this.source(job.connection);
503
521
  for (const target of await searchTargets(this.registry, job.app, job.connection)) {
504
522
  if ('problem' in target || target.connection !== job.connection)
505
523
  continue;
@@ -39,4 +39,6 @@ export declare function startupTargets(opts: Pick<Options, 'apps' | 'appEntry'>,
39
39
  export declare function presentationOf(config: Pick<StartupConfig, 'presentation' | 'configPath'>): LoadedApp['presentation'] | undefined;
40
40
  /** A presentation for an App this server does not serve is a typo or a stale config: said, with the Apps it does serve. */
41
41
  export declare function assertPresentationNamesApps(presentation: LoadedApp['presentation'] | undefined, loadedApps: readonly LoadedApp[]): void;
42
+ /** Refuses a non-tenant App bound to a connection under the row-security backstop (tenantBackstopOwner.ts). */
43
+ export declare function assertAppsOffBackstop(loadedApps: readonly LoadedApp[], registry: Pick<Registry, 'configs' | 'list' | 'active'>): void;
42
44
  export declare function loadStartupApps(opts: Options, registry: Registry, config: StartupConfig): Promise<StartupApps>;
@@ -14,6 +14,7 @@ import { BUILD_ENTRY_KINDS } from '../app/appBuild.js';
14
14
  import { assertAppSearch } from '../app/appSearchRuntime.js';
15
15
  import { configurePublicFormLimits } from '@mistriwork/engine/server/http/rateLimit.js';
16
16
  import { configureSignInState } from '../auth/signInState.js';
17
+ import { assertNoBackstop } from '../tenant/tenantBackstopOwner.js';
17
18
  /**
18
19
  * The variable a build's own `mistri check` child reads (build.ts): the App
19
20
  * directory the config lists that the `--app` build stands for, so the child
@@ -85,6 +86,17 @@ export function assertPresentationNamesApps(presentation, loadedApps) {
85
86
  if (stray.length)
86
87
  throw new Error(`${presentation.file ?? 'the config file'}: "presentation.${stray[0]}" names no App this server serves (${ids.map((id) => `"${id}"`).join(', ') || 'none'}). Key each presentation by the App's id.`);
87
88
  }
89
+ /** Refuses a non-tenant App bound to a connection under the row-security backstop (tenantBackstopOwner.ts). */
90
+ export function assertAppsOffBackstop(loadedApps, registry) {
91
+ for (const loaded of loadedApps) {
92
+ if (isTenantApp(loaded.app))
93
+ continue;
94
+ const scope = loaded.app.connection;
95
+ const bound = (scope ? registry.list().find((c) => c.id === scope || c.name === scope)?.id : undefined) ?? registry.active;
96
+ if (bound)
97
+ assertNoBackstop(registry, 'a non-tenant App', [bound]);
98
+ }
99
+ }
88
100
  export async function loadStartupApps(opts, registry, config) {
89
101
  /* The app layer. Loaded whether or not a config file was — `--app` is
90
102
  an explicit ask, and the config's "apps" list is the same ask written
@@ -155,6 +167,8 @@ export async function loadStartupApps(opts, registry, config) {
155
167
  assertBuildEntries(opts, loadedApps);
156
168
  assertPresentationNamesApps(presentation, loadedApps);
157
169
  assertAppScopes(loadedApps, (scope) => registry.list().find((c) => c.id === scope || c.name === scope)?.id ?? scope);
170
+ /* Only a tenant App reads through the row-security backstop; any other would see none of its tenant rows. */
171
+ assertAppsOffBackstop(loadedApps, registry);
158
172
  // A search names a search connection the config has; said here, not at the first keystroke.
159
173
  assertAppSearch(loadedApps.map((loaded) => loaded.app), registry);
160
174
  /* A bucket without credentials refuses the start, as a missing secrets key does; mistri check says it. */
@@ -330,8 +330,20 @@ export const main = async () => {
330
330
  /* A server with no App to serve, from the command line or the config, is the database browser's, whose dispatcher
331
331
  (http/browserHandler.ts) is the one that manages connections: this one's is an App's. Said before an App or a
332
332
  connection is opened. */
333
- if (!config.apps.length && !opts.apps?.length && opts.appEntry === undefined && !dev && startFor(opts) !== 'mistri')
333
+ if (!config.apps.length && !opts.apps?.length && opts.appEntry === undefined && !dev && startFor(opts) !== 'mistri') {
334
+ /* A connection under the row-security backstop is a tenant App's: the Workbench would browse it as the runtime
335
+ role and see none of its tenant rows, so that is said first (tenantBackstopOwner.ts). */
336
+ try {
337
+ (await import('../tenant/tenantBackstopOwner.js')).assertNoBackstop(registry, 'the Workbench');
338
+ }
339
+ catch (error) {
340
+ await registry.closeAll();
341
+ console.error(`mistri: ${error.message}`);
342
+ process.exitCode = 2;
343
+ return;
344
+ }
334
345
  return refuseBrowser('a server with no App', process.argv.slice(2), registry);
346
+ }
335
347
  /* Before any App opens a writer: a tenant App's is bound to live sync as it is made (tenantLive.ts). */
336
348
  if (opts.noLive)
337
349
  (await import('../live/liveBinding.js')).setLiveSync(false);
@@ -29,8 +29,21 @@ export async function reindexApps(registry, loadedApps, only, policyFile) {
29
29
  const { tenantSearchColumns } = await import('../tenant/tenantSearch.js');
30
30
  tenantColumns = tenantSearchColumns((await loadAppTenantPolicy(policyFile)).ownership);
31
31
  }
32
- for (const { resource, indexed } of await indexerFor(registry).reindex(loaded.app, owner, only || undefined, undefined, tenantColumns)) {
33
- console.error(`mistri: indexed ${indexed} record(s) of "${resource}" for app "${loaded.app.name}"`);
32
+ /* Under the row-security backstop the registry's adapter is the runtime role and reads no tenant row: the
33
+ indexer reads as the owner, across tenants by design (each document keeps its row's tenant). */
34
+ const { openBackstopOwnerReader } = await import('../tenant/tenantBackstopOwner.js');
35
+ const reader = await openBackstopOwnerReader(registry, owner);
36
+ const indexer = indexerFor(registry);
37
+ if (reader)
38
+ indexer.readThrough(owner, () => reader);
39
+ try {
40
+ for (const { resource, indexed } of await indexer.reindex(loaded.app, owner, only || undefined, undefined, tenantColumns)) {
41
+ console.error(`mistri: indexed ${indexed} record(s) of "${resource}" for app "${loaded.app.name}"`);
42
+ }
43
+ }
44
+ finally {
45
+ indexer.readThrough(owner, undefined);
46
+ await reader?.close();
34
47
  }
35
48
  }
36
49
  }
@@ -59,7 +59,12 @@ interface SqliteCommands extends NativeCommands {
59
59
  interface PostgresCommands extends NativeCommands {
60
60
  scopeVerifiedCommandTransaction<T>(input: RowScope, verify: PostgresTransactionVerifier, tenant: CommandJournalTenant | CommandJournalPlatform, run: ScopedCommandRun<T>,
61
61
  /** The outer bound the scope sits inside (scopedTransaction.ts ScopeBound), over the same tables. */
62
- boundInput?: RowScope): Promise<T>;
62
+ boundInput?: RowScope,
63
+ /** What the row policy reads under the backstop (PostgresAdapter.scopeTransaction's `tenant`): the source's to say,
64
+ * not the journal's, whose platform realm names no tenant even where a command runs in one. */
65
+ options?: {
66
+ readonly tenant?: string | null;
67
+ }): Promise<T>;
63
68
  }
64
69
  /** A constructed SQLite or PostgreSQL adapter's journal capabilities; undefined for anything else (a facade or a proxy lends no host). */
65
70
  export declare function nativeCommandsOf(adapter: SqliteAdapter): SqliteCommands;
@@ -136,7 +136,7 @@ function postgresCommands(host) {
136
136
  const owner = capturePublicPlacementOwner(input);
137
137
  return host.readSnapshot((snapshot) => recoverPostgresPublicPlacementReceipt(snapshot.client, owner, submission));
138
138
  },
139
- scopeVerifiedCommandTransaction: async (input, verify, tenant, run, boundInput) => {
139
+ scopeVerifiedCommandTransaction: async (input, verify, tenant, run, boundInput, options = {}) => {
140
140
  const scope = captureRowScope(input), owner = captureCommandJournalMember(tenant), bound = boundInput === undefined ? undefined : captureRowScope(boundInput);
141
141
  if (typeof verify !== 'function' ||
142
142
  typeof run !== 'function' ||
@@ -148,6 +148,7 @@ function postgresCommands(host) {
148
148
  scope,
149
149
  verify,
150
150
  bound,
151
+ ...(options.tenant !== undefined ? { tenant: options.tenant } : {}),
151
152
  });
152
153
  },
153
154
  };
@@ -454,7 +454,8 @@ async function openSqliteAdministrationStore(path, owner, auth, authStore, invit
454
454
  * it changes, in the lock order the business fence shares. */
455
455
  async function openPostgresAdministrationStore(url, owner, auth) {
456
456
  auth.assertCurrent();
457
- const writer = tenantAdapter(url, 'Private tenant administration');
457
+ // Administration manages every tenant by design: under the backstop, as the owner (tenantConnections.ts).
458
+ const writer = tenantAdapter(url, 'Private tenant administration', false, 'owner');
458
459
  try {
459
460
  let invitationStorage;
460
461
  const attestInvitations = async (client) => {
@@ -555,11 +555,13 @@ export async function createTenantAuthenticatedHttpServer(options) {
555
555
  }
556
556
  // Search, where the App declares it and a search provider is plugged in: the index follows this deployment's writer.
557
557
  const registry = raw.registry;
558
+ const searched = captureTenantEnrollment(enrollment);
558
559
  search = registry
559
560
  ? openTenantSearch({
560
561
  registry,
561
562
  app: loaded.app,
562
- ownership: captureTenantEnrollment(enrollment).ownership,
563
+ ownership: searched.ownership,
564
+ ...('url' in searched.source ? { url: searched.source.url } : {}),
563
565
  })
564
566
  : undefined;
565
567
  /* The reader's own name, for a dashboard's "Hello, {me.name}": the sign-in
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The owner's reader of a connection under the row-security backstop (docs/postgresql.md), for the paths that read
3
+ * through a registry rather than a tenant host: `--reindex`, and the profile table a local sign-in is made a member of.
4
+ *
5
+ * `registry.open` connects as `url`, the runtime role, which the pinned policy binds: with no tenant set it reads no
6
+ * row of a tenant table. These paths cross tenants by design (a document keeps its row's tenant; a profile row is a
7
+ * tenant), so they read as the owner, whose role the policy does not bind. The roles are attested here as enrollment
8
+ * attests them, so a pair that is not the backstop's refuses before anything is read.
9
+ */
10
+ import { PostgresAdapter } from '@mistriwork/engine/adapters/postgres.js';
11
+ import type { Registry } from '@mistriwork/engine/server/connections.js';
12
+ /** An adapter on the owner's URL for the connection `id`, or undefined when it is not under the backstop. The caller closes it. */
13
+ export declare function openBackstopOwnerReader(registry: Registry, id: string): Promise<PostgresAdapter | undefined>;
14
+ /**
15
+ * Refuses `who` a connection under the backstop: only a tenant App reads through it, because `url` is then the
16
+ * runtime role, which the pinned policy binds, and a read with no tenant set sees no tenant row. A non-tenant App or
17
+ * the Workbench pointed at it would start, paint empty tables and look like a database with no data, so the start
18
+ * refuses instead. `names` narrows it to the connections an App binds.
19
+ */
20
+ export declare function assertNoBackstop(registry: Pick<Registry, 'configs'>, who: 'a non-tenant App' | 'the Workbench', names?: readonly string[]): void;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The owner's reader of a connection under the row-security backstop (docs/postgresql.md), for the paths that read
3
+ * through a registry rather than a tenant host: `--reindex`, and the profile table a local sign-in is made a member of.
4
+ *
5
+ * `registry.open` connects as `url`, the runtime role, which the pinned policy binds: with no tenant set it reads no
6
+ * row of a tenant table. These paths cross tenants by design (a document keeps its row's tenant; a profile row is a
7
+ * tenant), so they read as the owner, whose role the policy does not bind. The roles are attested here as enrollment
8
+ * attests them, so a pair that is not the backstop's refuses before anything is read.
9
+ */
10
+ import { PostgresAdapter } from '@mistriwork/engine/adapters/postgres.js';
11
+ import { resolveConnection } from '@mistriwork/engine/server/auth/credentials.js';
12
+ /** An adapter on the owner's URL for the connection `id`, or undefined when it is not under the backstop. The caller closes it. */
13
+ export async function openBackstopOwnerReader(registry, id) {
14
+ const config = registry.configOf(id);
15
+ if (config?.backstop !== 'rls' || config.owner === undefined)
16
+ return undefined;
17
+ const options = { secrets: true, ...(registry.environment ? { environment: registry.environment } : {}) };
18
+ const url = (await resolveConnection(config.name, config.url, options)).url;
19
+ const owner = (await resolveConnection(config.name, config.owner, options)).url;
20
+ const { attestBackstopRoles } = await import('./tenantEnrollment.js');
21
+ const { role } = await attestBackstopRoles(url, owner, []);
22
+ return new PostgresAdapter(owner, 'Backstop owner reader', [], undefined, undefined, { rowSecurity: { role, bypass: true } });
23
+ }
24
+ /**
25
+ * Refuses `who` a connection under the backstop: only a tenant App reads through it, because `url` is then the
26
+ * runtime role, which the pinned policy binds, and a read with no tenant set sees no tenant row. A non-tenant App or
27
+ * the Workbench pointed at it would start, paint empty tables and look like a database with no data, so the start
28
+ * refuses instead. `names` narrows it to the connections an App binds.
29
+ */
30
+ export function assertNoBackstop(registry, who, names) {
31
+ const found = registry
32
+ .configs()
33
+ .find((config) => config.backstop === 'rls' && (names === undefined || names.includes(config.name) || names.includes(config.id)));
34
+ if (!found)
35
+ return;
36
+ throw new Error(`connection "${found.name}" is under the row-security backstop ("backstop": "rls"); only a tenant App reads through it — ${who} would see none of its tenant rows. Point it at the owner's URL instead, or remove "backstop".`);
37
+ }
@@ -19,12 +19,33 @@ export declare function declareTenantPool(url: string, pool: {
19
19
  read?: number;
20
20
  write?: number;
21
21
  } | undefined): void;
22
- /** Forget every declared pool: a test's, between hosts. */
22
+ /** Forget every declared pool and backstop: a test's, between hosts. */
23
23
  export declare function forgetTenantPools(): void;
24
+ /**
25
+ * Say that the tenant database on `url` runs under the row-security backstop (docs/postgresql.md): `url` and
26
+ * `replicas` connect as the runtime `role`, `owner` as `ownerRole`, which owns the tables. Declared once enrollment
27
+ * has attested the pair (tenantEnrollment.ts); from then on `tenantAdapter` hands the runtime's adapters the role,
28
+ * and an `'owner'` adapter the owner's own small pool.
29
+ */
30
+ export declare function declareTenantBackstop(url: string, backstop: {
31
+ owner: string;
32
+ role: string;
33
+ ownerRole: string;
34
+ replicas?: readonly string[];
35
+ }): void;
36
+ /** The backstop declared on `url` — the owner's URL and the runtime role the pinned policy binds — or undefined. */
37
+ export declare function tenantBackstop(url: string): Readonly<{
38
+ owner: string;
39
+ role: string;
40
+ }> | undefined;
24
41
  /** The readers of the widest request pool declared, or the process's default: what the arrival gate halves (tenantArrivals.ts). */
25
42
  export declare function tenantRequestReaders(): number;
26
43
  /**
27
44
  * An adapter of the tenant host's on `url`: its own catalog, lanes and stores, the database's one request pool. A
28
45
  * replica's holds its readers only (`replica`): its writers and background writer are never opened.
46
+ *
47
+ * `role`, under a declared backstop (declareTenantBackstop): `'runtime'` runs as the role the pinned policy binds,
48
+ * so a scoped read or write must say its tenant (PostgresAdapterOptions.rowSecurity); `'owner'` runs on the owner's
49
+ * URL and pool, which the policy does not bind, on the primary only. Without a backstop both are today's adapter.
29
50
  */
30
- export declare function tenantAdapter(url: string, label: string, replica?: boolean): PostgresAdapter;
51
+ export declare function tenantAdapter(url: string, label: string, replica?: boolean, role?: 'runtime' | 'owner'): PostgresAdapter;
@@ -14,6 +14,7 @@
14
14
  * Every other holder asks one statement at a time, which a pipelining client sends exactly as before.
15
15
  */
16
16
  import { sharedPostgresAdapter } from '@mistriwork/engine/adapters/postgres.js';
17
+ import { declareBackstopRoles, forgetBackstopRoles } from '@mistriwork/engine/adapters/postgresMaintenance.js';
17
18
  import { poolSizes } from '@mistriwork/engine/adapters/postgresPool.js';
18
19
  const TENANT_REQUEST_POOL = Object.freeze({ pipelineReads: true });
19
20
  /* The `"pool"` of each tenant database's connection, by URL (declareTenantPool): what `tenantAdapter` sizes the shared
@@ -23,9 +24,35 @@ const declared = new Map();
23
24
  export function declareTenantPool(url, pool) {
24
25
  declared.set(url, Object.freeze({ ...pool }));
25
26
  }
26
- /** Forget every declared pool: a test's, between hosts. */
27
+ /** Forget every declared pool and backstop: a test's, between hosts. */
27
28
  export function forgetTenantPools() {
28
29
  declared.clear();
30
+ backstops.clear();
31
+ forgetBackstopRoles();
32
+ }
33
+ /* The owner's pool under the row-security backstop: what crosses tenants by design (a public address resolved, the
34
+ jobs' sweep of every tenant, administration, enrollment's catalog) is a small share of the traffic, and it must
35
+ not take a connection the role's request pool is counting on. */
36
+ const OWNER_POOL = Object.freeze({ read: 2, write: 2 });
37
+ /* Each tenant database's backstop, by its runtime URL and each replica's (declareTenantBackstop). */
38
+ const backstops = new Map();
39
+ /**
40
+ * Say that the tenant database on `url` runs under the row-security backstop (docs/postgresql.md): `url` and
41
+ * `replicas` connect as the runtime `role`, `owner` as `ownerRole`, which owns the tables. Declared once enrollment
42
+ * has attested the pair (tenantEnrollment.ts); from then on `tenantAdapter` hands the runtime's adapters the role,
43
+ * and an `'owner'` adapter the owner's own small pool.
44
+ */
45
+ export function declareTenantBackstop(url, backstop) {
46
+ declareBackstopRoles(backstop.role, backstop.ownerRole);
47
+ const entry = Object.freeze({ owner: backstop.owner, role: backstop.role });
48
+ for (const each of [url, ...(backstop.replicas ?? [])])
49
+ backstops.set(each, entry);
50
+ if (!declared.has(backstop.owner))
51
+ declareTenantPool(backstop.owner, OWNER_POOL);
52
+ }
53
+ /** The backstop declared on `url` — the owner's URL and the runtime role the pinned policy binds — or undefined. */
54
+ export function tenantBackstop(url) {
55
+ return backstops.get(url);
29
56
  }
30
57
  /** The readers and writers the request pool on `url` takes: the connection's `"pool"`, else the process's settings. */
31
58
  function tenantPoolSizes(url) {
@@ -43,8 +70,17 @@ export function tenantRequestReaders() {
43
70
  /**
44
71
  * An adapter of the tenant host's on `url`: its own catalog, lanes and stores, the database's one request pool. A
45
72
  * replica's holds its readers only (`replica`): its writers and background writer are never opened.
73
+ *
74
+ * `role`, under a declared backstop (declareTenantBackstop): `'runtime'` runs as the role the pinned policy binds,
75
+ * so a scoped read or write must say its tenant (PostgresAdapterOptions.rowSecurity); `'owner'` runs on the owner's
76
+ * URL and pool, which the policy does not bind, on the primary only. Without a backstop both are today's adapter.
46
77
  */
47
- export function tenantAdapter(url, label, replica = false) {
78
+ export function tenantAdapter(url, label, replica = false, role = 'runtime') {
79
+ const backstop = backstops.get(url);
80
+ if (backstop && role === 'owner') {
81
+ const owner = tenantPoolSizes(backstop.owner);
82
+ return sharedPostgresAdapter(backstop.owner, label, { ...TENANT_REQUEST_POOL, ...owner }, { rowSecurity: { role: backstop.role, bypass: true } });
83
+ }
48
84
  const { readers, writers } = tenantPoolSizes(url);
49
- return sharedPostgresAdapter(url, label, { ...TENANT_REQUEST_POOL, readers, writers, ...(replica ? { readersOnly: true } : {}) });
85
+ return sharedPostgresAdapter(url, label, { ...TENANT_REQUEST_POOL, readers, writers, ...(replica ? { readersOnly: true } : {}) }, backstop ? { rowSecurity: { role: backstop.role } } : {});
50
86
  }
@@ -20,6 +20,9 @@ type TenantSourceWhere = {
20
20
  readonly replicas?: readonly string[];
21
21
  /** The PostgreSQL source's direct URL for the jobs host's `LISTEN`, when `url` is a transaction-mode pooler's. */
22
22
  readonly listen?: string;
23
+ /** Under the row-security backstop: the URL of the role that owns the tables, while `url` and `replicas` are the
24
+ * runtime role's (docs/postgresql.md). It serves what crosses tenants by design. */
25
+ readonly owner?: string;
23
26
  };
24
27
  export interface TenantEnrollmentOptions<Request> {
25
28
  readonly app: AppDef;
@@ -89,6 +92,11 @@ export declare function captureTenantEnrollment<Request>(value: TenantEnrollment
89
92
  }>;
90
93
  assistant?: AppTenantPolicy['assistant'];
91
94
  };
95
+ /** The backstop's two roles, asked of the primary and of each replica: every one must connect as the same runtime role. */
96
+ export declare function attestBackstopRoles(url: string, owner: string, replicas: readonly string[]): Promise<{
97
+ role: string;
98
+ ownerRole: string;
99
+ }>;
92
100
  export declare function createTenantEnrollment<Request>(input: TenantEnrollmentOptions<Request>): Promise<Readonly<{
93
101
  deployment: Readonly<{
94
102
  availability: (request: Request, selectors: readonly string[], body: unknown, options?: import("./tenantCommands.js").TenantCommandExecutionOptions, guard?: import("./tenantInvocation.js").TenantInvocationGuard) => Promise<import("../commands/commandPayload.js").CommandAvailabilityResult>;
@@ -31,6 +31,8 @@ import { tenantHistoryBinding } from './tenantRecordHistoryStore.js';
31
31
  import { tenantNoticeBinding, tenantNoticeMembers } from './tenantInbox.js';
32
32
  import { assertSqliteTenantStore } from './tenantStore.js';
33
33
  import { assertPostgresTenantStore } from './tenantStorePostgres.js';
34
+ import { assertPostgresRuntimeOwnsNone, attestPostgresBackstopRoles } from './tenantPostgresCatalog.js';
35
+ import { declareTenantBackstop } from './tenantConnections.js';
34
36
  import { keyId, supportAuditKey } from './tenantSupportAuditContract.js';
35
37
  import { membershipRole } from './tenantFeatureMembershipRoles.js';
36
38
  import { openPostgresTenantWriteSource, openSqliteTenantWriteSource } from './tenantWriteSource.js';
@@ -89,7 +91,7 @@ function capture(input) {
89
91
  const source = captureTenantData(raw.source);
90
92
  // One engine per source: an existing SQLite file or a PostgreSQL URL.
91
93
  const postgres = !!source && typeof source === 'object' && Object.hasOwn(source, 'url');
92
- tenantRecord(source, ['id', 'connection', ...(postgres ? ['url', 'replicas', 'listen'] : ['existingPath'])]);
94
+ tenantRecord(source, ['id', 'connection', ...(postgres ? ['url', 'replicas', 'listen', 'owner'] : ['existingPath'])]);
93
95
  tenantIdentifier(source.id);
94
96
  tenantIdentifier(source.connection, 1024);
95
97
  if (postgres) {
@@ -101,6 +103,11 @@ function capture(input) {
101
103
  if (!/^postgres(ql)?:\/\//i.test(source.listen))
102
104
  return denyTenant();
103
105
  }
106
+ if (source.owner !== undefined) {
107
+ tenantIdentifier(source.owner, 32768);
108
+ if (!/^postgres(ql)?:\/\//i.test(source.owner))
109
+ return denyTenant();
110
+ }
104
111
  const replicas = source.replicas;
105
112
  if (replicas !== undefined) {
106
113
  if (!Array.isArray(replicas) || !replicas.length || replicas.length > MAX_REPLICAS || new Set(replicas).size !== replicas.length)
@@ -253,7 +260,7 @@ async function acquire(config, policy) {
253
260
  ? tenantNoticeMembers({ appId: app.id, source: binding.source, deployment, now, reader: () => discovery, accountEmail })
254
261
  : undefined;
255
262
  if (source.url !== undefined) {
256
- ({ reader, writer, discovery } = await acquirePostgres(source.url, attested, pages, now, closes, auditing, members, source.replicas));
263
+ ({ reader, writer, discovery } = await acquirePostgres(source.url, attested, pages, now, closes, auditing, members, source.replicas, source.owner));
257
264
  }
258
265
  else {
259
266
  const existingPath = source.existingPath ?? denyTenant();
@@ -474,9 +481,13 @@ async function acquire(config, policy) {
474
481
  * enrollment attests preprovisioned linked storage too. Each event batch is then
475
482
  * written by the tenant writer's journal, inside the transaction that holds the
476
483
  * tenant/membership fence to COMMIT, exactly as on SQLite. */
477
- async function acquirePostgres(url, attested, pages, now, closes, audit, members, replicas = []) {
484
+ async function acquirePostgres(url, attested, pages, now, closes, audit, members, replicas = [], owner) {
478
485
  const { app, policy, binding } = attested;
479
- const inspector = new PostgresAdapter(url, 'Private tenant enrollment');
486
+ /* Under the row-security backstop (docs/postgresql.md) the roles are attested before anything opens on them, and
487
+ the catalog is read as the owner, which every tenant table belongs to. */
488
+ if (owner !== undefined)
489
+ declareTenantBackstop(url, { owner, ...(await attestBackstopRoles(url, owner, replicas)), replicas });
490
+ const inspector = new PostgresAdapter(owner ?? url, 'Private tenant enrollment');
480
491
  let physicalSchema;
481
492
  try {
482
493
  physicalSchema = await inspector.readSnapshot(async (snapshot) => {
@@ -503,6 +514,8 @@ async function acquirePostgres(url, attested, pages, now, closes, audit, members
503
514
  ownership: policy.ownership,
504
515
  ...(profile === undefined ? {} : { profile }),
505
516
  });
517
+ if (owner !== undefined)
518
+ await onEach([url], (snapshot) => assertPostgresRuntimeOwnsNone(snapshot.client, ownership));
506
519
  /* Only the request reader takes replicas. Discovery answers who is a
507
520
  member, for sign-in and notices: that stays where it was granted. */
508
521
  const reader = await openPostgresTenantReadSource(url, ownership, binding, now, replicas);
@@ -514,6 +527,29 @@ async function acquirePostgres(url, attested, pages, now, closes, audit, members
514
527
  closes.push(discovery.close);
515
528
  return { reader, writer, discovery };
516
529
  }
530
+ /* Run `work` in a read snapshot on each URL in turn, each on its own short-lived adapter: one that names no role, so the
531
+ connection is asked as whatever role its URL connects as. */
532
+ async function onEach(urls, work) {
533
+ const out = [];
534
+ for (const each of urls) {
535
+ const adapter = new PostgresAdapter(each, 'Private tenant backstop');
536
+ try {
537
+ out.push(await adapter.readSnapshot(work));
538
+ }
539
+ finally {
540
+ await adapter.close();
541
+ }
542
+ }
543
+ return out;
544
+ }
545
+ /** The backstop's two roles, asked of the primary and of each replica: every one must connect as the same runtime role. */
546
+ export async function attestBackstopRoles(url, owner, replicas) {
547
+ const [roles] = await onEach([owner], (theirs) => onEach([url, ...replicas], (mine) => attestPostgresBackstopRoles(mine.client, theirs.client)));
548
+ const first = roles[0];
549
+ if (roles.some((each) => each.role !== first.role || each.ownerRole !== first.ownerRole))
550
+ return denyTenant(new Error('The row-security backstop refuses these roles: every replica must connect as the role "url" does.'));
551
+ return first;
552
+ }
517
553
  export async function createTenantEnrollment(input) {
518
554
  try {
519
555
  const config = capture(input);
@@ -34,6 +34,12 @@ export declare function declareTenantAppLive(app: AppDef): void;
34
34
  * pooler gets none, and the hub polls.
35
35
  */
36
36
  export declare function bindTenantLive(adapter: Adapter, ownership: TenantOwnershipSnapshot, url?: string): Promise<void>;
37
+ /**
38
+ * A second writer of the source bound in `bindTenantLive` — the owner's, for the platform realm's commands under the
39
+ * row-security backstop (tenantWriteSource.ts) — records what the first records, into the same store, so the one hub
40
+ * hears its writes too. It opens no hub of its own; `unbindTenantLive` lets it go.
41
+ */
42
+ export declare function shareTenantLive(adapter: Adapter, ownership: TenantOwnershipSnapshot): Promise<void>;
37
43
  /** The writer closed: its hub stops, and its streams end at their next read. */
38
44
  export declare function unbindTenantLive(adapter: Adapter, ownership: Pick<TenantOwnershipSnapshot, 'appId' | 'source'>): Promise<void>;
39
45
  /** The tenant-owned choice tables (bare) whose writes the hub of this ownership hears: empty where it hears none. */