@mistriwork/mistri 1.0.0-rc.51 → 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.
- package/CHANGELOG.md +16 -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/appSearchRuntime.d.ts +9 -0
- package/dist/server/app/appSearchRuntime.js +21 -3
- package/dist/server/cli/apps.d.ts +2 -0
- package/dist/server/cli/apps.js +14 -0
- package/dist/server/cli/mistriMain.js +13 -1
- package/dist/server/cli/reindex.js +15 -2
- package/dist/server/stores/commandStores.d.ts +6 -1
- package/dist/server/stores/commandStores.js +2 -1
- package/dist/server/tenant/tenantAdministration.js +2 -1
- package/dist/server/tenant/tenantAuthenticatedHttp.js +3 -1
- package/dist/server/tenant/tenantBackstopOwner.d.ts +20 -0
- package/dist/server/tenant/tenantBackstopOwner.js +37 -0
- package/dist/server/tenant/tenantConnections.d.ts +23 -2
- package/dist/server/tenant/tenantConnections.js +39 -3
- package/dist/server/tenant/tenantEnrollment.d.ts +8 -0
- package/dist/server/tenant/tenantEnrollment.js +40 -4
- package/dist/server/tenant/tenantLive.d.ts +6 -0
- package/dist/server/tenant/tenantLive.js +18 -1
- package/dist/server/tenant/tenantLocalAccess.js +16 -2
- package/dist/server/tenant/tenantNames.d.ts +1 -1
- package/dist/server/tenant/tenantPostgresCatalog.d.ts +30 -1
- package/dist/server/tenant/tenantPostgresCatalog.js +138 -3
- package/dist/server/tenant/tenantReadSource.d.ts +4 -187
- package/dist/server/tenant/tenantReadSource.js +110 -693
- package/dist/server/tenant/tenantReadSourceShared.d.ts +213 -0
- package/dist/server/tenant/tenantReadSourceShared.js +176 -0
- package/dist/server/tenant/tenantReadSourceSqlite.d.ts +6 -0
- package/dist/server/tenant/tenantReadSourceSqlite.js +498 -0
- package/dist/server/tenant/tenantSearch.d.ts +2 -30
- package/dist/server/tenant/tenantSearch.js +17 -2
- package/dist/server/tenant/tenantStartup.js +13 -2
- package/dist/server/tenant/tenantSupportOperations.js +2 -1
- package/dist/server/tenant/tenantValidationRecord.js +2 -0
- package/dist/server/tenant/tenantWriteSource.d.ts +8 -1
- package/dist/server/tenant/tenantWriteSource.js +79 -14
- package/package.json +4 -4
|
@@ -55,7 +55,8 @@ export async function bindTenantLive(adapter, ownership, url) {
|
|
|
55
55
|
const skip = new Set([...wish.off].flatMap((resource) => ownership.resources[resource] === undefined || choices.has(bareTable(ownership.resources[resource]))
|
|
56
56
|
? []
|
|
57
57
|
: [ownership.resources[resource]]));
|
|
58
|
-
|
|
58
|
+
const changes = { owners, scoped: true, ...(skip.size ? { skip } : {}), ...(wish.live ? {} : { only: choices }) };
|
|
59
|
+
bindLiveChanges(adapter, changes);
|
|
59
60
|
const listen = url === undefined ? undefined : wakeListenUrl(url, postgresPoolDefaults().pooler);
|
|
60
61
|
const hub = await liveHubOf(adapter, listen === undefined ? {} : { listen });
|
|
61
62
|
bound.set(key, {
|
|
@@ -63,8 +64,24 @@ export async function bindTenantLive(adapter, ownership, url) {
|
|
|
63
64
|
...(hub ? { hub } : {}),
|
|
64
65
|
state: hub ? { state: 'on' } : { state: 'off', reason: 'no store' },
|
|
65
66
|
...(hub && choices.size ? { choices } : {}),
|
|
67
|
+
...(hub ? { changes } : {}),
|
|
66
68
|
});
|
|
67
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* A second writer of the source bound in `bindTenantLive` — the owner's, for the platform realm's commands under the
|
|
72
|
+
* row-security backstop (tenantWriteSource.ts) — records what the first records, into the same store, so the one hub
|
|
73
|
+
* hears its writes too. It opens no hub of its own; `unbindTenantLive` lets it go.
|
|
74
|
+
*/
|
|
75
|
+
export async function shareTenantLive(adapter, ownership) {
|
|
76
|
+
const changes = bound.get(keyOf(ownership))?.changes;
|
|
77
|
+
if (!changes)
|
|
78
|
+
return;
|
|
79
|
+
if (!(await liveStoreOf(adapter)
|
|
80
|
+
?.ready()
|
|
81
|
+
.catch(() => false)))
|
|
82
|
+
return;
|
|
83
|
+
bindLiveChanges(adapter, changes);
|
|
84
|
+
}
|
|
68
85
|
/** The writer closed: its hub stops, and its streams end at their next read. */
|
|
69
86
|
export async function unbindTenantLive(adapter, ownership) {
|
|
70
87
|
const key = keyOf(ownership);
|
|
@@ -4,6 +4,7 @@ import { homeSourceOf } from '../../shared/appModel.js';
|
|
|
4
4
|
import { primaryKey, tableNamed } from '@mistriwork/engine/shared/schema.js';
|
|
5
5
|
import { PLATFORM_TENANT_ID } from '@mistriwork/engine/shared/sessionLease.js';
|
|
6
6
|
import { grantPlatformMembership, grantTenantMembership, putTenant, setPlatformStatus, TenantMaintenanceRefusal, } from './tenantMaintenance.js';
|
|
7
|
+
import { openBackstopOwnerReader } from './tenantBackstopOwner.js';
|
|
7
8
|
/** Where the served tenant App's store is, and the binding its policy made it under, as `migrate stores up` binds it. */
|
|
8
9
|
export async function tenantLocalAccess(loaded, registry, policyFile) {
|
|
9
10
|
const { loadAppTenantPolicy } = await import('../policy/appTenantPolicy.js');
|
|
@@ -47,8 +48,21 @@ export async function profileTenants(loaded, registry, limit) {
|
|
|
47
48
|
const [key] = table ? primaryKey(table) : [];
|
|
48
49
|
if (!table || !key)
|
|
49
50
|
return [];
|
|
50
|
-
|
|
51
|
-
|
|
51
|
+
/* Under the row-security backstop the registry's adapter is the runtime role, which reads no tenant row. */
|
|
52
|
+
const owner = await openBackstopOwnerReader(registry, connection.id);
|
|
53
|
+
try {
|
|
54
|
+
const rows = await (owner ?? adapter).query({
|
|
55
|
+
table: table.id,
|
|
56
|
+
columns: [key],
|
|
57
|
+
limit,
|
|
58
|
+
offset: 0,
|
|
59
|
+
orderBy: [{ column: key, direction: 'asc' }],
|
|
60
|
+
});
|
|
61
|
+
return rows.rows.map((row) => String(row[key]));
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
await owner?.close();
|
|
65
|
+
}
|
|
52
66
|
}
|
|
53
67
|
/* A step that found what it would make already there: the steps refuse it, and here it is what was wanted. */
|
|
54
68
|
const already = (error) => error instanceof TenantMaintenanceRefusal && /version given is not the current one|already holds a live/.test(error.message);
|
|
@@ -24,7 +24,7 @@ type Part = {
|
|
|
24
24
|
readonly column: string;
|
|
25
25
|
readonly words?: Readonly<Record<string, string>>;
|
|
26
26
|
};
|
|
27
|
-
interface TenantNamePlan {
|
|
27
|
+
export interface TenantNamePlan {
|
|
28
28
|
readonly key: string;
|
|
29
29
|
readonly parts: readonly Part[];
|
|
30
30
|
readonly columns: readonly string[];
|
|
@@ -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,33 @@ 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>;
|
|
57
|
+
/**
|
|
58
|
+
* The backstop's two roles, each asked as it connects (tenantEnrollment.ts): the owner's, and the runtime role the
|
|
59
|
+
* pinned policy binds. The runtime role must be neither the owner nor a member of it, nor a superuser, nor BYPASSRLS,
|
|
60
|
+
* and must see the same database: each of those reads every tenant's rows whatever the policy says, and the
|
|
61
|
+
* PostgreSQL error that would say so is never raised. Refuses with the reason, which the trusted startup reports.
|
|
62
|
+
*/
|
|
63
|
+
export declare function attestPostgresBackstopRoles(runtime: PgQuery, owner: PgQuery): Promise<{
|
|
64
|
+
role: string;
|
|
65
|
+
ownerRole: string;
|
|
66
|
+
}>;
|
|
67
|
+
/** Under the backstop: the runtime role, asked on its own connection, owns no tenant table, directly or through a
|
|
68
|
+
* role it is a member of. A table's owner is exempt from its policies unless FORCE is on, which the backstop does
|
|
69
|
+
* not use. */
|
|
70
|
+
export declare function assertPostgresRuntimeOwnsNone(client: PgQuery, ownership: TenantOwnershipSnapshot): Promise<void>;
|
|
42
71
|
/** Attest tenant-local business uniqueness; a single opaque primary ID is the
|
|
43
72
|
* intentional global exception. Type and DDL cannot prove how a host
|
|
44
73
|
* 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,10 +150,57 @@ 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)));
|
|
68
158
|
}
|
|
159
|
+
/**
|
|
160
|
+
* The backstop's two roles, each asked as it connects (tenantEnrollment.ts): the owner's, and the runtime role the
|
|
161
|
+
* pinned policy binds. The runtime role must be neither the owner nor a member of it, nor a superuser, nor BYPASSRLS,
|
|
162
|
+
* and must see the same database: each of those reads every tenant's rows whatever the policy says, and the
|
|
163
|
+
* PostgreSQL error that would say so is never raised. Refuses with the reason, which the trusted startup reports.
|
|
164
|
+
*/
|
|
165
|
+
export async function attestPostgresBackstopRoles(runtime, owner) {
|
|
166
|
+
const theirs = (await owner.query('SELECT current_user::text AS role, current_database()::text AS db')).rows[0];
|
|
167
|
+
if (typeof theirs?.role !== 'string' || typeof theirs.db !== 'string')
|
|
168
|
+
return denyTenant();
|
|
169
|
+
const mine = (await runtime.query(`SELECT r.rolname::text AS role, r.rolsuper AS super, r.rolbypassrls AS bypass, current_database()::text AS db,
|
|
170
|
+
o.oid IS NOT NULL AS known, COALESCE(pg_catalog.pg_has_role(r.oid, o.oid, 'MEMBER'), false) AS member
|
|
171
|
+
FROM pg_catalog.pg_roles r LEFT JOIN pg_catalog.pg_roles o ON o.rolname = $1
|
|
172
|
+
WHERE r.rolname = current_user`, [theirs.role])).rows[0];
|
|
173
|
+
if (typeof mine?.role !== 'string')
|
|
174
|
+
return denyTenant();
|
|
175
|
+
const refuse = (why) => denyTenant(new Error(`The row-security backstop refuses this pair of roles: ${why}`));
|
|
176
|
+
if (mine.db !== theirs.db || mine.known !== true)
|
|
177
|
+
return refuse('"url" and "owner" must name the same database, and the runtime role must see the owner role there.');
|
|
178
|
+
if (mine.role === theirs.role)
|
|
179
|
+
return refuse('"url" connects as the owner. The runtime role must be another role, which owns nothing.');
|
|
180
|
+
if (mine.super !== false)
|
|
181
|
+
return refuse('the runtime role is a superuser, which row-level security never binds.');
|
|
182
|
+
if (mine.bypass !== false)
|
|
183
|
+
return refuse('the runtime role has BYPASSRLS. Run ALTER ROLE … NOBYPASSRLS.');
|
|
184
|
+
if (mine.member !== false)
|
|
185
|
+
return refuse('the runtime role is a member of the owner role, and so reads as the owner.');
|
|
186
|
+
return { role: mine.role, ownerRole: theirs.role };
|
|
187
|
+
}
|
|
188
|
+
/** Under the backstop: the runtime role, asked on its own connection, owns no tenant table, directly or through a
|
|
189
|
+
* role it is a member of. A table's owner is exempt from its policies unless FORCE is on, which the backstop does
|
|
190
|
+
* not use. */
|
|
191
|
+
export async function assertPostgresRuntimeOwnsNone(client, ownership) {
|
|
192
|
+
const tenantIds = Object.entries(ownership.ownership)
|
|
193
|
+
.filter(([, rule]) => rule.kind === 'tenant')
|
|
194
|
+
.map(([logical]) => ownership.resources[logical])
|
|
195
|
+
.sort(byCodeUnit);
|
|
196
|
+
const owned = (await client.query(`SELECT w.id FROM unnest($1::text[], $2::text[], $3::text[]) AS w(id, schema, name)
|
|
197
|
+
JOIN pg_catalog.pg_namespace n ON n.nspname = w.schema
|
|
198
|
+
JOIN pg_catalog.pg_class c ON c.relnamespace = n.oid AND c.relname = w.name
|
|
199
|
+
WHERE pg_catalog.pg_has_role(current_user, c.relowner, 'MEMBER')
|
|
200
|
+
ORDER BY w.id`, targets(tenantIds))).rows;
|
|
201
|
+
if (owned.length)
|
|
202
|
+
denyTenant(new Error(`The row-security backstop refuses this pair of roles: the runtime role owns ${owned.map((row) => row.id).join(', ')}, and a table's owner is exempt from its policy. ALTER TABLE … OWNER TO the owner role.`));
|
|
203
|
+
}
|
|
69
204
|
/** Attest tenant-local business uniqueness; a single opaque primary ID is the
|
|
70
205
|
* intentional global exception. Type and DDL cannot prove how a host
|
|
71
206
|
* generates those IDs, so ID generation remains a deployment responsibility. */
|
|
@@ -1,192 +1,10 @@
|
|
|
1
|
-
import { type SandboxRecord } from './tenantSandboxStore.js';
|
|
2
|
-
import { type ScopedReads, type WriteTransaction } from '@mistriwork/engine/adapters/adapter.js';
|
|
3
|
-
import { type RowScope } from '@mistriwork/engine/shared/rowScope.js';
|
|
4
|
-
import { type TenantMembershipEvidence, type TenantMembershipLookup, type TenantMembershipRecord } from './tenantMembership.js';
|
|
5
1
|
import { type TenantOwnershipSnapshot } from './tenantOwnership.js';
|
|
6
|
-
import
|
|
7
|
-
import { type TenantServiceEvidence } from './tenantServiceModel.js';
|
|
8
|
-
import { type TenantPublicEvidence, type TenantPublicLookup, type TenantPublicResolution } from './tenantPublicRead.js';
|
|
9
|
-
import type { SupportMembershipEvidence } from './tenantSupportLease.js';
|
|
10
|
-
import { type TenantMembershipListLookup, type TenantStoreBinding } from './tenantStore.js';
|
|
11
|
-
import { type TenantAddresses, type TenantAddressesLookup, type TenantProfileLookup, type ActiveTenant, type ActiveTenantsQuery, type TenantIntakeEvidence, type TenantIntakeLookup, type TenantIntakeTenantLookup, type TenantIntakeResolution } from './tenantIntakeModel.js';
|
|
2
|
+
import { type TenantStoreBinding } from './tenantStore.js';
|
|
12
3
|
import type { TenantValue } from '@mistriwork/engine/shared/queryOperands.js';
|
|
13
4
|
import type { AppDef } from '../../shared/app.js';
|
|
14
|
-
import { type
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
import { type InboxQuery, type StoredNotice } from '../../adapters/inbox/inbox.js';
|
|
18
|
-
import { type BrandingLogoQuery, type BrandingQuery, type StoredBranding, type StoredBrandingLogo } from '../../adapters/branding/branding.js';
|
|
19
|
-
/** One person's email switch in one inbox: the same names an inbox read takes. */
|
|
20
|
-
interface EmailSwitchQuery {
|
|
21
|
-
readonly app: string;
|
|
22
|
-
readonly recipient: string;
|
|
23
|
-
}
|
|
24
|
-
export interface TenantReadSource {
|
|
25
|
-
readonly ownership: TenantOwnershipSnapshot;
|
|
26
|
-
readMembership(lookup: TenantMembershipLookup): Promise<TenantMembershipRecord | null>;
|
|
27
|
-
readMemberships(lookup: TenantMembershipListLookup): Promise<readonly TenantMembershipRecord[]>;
|
|
28
|
-
assertCurrent(evidence: TenantMembershipEvidence): Promise<void>;
|
|
29
|
-
scopeReads(evidence: TenantMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
|
|
30
|
-
/** The reader `scopeReads` binds, composed by the same rule, without the
|
|
31
|
-
* snapshot `scopeReads` checks the membership in first. Nothing is read
|
|
32
|
-
* until an operation runs, and every operation revalidates the evidence in
|
|
33
|
-
* its own snapshot before its SQL, so no row is read on evidence that
|
|
34
|
-
* snapshot did not find current. For an owner that also revalidates before
|
|
35
|
-
* it releases anything (tenantReadRuntime.ts). */
|
|
36
|
-
bindReads(evidence: TenantMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
|
|
37
|
-
/** Several reads in one snapshot: the evidence revalidated once at its start,
|
|
38
|
-
* then every operation `work` asks for on that same snapshot, one after
|
|
39
|
-
* another, and none once it has returned. The snapshot is the fence each of
|
|
40
|
-
* `bindReads`' operations has, shared: what they read is one state, and it is
|
|
41
|
-
* the state the membership was found current in. For an answer that is only
|
|
42
|
-
* advice — which commands a record offers — and that its command asks again
|
|
43
|
-
* when it runs (tenantCommandAvailability.ts). */
|
|
44
|
-
withReads<T>(evidence: TenantMembershipEvidence, rows: RowScope, work: (reads: ScopedReads) => T | Promise<T>): Promise<T>;
|
|
45
|
-
/** `work`, with every operation of `bindReads`' readers for this evidence that it asks, while it runs, on one
|
|
46
|
-
* snapshot: opened at the first of them, the evidence revalidated in it once, held until `work` has returned and
|
|
47
|
-
* every read begun on it has settled, then ended. A composed record page, a page's boot, a post-write refresh asked
|
|
48
|
-
* many reads of one context at once, and each took a snapshot of its own — its BEGIN, its LOCK and its membership,
|
|
49
|
-
* its COMMIT, and a reader of the pool beside the others (tenantReadRuntime.ts `together`). What they read is then
|
|
50
|
-
* one state, the one the membership was found current in, as `withReads`' is. A read that wants a replica, and any
|
|
51
|
-
* asked once `work` has returned, takes its own snapshot as before. Where reads are not pooled (SQLite), `work`. */
|
|
52
|
-
together<T>(evidence: TenantMembershipEvidence, work: () => Promise<T>): Promise<T>;
|
|
53
|
-
/** `together`, and where its snapshot was opened and the catalog's attestation stands, the release fence in the
|
|
54
|
-
* message that ends it (PostgresReadSnapshot.finish): once `work` has returned and every read on the snapshot has
|
|
55
|
-
* settled, its COMMIT and this evidence's membership in a fresh snapshot of its own, one round trip where the
|
|
56
|
-
* COMMIT and assertCurrent's own snapshot were three. A membership that no longer holds refuses. `fenced` says
|
|
57
|
-
* whether it rode; where it did not — nothing was read, the attestation was due, `work` failed, SQLite — the
|
|
58
|
-
* caller fences as before. */
|
|
59
|
-
togetherFenced<T>(evidence: TenantMembershipEvidence, work: () => Promise<T>): Promise<{
|
|
60
|
-
value: T;
|
|
61
|
-
fenced: boolean;
|
|
62
|
-
}>;
|
|
63
|
-
/** The platform realm's twins: its membership, its revalidation, and reads
|
|
64
|
-
* under the platform scope (across tenants, unnamed tables denied). */
|
|
65
|
-
readPlatformMembership(lookup: PlatformMembershipLookup): Promise<PlatformMembershipRecord | null>;
|
|
66
|
-
assertPlatformCurrent(evidence: PlatformMembershipEvidence): Promise<void>;
|
|
67
|
-
scopePlatformReads(evidence: PlatformMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
|
|
68
|
-
/** `scopePlatformReads` without its snapshot, as `bindReads` is `scopeReads`
|
|
69
|
-
* without one: every operation revalidates the platform membership in its
|
|
70
|
-
* own snapshot before its SQL, for an owner that fences again before it
|
|
71
|
-
* releases anything (tenantPlatformReadRuntime.ts). */
|
|
72
|
-
bindPlatformReads(evidence: PlatformMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
|
|
73
|
-
/** `withReads` for the platform realm, under the platform scope. */
|
|
74
|
-
withPlatformReads<T>(evidence: PlatformMembershipEvidence, rows: RowScope, work: (reads: ScopedReads) => T | Promise<T>): Promise<T>;
|
|
75
|
-
/** A support session's twins ("enter as dealer"): its revalidation, and reads
|
|
76
|
-
* under the dealer's own scope. The fence is the support row itself, with its
|
|
77
|
-
* parent platform membership, `@platform` and the dealer — never a member
|
|
78
|
-
* membership, which an operator inside a dealer does not have. The scope is
|
|
79
|
-
* the dealer's, composed by the same rule a member's is, so a session can
|
|
80
|
-
* never read more than that one rule allows. */
|
|
81
|
-
assertSupportCurrent(evidence: SupportMembershipEvidence): Promise<void>;
|
|
82
|
-
scopeSupportReads(evidence: SupportMembershipEvidence, rows: RowScope): Promise<ScopedReads>;
|
|
83
|
-
/** Public intake's resolution, in one snapshot: the active tenant whose
|
|
84
|
-
* profile row alone holds the address, else the platform when it is active.
|
|
85
|
-
* Reads the profile by the policy's column only; admits nobody. */
|
|
86
|
-
resolveIntake(lookup: TenantIntakeLookup): Promise<TenantIntakeResolution>;
|
|
87
|
-
/** A token's public verb's placement, in one snapshot: the token's own
|
|
88
|
-
* tenant when it and the platform are both active, else refused — never
|
|
89
|
-
* triage, and never another tenant, whatever the request says. */
|
|
90
|
-
resolveIntakeByTenant(lookup: TenantIntakeTenantLookup): Promise<TenantIntakeResolution>;
|
|
91
|
-
/** A visitor's placement, in one snapshot: the active tenant whose profile
|
|
92
|
-
* row alone holds the address (or the mapped host's tenant, when active),
|
|
93
|
-
* with `@platform` active too; else null, whatever the reason, so no
|
|
94
|
-
* address is answered differently from another. Admits nobody. */
|
|
95
|
-
resolvePublic(lookup: TenantPublicLookup): Promise<TenantPublicResolution | null>;
|
|
96
|
-
/** A visitor's placement re-resolved in a snapshot of its own: the release fence. */
|
|
97
|
-
assertPublicCurrent(evidence: TenantPublicEvidence): Promise<void>;
|
|
98
|
-
/** Reads under a visitor's scope (tenantPublicRead.ts composePublicReadScope),
|
|
99
|
-
* as `bindReads` is a member's: every operation re-resolves the address in
|
|
100
|
-
* its own snapshot and requires the same tenant at the same versions before
|
|
101
|
-
* its SQL, so a rotated address or a suspended tenant reads nothing more. */
|
|
102
|
-
bindPublicReads(evidence: TenantPublicEvidence, rows: RowScope): Promise<ScopedReads>;
|
|
103
|
-
/** Reads for a public command's lookup in a tenant's intake (tenantIntake.ts): the submission read as the
|
|
104
|
-
* visitor it is (tenantPublicRead.ts intakeVisitor), under the same scope and the same fence as
|
|
105
|
-
* `bindPublicReads`. Triage is refused: it lands in no tenant, so no tenant's rows are its to look up. */
|
|
106
|
-
bindIntakeReads(evidence: TenantIntakeEvidence, rows: RowScope): Promise<ScopedReads>;
|
|
107
|
-
/** Reads under a tenant service's scope (tenantServiceModel.ts composeServiceScope), as `bindReads` is a
|
|
108
|
-
* member's: the source recomposes the scope from the evidence (never a caller's predicate), and every
|
|
109
|
-
* operation re-reads the service anchors in its own snapshot and requires the same tenant and platform at
|
|
110
|
-
* the same versions, inside the attempt's window. A platform place is refused: it runs outside any tenant. */
|
|
111
|
-
bindServiceReads(evidence: TenantServiceEvidence, rows: RowScope): Promise<ScopedReads>;
|
|
112
|
-
/** A capability link's placement, in one snapshot: the live link by this App and its id alone — the one read a
|
|
113
|
-
* tenant App's shared door makes before it knows the tenant — with its tenant and `@platform` each active; else
|
|
114
|
-
* null, whatever the reason. Admits nobody: the door checks the token or session against the tenant it names. */
|
|
115
|
-
resolveLink(lookup: TenantLinkLookup): Promise<TenantLinkResolution | null>;
|
|
116
|
-
/** Reads under a link's scope (tenantLinkModel.ts composeLinkScope): its one record within its tenant. Every
|
|
117
|
-
* operation re-reads the anchors and the link row in its own snapshot and requires the same tenant at the same
|
|
118
|
-
* versions, inside the request's window, with the link still live: a revoke or a suspension reads nothing more. */
|
|
119
|
-
bindLinkReads(evidence: TenantLinkEvidence, rows: RowScope): Promise<ScopedReads>;
|
|
120
|
-
/** What these tenants are called: each one's profile row said by the App's
|
|
121
|
-
* template for that resource (tenantNames.ts), for the ids a caller already
|
|
122
|
-
* holds. Reads the profile's key and the name's columns only; admits nobody. */
|
|
123
|
-
readTenantNames(lookup: TenantNamesLookup): Promise<Readonly<Record<string, string>>>;
|
|
124
|
-
/** A tenant's own intake and public addresses, by the policy's columns, in
|
|
125
|
-
* one snapshot: each only when its profile row holds one of an
|
|
126
|
-
* address's shape that resolves back to this tenant alone. For the tenant's
|
|
127
|
-
* own lease to show; admits nobody. */
|
|
128
|
-
readTenantAddresses(lookup: TenantAddressesLookup): Promise<TenantAddresses>;
|
|
129
|
-
/** The columns of a tenant's profile row its members read (`auth.tenancy.shared`), by column, once per request:
|
|
130
|
-
* the platform's own read of the row (as the names and addresses are), no App resource read and no grant. Those
|
|
131
|
-
* columns and nothing else of the row; a missing row reads as every column null. Admits nobody. */
|
|
132
|
-
readTenantProfile(lookup: TenantProfileLookup): Promise<Readonly<Record<string, TenantValue>>>;
|
|
133
|
-
/** A job attempt's anchors, in one snapshot: the named tenant's row and
|
|
134
|
-
* `@platform`, each its version while active, else null. With no tenant
|
|
135
|
-
* (the platform's own time job), `@platform` alone. Admits nobody. */
|
|
136
|
-
readServiceAnchors(tenantId: string | null): Promise<Readonly<{
|
|
137
|
-
tenantVersion: string | null;
|
|
138
|
-
platformVersion: string | null;
|
|
139
|
-
}>>;
|
|
140
|
-
/** The tenants active now, by id: whom a job at times per tenant runs for.
|
|
141
|
-
* Given `zone`, a shared profile column, each also carries that column off
|
|
142
|
-
* its row (null where it has none): the zone its slots keep. Each attempt is
|
|
143
|
-
* admitted again on its own tenant's row. Admits nobody. */
|
|
144
|
-
readActiveTenants(options?: ActiveTenantsQuery): Promise<readonly ActiveTenant[]>;
|
|
145
|
-
/** A machine timer's due records across the active tenants, a page at a
|
|
146
|
-
* time, each with the tenant its owner column names, read off the row here
|
|
147
|
-
* (tenantDueTimers.ts). A plan, as readActiveTenants is: each run is
|
|
148
|
-
* admitted again on its own tenant's row. Admits nobody. */
|
|
149
|
-
readDueTimers(query: DueTimersQuery): Promise<readonly DueTimer[]>;
|
|
150
|
-
/** The sandboxes whose dev clock reads ahead (tenantSandboxClock.ts), none where the store was never
|
|
151
|
-
* provisioned: which tenants' timers the sweep also reads on their own clock. A live tenant has no row
|
|
152
|
-
* there, so none is ever among them. Admits nobody. */
|
|
153
|
-
readSandboxClocks(): Promise<readonly SandboxRecord[]>;
|
|
154
|
-
/** Which of these tenants are sandboxes, for discovery to mark them to their members: none where the
|
|
155
|
-
* store was never provisioned. Admits nobody. */
|
|
156
|
-
readSandboxes(tenants: readonly string[]): Promise<ReadonlySet<string>>;
|
|
157
|
-
/** One record's stored history, by its store key — a tenant-owned record's
|
|
158
|
-
* carries its owner (adapters/history/recordHistory.ts). Admits nobody: the
|
|
159
|
-
* caller has read the record in the reader's own context first. */
|
|
160
|
-
readRecordHistory(query: RecordHistoryQuery): Promise<StoredRecordChange[]>;
|
|
161
|
-
/** A dashboard feed's stored rows (recordActivity.ts). Admits nobody: the
|
|
162
|
-
* caller names the context's own tenant in `owners`, or none for the
|
|
163
|
-
* platform realm, and reads each record the rows name in that context. */
|
|
164
|
-
readRecordActivity(query: RecordActivityQuery): Promise<StoredRecordChange[]>;
|
|
165
|
-
/** One person's notices in one inbox (tenantInbox.ts). Admits nobody: the caller names the lease's own inbox. */
|
|
166
|
-
readInbox(query: InboxQuery): Promise<StoredNotice[]>;
|
|
167
|
-
/** Whether one person asked an inbox for no email: the outbox's switch, read on the reader (inboxMail.ts). */
|
|
168
|
-
readEmailOff(query: EmailSwitchQuery): Promise<boolean>;
|
|
169
|
-
/** One tenant's saved branding in one App, or null (adapters/branding). */
|
|
170
|
-
readBranding(query: BrandingQuery): Promise<StoredBranding | null>;
|
|
171
|
-
/** One logo of an App by the hash of its bytes. */
|
|
172
|
-
readBrandingLogo(query: BrandingLogoQuery): Promise<StoredBrandingLogo | null>;
|
|
173
|
-
close(): Promise<void>;
|
|
174
|
-
}
|
|
175
|
-
/** The profile's record-name template, as the App's catalog serves it, and the tenants to name. */
|
|
176
|
-
interface TenantNamesLookup {
|
|
177
|
-
readonly template: string | undefined;
|
|
178
|
-
readonly tenants: readonly string[];
|
|
179
|
-
}
|
|
180
|
-
/** Only frozen factory objects can supply source authority. WeakSet lookup does
|
|
181
|
-
* not inspect properties, so lookalikes, getters and proxies never execute. */
|
|
182
|
-
export declare function captureTenantReadSource(input: TenantReadSource): TenantReadSource;
|
|
183
|
-
/** A batch's reads in the shape a command's records take, for the one caller
|
|
184
|
-
* that asks a command's questions without its transaction (availability): it
|
|
185
|
-
* reads, and every way of writing refuses. */
|
|
186
|
-
export declare function advisoryRecords(reads: ScopedReads): WriteTransaction;
|
|
187
|
-
/** Opens once, read-only. Every operation owns a serialized read snapshot on
|
|
188
|
-
* that exact handle; no registry lookup, request-time migration or writer exists. */
|
|
189
|
-
export declare function openSqliteTenantReadSource(existingPath: string, ownership: TenantOwnershipSnapshot, store: TenantStoreBinding, now?: () => number): TenantReadSource;
|
|
5
|
+
import { type TenantReadSource } from './tenantReadSourceShared.js';
|
|
6
|
+
export { advisoryRecords, captureTenantReadSource, type TenantReadSource } from './tenantReadSourceShared.js';
|
|
7
|
+
export { openSqliteTenantReadSource } from './tenantReadSourceSqlite.js';
|
|
190
8
|
/**
|
|
191
9
|
* The PostgreSQL counterpart of openSqliteTenantReadSource: the same source
|
|
192
10
|
* contract on a dedicated read pool. Every operation is one REPEATABLE READ,
|
|
@@ -222,4 +40,3 @@ export declare function openPostgresTenantReadSource(url: string, ownership: Ten
|
|
|
222
40
|
* nothing is read where the App shares none, nor in the platform realm, where no one tenant is meant. A failed read
|
|
223
41
|
* fails the request; a row scope never guesses a value. */
|
|
224
42
|
export declare function readSharedProfile(source: Pick<TenantReadSource, 'readTenantProfile'>, app: AppDef, tenantId: string): Promise<Readonly<Record<string, TenantValue>>>;
|
|
225
|
-
export {};
|