glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Checking that every action authorized, as Pundit's
//! `verify_authorized`: put [`VerifyAuthorized`] on a pipeline, and an
//! action there that answers without calling `authorize` (or
//! [`skip_authorization`], for public actions) is a bug the response
//! reports, instead of an endpoint silently open to everyone.
//!
//! ```ignore
//! pipeline authorized = Pipeline::api().with(VerifyAuthorized);
//! ```
//!
//! Rules are the app's own functions, by convention a policy per model
//! (`glacier generate policy Post`):
//! `authorize PostPolicy.update(user, post)!`.

use std::cell::Cell;

use crate::config::Env;
use crate::context::Context;
use crate::error::Error;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::{IntoResponse, Response};

tokio::task_local! {
    static AUTHORIZED: Cell<bool>;
}

/// Records that the request's action authorized (`authorize` calls it).
pub(crate) fn mark() {
    let _ = AUTHORIZED.try_with(|authorized| authorized.set(true));
}

/// What a policy rule decides: allowed, or denied with the status and
/// message the response gives. A rule can return a `bool` instead (`false`
/// is `403 Forbidden`); one that returns a `Decision` says more:
///
/// ```glacier
/// def show(user: &User, note: &Note) -> Decision do
///   if note.user_id == user.id do
///     allow
///   else
///     # As if there were no such note, so its id gives nothing away.
///     deny :not_found
///   end
/// end
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
    Allow,
    Deny {
        status: http::StatusCode,
        message: Option<String>,
    },
}

impl Decision {
    /// Denied with `status` (`"not_found"`, or a `StatusCode`) and, if
    /// given, `message` for the response.
    #[track_caller]
    pub fn deny(status: impl crate::response::IntoStatus, message: Option<&str>) -> Self {
        Self::Deny {
            status: status.into_status(),
            message: message.map(str::to_owned),
        }
    }

    /// Whether it's allowed, for a page that shows a link only to those who
    /// may follow it.
    pub fn is_allowed(&self) -> bool {
        matches!(self, Self::Allow)
    }
}

impl From<bool> for Decision {
    fn from(allowed: bool) -> Self {
        if allowed {
            Self::Allow
        } else {
            Self::Deny {
                status: http::StatusCode::FORBIDDEN,
                message: None,
            }
        }
    }
}

/// Marks an action as public, so [`VerifyAuthorized`] lets it answer
/// without an `authorize`.
pub fn skip_authorization() {
    mark();
}

/// Fails a successful response from an action that never authorized: a
/// `500` in development and test; in production the response goes out.
/// Either way the miss is logged as an error, naming the route.
pub struct VerifyAuthorized;

impl Middleware for VerifyAuthorized {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        let route = format!("{} {}", ctx.method(), ctx.path());
        Box::pin(AUTHORIZED.scope(Cell::new(false), async move {
            let response = next.run(ctx).await;
            let authorized = AUTHORIZED.with(Cell::get);
            if authorized || response.status().is_client_error() || response.status().is_server_error() {
                return response;
            }
            let message = format!(
                "{route} answered without authorizing: call `authorize` (or `skip_authorization` for a public action)"
            );
            tracing::error!(target: "glacier", "{message}");
            if Env::current().is_production() {
                response
            } else {
                Error::internal(message).into_response()
            }
        }))
    }
}