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
//! Types for verifying requests with Actix Web

use crate::{Config, PrepareVerifyError, SignatureVerify, Spawn};
use actix_web::{
    body::MessageBody,
    dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},
    http::StatusCode,
    Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
};
use futures_core::future::LocalBoxFuture;
use std::{
    collections::HashSet,
    future::{ready, Ready},
    rc::Rc,
    task::{Context, Poll},
};
use tracing::{debug, Span};
use tracing_error::SpanTrace;
use tracing_futures::Instrument;

#[derive(Clone, Debug)]
/// A marker type that is used to guard routes
pub struct SignatureVerified(String);

impl SignatureVerified {
    /// Return the Key ID used to verify the request
    ///
    /// It might be important for an application to verify that the payload being processed indeed
    /// belongs to the owner of the key used to sign the request.
    pub fn key_id(&self) -> &str {
        &self.0
    }
}

#[derive(Clone, Debug)]
/// The Verify signature middleware
///
/// ```rust,ignore
/// let middleware = VerifySignature::new(MyVerifier::new(), Config::default()).authorization();
///
/// HttpServer::new(move || {
///     App::new()
///         .wrap(middleware.clone())
///         .route("/protected", web::post().to(|_: SignatureVerified| "Verified Authorization Header"))
///         .route("/unprotected", web::post().to(|| "No verification required"))
/// })
/// ```
pub struct VerifySignature<T, Spawner>(T, Config<Spawner>, HeaderKind);

#[derive(Debug)]
#[doc(hidden)]
pub struct VerifyMiddleware<T, Spawner, S>(Rc<S>, Config<Spawner>, HeaderKind, T);

#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
enum HeaderKind {
    Authorization,
    Signature,
}

impl std::fmt::Display for HeaderKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Authorization => {
                write!(f, "Authorization")
            }
            Self::Signature => {
                write!(f, "Signature")
            }
        }
    }
}

#[derive(Clone)]
#[doc(hidden)]
pub struct VerifyError {
    context: String,
    kind: VerifyErrorKind,
}

impl std::fmt::Debug for VerifyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{:?}", self.kind)
    }
}

impl std::fmt::Display for VerifyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{}", self.kind)?;
        std::fmt::Display::fmt(&self.context, f)
    }
}

impl std::error::Error for VerifyError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.kind.source()
    }
}

#[derive(Clone, Debug, thiserror::Error)]
enum VerifyErrorKind {
    #[error("Signature or Authorization header is missing")]
    MissingSignature,

    #[error("{0}")]
    ExpiredSignature(String),

    #[error("Signature field could not be parsed")]
    ParseField(&'static str),

    #[error("Signature is not a valid string")]
    ParseSignature,

    #[error("Request extension not present")]
    Extension,

    #[error("Required headers are missing")]
    MissingHeader(HashSet<String>),
}

impl VerifyError {
    fn new(span: &Span, kind: VerifyErrorKind) -> Self {
        span.in_scope(|| VerifyError {
            context: SpanTrace::capture().to_string(),
            kind,
        })
    }
}

impl<T, Spawner> VerifySignature<T, Spawner>
where
    T: SignatureVerify,
{
    /// Create a new middleware for verifying HTTP Signatures. A type implementing
    /// [`SignatureVerify`] is required, as well as a Config
    ///
    /// By default, this middleware expects to verify Signature headers, and requires the presence
    /// of the header
    pub fn new(verify_signature: T, config: Config<Spawner>) -> Self
    where
        Spawner: Spawn,
    {
        VerifySignature(verify_signature, config, HeaderKind::Signature)
    }

    /// Verify Authorization headers instead of Signature headers
    pub fn authorization(self) -> Self {
        VerifySignature(self.0, self.1, HeaderKind::Authorization)
    }
}

impl<T, Spawner, S, B> VerifyMiddleware<T, Spawner, S>
where
    T: SignatureVerify + Clone + 'static,
    T::Future: 'static,
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    B: MessageBody + 'static,
{
    fn handle(
        &self,
        span: Span,
        req: ServiceRequest,
    ) -> LocalBoxFuture<'static, Result<ServiceResponse<B>, Error>> {
        let res = self.1.begin_verify(
            req.method(),
            req.uri().path_and_query(),
            req.headers().clone(),
        );

        let unverified = match res {
            Ok(unverified) => unverified,
            Err(PrepareVerifyError::Expired(reason)) => {
                return Box::pin(ready(Err(VerifyError::new(
                    &span,
                    VerifyErrorKind::ExpiredSignature(reason),
                )
                .into())));
            }
            Err(PrepareVerifyError::Missing) => {
                return Box::pin(ready(Err(VerifyError::new(
                    &span,
                    VerifyErrorKind::MissingSignature,
                )
                .into())));
            }
            Err(PrepareVerifyError::ParseField(field)) => {
                return Box::pin(ready(Err(VerifyError::new(
                    &span,
                    VerifyErrorKind::ParseField(field),
                )
                .into())));
            }
            Err(PrepareVerifyError::Header(_)) => {
                return Box::pin(ready(Err(VerifyError::new(
                    &span,
                    VerifyErrorKind::ParseSignature,
                )
                .into())));
            }
            Err(PrepareVerifyError::Required(mut req)) => {
                return Box::pin(ready(Err(VerifyError::new(
                    &span,
                    VerifyErrorKind::MissingHeader(req.take_headers()),
                )
                .into())));
            }
        };

        let algorithm = unverified.algorithm().cloned();
        let key_id = unverified.key_id().to_owned();

        let verify_fut = unverified.verify(|signature, signing_string| {
            span.in_scope(|| {
                self.3.clone().signature_verify(
                    algorithm,
                    key_id.clone(),
                    signature.to_string(),
                    signing_string.to_string(),
                )
            })
        });

        let service = Rc::clone(&self.0);

        Box::pin(async move {
            if verify_fut.instrument(span).await? {
                req.extensions_mut().insert(SignatureVerified(key_id));
            }

            service.call(req).await
        })
    }
}

impl HeaderKind {
    pub fn is_authorization(self) -> bool {
        HeaderKind::Authorization == self
    }

    pub fn is_signature(self) -> bool {
        HeaderKind::Signature == self
    }
}

impl FromRequest for SignatureVerified {
    type Error = VerifyError;
    type Future = Ready<Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
        let res = req
            .extensions()
            .get::<Self>()
            .cloned()
            .ok_or_else(|| VerifyError::new(&Span::current(), VerifyErrorKind::Extension));

        if res.is_err() {
            debug!("Failed to fetch SignatureVerified from request");
        }

        ready(res)
    }
}

impl<T, Spawner, S, B> Transform<S, ServiceRequest> for VerifySignature<T, Spawner>
where
    T: SignatureVerify + Clone + 'static,
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
    S::Error: 'static,
    B: MessageBody + 'static,
    Spawner: Clone,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Transform = VerifyMiddleware<T, Spawner, S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(VerifyMiddleware(
            Rc::new(service),
            self.1.clone(),
            self.2,
            self.0.clone(),
        )))
    }
}

impl<T, Spawner, S, B> Service<ServiceRequest> for VerifyMiddleware<T, Spawner, S>
where
    T: SignatureVerify + Clone + 'static,
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
    S::Error: 'static,
    B: MessageBody + 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

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

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let span = tracing::info_span!(
            "Signature Verification",
            signature.kind = tracing::field::Empty,
            signature.expected_kind = tracing::field::display(&self.2),
        );
        let authorization = req.headers().get("Authorization").is_some();
        let signature = req.headers().get("Signature").is_some();

        if authorization {
            span.record("signature.kind", &tracing::field::display("Authorization"));

            if self.2.is_authorization() {
                return self.handle(span, req);
            }
        } else if signature {
            span.record("signature.kind", &tracing::field::display("Signature"));

            if self.2.is_signature() {
                return self.handle(span, req);
            }
        } else {
            span.record("signature.kind", &tracing::field::display("None"));
        }

        Box::pin(self.0.call(req))
    }
}

impl ResponseError for VerifyError {
    fn status_code(&self) -> StatusCode {
        StatusCode::BAD_REQUEST
    }

    fn error_response(&self) -> HttpResponse {
        HttpResponse::new(self.status_code())
    }
}