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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
#![deny(missing_docs)]

//! # Integration of Http Signature Normalization with Actix Web
//!
//! This library provides middlewares for verifying HTTP Signature headers and, optionally, Digest
//! headers with the `digest` feature enabled. It also extends awc's ClientRequest type to
//! add signatures and digests to the request
//!
//! ### Use it in a server
//! ```rust,ignore
//! use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
//! use http_signature_normalization_actix::prelude::*;
//! use sha2::{Digest, Sha256};
//! use std::future::{ready, Ready};
//! use tracing::info;
//! use tracing_actix_web::TracingLogger;
//! use tracing_error::ErrorLayer;
//! use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
//!
//! #[derive(Clone, Debug)]
//! struct MyVerify;
//!
//! impl SignatureVerify for MyVerify {
//!     type Error = MyError;
//!     type Future = Ready<Result<bool, Self::Error>>;
//!
//!     fn signature_verify(
//!         &mut self,
//!         algorithm: Option<Algorithm>,
//!         key_id: String,
//!         signature: String,
//!         signing_string: String,
//!     ) -> Self::Future {
//!         match algorithm {
//!             Some(Algorithm::Hs2019) => (),
//!             _ => return ready(Err(MyError::Algorithm)),
//!         };
//!
//!         if key_id != "my-key-id" {
//!             return ready(Err(MyError::Key));
//!         }
//!
//!         let decoded = match base64::decode(&signature) {
//!             Ok(decoded) => decoded,
//!             Err(_) => return ready(Err(MyError::Decode)),
//!         };
//!
//!         info!("Signing String\n{}", signing_string);
//!
//!         ready(Ok(decoded == signing_string.as_bytes()))
//!     }
//! }
//!
//! async fn index(
//!     (_, sig_verified): (DigestVerified, SignatureVerified),
//!     req: HttpRequest,
//!     _body: web::Bytes,
//! ) -> &'static str {
//!     info!("Verified request for {}", sig_verified.key_id());
//!     info!("{:?}", req);
//!     "Eyyyyup"
//! }
//!
//! #[actix_rt::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
//!
//!     let subscriber = tracing_subscriber::Registry::default()
//!         .with(env_filter)
//!         .with(ErrorLayer::default())
//!         .with(tracing_subscriber::fmt::layer());
//!
//!     tracing::subscriber::set_global_default(subscriber)?;
//!
//!     let config = Config::default().require_header("accept").require_digest();
//!
//!     HttpServer::new(move || {
//!         App::new()
//!             .wrap(VerifyDigest::new(Sha256::new()).optional())
//!             .wrap(VerifySignature::new(MyVerify, config.clone()).optional())
//!             .wrap(TracingLogger::default())
//!             .route("/", web::post().to(index))
//!     })
//!     .bind("127.0.0.1:8010")?
//!     .run()
//!     .await?;
//!
//!     Ok(())
//! }
//!
//! #[derive(Debug, thiserror::Error)]
//! enum MyError {
//!     #[error("Failed to verify, {0}")]
//!     Verify(#[from] PrepareVerifyError),
//!
//!     #[error("Unsupported algorithm")]
//!     Algorithm,
//!
//!     #[error("Couldn't decode signature")]
//!     Decode,
//!
//!     #[error("Invalid key")]
//!     Key,
//! }
//!
//! impl ResponseError for MyError {
//!     fn status_code(&self) -> StatusCode {
//!         StatusCode::BAD_REQUEST
//!     }
//!
//!     fn error_response(&self) -> HttpResponse {
//!         HttpResponse::BadRequest().finish()
//!     }
//! }
//! ```
//!
//! ### Use it in a client
//! ```rust,ignore
//! use actix_rt::task::JoinError;
//! use awc::Client;
//! use http_signature_normalization_actix::prelude::*;
//! use sha2::{Digest, Sha256};
//! use std::time::SystemTime;
//! use tracing::{error, info};
//! use tracing_error::ErrorLayer;
//! use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
//!
//! async fn request(config: Config) -> Result<(), Box<dyn std::error::Error>> {
//!     let digest = Sha256::new();
//!
//!     let mut response = Client::default()
//!         .post("http://127.0.0.1:8010/")
//!         .append_header(("User-Agent", "Actix Web"))
//!         .append_header(("Accept", "text/plain"))
//!         .insert_header(actix_web::http::header::Date(SystemTime::now().into()))
//!         .signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
//!             info!("Signing String\n{}", s);
//!             Ok(base64::encode(s)) as Result<_, MyError>
//!         })
//!         .await?
//!         .send()
//!         .await
//!         .map_err(|e| {
//!             error!("Error, {}", e);
//!             MyError::SendRequest
//!         })?;
//!
//!     let body = response.body().await.map_err(|e| {
//!         error!("Error, {}", e);
//!         MyError::Body
//!     })?;
//!
//!     info!("{:?}", body);
//!     Ok(())
//! }
//!
//! #[actix_rt::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
//!
//!     let subscriber = tracing_subscriber::Registry::default()
//!         .with(env_filter)
//!         .with(ErrorLayer::default())
//!         .with(tracing_subscriber::fmt::layer());
//!
//!     tracing::subscriber::set_global_default(subscriber)?;
//!
//!     let config = Config::default().require_header("accept").require_digest();
//!
//!     request(config.clone()).await?;
//!     request(config.mastodon_compat()).await?;
//!     Ok(())
//! }
//!
//! #[derive(Debug, thiserror::Error)]
//! pub enum MyError {
//!     #[error("Failed to create signing string, {0}")]
//!     Convert(#[from] PrepareSignError),
//!
//!     #[error("Failed to create header, {0}")]
//!     Header(#[from] InvalidHeaderValue),
//!
//!     #[error("Failed to send request")]
//!     SendRequest,
//!
//!     #[error("Failed to retrieve request body")]
//!     Body,
//!
//!     #[error("Blocking operation was canceled")]
//!     Canceled,
//! }
//!
//! impl From<JoinError> for MyError {
//!     fn from(_: JoinError) -> Self {
//!         MyError::Canceled
//!     }
//! }
//! ```

use std::time::Duration;

#[cfg(any(feature = "client", feature = "server"))]
use actix_http::{
    header::{HeaderMap, ToStrError},
    uri::PathAndQuery,
    Method,
};
#[cfg(any(feature = "client", feature = "server"))]
use std::collections::BTreeMap;

#[cfg(feature = "client")]
mod sign;

#[cfg(feature = "digest")]
pub mod digest;

#[cfg(feature = "client")]
pub mod create;
#[cfg(feature = "server")]
pub mod middleware;

pub use http_signature_normalization::RequiredError;

/// Useful types and traits for using this library in Actix Web
pub mod prelude {
    pub use crate::{Config, RequiredError};

    #[cfg(feature = "client")]
    pub use crate::{PrepareSignError, Sign};

    #[cfg(feature = "server")]
    pub use crate::{
        middleware::{SignatureVerified, VerifySignature},
        verify::{Algorithm, DeprecatedAlgorithm, Unverified},
        PrepareVerifyError, SignatureVerify,
    };

    #[cfg(all(feature = "digest", feature = "client"))]
    pub use crate::digest::{DigestClient, DigestCreate, SignExt};

    #[cfg(all(feature = "digest", feature = "server"))]
    pub use crate::digest::{
        middleware::{DigestVerified, VerifyDigest},
        DigestPart, DigestVerify,
    };

    pub use actix_http::header::{InvalidHeaderValue, ToStrError};
}

#[cfg(feature = "server")]
/// Types for Verifying an HTTP Signature
pub mod verify {
    pub use http_signature_normalization::verify::{
        Algorithm, DeprecatedAlgorithm, ParseSignatureError, ParsedHeader, Unvalidated, Unverified,
        ValidateError,
    };
}

#[cfg(feature = "client")]
pub use self::client::{PrepareSignError, Sign};

#[cfg(feature = "server")]
pub use self::server::{PrepareVerifyError, SignatureVerify};

#[derive(Clone, Debug, Default)]
/// Configuration for signing and verifying signatures
///
/// By default, the config is set up to create and verify signatures that expire after 10
/// seconds, and use the `(created)` and `(expires)` fields that were introduced in draft 11
pub struct Config<Spawner = DefaultSpawner> {
    /// The inner config type
    config: http_signature_normalization::Config,

    /// Whether to set the Host header
    set_host: bool,

    /// Whether to set the Date header
    set_date: bool,

    /// The spawner used to create blocking operations
    spawner: Spawner,
}

/// A default implementation of Spawner for spawning blocking operations
#[derive(Clone, Copy, Debug, Default)]
pub struct DefaultSpawner;

/// An error that indicates a blocking operation panicked and cannot return a response
#[derive(Debug)]
pub struct Canceled;

impl std::fmt::Display for Canceled {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Operation was canceled")
    }
}

impl std::error::Error for Canceled {}

/// A trait dictating how to spawn a future onto a blocking threadpool. By default,
/// http-signature-normalization-actix will use actix_rt's built-in blocking threadpool, but this
/// can be customized
pub trait Spawn {
    /// The future type returned by spawn_blocking
    type Future<T>: std::future::Future<Output = Result<T, Canceled>>;

    /// Spawn the blocking function onto the threadpool
    fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
    where
        Func: FnOnce() -> Out + Send + 'static,
        Out: Send + 'static;
}

/// The future returned by DefaultSpawner when spawning blocking operations on the actix_rt
/// blocking threadpool
pub struct DefaultSpawnerFuture<Out> {
    inner: actix_rt::task::JoinHandle<Out>,
}

impl Spawn for DefaultSpawner {
    type Future<T> = DefaultSpawnerFuture<T>;

    fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
    where
        Func: FnOnce() -> Out + Send + 'static,
        Out: Send + 'static,
    {
        DefaultSpawnerFuture {
            inner: actix_rt::task::spawn_blocking(func),
        }
    }
}

impl<Out> std::future::Future for DefaultSpawnerFuture<Out> {
    type Output = Result<Out, Canceled>;

    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        let res = std::task::ready!(std::pin::Pin::new(&mut self.inner).poll(cx));

        std::task::Poll::Ready(res.map_err(|_| Canceled))
    }
}

#[cfg(feature = "client")]
mod client {
    use super::{Config, RequiredError, Spawn};
    use actix_http::header::{InvalidHeaderValue, ToStrError};
    use actix_rt::task::JoinError;
    use std::{fmt::Display, future::Future, pin::Pin};

    /// A trait implemented by the awc ClientRequest type to add an HTTP signature to the request
    pub trait Sign {
        /// Add an Authorization Signature to the request
        fn authorization_signature<F, E, K, S>(
            self,
            config: Config<S>,
            key_id: K,
            f: F,
        ) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
        where
            F: FnOnce(&str) -> Result<String, E> + Send + 'static,
            E: From<JoinError>
                + From<PrepareSignError>
                + From<crate::Canceled>
                + From<InvalidHeaderValue>
                + std::fmt::Debug
                + Send
                + 'static,
            K: Display + 'static,
            S: Spawn + 'static,
            Self: Sized;

        /// Add a Signature to the request
        fn signature<F, E, K, S>(
            self,
            config: Config<S>,
            key_id: K,
            f: F,
        ) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
        where
            F: FnOnce(&str) -> Result<String, E> + Send + 'static,
            E: From<JoinError>
                + From<PrepareSignError>
                + From<crate::Canceled>
                + From<InvalidHeaderValue>
                + std::fmt::Debug
                + Send
                + 'static,
            K: Display + 'static,
            S: Spawn + 'static,
            Self: Sized;
    }

    #[derive(Debug, thiserror::Error)]
    /// An error when preparing to sign a request
    pub enum PrepareSignError {
        #[error("Failed to read header")]
        /// An error occurred when reading the request's headers
        Header(#[from] ToStrError),

        #[error("Missing required header")]
        /// Some headers were marked as required, but are missing
        RequiredError(#[from] RequiredError),

        #[error("No host provided for URL, {0}")]
        /// Missing host
        Host(String),

        #[error("Failed to set header")]
        /// Invalid Date header
        InvalidHeader(#[from] actix_http::header::InvalidHeaderValue),
    }
}

#[cfg(feature = "server")]
mod server {
    use super::RequiredError;
    use actix_http::header::ToStrError;
    use std::future::Future;

    /// A trait for verifying signatures
    pub trait SignatureVerify {
        /// An error produced while attempting to verify the signature. This can be anything
        /// implementing ResponseError
        type Error: actix_web::ResponseError;

        /// The future that resolves to the verification state of the signature
        type Future: Future<Output = Result<bool, Self::Error>>;

        /// Given the algorithm, key_id, signature, and signing_string, produce a future that resulves
        /// to a the verification status
        fn signature_verify(
            &mut self,
            algorithm: Option<super::verify::Algorithm>,
            key_id: String,
            signature: String,
            signing_string: String,
        ) -> Self::Future;
    }

    #[derive(Debug, thiserror::Error)]
    /// An error when preparing to verify a request
    pub enum PrepareVerifyError {
        #[error("Header is missing")]
        /// Header is missing
        Missing,

        #[error("{0}")]
        /// Header is expired
        Expired(String),

        #[error("Couldn't parse required field, {0}")]
        /// Couldn't parse required field
        ParseField(&'static str),

        #[error("Failed to read header, {0}")]
        /// An error converting the header to a string for validation
        Header(#[from] ToStrError),

        #[error("{0}")]
        /// Required headers were missing from request
        Required(#[from] RequiredError),
    }

    impl From<http_signature_normalization::PrepareVerifyError> for PrepareVerifyError {
        fn from(e: http_signature_normalization::PrepareVerifyError) -> Self {
            use http_signature_normalization as hsn;

            match e {
                hsn::PrepareVerifyError::Parse(parse_error) => {
                    PrepareVerifyError::ParseField(parse_error.missing_field())
                }
                hsn::PrepareVerifyError::Validate(validate_error) => match validate_error {
                    hsn::verify::ValidateError::Missing => PrepareVerifyError::Missing,
                    e @ hsn::verify::ValidateError::Expired { .. } => {
                        PrepareVerifyError::Expired(e.to_string())
                    }
                },
                hsn::PrepareVerifyError::Required(required_error) => {
                    PrepareVerifyError::Required(required_error)
                }
            }
        }
    }

    impl actix_web::ResponseError for super::Canceled {
        fn status_code(&self) -> actix_http::StatusCode {
            actix_http::StatusCode::INTERNAL_SERVER_ERROR
        }

        fn error_response(&self) -> actix_web::HttpResponse<actix_http::body::BoxBody> {
            actix_web::HttpResponse::new(self.status_code())
        }
    }
}

impl Config {
    /// Create a new Config with a default expiration of 10 seconds
    pub fn new() -> Self {
        Config::default()
    }
}

impl<Spawner> Config<Spawner> {
    /// Since manually setting the Host header doesn't work so well in AWC, you can use this method
    /// to enable setting the Host header for signing requests without breaking client
    /// functionality
    pub fn set_host_header(self) -> Self {
        Config {
            config: self.config,
            set_host: true,
            set_date: self.set_date,
            spawner: self.spawner,
        }
    }

    #[cfg(feature = "client")]
    /// Set the spawner for spawning blocking tasks
    ///
    /// http-signature-normalization-actix offloads signing messages and generating hashes to a
    /// blocking threadpool, which can be configured by providing a custom spawner.
    pub fn spawner<S>(self, spawner: S) -> Config<S>
    where
        S: Spawn,
    {
        Config {
            config: self.config,
            set_host: self.set_host,
            set_date: self.set_date,
            spawner,
        }
    }

    /// Enable mastodon compatibility
    ///
    /// This is the same as disabling the use of `(created)` and `(expires)` signature fields,
    /// requiring the Date header, and requiring the Host header
    pub fn mastodon_compat(self) -> Self {
        Config {
            config: self.config.mastodon_compat(),
            set_host: true,
            set_date: true,
            spawner: self.spawner,
        }
    }

    /// Require the Digest header be set
    ///
    /// This is useful for POST, PUT, and PATCH requests, but doesn't make sense for GET or DELETE.
    pub fn require_digest(self) -> Self {
        Config {
            config: self.config.require_digest(),
            set_host: self.set_host,
            set_date: self.set_date,
            spawner: self.spawner,
        }
    }

    /// Opt out of using the (created) and (expires) fields introduced in draft 11
    ///
    /// Note that by enabling this, the Date header becomes required on requests. This is to
    /// prevent replay attacks
    pub fn dont_use_created_field(self) -> Self {
        Config {
            config: self.config.dont_use_created_field(),
            set_host: self.set_host,
            set_date: self.set_date,
            spawner: self.spawner,
        }
    }

    /// Set the expiration to a custom duration
    pub fn set_expiration(self, expires_after: Duration) -> Self {
        Config {
            config: self.config.set_expiration(expires_after),
            set_host: self.set_host,
            set_date: self.set_date,
            spawner: self.spawner,
        }
    }

    /// Require a header on signed and verified requests
    pub fn require_header(self, header: &str) -> Self {
        Config {
            config: self.config.require_header(header),
            set_host: self.set_host,
            set_date: self.set_date,
            spawner: self.spawner,
        }
    }

    #[cfg(feature = "client")]
    /// Begin the process of singing a request
    pub fn begin_sign(
        &self,
        method: &Method,
        path_and_query: Option<&PathAndQuery>,
        headers: HeaderMap,
    ) -> Result<self::create::Unsigned, PrepareSignError> {
        let headers = headers
            .iter()
            .map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
            .collect::<Result<BTreeMap<_, _>, ToStrError>>()?;

        let path_and_query = path_and_query
            .map(|p| p.to_string())
            .unwrap_or_else(|| "/".to_string());

        let unsigned = self
            .config
            .begin_sign(method.as_ref(), &path_and_query, headers)?;

        Ok(self::create::Unsigned { unsigned })
    }

    #[cfg(feature = "server")]
    /// Begin the proess of verifying a request
    pub fn begin_verify(
        &self,
        method: &Method,
        path_and_query: Option<&PathAndQuery>,
        headers: HeaderMap,
    ) -> Result<self::verify::Unverified, PrepareVerifyError> {
        let headers = headers
            .iter()
            .map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
            .collect::<Result<BTreeMap<_, _>, ToStrError>>()?;

        let path_and_query = path_and_query
            .map(|p| p.to_string())
            .unwrap_or_else(|| "/".to_string());

        let unverified = self
            .config
            .begin_verify(method.as_ref(), &path_and_query, headers)?;

        Ok(unverified)
    }
}