@dads-framework/postgres-access 0.0.0-stage → 0.2.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/BENCHMARK.md +275 -0
- package/LICENSE.md +21 -0
- package/README.md +275 -2
- package/dist/compile-access-policy.d.ts +9 -0
- package/dist/compile-access-policy.d.ts.map +1 -0
- package/dist/compile-access-policy.js +77 -0
- package/dist/compile-access-policy.js.map +1 -0
- package/dist/drizzle-executor.d.ts +5 -0
- package/dist/drizzle-executor.d.ts.map +1 -0
- package/dist/drizzle-executor.js +25 -0
- package/dist/drizzle-executor.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/lookup-primary-pool.d.ts +5 -0
- package/dist/lookup-primary-pool.d.ts.map +1 -0
- package/dist/lookup-primary-pool.js +24 -0
- package/dist/lookup-primary-pool.js.map +1 -0
- package/dist/lookup-revision-query.d.ts +7 -0
- package/dist/lookup-revision-query.d.ts.map +1 -0
- package/dist/lookup-revision-query.js +73 -0
- package/dist/lookup-revision-query.js.map +1 -0
- package/dist/lookup-revision-schema.d.ts +10 -0
- package/dist/lookup-revision-schema.d.ts.map +1 -0
- package/dist/lookup-revision-schema.js +75 -0
- package/dist/lookup-revision-schema.js.map +1 -0
- package/dist/lower-permissions.d.ts +8 -0
- package/dist/lower-permissions.d.ts.map +1 -0
- package/dist/lower-permissions.js +76 -0
- package/dist/lower-permissions.js.map +1 -0
- package/dist/policy/compile-linear-batch.d.ts +15 -0
- package/dist/policy/compile-linear-batch.d.ts.map +1 -0
- package/dist/policy/compile-linear-batch.js +34 -0
- package/dist/policy/compile-linear-batch.js.map +1 -0
- package/dist/policy/compile-linear-check.d.ts +5 -0
- package/dist/policy/compile-linear-check.d.ts.map +1 -0
- package/dist/policy/compile-linear-check.js +71 -0
- package/dist/policy/compile-linear-check.js.map +1 -0
- package/dist/policy/compile-postgres-policy.d.ts +28 -0
- package/dist/policy/compile-postgres-policy.d.ts.map +1 -0
- package/dist/policy/compile-postgres-policy.js +189 -0
- package/dist/policy/compile-postgres-policy.js.map +1 -0
- package/dist/policy/compile-reverse-policy.d.ts +5 -0
- package/dist/policy/compile-reverse-policy.d.ts.map +1 -0
- package/dist/policy/compile-reverse-policy.js +60 -0
- package/dist/policy/compile-reverse-policy.js.map +1 -0
- package/dist/policy/compile-shared-point-check.d.ts +18 -0
- package/dist/policy/compile-shared-point-check.d.ts.map +1 -0
- package/dist/policy/compile-shared-point-check.js +126 -0
- package/dist/policy/compile-shared-point-check.js.map +1 -0
- package/dist/policy/policy-model.d.ts +86 -0
- package/dist/policy/policy-model.d.ts.map +1 -0
- package/dist/policy/policy-model.js +2 -0
- package/dist/policy/policy-model.js.map +1 -0
- package/dist/policy/policy-sql.d.ts +20 -0
- package/dist/policy/policy-sql.d.ts.map +1 -0
- package/dist/policy/policy-sql.js +59 -0
- package/dist/policy/policy-sql.js.map +1 -0
- package/dist/postgres-access.tsbuildinfo +1 -0
- package/dist/postgres-authorization.d.ts +35 -0
- package/dist/postgres-authorization.d.ts.map +1 -0
- package/dist/postgres-authorization.js +170 -0
- package/dist/postgres-authorization.js.map +1 -0
- package/dist/postgres-response.d.ts +4 -0
- package/dist/postgres-response.d.ts.map +1 -0
- package/dist/postgres-response.js +13 -0
- package/dist/postgres-response.js.map +1 -0
- package/dist/postgres-serialization-conflict.d.ts +11 -0
- package/dist/postgres-serialization-conflict.d.ts.map +1 -0
- package/dist/postgres-serialization-conflict.js +29 -0
- package/dist/postgres-serialization-conflict.js.map +1 -0
- package/dist/postgres-tuples.d.ts +19 -0
- package/dist/postgres-tuples.d.ts.map +1 -0
- package/dist/postgres-tuples.js +135 -0
- package/dist/postgres-tuples.js.map +1 -0
- package/dist/postgres-types.d.ts +17 -0
- package/dist/postgres-types.d.ts.map +1 -0
- package/dist/postgres-types.js +10 -0
- package/dist/postgres-types.js.map +1 -0
- package/dist/prepared-check-executor.d.ts +12 -0
- package/dist/prepared-check-executor.d.ts.map +1 -0
- package/dist/prepared-check-executor.js +39 -0
- package/dist/prepared-check-executor.js.map +1 -0
- package/dist/protected-authorization-scope.d.ts +10 -0
- package/dist/protected-authorization-scope.d.ts.map +1 -0
- package/dist/protected-authorization-scope.js +41 -0
- package/dist/protected-authorization-scope.js.map +1 -0
- package/dist/relationship-schema.d.ts +11 -0
- package/dist/relationship-schema.d.ts.map +1 -0
- package/dist/relationship-schema.js +36 -0
- package/dist/relationship-schema.js.map +1 -0
- package/dist/revisioned-lookup.d.ts +13 -0
- package/dist/revisioned-lookup.d.ts.map +1 -0
- package/dist/revisioned-lookup.js +129 -0
- package/dist/revisioned-lookup.js.map +1 -0
- package/dist/transactional-access-changes.d.ts +19 -0
- package/dist/transactional-access-changes.d.ts.map +1 -0
- package/dist/transactional-access-changes.js +35 -0
- package/dist/transactional-access-changes.js.map +1 -0
- package/dist/with-protected-postgres-transaction.d.ts +22 -0
- package/dist/with-protected-postgres-transaction.d.ts.map +1 -0
- package/dist/with-protected-postgres-transaction.js +47 -0
- package/dist/with-protected-postgres-transaction.js.map +1 -0
- package/package.json +41 -4
package/BENCHMARK.md
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
# Experimental authorization benchmark
|
|
2
|
+
|
|
3
|
+
Measure the operation your application depends on. Point checks, fresh
|
|
4
|
+
resource discovery, revision-validated lookup reuse, and protected
|
|
5
|
+
transactions have different costs.
|
|
6
|
+
|
|
7
|
+
These are Linux development VM measurements with both engines accessed
|
|
8
|
+
locally. The SpiceDB comparison used the fully consistent in-memory
|
|
9
|
+
datastore. The figures apply to the listed fixtures and configurations.
|
|
10
|
+
They do not set a production latency target or compare persistent
|
|
11
|
+
SpiceDB deployments. The benchmarks do not include HTTP, application
|
|
12
|
+
writes, or serializable transaction overhead.
|
|
13
|
+
|
|
14
|
+
## Matched point checks against SpiceDB
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
CONTAINER_PER_FILE=1 npm run benchmark -w @dads-framework/postgres-access -- src/point-check-comparison.benchmark.test.ts
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The harness uses the same 5,000-leaf graph for each depth and engine. Both
|
|
21
|
+
use the public Node authorization adapters over local TCP, with the opt-in prepared-check path against PostgreSQL 16.16 and fully consistent gRPC
|
|
22
|
+
against the SpiceDB 1.57.0 in-memory testing datastore. It includes transport,
|
|
23
|
+
encoding, SQL compilation, and decoding in the timed calls. The Linux VM
|
|
24
|
+
has 32 vCPUs on an i9-13900KF and runs Node 24.20.0.
|
|
25
|
+
|
|
26
|
+
Each engine takes three rounds of 1,280 checks per depth and worker count,
|
|
27
|
+
after 30 warmups per worker. Engine order alternates and each worker checks
|
|
28
|
+
both granted and denied subjects. The measured mix is 75% granted, with
|
|
29
|
+
distinct leaf IDs and distinct denied subject IDs within each round. After
|
|
30
|
+
timing, an independent writer revokes and restores the membership while the
|
|
31
|
+
same reader must observe both changes.
|
|
32
|
+
|
|
33
|
+
The columns are the medians of the three round summaries. Latency is in
|
|
34
|
+
milliseconds, and throughput is completed checks per second at that worker
|
|
35
|
+
count.
|
|
36
|
+
|
|
37
|
+
| Arrows | Workers | Engine | p50 | p95 | p99 | Checks/s |
|
|
38
|
+
| -----: | ------: | :--------- | ----: | ----: | ----: | -------: |
|
|
39
|
+
| 2 | 1 | PostgreSQL | 0.275 | 0.702 | 1.192 | 3,054 |
|
|
40
|
+
| 2 | 1 | SpiceDB | 0.620 | 0.996 | 2.086 | 1,509 |
|
|
41
|
+
| 2 | 8 | PostgreSQL | 0.440 | 0.951 | 1.843 | 14,044 |
|
|
42
|
+
| 2 | 8 | SpiceDB | 1.369 | 2.269 | 3.342 | 5,678 |
|
|
43
|
+
| 8 | 1 | PostgreSQL | 0.184 | 0.472 | 0.873 | 4,118 |
|
|
44
|
+
| 8 | 1 | SpiceDB | 0.633 | 1.020 | 1.838 | 1,441 |
|
|
45
|
+
| 8 | 8 | PostgreSQL | 0.224 | 0.481 | 0.561 | 25,178 |
|
|
46
|
+
| 8 | 8 | SpiceDB | 0.814 | 1.654 | 2.116 | 8,446 |
|
|
47
|
+
| 16 | 1 | PostgreSQL | 0.187 | 0.362 | 0.419 | 4,476 |
|
|
48
|
+
| 16 | 1 | SpiceDB | 0.859 | 1.286 | 1.833 | 1,150 |
|
|
49
|
+
| 16 | 8 | PostgreSQL | 0.381 | 0.491 | 0.544 | 19,146 |
|
|
50
|
+
| 16 | 8 | SpiceDB | 1.268 | 1.986 | 2.885 | 5,925 |
|
|
51
|
+
|
|
52
|
+
At 16 arrows and eight workers, PostgreSQL's per-round p95 was 0.490,
|
|
53
|
+
0.491, and 0.500 ms. An earlier implementation used the ordinary named
|
|
54
|
+
query and measured 0.877, 0.878, and 1.003 ms on the same fixture.
|
|
55
|
+
One first check per depth after seeding, using a fresh adapter, took
|
|
56
|
+
6.73–8.98 ms with PostgreSQL and 2.26–4.86 ms with SpiceDB. These first
|
|
57
|
+
calls include any connection setup deferred until the first request and
|
|
58
|
+
start with the server already running.
|
|
59
|
+
|
|
60
|
+
The graph has a shared chain and one grant. The 8- and 16-arrow cases use
|
|
61
|
+
the bounded indexed traversal, while the 2-arrow case uses the shallow
|
|
62
|
+
prepared path. It exercises neither production
|
|
63
|
+
network hops nor all policy shapes, datastore configurations, or vendor
|
|
64
|
+
features. A warm point check can still exceed 1 ms, especially for wide
|
|
65
|
+
graphs that need the full traversal.
|
|
66
|
+
|
|
67
|
+
A separate 5,001-way branch at 16 arrows tested the exact fallback with
|
|
68
|
+
eight checks per mode in each of two alternating rounds. The observed
|
|
69
|
+
maximums were 486 and 281 ms for the ordinary prepared query, and 332 and
|
|
70
|
+
281 ms with the bounded traversal plus fallback. The small fanout sample
|
|
71
|
+
illustrates how wide data can dominate absolute latency.
|
|
72
|
+
|
|
73
|
+
## Opt-in lookup reuse
|
|
74
|
+
|
|
75
|
+
This run measured the public `lookupResources` call on PostgreSQL 16.16 after analyzing
|
|
76
|
+
the fixture tables. The application alternated between two users with distinct
|
|
77
|
+
authorized sets of 5,000 IDs reached over eight hops. The driver was on the
|
|
78
|
+
same Linux VM. The caller verified the complete ordered answers outside the
|
|
79
|
+
elapsed interval. Each row has 40 to 100 timed iterations after warm-up.
|
|
80
|
+
Batch rows measure completion of all eight operations.
|
|
81
|
+
|
|
82
|
+
| Public operation or workload | p95, ms |
|
|
83
|
+
| ----------------------------------------------------------------------- | -----------: |
|
|
84
|
+
| Fresh lookup, reuse disabled | 9.31 |
|
|
85
|
+
| Reuse enabled, forced miss on every call | 11.93 |
|
|
86
|
+
| Reuse enabled, both answers retained | 0.97 |
|
|
87
|
+
| Eight concurrent retained lookups | 1.05 |
|
|
88
|
+
| Retained lookups with an unrelated write every ten calls | 0.85 |
|
|
89
|
+
| Lookups with a same-namespace write every ten calls | 10.83 |
|
|
90
|
+
| Eight concurrent inserts to one namespace, migration absent / installed | 4.14 / 35.26 |
|
|
91
|
+
|
|
92
|
+
The recorded run had one-minute VM load 6.25. An earlier run saw a retained
|
|
93
|
+
lookup p95 of 0.43 ms and eight-write batch p95 of 0.88 / 2.96 ms. The revision
|
|
94
|
+
row is a contention point for writers. A lookup miss still evaluates the
|
|
95
|
+
graph, and throughput and tail latency depend on how often its namespace
|
|
96
|
+
changes. These retained-result timings include a primary PostgreSQL revision
|
|
97
|
+
read. They apply only after a successful fill for the same lookup. Fresh or
|
|
98
|
+
invalidated lookups still read the graph and return every requested ID.
|
|
99
|
+
|
|
100
|
+
## Recursive userset traversal
|
|
101
|
+
|
|
102
|
+
PostgreSQL 16.16 on the same Linux VM. Baseline and candidate alternated on
|
|
103
|
+
the same tuple table. Each result was verified; reported p95 is the upper
|
|
104
|
+
sample of eight calls. Before an explicit `ANALYZE`, the baseline recursive
|
|
105
|
+
step for 1,024 memberships revisited about 1,050,000 tuples. The same step
|
|
106
|
+
with indexed frontier probes visited 1,025 frontier rows. Both arms used the same test deadline.
|
|
107
|
+
|
|
108
|
+
| Nested memberships | Point check p95 before / after | Lookup p95 before / after |
|
|
109
|
+
| -----------------: | -----------------------------: | ------------------------: |
|
|
110
|
+
| 32 | 1.42 / 0.81 ms | 0.99 / 0.63 ms |
|
|
111
|
+
| 1,024 | 219.14 / 3.40 ms | 206.14 / 3.00 ms |
|
|
112
|
+
| 10,000 | timeout / 26.34 ms | timeout / 24.36 ms |
|
|
113
|
+
|
|
114
|
+
After explicit `ANALYZE`, the baseline and candidate 10,000-edge checks
|
|
115
|
+
both measured about 26 ms p95, and lookups about 23 ms p95. These chains
|
|
116
|
+
exercise nested subject sets, separate from the permission-arrow graph
|
|
117
|
+
above. Each test also checked denial, batched decisions, rollback and
|
|
118
|
+
revocation of a middle relationship, and regrant.
|
|
119
|
+
|
|
120
|
+
Ordinary permission-arrow fixtures remained comparable. At two hops and
|
|
121
|
+
500 IDs, allowed lookup p95 was 1.93 / 1.90 ms before explicit analyze.
|
|
122
|
+
At eight hops, 500 parent branches and 5,000 IDs it was 16.40 / 15.71 ms
|
|
123
|
+
before analyze. After analyze the broad fixture had similar medians
|
|
124
|
+
(14.98 / 15.11 ms) and more variable tails (16.40 / 19.50 ms). Each fixture
|
|
125
|
+
checked ordered result equality and post-commit revocation.
|
|
126
|
+
|
|
127
|
+
## Recursive group membership soak
|
|
128
|
+
|
|
129
|
+
From a built checkout with Docker available:
|
|
130
|
+
|
|
131
|
+
```sh
|
|
132
|
+
CONTAINER_PER_FILE=1 POSTGRES_ACCESS_DEEP_SOAK=1 npm run test:integration -w @dads-framework/postgres-access -- recursive-subject-set.integration.test.ts
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The soak traverses 32, 128, 1,024, and 10,000 group-to-group subject-set
|
|
136
|
+
links. Each case adds one root user membership and one terminal document
|
|
137
|
+
grant, for 10,002 tuples in the deepest case. These hops follow data across
|
|
138
|
+
instances of the same group relation. The arrow benchmarks above follow
|
|
139
|
+
permission references declared in the schema.
|
|
140
|
+
|
|
141
|
+
At each depth, the soak checks a point allow, ordered bulk allow and deny
|
|
142
|
+
decisions, and a singleton lookup. Removing a midpoint membership denies the
|
|
143
|
+
previously allowed point and bulk checks and empties the lookup. Restoring the
|
|
144
|
+
membership restores access and discovery.
|
|
145
|
+
|
|
146
|
+
The test uses isolated databases and sets `statement_timeout` to 4.9 seconds
|
|
147
|
+
for its fixture. This is a test setting.
|
|
148
|
+
The test disables autovacuum for its fixture table to control when statistics
|
|
149
|
+
are collected. One run leaves the freshly seeded table unanalyzed, and the
|
|
150
|
+
other runs `ANALYZE` after each seed. In a development VM run before the
|
|
151
|
+
indexed recursive traversal change, the first 10,000-hop point check hit the
|
|
152
|
+
4.9-second deadline without `ANALYZE`. With indexed traversal, all four depths
|
|
153
|
+
passed before and after `ANALYZE` on the same VM.
|
|
154
|
+
|
|
155
|
+
## Historical compiler measurements
|
|
156
|
+
|
|
157
|
+
These tables document changes to the benchmark fixtures over time. The
|
|
158
|
+
current code and benchmark commands can produce different timings.
|
|
159
|
+
|
|
160
|
+
### Original forward and reverse baseline
|
|
161
|
+
|
|
162
|
+
This early baseline was measured on 2026-11-19 Mountain Time. Both backends ran in containers on the same Linux development VM with a 32-vCPU Intel Core i9-13900KF and 25 GiB RAM. Postgres used the `postgres:16-alpine` image. SpiceDB v1.57.0 used its in-memory datastore and fully consistent reads. Node was v24.20.0.
|
|
163
|
+
|
|
164
|
+
The fixture grants one actor access through a chain of parent relationships. A single check targets one leaf. A lookup returns every leaf the actor can see. The benchmark validates each answer and takes 15 sequential samples after one warm-up call. Timings include application-side query compilation, transport, and reading the response. They exclude schema installation and seeding. This run used a 4.9-second PostgreSQL statement deadline and a 5-second client deadline.
|
|
165
|
+
|
|
166
|
+
All figures are milliseconds, shown as median / p95.
|
|
167
|
+
|
|
168
|
+
| Arrow depth | Visible IDs | Postgres check | SpiceDB check | Postgres lookup | SpiceDB lookup |
|
|
169
|
+
| ----------: | ----------: | -------------: | ------------: | --------------: | --------------: |
|
|
170
|
+
| 2 | 500 | 1.43 / 1.67 | 1.00 / 1.33 | 1.69 / 2.97 | 4.97 / 10.70 |
|
|
171
|
+
| 8 | 5,000 | Timeout | 0.74 / 1.74 | 48.06 / 53.23 | 59.57 / 87.73 |
|
|
172
|
+
| 16 | 5,000 | Timeout | 2.35 / 3.04 | 109.85 / 128.91 | 156.05 / 215.70 |
|
|
173
|
+
|
|
174
|
+
The original forward SQL check timed out at eight and sixteen arrows while reverse resource discovery completed. Keep the backend experimental and measure check latency on the application's real policy graph before rollout. These samples do not establish production throughput, concurrent behavior, or performance with a persistent SpiceDB datastore.
|
|
175
|
+
|
|
176
|
+
To run the same fixture against the current implementation:
|
|
177
|
+
|
|
178
|
+
```sh
|
|
179
|
+
CONTAINER_PER_FILE=1 npm run benchmark -w @dads-framework/postgres-access
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### Forward-check follow-up
|
|
183
|
+
|
|
184
|
+
On Postgres 16.16, the original depth-8 and depth-16 statements planned in
|
|
185
|
+
2.40 ms and 5.01 ms, then timed out during execution at 4.9 seconds. The
|
|
186
|
+
original plans pulled the arrow predicates up into nested semijoins. Disabling
|
|
187
|
+
JIT and setting `join_collapse_limit = 1` did not stop the timeouts. Keeping
|
|
188
|
+
each arrow as a correlated subplan with `OFFSET 0` left the predicates and
|
|
189
|
+
deadline intact. The resulting EXPLAIN ANALYZE reported 0.59 ms planning and
|
|
190
|
+
0.25 ms execution at depth 8, and 1.54 ms planning and 0.56 ms execution at
|
|
191
|
+
depth 16.
|
|
192
|
+
|
|
193
|
+
The same application benchmark also passed under concurrent VM load. The
|
|
194
|
+
one-minute load rose from 36.54 to 43.62 on 32 vCPUs. The kernel's ten-second
|
|
195
|
+
CPU pressure was 36.47% at the start and 27.64% at the end. These are measured
|
|
196
|
+
contention conditions. They differ from the earlier baseline.
|
|
197
|
+
|
|
198
|
+
| Arrow depth | Visible IDs | Postgres check | SpiceDB check | Postgres lookup | SpiceDB lookup |
|
|
199
|
+
| ----------: | ----------: | -------------: | ------------: | --------------: | --------------: |
|
|
200
|
+
| 2 | 500 | 1.87 / 3.22 | 1.94 / 5.28 | 4.04 / 22.94 | 15.23 / 35.90 |
|
|
201
|
+
| 8 | 5,000 | 2.31 / 6.73 | 2.43 / 5.83 | 86.43 / 94.09 | 123.45 / 148.72 |
|
|
202
|
+
| 16 | 5,000 | 5.63 / 6.56 | 3.20 / 3.78 | 146.43 / 193.42 | 105.89 / 133.29 |
|
|
203
|
+
|
|
204
|
+
In a second run with lower CPU pressure (10.94% to 4.65%), the depth-8
|
|
205
|
+
Postgres check measured 2.76 / 4.40 ms and depth 16 measured 2.10 / 2.73 ms.
|
|
206
|
+
Lookup medians were 80.26 ms and 117.57 ms respectively.
|
|
207
|
+
|
|
208
|
+
This historical comparison changed the forward SQL only. The adapter
|
|
209
|
+
remains experimental. This fixture measures one chain with a shared parent
|
|
210
|
+
and sequential requests. Production policies may have branching relationships,
|
|
211
|
+
more tuples, and concurrent reads and writes.
|
|
212
|
+
|
|
213
|
+
### Reverse-lookup follow-up
|
|
214
|
+
|
|
215
|
+
This historical change made reverse lookup drive each relationship hop from the resource IDs already
|
|
216
|
+
reached. A correlated lateral subquery keeps PostgreSQL from moving a broad
|
|
217
|
+
tuple scan ahead of the reached IDs. Each hop still returns distinct IDs and
|
|
218
|
+
the final result remains sorted. This comparison kept the forward compiler unchanged.
|
|
219
|
+
|
|
220
|
+
PostgreSQL 16.16 on the same 32-vCPU Linux VM. Baseline and candidate alternated
|
|
221
|
+
on the same database, with four warm-up and 20 timed calls per operation. Each
|
|
222
|
+
call checked the complete ordered ID result. Values below are p95 milliseconds.
|
|
223
|
+
|
|
224
|
+
| Shape, visible IDs | Table statistics | Allowed before / after | Denied before / after |
|
|
225
|
+
| -------------------------------------- | ----------------------- | ---------------------: | --------------------: |
|
|
226
|
+
| 8 hops, one parent branch, 5,000 IDs | Before explicit analyze | 63.77 / 6.62 | 58.14 / 3.20 |
|
|
227
|
+
| 16 hops, one parent branch, 5,000 IDs | Before explicit analyze | 123.65 / 8.58 | 108.98 / 3.06 |
|
|
228
|
+
| 8 hops, 500 parent branches, 5,000 IDs | Before explicit analyze | 4.9 s timeout / 18.32 | — / 2.28 |
|
|
229
|
+
| 8 hops, 500 parent branches, 5,000 IDs | After analyze | 20.02 / 15.88 | 1.20 / 1.09 |
|
|
230
|
+
|
|
231
|
+
With the broad graph the baseline timed out during its allowed warm-up before
|
|
232
|
+
the denied samples ran. The narrower, analyzed graphs already used efficient
|
|
233
|
+
plans and showed similar medians. Tail timings varied across repeats. Before
|
|
234
|
+
explicit analyze, the depth-16 baseline plan ran the inner chain 5,000 times.
|
|
235
|
+
The measured execution time fell from 150.995 ms to 3.730 ms when the query
|
|
236
|
+
drove the walk from the reached parent. These are synthetic planner tests,
|
|
237
|
+
with no throughput measurement.
|
|
238
|
+
|
|
239
|
+
### Earlier prepared single checks
|
|
240
|
+
|
|
241
|
+
This historical comparison predates bounded linear checks and the current
|
|
242
|
+
limits on named ordinary statements. To run the fixture on the current checkout:
|
|
243
|
+
|
|
244
|
+
```sh
|
|
245
|
+
CONTAINER_PER_FILE=1 npm run benchmark -w @dads-framework/postgres-access -- src/prepared-single-check.benchmark.test.ts
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
This exercises public `PostgresAuthorization.check()` over local TCP against
|
|
249
|
+
Postgres 16.16 with an eight-connection node-postgres pool. It interleaves
|
|
250
|
+
unnamed and named statements across three runs of 1,280 measured checks per
|
|
251
|
+
mode and worker count. Each worker warms up with 30 checks before sampling.
|
|
252
|
+
The fixture has one shared chain per namespace, 5,000 leaves for each positive
|
|
253
|
+
depth, varied resource and subject IDs, and 25% denials. It proves that
|
|
254
|
+
revocations, re-grants, a different subject kind, and an isolated namespace
|
|
255
|
+
change the answer after warm-up. Timings include SQL compilation, the pool,
|
|
256
|
+
the round trip, and decision decoding. They exclude HTTP and cold pool
|
|
257
|
+
startup.
|
|
258
|
+
|
|
259
|
+
Each cell lists the p95 in milliseconds from the three runs on the Linux VM.
|
|
260
|
+
|
|
261
|
+
| Arrows | Workers | Unnamed p95 | Named p95 |
|
|
262
|
+
| -----: | ------: | ---------------: | ---------------: |
|
|
263
|
+
| 0 | 1 | 0.47, 0.40, 0.45 | 0.29, 0.31, 0.30 |
|
|
264
|
+
| 0 | 8 | 0.69, 0.77, 0.72 | 0.68, 0.63, 0.59 |
|
|
265
|
+
| 2 | 1 | 0.62, 0.63, 0.69 | 0.17, 0.16, 0.27 |
|
|
266
|
+
| 2 | 8 | 1.11, 1.10, 1.14 | 0.55, 0.48, 0.58 |
|
|
267
|
+
| 8 | 1 | 1.15, 1.15, 1.15 | 0.40, 0.29, 0.51 |
|
|
268
|
+
| 8 | 8 | 2.23, 2.34, 2.37 | 0.57, 0.58, 0.73 |
|
|
269
|
+
| 16 | 1 | 1.94, 1.96, 1.94 | 0.41, 0.42, 0.43 |
|
|
270
|
+
| 16 | 8 | 4.23, 4.28, 4.30 | 0.92, 0.88, 0.89 |
|
|
271
|
+
|
|
272
|
+
An earlier matching fixture on the VM gave 1.03, 1.03, and 0.98 ms named
|
|
273
|
+
at 16 arrows with eight workers. The recorded tail crossed 1 ms in other runs of the same fixture. New or replaced connections still incur
|
|
274
|
+
parse and planning costs. PostgreSQL can retain custom plans for some
|
|
275
|
+
queries, and production policies, tuple distributions, and transport differ.
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bryton Cooper
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,276 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@dads-framework/postgres-access`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Check permissions, list the resources a user can access, and commit relationship
|
|
4
|
+
changes alongside business data in the application's Postgres database.
|
|
5
|
+
|
|
6
|
+
## Trusted experimental
|
|
7
|
+
|
|
8
|
+
We recommend this adapter when your app keeps its records and permission
|
|
9
|
+
relationships in the same Postgres database and your policy fits the
|
|
10
|
+
[supported model](#what-it-refuses-to-do). For example, removing a workspace
|
|
11
|
+
member can delete their membership row and revoke their access in one
|
|
12
|
+
transaction. Both changes commit together or both roll back. A check using
|
|
13
|
+
a fresh snapshot on the primary sees the revocation as soon as it commits. That
|
|
14
|
+
removes the authorization outbox, its delivery worker, and the interval
|
|
15
|
+
during which a committed revoke would still be waiting for delivery.
|
|
16
|
+
|
|
17
|
+
Its access decisions and visible resource lists have been checked against
|
|
18
|
+
SpiceDB. The [live transaction tests](./src/protected-transaction.integration.test.ts)
|
|
19
|
+
cover revocation and rollback. The [graph tests](./src/recursive-subject-set.integration.test.ts)
|
|
20
|
+
also exercise nested memberships up to 10,000 links.
|
|
21
|
+
|
|
22
|
+
Start with one protected operation and test a grant, a denial and a
|
|
23
|
+
revocation with your own policy. Measure checks and lists while permissions
|
|
24
|
+
are changing. Sustained production performance under that mix is still open.
|
|
25
|
+
See the [benchmark results](./BENCHMARK.md) for measured workloads.
|
|
26
|
+
|
|
27
|
+
## Protected writes
|
|
28
|
+
|
|
29
|
+
Use `withProtectedPostgresTransaction({ database, authorization }, work)`
|
|
30
|
+
when a decision protects a write. The helper opens a serializable Drizzle
|
|
31
|
+
transaction and passes `{ tx, authorization }` to the callback. Check access
|
|
32
|
+
again inside the callback, even if the route already authorized the request.
|
|
33
|
+
Use these same handles for the application writes and relationship changes. Await all work before leaving the callback.
|
|
34
|
+
The authorization handle expires on return or error.
|
|
35
|
+
|
|
36
|
+
To join an existing transaction, pass `{ transaction: tx, authorization }`.
|
|
37
|
+
The helper verifies that it is already serializable and uses the same
|
|
38
|
+
transaction. The caller still owns commit and rollback. Propagate failures so
|
|
39
|
+
the outer transaction can roll back. The helper does not create a savepoint.
|
|
40
|
+
|
|
41
|
+
A PostgreSQL serialization failure surfaces as `PostgresSerializationConflict`
|
|
42
|
+
with code `POSTGRES_CONFLICT` and `retryable: true`. A caller that owns the
|
|
43
|
+
outer commit can use `readPostgresSerializationConflict(error)` to classify
|
|
44
|
+
a failure raised there. Retry the entire application transaction if retrying
|
|
45
|
+
is appropriate. The helper invokes the callback at most once per call.
|
|
46
|
+
|
|
47
|
+
Serializable isolation makes the commit consistent with a serial ordering of
|
|
48
|
+
transactions. A revoke committed before the permission check's transaction
|
|
49
|
+
snapshot is visible to that check. An overlapping revoke may serialize after
|
|
50
|
+
the protected write. If an operation requires revocation to take precedence
|
|
51
|
+
over an overlapping write, coordinate both operations through an application
|
|
52
|
+
lock or equivalent ordering mechanism. For reads and explicit tuple changes
|
|
53
|
+
in an existing transaction, use `inTransaction` or `inDrizzleTransaction`.
|
|
54
|
+
|
|
55
|
+
## Try it
|
|
56
|
+
|
|
57
|
+
In the generated starter, [`assembly/services.ts`](../../../apps/kit-workbench/assembly/services.ts) creates the Postgres
|
|
58
|
+
adapter and connects it to tenant services using the application database.
|
|
59
|
+
[`assembly/protected-write.ts`](../../../apps/kit-workbench/assembly/protected-write.ts) checks permission in the transaction
|
|
60
|
+
that commits the protected write.
|
|
61
|
+
|
|
62
|
+
Use Node.js 22 or later and an empty development Postgres database. Set
|
|
63
|
+
`DATABASE_URL` to a connection string for a role that can create tables and
|
|
64
|
+
indexes. The script installs the relationship schema and uses a fresh
|
|
65
|
+
namespace per run. In an application, apply the SQL through your migration
|
|
66
|
+
runner and use a stable namespace.
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
npm install @dads-framework/access @dads-framework/postgres @dads-framework/postgres-access zod
|
|
70
|
+
npm install -D tsx
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Save as `check-postgres-access.mts` and run `npx tsx check-postgres-access.mts`.
|
|
74
|
+
|
|
75
|
+
<!-- dads:check-example -->
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { randomUUID } from "node:crypto";
|
|
79
|
+
import { access, accessModel, entityHandle } from "@dads-framework/access";
|
|
80
|
+
import { relationshipWrite } from "@dads-framework/access/runtime";
|
|
81
|
+
import { createPostgresConnection } from "@dads-framework/postgres";
|
|
82
|
+
import {
|
|
83
|
+
PostgresAuthorization,
|
|
84
|
+
relationshipSchemaMigration,
|
|
85
|
+
} from "@dads-framework/postgres-access";
|
|
86
|
+
import { z } from "zod";
|
|
87
|
+
|
|
88
|
+
const connectionString = process.env.DATABASE_URL;
|
|
89
|
+
if (!connectionString) throw new Error("Set DATABASE_URL.");
|
|
90
|
+
|
|
91
|
+
const user = entityHandle({ wireName: "user", idSchema: z.string() });
|
|
92
|
+
const team = entityHandle({
|
|
93
|
+
wireName: "team",
|
|
94
|
+
idSchema: z.string(),
|
|
95
|
+
kind: "scope",
|
|
96
|
+
});
|
|
97
|
+
const teamAccess = access(team, {
|
|
98
|
+
roles: { member: user },
|
|
99
|
+
permissions: (roles) => ({ view: [roles.member] }),
|
|
100
|
+
});
|
|
101
|
+
const model = accessModel([
|
|
102
|
+
access(user, { roles: {}, permissions: () => ({}) }),
|
|
103
|
+
teamAccess,
|
|
104
|
+
]);
|
|
105
|
+
|
|
106
|
+
const connection = createPostgresConnection(
|
|
107
|
+
{ connectionString, schema: {} },
|
|
108
|
+
console,
|
|
109
|
+
);
|
|
110
|
+
try {
|
|
111
|
+
await connection.pool.query(relationshipSchemaMigration.sql);
|
|
112
|
+
const authorization = new PostgresAuthorization({
|
|
113
|
+
model,
|
|
114
|
+
namespace: randomUUID(),
|
|
115
|
+
executor: connection.pool,
|
|
116
|
+
});
|
|
117
|
+
const resource = { type: team.wireName, id: "team-1" };
|
|
118
|
+
const subject = { type: user.wireName, id: "alice" };
|
|
119
|
+
const relation = teamAccess.roles.member.roleName;
|
|
120
|
+
const query = {
|
|
121
|
+
resource,
|
|
122
|
+
subject,
|
|
123
|
+
permission: teamAccess.permissions.view.permissionName,
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
console.log(await authorization.check(query));
|
|
127
|
+
await authorization.writeRelationships([
|
|
128
|
+
relationshipWrite(resource, relation, subject),
|
|
129
|
+
]);
|
|
130
|
+
console.log(await authorization.check(query));
|
|
131
|
+
await authorization.deleteRelationships({
|
|
132
|
+
resourceType: resource.type,
|
|
133
|
+
resourceId: resource.id,
|
|
134
|
+
relation,
|
|
135
|
+
subject,
|
|
136
|
+
});
|
|
137
|
+
console.log(await authorization.check(query));
|
|
138
|
+
} finally {
|
|
139
|
+
await connection.close();
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The script prints `false`, `true`, and `false` as the membership is granted
|
|
144
|
+
and revoked.
|
|
145
|
+
|
|
146
|
+
## Use it
|
|
147
|
+
|
|
148
|
+
Choose Postgres for an app that already uses Postgres and can keep relationship facts beside its data. Install the relationship schema through the app's migration runner. Configure a stable namespace for this model, and select the backend at application composition. Use the same model for Postgres policy compilation and HTTP scope planning.
|
|
149
|
+
|
|
150
|
+
Bind `TransactionalAccessChanges` as the enqueue port and
|
|
151
|
+
`AlreadyAppliedAccessChanges` as the after-commit dispatcher. The
|
|
152
|
+
application passes its active transaction to `enqueue(entries, tx)`.
|
|
153
|
+
Relationship facts and the business row then commit or roll back together.
|
|
154
|
+
|
|
155
|
+
In Postgres mode, start neither the access-change projector nor the SpiceDB migration runner. Successful writes return an empty consistency token. Data visibility follows the caller's Postgres transaction. The after-commit dispatcher is a no-op because committed facts are already visible. Keep any application locks that coordinate work beyond projecting authorization facts.
|
|
156
|
+
|
|
157
|
+
Choose the backend based on the model features the application needs, its
|
|
158
|
+
transaction requirements, and measurements with its own data and traffic.
|
|
159
|
+
The [SpiceDB adapter](../authorization/README.md) provides a separate graph
|
|
160
|
+
store, with a Postgres outbox for writes.
|
|
161
|
+
|
|
162
|
+
## What it refuses to do
|
|
163
|
+
|
|
164
|
+
Compilation rejects missing relation or permission targets, empty expressions, and local permission cycles. Cross-entity permission cycles are unsupported by the SQL engine. Each arrow needs one direct target entity type. Permission checks require a concrete subject; relationship writes can contain wildcard and subject-set tuples.
|
|
165
|
+
|
|
166
|
+
The enqueue port rejects a database handle in place of an application transaction. Its transaction-bound changes are exact tuple writes or deletes. A broad revocation sweep needs its filters passed to a transaction-bound adapter if it must commit with the business update.
|
|
167
|
+
|
|
168
|
+
## Contract
|
|
169
|
+
|
|
170
|
+
`PostgresAuthorization` implements the authorization port's checks, ordered bulk checks, discovery, relationship writes and filtered deletes, direct-subject listing, and relationship existence reads. Unknown permission names give denied checks and empty lookup results. Invalid tuple writes and failed storage operations reject.
|
|
171
|
+
|
|
172
|
+
For operations on a root adapter, `queryTimeoutMs` defaults to 5,000 ms. It
|
|
173
|
+
is a client deadline for executors that honor node-postgres query options.
|
|
174
|
+
Configure a server-side `statement_timeout` in the application as needed.
|
|
175
|
+
Drizzle transaction operations use the application's database settings.
|
|
176
|
+
Connection management and schema migration remain application-owned.
|
|
177
|
+
|
|
178
|
+
With Docker available, run the integration suite from a built checkout:
|
|
179
|
+
|
|
180
|
+
```sh
|
|
181
|
+
CONTAINER_PER_FILE=1 npm run test:integration -w @dads-framework/postgres-access
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
The [benchmark notes](./BENCHMARK.md) explain which read paths were measured.
|
|
185
|
+
|
|
186
|
+
### Optimize point checks
|
|
187
|
+
|
|
188
|
+
For a direct node-postgres pool, opt in by passing
|
|
189
|
+
`executor: preparePostgresChecks(connection.pool)`. Share the wrapper across
|
|
190
|
+
authorization namespaces. The wrapper can admit up to 64 distinct SQL shapes
|
|
191
|
+
of at most 4 KiB each and 32 KiB total per pool lifetime. Other shapes execute
|
|
192
|
+
unnamed, as do bulk checks, lookups, and writes. PostgreSQL decides when each
|
|
193
|
+
connection can reuse a generic plan. New connections and the first checks on
|
|
194
|
+
each connection still pay planning costs.
|
|
195
|
+
|
|
196
|
+
Checks always read the facts visible to the executing transaction. The wrapper
|
|
197
|
+
stores statement names and SQL shapes, and PostgreSQL stores plans per
|
|
198
|
+
connection. Use the ordinary executor for connections through poolers that do
|
|
199
|
+
not support protocol-level named statements. Drizzle-bound transactions
|
|
200
|
+
continue using their own execution path.
|
|
201
|
+
|
|
202
|
+
Prepared single checks can fuse a chain of four to 32 arrows ending in one
|
|
203
|
+
relation into an indexed recursive query. The query preserves wildcard grants
|
|
204
|
+
and recursive subject sets. If the bounded traversal completes without a
|
|
205
|
+
match, it denies. If the traversal reaches its bound without deciding, the
|
|
206
|
+
adapter runs the full check unnamed with the remaining query deadline.
|
|
207
|
+
Small ordinary point checks may also use named statements when their policy
|
|
208
|
+
has at most two arrows and four total relation or arrow references.
|
|
209
|
+
Larger point checks, bulk checks, and Drizzle transactions run unnamed.
|
|
210
|
+
A bulk branch with four to 32 linear arrows evaluates the complete
|
|
211
|
+
permission once per distinct subject and joins the results to the original
|
|
212
|
+
request ordinals. Mixed permissions, denials, and duplicate request rows
|
|
213
|
+
keep their order in the same SQL statement.
|
|
214
|
+
If a point policy expands beyond 64 KiB of forward SQL, the adapter compiles
|
|
215
|
+
a single Boolean query that shares repeated permission expressions and matches
|
|
216
|
+
the requested resource in PostgreSQL. It reads current relationship facts
|
|
217
|
+
under the configured query deadline.
|
|
218
|
+
|
|
219
|
+
### Reuse large lookup results
|
|
220
|
+
|
|
221
|
+
By default, `lookupResources` evaluates the current relationship graph on
|
|
222
|
+
every call. For repeated lookups in a read-mostly service, an application can
|
|
223
|
+
opt in to reusing immutable ID lists. A reused list still makes a fresh
|
|
224
|
+
database round trip for every call. Transaction-bound adapters always
|
|
225
|
+
evaluate within their transaction.
|
|
226
|
+
|
|
227
|
+
Install `lookupRevisionSchemaMigration` after `relationshipSchemaMigration`
|
|
228
|
+
in the application's normal migration runner. Apply the optional migration
|
|
229
|
+
in one transaction as the migration owner. Existing v1 installations can
|
|
230
|
+
continue without it. This mode requires the durable, unpartitioned
|
|
231
|
+
`public.dad_authorization_relationship` table without row-level security.
|
|
232
|
+
|
|
233
|
+
Use a direct node-postgres 8.21+ pool connected to one primary. Configure its
|
|
234
|
+
role and search path once and keep the pool out of session-routing middleware.
|
|
235
|
+
The runtime role may use the tuple table and read revision metadata. Do not
|
|
236
|
+
grant runtime roles owner membership, schema DDL, revision writes, sequence
|
|
237
|
+
usage, or trigger privileges. For example, grant an existing runtime role:
|
|
238
|
+
|
|
239
|
+
```sql
|
|
240
|
+
GRANT SELECT, INSERT, UPDATE, DELETE
|
|
241
|
+
ON public.dad_authorization_relationship TO app_runtime;
|
|
242
|
+
GRANT USAGE ON SCHEMA dad_lookup_revision TO app_runtime;
|
|
243
|
+
GRANT SELECT ON dad_lookup_revision.epoch, dad_lookup_revision.namespace
|
|
244
|
+
TO app_runtime;
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
const authorization = new PostgresAuthorization({
|
|
249
|
+
model,
|
|
250
|
+
namespace: "workspace",
|
|
251
|
+
executor: connection.pool,
|
|
252
|
+
reuseLookupResultsOn: connection.pool,
|
|
253
|
+
});
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
You can pass `preparePostgresChecks(connection.pool)` as the executor with the
|
|
257
|
+
same pool. Write and read-only transaction clients do not qualify. Remove the
|
|
258
|
+
option before rolling the optional migration back. Failed validation rejects
|
|
259
|
+
the operation and clears retained answers. Table-wide tuple `SELECT` is checked
|
|
260
|
+
for every reuse, so revoking it prevents reuse even if revision metadata is
|
|
261
|
+
still readable.
|
|
262
|
+
|
|
263
|
+
The migration marks each touched namespace in the same transaction as
|
|
264
|
+
INSERT, DELETE, or UPDATE. Moving a tuple marks both namespaces, and
|
|
265
|
+
TRUNCATE changes a shared epoch. A miss reads the ID list and its revision in
|
|
266
|
+
one statement. Each reuse, including coalesced empty lists, validates its
|
|
267
|
+
revision against the primary after the call begins. Calls that overlap a
|
|
268
|
+
commit may observe the snapshot before or after it.
|
|
269
|
+
|
|
270
|
+
The application still owns database administration. Keep the triggers
|
|
271
|
+
installed for all writers, including direct SQL. Stop reuse while privileged
|
|
272
|
+
maintenance could bypass them. Reapply the migration to rotate the
|
|
273
|
+
installation revision before resuming. Recreate the authorization instances
|
|
274
|
+
if their pool changes authority or is restored. The cache retains a bounded
|
|
275
|
+
number of lists and IDs. Same-namespace writers share a revision row, so
|
|
276
|
+
concurrent writes may slow down. See the [benchmark](./BENCHMARK.md).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type AccessModel } from "@dads-framework/access";
|
|
2
|
+
import type { AuthorizationModelDefinition } from "./policy/policy-model.js";
|
|
3
|
+
export type CompiledAccessPolicy = {
|
|
4
|
+
readonly model: AuthorizationModelDefinition;
|
|
5
|
+
/** The engine's permission name for an authored permission or direct relation. */
|
|
6
|
+
permissionName(entity: string, name: string): string | undefined;
|
|
7
|
+
};
|
|
8
|
+
export declare function compileAccessPolicy(access: AccessModel): CompiledAccessPolicy;
|
|
9
|
+
//# sourceMappingURL=compile-access-policy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compile-access-policy.d.ts","sourceRoot":"","sources":["../src/compile-access-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EACV,4BAA4B,EAG7B,MAAM,0BAA0B,CAAC;AAOlC,MAAM,MAAM,oBAAoB,GAAG;IACjC,QAAQ,CAAC,KAAK,EAAE,4BAA4B,CAAC;IAC7C,kFAAkF;IAClF,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CAClE,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,WAAW,GAAG,oBAAoB,CA0B7E"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { emitAccessIr, } from "@dads-framework/access";
|
|
2
|
+
import { lowerPermissions, } from "./lower-permissions.js";
|
|
3
|
+
export function compileAccessPolicy(access) {
|
|
4
|
+
const definitions = emitAccessIr(access);
|
|
5
|
+
const byName = new Map(definitions.map((entry) => [entry.wireName, entry]));
|
|
6
|
+
const generated = new Map(definitions.map((entry) => [entry.wireName, rolePermissions(entry)]));
|
|
7
|
+
const model = {
|
|
8
|
+
entities: definitions.map((entry, index) => ({
|
|
9
|
+
wireName: entry.wireName,
|
|
10
|
+
sourceName: `entity_${index}`,
|
|
11
|
+
})),
|
|
12
|
+
relations: definitions.flatMap(lowerRelations),
|
|
13
|
+
permissions: definitions.flatMap((entry) => compiledPermissions(entry, { byName, generated })),
|
|
14
|
+
lifecycle: [],
|
|
15
|
+
};
|
|
16
|
+
return {
|
|
17
|
+
model,
|
|
18
|
+
permissionName: (entity, name) => {
|
|
19
|
+
const definition = byName.get(entity);
|
|
20
|
+
if (definition?.permissions.some((entry) => entry.name === name))
|
|
21
|
+
return name;
|
|
22
|
+
return generated.get(entity)?.get(name);
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function lowerRelations(definition) {
|
|
27
|
+
return definition.roles.map((role, index) => ({
|
|
28
|
+
authority: "system",
|
|
29
|
+
entity: definition.wireName,
|
|
30
|
+
sourceName: `relation_${index}`,
|
|
31
|
+
wireName: role.name,
|
|
32
|
+
targets: role.subjects.map((subject) => {
|
|
33
|
+
if (subject.kind === "userset") {
|
|
34
|
+
return {
|
|
35
|
+
kind: "subject-set",
|
|
36
|
+
entity: subject.wireName,
|
|
37
|
+
relation: subject.relation,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
kind: subject.kind === "type" ? "entity" : "wildcard",
|
|
42
|
+
entity: subject.wireName,
|
|
43
|
+
};
|
|
44
|
+
}),
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
function compiledPermissions(definition, context) {
|
|
48
|
+
const authored = lowerPermissions(definition, context);
|
|
49
|
+
const wrappers = context.generated.get(definition.wireName) ?? new Map();
|
|
50
|
+
return [
|
|
51
|
+
...authored,
|
|
52
|
+
...[...wrappers].map(([relation, wireName], index) => ({
|
|
53
|
+
entity: definition.wireName,
|
|
54
|
+
sourceName: `relation_permission_${index}`,
|
|
55
|
+
wireName,
|
|
56
|
+
expression: { kind: "relation", relation },
|
|
57
|
+
})),
|
|
58
|
+
];
|
|
59
|
+
}
|
|
60
|
+
function rolePermissions(definition) {
|
|
61
|
+
const names = new Set([
|
|
62
|
+
...definition.roles.map((entry) => entry.name),
|
|
63
|
+
...definition.permissions.map((entry) => entry.name),
|
|
64
|
+
]);
|
|
65
|
+
const wrappers = new Map();
|
|
66
|
+
let suffix = 0;
|
|
67
|
+
for (const role of definition.roles) {
|
|
68
|
+
let generated;
|
|
69
|
+
do {
|
|
70
|
+
generated = `dads_relation_${suffix}`;
|
|
71
|
+
suffix += 1;
|
|
72
|
+
} while (names.has(generated));
|
|
73
|
+
wrappers.set(role.name, generated);
|
|
74
|
+
}
|
|
75
|
+
return wrappers;
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=compile-access-policy.js.map
|