1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use async_trait;
use fmt;
use Hash;
use NonZeroUsize;
use Arc;
/// A typed fact key that can be loaded through an [`crate::EvaluationSession`].
///
/// Keys are flat, cloneable, and hashable so the session can deduplicate and
/// cache fact loads for the lifetime of a single [`crate::EvaluationSession`].
///
/// Caching is scoped to that session, not the process. Gatehouse has no
/// built-in notion of a "request"; the caller decides how long a session lives
/// and, by convention, scopes it to one authorization pass (for an HTTP
/// service, typically one inbound request). Cached facts and cached errors are
/// dropped when the session is dropped, so permission revocations or backend
/// changes are observed by the next session rather than being held in a
/// process-global cache.
/// Private error type backing [`FactLoadError::backend_message`], so callers
/// can wrap a human-readable message without defining their own error type.
;
/// Error raised while loading a fact.
/// Result of loading one fact.
///
/// This is shaped like `Result<Option<V>, FactLoadError>` — `Found`, `Missing`,
/// and `Error` map onto `Ok(Some)`, `Ok(None)`, and `Err`. A dedicated enum is
/// used instead so the three outcomes read as domain concepts at policy call
/// sites (`FactLoadResult::Missing` rather than `Ok(None)`), so "the fact does
/// not exist" is never visually conflated with "the load failed" — a
/// distinction that matters for fail-closed authorization — and so the type can
/// gain variants later without breaking a `Result` alias callers rely on.
/// A batched source for one fact key type.
///
/// Sources can be shared across many request sessions. The source owns
/// backend-specific serialization and I/O; the session owns per-request
/// deduplication, caching, chunking, and in-flight coalescing.
///
/// `FactSource` is gatehouse's request-scoped DataLoader-style primitive:
/// the session deduplicates inputs, holds a per-session cache, and joins
/// concurrent in-flight loads for the same key, then hands one or more
/// unique-key slices to [`Self::load_many`] (chunked by
/// [`Self::max_batch_size`]). If your application already runs a
/// DataLoader implementation — `async_graphql::dataloader` (from the
/// `async-graphql` crate), the `ultra-batch` crate, or any home-grown
/// batcher — call it directly from inside `load_many`. The two layers
/// compose: gatehouse owns the per-request fact graph for one
/// authorization pass; the underlying loader owns batching across the rest
/// of the request, request coalescing across many concurrent passes, and
/// any longer-lived caching.
///
/// # Beyond relationship facts: `(subject, scope) → resolved-id` lookups
///
/// `FactSource` is not relationship-shaped. Any per-request lookup whose
/// answer is fixed for the request — "what customer does this org map to",
/// "what tenant config applies to this caller", "what billing plan is in
/// force right now" — can be a fact key. Define a [`FactKey`] for the
/// question, register a source that resolves it, and have the policy ask
/// the session instead of calling the backing service directly. The session
/// then guarantees one round trip per unique key per request, regardless of
/// how many policies or items in a list endpoint consult it.
///
/// ```rust,ignore
/// use async_trait::async_trait;
/// use gatehouse::{FactKey, FactLoadResult, FactSource};
///
/// /// "Which customer is this org billed under?" — same answer for every
/// /// item in a list-of-invoices request.
/// #[derive(Debug, Clone, Hash, PartialEq, Eq)]
/// struct CustomerForOrg(uuid::Uuid);
///
/// impl FactKey for CustomerForOrg {
/// const NAME: &'static str = "customer_for_org";
/// type Value = Option<uuid::Uuid>;
/// }
///
/// struct HierarchyFacts(/* Arc<dyn HierarchyService> */);
///
/// #[async_trait]
/// impl FactSource<CustomerForOrg> for HierarchyFacts {
/// async fn load_many(
/// &self,
/// keys: &[CustomerForOrg],
/// ) -> Vec<FactLoadResult<Option<uuid::Uuid>>> {
/// // One backend call covering every unique org in the batch.
/// // Return one result per input key, in input order.
/// keys.iter()
/// .map(|_| FactLoadResult::Found(None)) // resolve from backend
/// .collect()
/// }
/// }
/// ```
///
/// Inside the policy, the canonical pattern is:
///
/// ```rust,ignore
/// async fn evaluate(
/// &self,
/// ctx: &EvalCtx<'_, OrgAuth, Invoice, Read, ()>,
/// ) -> PolicyEvalResult {
/// match ctx.session.get(CustomerForOrg(ctx.subject.org_id)).await {
/// FactLoadResult::Found(Some(customer_id)) if customer_id == ctx.resource.customer_id => {
/// ctx.grant("subject's org bills under the invoice's customer")
/// }
/// _ => ctx.deny("not the billing customer"),
/// }
/// }
/// ```
///
/// The built-in [`RebacPolicy`](crate::RebacPolicy) generalises this idiom
/// for relationship-shaped facts; the same plumbing handles arbitrary
/// `(subject, scope) → value` lookups when you define your own key.
/// Error returned by non-panicking fact-source registration helpers.
/// Canonical fact key for relationship (ReBAC) lookups.
///
/// A `RelationshipQuery` encodes one yes/no question: does `subject_id` have
/// `relation` to `resource_id`? It is the [`FactKey`] used by the built-in
/// [`crate::RebacPolicy`], with [`FactKey::Value`] = `bool` — a registered
/// [`FactSource`] answers `true` when the relationship exists and `false`
/// otherwise.
///
/// The three identifier types are generic so callers can use their own
/// strongly-typed ids and relation enums rather than stringly-typed keys.
/// Because the session registry is keyed by the concrete Rust type (see
/// [`crate::EvaluationSession`]), two logically distinct relationship graphs
/// that share the same `RelationshipQuery<…>` instantiation resolve to the same
/// source; give them distinct id or relation types if they must be backed
/// separately.
///
/// For relationships that carry a payload (a rank, weight, or scope set) rather
/// than a plain boolean, define a custom [`FactKey`] with `Value =
/// YourPayload` instead of using this type.
///
/// # Example
///
/// ```rust
/// # use gatehouse::RelationshipQuery;
/// #[derive(Clone, PartialEq, Eq, Hash, Debug)]
/// enum Relation {
/// Owner,
/// Viewer,
/// }
///
/// let query = RelationshipQuery {
/// subject_id: "user:42".to_string(),
/// resource_id: "doc:7".to_string(),
/// relation: Relation::Owner,
/// };
/// assert_eq!(query.relation, Relation::Owner);
/// ```