1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3
4mod middleware;
7
8use async_trait::async_trait;
9use axum::{Json, response::IntoResponse};
10use http::{
11 HeaderMap, StatusCode,
12 header::{AUTHORIZATION, AsHeaderName},
13};
14use serde::Serialize;
15use std::sync::Arc;
16
17pub use middleware::{GuardLayer, GuardService, guard_layer};
18
19#[async_trait]
21pub trait Guard<S>: Send + Sync + 'static {
22 async fn check(&self, ctx: GuardContext<S>) -> Result<(), GuardError>;
24}
25
26#[async_trait]
27impl<S, G> Guard<S> for Arc<G>
28where
29 S: Send + Sync + 'static,
30 G: Guard<S>,
31{
32 async fn check(&self, ctx: GuardContext<S>) -> Result<(), GuardError> {
33 self.as_ref().check(ctx).await
34 }
35}
36
37pub trait GuardExt<S>: Guard<S> + Sized {
39 fn and<G>(self, other: G) -> AndGuard<Self, G>
41 where
42 G: Guard<S>,
43 {
44 AndGuard {
45 first: self,
46 second: other,
47 }
48 }
49
50 fn or<G>(self, other: G) -> OrGuard<Self, G>
52 where
53 G: Guard<S>,
54 {
55 OrGuard {
56 first: self,
57 second: other,
58 }
59 }
60}
61
62impl<S, G> GuardExt<S> for G where G: Guard<S> + Sized {}
63
64#[derive(Clone, Debug)]
66pub struct AndGuard<A, B> {
67 first: A,
68 second: B,
69}
70
71#[async_trait]
72impl<S, A, B> Guard<S> for AndGuard<A, B>
73where
74 S: Clone + Send + Sync + 'static,
75 A: Guard<S>,
76 B: Guard<S>,
77{
78 async fn check(&self, ctx: GuardContext<S>) -> Result<(), GuardError> {
79 self.first.check(ctx.clone()).await?;
80 self.second.check(ctx).await
81 }
82}
83
84#[derive(Clone, Debug)]
86pub struct OrGuard<A, B> {
87 first: A,
88 second: B,
89}
90
91#[async_trait]
92impl<S, A, B> Guard<S> for OrGuard<A, B>
93where
94 S: Clone + Send + Sync + 'static,
95 A: Guard<S>,
96 B: Guard<S>,
97{
98 async fn check(&self, ctx: GuardContext<S>) -> Result<(), GuardError> {
99 let first_error = match self.first.check(ctx.clone()).await {
100 Ok(()) => return Ok(()),
101 Err(error) => error,
102 };
103 match self.second.check(ctx).await {
104 Ok(()) => Ok(()),
105 Err(_) => Err(first_error),
106 }
107 }
108}
109
110#[derive(Clone, Debug)]
112pub struct GuardContext<S> {
113 state: S,
114 route_label: Arc<str>,
115 headers: HeaderMap,
116}
117
118impl<S> GuardContext<S> {
119 pub fn new(state: S, route_label: impl Into<String>) -> Self {
121 Self {
122 state,
123 route_label: Arc::from(route_label.into()),
124 headers: HeaderMap::new(),
125 }
126 }
127
128 #[doc(hidden)]
134 pub fn from_shared_route_label(state: S, route_label: Arc<str>) -> Self {
135 Self {
136 state,
137 route_label,
138 headers: HeaderMap::new(),
139 }
140 }
141
142 pub fn state(&self) -> &S {
144 &self.state
145 }
146
147 pub fn route_label(&self) -> &str {
149 &self.route_label
150 }
151
152 pub fn headers(&self) -> &HeaderMap {
154 &self.headers
155 }
156
157 pub fn header_str<K>(&self, name: K) -> Result<Option<&str>>
163 where
164 K: AsHeaderName,
165 {
166 self.headers
167 .get(name)
168 .map(|value| {
169 value
170 .to_str()
171 .map_err(|_| GuardError::unauthorized("header value is not valid UTF-8"))
172 })
173 .transpose()
174 }
175
176 pub fn bearer_token(&self) -> Result<Option<&str>> {
183 let Some(header) = self.header_str(AUTHORIZATION)? else {
184 return Ok(None);
185 };
186 let Some((scheme, token)) = header.split_once(' ') else {
187 return Err(GuardError::unauthorized(
188 "authorization header must use `Bearer <token>`",
189 ));
190 };
191 if !scheme.eq_ignore_ascii_case("Bearer")
192 || token.is_empty()
193 || token.chars().any(char::is_whitespace)
194 {
195 return Err(GuardError::unauthorized(
196 "authorization header must use `Bearer <token>`",
197 ));
198 }
199 Ok(Some(token))
200 }
201
202 pub fn api_key<K>(&self, header_name: K) -> Result<Option<&str>>
208 where
209 K: AsHeaderName,
210 {
211 self.header_str(header_name)
212 }
213
214 pub fn with_headers(mut self, headers: HeaderMap) -> Self {
216 self.headers = headers;
217 self
218 }
219
220 pub fn into_state(self) -> S {
222 self.state
223 }
224}
225
226pub type Result<T, E = GuardError> = std::result::Result<T, E>;
228
229#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
231#[error("{reason}")]
232pub struct GuardError {
233 status_code: StatusCode,
234 reason: String,
235}
236
237impl GuardError {
238 pub fn new(status_code: StatusCode, reason: impl Into<String>) -> Self {
240 Self {
241 status_code,
242 reason: reason.into(),
243 }
244 }
245
246 pub fn unauthorized(reason: impl Into<String>) -> Self {
248 Self::new(StatusCode::UNAUTHORIZED, reason)
249 }
250
251 pub fn forbidden(reason: impl Into<String>) -> Self {
253 Self::new(StatusCode::FORBIDDEN, reason)
254 }
255
256 pub fn status_code(&self) -> StatusCode {
258 self.status_code
259 }
260
261 pub fn reason(&self) -> &str {
263 &self.reason
264 }
265
266 pub fn code(&self) -> &'static str {
268 match self.status_code {
269 StatusCode::UNAUTHORIZED => "unauthorized",
270 StatusCode::FORBIDDEN => "forbidden",
271 _ => "authorization_failed",
272 }
273 }
274}
275
276impl IntoResponse for GuardError {
277 fn into_response(self) -> axum::response::Response {
278 let status = self.status_code;
279 let body = Json(GuardErrorBody {
280 error: GuardErrorDetails {
281 code: self.code(),
282 message: self.reason,
283 },
284 });
285 (status, body).into_response()
286 }
287}
288
289#[derive(Debug, Serialize)]
290struct GuardErrorBody {
291 error: GuardErrorDetails,
292}
293
294#[derive(Debug, Serialize)]
295struct GuardErrorDetails {
296 code: &'static str,
297 message: String,
298}