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
use actix_web::{
    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
    error::ErrorUnauthorized,
    http::header::HeaderValue,
    web::Bytes,
    Error,
};
use ed25519_dalek::{PublicKey, Signature, Verifier};
use futures_util::{future::LocalBoxFuture, FutureExt};
use std::{future::Ready, pin::Pin, rc::Rc};

pub struct Ed25519Authenticator {
    pub data: MiddlewareData,
}

impl<S, B> Transform<S, ServiceRequest> for Ed25519Authenticator
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type InitError = ();
    type Transform = Ed25519AuthenticatorMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        std::future::ready(Ok(Ed25519AuthenticatorMiddleware {
            service: Rc::new(service),
            data: Rc::new(self.data.clone()),
        }))
    }
}

#[derive(Clone, Debug)]
pub struct MiddlewareData {
    public_key: String,
    signature_header: String,
    timestamp_header: String,
}

impl Default for MiddlewareData {
    fn default() -> Self {
        MiddlewareData {
            public_key: String::new(),
            signature_header: String::from("X-Signature-Ed25519"),
            timestamp_header: String::from("X-Signature-Timestamp"),
        }
    }
}

impl MiddlewareData {
    pub fn new(public_key: &str) -> Self {
        Self {
            public_key: public_key.into(),
            ..Self::default()
        }
    }
    pub fn new_with_custom_headers(
        public_key: &str,
        signature_header: &str,
        timestamp_header: &str,
    ) -> Self {
        Self {
            public_key: public_key.into(),
            signature_header: signature_header.into(),
            timestamp_header: timestamp_header.into(),
        }
    }
}

pub struct Ed25519AuthenticatorMiddleware<S> {
    service: Rc<S>,
    data: Rc<MiddlewareData>,
}

impl<S, B> Service<ServiceRequest> for Ed25519AuthenticatorMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(
        &self,
        mut req: ServiceRequest,
    ) -> Pin<
        Box<
            (dyn futures_util::Future<Output = Result<ServiceResponse<B>, actix_web::Error>>
                 + 'static),
        >,
    > {
        let data = self.data.clone();
        let srv = self.service.clone();

        async move {
            let body = req.extract::<Bytes>().await?;

            let default_header = HeaderValue::from_static("");

            let public_key =
                PublicKey::from_bytes(&hex::decode(&data.public_key).unwrap_or_else(|_| {
                    println!("Couldn't decode public key!");
                    Vec::<u8>::new()
                }))
                .unwrap();

            let timestamp = req
                .headers()
                .get(data.timestamp_header.clone())
                .unwrap_or(&default_header);

            let signature = {
                let header = req
                    .headers()
                    .get(data.signature_header.clone())
                    .unwrap_or(&default_header);
                let decoded_header = hex::decode(header).unwrap();

                let mut sig_arr: [u8; 64] = [0; 64];
                for (i, byte) in decoded_header.into_iter().enumerate() {
                    sig_arr[i] = byte;
                }
                Signature::from_bytes(&sig_arr).unwrap()
            };

            let content = timestamp
                .as_bytes()
                .iter()
                .chain(body.as_ref().iter())
                .cloned()
                .collect::<Vec<u8>>();

            match public_key.verify(&content, &signature) {
                Err(_) => Err(ErrorUnauthorized("Unauthorized")),
                Ok(_) => {
                    let fut = srv.call(req);
                    let res = fut.await?;
                    Ok(res)
                }
            }
        }
        .boxed_local()
    }
}