id_effect_authz 0.10.1

Authorization for id_effect services: roles and permissions, named and resource policies, route guards
Documentation
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
//! Route guards (feature `axum`): a [`Guard`] is a Tower layer that evaluates a policy before the
//! handler runs, and [`AuthorizeExt::authorize`] attaches one to a route.
//!
//! # Where the principal comes from
//!
//! The guard reads the request's principal from its extensions, in this order:
//!
//! 1. a [`CurrentPrincipal`] request extension — what an authentication layer inserts
//!    (`req.extensions_mut().insert(CurrentPrincipal::new(..))`; `id_effect_auth`'s middleware
//!    does this);
//! 2. a [`CurrentPrincipal`] recorded in [`RequestCaps`] by an
//!    [`id_effect_axum::CapOverrideLayer`] (the per-request capability override);
//! 3. otherwise the [`Anonymous`](crate::Anonymous) principal.
//!
//! The authentication layer must therefore run **before** (outside) the guard: add it with
//! `Router::layer` and the guard per route.
//!
//! # Answers
//!
//! Allowed requests reach the handler unchanged. A denial answers per
//! [`AuthzError::http_status`]: **401** for an anonymous principal, **403** otherwise, **500**
//! when the policy cannot be evaluated. The body is Problem Details (RFC 9457,
//! `application/problem+json`) with `type`, `title`, `status`, `detail` and the guard's `policy`
//! name; the denial reason is only included with [`Guard::expose_reason`]. The [`AuthzError`] is
//! also set as a response extension for logging middleware.
//!
//! ```
//! use axum::routing::get;
//! use id_effect_authz::guard::{AuthorizeExt, Guard};
//! use id_effect_authz::require_role;
//!
//! let app: axum::Router = axum::Router::new().route(
//!   "/ledger",
//!   get(|| async { "entries" }).authorize(Guard::new("ledger.read", require_role("viewer"))),
//! );
//! # let _ = app;
//! ```

use std::convert::Infallible;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use axum::http::request::Parts;
use axum::http::{HeaderValue, Request, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::MethodRouter;
use id_effect::{Cause, Exit, fail};
use id_effect_axum::route::{Endpoint, RouteInfo, RouteRegistry};
use id_effect_axum::{EffectExecutor, RequestCaps};
use serde_json::json;
use tower_layer::Layer;
use tower_service::Service;

use crate::audit::{AuthzEvents, audited};
use crate::policy::{AuthzError, Decision, Policy, PolicyEffect};
use crate::principal::CurrentPrincipal;
use crate::registry::Policies;

type Check = dyn Fn(&CurrentPrincipal, &Parts) -> PolicyEffect + Send + Sync;

/// A route guard: a named policy evaluated for the request's principal before the handler.
///
/// It is a Tower [`Layer`]; attach it with [`AuthorizeExt::authorize`] or any `.layer(..)` /
/// `.route_layer(..)`.
#[derive(Clone)]
pub struct Guard {
  name: Arc<str>,
  check: Arc<Check>,
  events: Option<AuthzEvents>,
  expose_reason: bool,
}

impl Guard {
  /// A guard named `name` evaluating `policy` (a rule over the principal only).
  pub fn new(name: impl Into<String>, policy: impl Policy<()>) -> Self {
    Self::from_check(name, move |principal, _| policy.evaluate(principal, &()))
  }

  /// A guard named `name` evaluating `policy` against the request head (method, URI, headers,
  /// extensions) — e.g. a tenant taken from the path.
  pub fn request(name: impl Into<String>, policy: impl Policy<Parts>) -> Self {
    Self::from_check(name, move |principal, parts| {
      policy.evaluate(principal, parts)
    })
  }

  /// A guard evaluating the policy `name` of `policies` (defined over `()`). An unknown name or
  /// a policy defined for another resource type answers 500 when a request arrives.
  pub fn named(policies: &Policies, name: impl Into<String>) -> Self {
    let name = name.into();
    let policies = policies.clone();
    let lookup = name.clone();
    Self::from_check(name, move |principal, _| {
      policies.evaluate(&lookup, principal, &())
    })
  }

  fn from_check(
    name: impl Into<String>,
    check: impl Fn(&CurrentPrincipal, &Parts) -> PolicyEffect + Send + Sync + 'static,
  ) -> Self {
    Self {
      name: Arc::from(name.into()),
      check: Arc::new(check),
      events: None,
      expose_reason: false,
    }
  }

  /// Records every decision of this guard to `events` (the resource is `METHOD /path`).
  #[must_use]
  pub fn events(mut self, events: AuthzEvents) -> Self {
    self.events = Some(events);
    self
  }

  /// Whether a 403 body's `detail` carries the denial reason (default `false`: reasons can
  /// reveal how access is decided).
  #[must_use]
  pub fn expose_reason(mut self, expose: bool) -> Self {
    self.expose_reason = expose;
    self
  }

  /// The guard's policy name.
  pub fn name(&self) -> &str {
    &self.name
  }

  /// Decides for the request head `parts`: `Ok(())` when allowed, otherwise the error to answer
  /// with.
  pub async fn decide(&self, parts: &Parts) -> Result<(), AuthzError> {
    let principal = principal_of(parts);
    let mut effect = (self.check)(&principal, parts);
    if let Some(events) = &self.events {
      let resource = format!("{} {}", parts.method, parts.uri.path());
      effect = audited(effect, events, &principal, &self.name, &resource);
    }
    let name = Arc::clone(&self.name);
    let effect = effect.flat_map(move |decision| match decision {
      Decision::Deny(denial) => fail(AuthzError::Denied(denial.attributed_to(&name))),
      Decision::Allow => id_effect::succeed(()),
    });
    match EffectExecutor::global().run_effect(effect).await {
      Exit::Success(()) => Ok(()),
      Exit::Failure(cause) => Err(first_error(cause, &principal)),
    }
  }

  /// The response for `error` raised by this guard.
  pub fn reject(&self, error: AuthzError) -> Response {
    problem(error, Some(&self.name), self.expose_reason)
  }
}

impl fmt::Debug for Guard {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("Guard")
      .field("name", &self.name)
      .field("events", &self.events.is_some())
      .field("expose_reason", &self.expose_reason)
      .finish()
  }
}

/// The principal of a request (see the [module docs](self)): the [`CurrentPrincipal`] extension,
/// else one recorded in [`RequestCaps`], else anonymous.
pub fn principal_of(parts: &Parts) -> CurrentPrincipal {
  if let Some(principal) = parts.extensions.get::<CurrentPrincipal>() {
    return principal.clone();
  }
  parts
    .extensions
    .get::<RequestCaps>()
    .and_then(RequestCaps::get::<CurrentPrincipal>)
    .map_or_else(CurrentPrincipal::anonymous, |p| CurrentPrincipal::clone(&p))
}

/// The typed failure in `cause` mapped to what the guard answers: a denial of an anonymous
/// principal is `Unauthenticated`; a defect or interrupt is an `Evaluation` error.
fn first_error(cause: Cause<AuthzError>, principal: &CurrentPrincipal) -> AuthzError {
  match cause {
    Cause::Fail(AuthzError::Denied(_)) if !principal.is_authenticated() => {
      AuthzError::Unauthenticated
    }
    Cause::Fail(error) => error,
    other => AuthzError::Evaluation(format!("{other:?}")),
  }
}

fn problem(error: AuthzError, policy: Option<&str>, expose_reason: bool) -> Response {
  let status =
    StatusCode::from_u16(error.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
  let detail = match &error {
    AuthzError::Unauthenticated => "authentication required".to_owned(),
    AuthzError::Denied(denial) if expose_reason => denial.reason().to_owned(),
    AuthzError::Denied(_) => "access denied".to_owned(),
    _ => "authorization could not be evaluated".to_owned(),
  };
  let policy = policy.or(match &error {
    AuthzError::Denied(denial) => denial.policy(),
    _ => None,
  });
  let mut body = json!({
    "type": "about:blank",
    "title": status.canonical_reason().unwrap_or("Error"),
    "status": status.as_u16(),
    "detail": detail,
  });
  if let Some(policy) = policy {
    body["policy"] = json!(policy);
  }
  let mut response = (status, body.to_string()).into_response();
  response.headers_mut().insert(
    header::CONTENT_TYPE,
    HeaderValue::from_static("application/problem+json"),
  );
  response.extensions_mut().insert(error);
  response
}

/// Answers per [`AuthzError::http_status`] with a Problem Details body (the denial reason is not
/// included), so a handler can fail with `AuthzError` directly.
impl IntoResponse for AuthzError {
  fn into_response(self) -> Response {
    problem(self, None, false)
  }
}

impl<S> Layer<S> for Guard {
  type Service = GuardService<S>;

  fn layer(&self, inner: S) -> Self::Service {
    GuardService {
      guard: self.clone(),
      inner,
    }
  }
}

/// The service a [`Guard`] wraps a route in.
#[derive(Clone, Debug)]
pub struct GuardService<S> {
  guard: Guard,
  inner: S,
}

impl<S, B> Service<Request<B>> for GuardService<S>
where
  S: Service<Request<B>, Response = Response, Error = Infallible> + Clone + Send + 'static,
  S::Future: Send + 'static,
  B: Send + 'static,
{
  type Response = Response;
  type Error = Infallible;
  type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;

  fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
    self.inner.poll_ready(cx)
  }

  fn call(&mut self, req: Request<B>) -> Self::Future {
    let ready = self.inner.clone();
    let mut inner = std::mem::replace(&mut self.inner, ready);
    let guard = self.guard.clone();
    Box::pin(async move {
      let (parts, body) = req.into_parts();
      match guard.decide(&parts).await {
        Ok(()) => inner.call(Request::from_parts(parts, body)).await,
        Err(error) => Ok(guard.reject(error)),
      }
    })
  }
}

/// `.authorize(guard)` on routes: an Axum [`MethodRouter`] or a typed
/// [`Endpoint`].
pub trait AuthorizeExt: Sized {
  /// The guarded route.
  type Output;

  /// Evaluate `guard` before this route's handler.
  fn authorize(self, guard: Guard) -> Self::Output;
}

impl<S: Clone + Send + Sync + 'static> AuthorizeExt for MethodRouter<S> {
  type Output = MethodRouter<S>;

  fn authorize(self, guard: Guard) -> MethodRouter<S> {
    self.layer(guard)
  }
}

impl<S: Clone + Send + Sync + 'static> AuthorizeExt for Endpoint<S> {
  type Output = AuthorizedEndpoint<S>;

  fn authorize(self, guard: Guard) -> AuthorizedEndpoint<S> {
    let (info, method_router) = self.into_parts();
    AuthorizedEndpoint {
      info,
      method_router,
    }
    .authorize(guard)
  }
}

impl<S: Clone + Send + Sync + 'static> AuthorizeExt for AuthorizedEndpoint<S> {
  type Output = AuthorizedEndpoint<S>;

  fn authorize(mut self, guard: Guard) -> AuthorizedEndpoint<S> {
    self.info.policies.push(guard.name().to_owned());
    self.method_router = self.method_router.layer(guard);
    self
  }
}

/// A typed endpoint behind one or more guards: its [`RouteInfo`] (whose
/// [`policies`](RouteInfo::policies) lists the guard names) and the guarded method router.
///
/// Add it to an [`id_effect_axum::route::Router`] through [`AuthorizedEndpoint::into_endpoint`]
/// (or `Endpoint::from`), mount it with [`AuthorizedEndpoint::mount`] (both keep the
/// [`RouteRegistry`] complete) or take [`AuthorizedEndpoint::into_parts`].
#[must_use = "mount the endpoint on a router"]
pub struct AuthorizedEndpoint<S = ()> {
  info: RouteInfo,
  method_router: MethodRouter<S>,
}

impl<S: Clone + Send + Sync + 'static> AuthorizedEndpoint<S> {
  /// What the route declares.
  pub fn info(&self) -> &RouteInfo {
    &self.info
  }

  /// The guards' policy names, outermost last ([`RouteInfo::policies`]).
  pub fn policies(&self) -> &[String] {
    &self.info.policies
  }

  /// The guarded route as a typed [`Endpoint`], for [`id_effect_axum::route::Router::route`].
  pub fn into_endpoint(self) -> Endpoint<S> {
    Endpoint::from_parts(self.info, self.method_router)
  }

  /// The declaration and the guarded method router.
  pub fn into_parts(self) -> (RouteInfo, MethodRouter<S>) {
    (self.info, self.method_router)
  }

  /// Route the endpoint on `router` at its path and record its [`RouteInfo`] in `registry`
  /// (from [`id_effect_axum::route::Router::into_parts`]).
  ///
  /// # Panics
  ///
  /// Like [`axum::Router::route`]: when the method is already routed at that path.
  pub fn mount(self, router: axum::Router<S>, registry: &mut RouteRegistry) -> axum::Router<S> {
    let router = router.route(&self.info.path, self.method_router);
    registry.register(self.info);
    router
  }
}

impl<S: Clone + Send + Sync + 'static> From<AuthorizedEndpoint<S>> for Endpoint<S> {
  fn from(endpoint: AuthorizedEndpoint<S>) -> Self {
    endpoint.into_endpoint()
  }
}

impl<S> fmt::Debug for AuthorizedEndpoint<S> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("AuthorizedEndpoint")
      .field("method", &self.info.method)
      .field("path", &self.info.path)
      .field("policies", &self.info.policies)
      .finish()
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::audit::{MemorySink, Outcome};
  use crate::policy::{Denial, allow_all, deny_all, from_effect, require_role};
  use crate::principal::BasicPrincipal;

  fn head(principal: Option<CurrentPrincipal>) -> Parts {
    let mut req = Request::get("/books/7").body(()).expect("request");
    if let Some(p) = principal {
      req.extensions_mut().insert(p);
    }
    req.into_parts().0
  }

  fn alice() -> CurrentPrincipal {
    CurrentPrincipal::new(BasicPrincipal::new("alice").with_role("editor"))
  }

  #[test]
  fn principal_comes_from_the_extension_then_request_caps() {
    assert_eq!(principal_of(&head(Some(alice()))).id(), "alice");
    assert!(!principal_of(&head(None)).is_authenticated());
    let mut parts = head(None);
    let mut caps = RequestCaps::new();
    caps.insert(alice());
    parts.extensions.insert(caps);
    assert_eq!(principal_of(&parts).id(), "alice");
  }

  #[tokio::test]
  async fn decisions_map_to_errors() {
    let editor = Guard::new("edit", require_role("editor"));
    assert_eq!(editor.decide(&head(Some(alice()))).await, Ok(()));
    assert_eq!(
      editor.decide(&head(None)).await,
      Err(AuthzError::Unauthenticated)
    );
    let closed = Guard::new("closed", deny_all("maintenance"));
    assert_eq!(
      closed.decide(&head(Some(alice()))).await,
      Err(AuthzError::Denied(
        Denial::new("maintenance").attributed_to("closed")
      ))
    );
    let broken = Guard::new(
      "broken",
      from_effect(|_: &CurrentPrincipal, _: &()| -> PolicyEffect { id_effect::die("boom") }),
    );
    assert!(matches!(
      broken.decide(&head(Some(alice()))).await,
      Err(AuthzError::Evaluation(_))
    ));
    let unknown = Guard::named(&Policies::default(), "nope");
    assert_eq!(
      unknown.decide(&head(Some(alice()))).await,
      Err(AuthzError::UnknownPolicy("nope".into()))
    );
  }

  #[tokio::test]
  async fn request_guards_see_the_head_and_record_events() {
    let sink = MemorySink::new();
    let books = Guard::request(
      "books",
      crate::policy::predicate("not a book", |_, parts: &Parts| {
        parts.uri.path().starts_with("/books/")
      }),
    )
    .events(AuthzEvents::new(sink.clone()));
    assert_eq!(books.decide(&head(Some(alice()))).await, Ok(()));
    let events = sink.events();
    assert_eq!(events[0].resource, "GET /books/7");
    assert_eq!(events[0].outcome, Outcome::Allow);
    assert_eq!(events[0].policy, "books");
  }

  #[test]
  fn guarded_endpoints_record_their_policies_in_the_route_info() {
    use id_effect_axum::route::{Input, Route, Router};
    let endpoint = Route::get("/books")
      .handler(|_: &mut (), _: Input| id_effect::succeed::<_, Infallible, ()>("books"))
      .authorize(Guard::new("books.read", allow_all()))
      .authorize(Guard::new("staff", allow_all()));
    assert_eq!(endpoint.info().policies, ["books.read", "staff"]);
    let router = Router::new().route(endpoint.into());
    let info = router.routes().next().expect("registered");
    assert_eq!(info.policies, ["books.read", "staff"]);
    let plain = Route::get("/open")
      .handler(|_: &mut (), _: Input| id_effect::succeed::<_, Infallible, ()>("open"));
    assert!(plain.info().policies.is_empty());
  }

  #[test]
  fn problem_bodies_and_debug() {
    let guard = Guard::new("p", allow_all()).expose_reason(true);
    let res = guard.reject(AuthzError::Denied(Denial::new("why")));
    assert_eq!(res.status(), StatusCode::FORBIDDEN);
    assert_eq!(
      res.headers()[header::CONTENT_TYPE],
      "application/problem+json"
    );
    assert!(res.extensions().get::<AuthzError>().is_some());
    let res = AuthzError::Evaluation("db".into()).into_response();
    assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
    let dbg = format!("{guard:?}");
    assert!(dbg.contains("expose_reason: true"), "{dbg}");
    assert_eq!(guard.name(), "p");
  }
}