summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 670a397a2bf9ad63fc4ef4781ccd69eb652074fb (plain)
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
//! Actix-web extractor which validates OAuth2 tokens through an
//! [RFC 7662](https://datatracker.ietf.org/doc/html/rfc7662) token
//! introspection endpoint.
//!
//! To protect a resource, you add the `RequireAuthorization` extractor.
//! This extractor must be configured with a token introspection url
//! before it can be used.
//!
//! The extractor takes an implementation of the
//! `AuthorizationRequirements` trait, which is used to analyze the
//! introspection response to determine if the request is authorized.
//!
//! # Example
//! ```
//! # use actix_web::{ get, HttpResponse, HttpServer, Responder };
//! # use actix_middleware_rfc7662::{AnyScope, RequireAuthorization, RequireAuthorizationConfig};
//!
//! #[get("/protected/api")]
//! async fn handle_read(_auth: RequireAuthorization<AnyScope>) -> impl Responder {
//!     HttpResponse::Ok().body("Success!\n")
//! }
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//!     let oauth_config = RequireAuthorizationConfig::new(
//!         "client_id".to_string(),
//!         Some("client_secret".to_string()),
//!         "https://example.com/oauth/authorize".parse().expect("invalid url"),
//!         "https://example.com/oauth/introspect".parse().expect("invalid url"),
//!     );
//!
//!     HttpServer::new(move || {
//!         actix_web::App::new()
//!             .app_data(oauth_config.clone())
//!             .service(handle_read)
//!             .service(handle_write)
//!     })
//!     .bind("127.0.0.1:8182".to_string())?
//!     .run()
//!     .await
//! }
//! ```

use actix_web::{dev, FromRequest, HttpRequest};
use futures_util::future::LocalBoxFuture;
use oauth2::basic::{BasicErrorResponseType, BasicTokenType};
use oauth2::url::Url;
use oauth2::*;
use std::future::ready;
use std::marker::PhantomData;
use std::sync::Arc;

mod error;
use error::Error;

const BEARER_TOKEN_PREFIX: &str = "Bearer ";

pub type IntrospectionResponse =
    StandardTokenIntrospectionResponse<EmptyExtraTokenFields, BasicTokenType>;

pub trait AuthorizationRequirements {
    fn authorized(introspection: &IntrospectionResponse) -> Result<bool, Error>;
}

pub trait RequireScope {
    fn scope() -> &'static str;
}

impl<T> AuthorizationRequirements for T
where
    T: RequireScope,
{
    fn authorized(introspection: &IntrospectionResponse) -> Result<bool, Error> {
        Ok(introspection
            .scopes()
            .map(|s| s.iter().find(|s| s.as_ref() == T::scope()).is_some())
            .unwrap_or(false))
    }
}

pub struct AnyScope;

impl AuthorizationRequirements for AnyScope {
    fn authorized(_: &IntrospectionResponse) -> Result<bool, Error> {
        Ok(true)
    }
}

pub struct RequireAuthorization<T>
where
    T: AuthorizationRequirements,
{
    introspection: IntrospectionResponse,
    _auth_marker: PhantomData<T>,
}

impl<T> RequireAuthorization<T>
where
    T: AuthorizationRequirements,
{
    pub fn introspection(&self) -> &IntrospectionResponse {
        &self.introspection
    }
}

impl<T> FromRequest for RequireAuthorization<T>
where
    T: AuthorizationRequirements + 'static,
{
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;

    fn from_request(req: &actix_web::HttpRequest, _: &mut dev::Payload) -> Self::Future {
        let verifier = if let Some(verifier) = req.app_data::<RequireAuthorizationConfig>() {
            verifier.clone()
        } else {
            return Box::pin(ready(Err(Error::ConfigurationError)));
        };

        let my_req = req.clone();

        Box::pin(async move {
            verifier
                .verify_request(my_req)
                .await
                .and_then(|introspection| {
                    if T::authorized(&introspection)? {
                        Ok(RequireAuthorization {
                            introspection,
                            _auth_marker: PhantomData::default(),
                        })
                    } else {
                        Err(Error::AccessDenied)
                    }
                })
        })
    }
}

#[derive(Clone)]
struct RequireAuthorizationConfigInner {
    client: oauth2::Client<
        StandardErrorResponse<BasicErrorResponseType>,
        StandardTokenResponse<EmptyExtraTokenFields, BasicTokenType>,
        BasicTokenType,
        StandardTokenIntrospectionResponse<EmptyExtraTokenFields, BasicTokenType>,
        StandardRevocableToken,
        StandardErrorResponse<BasicErrorResponseType>,
    >,
}

#[derive(Clone)]
pub struct RequireAuthorizationConfig(Arc<RequireAuthorizationConfigInner>);

impl RequireAuthorizationConfig {
    pub fn new(
        client_id: String,
        client_secret: Option<String>,
        auth_url: Url,
        introspection_url: Url,
    ) -> Self {
        let client = oauth2::Client::new(
            ClientId::new(client_id),
            client_secret.map(|s| ClientSecret::new(s)),
            AuthUrl::from_url(auth_url),
            None,
        )
        .set_introspection_uri(IntrospectionUrl::from_url(introspection_url));
        RequireAuthorizationConfig(Arc::new(RequireAuthorizationConfigInner { client }))
    }

    async fn verify_request(&self, req: HttpRequest) -> Result<IntrospectionResponse, Error> {
        let access_token = req
            .headers()
            .get("Authorization")
            .and_then(|value| value.to_str().ok())
            .filter(|value| value.starts_with(BEARER_TOKEN_PREFIX))
            .map(|value| AccessToken::new(value.split_at(BEARER_TOKEN_PREFIX.len()).1.to_string()))
            .ok_or(Error::MissingToken)?;

        self.0
            .client
            .introspect(&access_token)
            .map_err(|e| {
                log::error!("OAuth2 client configuration error: {}", e);
                Error::ConfigurationError
            })?
            .request_async(reqwest::async_http_client)
            .await
            .map_err(|e| {
                log::warn!("Error from token introspection service: {}", e);
                Error::IntrospectionServerError
            })
            .and_then(|resp| {
                if resp.active() {
                    Ok(resp)
                } else {
                    Err(Error::InvalidToken)
                }
            })
    }
}