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