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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
use async_trait;
use Cow;
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`] and
/// [`FactLoadError::backend_with_message`]: a caller-authored message that is
/// safe to record in audit output, optionally wrapping the underlying error.
/// The [`FactLoadError::audit_detail`] text for a backend error that carries
/// no caller-authored message.
pub const REDACTED_BACKEND_DETAIL: &str =
"backend error (message withheld from audit output)";
/// Error raised while loading a fact.
///
/// [`fmt::Display`] and [`fmt::Debug`] include a wrapped backend error's own
/// text, so they are for operational logs only. [`Self::audit_detail`] is the
/// audit-safe form that Gatehouse records in traces.
/// Stable, value-erased classification of a [`FactLoadError`].
///
/// Use this when a machine needs to choose an operational response without
/// parsing [`FactLoadError`]'s human-readable [`fmt::Display`] output. The
/// classification deliberately does not promise that every backend error is
/// transient: callers can distinguish backend failures from Gatehouse source
/// wiring and contract failures, then apply their own retry policy.
/// 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
/// 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
/// # use async_trait::async_trait;
/// # use gatehouse::{EvalCtx, FactKey, FactLoadResult, GrantResult, Policy, PolicyDomain};
/// # use std::borrow::Cow;
/// # struct User { org_id: uuid::Uuid }
/// # struct Invoice { customer_id: uuid::Uuid }
/// # struct InvoiceAccess;
/// # impl PolicyDomain for InvoiceAccess {
/// # type Subject = User;
/// # type Action = ();
/// # type Resource = Invoice;
/// # type Context = ();
/// # }
/// # #[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 BillingCustomer;
/// # #[async_trait]
/// # impl Policy<InvoiceAccess> for BillingCustomer {
/// async fn evaluate(
/// &self,
/// ctx: &EvalCtx<'_, InvoiceAccess>,
/// ) -> GrantResult {
/// match ctx.fact(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.not_applicable("not the billing customer"),
/// }
/// }
/// # fn policy_type(&self) -> Cow<'static, str> { Cow::Borrowed("BillingCustomer") }
/// # }
/// ```
///
/// [`crate::EvalCtx::fact`] records the consulted fact as
/// [`crate::FactProvenance`] and the context's result helpers attach it, so
/// provenance is correct by construction — and a failed load reported
/// through `ctx.not_applicable` is upgraded to an indeterminate result,
/// which lets [`crate::AccessEvaluation::is_indeterminate`] distinguish a
/// failed load from an ordinary authorization denial. Policies that load
/// outside the context (via [`crate::EvalCtx::session`]) can still record
/// provenance manually with
/// [`FactProvenance::from_load_result`](crate::FactProvenance::from_load_result)
/// and [`crate::EvalCtx::record`].
///
/// 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 raised while installing fact sources into a request session.
pub
/// 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);
/// ```