@mistriwork/mistri 1.0.0-rc.50 → 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 +17 -0
- package/README.md +1 -1
- package/dist/docs/status.md +3 -3
- package/dist/embed/react/headless.js +1 -1
- package/dist/embed/react/index.js +1 -1
- package/dist/server/app/appErrors.js +6 -0
- package/dist/server/commands/businessCommandExecution.js +6 -1
- package/dist/server/http/handler.js +6 -2
- package/dist/server/recordActivity.js +2 -1
- package/dist/server/recordHistory.d.ts +5 -1
- package/dist/server/recordHistory.js +3 -0
- package/dist/server/tenant/tenantHttp.js +4 -3
- package/dist/server/tenant/tenantPostgresCatalog.d.ts +16 -1
- package/dist/server/tenant/tenantPostgresCatalog.js +93 -3
- package/dist/server/tenant/tenantRecordHistoryStore.d.ts +7 -0
- package/dist/server/tenant/tenantRecordHistoryStore.js +11 -0
- package/dist/server/tenant/tenantWriteFault.d.ts +2 -1
- package/dist/server/tenant/tenantWriteFault.js +8 -3
- package/dist/server/tenant/tenantWriteSource.js +17 -2
- package/dist/ssr/render.js +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,23 @@
|
|
|
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
|
+
|
|
13
|
+
## 1.0.0-rc.51
|
|
14
|
+
|
|
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.
|
|
16
|
+
- **A key already taken names its field only where the row it met is one the writer reads.** Under a row policy or a tenant fence, a unique value held by a row outside the writer's reach is refused as a generic forbidden write, not `duplicate_value`, so a form is no way to learn another tenant's emails or numbers. A command that met such a row answered 503 `temporarily_unavailable`, inviting a retry that could never succeed; it now answers 403 `forbidden`. A tenant's own table whose unique index includes the owner column still says which field is taken, as before.
|
|
17
|
+
- **A member no longer reads the change history of a table shared by every tenant.** A global or platform table's history, its record flows and its place in an activity feed answer a tenant member as a missing record does (404), whether or not the record exists. The platform realm reads them as before.
|
|
18
|
+
- **Section conditions, board lanes, imports and references are tested across tenants**: a lane value only another tenant holds adds no lane or count, an import's refusal is the same for a key taken in this tenant and in another, and a reference to another tenant's record reads as nowhere.
|
|
19
|
+
- **Every route, source method and declared table of a tenant App is checked across tenants by one generated test**, and a route, method or table added without a case fails it, naming what is missing. Each declared resource is read through every read path as two tenants, and each sees its own rows alone (a global table: all of them).
|
|
20
|
+
- **The combination proof re-introduces the rollup that let a tenant condition through in rc.49**, and the cross-tenant fixture goes red on it, so the fixture is held to catching that class of defect.
|
|
21
|
+
|
|
5
22
|
## 1.0.0-rc.50
|
|
6
23
|
|
|
7
24
|
- **A command links to a public view with `ctx.publicLink(view)`.** It names a public form, a public page or a list the public grant reads, and is refused at the call, naming the view, for any other. The receipt and the outbox keep the view's name; the answer and a delivered effect say the URL, read when it is sent: the App's own address, or in a tenant App the tenant's host with its current intake or public address as `?via=`, so an address rotated after the command ran is never sent. With no address known an answer keeps the reference and an effect is not delivered, as a capability link's. The view's address follows the one rule the browser's `useNavigate().publicLink(view)` uses.
|
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.
|
|
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`).
|
package/dist/docs/status.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Status & roadmap
|
|
3
|
-
description: The 1.0.0-rc.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Refusal, WriteConflict } from '@mistriwork/engine/adapters/adapter.js';
|
|
2
2
|
import { PathError } from '@mistriwork/engine/shared/view.js';
|
|
3
|
+
import { referencedBeneath } from '@mistriwork/engine/adapters/scoped/scopedTransaction.js';
|
|
3
4
|
import { AppAccessDenied } from './appAccess.js';
|
|
4
5
|
import { ReadAuditFailed } from '../readAudit.js';
|
|
5
6
|
import { AppValidationDenied, ConsumesRefused } from './appValidationDenied.js';
|
|
@@ -21,6 +22,11 @@ caption) {
|
|
|
21
22
|
return { code: 'forbidden', message: error.message };
|
|
22
23
|
if (error instanceof WriteConflict)
|
|
23
24
|
return { code: 'record_conflict', message: error.message };
|
|
25
|
+
/* A delete a row policy refused while rows still point at it: named by what the principal reads of them, or
|
|
26
|
+
by nothing when it reads none (scopedTransaction.ts ReferencedRefusal), so the sentence is said as it stands. */
|
|
27
|
+
const referenced = referencedBeneath(error);
|
|
28
|
+
if (referenced)
|
|
29
|
+
return { code: 'reference_conflict', message: referenced.message };
|
|
24
30
|
if (error instanceof Refusal || error instanceof PathError) {
|
|
25
31
|
if (error instanceof AppValidationDenied && operation === 'write' && error.fields.length) {
|
|
26
32
|
return {
|
|
@@ -11,7 +11,7 @@ import { AUDIT_PART_ENTRIES, AUDIT_TARGET_ENTRIES, COMMAND_TARGET_BOUNDS } from
|
|
|
11
11
|
import { scopedAudit, splitAudit } from '../../adapters/commands/commandAuditParts.js';
|
|
12
12
|
import { EffectBodyTooLarge, EffectProjectionRefused } from '../../adapters/events/commandEventTypes.js';
|
|
13
13
|
import { snapshotScopedData } from '@mistriwork/engine/adapters/scoped/scopedReads.js';
|
|
14
|
-
import { ScopeRefusal } from '@mistriwork/engine/adapters/scoped/scopedTransaction.js';
|
|
14
|
+
import { referencedBeneath, ScopeRefusal } from '@mistriwork/engine/adapters/scoped/scopedTransaction.js';
|
|
15
15
|
import { lockTimedOut } from '@mistriwork/engine/adapters/writeLanes.js';
|
|
16
16
|
import { AppAccessDenied } from '../app/appAccess.js';
|
|
17
17
|
import { NarrowedRefusal } from '../app/appNarrowedWrites.js';
|
|
@@ -1627,6 +1627,11 @@ async function executeUntraced(binding, actor, rawRequest, options = {}) {
|
|
|
1627
1627
|
/* The row scope's own refusal is permanent for this request: said as forbidden, which names no row and no value,
|
|
1628
1628
|
where it fell through to temporarily_unavailable and sent a caller, a job or a workflow round a retry that
|
|
1629
1629
|
could never succeed. */
|
|
1630
|
+
/* A delete refused while rows still point at it is the record's state, not the caller's grants: said in its own
|
|
1631
|
+
sentence, which names only the rows the caller reads, or none (scopedTransaction.ts ReferencedRefusal). */
|
|
1632
|
+
const referenced = referencedBeneath(cause);
|
|
1633
|
+
if (referenced)
|
|
1634
|
+
throw recordRefusalCause(new BusinessCommandExecutionError('ineligible_state', outcome, undefined, undefined, referenced.message), cause);
|
|
1630
1635
|
if (cause instanceof ScopeRefusal)
|
|
1631
1636
|
throw recordRefusalCause(new BusinessCommandExecutionError('forbidden', outcome), cause);
|
|
1632
1637
|
if (cause instanceof CommandInputError)
|
|
@@ -42,6 +42,7 @@ import { isRowPolicyApp, isTenantApp } from '../../shared/app.js';
|
|
|
42
42
|
import { catalogLocales, requestLocale, unvaryOnLanguage } from '../app/readerLocale.js';
|
|
43
43
|
import { accountOf } from '../app/appStamps.js';
|
|
44
44
|
import { attributeWrites } from '@mistriwork/engine/adapters/writeAttribution.js';
|
|
45
|
+
import { referencedBeneath } from '@mistriwork/engine/adapters/scoped/scopedTransaction.js';
|
|
45
46
|
import { AppAccessDenied } from '@mistriwork/engine/server/columnGrants.js';
|
|
46
47
|
import { httpRowPolicyAllows } from '../policy/appPolicyHttp.js';
|
|
47
48
|
import { writeFailureOutcome, writeRefusalStatus } from '@mistriwork/engine/server/constraints.js';
|
|
@@ -493,11 +494,14 @@ async function underPolicy(ctx, routes) {
|
|
|
493
494
|
const broke = error instanceof Refusal ? refusalCause(error) : error;
|
|
494
495
|
const refusedBy = rejected && !conflict && !denied ? writeRefusalStatus(broke) : undefined;
|
|
495
496
|
const { code, errcode, severity } = (refusedBy ? broke : {});
|
|
496
|
-
|
|
497
|
+
/* A delete refused while rows still point at it (scopedTransaction.ts ReferencedRefusal) says only the rows
|
|
498
|
+
the principal reads, or nothing, so its own sentence is the answer, by the code the database's would be. */
|
|
499
|
+
const referenced = rejected && !conflict && !denied && !refusedBy ? referencedBeneath(error) : undefined;
|
|
500
|
+
const said = refusedBy ? appError({ code, errcode, severity }, 'write') : referenced && appError(referenced, 'write');
|
|
497
501
|
const failure = said ? { code: said.code, message: said.message } : refused;
|
|
498
502
|
// A body past its ceiling is too large, not a refusal of the change: the client can shrink it.
|
|
499
503
|
const tooLarge = error instanceof HttpError && error.status === 413;
|
|
500
|
-
const status = tooLarge ? 413 : denied ? 403 : conflict ? 409 : (refusedBy ?? (rejected ? 400 : 200));
|
|
504
|
+
const status = tooLarge ? 413 : denied ? 403 : conflict ? 409 : (refusedBy ?? (referenced ? 409 : rejected ? 400 : 200));
|
|
501
505
|
const cause = reportRefusal(req, rejected ? status : 503, failure.code, failure.message, error);
|
|
502
506
|
/* One refusal body for every route: the code and message at the top, as a command's say them, and errors[]
|
|
503
507
|
for the readers of a write's per-field list. */
|
|
@@ -141,7 +141,8 @@ export async function readRecordActivityFor(options) {
|
|
|
141
141
|
const kept = historyRules(app, options.pages);
|
|
142
142
|
/* The section's resources the reader's catalog holds: one their grant leaves out has no feed for them. */
|
|
143
143
|
const resources = Object.keys(section.resources ?? {}).flatMap((resource) => {
|
|
144
|
-
|
|
144
|
+
// A resource whose changes the reader's context may not read (record history's `storeKey.holds`) has no feed for them.
|
|
145
|
+
const table = kept.has(resource) && (options.storeKey?.holds(resource) ?? true) ? findTable(schema, resource) : undefined;
|
|
145
146
|
return table
|
|
146
147
|
? [{ resource, table, physical: options.mapping.toPhysical(resource), connection: options.mapping.connectionFor(resource) }]
|
|
147
148
|
: [];
|
|
@@ -104,8 +104,12 @@ export declare function projectFields(changes: readonly StoredChange[], table: {
|
|
|
104
104
|
export declare function exactKey(schema: DatabaseSchema, table: string, raw: unknown): Record<string, string | number>;
|
|
105
105
|
/** The key a record's changes are kept under, where it is more than the
|
|
106
106
|
* record's key: a tenant App's (tenant/tenantRecordHistoryStore.ts). `read`
|
|
107
|
-
* names the columns the record's read must also return for `key` to say it.
|
|
107
|
+
* names the columns the record's read must also return for `key` to say it.
|
|
108
|
+
* `holds` is false for a table whose stored changes cannot be told apart by
|
|
109
|
+
* whose they are, in a context that may read only its own: its history is
|
|
110
|
+
* closed there, as a record with none is. */
|
|
108
111
|
export interface RecordHistoryStoreKey {
|
|
112
|
+
holds(table: string): boolean;
|
|
109
113
|
read(table: string): string[];
|
|
110
114
|
key(table: string, key: Record<string, string | number>, row: Record<string, unknown>): Record<string, unknown>;
|
|
111
115
|
}
|
|
@@ -281,6 +281,9 @@ export async function readRecordHistoryFor(options) {
|
|
|
281
281
|
// Only a resource whose page shows a history keeps one; the rest have none to read.
|
|
282
282
|
if (!historyRules(app, options.pages).has(table) || !findTable(schema, table))
|
|
283
283
|
throw new AppAccessDenied();
|
|
284
|
+
// Asked before the record is read, so a record that exists and one that does not answer alike.
|
|
285
|
+
if (options.storeKey && !options.storeKey.holds(table))
|
|
286
|
+
throw new AppAccessDenied();
|
|
284
287
|
const key = exactKey(schema, table, options.key);
|
|
285
288
|
const limit = options.limit === undefined ? 20 : options.limit;
|
|
286
289
|
if (typeof limit !== 'number' || !Number.isSafeInteger(limit) || limit < 1 || limit > RECORD_HISTORY_PAGE)
|
|
@@ -1161,9 +1161,10 @@ export function createTenantHttpServer(options) {
|
|
|
1161
1161
|
}
|
|
1162
1162
|
if (path === '/api/record-activity') {
|
|
1163
1163
|
/* A dashboard's feed. In a tenant's context the store reads that
|
|
1164
|
-
tenant's rows of its tenant-owned resources alone
|
|
1165
|
-
|
|
1166
|
-
|
|
1164
|
+
tenant's rows of its tenant-owned resources alone, so no other
|
|
1165
|
+
tenant's writes crowd it or reach it (a global or platform
|
|
1166
|
+
resource's changes say no tenant, and are no member's feed);
|
|
1167
|
+
each record a row names is then read in this context, under
|
|
1167
1168
|
the owner this context is, before anything about it is said.
|
|
1168
1169
|
The platform realm's feed spans tenants, each record read as
|
|
1169
1170
|
the platform realm reads it (tenantRecordHistoryStore.ts). */
|
|
@@ -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)));
|
|
@@ -38,8 +38,15 @@ export declare function bindTenantRecordHistoryStore(adapter: object, binding: R
|
|
|
38
38
|
* context (a member's, or a support operator's inside it), or the platform
|
|
39
39
|
* realm's when `tenantId` is undefined. `read` is what the visibility read
|
|
40
40
|
* must also return: the owner column, where only the row can say whose it is.
|
|
41
|
+
*
|
|
42
|
+
* Only a tenant-owned table's entries say whose they are. A global or
|
|
43
|
+
* platform table's are kept under the record's key alone, and the store keeps
|
|
44
|
+
* no tenant beside them, so nothing could tell a member which entries were
|
|
45
|
+
* made inside their tenant: such a table's history is closed in a tenant's
|
|
46
|
+
* context (`holds`), as a record with none is, and open to the platform realm.
|
|
41
47
|
*/
|
|
42
48
|
export declare function tenantHistoryStoreKey(ownership: TenantOwnershipSnapshot, tenantId: string | undefined): Readonly<{
|
|
49
|
+
holds: (table: string) => boolean;
|
|
43
50
|
read: (table: string) => string[];
|
|
44
51
|
key: (table: string, key: Readonly<Record<string, string | number>>, row: Readonly<Record<string, unknown>>) => Record<string, unknown>;
|
|
45
52
|
}>;
|
|
@@ -27,6 +27,7 @@ import { storesOf } from '../stores/appStores.js';
|
|
|
27
27
|
import { historyRules, withBookkeeping } from '../recordHistory.js';
|
|
28
28
|
import { findTable } from '@mistriwork/engine/shared/schema.js';
|
|
29
29
|
import { denyTenant } from '@mistriwork/engine/server/evidence.js';
|
|
30
|
+
import { AppAccessDenied } from '../app/appAccess.js';
|
|
30
31
|
/** The App's history tables, by the physical id the writer is asked them by, each tenant-owned one with its owner column. */
|
|
31
32
|
export function tenantHistoryBinding(app, pages, ownership) {
|
|
32
33
|
const binding = new Map();
|
|
@@ -66,15 +67,25 @@ adapter, binding, dialect) {
|
|
|
66
67
|
* context (a member's, or a support operator's inside it), or the platform
|
|
67
68
|
* realm's when `tenantId` is undefined. `read` is what the visibility read
|
|
68
69
|
* must also return: the owner column, where only the row can say whose it is.
|
|
70
|
+
*
|
|
71
|
+
* Only a tenant-owned table's entries say whose they are. A global or
|
|
72
|
+
* platform table's are kept under the record's key alone, and the store keeps
|
|
73
|
+
* no tenant beside them, so nothing could tell a member which entries were
|
|
74
|
+
* made inside their tenant: such a table's history is closed in a tenant's
|
|
75
|
+
* context (`holds`), as a record with none is, and open to the platform realm.
|
|
69
76
|
*/
|
|
70
77
|
export function tenantHistoryStoreKey(ownership, tenantId) {
|
|
78
|
+
const holds = (table) => tenantId === undefined || ownership.ownership[table]?.kind === 'tenant';
|
|
71
79
|
return Object.freeze({
|
|
80
|
+
holds,
|
|
72
81
|
read: (table) => {
|
|
73
82
|
const rule = ownership.ownership[table];
|
|
74
83
|
return rule?.kind === 'tenant' && tenantId === undefined ? [rule.column] : [];
|
|
75
84
|
},
|
|
76
85
|
key: (table, key, row) => {
|
|
77
86
|
const rule = ownership.ownership[table];
|
|
87
|
+
if (!holds(table))
|
|
88
|
+
throw new AppAccessDenied();
|
|
78
89
|
if (rule?.kind !== 'tenant')
|
|
79
90
|
return { ...key };
|
|
80
91
|
const owner = tenantId ?? row[rule.column];
|
|
@@ -13,7 +13,8 @@ export declare function unansweredWrite(path: string, error?: unknown): {
|
|
|
13
13
|
* fixed sentence that names no column: the engine's own names are physical, the tenant's column among them, and its
|
|
14
14
|
* detail carries values. A key is global while rows are a tenant's, so an id another tenant holds is refused exactly
|
|
15
15
|
* as one this tenant holds, word for word: the reply is chosen by the SQLSTATE alone, and says nothing more of whose
|
|
16
|
-
* row it met.
|
|
16
|
+
* row it met. A delete refused for the rows still pointing at it is answered the same way, by reference_conflict.
|
|
17
|
+
* Undefined for anything else, and for a denial on the way down, which stays a denial.
|
|
17
18
|
*/
|
|
18
19
|
export declare function refusedWrite(path: string, error: unknown): {
|
|
19
20
|
status: 409 | 422;
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* the way down stays a denial.
|
|
11
11
|
*/
|
|
12
12
|
import { POOL_BUSY_MESSAGE, PoolBusy } from '@mistriwork/engine/adapters/poolMetrics.js';
|
|
13
|
+
import { ReferencedRefusal } from '@mistriwork/engine/adapters/scoped/scopedTransaction.js';
|
|
13
14
|
import { refusalCause } from '@mistriwork/engine/shared/refusal.js';
|
|
14
15
|
import { writeRefusalStatus } from '@mistriwork/engine/server/constraints.js';
|
|
15
16
|
import { TenantContextError, TenantUnavailableError } from '@mistriwork/engine/server/evidence.js';
|
|
@@ -53,16 +54,20 @@ export function unansweredWrite(path, error) {
|
|
|
53
54
|
* fixed sentence that names no column: the engine's own names are physical, the tenant's column among them, and its
|
|
54
55
|
* detail carries values. A key is global while rows are a tenant's, so an id another tenant holds is refused exactly
|
|
55
56
|
* as one this tenant holds, word for word: the reply is chosen by the SQLSTATE alone, and says nothing more of whose
|
|
56
|
-
* row it met.
|
|
57
|
+
* row it met. A delete refused for the rows still pointing at it is answered the same way, by reference_conflict.
|
|
58
|
+
* Undefined for anything else, and for a denial on the way down, which stays a denial.
|
|
57
59
|
*/
|
|
58
60
|
export function refusedWrite(path, error) {
|
|
59
61
|
let at = error;
|
|
60
62
|
for (let depth = 0; at !== null && typeof at === 'object' && depth < 16; depth++) {
|
|
61
|
-
|
|
63
|
+
/* A delete refused while rows still point at it (scopedTransaction.ts ReferencedRefusal): its sentence names
|
|
64
|
+
only the rows this tenant reads, or nothing, so it is said as it stands. */
|
|
65
|
+
const referenced = at instanceof ReferencedRefusal;
|
|
66
|
+
const status = referenced ? 409 : writeRefusalStatus(at);
|
|
62
67
|
if (status) {
|
|
63
68
|
// Its codes and nothing else: no column, constraint or detail reaches appError, so it says the fixed sentence.
|
|
64
69
|
const { code, errcode, severity } = at;
|
|
65
|
-
const failure = appError({ code, errcode, severity }, 'write');
|
|
70
|
+
const failure = referenced ? appError(at, 'write') : appError({ code, errcode, severity }, 'write');
|
|
66
71
|
return {
|
|
67
72
|
status,
|
|
68
73
|
code: failure.code,
|
|
@@ -27,12 +27,25 @@ import { bindTenantLive, unbindTenantLive } from './tenantLive.js';
|
|
|
27
27
|
import { appStoresOf } from '../stores/appStores.js';
|
|
28
28
|
import { assertInboxMark } from '../../adapters/inbox/inbox.js';
|
|
29
29
|
import { physicalRowScope } from './tenantReadScope.js';
|
|
30
|
+
import { ReferencedRefusal } from '@mistriwork/engine/adapters/scoped/scopedTransaction.js';
|
|
31
|
+
import { recordRefusalCause, refusalCause } from '@mistriwork/engine/shared/refusal.js';
|
|
30
32
|
import { bindTenantInboxStore } from './tenantInbox.js';
|
|
31
33
|
import { bindTenantBrandingStore } from './tenantBrandingStore.js';
|
|
32
34
|
import { bindTenantReadAuditStore } from './tenantReadAudit.js';
|
|
33
35
|
import { assertReadAuditRow } from '../../adapters/readAudit/readAudit.js';
|
|
34
36
|
import { groupCommit } from '../../adapters/readAudit/groupCommit.js';
|
|
35
37
|
import { assertBrandingWrite } from '../../adapters/branding/branding.js';
|
|
38
|
+
/* A delete still referenced is refused by the engine under the physical table it counted (scopedTransaction.ts
|
|
39
|
+
ReferencedRefusal). A member hears the App's name for that table, or no table at all where the App has none. */
|
|
40
|
+
function logicalReferences(physical) {
|
|
41
|
+
const logical = new Map([...physical].map(([name, table]) => [table, name]));
|
|
42
|
+
return (error) => {
|
|
43
|
+
if (!(error instanceof ReferencedRefusal) || !error.seen)
|
|
44
|
+
throw error;
|
|
45
|
+
const table = logical.get(error.seen.table);
|
|
46
|
+
throw recordRefusalCause(new ReferencedRefusal(table ? { table, count: error.seen.count } : undefined), refusalCause(error) ?? error);
|
|
47
|
+
};
|
|
48
|
+
}
|
|
36
49
|
/* A writer an uncertain outcome closed is reopening itself (tenantWriterLifecycle.ts). What it turns away meanwhile
|
|
37
50
|
decided nothing about the person, so it is said as the database not answering, a 503 to try again, as /readyz says
|
|
38
51
|
it: not as a denial, which told a person mid-edit they could not edit the record. */
|
|
@@ -257,6 +270,7 @@ export async function openSqliteTenantWriteSource(existingPath, ownership, store
|
|
|
257
270
|
const physical = new Map(Object.entries(owned.resources));
|
|
258
271
|
const ids = new Set(physical.values());
|
|
259
272
|
const toPhysical = (logical) => physical.get(logical) ?? denyTenant();
|
|
273
|
+
const said = logicalReferences(physical);
|
|
260
274
|
// A snapshot, so every write's composition with it is kept (tenantReadScope.ts).
|
|
261
275
|
const allTrue = snapshotRowScope(owned.schema, Object.fromEntries([...physical.keys()].map((id) => [id, true])));
|
|
262
276
|
let baseline;
|
|
@@ -451,7 +465,7 @@ export async function openSqliteTenantWriteSource(existingPath, ownership, store
|
|
|
451
465
|
: {}),
|
|
452
466
|
insert: (request) => records.insert({ ...request, table: toPhysical(request.table) }),
|
|
453
467
|
update: (request) => records.update({ ...request, table: toPhysical(request.table) }),
|
|
454
|
-
remove: (request) => records.remove({ ...request, table: toPhysical(request.table) }),
|
|
468
|
+
remove: (request) => records.remove({ ...request, table: toPhysical(request.table) }).catch(said),
|
|
455
469
|
...(records.tell ? { tell: (request) => records.tell({ ...request, table: toPhysical(request.table) }) } : {}),
|
|
456
470
|
...(records.noted
|
|
457
471
|
? { noted: (request) => records.noted({ ...request, table: toPhysical(request.table) }) }
|
|
@@ -607,6 +621,7 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
|
|
|
607
621
|
const physical = new Map(Object.entries(owned.resources));
|
|
608
622
|
const ids = new Set(physical.values());
|
|
609
623
|
const toPhysical = (logical) => physical.get(logical) ?? denyTenant();
|
|
624
|
+
const said = logicalReferences(physical);
|
|
610
625
|
// A snapshot, so every write's composition with it is kept (tenantReadScope.ts).
|
|
611
626
|
const allTrue = snapshotRowScope(owned.schema, Object.fromEntries([...physical.keys()].map((id) => [id, true])));
|
|
612
627
|
let baseline;
|
|
@@ -823,7 +838,7 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
|
|
|
823
838
|
},
|
|
824
839
|
remove: (request) => {
|
|
825
840
|
live();
|
|
826
|
-
return records.remove({ ...request, table: toPhysical(request.table) });
|
|
841
|
+
return records.remove({ ...request, table: toPhysical(request.table) }).catch(said);
|
|
827
842
|
},
|
|
828
843
|
...(records.tell
|
|
829
844
|
? {
|