@agentic-kit/db-tools 0.12.46 → 0.13.0
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/README.md +18 -4
- package/access/findings.d.ts +93 -0
- package/access/findings.js +434 -0
- package/access/index.d.ts +5 -0
- package/access/index.js +27 -0
- package/access/policies.d.ts +142 -0
- package/access/policies.js +338 -0
- package/access/provisioning.d.ts +121 -0
- package/access/provisioning.js +381 -0
- package/access/rule-check.d.ts +52 -0
- package/access/rule-check.js +307 -0
- package/access/words.d.ts +38 -0
- package/access/words.js +530 -0
- package/app-workspace.d.ts +1 -0
- package/app-workspace.js +7 -9
- package/blueprint/blueprint-defaults.d.ts +9 -0
- package/blueprint/blueprint-defaults.js +77 -0
- package/blueprint/blueprint-schema.d.ts +68 -0
- package/blueprint/blueprint-schema.js +139 -0
- package/blueprint/field-type.d.ts +4 -0
- package/blueprint/field-type.js +100 -0
- package/blueprint/internal-policies.d.ts +1 -0
- package/blueprint/internal-policies.js +10 -0
- package/blueprint-construction.d.ts +10 -6
- package/blueprint-construction.js +34 -25
- package/context.d.ts +15 -0
- package/context.js +132 -69
- package/db-probe.d.ts +1 -1
- package/db-probe.js +19 -4
- package/esm/access/findings.d.ts +93 -0
- package/esm/access/findings.js +428 -0
- package/esm/access/index.d.ts +5 -0
- package/esm/access/index.js +5 -0
- package/esm/access/policies.d.ts +142 -0
- package/esm/access/policies.js +315 -0
- package/esm/access/provisioning.d.ts +121 -0
- package/esm/access/provisioning.js +375 -0
- package/esm/access/rule-check.d.ts +52 -0
- package/esm/access/rule-check.js +297 -0
- package/esm/access/words.d.ts +38 -0
- package/esm/access/words.js +524 -0
- package/esm/app-workspace.d.ts +1 -0
- package/esm/app-workspace.js +7 -10
- package/esm/blueprint/blueprint-defaults.d.ts +9 -0
- package/esm/blueprint/blueprint-defaults.js +74 -0
- package/esm/blueprint/blueprint-schema.d.ts +68 -0
- package/esm/blueprint/blueprint-schema.js +134 -0
- package/esm/blueprint/field-type.d.ts +4 -0
- package/esm/blueprint/field-type.js +95 -0
- package/esm/blueprint/internal-policies.d.ts +1 -0
- package/esm/blueprint/internal-policies.js +7 -0
- package/esm/blueprint-construction.d.ts +10 -6
- package/esm/blueprint-construction.js +32 -24
- package/esm/context.d.ts +15 -0
- package/esm/context.js +133 -70
- package/esm/db-probe.d.ts +1 -1
- package/esm/db-probe.js +21 -6
- package/esm/failure.d.ts +89 -0
- package/esm/failure.js +362 -0
- package/esm/gate.d.ts +6 -4
- package/esm/gate.js +42 -14
- package/esm/graphql-http.d.ts +27 -6
- package/esm/graphql-http.js +96 -24
- package/esm/host.d.ts +33 -8
- package/esm/host.js +42 -2
- package/esm/index.d.ts +22 -12
- package/esm/index.js +21 -39
- package/esm/provision-database/env-file.d.ts +7 -0
- package/esm/provision-database/env-file.js +30 -0
- package/esm/provision-database/preset-match.js +1 -2
- package/esm/provision-database/provision.d.ts +21 -4
- package/esm/provision-database/provision.js +330 -85
- package/esm/provision-database/request-database.d.ts +22 -3
- package/esm/provision-database/request-database.js +46 -13
- package/esm/ready.d.ts +20 -0
- package/esm/ready.js +45 -0
- package/esm/run-codegen/barrels.js +1 -1
- package/esm/run-codegen/endpoints.js +5 -6
- package/esm/schema-model/normalize.js +1 -1
- package/esm/schema-model.js +4 -5
- package/esm/schema-resolve.d.ts +50 -0
- package/esm/schema-resolve.js +200 -14
- package/esm/table-access.d.ts +116 -0
- package/esm/table-access.js +418 -0
- package/esm/tools/access.d.ts +218 -0
- package/esm/tools/access.js +651 -0
- package/esm/tools/add-policies.d.ts +44 -12
- package/esm/tools/add-policies.js +84 -84
- package/esm/tools/add-records.d.ts +23 -2
- package/esm/tools/add-records.js +113 -75
- package/esm/tools/add-relation-schema.d.ts +5 -5
- package/esm/tools/add-relation-schema.js +13 -14
- package/esm/tools/add-relation.d.ts +11 -2
- package/esm/tools/add-relation.js +68 -31
- package/esm/tools/create-api-key.d.ts +18 -4
- package/esm/tools/create-api-key.js +105 -54
- package/esm/tools/describe-schema.d.ts +5 -7
- package/esm/tools/describe-schema.js +41 -118
- package/esm/tools/entity-types.d.ts +54 -0
- package/esm/tools/entity-types.js +233 -0
- package/esm/tools/index.d.ts +26 -0
- package/esm/tools/index.js +151 -0
- package/esm/tools/mutations.d.ts +36 -7
- package/esm/tools/mutations.js +245 -99
- package/esm/tools/provision-blueprint.d.ts +25 -1
- package/esm/tools/provision-blueprint.js +184 -42
- package/esm/tools/provision-database.d.ts +7 -5
- package/esm/tools/provision-database.js +31 -17
- package/esm/tools/run-codegen.d.ts +27 -4
- package/esm/tools/run-codegen.js +143 -76
- package/esm/tools/templates.d.ts +30 -7
- package/esm/tools/templates.js +166 -95
- package/failure.d.ts +89 -0
- package/failure.js +375 -0
- package/gate.d.ts +6 -4
- package/gate.js +41 -13
- package/graphql-http.d.ts +27 -6
- package/graphql-http.js +105 -25
- package/host.d.ts +33 -8
- package/host.js +45 -2
- package/index.d.ts +22 -12
- package/index.js +86 -43
- package/package.json +6 -5
- package/provision-database/env-file.d.ts +7 -0
- package/provision-database/env-file.js +32 -1
- package/provision-database/preset-match.js +1 -2
- package/provision-database/provision.d.ts +21 -4
- package/provision-database/provision.js +327 -81
- package/provision-database/request-database.d.ts +22 -3
- package/provision-database/request-database.js +49 -14
- package/ready.d.ts +20 -0
- package/ready.js +52 -0
- package/run-codegen/barrels.js +1 -1
- package/run-codegen/endpoints.js +5 -6
- package/schema-model/normalize.js +4 -4
- package/schema-model.js +4 -5
- package/schema-resolve.d.ts +50 -0
- package/schema-resolve.js +209 -14
- package/table-access.d.ts +116 -0
- package/table-access.js +437 -0
- package/tools/access.d.ts +218 -0
- package/tools/access.js +669 -0
- package/tools/add-policies.d.ts +44 -12
- package/tools/add-policies.js +86 -84
- package/tools/add-records.d.ts +23 -2
- package/tools/add-records.js +113 -74
- package/tools/add-relation-schema.d.ts +5 -5
- package/tools/add-relation-schema.js +13 -14
- package/tools/add-relation.d.ts +11 -2
- package/tools/add-relation.js +69 -31
- package/tools/create-api-key.d.ts +18 -4
- package/tools/create-api-key.js +104 -53
- package/tools/describe-schema.d.ts +5 -7
- package/tools/describe-schema.js +40 -117
- package/tools/entity-types.d.ts +54 -0
- package/tools/entity-types.js +240 -0
- package/tools/index.d.ts +26 -0
- package/tools/index.js +154 -0
- package/tools/mutations.d.ts +36 -7
- package/tools/mutations.js +252 -101
- package/tools/provision-blueprint.d.ts +25 -1
- package/tools/provision-blueprint.js +186 -43
- package/tools/provision-database.d.ts +7 -5
- package/tools/provision-database.js +33 -18
- package/tools/run-codegen.d.ts +27 -4
- package/tools/run-codegen.js +141 -73
- package/tools/templates.d.ts +30 -7
- package/tools/templates.js +167 -94
- package/esm/policy/add-policies-to-table.d.ts +0 -26
- package/esm/policy/add-policies-to-table.js +0 -66
- package/esm/policy/provision-helpers.d.ts +0 -38
- package/esm/policy/provision-helpers.js +0 -50
- package/esm/tools/manage-entity-types.d.ts +0 -40
- package/esm/tools/manage-entity-types.js +0 -201
- package/policy/add-policies-to-table.d.ts +0 -26
- package/policy/add-policies-to-table.js +0 -71
- package/policy/provision-helpers.d.ts +0 -38
- package/policy/provision-helpers.js +0 -58
- package/tools/manage-entity-types.d.ts +0 -40
- package/tools/manage-entity-types.js +0 -206
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
// The access tools: what a policy type takes, the rules of a live table in plain words with the structural findings,
|
|
2
|
+
// and a replace of a table's rules. Each sentence comes from the words of a rule's Authz node; no part of a result
|
|
3
|
+
// says who can or cannot reach a row.
|
|
4
|
+
import { identifierParam, strictObject } from '@agentic-kit/harness';
|
|
5
|
+
import { policyNodeTypes } from 'node-type-registry';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { accessFindings, checkRule, columnGaps, dataNodesForPolicies, POLICY_ROLES, policyDifference, resolveEntityTypes, TABLE_NEEDS, tablePolicyFromBlueprint, } from '../access';
|
|
8
|
+
import { AUTHZ_NODES as AUTHZ } from '../access/policies';
|
|
9
|
+
import { columnsOf } from '../access/words';
|
|
10
|
+
import { AccessPolicyZod, AuthzTypeZod, ruleShapeProblems } from '../blueprint/blueprint-schema';
|
|
11
|
+
import { failedResult, failureFromError, failureText, noRowCreated, suggest } from '../failure';
|
|
12
|
+
import { statusAdapter } from '../graphql-http';
|
|
13
|
+
import { appSessionReady, projectReady } from '../ready';
|
|
14
|
+
import { findMetaTable, META_QUERY } from '../records/meta';
|
|
15
|
+
import { storedName } from '../schema-resolve';
|
|
16
|
+
import { accessInputOf, asWritten, canonical, changeMeaning, columnChange, columnPlan, grantWords, planRule, planTableAccess, readTable, readTables, rowsConflict, ruleWords, tableField, } from '../table-access';
|
|
17
|
+
import { LIST_ENTITY_TYPES, readEntityTypes } from './entity-types';
|
|
18
|
+
function fail(failure, extra) {
|
|
19
|
+
return failedResult(failure, { success: false, message: failureText(failure), ...extra });
|
|
20
|
+
}
|
|
21
|
+
/** The call that describes one policy type, or every one. */
|
|
22
|
+
const describeType = (type) => type ? suggest('describe_policy_type', { type }, `See the parameters of ${type}`) : suggest('describe_policy_type', {}, 'See the policy types a rule can use');
|
|
23
|
+
/** The read of the rules a table has. */
|
|
24
|
+
const explainTable = (table, why = 'See the rules the table has') => suggest('explain_access', { table_name: table }, why);
|
|
25
|
+
// ── describe_policy_type ─────────────────────────────────────────────────
|
|
26
|
+
const DescribePolicyTypeZod = strictObject('the input', {
|
|
27
|
+
type: AuthzTypeZod.optional().describe('One Authz node to describe in full; every node in short when left out'),
|
|
28
|
+
});
|
|
29
|
+
export const describePolicyTypeTool = {
|
|
30
|
+
name: 'describe_policy_type',
|
|
31
|
+
label: 'Describe policy type',
|
|
32
|
+
description: 'Describe the Authz policy types a rule can use: with no type, each one with who it lets in and what it needs on the table; with a type, its parameters (JSON Schema), when to use it and when not, its risks, and the columns it needs. Read-only.',
|
|
33
|
+
promptSnippet: 'describe_policy_type: the parameters and plain words of a policy type, before writing rules. Read-only.',
|
|
34
|
+
parameters: DescribePolicyTypeZod,
|
|
35
|
+
effect: 'read',
|
|
36
|
+
async execute(params) {
|
|
37
|
+
if (!params.type) {
|
|
38
|
+
const types = policyNodeTypes.map((node) => ({ name: node.name, summary: node.summary, tableKind: TABLE_NEEDS[node.name]?.kind }));
|
|
39
|
+
const text = types.map((type) => `${type.name} (${type.tableKind}): ${type.summary ?? ''}`).join('\n');
|
|
40
|
+
return { content: [{ type: 'text', text }], details: { types } };
|
|
41
|
+
}
|
|
42
|
+
const node = policyNodeTypes.find((entry) => entry.name === params.type);
|
|
43
|
+
const needs = TABLE_NEEDS[node.name];
|
|
44
|
+
const type = {
|
|
45
|
+
name: node.name,
|
|
46
|
+
summary: node.summary,
|
|
47
|
+
tableKind: needs?.kind,
|
|
48
|
+
parameterSchema: node.parameter_schema,
|
|
49
|
+
useWhen: node.use_when ?? [],
|
|
50
|
+
avoidWhen: node.avoid_when ?? [],
|
|
51
|
+
risks: node.risks ?? [],
|
|
52
|
+
...(needs?.data_node ? { dataNode: needs.data_node } : {}),
|
|
53
|
+
};
|
|
54
|
+
const text = [
|
|
55
|
+
`${node.name} (${type.tableKind}): ${node.summary ?? ''}`,
|
|
56
|
+
`parameters: ${JSON.stringify(node.parameter_schema.properties ?? {})}`,
|
|
57
|
+
...type.useWhen.map((line) => `use when: ${line}`),
|
|
58
|
+
...type.avoidWhen.map((line) => `avoid when: ${line}`),
|
|
59
|
+
...type.risks.map((line) => `risk: ${line}`),
|
|
60
|
+
...(needs?.data_node ? [`needs on the table: ${needs.data_node.type} ${JSON.stringify(needs.data_node.columns)}`] : []),
|
|
61
|
+
].join('\n');
|
|
62
|
+
return { content: [{ type: 'text', text }], details: { type } };
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
// ── explain_access ───────────────────────────────────────────────────────
|
|
66
|
+
const ExplainAccessZod = strictObject('the input', {
|
|
67
|
+
table_name: identifierParam().optional().describe('The table to explain; every application table when left out'),
|
|
68
|
+
});
|
|
69
|
+
function explained(table, related) {
|
|
70
|
+
const input = { ...accessInputOf(table), ...(related ? { related } : {}) };
|
|
71
|
+
return {
|
|
72
|
+
name: table.name,
|
|
73
|
+
rules: input.policies.map((policy) => ({ ...asWritten(policy), words: planRule(policy, input.related).words })),
|
|
74
|
+
grants: grantWords(input.grants),
|
|
75
|
+
rowSecurity: input.rls_enabled !== false,
|
|
76
|
+
findings: accessFindings(input),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
const ruleLine = (rule) => ` ${rule.permissive ? 'rule' : 'limit'} (${[rule.privileges.join(', '), ...(rule.policy_role === 'authenticated' ? [] : [`role ${rule.policy_role}`])].join('; ')}): ${rule.words}`;
|
|
80
|
+
function accessText(table) {
|
|
81
|
+
return [
|
|
82
|
+
table.name,
|
|
83
|
+
...(table.rules.length ? table.rules.map(ruleLine) : [' rules: none']),
|
|
84
|
+
` grants: ${table.grants.join('; ') || 'none'}`,
|
|
85
|
+
...(table.rowSecurity ? [] : [' row security: off, so the rules do not apply']),
|
|
86
|
+
...table.findings.map((finding) => ` finding (${finding.level}): ${finding.summary} ${finding.fix}`),
|
|
87
|
+
];
|
|
88
|
+
}
|
|
89
|
+
export const explainAccessTool = {
|
|
90
|
+
name: 'explain_access',
|
|
91
|
+
label: 'Explain access',
|
|
92
|
+
description: 'Show the access rules of a table (or of every table): each rule in the shape a rule is written, without the parts the backend sets, with one plain sentence for it; the grants, row security, and the structures that may let in more people than meant or lock out people who should pass. Read-only.',
|
|
93
|
+
promptSnippet: 'explain_access: the rules of a table in plain words, and what may be wrong with them. Read-only.',
|
|
94
|
+
parameters: ExplainAccessZod,
|
|
95
|
+
effect: 'read',
|
|
96
|
+
async execute(params, ctx) {
|
|
97
|
+
const ready = await projectReady(ctx.cwd);
|
|
98
|
+
if (ready.kind === 'failed')
|
|
99
|
+
return failedResult(ready.failure, { tables: [] });
|
|
100
|
+
const read = params.table_name ? await readTable(ready.value, params.table_name) : await readTables(ready.value);
|
|
101
|
+
if (read.kind === 'failed')
|
|
102
|
+
return failedResult(read.failure, { tables: [] });
|
|
103
|
+
const records = Array.isArray(read.value) ? read.value : [read.value];
|
|
104
|
+
const related = await relatedColumns(ready.value, records.flatMap((table) => table.policyRules), Array.isArray(read.value) ? read.value : undefined);
|
|
105
|
+
if (related.kind === 'failed')
|
|
106
|
+
return failedResult(related.failure, { tables: [] });
|
|
107
|
+
const tables = records.map((table) => explained(table, related.value));
|
|
108
|
+
const text = tables.length ? tables.flatMap(accessText).join('\n') : 'No application tables yet.';
|
|
109
|
+
return { content: [{ type: 'text', text }], details: { tables } };
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
// ── set_access ───────────────────────────────────────────────────────────
|
|
113
|
+
const SetAccessZod = strictObject('the input', {
|
|
114
|
+
table_name: identifierParam().describe('The table whose access rules are replaced'),
|
|
115
|
+
policies: z.array(AccessPolicyZod).describe('The rules that become the whole set; the grants of the table stay'),
|
|
116
|
+
});
|
|
117
|
+
/** True when the person signed in to the app sees a row of the table, so it certainly has rows; false when this tool cannot tell. */
|
|
118
|
+
async function rowsSeen(context, table) {
|
|
119
|
+
if (!context.dataEndpoint)
|
|
120
|
+
return false;
|
|
121
|
+
const session = await appSessionReady(context);
|
|
122
|
+
if (session.kind === 'failed')
|
|
123
|
+
return false;
|
|
124
|
+
try {
|
|
125
|
+
const adapter = statusAdapter(context.dataEndpoint, { Authorization: `Bearer ${session.value.token}` });
|
|
126
|
+
const meta = await adapter.execute(META_QUERY);
|
|
127
|
+
const all = meta.ok ? findMetaTable((meta.data._meta?.tables ?? []).filter(Boolean), table)?.query?.all : undefined;
|
|
128
|
+
if (!all)
|
|
129
|
+
return false;
|
|
130
|
+
const rows = await adapter.execute(`query DbToolsRowsSeen { ${all}(first: 1) { nodes { __typename } } }`);
|
|
131
|
+
return rows.ok && (rows.data[all]?.nodes?.length ?? 0) > 0;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* A column the rules' Data nodes would add that the table has with another type: a generator keeps it as it is,
|
|
139
|
+
* so the rule cannot work on it.
|
|
140
|
+
*/
|
|
141
|
+
function typeGaps(table, rules) {
|
|
142
|
+
const gaps = columnGaps(table.fields.map(tableField), rules.map((rule) => ({ type: rule.type, data: rule.data ?? {} }))).filter((gap) => gap.gaps.includes('type'));
|
|
143
|
+
if (gaps.length === 0)
|
|
144
|
+
return null;
|
|
145
|
+
return {
|
|
146
|
+
code: 'conflict',
|
|
147
|
+
message: gaps
|
|
148
|
+
.map(({ column, expected, actual }) => `Table "${table.name}" has the column ${column} as ${actual.type ?? 'another type'}, and the rules need it as ${expected.type}; the backend keeps a column that exists, so the change cannot work on it.`)
|
|
149
|
+
.join(' '),
|
|
150
|
+
hint: gaps
|
|
151
|
+
.map(({ column, expected }) => `Change ${column} to ${expected.type} (each value is converted, and one that does not fit fails), or drop it so the change adds it.`)
|
|
152
|
+
.join(' '),
|
|
153
|
+
calls: gaps.flatMap(({ column, expected }) => [
|
|
154
|
+
suggest('retype_field', { table_name: table.name, field_name: column, type: expected.type }, `Change ${column} to ${expected.type}, the type the rules need`),
|
|
155
|
+
suggest('delete_field', { table_name: table.name, field_name: column }, `Drop ${column} and its values, so the change adds it as the rules need it`),
|
|
156
|
+
]),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* What a change does to the columns of an existing table, refused before
|
|
161
|
+
* anything changes when the backend cannot apply it: a rule reads a column
|
|
162
|
+
* nothing gives the table, or a required column would be added to a table
|
|
163
|
+
* whose rows this tool can see.
|
|
164
|
+
*/
|
|
165
|
+
export async function existingTableChange(context, table, nodes, rules) {
|
|
166
|
+
const change = columnChange(table.name, table.fields, nodes, rules);
|
|
167
|
+
if (change.kind === 'failed')
|
|
168
|
+
return change;
|
|
169
|
+
const misfit = typeGaps(table, rules);
|
|
170
|
+
if (misfit)
|
|
171
|
+
return { kind: 'failed', failure: misfit };
|
|
172
|
+
if (change.value.failsIfRows.length === 0 || !(await rowsSeen(context, table.name)))
|
|
173
|
+
return change;
|
|
174
|
+
const conflict = rowsConflict(table.name, change.value.failsIfRows);
|
|
175
|
+
const message = `${conflict.message.charAt(0).toUpperCase()}${conflict.message.slice(1)} The backend would refuse the change, so nothing was sent.`;
|
|
176
|
+
return { kind: 'failed', failure: { code: 'conflict', ...conflict, message } };
|
|
177
|
+
}
|
|
178
|
+
/** Installs `provision` on the table in one request: the backend applies it in one transaction. */
|
|
179
|
+
export async function applyProvision(context, table, provision, action, meaning) {
|
|
180
|
+
try {
|
|
181
|
+
const result = await context.modules.secureTableProvision
|
|
182
|
+
.create({
|
|
183
|
+
data: {
|
|
184
|
+
databaseId: context.databaseId,
|
|
185
|
+
schemaId: context.schemaId,
|
|
186
|
+
tableId: table.id,
|
|
187
|
+
nodes: provision.nodes,
|
|
188
|
+
policies: provision.policies,
|
|
189
|
+
...(provision.grants ? { grants: provision.grants } : {}),
|
|
190
|
+
...(provision.owns ? { owns: provision.owns } : {}),
|
|
191
|
+
},
|
|
192
|
+
select: { id: true },
|
|
193
|
+
})
|
|
194
|
+
.unwrap();
|
|
195
|
+
return result.createSecureTableProvision?.secureTableProvision ? null : noRowCreated(action, explainTable(table.name, 'See the rules the table has now'));
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
return failureFromError(err, action, meaning);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// A grant as one fact: the role, the privilege and the columns ('*' for every column).
|
|
202
|
+
const grantKeys = (grants) => new Set((grants ?? []).flatMap((grant) => grant.roles.flatMap((role) => grant.privileges.map(([privilege, columns]) => `${role} ${String(privilege).toLowerCase()} ${Array.isArray(columns) ? [...columns].sort().join(',') : '*'}`))));
|
|
203
|
+
const grantKeyWords = (key) => {
|
|
204
|
+
const [role, privilege, columns] = key.split(' ');
|
|
205
|
+
return `${privilege} to ${role}${columns === '*' ? '' : ` on ${columns}`}`;
|
|
206
|
+
};
|
|
207
|
+
const policyWords = (policy) => `${policy.type} for ${policy.privileges.join(', ')} ("${ruleWords(policy.type, policy.data)}")`;
|
|
208
|
+
// A rule with a part no Authz node describes: policyDifference compares it by its exact data, so two such rules that
|
|
209
|
+
// mean the same can still differ.
|
|
210
|
+
const unreadable = (policy) => !AUTHZ.has(policy.type) || checkRule(policy.type, policy.data).some((problem) => problem.code === 'not-a-node' || problem.code === 'mistyped-node');
|
|
211
|
+
// A read that can pass a moment later: the backend failing, gone for a moment, or limiting requests.
|
|
212
|
+
const PASSING = new Set(['backend-unreachable', 'rate-limited']);
|
|
213
|
+
const READ_AGAIN_MS = 1000;
|
|
214
|
+
/**
|
|
215
|
+
* Reads the access of a table again after a change returned, and compares it
|
|
216
|
+
* by meaning with the after state of the plan: `policyDifference` decides for
|
|
217
|
+
* the rules (order, duplicates, defaults, derived keys and the backend's own
|
|
218
|
+
* copy of the read-only block do not count), then the grants, row security
|
|
219
|
+
* and the columns the change added. A change made at the same moment by
|
|
220
|
+
* another call is what this finds: the backend's replace does not wait for
|
|
221
|
+
* one. `again` is the call that makes the table as the plan said, when there
|
|
222
|
+
* is one.
|
|
223
|
+
*/
|
|
224
|
+
export async function readBack(context, table, planned, added, again) {
|
|
225
|
+
const explain = explainTable(table, 'See the rules the table has now');
|
|
226
|
+
let live = await readTable(context, table);
|
|
227
|
+
if (live.kind === 'failed' && PASSING.has(live.failure.code)) {
|
|
228
|
+
await new Promise((resolve) => setTimeout(resolve, READ_AGAIN_MS));
|
|
229
|
+
live = await readTable(context, table);
|
|
230
|
+
}
|
|
231
|
+
if (live.kind === 'failed') {
|
|
232
|
+
// The change's state is the news; a session that ended is the step before the read.
|
|
233
|
+
const signIn = live.failure.code === 'signed-out' ? 'Sign in again, then read' : 'Read';
|
|
234
|
+
return {
|
|
235
|
+
kind: 'unverified',
|
|
236
|
+
failure: {
|
|
237
|
+
code: 'unverified',
|
|
238
|
+
message: `The change to the access of table "${table}" was sent, and the backend answered that it applied it, but reading the access back failed (${live.failure.message}), so this tool cannot say whether the table is as the plan said.`,
|
|
239
|
+
hint: `${signIn} the rules the table has now before you change it again.`,
|
|
240
|
+
calls: [explain],
|
|
241
|
+
},
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
const now = accessInputOf(live.value);
|
|
245
|
+
const { missing, unplanned } = policyDifference(planned.policies, now.policies);
|
|
246
|
+
const [want, have] = [grantKeys(planned.grants), grantKeys(now.grants)];
|
|
247
|
+
const grants = { unplanned: [...have].filter((key) => !want.has(key)), missing: [...want].filter((key) => !have.has(key)) };
|
|
248
|
+
const columnsMissing = added.filter((name) => !live.value.fields.some((field) => field.name === name));
|
|
249
|
+
const rowSecurityOff = planned.rls_enabled === true && now.rls_enabled !== true;
|
|
250
|
+
const difference = {
|
|
251
|
+
unplanned,
|
|
252
|
+
missing,
|
|
253
|
+
...(grants.unplanned.length || grants.missing.length ? { grants } : {}),
|
|
254
|
+
...(rowSecurityOff ? { rowSecurityOff: true } : {}),
|
|
255
|
+
...(columnsMissing.length ? { columnsMissing } : {}),
|
|
256
|
+
};
|
|
257
|
+
const parts = [
|
|
258
|
+
...(unplanned.length ? [`it has rules the plan did not have: ${unplanned.map(policyWords).join('; ')}`] : []),
|
|
259
|
+
...(missing.length ? [`rules of the plan are missing: ${missing.map(policyWords).join('; ')}`] : []),
|
|
260
|
+
...(grants.unplanned.length ? [`it grants what the plan did not: ${grants.unplanned.map(grantKeyWords).join(', ')}`] : []),
|
|
261
|
+
...(grants.missing.length ? [`grants of the plan are missing: ${grants.missing.map(grantKeyWords).join(', ')}`] : []),
|
|
262
|
+
...(rowSecurityOff ? ['row security is off'] : []),
|
|
263
|
+
...(columnsMissing.length ? [`the column${columnsMissing.length === 1 ? '' : 's'} ${columnsMissing.join(', ')} the change adds ${columnsMissing.length === 1 ? 'is' : 'are'} missing`] : []),
|
|
264
|
+
];
|
|
265
|
+
if (parts.length === 0)
|
|
266
|
+
return { kind: 'same', table: live.value };
|
|
267
|
+
const exact = [...new Set([...unplanned, ...missing].filter(unreadable).map((policy) => policy.type))];
|
|
268
|
+
if (exact.length)
|
|
269
|
+
parts.push(`the comparison of ${exact.join(', ')} is exact, not by meaning, because a part of it is one no Authz node describes`);
|
|
270
|
+
return {
|
|
271
|
+
kind: 'different',
|
|
272
|
+
failure: {
|
|
273
|
+
code: 'conflict',
|
|
274
|
+
message: `The access of table "${table}" is not what the approved plan said: ${parts.join('; ')}. Another change may have run at the same moment.`,
|
|
275
|
+
hint: `Read the rules the table has now${again ? '; sending the same change again replaces the whole set with the one you approved' : ''}.`,
|
|
276
|
+
calls: again ? [explain, again] : [explain],
|
|
277
|
+
context: { difference },
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
// A team-membership rule: AuthzEntityMembership with a team kind given as a number of 2 or more, and an entity_field.
|
|
282
|
+
const teamRule = (policies) => policies.find((policy) => {
|
|
283
|
+
const data = (policy.data ?? {});
|
|
284
|
+
return policy.$type === 'AuthzEntityMembership' && Number(data.membership_type) >= 2 && data.entity_field !== undefined;
|
|
285
|
+
});
|
|
286
|
+
const writesOf = (grants) => [...new Set((grants ?? []).flatMap((grant) => grant.privileges.map(([privilege]) => String(privilege).toLowerCase())))].filter((privilege) => privilege === 'insert' || privilege === 'update' || privilege === 'delete');
|
|
287
|
+
/**
|
|
288
|
+
* The rule the backend adds by itself beside the first team-membership rule of a change that grants writes: a
|
|
289
|
+
* restrictive `AuthzNotReadOnly` for those writes. A plan's after state holds it, so the plan and the read-back after
|
|
290
|
+
* the change both count it.
|
|
291
|
+
*/
|
|
292
|
+
export function addedByBackend(policies, grants) {
|
|
293
|
+
const team = teamRule(policies);
|
|
294
|
+
const writes = writesOf(grants);
|
|
295
|
+
if (!team || writes.length === 0)
|
|
296
|
+
return [];
|
|
297
|
+
const { entity_field, membership_type } = team.data;
|
|
298
|
+
return [{ type: 'AuthzNotReadOnly', privileges: writes, permissive: false, role: team.policy_role ?? 'authenticated', data: { entity_field, membership_type } }];
|
|
299
|
+
}
|
|
300
|
+
/** What a plan says about the read-only limit beside a team rule: the backend adds it only for a change that grants writes. */
|
|
301
|
+
export function readOnlyNotes(policies, grants) {
|
|
302
|
+
if (!teamRule(policies))
|
|
303
|
+
return [];
|
|
304
|
+
if (writesOf(grants).length)
|
|
305
|
+
return ['The backend adds its own read-only limit beside the team rule, for the writes this change grants.'];
|
|
306
|
+
if (policies.some((policy) => policy.$type === 'AuthzNotReadOnly'))
|
|
307
|
+
return [];
|
|
308
|
+
return [
|
|
309
|
+
"No read-only limit is added: the backend adds one only for a change that grants writes, and this one keeps the table's grants. Read-only members of the team pass these rules unless a rule here limits them.",
|
|
310
|
+
];
|
|
311
|
+
}
|
|
312
|
+
const PRIVILEGE_ORDER = ['select', 'insert', 'update', 'delete'];
|
|
313
|
+
// The team kinds an entity_type names: the database's entity types, read only when a rule names one.
|
|
314
|
+
async function scopesFor(context, policies) {
|
|
315
|
+
if (!policies.some((policy) => JSON.stringify([policy.data ?? {}, policy.with_check ?? {}]).includes('"entity_type"')))
|
|
316
|
+
return { kind: 'ok', value: [] };
|
|
317
|
+
const read = await readEntityTypes(context);
|
|
318
|
+
if (read.kind === 'failed')
|
|
319
|
+
return read;
|
|
320
|
+
return {
|
|
321
|
+
kind: 'ok',
|
|
322
|
+
value: read.value.flatMap((row) => (row.prefix && typeof row.outMembershipType === 'number' ? [{ scope: row.prefix, membership_type: row.outMembershipType }] : [])),
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
/** The roles a rule can name: the request roles every API has, and the roles the database's APIs run as, read only when a rule names another. */
|
|
326
|
+
export async function rolesFor(context, policies) {
|
|
327
|
+
const known = POLICY_ROLES;
|
|
328
|
+
if (policies.every((policy) => policy.policy_role === undefined || known.includes(policy.policy_role)))
|
|
329
|
+
return { kind: 'ok', value: undefined };
|
|
330
|
+
try {
|
|
331
|
+
const result = await context.api.api
|
|
332
|
+
.findMany({ where: { databaseId: { equalTo: context.databaseId } }, select: { roleName: true, anonRole: true } })
|
|
333
|
+
.unwrap();
|
|
334
|
+
const own = result.apis.nodes.flatMap((api) => [api.roleName, api.anonRole]).filter((role) => Boolean(role));
|
|
335
|
+
return { kind: 'ok', value: [...new Set([...known, ...own])] };
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
return { kind: 'failed', failure: failureFromError(err, 'Failed to read the roles of the APIs of the project database') };
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* The problems of the rules a caller wrote, as one failure: each rule's shape against the registry's `BlueprintPolicy`
|
|
343
|
+
* (`with_check` only where `withCheck` allows it), and its data against its policy type with the rule's context; each
|
|
344
|
+
* problem with its rule, and the calls that describe the nodes it is in.
|
|
345
|
+
*/
|
|
346
|
+
export function ruleProblems(policies, context, label) {
|
|
347
|
+
const found = policies.flatMap((policy, index) => {
|
|
348
|
+
const shape = ruleShapeProblems(policy, { withCheck: context.withCheck });
|
|
349
|
+
const problems = shape.length ? shape : checkRule(policy.$type, policy.data, { ...context, ...(policy.policy_role !== undefined ? { role: policy.policy_role } : {}) });
|
|
350
|
+
return problems.map((problem) => ({ ...problem, index, type: policy.$type }));
|
|
351
|
+
});
|
|
352
|
+
if (found.length === 0)
|
|
353
|
+
return null;
|
|
354
|
+
const calls = found.flatMap(({ code, meant, path, type }) => {
|
|
355
|
+
if (code === 'mistyped-node' && meant)
|
|
356
|
+
return [describeType(meant)];
|
|
357
|
+
if (code === 'not-a-node' || code === 'not-a-policy')
|
|
358
|
+
return [describeType()];
|
|
359
|
+
if (code === 'unknown-role' || !AUTHZ.has(type))
|
|
360
|
+
return [];
|
|
361
|
+
return [type, ...path.split('.').filter((part) => AUTHZ.has(part))].map((name) => describeType(name));
|
|
362
|
+
});
|
|
363
|
+
return {
|
|
364
|
+
code: 'invalid-input',
|
|
365
|
+
message: found.map((problem) => `${label(problem.index)}: ${problem.message}`).join(' '),
|
|
366
|
+
hint: 'Fix each rule the message names; the parameters of each policy type say what its data takes.',
|
|
367
|
+
calls: calls.filter((call, index) => calls.findIndex((other) => canonical(other.input) === canonical(call.input)) === index),
|
|
368
|
+
context: { problems: found.map(({ index, path, code, message }) => ({ rule: index + 1, path, code, message })) },
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
function entityTypeFailure(problems) {
|
|
372
|
+
const unknown = problems.some((problem) => problem.code === 'unknown-entity-type');
|
|
373
|
+
return {
|
|
374
|
+
code: 'invalid-input',
|
|
375
|
+
message: problems.map((problem) => `Rule ${problem.policy + 1}: ${problem.message}`).join(' '),
|
|
376
|
+
...(unknown ? { hint: 'Use an entity type the database has, by its prefix.', calls: [LIST_ENTITY_TYPES] } : {}),
|
|
377
|
+
context: { problems },
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
// A rule whose meaning depends on the columns of another table: AuthzRelatedMemberList, at any depth.
|
|
381
|
+
const readsRelatedColumns = (policies) => policies.some((policy) => (policy.type ?? policy.$type) === 'AuthzRelatedMemberList' || JSON.stringify(policy.data ?? {}).includes('"AuthzRelatedMemberList"'));
|
|
382
|
+
/**
|
|
383
|
+
* The columns of the database's application tables, by id and by name, read only when a rule needs another table's
|
|
384
|
+
* columns; `tables` are tables already read.
|
|
385
|
+
*/
|
|
386
|
+
export async function relatedColumns(context, policies, tables) {
|
|
387
|
+
if (!readsRelatedColumns(policies))
|
|
388
|
+
return { kind: 'ok', value: undefined };
|
|
389
|
+
const read = tables ? { kind: 'ok', value: tables } : await readTables(context);
|
|
390
|
+
if (read.kind === 'failed')
|
|
391
|
+
return read;
|
|
392
|
+
const columns = {};
|
|
393
|
+
for (const table of read.value)
|
|
394
|
+
columns[table.id] = columns[table.name] = table.fields.map((field) => field.name);
|
|
395
|
+
return { kind: 'ok', value: columns };
|
|
396
|
+
}
|
|
397
|
+
// The name the backend gives each policy row of a rule: the role's first four letters, the privilege's first three, and
|
|
398
|
+
// the rule's name, which is its type without "Authz" unless it gives one.
|
|
399
|
+
const shortName = (type) => storedName(type.replace(/^Authz/, '')) ?? type;
|
|
400
|
+
const rowName = (role, privilege, name) => {
|
|
401
|
+
const full = `${role.toLowerCase().slice(0, 4)}_${privilege.toLowerCase().slice(0, 3)}_${name}`;
|
|
402
|
+
return storedName(full) ?? full;
|
|
403
|
+
};
|
|
404
|
+
const COMPOSITE_CALL = describeType('AuthzComposite');
|
|
405
|
+
// What the backend keeps one of on a table: a rule of one policy type with the same data and check of a changed row,
|
|
406
|
+
// whatever its privileges, role and kind.
|
|
407
|
+
const sameTypeAndData = (rule) => canonical([rule.$type, rule.data ?? {}, rule.with_check ?? null]);
|
|
408
|
+
/**
|
|
409
|
+
* The rules a change sends, as the backend creates them, or the failure that names the first rule the backend would
|
|
410
|
+
* skip or refuse. Rules of one policy type, role, kind and data become one rule with all their privileges (in lower
|
|
411
|
+
* case). Beside an earlier rule or one the table keeps (`table`, for an add), a rule is refused when the backend keeps
|
|
412
|
+
* only one of its type and data, or when it names a policy row the same way: the role's first four letters, the
|
|
413
|
+
* privilege's first three, and the rule's name. Every tool that sends rules sends them through this.
|
|
414
|
+
*/
|
|
415
|
+
export function rulesToSend(given, { table, defaultRole, label }) {
|
|
416
|
+
const merged = [];
|
|
417
|
+
for (const [index, rule] of given.entries()) {
|
|
418
|
+
const role = rule.policy_role ?? defaultRole;
|
|
419
|
+
const privileges = rule.privileges?.map((privilege) => privilege.toLowerCase());
|
|
420
|
+
const same = merged.find(({ rule: other }) => sameTypeAndData(other) === sameTypeAndData(rule) && (other.policy_role ?? defaultRole) === role && (other.permissive ?? true) === (rule.permissive ?? true) && other.policy_name === rule.policy_name);
|
|
421
|
+
if (same && same.rule.privileges && privileges) {
|
|
422
|
+
same.rule = { ...same.rule, privileges: PRIVILEGE_ORDER.filter((privilege) => same.rule.privileges.includes(privilege) || privileges.includes(privilege)) };
|
|
423
|
+
}
|
|
424
|
+
else {
|
|
425
|
+
merged.push({ rule: { ...rule, ...(privileges ? { privileges } : {}) }, index });
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
const kept = table?.policyRules ?? [];
|
|
429
|
+
const names = new Map();
|
|
430
|
+
for (const [position, { rule, index }] of merged.entries()) {
|
|
431
|
+
const role = rule.policy_role ?? defaultRole;
|
|
432
|
+
const twin = merged.slice(0, position).find(({ rule: other }) => sameTypeAndData(other) === sameTypeAndData(rule));
|
|
433
|
+
if (twin) {
|
|
434
|
+
return {
|
|
435
|
+
kind: 'failed',
|
|
436
|
+
failure: {
|
|
437
|
+
code: 'invalid-input',
|
|
438
|
+
message: `${label(index)} has the same policy type and data as rule ${twin.index + 1}, and a table keeps one rule of a type with the same data, ` +
|
|
439
|
+
'so the backend would skip it.',
|
|
440
|
+
hint: 'Give them as one rule for one role, which also lets in the roles that are members of it, or make the data differ, ' +
|
|
441
|
+
'for example by putting one in an AuthzComposite rule.',
|
|
442
|
+
calls: [COMPOSITE_CALL],
|
|
443
|
+
},
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
const stored = kept.find((other) => other.type === rule.$type && canonical(other.data) === canonical(rule.data ?? {}) && canonical(other.withCheck ?? null) === canonical(rule.with_check ?? null));
|
|
447
|
+
if (stored) {
|
|
448
|
+
return {
|
|
449
|
+
kind: 'failed',
|
|
450
|
+
failure: {
|
|
451
|
+
code: 'conflict',
|
|
452
|
+
message: `${label(index)}: table "${table.name}" has a ${rule.$type} rule with the same data for ${stored.privileges.join(', ')}, and a table keeps one rule of a type with the same data, so the backend would skip this one.`,
|
|
453
|
+
hint: "Replace the table's rules with the whole set instead, with these privileges in that one rule.",
|
|
454
|
+
calls: [explainTable(table.name)],
|
|
455
|
+
},
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
for (const privilege of rule.privileges ?? []) {
|
|
459
|
+
const name = rowName(role, privilege, rule.policy_name ?? shortName(rule.$type));
|
|
460
|
+
const what = `a second ${rule.$type} rule for ${privilege} and the role ${role}`;
|
|
461
|
+
const before = names.get(name);
|
|
462
|
+
if (before !== undefined) {
|
|
463
|
+
return {
|
|
464
|
+
kind: 'failed',
|
|
465
|
+
failure: {
|
|
466
|
+
code: 'invalid-input',
|
|
467
|
+
message: `${label(index)} is ${what}, beside rule ${before + 1}: the backend names a rule by its role, privilege and policy type, so it would refuse the second one.`,
|
|
468
|
+
hint: 'Put both in one AuthzComposite rule: under OR either one lets a person in, under AND a person must pass both. Or give one a "policy_name" of its own.',
|
|
469
|
+
calls: [COMPOSITE_CALL],
|
|
470
|
+
},
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
if (table?.policyNames.includes(name)) {
|
|
474
|
+
return {
|
|
475
|
+
kind: 'failed',
|
|
476
|
+
failure: {
|
|
477
|
+
code: 'conflict',
|
|
478
|
+
message: `${label(index)} would be ${what} on table "${table.name}", which already has one: the backend names a rule by its role, privilege and policy type, so it would refuse this one.`,
|
|
479
|
+
hint: "Put the table's rule and this one in one AuthzComposite rule, and replace the table's rules with a set that holds it.",
|
|
480
|
+
calls: [explainTable(table.name), COMPOSITE_CALL],
|
|
481
|
+
},
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
names.set(name, index);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return { kind: 'ok', value: merged.map(({ rule }) => rule) };
|
|
488
|
+
}
|
|
489
|
+
// The backend names the read-only limit it adds beside a team rule the same way whatever the rule, and never finds the
|
|
490
|
+
// copy a table keeps, so an add that makes one fails on a table that has one.
|
|
491
|
+
function readOnlyNameTaken(rules, grants, table) {
|
|
492
|
+
const [limit] = addedByBackend(rules, grants);
|
|
493
|
+
const taken = limit && limit.privileges.map((privilege) => rowName(limit.role, privilege, 'read_only_restriction')).find((name) => table.policyNames.includes(name));
|
|
494
|
+
if (!taken)
|
|
495
|
+
return null;
|
|
496
|
+
return {
|
|
497
|
+
code: 'conflict',
|
|
498
|
+
message: `Beside a team rule, the backend adds its own read-only limit for the writes the change grants, always under one name, ` +
|
|
499
|
+
`and table "${table.name}" already has the policy ${taken}, so the backend would refuse the change.`,
|
|
500
|
+
hint: "Replace the table's rules with the whole set instead: a replace removes that limit too.",
|
|
501
|
+
calls: [explainTable(table.name)],
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* The rules a change sends, checked before the plan: each rule's shape and data, with the role it names and the
|
|
506
|
+
* columns of the other tables it reads; every `entity_type` becomes the team kind the backend stores; and the rules
|
|
507
|
+
* go through `rulesToSend`, beside the rules the table keeps (`table`, for an add). `live` is the table the plan shows
|
|
508
|
+
* now, whose rules may read other tables too.
|
|
509
|
+
*/
|
|
510
|
+
export async function storedRules(context, given, { table, grants, live = table }) {
|
|
511
|
+
const label = (index) => `Rule ${index + 1} (${given[index].$type})`;
|
|
512
|
+
const roles = await rolesFor(context, given);
|
|
513
|
+
if (roles.kind === 'failed')
|
|
514
|
+
return roles;
|
|
515
|
+
const related = await relatedColumns(context, [...given, ...(live?.policyRules ?? [])]);
|
|
516
|
+
if (related.kind === 'failed')
|
|
517
|
+
return related;
|
|
518
|
+
const problems = ruleProblems(given, { roles: roles.value, columnsOf: columnsOf(related.value) }, label);
|
|
519
|
+
if (problems)
|
|
520
|
+
return { kind: 'failed', failure: problems };
|
|
521
|
+
const policies = given;
|
|
522
|
+
const scopes = await scopesFor(context, policies);
|
|
523
|
+
if (scopes.kind === 'failed')
|
|
524
|
+
return scopes;
|
|
525
|
+
const resolved = resolveEntityTypes(policies.map(tablePolicyFromBlueprint), scopes.value);
|
|
526
|
+
if (resolved.problems.length)
|
|
527
|
+
return { kind: 'failed', failure: entityTypeFailure(resolved.problems) };
|
|
528
|
+
// The backend takes a rule's role from the first grant of the call when the rule names none.
|
|
529
|
+
const defaultRole = grants?.[0]?.roles?.[0] ?? 'authenticated';
|
|
530
|
+
const sent = rulesToSend(policies.map((policy, index) => ({ ...policy, data: resolved.policies[index].data })), { table, defaultRole, label });
|
|
531
|
+
if (sent.kind === 'failed')
|
|
532
|
+
return sent;
|
|
533
|
+
const taken = table && readOnlyNameTaken(sent.value, grants, table);
|
|
534
|
+
if (taken)
|
|
535
|
+
return { kind: 'failed', failure: taken };
|
|
536
|
+
return { kind: 'ok', value: { policies: sent.value, scopes: scopes.value, ...(related.value ? { related: related.value } : {}) } };
|
|
537
|
+
}
|
|
538
|
+
/** The access a change leaves: `kept` (the table's rules an add keeps) and `sent`, with the rule the backend adds itself. */
|
|
539
|
+
export function plannedPolicies(kept, sent, grants, scopes) {
|
|
540
|
+
return resolveEntityTypes([...kept, ...sent.map(tablePolicyFromBlueprint), ...addedByBackend(sent, grants)], scopes).policies;
|
|
541
|
+
}
|
|
542
|
+
/** The Data nodes the rules need for the columns `table` lacks, or the failure that says which rule names a column its node cannot add. */
|
|
543
|
+
export function neededNodes(policies, table) {
|
|
544
|
+
const needed = dataNodesForPolicies(policies.map((policy) => ({ type: policy.$type, data: policy.data ?? {} })), new Set(table.fields.map((field) => field.name)));
|
|
545
|
+
if (needed.problems.length > 0)
|
|
546
|
+
return { kind: 'failed', failure: { code: 'invalid-input', message: needed.problems.join(' ') } };
|
|
547
|
+
return { kind: 'ok', value: needed.nodes };
|
|
548
|
+
}
|
|
549
|
+
/** The calls that fix a required column no rule sets: make it optional, or drop it. */
|
|
550
|
+
export const columnFixes = (table, column) => [
|
|
551
|
+
suggest('update_field', { table_name: table, field_name: column, is_required: false }, `Make ${column} optional, so new rows can leave it empty`),
|
|
552
|
+
suggest('delete_field', { table_name: table, field_name: column }, `Drop ${column} and its values`),
|
|
553
|
+
];
|
|
554
|
+
// The columns of the finding that a required column is left from rules the table no longer has.
|
|
555
|
+
const strandedColumns = (findings) => findings.find((finding) => finding.id === 'required-column-not-set')?.columns ?? [];
|
|
556
|
+
/**
|
|
557
|
+
* What set_access checks before it changes anything: a list of rules, the
|
|
558
|
+
* table, and the columns the rules need. It resolves the replacement and the
|
|
559
|
+
* access the table will have.
|
|
560
|
+
*/
|
|
561
|
+
export async function setAccessReady(params, cwd) {
|
|
562
|
+
if (params.policies.length === 0) {
|
|
563
|
+
return {
|
|
564
|
+
kind: 'failed',
|
|
565
|
+
failure: {
|
|
566
|
+
code: 'invalid-input',
|
|
567
|
+
message: 'The rule list is empty: the table would keep no rule, and the backend replaces the rules only with a set that has one. ' +
|
|
568
|
+
'To let no one read or change the rows, give one AuthzDenyAll rule for select, insert, update and delete.',
|
|
569
|
+
calls: [describeType('AuthzDenyAll')],
|
|
570
|
+
},
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
const ready = await projectReady(cwd);
|
|
574
|
+
if (ready.kind === 'failed')
|
|
575
|
+
return ready;
|
|
576
|
+
const context = ready.value;
|
|
577
|
+
const read = await readTable(context, params.table_name);
|
|
578
|
+
if (read.kind === 'failed')
|
|
579
|
+
return read;
|
|
580
|
+
const table = read.value;
|
|
581
|
+
const prepared = await storedRules(context, params.policies, { live: table });
|
|
582
|
+
if (prepared.kind === 'failed')
|
|
583
|
+
return prepared;
|
|
584
|
+
const { policies, scopes, related } = prepared.value;
|
|
585
|
+
const nodes = neededNodes(policies, table);
|
|
586
|
+
if (nodes.kind === 'failed')
|
|
587
|
+
return nodes;
|
|
588
|
+
const provision = { nodes: nodes.value, policies, owns: ['policies'] };
|
|
589
|
+
const rules = policies.map((policy) => ({ type: policy.$type, data: policy.data }));
|
|
590
|
+
const columns = await existingTableChange(context, table, provision.nodes, rules);
|
|
591
|
+
if (columns.kind === 'failed')
|
|
592
|
+
return columns;
|
|
593
|
+
const after = {
|
|
594
|
+
policies: plannedPolicies([], policies, undefined, scopes),
|
|
595
|
+
grants: table.grants,
|
|
596
|
+
rls_enabled: true,
|
|
597
|
+
fields: [...table.fields.map(tableField), ...columns.value.fields],
|
|
598
|
+
...(related ? { related } : {}),
|
|
599
|
+
};
|
|
600
|
+
return {
|
|
601
|
+
kind: 'ok',
|
|
602
|
+
value: {
|
|
603
|
+
context,
|
|
604
|
+
table,
|
|
605
|
+
provision,
|
|
606
|
+
after,
|
|
607
|
+
notes: [...readOnlyNotes(policies, undefined), ...columns.value.notes],
|
|
608
|
+
columns: columns.value,
|
|
609
|
+
meaning: changeMeaning(table.name, columns.value, rules),
|
|
610
|
+
},
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
/** The plan's access for set_access: the live table now, and after the replace, with the columns it adds. */
|
|
614
|
+
export const setAccessPlan = ({ table, after, notes, columns }) => [
|
|
615
|
+
{ ...planTableAccess(table.name, { ...accessInputOf(table), ...(after.related ? { related: after.related } : {}) }, after), ...columnPlan(columns, true), ...(notes.length ? { notes } : {}) },
|
|
616
|
+
];
|
|
617
|
+
export const setAccessTool = {
|
|
618
|
+
name: 'set_access',
|
|
619
|
+
label: 'Set access',
|
|
620
|
+
description: 'Replace every access rule of a table with a list of rules, in one change; the grants stay, and the columns the rules need are added. The plan marks each rule as kept, added or removed.',
|
|
621
|
+
promptSnippet: 'set_access: replace the access rules of a table with a list of rules. Gated.',
|
|
622
|
+
parameters: SetAccessZod,
|
|
623
|
+
effect: 'write',
|
|
624
|
+
async execute(params, ctx) {
|
|
625
|
+
const ready = await setAccessReady(params, ctx.cwd);
|
|
626
|
+
if (ready.kind === 'failed')
|
|
627
|
+
return fail(ready.failure, {});
|
|
628
|
+
const { context, table, provision, meaning } = ready.value;
|
|
629
|
+
const failure = await applyProvision(context, table, provision, `Failed to set the access of table "${table.name}"`, meaning);
|
|
630
|
+
if (failure)
|
|
631
|
+
return fail(failure, { table: table.name });
|
|
632
|
+
const again = suggest('set_access', params, 'Replace the whole set again with the rules you approved, once nothing else changes the table');
|
|
633
|
+
const checked = await readBack(context, table.name, ready.value.after, ready.value.columns.added.map((column) => column.name), again);
|
|
634
|
+
if (checked.kind !== 'same')
|
|
635
|
+
return fail(checked.failure, { table: table.name });
|
|
636
|
+
const access = explained(checked.table, ready.value.after.related);
|
|
637
|
+
const stranded = strandedColumns(access.findings);
|
|
638
|
+
const message = [
|
|
639
|
+
`Set the access of table "${table.name}" to ${provision.policies.length} rule${provision.policies.length === 1 ? '' : 's'}.`,
|
|
640
|
+
...accessText(access).slice(1),
|
|
641
|
+
...ready.value.notes.map((note) => ` note: ${note}`),
|
|
642
|
+
...stranded.map((column) => ` ${column} is required and no rule sets it now: make it optional, or drop it.`),
|
|
643
|
+
].join('\n');
|
|
644
|
+
const calls = stranded.flatMap((column) => columnFixes(table.name, column));
|
|
645
|
+
return {
|
|
646
|
+
content: [{ type: 'text', text: message }],
|
|
647
|
+
details: { success: true, message, table: table.name, access },
|
|
648
|
+
...(calls.length ? { calls } : {}),
|
|
649
|
+
};
|
|
650
|
+
},
|
|
651
|
+
};
|