@workbasehq/core 0.2.12 → 0.2.13
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/package.json +1 -1
- package/src/config.ts +1 -1
- package/src/execution/policies.ts +7 -4
- package/src/kernel/plugin.ts +14 -1
- package/src/kernel/predicate.ts +71 -6
- package/src/kernel/registry.ts +11 -3
- package/src/policies.ts +63 -18
- package/src/query/compiler.ts +14 -10
- package/src/query/schema.ts +4 -1
package/package.json
CHANGED
package/src/config.ts
CHANGED
|
@@ -18,7 +18,7 @@ export { Q, Cond }
|
|
|
18
18
|
/** SQLite date formatting with column operands; values use the library wire encoding. */
|
|
19
19
|
export const Fn = { ...LibraryFn, strftime: (format: string, date: string) => Q.expr(`FN(${JSON.stringify(['STRFTIME', Q.value(format).serialize(), Q.expr(date).serialize()])})`) }
|
|
20
20
|
|
|
21
|
-
export const CORE_VERSION = '0.2.
|
|
21
|
+
export const CORE_VERSION = '0.2.13'
|
|
22
22
|
const navigationIconSchema = z.enum(['LayoutDashboard', 'Users', 'MapPin', 'Coins', 'Wallet', 'ArrowLeftRight', 'Settings', 'Building2', 'Activity', 'Workflow', 'Database', 'Folder'])
|
|
23
23
|
const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
|
|
24
24
|
export const serializedExpressionSchema = z.union([z.string().min(1).max(32000), z.record(z.string(), z.unknown()).transform(value => JSON.stringify(value))])
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ApiError } from '../errors'
|
|
2
2
|
import { renderPredicate, type KernelRegistry } from '../kernel/registry'
|
|
3
|
+
import { expandPolicyFilter } from '../kernel/predicate'
|
|
3
4
|
import type { Predicate, PredicateRelation, TableFilter } from '../kernel/plugin'
|
|
4
5
|
import { actorAccountId, canManageAccountAssignments, protectedActorFields } from '../policies'
|
|
5
6
|
import { quote } from '../migrations/schema'
|
|
@@ -20,16 +21,18 @@ export function writeFilter(kernel: KernelRegistry, scope: Scope, entity: string
|
|
|
20
21
|
}
|
|
21
22
|
function relation(node: PredicateRelation, parent: string, negated: boolean): string {
|
|
22
23
|
const child = `write_policy_${references}`
|
|
23
|
-
const scoped = render(kernel.tableFilter(node.entity, scope), child)
|
|
24
24
|
const explicit = render({ kind: 'where', predicate: node.predicate }, child)
|
|
25
25
|
// Put policy expressions inside the derived source, as the read compiler does.
|
|
26
26
|
// SQLite's expression-depth cap then does not accumulate the complete target
|
|
27
27
|
// policy tree at every correlation along a four-relation path.
|
|
28
28
|
const visible = `${child}_visible`
|
|
29
|
-
return `${negated ? 'NOT ' : ''}EXISTS(SELECT 1 FROM (SELECT ${quote(child)}.${quote(node.field)} AS ${quote('policy_key')} FROM ${quote(node.entity)} AS ${quote(child)} WHERE ${
|
|
29
|
+
return `${negated ? 'NOT ' : ''}EXISTS(SELECT 1 FROM (SELECT ${quote(child)}.${quote(node.field)} AS ${quote('policy_key')} FROM ${quote(node.entity)} AS ${quote(child)} WHERE ${explicit}) AS ${quote(visible)} WHERE ${quote(visible)}.${quote('policy_key')}=${quote(parent)}.${quote(node.parentField)})`
|
|
30
30
|
}
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
let filter: TableFilter
|
|
32
|
+
try { filter = expandPolicyFilter(entity, child => kernel.tableFilter(child, scope), 128) }
|
|
33
|
+
catch { throw new ApiError(403, 'policy_violation') }
|
|
34
|
+
const sql = render(filter, alias)
|
|
35
|
+
if (bindings.length > 100 || sql.length > 64_000) throw new ApiError(403, 'policy_violation')
|
|
33
36
|
return { sql, bindings }
|
|
34
37
|
}
|
|
35
38
|
|
package/src/kernel/plugin.ts
CHANGED
|
@@ -20,10 +20,23 @@ export interface PredicateOperators {
|
|
|
20
20
|
}
|
|
21
21
|
/** Child field correlates to parentField on the current table; identifiers are server-owned. */
|
|
22
22
|
export interface PredicateRelation { entity: string; field: string; parentField: string; predicate: Predicate }
|
|
23
|
+
/** Trusted policy-only probe. Authority comes from the live server projection;
|
|
24
|
+
* renderers recheck membership/account/token in the same statement as the row. */
|
|
25
|
+
export interface PredicateActorLink {
|
|
26
|
+
entity: string; organizationId: string; accountId: string; membershipRole: string
|
|
27
|
+
token?: { id: string; role: string }
|
|
28
|
+
}
|
|
23
29
|
export type Predicate = { all: readonly Predicate[] } | { any: readonly Predicate[] }
|
|
24
30
|
| { not: Predicate } | { exists: PredicateRelation } | { notExists: PredicateRelation }
|
|
31
|
+
| { actorLinkedIn: PredicateActorLink }
|
|
32
|
+
/** Mandatory top-level conjunct emitted by the policy compiler. */
|
|
33
|
+
| { actorAuthority: Omit<PredicateActorLink, 'entity'> }
|
|
25
34
|
| { [field: string]: PredicateOperators }
|
|
26
|
-
export type TableFilter = { kind: 'all' } | { kind: 'none'; deny?: 'empty' | 'forbidden' } | { kind: 'where'; predicate: Predicate; deny?: 'empty' | 'forbidden' }
|
|
35
|
+
export type TableFilter = ({ kind: 'all' } | { kind: 'none'; deny?: 'empty' | 'forbidden' } | { kind: 'where'; predicate: Predicate; deny?: 'empty' | 'forbidden' }) & {
|
|
36
|
+
/** Mandatory request authority, independent of row selection and constant
|
|
37
|
+
* folding. The final expanded compiler emits these as root conjuncts. */
|
|
38
|
+
actorAuthorities?: readonly Omit<PredicateActorLink, 'entity'>[]
|
|
39
|
+
}
|
|
27
40
|
export type GuardResult = { allow: true } | { allow: false; code: string }
|
|
28
41
|
export type ResourceAction = OrganizationAction | 'audit.read' | 'workflows.read' | 'workflows.resume' | 'workflows.cancel'
|
|
29
42
|
/** Metadata only; no planning function, store or execution capability is exposed. */
|
package/src/kernel/predicate.ts
CHANGED
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
import { quote } from '../migrations/schema'
|
|
2
|
-
import type { Predicate, PredicateRelation, PredicateValue } from './plugin'
|
|
2
|
+
import type { Predicate, PredicateActorLink, PredicateRelation, PredicateValue, TableFilter } from './plugin'
|
|
3
|
+
|
|
4
|
+
export class PolicyExpansionLimit extends Error {}
|
|
5
|
+
|
|
6
|
+
/** Expand every related source before separating mandatory request authority from
|
|
7
|
+
* row selection. Both read and pre/post-image compilers consume this same tree;
|
|
8
|
+
* renderers must not introduce another table policy inside a quantifier. */
|
|
9
|
+
export function expandPolicyFilter(entity: string, tableFilter: (entity: string) => TableFilter, maxReferences = 64): TableFilter {
|
|
10
|
+
let references = 0
|
|
11
|
+
const authorities = new Map<string, Omit<PredicateActorLink, 'entity'>>()
|
|
12
|
+
function authority(link: Omit<PredicateActorLink, 'entity'>) {
|
|
13
|
+
const key = JSON.stringify([link.organizationId, link.accountId, link.membershipRole, link.token?.id, link.token?.role])
|
|
14
|
+
authorities.set(key, link)
|
|
15
|
+
}
|
|
16
|
+
function visit(node: Predicate): Predicate {
|
|
17
|
+
if ('actorAuthority' in node) {
|
|
18
|
+
authority(node.actorAuthority as Omit<PredicateActorLink, 'entity'>)
|
|
19
|
+
return { all: [] }
|
|
20
|
+
}
|
|
21
|
+
if ('actorLinkedIn' in node) {
|
|
22
|
+
const { entity: _entity, ...link } = node.actorLinkedIn as PredicateActorLink
|
|
23
|
+
authority(link)
|
|
24
|
+
return node
|
|
25
|
+
}
|
|
26
|
+
if ('all' in node && Array.isArray(node.all)) return { all: (node.all as Predicate[]).map(visit) }
|
|
27
|
+
if ('any' in node && Array.isArray(node.any)) return { any: (node.any as Predicate[]).map(visit) }
|
|
28
|
+
if ('not' in node) return { not: visit(node.not as Predicate) }
|
|
29
|
+
const key = 'exists' in node ? 'exists' : 'notExists' in node ? 'notExists' : undefined
|
|
30
|
+
if (!key) return node
|
|
31
|
+
const relation = (node as Record<string, PredicateRelation>)[key]
|
|
32
|
+
const scoped = expand(relation.entity)
|
|
33
|
+
const expanded = { ...relation, predicate: { all: [scoped, visit(relation.predicate)] } }
|
|
34
|
+
return key === 'exists' ? { exists: expanded } : { notExists: expanded }
|
|
35
|
+
}
|
|
36
|
+
function expand(entity: string, filter = tableFilter(entity)): Predicate {
|
|
37
|
+
if (++references > maxReferences) throw new PolicyExpansionLimit('Expanded policy graph exceeds table reference budget')
|
|
38
|
+
filter.actorAuthorities?.forEach(authority)
|
|
39
|
+
return filter.kind === 'where' ? visit(filter.predicate) : filter.kind === 'all' ? { all: [] } : { any: [] }
|
|
40
|
+
}
|
|
41
|
+
const root = tableFilter(entity)
|
|
42
|
+
const expanded = expand(entity, root)
|
|
43
|
+
if (root.kind !== 'where' && !authorities.size) return root
|
|
44
|
+
return { ...root, kind: 'where', predicate: authorities.size ? { all: [...authorities.values()].map(link => ({ actorAuthority: link } as Predicate)).concat(expanded) } : expanded }
|
|
45
|
+
}
|
|
3
46
|
|
|
4
47
|
/** Structured predicates only. The query compiler supplies the active library value/EXISTS renderers. */
|
|
5
48
|
export function renderPredicate(predicate: Predicate, tableAlias: string,
|
|
@@ -12,7 +55,7 @@ export function renderPredicate(predicate: Predicate, tableAlias: string,
|
|
|
12
55
|
if (bindValue) return bindValue(value as Exclude<PredicateValue, null>)
|
|
13
56
|
bindings.push(typeof value === 'boolean' ? Number(value) : value); return '?'
|
|
14
57
|
}
|
|
15
|
-
function render(node: Predicate): string {
|
|
58
|
+
function render(node: Predicate, negated = false): string {
|
|
16
59
|
if (!node || typeof node !== 'object' || Array.isArray(node)) throw new Error('Invalid predicate')
|
|
17
60
|
const entries = Object.entries(node)
|
|
18
61
|
if (!entries.length) throw new Error('Empty predicate')
|
|
@@ -20,11 +63,32 @@ export function renderPredicate(predicate: Predicate, tableAlias: string,
|
|
|
20
63
|
if (logical) {
|
|
21
64
|
if (entries.length !== 1) throw new Error('Invalid predicate combinator')
|
|
22
65
|
const [key, children] = logical as ['all' | 'any', Predicate[]]
|
|
23
|
-
|
|
66
|
+
const all = (key === 'all') !== negated
|
|
67
|
+
return `(${children.length ? children.map(child => render(child, negated)).join(all ? ' AND ' : ' OR ') : all ? '1=1' : '0=1'})`
|
|
24
68
|
}
|
|
25
69
|
if (Object.hasOwn(node, 'not')) {
|
|
26
70
|
if (entries.length !== 1) throw new Error('Invalid predicate combinator')
|
|
27
|
-
return
|
|
71
|
+
return render((node as { not: Predicate }).not, !negated)
|
|
72
|
+
}
|
|
73
|
+
if (Object.hasOwn(node, 'actorAuthority')) {
|
|
74
|
+
if (entries.length !== 1 || negated) throw new Error('Invalid actor authority predicate')
|
|
75
|
+
const link = (node as { actorAuthority: Omit<PredicateActorLink, 'entity'> }).actorAuthority
|
|
76
|
+
// The policy compiler hoists this mandatory conjunct outside all Boolean
|
|
77
|
+
// operators and relation quantifiers. Pin roles and issuer at execution.
|
|
78
|
+
return `(EXISTS(SELECT 1 FROM memberships AS __actor_link_member
|
|
79
|
+
JOIN users AS __actor_link_account ON __actor_link_account.id=__actor_link_member.user_id AND __actor_link_account.organization_id=__actor_link_member.organization_id
|
|
80
|
+
${link.token ? 'JOIN access_tokens AS __actor_link_token ON __actor_link_token.issuer_id=__actor_link_member.user_id AND __actor_link_token.organization_id=__actor_link_member.organization_id' : ''}
|
|
81
|
+
WHERE __actor_link_member.organization_id=${alias}.organization_id AND __actor_link_member.organization_id=${bind(link.organizationId)}
|
|
82
|
+
AND __actor_link_member.user_id=${bind(link.accountId)} AND __actor_link_member.role=${bind(link.membershipRole)}
|
|
83
|
+
${link.token ? `AND __actor_link_token.id=${bind(link.token.id)} AND __actor_link_token.role=${bind(link.token.role)} AND __actor_link_token.revoked_at IS NULL AND __actor_link_token.expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')` : ''}))`
|
|
84
|
+
}
|
|
85
|
+
if (Object.hasOwn(node, 'actorLinkedIn')) {
|
|
86
|
+
if (entries.length !== 1) throw new Error('Invalid actorLinkedIn predicate')
|
|
87
|
+
const link = (node as { actorLinkedIn: PredicateActorLink }).actorLinkedIn
|
|
88
|
+
// Only link presence is negatable. Bypass target read policies/transforms
|
|
89
|
+
// with one indexed lookup per predicate, without per-row policy recursion.
|
|
90
|
+
return `(${negated ? 'NOT ' : ''}EXISTS(SELECT 1 FROM ${quote(link.entity)} AS __actor_link
|
|
91
|
+
WHERE __actor_link.organization_id=${alias}.organization_id AND __actor_link.organization_id=${bind(link.organizationId)} AND __actor_link.user=${bind(link.accountId)}))`
|
|
28
92
|
}
|
|
29
93
|
const relationKey = Object.hasOwn(node, 'exists') ? 'exists' : Object.hasOwn(node, 'notExists') ? 'notExists' : undefined
|
|
30
94
|
if (relationKey) {
|
|
@@ -33,9 +97,9 @@ export function renderPredicate(predicate: Predicate, tableAlias: string,
|
|
|
33
97
|
if (!relation || Object.keys(relation).length !== 4 || !['entity', 'field', 'parentField', 'predicate'].every(key => Object.hasOwn(relation, key))
|
|
34
98
|
|| ![relation.entity, relation.field, relation.parentField].every(value => typeof value === 'string')) throw new Error('Invalid predicate relation')
|
|
35
99
|
quote(relation.entity); quote(relation.field); quote(relation.parentField)
|
|
36
|
-
return `(${renderRelation(relation, tableAlias, relationKey === 'notExists')})`
|
|
100
|
+
return `(${renderRelation(relation, tableAlias, (relationKey === 'notExists') !== negated)})`
|
|
37
101
|
}
|
|
38
|
-
|
|
102
|
+
const scalar = `(${entries.flatMap(([field, operators]) => {
|
|
39
103
|
const column = `${alias}.${quote(field)}`
|
|
40
104
|
if (!operators || typeof operators !== 'object' || Array.isArray(operators) || !Object.keys(operators).length) throw new Error('Invalid predicate operator')
|
|
41
105
|
return Object.entries(operators).map(([op, value]) => {
|
|
@@ -64,6 +128,7 @@ export function renderPredicate(predicate: Predicate, tableAlias: string,
|
|
|
64
128
|
return `${column}${sqlOp}${bind(value)}`
|
|
65
129
|
})
|
|
66
130
|
}).join(' AND ')})`
|
|
131
|
+
return negated ? `(NOT ${scalar})` : scalar
|
|
67
132
|
}
|
|
68
133
|
return { sql: render(predicate), bindings }
|
|
69
134
|
}
|
package/src/kernel/registry.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { ApiError } from '../errors'
|
|
|
8
8
|
import type { App, ResolvedActor, RuntimeEnv, RuntimeOptions, Scope } from '../types'
|
|
9
9
|
import type { AuditEvent } from '../audit-event'
|
|
10
10
|
import type { AtomicOperation } from '../execution/types'
|
|
11
|
-
import type { KernelCommand, ResourceAction, PluginMigration, TableFilter, WorkbasePlugin } from './plugin'
|
|
11
|
+
import type { KernelCommand, ResourceAction, PluginMigration, Predicate, TableFilter, WorkbasePlugin } from './plugin'
|
|
12
12
|
import { renderPredicate } from './predicate'
|
|
13
13
|
export { renderPredicate } from './predicate'
|
|
14
14
|
import { resolvePlugins } from './composition'
|
|
@@ -147,9 +147,13 @@ export class KernelRegistry {
|
|
|
147
147
|
if (!this.trust && !this.hasAuthorization) return { kind: 'none' }
|
|
148
148
|
const filters = this.plugins.flatMap(plugin => plugin.tableFilter ? [plugin.tableFilter.call(this, entity, scope)] : [])
|
|
149
149
|
if (!filters.length) return { kind: this.trust ? 'all' : 'none' }
|
|
150
|
-
|
|
150
|
+
// A denying provider may erase row selection, but never request authority
|
|
151
|
+
// needed by an enclosing policy that negates this source's existence.
|
|
152
|
+
const actorAuthorities = filters.flatMap(filter => filter.actorAuthorities ?? [])
|
|
153
|
+
const authority = actorAuthorities.length ? { actorAuthorities } : {}
|
|
154
|
+
if (filters.some(filter => filter.kind === 'none')) return { kind: 'none', ...authority, ...(filters.some(filter => 'deny' in filter && filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) }
|
|
151
155
|
const where = filters.filter((filter): filter is Extract<TableFilter, { kind: 'where' }> => filter.kind === 'where')
|
|
152
|
-
return where.length ? { kind: 'where', predicate: { all: where.map(filter => filter.predicate) }, ...(where.some(filter => filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) } : { kind: 'all' }
|
|
156
|
+
return where.length ? { kind: 'where', predicate: { all: where.map(filter => filter.predicate) }, ...authority, ...(where.some(filter => filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) } : { kind: 'all', ...authority }
|
|
153
157
|
}
|
|
154
158
|
fieldMask(entity: string, scope: Scope): string[] {
|
|
155
159
|
let fields = [...baseFields, ...Object.keys(this.config.entities[entity].fields)]
|
|
@@ -200,5 +204,9 @@ export function kernelFor(config: InstanceConfig): KernelRegistry {
|
|
|
200
204
|
/** Preserve the selected ports across immutable execution-context config snapshots. */
|
|
201
205
|
export function bindKernel(source: InstanceConfig, target: InstanceConfig) { registries.set(target, kernelFor(source)) }
|
|
202
206
|
export function filterSql(filter: TableFilter, tableAlias: string): { sql: string; bindings: unknown[] } {
|
|
207
|
+
if (filter.actorAuthorities?.length) {
|
|
208
|
+
const row: Predicate = filter.kind === 'where' ? filter.predicate : filter.kind === 'all' ? { all: [] } : { any: [] }
|
|
209
|
+
return renderPredicate({ all: [...filter.actorAuthorities.map(actorAuthority => ({ actorAuthority })), row] }, tableAlias)
|
|
210
|
+
}
|
|
203
211
|
return filter.kind === 'where' ? renderPredicate(filter.predicate, tableAlias) : { sql: filter.kind === 'all' ? '1=1' : '0=1', bindings: [] }
|
|
204
212
|
}
|
package/src/policies.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { constantQuantifier } from './config-shorthand'
|
|
|
2
2
|
import { z } from 'zod'
|
|
3
3
|
import { baseFields, type Field, type InstanceConfig } from './config'
|
|
4
4
|
import { fieldsFor, fieldType, filterSchema, type Filter } from './query/schema'
|
|
5
|
-
import type { Predicate, PredicateOperators, TableFilter } from './kernel/plugin'
|
|
5
|
+
import type { Predicate, PredicateActorLink, PredicateOperators, TableFilter } from './kernel/plugin'
|
|
6
6
|
import type { Scope } from './types'
|
|
7
7
|
import { ApiError } from './errors'
|
|
8
8
|
import { roleNamePrivileges } from './organization-permissions'
|
|
@@ -85,6 +85,36 @@ export async function loadActorProjection(config: InstanceConfig, scope: Scope,
|
|
|
85
85
|
}
|
|
86
86
|
export function actorAccountId(scope: Scope): string { return String(projections.get(scope)?.id ?? scope.actor.id) }
|
|
87
87
|
export function copyActorProjection(source: Scope, target: Scope) { const row = projections.get(source); if (row) projections.set(target, row) }
|
|
88
|
+
function actorLinkProjection(scope: Scope): Omit<PredicateActorLink, 'entity'> | undefined {
|
|
89
|
+
const actor = projections.get(scope)
|
|
90
|
+
return actor ? {
|
|
91
|
+
organizationId: scope.organizationId, accountId: String(actor.id), membershipRole: String(actor.role),
|
|
92
|
+
...(scope.actor.type === 'agent' ? { token: { id: scope.actor.tokenId ?? scope.actor.id, role: scope.role } } : {}),
|
|
93
|
+
} : undefined
|
|
94
|
+
}
|
|
95
|
+
/** Constant folding and missing operands must not erase authority reachable via
|
|
96
|
+
* a related policy: that FALSE source can itself be used beneath none/not. */
|
|
97
|
+
function policyGraphUsesActorLinks(config: InstanceConfig, entity: string, roles: string[]): boolean {
|
|
98
|
+
const visited = new Set<string>()
|
|
99
|
+
function policy(name: string): boolean {
|
|
100
|
+
if (visited.has(name)) return false
|
|
101
|
+
visited.add(name)
|
|
102
|
+
return roles.some(role => {
|
|
103
|
+
const entry = config.policies[name]?.[role]
|
|
104
|
+
return typeof entry === 'object' && filter(name, entry.where)
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
function filter(name: string, where: Filter): boolean {
|
|
108
|
+
return Object.entries(where).some(([key, value]) => {
|
|
109
|
+
if (key === 'actorLinkedIn') return true
|
|
110
|
+
if (key === 'and' || key === 'or') return (value as Filter[]).some(child => filter(name, child))
|
|
111
|
+
if (key === 'not') return filter(name, value as Filter)
|
|
112
|
+
const relation = config.entities[name].relations[key]
|
|
113
|
+
return !!relation && (policy(relation.entity) || filter(relation.entity, (relation.many ? Object.values(value as Record<string, Filter>)[0] : value) as Filter))
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
return policy(entity)
|
|
117
|
+
}
|
|
88
118
|
function rolePolicyFilter(config: InstanceConfig, entity: string, scope: Scope, role: string): TableFilter {
|
|
89
119
|
if (scope.actor.type === 'service' && scope.role === 'SYSTEM') return { kind: 'all' }
|
|
90
120
|
const actor = projections.get(scope)
|
|
@@ -106,23 +136,30 @@ function rolePolicyFilter(config: InstanceConfig, entity: string, scope: Scope,
|
|
|
106
136
|
if (typeof value === 'string' && value.startsWith('$actor.')) return actor![value.slice(7)] ?? null
|
|
107
137
|
return Array.isArray(value) ? value.map(substitute) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, child]) => [key, substitute(child)])) : value
|
|
108
138
|
}
|
|
109
|
-
const predicate = compilePolicyPredicate(config, entity, policy.where, substitute)
|
|
139
|
+
const predicate = compilePolicyPredicate(config, entity, policy.where, substitute, actorLinkProjection(scope))
|
|
110
140
|
if (constantPredicate(predicate) === false) return { kind: 'none', ...(policy.deny === 'forbidden' ? { deny: 'forbidden' as const } : {}) }
|
|
111
141
|
return { kind: 'where', predicate, ...(policy.deny === 'forbidden' ? { deny: 'forbidden' as const } : {}) }
|
|
112
142
|
}
|
|
113
|
-
function compilePolicyPredicate(config: InstanceConfig, name: string, filter: Filter, substitute: (value: unknown) => unknown): Predicate {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
143
|
+
function compilePolicyPredicate(config: InstanceConfig, name: string, filter: Filter, substitute: (value: unknown) => unknown, actorLink?: Omit<PredicateActorLink, 'entity'>): Predicate {
|
|
144
|
+
function compile(name: string, filter: Filter): Predicate {
|
|
145
|
+
return { all: Object.entries(filter).map(([key, value]): Predicate => {
|
|
146
|
+
if (key === 'and' || key === 'or') return { [key === 'and' ? 'all' : 'any']: (value as Filter[]).map(child => compile(name, child)) } as Predicate
|
|
147
|
+
if (key === 'not') return { not: compile(name, value as Filter) }
|
|
148
|
+
if (key === 'actorLinkedIn') {
|
|
149
|
+
if (!actorLink) throw new Error('actorLinkedIn requires a live actor projection')
|
|
150
|
+
return { actorLinkedIn: { ...actorLink, entity: value as string } }
|
|
151
|
+
}
|
|
152
|
+
const relation = config.entities[name].relations[key]
|
|
153
|
+
if (relation) {
|
|
154
|
+
const none = relation.many && Object.hasOwn(value as object, 'none')
|
|
155
|
+
return { [none ? 'notExists' : 'exists']: { entity: relation.entity, field: relation.many ? relation.field : 'id', parentField: relation.many ? 'id' : relation.field,
|
|
156
|
+
predicate: compile(relation.entity, (relation.many ? (value as Record<string, Filter>)[none ? 'none' : 'some'] : value) as Filter) } } as Predicate
|
|
157
|
+
}
|
|
158
|
+
const operators = substitute(value) as PredicateOperators
|
|
159
|
+
return { [key]: operators }
|
|
160
|
+
}) }
|
|
161
|
+
}
|
|
162
|
+
return compile(name, filter)
|
|
126
163
|
}
|
|
127
164
|
/** Fold only Boolean constants; no database state is inferred by capability metadata. */
|
|
128
165
|
function constantPredicate(node: Predicate): boolean | undefined {
|
|
@@ -153,10 +190,18 @@ export function hasOwnerRole(scope: Scope): boolean {
|
|
|
153
190
|
return (scope.actor.type !== 'agent' || projections.has(scope)) && rbacRoles(scope).every(role => roleNamePrivileges(role).has('audit.read'))
|
|
154
191
|
}
|
|
155
192
|
export function policyFilter(config: InstanceConfig, entity: string, scope: Scope): TableFilter {
|
|
156
|
-
const
|
|
157
|
-
|
|
193
|
+
const roles = rbacRoles(scope)
|
|
194
|
+
const filters = roles.map(role => rolePolicyFilter(config, entity, scope, role))
|
|
158
195
|
const where = filters.filter((filter): filter is Extract<TableFilter, { kind: 'where' }> => filter.kind === 'where')
|
|
159
|
-
|
|
196
|
+
const result: TableFilter = filters.some(filter => filter.kind === 'none')
|
|
197
|
+
? { kind: 'none', ...(filters.some(filter => 'deny' in filter && filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) }
|
|
198
|
+
: where.length ? { kind: 'where', predicate: { all: where.map(filter => filter.predicate) }, ...(where.some(filter => filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) } : { kind: 'all' }
|
|
199
|
+
const authority = actorLinkProjection(scope)
|
|
200
|
+
// Collect from the complete configured graph before Boolean folding, operand
|
|
201
|
+
// denial or the role intersection can erase a related source. All requirements
|
|
202
|
+
// use this request's organization and principal, so hoisting is row-independent
|
|
203
|
+
// even beneath none/not/every and across different effective roles.
|
|
204
|
+
return authority && policyGraphUsesActorLinks(config, entity, roles) ? { ...result, actorAuthorities: [authority] } : result
|
|
160
205
|
}
|
|
161
206
|
export function readableFields(config: InstanceConfig, entity: string, scope: Scope): string[] {
|
|
162
207
|
return [...baseFields, ...Object.keys(config.entities[entity].fields)].filter(field => rbacRoles(scope).every(role => {
|
package/src/query/compiler.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { expressionInfo, readableComputed, rebindExpression, type ExpressionInfo
|
|
|
3
3
|
import { ApiError } from '../errors'
|
|
4
4
|
import { Q, Fn, Cond, Condition, toSQLWithBindings, type ISQLFlavor, type SelectQuery, type ISequelizable } from '@jakub.knejzlik/ts-query'
|
|
5
5
|
import { renderPredicate, type KernelRegistry } from '../kernel/registry'
|
|
6
|
+
import { expandPolicyFilter, PolicyExpansionLimit } from '../kernel/predicate'
|
|
6
7
|
import type { TableFilter, PredicateRelation } from '../kernel/plugin'
|
|
7
8
|
import type { Scope } from '../types'
|
|
8
9
|
import { quote } from '../migrations/schema'
|
|
@@ -362,22 +363,25 @@ export function renderStatement(kernel: KernelRegistry, scope: Scope, ast: Selec
|
|
|
362
363
|
} else query = query.field(col(alias, field))
|
|
363
364
|
}
|
|
364
365
|
if (!fields.length) query = query.field(Q.raw('1'), '__policy_row')
|
|
365
|
-
query = query.where(new ScopedCondition(kernel.tableFilter(
|
|
366
|
+
query = query.where(new ScopedCondition(expandPolicyFilter(entity, child => kernel.tableFilter(child, scope), L.tableReferences), alias, relation))
|
|
366
367
|
return extra ? query.where(extra(alias)) : query
|
|
367
368
|
}
|
|
368
369
|
function relation(node: PredicateRelation, parent: string, negated: boolean, flavor: ISQLFlavor): string {
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
//
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
]), false) })
|
|
370
|
+
if (++references > L.tableReferences) throw new QueryError('query_too_expensive', [], cost)
|
|
371
|
+
const child = `scope_row_${references}`; const visible = `${child}_visible`
|
|
372
|
+
// The shared expansion already scoped this source and moved all authority to
|
|
373
|
+
// the root. Expose only the stored correlation key; no field projection or
|
|
374
|
+
// policy expansion may add authority back beneath this quantifier.
|
|
375
|
+
const explicit = new ScopedCondition({ kind: 'where', predicate: node.predicate }, child, relation).toSQL(flavor)
|
|
376
|
+
return `${negated ? 'NOT ' : ''}EXISTS(SELECT 1 FROM (SELECT ${quote(child)}.${quote(node.field)} AS ${quote('policy_key')} FROM ${quote(node.entity)} AS ${quote(child)} WHERE ${explicit}) AS ${quote(visible)} WHERE ${quote(visible)}.${quote('policy_key')}=${quote(parent)}.${quote(node.parentField)})`
|
|
377
377
|
}
|
|
378
378
|
try {
|
|
379
379
|
return assertStatement(compactBindings(toSQLWithBindings(ast, numberedSQLite, { transformTable: entity => scopedTable(entity) })), cost)
|
|
380
|
-
} catch (error) {
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (error instanceof PolicyExpansionLimit) throw new QueryError('query_too_expensive', [], cost)
|
|
382
|
+
if (error instanceof ApiError) throw error
|
|
383
|
+
throw new QueryError('query_invalid')
|
|
384
|
+
}
|
|
381
385
|
}
|
|
382
386
|
|
|
383
387
|
/** Expression demand follows all user-visible uses, including unprojected filters.
|
package/src/query/schema.ts
CHANGED
|
@@ -29,7 +29,7 @@ function valueSchema(config: InstanceConfig, entity: string, field: string, rest
|
|
|
29
29
|
return type === 'bool' ? z.boolean() : type === 'int' ? z.number().int().safe()
|
|
30
30
|
: type === 'float' ? z.number().finite() : z.string().max(2_000)
|
|
31
31
|
}
|
|
32
|
-
/** Shared client/policy grammar; only trusted configuration enables actor
|
|
32
|
+
/** Shared client/policy grammar; only trusted configuration enables actor predicates. */
|
|
33
33
|
export function filterSchema(config: InstanceConfig, rest = false, maxDepth = L.relationDepth as number,
|
|
34
34
|
actorValues?: (type: Field['type']) => z.ZodType) {
|
|
35
35
|
const filters = new Map<string, z.ZodType>()
|
|
@@ -49,6 +49,9 @@ export function filterSchema(config: InstanceConfig, rest = false, maxDepth = L.
|
|
|
49
49
|
const child = filter(r.entity, depth + 1)
|
|
50
50
|
shape[relation] = (r.many ? z.union([z.strictObject({ some: child }), z.strictObject({ none: child })]) : child).optional()
|
|
51
51
|
}
|
|
52
|
+
if (actorValues) shape.actorLinkedIn = z.string().refine(entity =>
|
|
53
|
+
Object.hasOwn(config.entities, entity) && Object.values(config.entities[entity].fields).some(field => field.userLink),
|
|
54
|
+
'actorLinkedIn requires an entity with a protected user link').optional()
|
|
52
55
|
shape.and = z.array(schema).min(1).max(L.nodes).optional()
|
|
53
56
|
shape.or = z.array(schema).min(1).max(L.nodes).optional()
|
|
54
57
|
shape.not = schema.optional()
|