@fabrika/db 0.9.0-dev.12 → 0.9.0-dev.14

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/src/registry.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // files may import.
4
4
 
5
5
  import type { Admissions } from './admissions'
6
+ import type { ContainerGrant, RelationHold } from './capability'
6
7
  import type { Session } from './database'
7
8
  import type { WebhookTables } from './framework-tables'
8
9
  import type { JobLeases } from './job-leases'
@@ -17,6 +18,41 @@ import type { StoredFiles } from './stored-files'
17
18
  */
18
19
  export type Locator = (dimension: string, id: string, using?: Session) => Promise<ReadonlyMap<string, string> | null>
19
20
 
21
+ /** Whether an active row of `relation`'s source names `principal` at `node`: what a Ref held through it is minted on. */
22
+ export type RelationCheck = (relation: string, node: string, principal: string) => Promise<boolean>
23
+
24
+ /**
25
+ * Whether a row `relation` reaches for `principal` reveals `node` of `dimension` now: what a Ref held through a reveal
26
+ * is minted on.
27
+ */
28
+ export type RevealCheck = (relation: string, dimension: string, node: string, principal: string, action: string) => Promise<boolean>
29
+
30
+ /**
31
+ * Of `relations` and `paths`, the caller's relations and grants of `action` that reach the object `id` of `dimension`
32
+ * through a secondary path that holds the action for a Ref (`writeThrough`), or through a relation row or reveal: what a
33
+ * Ref held through a path is minted on, and carries.
34
+ */
35
+ export type PathCheck = (
36
+ dimension: string,
37
+ id: string,
38
+ action: string,
39
+ principal: string,
40
+ relations: readonly RelationHold[],
41
+ paths: readonly ContainerGrant[],
42
+ ) => Promise<{ readonly relations: readonly RelationHold[]; readonly paths: readonly ContainerGrant[] }>
43
+
44
+ /**
45
+ * Of `values`, the caller's grants of `action` at nodes of `revealing`, those whose row reveals `node` of `dimension` to
46
+ * its members now: what a Ref held through member reveals is minted on, and carries.
47
+ */
48
+ export type MemberRevealCheck = (
49
+ revealing: string,
50
+ values: readonly string[],
51
+ dimension: string,
52
+ node: string,
53
+ action: string,
54
+ ) => Promise<readonly string[]>
55
+
20
56
  /** What the framework writes itself: its own `fabrika_*` tables. Usable once bound. */
21
57
  export interface FrameworkTables {
22
58
  readonly webhooks: WebhookTables
@@ -32,6 +68,10 @@ export interface FrameworkTables {
32
68
  /** A connection of the layer and its locator. Only its holder can `release` it, which lets the layer be bound again. */
33
69
  export interface ProvisionalBinding {
34
70
  readonly locate: Locator
71
+ readonly relates: RelationCheck
72
+ readonly reveals: RevealCheck
73
+ readonly holdsThrough: PathCheck
74
+ readonly revealsToMembers: MemberRevealCheck
35
75
  release(): void
36
76
  }
37
77
 
package/src/sql.ts CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  ReadSql,
17
17
  referencedForeignSchema,
18
18
  refusedCall,
19
+ SQLITE_PARAMETER_STARTS,
19
20
  type SqlToken,
20
21
  statementKind,
21
22
  statementsOf,
@@ -119,8 +120,6 @@ const WRITE_WORDS: ReadonlySet<string> = new Set(['INSERT', 'UPDATE', 'DELETE',
119
120
  const LOCK_WORDS: ReadonlySet<string> = new Set(['UPDATE', 'NO', 'SHARE', 'KEY'])
120
121
  /** ctx.sql calls reviewed built-ins only: the functions the migrations declare are not known at runtime. */
121
122
  const NO_DECLARED_FUNCTIONS: ReadonlySet<string> = new Set()
122
- /** What starts a parameter SQLite binds by name or by position (`?`, `:x`, `@x`, `$x`, `#x`): only the tag writes one. */
123
- const SQLITE_PARAMETER_STARTS: ReadonlySet<string> = new Set(['?', ':', '@', '$', '#'])
124
123
 
125
124
  function refuse(reason: QueryRefusal, message: string): never {
126
125
  throw new QueryRefusedError(reason, `ctx.sql: ${message}`)
@@ -238,6 +237,18 @@ function sqliteNameRefusal(tokens: readonly SqlToken[]): { readonly name: string
238
237
  return undefined
239
238
  }
240
239
 
240
+ /**
241
+ * The name of a table whose rows hand out access anywhere in a statement of a writing site, in any spelling: only the
242
+ * data layer's insert bounds the delegation, or generates the key a grant names. No statement kind is trusted to be a read (SQLite's `WITH … REPLACE`).
243
+ */
244
+ function sourceReference(tokens: readonly SqlToken[], sources: readonly string[]): { readonly name: string; readonly line: number } | undefined {
245
+ for (const token of tokens) {
246
+ const text = token.kind === 'word' || token.kind === 'quoted' || token.kind === 'string' ? token.text : undefined
247
+ if (text !== undefined && sources.includes(text.toLowerCase())) return { name: text, line: token.line }
248
+ }
249
+ return undefined
250
+ }
251
+
241
252
  /**
242
253
  * The SQL `parts` make, with a bound placeholder for each value, or a `QueryRefusedError` that names what is refused.
243
254
  * On both dialects: more than one statement, any statement but a query (and `INSERT`/`UPDATE`/`DELETE` for
@@ -246,7 +257,7 @@ function sqliteNameRefusal(tokens: readonly SqlToken[]): { readonly name: string
246
257
  * name outside `schema` and a function outside the reviewed built-ins; on SQLite also a `sqlite_*` name, and a
247
258
  * parameter the text writes itself. workerd's authorizer bounds SQLite's functions, PRAGMAs and DDL.
248
259
  */
249
- export function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase): string {
260
+ export function classifySql(parts: readonly string[], mode: SqlMode, database: SqlDatabase, sources: readonly string[] = []): string {
250
261
  const all = placedTokens(parts, database)
251
262
  const statements = statementsOf(all)
252
263
  const [statement] = statements
@@ -271,6 +282,13 @@ export function classifySql(parts: readonly string[], mode: SqlMode, database: S
271
282
  if (writes !== undefined) {
272
283
  refuse('sql_read_only', `sql: 'read' runs queries only, and the statement holds ${writes}; declare sql: 'write' on a mutation, a job or a webhook`)
273
284
  }
285
+ const source = mode === 'write' ? sourceReference(tokens, sources) : undefined
286
+ if (source !== undefined) {
287
+ refuse(
288
+ 'sql_name',
289
+ `'${source.name}' at line ${source.line} hands out access, so a statement that writes never names it: write its rows through ctx.db`,
290
+ )
291
+ }
274
292
  const framework = frameworkReference(tokens)
275
293
  if (framework !== undefined) {
276
294
  refuse('sql_name', `'${framework.name}' at line ${framework.line} is the framework's; ctx.sql reaches only the application's own tables`)
@@ -566,7 +584,7 @@ function scopeOptions(options: unknown): { readonly alias: string | undefined; r
566
584
  * `ctx.sql` of one site. Every call first checks that the work running now is the site's invocation, then classifies
567
585
  * the text, then binds the values; only then does it reach the session, so a refused statement sends nothing.
568
586
  */
569
- export function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf): SqlTag {
587
+ export function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf, sources: readonly string[]): SqlTag {
570
588
  const tag = <S extends z.core.$ZodType>(row: S) => {
571
589
  site.check()
572
590
  if (!(row instanceof z.core.$ZodType)) {
@@ -577,7 +595,7 @@ export function sqlTag(site: SqlSite, database: SqlDatabase, termsOf: ScopeOf):
577
595
  site.check()
578
596
  return failing(site, async () => {
579
597
  const expanded = expandScopes(site, templateParts(text), values, database)
580
- const statement = classifySql(expanded.parts, site.mode, database)
598
+ const statement = classifySql(expanded.parts, site.mode, database, sources)
581
599
  const parameters = expanded.values.map((value, index) => parameterOf(value, index + 1, database))
582
600
  const session = await site.session()
583
601
  if (session.readOnly && site.mode === 'write') {
package/src/sqlite.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  type DialectAdapter,
11
11
  type Driver,
12
12
  Kysely,
13
+ type OperationNode,
13
14
  OperatorNode,
14
15
  type QueryResult,
15
16
  type SelectModifierNode,
@@ -17,6 +18,8 @@ import {
17
18
  SqliteAdapter,
18
19
  SqliteIntrospector,
19
20
  SqliteQueryCompiler,
21
+ ValueListNode,
22
+ ValueNode,
20
23
  } from 'kysely'
21
24
  import { Database, freezePrototypeChain, type LooseDB, type TransactionRunner } from './database'
22
25
  import { DatabaseError, QueryRefusedError } from './errors'
@@ -40,6 +43,14 @@ export interface SqliteStorage {
40
43
  transactionSync<T>(closure: () => T): T
41
44
  }
42
45
 
46
+ // Captured at load, as the compiler's prototype is frozen at load: a later patch would change what a list binds.
47
+ const stringify = JSON.stringify
48
+ const test = RegExp.prototype.test
49
+ const apply = Reflect.apply
50
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/
51
+
52
+ const MEMBERSHIP_OPERATORS: ReadonlySet<string> = new Set(['in', 'not in'])
53
+
43
54
  const LIKE_OPERATORS: ReadonlyMap<string, string> = new Map([
44
55
  ['like', 'like'],
45
56
  ['ilike', 'like'],
@@ -64,7 +75,17 @@ class SqliteCompiler extends SqliteQueryCompiler {
64
75
  }
65
76
 
66
77
  protected override visitBinaryOperation(node: BinaryOperationNode): void {
67
- const pattern = OperatorNode.is(node.operator) ? LIKE_OPERATORS.get(node.operator.operator) : undefined
78
+ const operator = OperatorNode.is(node.operator) ? node.operator.operator : undefined
79
+ const texts = operator !== undefined && MEMBERSHIP_OPERATORS.has(operator) ? jsonTexts(node.rightOperand) : undefined
80
+ if (texts !== undefined) {
81
+ // workerd binds at most 100 parameters a statement, and a Within alone carries up to MAX_WITHIN_VALUES.
82
+ this.visitNode(node.leftOperand)
83
+ this.append(` ${operator} (select value from json_each(`)
84
+ this.appendValue(texts)
85
+ this.append('))')
86
+ return
87
+ }
88
+ const pattern = operator === undefined ? undefined : LIKE_OPERATORS.get(operator)
68
89
  if (pattern === undefined) {
69
90
  super.visitBinaryOperation(node)
70
91
  return
@@ -81,6 +102,30 @@ class SqliteCompiler extends SqliteQueryCompiler {
81
102
  }
82
103
  }
83
104
 
105
+ /**
106
+ * An `in` list of bound texts as one JSON array text, or undefined when it holds anything else. Each text is serialized
107
+ * on its own (a string has no `toJSON` to consult). A text with a lone surrogate keeps its own parameter: each driver
108
+ * encodes one its own way, and json_each would not decode it to the same bytes.
109
+ */
110
+ function jsonTexts(node: OperationNode): string | undefined {
111
+ if (!ValueListNode.is(node)) {
112
+ return undefined
113
+ }
114
+ const values = node.values
115
+ let json = '['
116
+ for (let index = 0; index < values.length; index++) {
117
+ const value = values[index]
118
+ if (value === undefined || !ValueNode.is(value) || value.immediate === true || typeof value.value !== 'string') {
119
+ return undefined
120
+ }
121
+ if (apply(test, LONE_SURROGATE, [value.value])) {
122
+ return undefined
123
+ }
124
+ json += (index === 0 ? '' : ',') + stringify(value.value)
125
+ }
126
+ return `${json}]`
127
+ }
128
+
84
129
  function sqliteParameter(parameter: unknown): unknown {
85
130
  if (parameter instanceof Date) {
86
131
  if (Number.isNaN(parameter.getTime())) {