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