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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use axum::http::Request;
use axum::response::IntoResponse;
use axum::{body::Body, response::Response};
use futures_core::ready;
use futures_util::future::BoxFuture;
use headers::authorization::Bearer;
use headers::{Authorization, HeaderMapExt};
use http::StatusCode;
use pin_project::pin_project;
use serde::de::DeserializeOwned;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tower_layer::Layer;
use tower_service::Service;
use crate::authorizer::{Authorizer, FnClaimsChecker};
pub struct JwtAuthorizer<C>
where
C: Clone + DeserializeOwned,
{
url: Option<&'static str>,
claims_checker: Option<FnClaimsChecker<C>>,
}
impl<C> JwtAuthorizer<C>
where
C: Clone + DeserializeOwned + Send + Sync,
{
pub fn new() -> Self {
JwtAuthorizer {
url: None,
claims_checker: None,
}
}
pub fn from_jwks_url(mut self, url: &'static str) -> JwtAuthorizer<C> {
self.url = Some(url);
self
}
pub fn from_rsa_pem(mut self, path: &'static str) -> JwtAuthorizer<C> {
self
}
pub fn from_ec_der(mut self, path: &'static str) -> JwtAuthorizer<C> {
self
}
pub fn from_ed_der(mut self, path: &'static str) -> JwtAuthorizer<C> {
self
}
pub fn from_secret(mut self, path: &'static str) -> JwtAuthorizer<C> {
self
}
pub fn with_check(mut self, checker_fn: fn(&C) -> bool) -> JwtAuthorizer<C> {
self.claims_checker = Some(FnClaimsChecker { checker_fn });
self
}
pub fn layer(&self) -> AsyncAuthorizationLayer<C> {
let auth = Arc::new(Authorizer::from_jwks_url(self.url.unwrap(), self.claims_checker.clone()).unwrap());
AsyncAuthorizationLayer::new(auth)
}
}
pub trait AsyncAuthorizer<B> {
type RequestBody;
type ResponseBody;
type Future: Future<Output = Result<Request<Self::RequestBody>, Response<Self::ResponseBody>>>;
fn authorize(&self, request: Request<B>) -> Self::Future;
}
impl<B, S, C> AsyncAuthorizer<B> for AsyncAuthorizationService<S, C>
where
B: Send + Sync + 'static,
C: Clone + DeserializeOwned + Send + Sync + 'static,
{
type RequestBody = B;
type ResponseBody = Body;
type Future = BoxFuture<'static, Result<Request<B>, Response<Self::ResponseBody>>>;
fn authorize(&self, mut request: Request<B>) -> Self::Future {
let authorizer = self.auth.clone();
let h = request.headers();
let bearer: Authorization<Bearer> = h.typed_get().unwrap();
Box::pin(async move {
if let Ok(token_data) = authorizer.check_auth(bearer.token()).await {
request.extensions_mut().insert(token_data);
Ok(request)
} else {
let unauthorized_response = Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::empty())
.unwrap();
Err(unauthorized_response)
}
})
}
}
#[derive(Clone)]
pub struct AsyncAuthorizationLayer<C>
where
C: Clone + DeserializeOwned + Send,
{
auth: Arc<Authorizer<C>>,
}
impl<C> AsyncAuthorizationLayer<C>
where
C: Clone + DeserializeOwned + Send,
{
pub fn new(auth: Arc<Authorizer<C>>) -> AsyncAuthorizationLayer<C> {
Self { auth }
}
}
impl<S, C> Layer<S> for AsyncAuthorizationLayer<C>
where
C: Clone + DeserializeOwned + Send + Sync,
{
type Service = AsyncAuthorizationService<S, C>;
fn layer(&self, inner: S) -> Self::Service {
AsyncAuthorizationService::new(inner, self.auth.clone())
}
}
#[derive(Clone)]
pub struct AsyncAuthorizationService<S, C>
where
C: Clone + DeserializeOwned + Send + Sync,
{
pub inner: S,
pub auth: Arc<Authorizer<C>>,
}
impl<S, C> AsyncAuthorizationService<S, C>
where
C: Clone + DeserializeOwned + Send + Sync,
{
pub fn get_ref(&self) -> &S {
&self.inner
}
pub fn get_mut(&mut self) -> &mut S {
&mut self.inner
}
pub fn into_inner(self) -> S {
self.inner
}
}
impl<S, C> AsyncAuthorizationService<S, C>
where
C: Clone + DeserializeOwned + Send + Sync,
{
pub fn new(inner: S, auth: Arc<Authorizer<C>>) -> AsyncAuthorizationService<S, C> {
Self { inner, auth }
}
}
impl<ReqBody, S, C> Service<Request<ReqBody>> for AsyncAuthorizationService<S, C>
where
ReqBody: Send + Sync + 'static,
S: Service<Request<ReqBody>, Response = Response> + Clone,
C: Clone + DeserializeOwned + Send + Sync + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = ResponseFuture<S, ReqBody, C>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
let inner = self.inner.clone();
let auth_fut = self.authorize(req);
ResponseFuture {
state: State::Authorize { auth_fut },
service: inner,
}
}
}
#[pin_project]
pub struct ResponseFuture<S, ReqBody, C>
where
S: Service<Request<ReqBody>, Response = Response>,
ReqBody: Send + Sync + 'static,
C: Clone + DeserializeOwned + Send + Sync + 'static,
{
#[pin]
state: State<<AsyncAuthorizationService<S, C> as AsyncAuthorizer<ReqBody>>::Future, S::Future>,
service: S,
}
#[pin_project(project = StateProj)]
enum State<A, SFut> {
Authorize {
#[pin]
auth_fut: A,
},
Authorized {
#[pin]
svc_fut: SFut,
},
}
impl<S, ReqBody, C> Future for ResponseFuture<S, ReqBody, C>
where
S: Service<Request<ReqBody>, Response = Response>,
ReqBody: Send + Sync + 'static,
C: Clone + DeserializeOwned + Send + Sync,
{
type Output = Result<S::Response, S::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
loop {
match this.state.as_mut().project() {
StateProj::Authorize { auth_fut } => {
let auth = ready!(auth_fut.poll(cx));
match auth {
Ok(req) => {
let svc_fut = this.service.call(req);
this.state.set(State::Authorized { svc_fut })
}
Err(res) => {
tracing::info!("err: {:?}", res);
let r = (StatusCode::FORBIDDEN, format!("Unauthorized : {:?}", res)).into_response();
return Poll::Ready(Ok(r));
}
};
}
StateProj::Authorized { svc_fut } => {
return svc_fut.poll(cx);
}
}
}
}
}