@dads-framework/postgres-access 0.2.0 → 0.3.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.
Files changed (135) hide show
  1. package/BENCHMARK.md +94 -8
  2. package/README.md +165 -102
  3. package/dist/compile-access-policy.d.ts +2 -1
  4. package/dist/compile-access-policy.d.ts.map +1 -1
  5. package/dist/compile-access-policy.js +9 -2
  6. package/dist/compile-access-policy.js.map +1 -1
  7. package/dist/drizzle-executor.d.ts +2 -2
  8. package/dist/drizzle-executor.d.ts.map +1 -1
  9. package/dist/drizzle-executor.js.map +1 -1
  10. package/dist/drizzle-structural.d.ts +23 -0
  11. package/dist/drizzle-structural.d.ts.map +1 -0
  12. package/dist/drizzle-structural.js +22 -0
  13. package/dist/drizzle-structural.js.map +1 -0
  14. package/dist/drizzle.d.ts +4 -0
  15. package/dist/drizzle.d.ts.map +1 -0
  16. package/dist/drizzle.js +4 -0
  17. package/dist/drizzle.js.map +1 -0
  18. package/dist/index.d.ts +5 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +3 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/lookup-primary-pool.d.ts +2 -3
  23. package/dist/lookup-primary-pool.d.ts.map +1 -1
  24. package/dist/lookup-primary-pool.js +2 -1
  25. package/dist/lookup-primary-pool.js.map +1 -1
  26. package/dist/lower-permissions.d.ts.map +1 -1
  27. package/dist/lower-permissions.js +37 -12
  28. package/dist/lower-permissions.js.map +1 -1
  29. package/dist/policy/column-relations.d.ts +34 -0
  30. package/dist/policy/column-relations.d.ts.map +1 -0
  31. package/dist/policy/column-relations.js +127 -0
  32. package/dist/policy/column-relations.js.map +1 -0
  33. package/dist/policy/compile-filter.d.ts +41 -0
  34. package/dist/policy/compile-filter.d.ts.map +1 -0
  35. package/dist/policy/compile-filter.js +127 -0
  36. package/dist/policy/compile-filter.js.map +1 -0
  37. package/dist/policy/compile-forward-policy.d.ts +20 -0
  38. package/dist/policy/compile-forward-policy.d.ts.map +1 -0
  39. package/dist/policy/compile-forward-policy.js +129 -0
  40. package/dist/policy/compile-forward-policy.js.map +1 -0
  41. package/dist/policy/compile-linear-batch.d.ts +1 -0
  42. package/dist/policy/compile-linear-batch.d.ts.map +1 -1
  43. package/dist/policy/compile-linear-batch.js +3 -6
  44. package/dist/policy/compile-linear-batch.js.map +1 -1
  45. package/dist/policy/compile-linear-check.d.ts.map +1 -1
  46. package/dist/policy/compile-linear-check.js +53 -9
  47. package/dist/policy/compile-linear-check.js.map +1 -1
  48. package/dist/policy/compile-postgres-policy.d.ts +9 -4
  49. package/dist/policy/compile-postgres-policy.d.ts.map +1 -1
  50. package/dist/policy/compile-postgres-policy.js +91 -118
  51. package/dist/policy/compile-postgres-policy.js.map +1 -1
  52. package/dist/policy/compile-recursive-policy.d.ts +53 -0
  53. package/dist/policy/compile-recursive-policy.d.ts.map +1 -0
  54. package/dist/policy/compile-recursive-policy.js +231 -0
  55. package/dist/policy/compile-recursive-policy.js.map +1 -0
  56. package/dist/policy/compile-recursive-subjects.d.ts +27 -0
  57. package/dist/policy/compile-recursive-subjects.d.ts.map +1 -0
  58. package/dist/policy/compile-recursive-subjects.js +180 -0
  59. package/dist/policy/compile-recursive-subjects.js.map +1 -0
  60. package/dist/policy/compile-reverse-policy.d.ts +12 -2
  61. package/dist/policy/compile-reverse-policy.d.ts.map +1 -1
  62. package/dist/policy/compile-reverse-policy.js +168 -39
  63. package/dist/policy/compile-reverse-policy.js.map +1 -1
  64. package/dist/policy/compile-shared-point-check.d.ts.map +1 -1
  65. package/dist/policy/compile-shared-point-check.js +165 -13
  66. package/dist/policy/compile-shared-point-check.js.map +1 -1
  67. package/dist/policy/compile-subject-lookup.d.ts +8 -0
  68. package/dist/policy/compile-subject-lookup.d.ts.map +1 -0
  69. package/dist/policy/compile-subject-lookup.js +254 -0
  70. package/dist/policy/compile-subject-lookup.js.map +1 -0
  71. package/dist/policy/permission-cycles.d.ts +27 -0
  72. package/dist/policy/permission-cycles.d.ts.map +1 -0
  73. package/dist/policy/permission-cycles.js +181 -0
  74. package/dist/policy/permission-cycles.js.map +1 -0
  75. package/dist/policy/policy-model.d.ts +24 -0
  76. package/dist/policy/policy-model.d.ts.map +1 -1
  77. package/dist/policy/policy-sql.d.ts +39 -5
  78. package/dist/policy/policy-sql.d.ts.map +1 -1
  79. package/dist/policy/policy-sql.js +189 -15
  80. package/dist/policy/policy-sql.js.map +1 -1
  81. package/dist/policy/resolve-filter.d.ts +25 -0
  82. package/dist/policy/resolve-filter.d.ts.map +1 -0
  83. package/dist/policy/resolve-filter.js +156 -0
  84. package/dist/policy/resolve-filter.js.map +1 -0
  85. package/dist/policy/tarjan-scc.d.ts +3 -0
  86. package/dist/policy/tarjan-scc.d.ts.map +1 -0
  87. package/dist/policy/tarjan-scc.js +58 -0
  88. package/dist/policy/tarjan-scc.js.map +1 -0
  89. package/dist/postgres-access.tsbuildinfo +1 -1
  90. package/dist/postgres-authorization.d.ts +17 -17
  91. package/dist/postgres-authorization.d.ts.map +1 -1
  92. package/dist/postgres-authorization.js +67 -29
  93. package/dist/postgres-authorization.js.map +1 -1
  94. package/dist/postgres-options.d.ts +25 -0
  95. package/dist/postgres-options.d.ts.map +1 -0
  96. package/dist/postgres-options.js +36 -0
  97. package/dist/postgres-options.js.map +1 -0
  98. package/dist/postgres-response.d.ts +5 -0
  99. package/dist/postgres-response.d.ts.map +1 -1
  100. package/dist/postgres-response.js +42 -0
  101. package/dist/postgres-response.js.map +1 -1
  102. package/dist/postgres-tuples.d.ts.map +1 -1
  103. package/dist/postgres-tuples.js +64 -7
  104. package/dist/postgres-tuples.js.map +1 -1
  105. package/dist/postgres-types.d.ts +11 -0
  106. package/dist/postgres-types.d.ts.map +1 -1
  107. package/dist/protected-authorization-scope.d.ts +6 -8
  108. package/dist/protected-authorization-scope.d.ts.map +1 -1
  109. package/dist/protected-authorization-scope.js +13 -8
  110. package/dist/protected-authorization-scope.js.map +1 -1
  111. package/dist/relationship-schema.d.ts +9 -0
  112. package/dist/relationship-schema.d.ts.map +1 -1
  113. package/dist/relationship-schema.js +24 -2
  114. package/dist/relationship-schema.js.map +1 -1
  115. package/dist/testing.d.ts +20 -0
  116. package/dist/testing.d.ts.map +1 -0
  117. package/dist/testing.js +88 -0
  118. package/dist/testing.js.map +1 -0
  119. package/dist/transactional-access-changes.d.ts +3 -3
  120. package/dist/transactional-access-changes.d.ts.map +1 -1
  121. package/dist/transactional-access-changes.js +5 -3
  122. package/dist/transactional-access-changes.js.map +1 -1
  123. package/dist/with-protected-drizzle-transaction.d.ts +18 -0
  124. package/dist/with-protected-drizzle-transaction.d.ts.map +1 -0
  125. package/dist/with-protected-drizzle-transaction.js +52 -0
  126. package/dist/with-protected-drizzle-transaction.js.map +1 -0
  127. package/dist/with-protected-pg-transaction.d.ts +29 -0
  128. package/dist/with-protected-pg-transaction.d.ts.map +1 -0
  129. package/dist/with-protected-pg-transaction.js +110 -0
  130. package/dist/with-protected-pg-transaction.js.map +1 -0
  131. package/dist/with-protected-postgres-transaction.d.ts +6 -21
  132. package/dist/with-protected-postgres-transaction.d.ts.map +1 -1
  133. package/dist/with-protected-postgres-transaction.js +4 -45
  134. package/dist/with-protected-postgres-transaction.js.map +1 -1
  135. package/package.json +26 -4
@@ -0,0 +1,129 @@
1
+ import { analyzePermissionCycles, } from "./permission-cycles.js";
2
+ import { compileRecursiveForwardCheck } from "./compile-recursive-policy.js";
3
+ import { findColumnRelation } from "./column-relations.js";
4
+ import { compiledRelationCheck, isPolymorphicRelation, notExpired, permissionIdentity, resolveArrowTargets, TUPLES, } from "./policy-sql.js";
5
+ export function countRecursiveClauses(sql) {
6
+ let count = 0;
7
+ let position = sql.indexOf("WITH RECURSIVE");
8
+ while (position !== -1) {
9
+ count += 1;
10
+ position = sql.indexOf("WITH RECURSIVE", position + 14);
11
+ }
12
+ return count;
13
+ }
14
+ export function createForwardContext(model, builder, namespace, subject) {
15
+ return {
16
+ model,
17
+ cycles: analyzePermissionCycles(model),
18
+ builder,
19
+ namespace: builder.value(namespace),
20
+ subject,
21
+ active: new Set(),
22
+ };
23
+ }
24
+ export function compileForwardPermission(context, resource, permissionName) {
25
+ const definition = context.model.permissions.find((candidate) => candidate.wireName === permissionName &&
26
+ candidate.entity === resource.entity);
27
+ if (!definition)
28
+ throw new Error(`Postgres policy cannot find permission ${permissionName}.`);
29
+ const scc = context.cycles.sccFor(resource.entity, permissionName);
30
+ if (scc !== undefined) {
31
+ return compileRecursiveForwardCheck({
32
+ model: context.model,
33
+ builder: context.builder,
34
+ namespace: context.namespace,
35
+ resource,
36
+ entryEntity: resource.entity,
37
+ entryPermission: permissionName,
38
+ scc,
39
+ compileExpression: (nodeResource, expression) => compileForwardExpression(context, nodeResource, expression),
40
+ });
41
+ }
42
+ const identity = permissionIdentity(resource.entity, permissionName);
43
+ if (context.active.has(identity))
44
+ throw new Error("Postgres SQL compilation does not support a cycle through permissions.");
45
+ context.active.add(identity);
46
+ try {
47
+ return compileForwardExpression(context, resource, definition.expression);
48
+ }
49
+ finally {
50
+ context.active.delete(identity);
51
+ }
52
+ }
53
+ function compileForwardExpression(context, resource, expression) {
54
+ if (expression.kind === "relation") {
55
+ return compiledRelationCheck(context.model, context.builder, context.namespace, context.subject.type, context.subject.id, resource.entity, resource.type, resource.id, expression.relation);
56
+ }
57
+ if (expression.kind === "through")
58
+ return compileThrough(context, resource, expression);
59
+ if (expression.kind === "through-all")
60
+ return compileThroughAll(context, resource, expression);
61
+ if (expression.kind === "exclude")
62
+ return `((${compileForwardExpression(context, resource, expression.include)}) AND NOT (${compileForwardExpression(context, resource, expression.exclude)}))`;
63
+ const joiner = expression.kind === "any-of" ? " OR " : " AND ";
64
+ return `(${expression.expressions.map((child) => `(${compileForwardExpression(context, resource, child)})`).join(joiner)})`;
65
+ }
66
+ function compileThrough(context, resource, expression) {
67
+ const { builder, namespace } = context;
68
+ const targets = resolveArrowTargets(context.model, resource.entity, expression);
69
+ const columnRel = findColumnRelation(context.model, resource.entity, expression.relation);
70
+ if (columnRel !== undefined && targets[0] !== undefined) {
71
+ const throughAlias = builder.throughAlias();
72
+ const entitySql = builder.value(columnRel.entity);
73
+ const targetKindSql = builder.value(columnRel.targetEntity);
74
+ const child = compileForwardPermission(context, {
75
+ type: targetKindSql,
76
+ id: `${throughAlias}.${columnRel.targetIdColumn}`,
77
+ entity: targets[0].entity,
78
+ }, targets[0].permission);
79
+ return `EXISTS (SELECT 1 FROM ${columnRel.table} ${throughAlias} WHERE (${resource.type})::text = ${entitySql}::text AND ${throughAlias}.${columnRel.idColumn} = ${resource.id} AND ${throughAlias}.${columnRel.targetIdColumn} IS NOT NULL AND (${child}) OFFSET 0)`;
80
+ }
81
+ const polymorphic = isPolymorphicRelation(context.model, resource.entity, expression.relation);
82
+ const relationSql = builder.value(expression.relation);
83
+ const throughAlias = builder.throughAlias();
84
+ const branchSql = compileArrowTargetBranches(context, throughAlias, targets, polymorphic);
85
+ // OFFSET 0 keeps each arrow a correlated subplan. Pulling arrows up
86
+ // into semijoins can repeatedly execute the nested membership query.
87
+ return `EXISTS (SELECT 1 FROM ${TUPLES} ${throughAlias} WHERE ${throughAlias}.namespace = ${namespace} AND ${throughAlias}.resource_kind = ${resource.type} AND ${throughAlias}.resource_id = ${resource.id} AND ${throughAlias}.relation = ${relationSql} AND ${throughAlias}.subject_is_wildcard = false AND ${throughAlias}.subject_relation = '' AND ${notExpired(throughAlias)} AND (${branchSql}) OFFSET 0)`;
88
+ }
89
+ function compileThroughAll(context, resource, expression) {
90
+ const { builder, namespace } = context;
91
+ const targets = resolveArrowTargets(context.model, resource.entity, expression);
92
+ const columnRel = findColumnRelation(context.model, resource.entity, expression.relation);
93
+ if (columnRel !== undefined && targets[0] !== undefined) {
94
+ const existsAlias = builder.throughAlias();
95
+ const checkAlias = builder.throughAlias();
96
+ const entitySql = builder.value(columnRel.entity);
97
+ const targetKindSql = builder.value(columnRel.targetEntity);
98
+ const child = compileForwardPermission(context, {
99
+ type: targetKindSql,
100
+ id: `${checkAlias}.${columnRel.targetIdColumn}`,
101
+ entity: targets[0].entity,
102
+ }, targets[0].permission);
103
+ const match = (alias) => `(${resource.type})::text = ${entitySql}::text AND ${alias}.${columnRel.idColumn} = ${resource.id} AND ${alias}.${columnRel.targetIdColumn} IS NOT NULL`;
104
+ return `(EXISTS (SELECT 1 FROM ${columnRel.table} ${existsAlias} WHERE ${match(existsAlias)}) AND NOT EXISTS (SELECT 1 FROM ${columnRel.table} ${checkAlias} WHERE ${match(checkAlias)} AND NOT (${child}) OFFSET 0))`;
105
+ }
106
+ const polymorphic = isPolymorphicRelation(context.model, resource.entity, expression.relation);
107
+ const relationSql = builder.value(expression.relation);
108
+ const existsAlias = builder.throughAlias();
109
+ const checkAlias = builder.throughAlias();
110
+ const branchSql = compileArrowTargetBranches(context, checkAlias, targets, polymorphic);
111
+ const parentMatch = (alias) => `${alias}.namespace = ${namespace} AND ${alias}.resource_kind = ${resource.type} AND ${alias}.resource_id = ${resource.id} AND ${alias}.relation = ${relationSql} AND ${alias}.subject_is_wildcard = false AND ${alias}.subject_relation = '' AND ${notExpired(alias)}`;
112
+ return `(EXISTS (SELECT 1 FROM ${TUPLES} ${existsAlias} WHERE ${parentMatch(existsAlias)}) AND NOT EXISTS (SELECT 1 FROM ${TUPLES} ${checkAlias} WHERE ${parentMatch(checkAlias)} AND NOT (${branchSql}) OFFSET 0))`;
113
+ }
114
+ function compileArrowTargetBranches(context, tupleAlias, targets, polymorphic) {
115
+ const branches = targets.map((target) => {
116
+ const related = {
117
+ type: `${tupleAlias}.subject_kind`,
118
+ id: `${tupleAlias}.subject_id`,
119
+ entity: target.entity,
120
+ };
121
+ const child = compileForwardPermission(context, related, target.permission);
122
+ if (!polymorphic && targets.length === 1)
123
+ return child;
124
+ const targetKindSql = context.builder.value(target.entity);
125
+ return `(${tupleAlias}.subject_kind = ${targetKindSql} AND (${child}))`;
126
+ });
127
+ return branches.join(" OR ");
128
+ }
129
+ //# sourceMappingURL=compile-forward-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile-forward-policy.js","sourceRoot":"","sources":["../../src/policy/compile-forward-policy.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uBAAuB,GAExB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,UAAU,EACV,kBAAkB,EAElB,mBAAmB,EACnB,MAAM,GACP,MAAM,iBAAiB,CAAC;AAiBzB,MAAM,UAAU,qBAAqB,CAAC,GAAW;IAC/C,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAC7C,OAAO,QAAQ,KAAK,CAAC,CAAC,EAAE,CAAC;QACvB,KAAK,IAAI,CAAC,CAAC;QACX,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,gBAAgB,EAAE,QAAQ,GAAG,EAAE,CAAC,CAAC;IAC1D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,oBAAoB,CAClC,KAAmC,EACnC,OAAqB,EACrB,SAAiB,EACjB,OAAqB;IAErB,OAAO;QACL,KAAK;QACL,MAAM,EAAE,uBAAuB,CAAC,KAAK,CAAC;QACtC,OAAO;QACP,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;QACnC,OAAO;QACP,MAAM,EAAE,IAAI,GAAG,EAAE;KAClB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,OAAuB,EACvB,QAAsB,EACtB,cAAsB;IAEtB,MAAM,UAAU,GAAG,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAC/C,CAAC,SAAS,EAAE,EAAE,CACZ,SAAS,CAAC,QAAQ,KAAK,cAAc;QACrC,SAAS,CA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B,CACjC,OAAuB,EACvB,UAAkB,EAClB,OAAuC,EACvC,WAAoB;IAEpB,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;QACtC,MAAM,OAAO,GAAiB;YAC5B,IAAI,EAAE,GAAG,UAAU,eAAe;YAClC,EAAE,EAAE,GAAG,UAAU,aAAa;YAC9B,MAAM,EAAE,MAAM,CAAC,MAAM;SACtB,CAAC;QACF,MAAM,KAAK,GAAG,wBAAwB,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;QAC5E,IAAI,CAAC,WAAW,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;QACvD,MAAM,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC3D,OAAO,IAAI,UAAU,mBAAmB,aAAa,SAAS,KAAK,IAAI,CAAC;IAC1E,CAAC,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC/B,CAAC"}
@@ -9,6 +9,7 @@ type LinearBatchBranch = {
9
9
  /** Evaluate a deep linear policy once for each actor in this batch branch. */
10
10
  export declare function compileLinearBatchBranch(model: AuthorizationModelDefinition, builder: QueryBuilder, { namespace, resourceType, permission, index }: LinearBatchBranch): {
11
11
  readonly hits: string;
12
+ readonly join: string;
12
13
  readonly decision: string;
13
14
  };
14
15
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"compile-linear-batch.d.ts","sourceRoot":"","sources":["../../src/policy/compile-linear-batch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAGpD,KAAK,iBAAiB,GAAG;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,8EAA8E;AAC9E,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,4BAA4B,EACnC,OAAO,EAAE,YAAY,EACrB,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE,iBAAiB,GAChE;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CA8BtD"}
1
+ {"version":3,"file":"compile-linear-batch.d.ts","sourceRoot":"","sources":["../../src/policy/compile-linear-batch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAGpD,KAAK,iBAAiB,GAAG;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,8EAA8E;AAC9E,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,4BAA4B,EACnC,OAAO,EAAE,YAAY,EACrB,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE,iBAAiB,GAChE;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CA2B7E"}
@@ -14,7 +14,7 @@ export function compileLinearBatchBranch(model, builder, { namespace, resourceTy
14
14
  });
15
15
  return {
16
16
  hits: `${hits} AS MATERIALIZED (
17
- SELECT actor.subject_kind, actor.subject_id, permitted.resource_id
17
+ SELECT DISTINCT actor.subject_kind, actor.subject_id, permitted.resource_id
18
18
  FROM (
19
19
  SELECT subject_kind, subject_id, array_agg(DISTINCT resource_id) AS resource_ids
20
20
  FROM input i WHERE ${branch}
@@ -24,11 +24,8 @@ export function compileLinearBatchBranch(model, builder, { namespace, resourceTy
24
24
  WHERE permitted.resource_kind = ${resourceKind}
25
25
  AND permitted.resource_id = ANY(actor.resource_ids)
26
26
  )`,
27
- decision: `WHEN ${branch} THEN EXISTS (
28
- SELECT 1 FROM ${hits}
29
- WHERE subject_kind = i.subject_kind AND subject_id = i.subject_id
30
- AND resource_id = i.resource_id
31
- )`,
27
+ join: `LEFT JOIN ${hits} ON ${branch} AND ${hits}.subject_kind = i.subject_kind AND ${hits}.subject_id = i.subject_id AND ${hits}.resource_id = i.resource_id`,
28
+ decision: `WHEN ${branch} THEN (${hits}.resource_id IS NOT NULL)`,
32
29
  };
33
30
  }
34
31
  //# sourceMappingURL=compile-linear-batch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compile-linear-batch.js","sourceRoot":"","sources":["../../src/policy/compile-linear-batch.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AASzE,8EAA8E;AAC9E,MAAM,UAAU,wBAAwB,CACtC,KAAmC,EACnC,OAAqB,EACrB,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,KAAK,EAAqB;IAEjE,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACjD,MAAM,cAAc,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,qBAAqB,YAAY,uBAAuB,cAAc,EAAE,CAAC;IACxF,MAAM,IAAI,GAAG,eAAe,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;IAC5C,MAAM,SAAS,GAAG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J,QAAQ,EAAE,QAAQ,MAAM,UAAU,IAAI,2BAA2B;KAClE,CAAC;AACJ,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"compile-linear-check.d.ts","sourceRoot":"","sources":["../../src/policy/compile-linear-check.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAC5B,yBAAyB,EAC1B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAQ/E,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,4BAA4B,EACnC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,yBAAyB,GAC/B,0BAA0B,GAAG,SAAS,CAexC;AAkCD,wBAAgB,cAAc,CAC5B,KAAK,EAAE,4BAA4B,EACnC,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,GACjB,SAAS,MAAM,EAAE,GAAG,SAAS,CAkB/B"}
1
+ {"version":3,"file":"compile-linear-check.d.ts","sourceRoot":"","sources":["../../src/policy/compile-linear-check.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,4BAA4B,EAE5B,yBAAyB,EAC1B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAc/E,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,4BAA4B,EACnC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,yBAAyB,GAC/B,0BAA0B,GAAG,SAAS,CAexC;AAoCD,wBAAgB,cAAc,CAC5B,KAAK,EAAE,4BAA4B,EACnC,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,GACjB,SAAS,MAAM,EAAE,GAAG,SAAS,CAqB/B"}
@@ -1,4 +1,5 @@
1
- import { relatedEntity, TUPLES } from "./policy-sql.js";
1
+ import { findColumnRelation } from "./column-relations.js";
2
+ import { notExpired, permissionIdentity, resolveArrowTargets, TUPLES, } from "./policy-sql.js";
2
3
  const MIN_FUSED_ARROWS = 4;
3
4
  const MAX_FUSED_ARROWS = 32;
4
5
  const MAX_TRAVERSED_STATES = 64;
@@ -34,6 +35,7 @@ const SQL = `WITH RECURSIVE levels(ordinal, resource_kind, resource_id, relation
34
35
  ON tuple.namespace = $1 AND tuple.resource_kind = levels.resource_kind
35
36
  AND tuple.resource_id = levels.resource_id AND tuple.relation = levels.relation
36
37
  WHERE tuple.subject_is_wildcard = false
38
+ AND ${notExpired("tuple")}
37
39
  AND (levels.ordinal < ${terminal}) = (tuple.subject_relation = '')
38
40
  ), bounded AS MATERIALIZED (
39
41
  SELECT * FROM levels LIMIT ${String(FALLBACK_THRESHOLD)}
@@ -45,6 +47,7 @@ SELECT CASE WHEN EXISTS (
45
47
  AND tuple.resource_id = bounded.resource_id AND tuple.relation = bounded.relation
46
48
  WHERE bounded.ordinal = ${terminal} AND tuple.subject_kind = $2
47
49
  AND tuple.subject_relation = ''
50
+ AND ${notExpired("tuple")}
48
51
  AND ((tuple.subject_id = $3 AND tuple.subject_is_wildcard = false)
49
52
  OR (tuple.subject_id = '' AND tuple.subject_is_wildcard = true))
50
53
  ) THEN true
@@ -52,20 +55,61 @@ WHEN (SELECT count(*) FROM bounded) >= ${String(FALLBACK_THRESHOLD)} THEN NULL
52
55
  ELSE false END AS allowed`;
53
56
  export function readLinearPath(model, resourceEntity, permission) {
54
57
  const arrows = [];
58
+ const visited = new Set();
55
59
  let entity = resourceEntity;
56
60
  let name = permission;
57
61
  while (arrows.length <= MAX_FUSED_ARROWS) {
58
- const expression = model.permissions.find((candidate) => candidate.entity === entity && candidate.wireName === name)?.expression;
59
- if (expression?.kind === "relation")
62
+ const identity = permissionIdentity(entity, name);
63
+ if (visited.has(identity))
64
+ return undefined;
65
+ visited.add(identity);
66
+ const step = readLinearStep(model, entity, name);
67
+ if (step === undefined)
68
+ return undefined;
69
+ if (step.kind === "leaf") {
60
70
  return arrows.length >= MIN_FUSED_ARROWS
61
- ? [...arrows, expression.relation]
71
+ ? [...arrows, step.relation]
62
72
  : undefined;
63
- if (expression?.kind !== "through")
64
- return undefined;
65
- arrows.push(expression.relation);
66
- entity = relatedEntity(model, entity, expression.relation);
67
- name = expression.permission;
73
+ }
74
+ arrows.push(step.relation);
75
+ entity = step.nextEntity;
76
+ name = step.nextPermission;
68
77
  }
69
78
  return undefined;
70
79
  }
80
+ function isColumnBacked(model, entity, relation) {
81
+ return findColumnRelation(model, entity, relation) !== undefined;
82
+ }
83
+ function readLinearStep(model, entity, name) {
84
+ const expression = model.permissions.find((candidate) => candidate.entity === entity && candidate.wireName === name)?.expression;
85
+ if (expression?.kind === "relation") {
86
+ return isColumnBacked(model, entity, expression.relation)
87
+ ? undefined
88
+ : { kind: "leaf", relation: expression.relation };
89
+ }
90
+ if (expression?.kind !== "through")
91
+ return undefined;
92
+ return readLinearArrowStep(model, entity, expression);
93
+ }
94
+ function readLinearArrowStep(model, entity, expression) {
95
+ if (isColumnBacked(model, entity, expression.relation) ||
96
+ !hasSingleEntityTarget(model, entity, expression.relation)) {
97
+ return undefined;
98
+ }
99
+ const targets = resolveArrowTargets(model, entity, expression);
100
+ const [only] = targets;
101
+ if (targets.length !== 1 || only === undefined)
102
+ return undefined;
103
+ return {
104
+ kind: "arrow",
105
+ relation: expression.relation,
106
+ nextEntity: only.entity,
107
+ nextPermission: only.permission,
108
+ };
109
+ }
110
+ function hasSingleEntityTarget(model, entity, relation) {
111
+ const definition = model.relations.find((candidate) => candidate.entity === entity && candidate.wireName === relation);
112
+ const entityTargets = definition?.targets.filter((target) => target.kind === "entity") ?? [];
113
+ return entityTargets.length === 1;
114
+ }
71
115
  //# sourceMappingURL=compile-linear-check.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compile-linear-check.js","sourceRoot":"","sources":["../../src/policy/compile-linear-check.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAExD,MAAM,gBAAgB,GAAG,CAAC,CAAC;A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GC;IAED,IACE,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC;QAClD,CAAC,qBAAqB,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,QAAQ,CAAC,EAC1D,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;IAC/D,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC;IACvB,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IACjE,OAAO;QACL,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,UAAU,CAAC,QAAQ;QAC7B,UAAU,EAAE,IAAI,CAAC,MAAM;QACvB,cAAc,EAAE,IAAI,CAAC,UAAU;KAChC,CAAC;AACJ,CAAC;AAED,SAAS,qBAAqB,CAC5B,KAAmC,EACnC,MAAc,EACd,QAAgB;IAEhB,MAAM,UAAU,GAAG,KAAK,CAAC,SAAS,CAAC,IAAI,CACrC,CAAC,SAAS,EAAE,EAAE,CACZ,SAAS,CAAC,MAAM,KAAK,MAAM,IAAI,SAAS,CAAC,QAAQ,KAAK,QAAQ,CACjE,CAAC;IACF,MAAM,aAAa,GACjB,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,EAAE,CAAC;IACzE,OAAO,aAAa,CAAC,MAAM,KAAK,CAAC,CAAC;AACpC,CAAC"}
@@ -1,7 +1,7 @@
1
- import { type AuthorizationModelDefinition, type NormalizedPermissionCheck, type NormalizedResourceLookup } from "./policy-model.js";
1
+ import type { AuthorizationModelDefinition, NormalizedPermissionCheck, NormalizedResourceLookup } from "./policy-model.js";
2
2
  import type { PostgresQuery } from "../postgres-types.js";
3
3
  export type CompiledAuthorizationQuery = PostgresQuery & {
4
- readonly kind: "check" | "check-many" | "lookup" | "candidate-predicate";
4
+ readonly kind: "check" | "check-many" | "lookup" | "subject-lookup" | "candidate-predicate";
5
5
  };
6
6
  export type PostgresAuthorizationCandidateBinding = {
7
7
  readonly tableAlias: "dad_authorization_candidate";
@@ -14,7 +14,9 @@ export declare function compilePostgresCheck(model: AuthorizationModelDefinition
14
14
  readonly canPrepare: boolean;
15
15
  };
16
16
  /** One ordinal input relation and one SQL statement preserve input ordering and duplicates. */
17
- export declare function compilePostgresCheckMany(model: AuthorizationModelDefinition, namespace: string, requests: readonly NormalizedPermissionCheck[]): CompiledAuthorizationQuery;
17
+ export declare function compilePostgresCheckMany(model: AuthorizationModelDefinition, namespace: string, requests: readonly NormalizedPermissionCheck[]): CompiledAuthorizationQuery & {
18
+ readonly canPrepare: boolean;
19
+ };
18
20
  /**
19
21
  * Computes allowed IDs actor-first from the reverse subject index. It never
20
22
  * enumerates every resource of a kind in application memory or SQL.
@@ -24,5 +26,8 @@ export declare function compilePostgresLookup(model: AuthorizationModelDefinitio
24
26
  * Compiles one descriptor's permission against the fixed integration candidate
25
27
  * binding. The caller supplies neither SQL text nor an identifier.
26
28
  */
27
- export declare function compilePostgresCandidatePredicate(model: AuthorizationModelDefinition, namespace: string, request: NormalizedResourceLookup): CompiledAuthorizationQuery;
29
+ export declare function compilePostgresCandidatePredicate(model: AuthorizationModelDefinition, namespace: string, request: NormalizedResourceLookup, options?: {
30
+ readonly idColumn?: string;
31
+ readonly paramOffset?: number;
32
+ }): CompiledAuthorizationQuery;
28
33
  //# sourceMappingURL=compile-postgres-policy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"compile-postgres-policy.d.ts","sourceRoot":"","sources":["../../src/policy/compile-postgres-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,4BAA4B,EAEjC,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KA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
2
  import { compileLinearBatchBranch } from "./compile-linear-batch.js";
4
3
  import { compileSharedPointCheck } from "./compile-shared-point-check.js";
5
4
  import { compileReversePermission } from "./compile-reverse-policy.js";
6
- import { QueryBuilder, relatedEntity, subjectReachability, TUPLES, } from "./policy-sql.js";
5
+ import { analyzePermissionCycles, } from "./permission-cycles.js";
6
+ import { compileForwardPermission, countRecursiveClauses, createForwardContext, } from "./compile-forward-policy.js";
7
+ import { permissionIdentity, QueryBuilder, splitIdentity, subjectReachability, } from "./policy-sql.js";
7
8
  /** Fixed outer binding used only by named integration adapters. */
8
9
  export const POSTGRES_AUTHORIZATION_CANDIDATE_BINDING = Object.freeze({
9
10
  tableAlias: "dad_authorization_candidate",
@@ -12,56 +13,107 @@ export const POSTGRES_AUTHORIZATION_CANDIDATE_BINDING = Object.freeze({
12
13
  /** Compiles one permission decision into a parameterized Postgres Boolean query. */
13
14
  export function compilePostgresCheck(model, namespace, request) {
14
15
  const builder = new QueryBuilder();
15
- const namespaceSql = builder.value(namespace);
16
- const expression = compilePermission(model, builder, namespaceSql, {
16
+ const context = createForwardContext(model, builder, namespace, {
17
17
  type: builder.value(request.subject.type),
18
18
  id: builder.value(request.subject.id),
19
19
  entity: request.subject.type,
20
- }, {
20
+ });
21
+ const resource = {
21
22
  type: builder.value(request.resource.type),
22
23
  id: builder.value(request.resource.id),
23
24
  entity: request.resource.type,
24
- }, request.permission, new Set());
25
- if (Buffer.byteLength(expression) > 64 * 1024)
25
+ };
26
+ const expression = compileForwardPermission(context, resource, request.permission);
27
+ if (Buffer.byteLength(expression) > 16 * 1024 ||
28
+ countRecursiveClauses(expression) > 6)
26
29
  return compileSharedPointCheck(model, namespace, request);
27
30
  return Object.freeze({
28
31
  kind: "check",
29
32
  text: `SELECT (${expression}) AS allowed`,
30
33
  values: builder.values,
31
- // Five bindings describe the namespace and endpoints. Each remaining
32
- // binding adds one relation or arrow to the ordinary permission plan.
33
- canPrepare: builder.values.length <= 9 && builder.throughCount <= 2,
34
+ // Prepare bounded ordinary and recursive single-check plans so PostgreSQL
35
+ // reuses compiled execution plans across repeated checks.
36
+ canPrepare: builder.hasRecursive
37
+ ? builder.values.length <= 24 && builder.throughCount <= 2
38
+ : builder.values.length <= 9 && builder.throughCount <= 2,
34
39
  });
35
40
  }
36
41
  /** One ordinal input relation and one SQL statement preserve input ordering and duplicates. */
37
42
  export function compilePostgresCheckMany(model, namespace, requests) {
38
43
  const builder = new QueryBuilder();
39
44
  const namespaceSql = builder.value(namespace);
40
- const tuples = requests.map((request, ordinal) => `(${builder.value(ordinal)}, ${builder.value(request.subject.type)}, ${builder.value(request.subject.id)}, ${builder.value(request.resource.type)}, ${builder.value(request.resource.id)}, ${builder.value(request.permission)})`);
45
+ const cycles = analyzePermissionCycles(model);
46
+ const ordinals = requests.map((_, ordinal) => ordinal);
47
+ const subjectKinds = requests.map((request) => request.subject.type);
48
+ const subjectIds = requests.map((request) => request.subject.id);
49
+ const resourceKinds = requests.map((request) => request.resource.type);
50
+ const resourceIds = requests.map((request) => request.resource.id);
51
+ const permissions = requests.map((request) => request.permission);
52
+ const inputRows = `SELECT * FROM unnest(${builder.value(ordinals)}::integer[], ${builder.value(subjectKinds)}::text[], ${builder.value(subjectIds)}::text[], ${builder.value(resourceKinds)}::text[], ${builder.value(resourceIds)}::text[], ${builder.value(permissions)}::text[])`;
41
53
  const shared = [];
42
- const branches = [
43
- ...new Set(requests.map((request) => `${request.resource.type}\u0000${request.permission}`)),
44
- ].map((identity) => {
45
- const [resourceType, permission] = splitIdentity(identity);
46
- if (readLinearPath(model, resourceType, permission) !== undefined) {
47
- const branch = compileLinearBatchBranch(model, builder, {
48
- namespace: namespaceSql,
49
- resourceType,
50
- permission,
51
- index: shared.length,
52
- });
53
- shared.push(branch.hits);
54
- return branch.decision;
55
- }
56
- const expression = compilePermission(model, builder, namespaceSql, { type: "i.subject_kind", id: "i.subject_id", entity: resourceType }, { type: "i.resource_kind", id: "i.resource_id", entity: resourceType }, permission, new Set());
57
- return `WHEN i.resource_kind = ${builder.value(resourceType)} AND i.permission = ${builder.value(permission)} THEN (${expression})`;
58
- });
54
+ const joins = [];
55
+ const identities = [
56
+ ...new Set(requests.map((request) => permissionIdentity(request.resource.type, request.permission))),
57
+ ];
58
+ const branches = identities.map((identity) => compileBatchBranch(model, cycles, builder, namespaceSql, identity, shared, joins));
59
+ const joinSql = joins.length === 0 ? "" : ` ${joins.join(" ")}`;
60
+ const text = `WITH input(ordinal, subject_kind, subject_id, resource_kind, resource_id, permission) AS (${inputRows})${shared.map((query) => `, ${query}`).join("")} SELECT i.ordinal AS ordinal, CASE ${branches.join(" ")} ELSE false END AS allowed FROM input i${joinSql} ORDER BY i.ordinal`;
59
61
  return Object.freeze({
60
62
  kind: "check-many",
61
- text: `WITH input(ordinal, subject_kind, subject_id, resource_kind, resource_id, permission) AS (VALUES ${tuples.join(", ")})${shared.map((query) => `, ${query}`).join("")} SELECT i.ordinal::integer AS ordinal, CASE ${branches.join(" ")} ELSE false END AS allowed FROM input i ORDER BY i.ordinal::integer`,
63
+ text,
62
64
  values: builder.values,
65
+ canPrepare: identities.length <= 4 && Buffer.byteLength(text) <= 8 * 1024,
63
66
  });
64
67
  }
68
+ function shouldUseSharedBatchBranch(model, cycles, namespaceSql, resourceType, permission) {
69
+ if (readLinearPath(model, resourceType, permission) !== undefined) {
70
+ return true;
71
+ }
72
+ const probeBuilder = new QueryBuilder();
73
+ const probeContext = {
74
+ model,
75
+ cycles,
76
+ builder: probeBuilder,
77
+ namespace: namespaceSql,
78
+ subject: {
79
+ type: "i.subject_kind",
80
+ id: "i.subject_id",
81
+ entity: resourceType,
82
+ },
83
+ active: new Set(),
84
+ };
85
+ const probeSql = compileForwardPermission(probeContext, { type: "i.resource_kind", id: "i.resource_id", entity: resourceType }, permission);
86
+ return (Buffer.byteLength(probeSql) > 16 * 1024 ||
87
+ countRecursiveClauses(probeSql) > 6);
88
+ }
89
+ function compileBatchBranch(model, cycles, builder, namespaceSql, identity, shared, joins) {
90
+ const [resourceType, permission] = splitIdentity(identity);
91
+ if (shouldUseSharedBatchBranch(model, cycles, namespaceSql, resourceType, permission)) {
92
+ const branch = compileLinearBatchBranch(model, builder, {
93
+ namespace: namespaceSql,
94
+ resourceType,
95
+ permission,
96
+ index: shared.length,
97
+ });
98
+ shared.push(branch.hits);
99
+ joins.push(branch.join);
100
+ return branch.decision;
101
+ }
102
+ const context = {
103
+ model,
104
+ cycles,
105
+ builder,
106
+ namespace: namespaceSql,
107
+ subject: {
108
+ type: "i.subject_kind",
109
+ id: "i.subject_id",
110
+ entity: resourceType,
111
+ },
112
+ active: new Set(),
113
+ };
114
+ const expression = compileForwardPermission(context, { type: "i.resource_kind", id: "i.resource_id", entity: resourceType }, permission);
115
+ return `WHEN i.resource_kind = ${builder.value(resourceType)} AND i.permission = ${builder.value(permission)} THEN (${expression})`;
116
+ }
65
117
  /**
66
118
  * Computes allowed IDs actor-first from the reverse subject index. It never
67
119
  * enumerates every resource of a kind in application memory or SQL.
@@ -79,7 +131,7 @@ export function compilePostgresLookup(model, namespace, request) {
79
131
  // Flattening the LATERAL probe can scan the namespace once per iteration.
80
132
  return Object.freeze({
81
133
  kind: "lookup",
82
- text: `WITH RECURSIVE ${subjectReachability(namespaceSql, subject.type, subject.id)} SELECT DISTINCT allowed_resource.resource_id FROM (${allowedResourceIds}) allowed_resource ORDER BY allowed_resource.resource_id`,
134
+ text: `WITH RECURSIVE ${subjectReachability(namespaceSql, subject.type, subject.id, model.columnRelations, builder)} SELECT DISTINCT allowed_resource.resource_id FROM (${allowedResourceIds}) allowed_resource ORDER BY allowed_resource.resource_id`,
83
135
  values: builder.values,
84
136
  });
85
137
  }
@@ -87,103 +139,24 @@ export function compilePostgresLookup(model, namespace, request) {
87
139
  * Compiles one descriptor's permission against the fixed integration candidate
88
140
  * binding. The caller supplies neither SQL text nor an identifier.
89
141
  */
90
- export function compilePostgresCandidatePredicate(model, namespace, request) {
91
- const builder = new QueryBuilder();
92
- const namespaceSql = builder.value(namespace);
93
- const expression = compilePermission(model, builder, namespaceSql, {
142
+ export function compilePostgresCandidatePredicate(model, namespace, request, options) {
143
+ const builder = new QueryBuilder(options?.paramOffset ?? 1);
144
+ const context = createForwardContext(model, builder, namespace, {
94
145
  type: builder.value(request.subject.type),
95
146
  id: builder.value(request.subject.id),
96
147
  entity: request.subject.type,
97
- }, {
148
+ });
149
+ const idColumn = options?.idColumn ??
150
+ `${POSTGRES_AUTHORIZATION_CANDIDATE_BINDING.tableAlias}.${POSTGRES_AUTHORIZATION_CANDIDATE_BINDING.resourceIdColumn}`;
151
+ const expression = compileForwardPermission(context, {
98
152
  type: builder.value(request.resourceType),
99
- id: `${POSTGRES_AUTHORIZATION_CANDIDATE_BINDING.tableAlias}.${POSTGRES_AUTHORIZATION_CANDIDATE_BINDING.resourceIdColumn}`,
153
+ id: idColumn,
100
154
  entity: request.resourceType,
101
- }, request.permission, new Set());
155
+ }, request.permission);
102
156
  return Object.freeze({
103
157
  kind: "candidate-predicate",
104
158
  text: `(${expression})`,
105
159
  values: builder.values,
106
160
  });
107
161
  }
108
- function compilePermission(model, builder, namespace, subject, resource, permissionName, active) {
109
- const definition = model.permissions.find((candidate) => candidate.wireName === permissionName &&
110
- candidate.entity === resource.entity);
111
- if (!definition)
112
- throw new Error(`Postgres policy cannot find permission ${permissionName}.`);
113
- const identity = `${resource.entity}\u0000${permissionName}`;
114
- if (active.has(identity))
115
- throw new Error("Postgres SQL compilation does not yet support a cycle through permissions. Subject-set cycles are supported by recursive relation SQL; rewrite this permission-through cycle or add a dedicated recursive permission compiler.");
116
- active.add(identity);
117
- try {
118
- return compileExpression(model, builder, namespace, subject, resource, definition.expression, active);
119
- }
120
- finally {
121
- active.delete(identity);
122
- }
123
- }
124
- function compileExpression(model, builder, namespace, subject, resource, expression, active) {
125
- if (expression.kind === "relation")
126
- return compileRelationMembership(builder, namespace, subject, resource, expression.relation);
127
- if (expression.kind === "through") {
128
- const relationSql = builder.value(expression.relation);
129
- const throughAlias = builder.throughAlias();
130
- const related = {
131
- type: `${throughAlias}.subject_kind`,
132
- id: `${throughAlias}.subject_id`,
133
- entity: relatedEntity(model, resource.entity, expression.relation),
134
- };
135
- const child = compilePermissionForRelated(model, builder, namespace, subject, related, expression.permission, active);
136
- // OFFSET 0 keeps each arrow a correlated subplan. Pulling arrows up
137
- // into semijoins can repeatedly execute the nested membership query.
138
- return `EXISTS (SELECT 1 FROM ${TUPLES} ${throughAlias} WHERE ${throughAlias}.namespace = ${namespace} AND ${throughAlias}.resource_kind = ${resource.type} AND ${throughAlias}.resource_id = ${resource.id} AND ${throughAlias}.relation = ${relationSql} AND ${throughAlias}.subject_is_wildcard = false AND ${throughAlias}.subject_relation = '' AND (${child}) OFFSET 0)`;
139
- }
140
- if (expression.kind === "exclude")
141
- return `((${compileExpression(model, builder, namespace, subject, resource, expression.include, active)}) AND NOT (${compileExpression(model, builder, namespace, subject, resource, expression.exclude, active)}))`;
142
- const joiner = expression.kind === "any-of" ? " OR " : " AND ";
143
- return `(${expression.expressions.map((child) => `(${compileExpression(model, builder, namespace, subject, resource, child, active)})`).join(joiner)})`;
144
- }
145
- function compilePermissionForRelated(model, builder, namespace, subject, resource, permission, active) {
146
- const definition = model.permissions.find((candidate) => candidate.wireName === permission && candidate.entity === resource.entity);
147
- if (!definition)
148
- throw new Error("Postgres policy is missing a through permission.");
149
- return compilePermission(model, builder, namespace, subject, resource, permission, active);
150
- }
151
- /**
152
- * The recursive UNION deduplicates usersets, including cycles and diamonds.
153
- * Keep each hop correlated so stale statistics cannot select a repeated
154
- * namespace scan in place of a tuple key lookup.
155
- */
156
- function compileRelationMembership(builder, namespace, subject, resource, relation) {
157
- const relationSql = builder.value(relation);
158
- return `EXISTS (WITH RECURSIVE requested(resource_kind, resource_id, relation) AS (
159
- VALUES (${resource.type}, ${resource.id}, ${relationSql})
160
- UNION
161
- SELECT child.subject_kind, child.subject_id, child.subject_relation
162
- FROM requested requested_relation
163
- CROSS JOIN LATERAL (
164
- SELECT tuple.subject_kind, tuple.subject_id, tuple.subject_relation
165
- FROM ${TUPLES} tuple
166
- WHERE tuple.namespace = ${namespace}
167
- AND tuple.resource_kind = requested_relation.resource_kind
168
- AND tuple.resource_id = requested_relation.resource_id
169
- AND tuple.relation = requested_relation.relation
170
- AND tuple.subject_is_wildcard = false
171
- AND tuple.subject_relation <> ''
172
- OFFSET 0
173
- ) child
174
- )
175
- SELECT 1
176
- FROM ${TUPLES} tuple
177
- JOIN requested requested_relation
178
- ON requested_relation.resource_kind = tuple.resource_kind
179
- AND requested_relation.resource_id = tuple.resource_id
180
- AND requested_relation.relation = tuple.relation
181
- WHERE tuple.namespace = ${namespace}
182
- AND ((tuple.subject_is_wildcard = false AND tuple.subject_relation = '' AND tuple.subject_kind = ${subject.type} AND tuple.subject_id = ${subject.id}) OR (tuple.subject_is_wildcard = true AND tuple.subject_kind = ${subject.type}))
183
- LIMIT 1)`;
184
- }
185
- function splitIdentity(value) {
186
- const index = value.indexOf("\u0000");
187
- return [value.slice(0, index), value.slice(index + 1)];
188
- }
189
162
  //# sourceMappingURL=compile-postgres-policy.js.map