sylvia_iot_auth/routes/oauth2/
middleware.rs

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
use std::{
    borrow::Cow,
    collections::{HashMap, HashSet},
    str,
    sync::Arc,
    task::{Context, Poll},
};

use axum::{
    extract::{FromRequest, Request},
    http::{header, Method, StatusCode},
    response::{IntoResponse, Response},
};
use futures::future::BoxFuture;
use oxide_auth::code_grant::resource::{Error as ResourceError, Request as OxideResourceRequest};
use oxide_auth_async::code_grant;
use tower::{Layer, Service};

use sylvia_iot_corelib::{err::ErrResp, http::parse_header_auth};

use super::endpoint::Endpoint;
use crate::models::{
    client::QueryCond as ClientQueryCond, user::QueryCond as UserQueryCond, Model,
};

pub type RoleScopeType = (Vec<&'static str>, Vec<String>);
type RoleScopeInner = (HashSet<&'static str>, HashSet<String>);

#[derive(Clone)]
pub struct AuthService {
    model: Arc<dyn Model>,
    role_scopes: HashMap<Method, RoleScopeType>,
}

#[derive(Clone)]
pub struct AuthMiddleware<S> {
    endpoint: Endpoint,
    model: Arc<dyn Model>,
    role_scopes: HashMap<Method, RoleScopeInner>,
    service: S,
}

struct ResourceRequest {
    authorization: Option<String>,
}

impl AuthService {
    pub fn new(model: &Arc<dyn Model>, role_scopes: HashMap<Method, RoleScopeType>) -> Self {
        AuthService {
            model: model.clone(),
            role_scopes,
        }
    }
}

impl<S> Layer<S> for AuthService {
    type Service = AuthMiddleware<S>;

    fn layer(&self, inner: S) -> Self::Service {
        let mut role_scopes: HashMap<Method, RoleScopeInner> = HashMap::new();
        for (k, (r, s)) in self.role_scopes.iter() {
            role_scopes.insert(
                k.clone(),
                (
                    r.iter().map(|&r| r).collect(),
                    s.iter().map(|s| s.clone()).collect(),
                ),
            );
        }
        AuthMiddleware {
            endpoint: Endpoint::new(self.model.clone(), Some("")),
            model: self.model.clone(),
            role_scopes,
            service: inner,
        }
    }
}

impl<S> Service<Request> for AuthMiddleware<S>
where
    S: Service<Request, Response = Response> + Clone + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request) -> Self::Future {
        let mut svc = self.service.clone();
        let mut endpoint = self.endpoint.clone();
        let model = self.model.clone();
        let role_scopes = self.role_scopes.clone();

        Box::pin(async move {
            let auth_req = match ResourceRequest::new(&req) {
                Err(e) => return Ok(e.into_response()),
                Ok(req) => match req.token().is_none() {
                    false => req,
                    true => {
                        let e = ErrResp::ErrParam(Some("missing token".to_string()));
                        return Ok(e.into_response());
                    }
                },
            };
            let grant = match code_grant::resource::protect(&mut endpoint, &auth_req).await {
                Err(e) => match e {
                    ResourceError::PrimitiveError => {
                        return Ok(ErrResp::ErrDb(None).into_response());
                    }
                    _ => {
                        return Ok((
                            StatusCode::UNAUTHORIZED,
                            [(header::WWW_AUTHENTICATE, e.www_authenticate())],
                        )
                            .into_response());
                    }
                },
                Ok(grant) => grant,
            };

            let cond = UserQueryCond {
                user_id: Some(grant.owner_id.as_str()),
                account: None,
            };
            let user = match model.user().get(&cond).await {
                Err(e) => {
                    return Ok(ErrResp::ErrDb(Some(e.to_string())).into_response());
                }
                Ok(user) => match user {
                    None => {
                        let e = ErrResp::ErrPerm(Some("user not exist".to_string()));
                        return Ok(e.into_response());
                    }
                    Some(user) => {
                        if let Some((api_roles, api_scopes)) = role_scopes.get(req.method()) {
                            if api_roles.len() > 0 {
                                let roles: HashSet<&str> = user
                                    .roles
                                    .iter()
                                    .filter(|(_, &v)| v)
                                    .map(|(k, _)| k.as_str())
                                    .collect();
                                if api_roles.is_disjoint(&roles) {
                                    let e = ErrResp::ErrPerm(Some("invalid role".to_string()));
                                    return Ok(e.into_response());
                                }
                            }
                            if api_scopes.len() > 0 {
                                let api_scopes: HashSet<&str> =
                                    api_scopes.iter().map(|s| s.as_str()).collect();
                                let scopes: HashSet<&str> = grant.scope.iter().map(|s| s).collect();
                                if api_scopes.is_disjoint(&scopes) {
                                    return Ok(ErrResp::ErrPerm(Some("invalid scope".to_string()))
                                        .into_response());
                                }
                            }
                        }
                        user
                    }
                },
            };
            req.extensions_mut().insert(user);

            let cond = ClientQueryCond {
                client_id: Some(grant.client_id.as_str()),
                ..Default::default()
            };
            let client = match model.client().get(&cond).await {
                Err(e) => {
                    return Ok(ErrResp::ErrDb(Some(e.to_string())).into_response());
                }
                Ok(client) => match client {
                    None => {
                        let e = ErrResp::ErrPerm(Some("client not exist".to_string()));
                        return Ok(e.into_response());
                    }
                    Some(client) => client,
                },
            };
            req.extensions_mut().insert(client);

            let res = svc.call(req).await?;
            Ok(res)
        })
    }
}

impl ResourceRequest {
    fn new(req: &Request) -> Result<Self, ErrResp> {
        match parse_header_auth(req) {
            Err(e) => Err(e),
            Ok(auth) => Ok(ResourceRequest {
                authorization: auth,
            }),
        }
    }
}

impl<S> FromRequest<S> for ResourceRequest
where
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
        match parse_header_auth(&req) {
            Err(e) => Err(e.into_response()),
            Ok(auth) => Ok(ResourceRequest {
                authorization: auth,
            }),
        }
    }
}

impl OxideResourceRequest for ResourceRequest {
    fn valid(&self) -> bool {
        true
    }

    fn token(&self) -> Option<Cow<str>> {
        match self.authorization.as_deref() {
            None => None,
            Some(auth) => Some(Cow::from(auth)),
        }
    }
}