Skip to main content

glacier/
authorization.rs

1//! Checking that every action authorized, as Pundit's
2//! `verify_authorized`: put [`VerifyAuthorized`] on a pipeline, and an
3//! action there that answers without calling `authorize` (or
4//! [`skip_authorization`], for public actions) is a bug the response
5//! reports, instead of an endpoint silently open to everyone.
6//!
7//! ```ignore
8//! pipeline authorized = Pipeline::api().with(VerifyAuthorized);
9//! ```
10//!
11//! Rules are the app's own functions, by convention a policy per model
12//! (`glacier generate policy Post`):
13//! `authorize PostPolicy.update(user, post)!`.
14
15use std::cell::Cell;
16
17use crate::config::Env;
18use crate::context::Context;
19use crate::error::Error;
20use crate::handler::BoxFuture;
21use crate::middleware::{Middleware, Next};
22use crate::response::{IntoResponse, Response};
23
24tokio::task_local! {
25    static AUTHORIZED: Cell<bool>;
26}
27
28/// Records that the request's action authorized (`authorize` calls it).
29pub(crate) fn mark() {
30    let _ = AUTHORIZED.try_with(|authorized| authorized.set(true));
31}
32
33/// What a policy rule decides: allowed, or denied with the status and
34/// message the response gives. A rule can return a `bool` instead (`false`
35/// is `403 Forbidden`); one that returns a `Decision` says more:
36///
37/// ```glacier
38/// def show(user: &User, note: &Note) -> Decision do
39///   if note.user_id == user.id do
40///     allow
41///   else
42///     # As if there were no such note, so its id gives nothing away.
43///     deny :not_found
44///   end
45/// end
46/// ```
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum Decision {
49    Allow,
50    Deny {
51        status: http::StatusCode,
52        message: Option<String>,
53    },
54}
55
56impl Decision {
57    /// Denied with `status` (`"not_found"`, or a `StatusCode`) and, if
58    /// given, `message` for the response.
59    #[track_caller]
60    pub fn deny(status: impl crate::response::IntoStatus, message: Option<&str>) -> Self {
61        Self::Deny {
62            status: status.into_status(),
63            message: message.map(str::to_owned),
64        }
65    }
66
67    /// Whether it's allowed, for a page that shows a link only to those who
68    /// may follow it.
69    pub fn is_allowed(&self) -> bool {
70        matches!(self, Self::Allow)
71    }
72}
73
74impl From<bool> for Decision {
75    fn from(allowed: bool) -> Self {
76        if allowed {
77            Self::Allow
78        } else {
79            Self::Deny {
80                status: http::StatusCode::FORBIDDEN,
81                message: None,
82            }
83        }
84    }
85}
86
87/// Marks an action as public, so [`VerifyAuthorized`] lets it answer
88/// without an `authorize`.
89pub fn skip_authorization() {
90    mark();
91}
92
93/// Fails a successful response from an action that never authorized: a
94/// `500` in development and test; in production the response goes out.
95/// Either way the miss is logged as an error, naming the route.
96pub struct VerifyAuthorized;
97
98impl Middleware for VerifyAuthorized {
99    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
100        let route = format!("{} {}", ctx.method(), ctx.path());
101        Box::pin(AUTHORIZED.scope(Cell::new(false), async move {
102            let response = next.run(ctx).await;
103            let authorized = AUTHORIZED.with(Cell::get);
104            if authorized || response.status().is_client_error() || response.status().is_server_error() {
105                return response;
106            }
107            let message = format!(
108                "{route} answered without authorizing: call `authorize` (or `skip_authorization` for a public action)"
109            );
110            tracing::error!(target: "glacier", "{message}");
111            if Env::current().is_production() {
112                response
113            } else {
114                Error::internal(message).into_response()
115            }
116        }))
117    }
118}