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

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 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.52
6
+
7
+ - **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.
8
+ - **Under that backstop, a table carrying exactly mistri's tenant policy is one the engine still writes to.** The policy is one, pinned: permissive, for every command, for the runtime role alone, comparing the owner column with the setting in both `USING` and `WITH CHECK`. A second policy, a restrictive one, one for another role or command, a changed expression or `FORCE ROW LEVEL SECURITY` where it was not allowed refuses as "a row policy that is not mistri's tenant policy". Without the backstop any row-level security refuses, as before.
9
+ - **A tenant App's catalog check, under the backstop, says what the database must look like around the policy**: each tenant table carries it on its own ownership column, a global or platform table carries none, a view that reaches a tenant table reads as the person reading it (`security_invoker`), there is no materialized view over one and no `SECURITY DEFINER` function in a schema the App maps, and the server is PostgreSQL 15 or later.
10
+ - **The store check can allow a named runtime role** to read and write the store's tables and use its schema: never with grant option, never `CREATE`, never ownership. Without a runtime role the check is what it was.
11
+ - **Test servers take a free port when they start**, so two suites can no longer meet on a fixed one (the race that failed main CI once on rc.51).
12
+
5
13
  ## 1.0.0-rc.51
6
14
 
7
15
  - **A delete refused because the record is still referenced names only the references its principal reads.** Each referencing table is counted under the person's own reads, row policy and tenant fence, and the refusal says how many rows in which table still point at the record (2 records in "invoice" still point at this one) only for rows they can see; where none are theirs it says "This record is in use and can't be deleted." The full count across every tenant goes to the operator's log alone. A tenant App names the App's own table, never the physical one. The answer stays a 409. That a hidden reference exists is still told, as a refusal must; how many, and where, is not.
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.51; the
33
+ These App features ship in mistri 1.0.0-rc.52; 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.51 scope, stable and preview features, current limitations and planned work.
3
+ description: The 1.0.0-rc.52 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.51**, a release candidate. Since rc.2, the first release under the mistri name,
13
+ This site describes **mistri 1.0.0-rc.52**, 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.51" }
174
+ "peerDependencies": { "@mistriwork/mistri": "^1.0.0-rc.52" }
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.51";
4305
+ var li = "1.0.0-rc.52";
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.51", v = u(null), y;
7
+ var _ = "1.0.0-rc.52", 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,
@@ -24,6 +24,14 @@
24
24
  * deterministic collation, except the primary key of a single opaque
25
25
  * text, varchar or uuid identifier. Expression keys and exclusion
26
26
  * constraints refuse: neither says which tenant it compares within.
27
+ * - Under the row-security backstop (TenantRelationOptions.rowSecurity), the
28
+ * database's own second fence, attested: every tenant table carries
29
+ * exactly mistri's tenant policy on its own ownership column, every global
30
+ * and platform table none, no view reaches a tenant table but as the person
31
+ * reading it, and no SECURITY DEFINER function in an App schema reads as
32
+ * someone else. The engine refuses a write to any other shape of policy
33
+ * (postgresScopeCatalog.ts); which table carries it, on which column, is
34
+ * the ownership's to say, so it is said here.
27
35
  */
28
36
  import type { PgQuery } from '@mistriwork/engine/adapters/postgresPool.js';
29
37
  import { type TenantOwnershipSnapshot } from './tenantOwnership.js';
@@ -33,12 +41,19 @@ export declare const tenantCatalogTrust: () => number;
33
41
  /** For a suite whose cases change the catalog and expect the very next read to see it: zero makes every snapshot
34
42
  read the digest, as every snapshot did before the window. Returns what it replaced. */
35
43
  export declare function trustTenantCatalogFor(ms: number): number;
44
+ /** Under the backstop: the runtime role its policies name, and whether FORCE ROW LEVEL SECURITY may be on. */
45
+ export interface TenantRelationOptions {
46
+ readonly rowSecurity?: {
47
+ readonly role: string;
48
+ readonly force?: boolean;
49
+ };
50
+ }
36
51
  /**
37
52
  * Describes the source's mapped relations and checks every ownership column;
38
53
  * returns the description as one comparable string. Call on the source's own
39
54
  * snapshot or writer, after the relations are locked.
40
55
  */
41
- export declare function attestPostgresTenantRelations(client: PgQuery, ownership: TenantOwnershipSnapshot): Promise<string>;
56
+ export declare function attestPostgresTenantRelations(client: PgQuery, ownership: TenantOwnershipSnapshot, options?: TenantRelationOptions): Promise<string>;
42
57
  /** Attest tenant-local business uniqueness; a single opaque primary ID is the
43
58
  * intentional global exception. Type and DDL cannot prove how a host
44
59
  * generates those IDs, so ID generation remains a deployment responsibility. */
@@ -2,6 +2,7 @@ import { postgresCatalogDigestOf } from '@mistriwork/engine/adapters/postgresCat
2
2
  import { denyTenant } from '@mistriwork/engine/server/evidence.js';
3
3
  import { tenantKeyRefusal, tenantUniqueRefusal } from './tenantOwnership.js';
4
4
  import { EPOCHLESS_TTL_MS } from '@mistriwork/engine/adapters/postgresSchemaEpoch.js';
5
+ import { TENANT_POLICY, TENANT_POLICY_TAIL } from '@mistriwork/engine/adapters/scoped/postgresScopeCatalog.js';
5
6
  let catalogTrust = EPOCHLESS_TTL_MS;
6
7
  /** How long a tenant read source's catalog attestation stands before a snapshot reads the digest again
7
8
  (tenantReadSource.ts, tenantPlatformSource.ts): what a source opened without saying takes. */
@@ -26,13 +27,100 @@ const targets = (ids) => {
26
27
  const at = ids.map(located);
27
28
  return [ids, at.map((value) => value.schema), at.map((value) => value.name)];
28
29
  };
30
+ /* PostgreSQL 15 is the first with a view's `security_invoker`, without which a view reads its tables as its owner. */
31
+ const BACKSTOP_VERSION = 150000;
32
+ /* What PostgreSQL's parse_bool reads as true, as a reloption may be spelt (`security_invoker`, `=on`, `=1`). */
33
+ const TRUE_OPTION = /^(t|tr|tru|true|y|ye|yes|on|1)$/i;
34
+ const invoker = (options) => (options ?? []).some((option) => option.startsWith('security_invoker=') && TRUE_OPTION.test(option.slice('security_invoker='.length)));
35
+ /**
36
+ * The backstop's reads, appended to the description so that it costs no round trip: each relation's policies as
37
+ * deparsed (and which column each compares, matched as the engine matches it), the server version, every view that
38
+ * reaches a tenant table through other views, and the SECURITY DEFINER functions in the schemas the App maps.
39
+ * `$4` is the tenant tables' ids, `$5` the expression's tail.
40
+ */
41
+ const BACKSTOP_COLUMNS = `,
42
+ COALESCE((SELECT json_agg(json_build_object('name', p.polname, 'cmd', p.polcmd, 'permissive', p.polpermissive,
43
+ 'roles', (SELECT json_agg(CASE WHEN r.oid = 0 THEN NULL ELSE ro.rolname END ORDER BY r.ord)
44
+ FROM unnest(p.polroles) WITH ORDINALITY AS r(oid, ord) LEFT JOIN pg_catalog.pg_roles ro ON ro.oid = r.oid),
45
+ 'qual', pg_catalog.pg_get_expr(p.polqual, p.polrelid), 'check', pg_catalog.pg_get_expr(p.polwithcheck, p.polrelid),
46
+ 'column', (SELECT a.attname FROM pg_catalog.pg_attribute a
47
+ CROSS JOIN LATERAL (SELECT CASE a.atttypid
48
+ WHEN 25::oid THEN '(' || pg_catalog.quote_ident(a.attname) || $5::text
49
+ WHEN 1043::oid THEN '((' || pg_catalog.quote_ident(a.attname) || ')::text' || $5::text END AS said) AS e
50
+ WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
51
+ AND pg_catalog.pg_get_expr(p.polqual, p.polrelid) = e.said AND pg_catalog.pg_get_expr(p.polwithcheck, p.polrelid) = e.said
52
+ LIMIT 1))
53
+ ORDER BY p.polname)
54
+ FROM pg_catalog.pg_policy p WHERE p.polrelid = c.oid), '[]'::json) AS policy_detail,
55
+ (SELECT pg_catalog.current_setting('server_version_num')::int) AS version,
56
+ (WITH RECURSIVE tenant AS (
57
+ SELECT tc.oid FROM unnest($4::text[]) AS t(id)
58
+ JOIN pg_catalog.pg_namespace tn ON tn.nspname = split_part(t.id, '.', 1)
59
+ JOIN pg_catalog.pg_class tc ON tc.relnamespace = tn.oid AND tc.relname = substr(t.id, length(split_part(t.id, '.', 1)) + 2)),
60
+ -- A view's query is its rewrite rule, which depends on every relation the query reads.
61
+ over(oid) AS (
62
+ SELECT r.ev_class FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_rewrite r ON r.oid = d.objid
63
+ WHERE d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.refclassid = 'pg_catalog.pg_class'::regclass
64
+ AND d.refobjid IN (SELECT oid FROM tenant) AND r.ev_class <> d.refobjid
65
+ UNION
66
+ SELECT r.ev_class FROM over o JOIN pg_catalog.pg_depend d ON d.refobjid = o.oid
67
+ JOIN pg_catalog.pg_rewrite r ON r.oid = d.objid
68
+ WHERE d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.refclassid = 'pg_catalog.pg_class'::regclass AND r.ev_class <> o.oid)
69
+ SELECT COALESCE(json_agg(json_build_object('id', vn.nspname || '.' || v.relname, 'kind', v.relkind, 'options', v.reloptions)
70
+ ORDER BY vn.nspname, v.relname), '[]'::json)
71
+ FROM over JOIN pg_catalog.pg_class v ON v.oid = over.oid JOIN pg_catalog.pg_namespace vn ON vn.oid = v.relnamespace) AS views,
72
+ (SELECT COALESCE(json_agg(fn.nspname || '.' || f.proname ORDER BY fn.nspname, f.proname), '[]'::json)
73
+ FROM pg_catalog.pg_proc f JOIN pg_catalog.pg_namespace fn ON fn.oid = f.pronamespace
74
+ WHERE f.prosecdef AND fn.nspname = ANY ($2::text[])) AS definers`;
75
+ /** Under the backstop, what the database must say beside the description; refuses where it says anything else. */
76
+ function attestBackstop(rows, ownership, security) {
77
+ // Nothing mapped, nothing to fence: the server-wide reads ride on a relation's row.
78
+ const first = rows[0];
79
+ if (!first)
80
+ return;
81
+ if (typeof first.version !== 'number' || first.version < BACKSTOP_VERSION)
82
+ return denyTenant();
83
+ if (!Array.isArray(first.definers) || first.definers.length)
84
+ return denyTenant();
85
+ if (!Array.isArray(first.views) || first.views.some((view) => view.kind !== 'v' || !invoker(view.options)))
86
+ return denyTenant();
87
+ const described = new Map(rows.map((row) => [row.id, row]));
88
+ for (const [logical, rule] of Object.entries(ownership.ownership)) {
89
+ const row = described.get(ownership.resources[logical]);
90
+ if (!row || !Array.isArray(row.policy_detail))
91
+ return denyTenant();
92
+ if (rule.kind !== 'tenant') {
93
+ if (row.rls || row.force || row.policies !== 0 || row.policy_detail.length)
94
+ return denyTenant();
95
+ continue;
96
+ }
97
+ const [policy, ...others] = row.policy_detail;
98
+ if (!row.rls ||
99
+ (row.force && security.force !== true) ||
100
+ row.policies !== 1 ||
101
+ others.length ||
102
+ !policy ||
103
+ policy.name !== TENANT_POLICY ||
104
+ policy.cmd !== '*' ||
105
+ policy.permissive !== true ||
106
+ !Array.isArray(policy.roles) ||
107
+ policy.roles.length !== 1 ||
108
+ policy.roles[0] !== security.role ||
109
+ policy.column !== rule.column)
110
+ return denyTenant();
111
+ }
112
+ }
29
113
  /**
30
114
  * Describes the source's mapped relations and checks every ownership column;
31
115
  * returns the description as one comparable string. Call on the source's own
32
116
  * snapshot or writer, after the relations are locked.
33
117
  */
34
- export async function attestPostgresTenantRelations(client, ownership) {
118
+ export async function attestPostgresTenantRelations(client, ownership, options = {}) {
35
119
  const ids = [...new Set(Object.values(ownership.resources))].sort(byCodeUnit);
120
+ const security = options.rowSecurity;
121
+ const tenantIds = Object.entries(ownership.ownership)
122
+ .filter(([, rule]) => rule.kind === 'tenant')
123
+ .map(([logical]) => ownership.resources[logical]);
36
124
  const rows = (await client.query(`SELECT w.id, c.relkind::text AS kind, COALESCE(c.relrowsecurity, false) AS rls, COALESCE(c.relforcerowsecurity, false) AS force,
37
125
  COALESCE((SELECT json_agg(json_build_object('name', a.attname, 'type', pg_catalog.format_type(a.atttypid, a.atttypmod),
38
126
  'notnull', a.attnotnull, 'collation', l.collname, 'deterministic', l.collisdeterministic,
@@ -48,10 +136,10 @@ export async function attestPostgresTenantRelations(client, ownership) {
48
136
  FROM pg_catalog.pg_index i WHERE i.indrelid = c.oid), '[]'::json) AS indexes,
49
137
  (SELECT count(*) FROM pg_catalog.pg_trigger t WHERE t.tgrelid = c.oid AND NOT t.tgisinternal)::int AS triggers,
50
138
  (SELECT count(*) FROM pg_catalog.pg_rewrite r WHERE r.ev_class = c.oid)::int AS rules,
51
- (SELECT count(*) FROM pg_catalog.pg_policy p WHERE p.polrelid = c.oid)::int AS policies
139
+ (SELECT count(*) FROM pg_catalog.pg_policy p WHERE p.polrelid = c.oid)::int AS policies${security ? BACKSTOP_COLUMNS : ''}
52
140
  FROM unnest($1::text[], $2::text[], $3::text[]) AS w(id, schema, name)
53
141
  LEFT JOIN pg_catalog.pg_namespace n ON n.nspname = w.schema
54
- LEFT JOIN pg_catalog.pg_class c ON c.relnamespace = n.oid AND c.relname = w.name`, targets(ids))).rows;
142
+ LEFT JOIN pg_catalog.pg_class c ON c.relnamespace = n.oid AND c.relname = w.name`, security ? [...targets(ids), tenantIds, TENANT_POLICY_TAIL] : targets(ids))).rows;
55
143
  if (rows.length !== ids.length || rows.some((row) => typeof row.kind !== 'string' || !Array.isArray(row.columns)))
56
144
  return denyTenant();
57
145
  const described = new Map(rows.map((row) => [row.id, row]));
@@ -62,6 +150,8 @@ export async function attestPostgresTenantRelations(client, ownership) {
62
150
  if (!column || column.deterministic !== true || !/^(text|character varying(\(\d+\))?)$/.test(column.type))
63
151
  return denyTenant();
64
152
  }
153
+ if (security)
154
+ attestBackstop(rows, ownership, security);
65
155
  return JSON.stringify(rows
66
156
  .map((row) => ({ ...row, constraints: [...row.constraints].sort(byCodeUnit), indexes: [...row.indexes].sort(byCodeUnit) }))
67
157
  .sort((a, b) => byCodeUnit(a.id, b.id)));