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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
//! Open Policy Agent (openpolicyagent/OPA) verification for Actix applications
//!
//! OPA middleware could be used with application.
//!
//!
//!
extern crate actix_web;
extern crate base64;
extern crate bytes;
extern crate futures;
extern crate http;
extern crate url;

#[cfg(feature = "jwt")]
extern crate jsonwebtoken;

#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;

use base64::decode;
use bytes::Bytes;
use futures::future::Future;
use serde::de::DeserializeOwned;
use serde::Serialize;

use std::iter::FromIterator;
use std::str;
use std::time::Duration;

use actix_web::middleware::{Middleware, Started};
use actix_web::{client, HttpRequest, Result};
use actix_web::{HttpMessage, HttpResponse};
use http::header;

/// `Middleware` for validating access against Open Policy Agent.
///
///
/// ```rust
/// extern crate actix_web;
/// extern crate actix_web_middleware_opa;
/// #[macro_use]
/// extern crate serde_derive;
/// extern crate serde;
///
/// use actix_web::{http, middleware, App, HttpResponse};
/// use actix_web_middleware_opa::*;
///
/// #[derive(Deserialize)]
/// struct PolicyDecision {
///     result: PolicyDecisionResult,
/// }
///
/// #[derive(Deserialize)]
/// struct PolicyDecisionResult {
///     allow: bool,
/// }
///
/// impl OPAResponse for PolicyDecision {
///     fn allowed(&self) -> bool {
///         self.result.allow
///     }
/// }
///
/// type Verifier = PolicyVerifier<HTTPTokenAuthRequest, PolicyDecision>;
///
/// fn main() {
///     let app = App::new()
///         .middleware(Verifier::build("http://localhost:8181/opa/api".to_string()))
///         .resource("/", |r| {
///             r.method(http::Method::GET).f(|_| HttpResponse::Ok());
///         })
///         .finish();
/// }
/// ```
///
static HEADER_USER_AGENT_KEY: &str = "User-Agent";
static HEADER_USER_AGENT_VALUE: &str = "PolicyVerifier middleware";
static MIMETYPE_JSON: &str = "application/json; charset=utf-8";
static RESPONSE_BODY_SIZE: usize = 1024;
static DEFAULT_TIMEOUT_MS: u64 = 100;

pub trait OPARequest<S>
where
    Self: std::marker::Sized,
{
    fn from_http_request(req: &HttpRequest<S>) -> Result<Self, String>;
}

pub trait OPAResponse {
    fn allowed(&self) -> bool;
}

fn get_el_from_split(s: &str, separator: &str, offset: usize) -> Result<String, String> {
    let res: Vec<&str> = s.split(separator).collect();
    if res.len() > (offset) {
        Ok(res[offset].into())
    } else {
        Err("Requested offset is out of range".into())
    }
}

fn get_path_list<S>(req: &HttpRequest<S>) -> Vec<String> {
    Vec::from_iter(
        req.path()
            .split('/')
            .filter(|s| !s.is_empty())
            .map({ |s| s.to_string() }),
    )
}

#[derive(Serialize)]
pub struct HTTPBasicAuthRequest {
    input: HTTPBasicAuthRequestInput,
}

#[derive(Serialize)]
pub struct HTTPBasicAuthRequestInput {
    user: String,
    path: Vec<String>,
    method: String,
}

// XXX This does not verify the password
impl<S> OPARequest<S> for HTTPBasicAuthRequest {
    fn from_http_request(req: &HttpRequest<S>) -> Result<Self, String> {
        let headermap = req.headers();
        if headermap.contains_key(header::AUTHORIZATION) {
            match headermap[header::AUTHORIZATION].to_str() {
                Ok(s) => {
                    // Header value has the form "Authorization KEY"
                    match decode(&get_el_from_split(s, " ", 1)?) {
                        Ok(s) => {
                            // Decoded KEY has the form "username:password-hash"
                            let username = get_el_from_split(str::from_utf8(&s).unwrap(), ":", 0)?;
                            Ok(HTTPBasicAuthRequest {
                                input: HTTPBasicAuthRequestInput {
                                    user: username,
                                    path: get_path_list(req),
                                    method: req.method().to_string(),
                                },
                            })
                        }
                        Err(err) => Err(format!("Invalid Authorization key structure: {:?}", err)),
                    }
                }
                Err(err) => Err(format!(
                    "Unable to read the Authorization header : {:?}",
                    err
                )),
            }
        } else {
            Err("Missing Authorization header".to_string())
        }
    }
}

#[derive(Serialize)]
pub struct HTTPTokenAuthRequest {
    input: HTTPTokenAuthRequestInput,
}

#[derive(Serialize)]
pub struct HTTPTokenAuthRequestInput {
    token: String,
    path: Vec<String>,
    method: String,
}

impl<S> OPARequest<S> for HTTPTokenAuthRequest {
    fn from_http_request(req: &HttpRequest<S>) -> Result<Self, String> {
        let headermap = req.headers();
        if headermap.contains_key(header::AUTHORIZATION) {
            match headermap[header::AUTHORIZATION].to_str() {
                Ok(s) => {
                    // Header value has the form "Bearer TOKEN"
                    let token = &get_el_from_split(s, " ", 1)?;

                    if cfg!(feature = "jwt") {
                        if !jsonwebtoken::decode_header(token).is_ok() {
                            return Err("Bad token".to_string());
                        }
                    }

                    Ok(HTTPTokenAuthRequest {
                        input: HTTPTokenAuthRequestInput {
                            token: token.to_string(),
                            path: get_path_list(req),
                            method: req.method().to_string(),
                        },
                    })
                }
                Err(err) => Err(format!(
                    "Unable to read the Authorization header : {:?}",
                    err
                )),
            }
        } else {
            Err("Missing Authorization header".to_string())
        }
    }
}

pub struct PolicyVerifier<A, B> {
    url: String,
    duration: Duration,
    request: Option<A>,
    response: Option<B>,
}

impl<A, B> PolicyVerifier<A, B>
where
    A: Serialize,
{
    pub fn build(url: String) -> Self {
        PolicyVerifier {
            url: url,
            duration: Duration::from_millis(DEFAULT_TIMEOUT_MS),
            request: None,
            response: None,
        }
    }

    pub fn url(mut self, url: String) -> PolicyVerifier<A, B> {
        self.url = url;
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> PolicyVerifier<A, B> {
        self.duration = timeout;
        self
    }

    pub fn build_request(&self, req: &A) -> client::SendRequest {
        client::ClientRequest::post(&self.url)
            .header(HEADER_USER_AGENT_KEY, HEADER_USER_AGENT_VALUE)
            .header(header::CONTENT_TYPE, MIMETYPE_JSON)
            .timeout(self.duration)
            .json(req)
            .unwrap()
            .send()
    }
}

fn extract_response<B>(bytes: &Bytes) -> Result<Option<HttpResponse>>
where
    B: OPAResponse + DeserializeOwned,
{
    // println!("==== BODY ==== {:?}", bytes);
    match str::from_utf8(&bytes) {
        Ok(s) => {
            let response: B = serde_json::from_str(&s)?;
            if response.allowed() {
                println!("Response");
                Ok(None)
            } else {
                println!("403 FORBIDDEN");
                Ok(Some(HttpResponse::Forbidden().finish()))
            }
        }
        Err(_) => {
            println!("400");
            Ok(Some(HttpResponse::InternalServerError().finish()))
        }
    }
}

impl<A: 'static, B: 'static, S> Middleware<S> for PolicyVerifier<A, B>
where
    A: OPARequest<S> + Serialize,
    B: OPAResponse + DeserializeOwned,
{
    fn start(&self, req: &HttpRequest<S>) -> Result<Started> {
        println!("Get request {:?}", req);

        match &A::from_http_request(req) {
            Ok(res) => {
                let response = self.build_request(res);
                Ok(Started::Future(Box::new(
                            response
                            .from_err()
                            .and_then(|response| {
                                println!("Response : {:?}", response);
                                Ok(response.body())
                            })
                            .and_then(|body| {
                                body.limit(RESPONSE_BODY_SIZE)
                                    .from_err()
                                    .and_then(|bytes: Bytes| extract_response::<B>(&bytes))
                            }))))

            },
            Err(err) => {
                println!("Denied - bad request : {:?}", err);
                Ok(Started::Response(HttpResponse::Unauthorized().finish()))
            }
        }

    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::test::{TestRequest, TestServer};

    const TEST_BODY: &str = r#"{"input":{"user":"testuser"}}"#;

    #[derive(Serialize)]
    struct PolicyRequest {
        name: String,
    }

    impl<S> OPARequest<S> for PolicyRequest {
        fn from_http_request(_req: &HttpRequest<S>) -> Result<Self, String> {
            Ok(PolicyRequest {
                name: "Sam".to_string(),
            })
        }
    }

    #[derive(Deserialize)]
    struct PolicyDecision {
        result: OPAResult,
    }

    #[derive(Deserialize)]
    struct OPAResult {
        allow: bool,
    }

    impl OPAResponse for PolicyDecision {
        fn allowed(&self) -> bool {
            self.result.allow
        }
    }

    type Verifier = PolicyVerifier<PolicyRequest, PolicyDecision>;

    #[test]
    fn build_works() {
        let url = "http://localhost:5151/api/)".to_string();
        let verifier = Verifier::build(url.clone());
        assert_eq!(verifier.url, url);
    }

    #[test]
    fn url_change_works() {
        let url_a = "http://localhost:6161/api/)".to_string();
        let url_b = "http://localhost:6161/api/)".to_string();
        let verifier = Verifier::build(url_a.to_owned());
        verifier.url(url_b.to_owned());
        // assert_ne!(&verifier.url.clone(), &url_a);
        // assert_eq!(&verifier.url.clone(), &url_b);
    }

    #[test]
    fn basic() {
        let url_a = "http://localhost:6161/api/)".to_string();
        let verifier = Verifier::build(url_a.to_owned());

        let mut srv =
            TestServer::new(|app|
                                  app.handler(|_| HttpResponse::Ok().body(TEST_BODY)));

        let request = srv.get().header("X-Test", "456456456").finish().unwrap();
        let repr = format!("{:?}", request);
        // assert!(repr.contains("PolicyVerifier middleware"));

        let response = srv.execute(request.send()).unwrap();
        assert!(response.status().is_success());
    }
}