glacier-web 0.1.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));
}

/// 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()
            }
        }))
    }
}