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
#![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 actix_web's ClientRequest type to //! add signatures and digests to the request //! //! ### Use it in a server //! ```rust,ignore //! use actix::System; //! use actix_web::{web, App, HttpResponse, HttpServer, ResponseError}; //! use failure::Fail; //! use http_signature_normalization_actix::{prelude::*, verify::Algorithm}; //! use sha2::{Digest, Sha256}; //! //! #[derive(Clone, Debug)] //! struct MyVerify; //! //! impl SignatureVerify for MyVerify { //! type Error = MyError; //! type Future = Result<bool, Self::Error>; //! //! fn signature_verify( //! &mut self, //! algorithm: Option<Algorithm>, //! key_id: &str, //! signature: &str, //! signing_string: &str, //! ) -> Self::Future { //! match algorithm { //! Some(Algorithm::Hs2019) => (), //! _ => return Err(MyError::Algorithm), //! }; //! //! if key_id != "my-key-id" { //! return Err(MyError::Key); //! } //! //! let decoded = base64::decode(signature).map_err(|_| MyError::Decode)?; //! //! // In a real system, you'd want to actually verify a signature, not just check for //! // byte equality //! Ok(decoded == signing_string.as_bytes()) //! } //! } //! //! fn index(_: (DigestVerified, SignatureVerified)) -> &'static str { //! "Eyyyyup" //! } //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! let sys = System::new("server-example"); //! //! let config = Config::default(); //! //! HttpServer::new(move || { //! App::new() //! .wrap(VerifyDigest::new(Sha256::new()).optional()) //! .wrap( //! VerifySignature::new(MyVerify, config.clone()) //! .authorization() //! .optional(), //! ) //! .route("/", web::post().to(index)) //! }) //! .bind("127.0.0.1:8010")? //! .start(); //! //! sys.run()?; //! Ok(()) //! } //! //! #[derive(Debug, Fail)] //! enum MyError { //! #[fail(display = "Failed to verify, {}", _0)] //! Verify(#[cause] PrepareVerifyError), //! //! #[fail(display = "Unsupported algorithm")] //! Algorithm, //! //! #[fail(display = "Couldn't decode signature")] //! Decode, //! //! #[fail(display = "Invalid key")] //! Key, //! } //! //! impl ResponseError for MyError { //! fn error_response(&self) -> HttpResponse { //! HttpResponse::BadRequest().finish() //! } //! //! fn render_response(&self) -> HttpResponse { //! self.error_response() //! } //! } //! //! impl From<PrepareVerifyError> for MyError { //! fn from(e: PrepareVerifyError) -> Self { //! MyError::Verify(e) //! } //! } //! ``` //! //! ### Use it in a client //! ```rust,ignore //! use actix::System; //! use actix_web::client::Client; //! use failure::Fail; //! use futures::future::{lazy, Future}; //! use http_signature_normalization_actix::prelude::*; //! use sha2::{Digest, Sha256}; //! //! fn main() { //! System::new("client-example") //! .block_on(lazy(|| { //! let config = Config::default(); //! let mut digest = Sha256::new(); //! //! Client::default() //! .post("http://127.0.0.1:8010/") //! .header("User-Agent", "Actix Web") //! .authorization_signature_with_digest( //! &config, //! "my-key-id", //! &mut digest, //! "Hewwo-owo", //! |s| { //! // In a real-world system, you'd actually want to sign the string, //! // not just base64 encode it //! Ok(base64::encode(s)) as Result<_, MyError> //! }, //! ) //! .unwrap() //! .send() //! .map_err(|_| ()) //! .and_then(|mut res| res.body().map_err(|_| ())) //! .map(|body| { //! println!("{:?}", body); //! }) //! })) //! .unwrap(); //! } //! //! #[derive(Debug, Fail)] //! pub enum MyError { //! #[fail(display = "Failed to read header, {}", _0)] //! Convert(#[cause] ToStrError), //! //! #[fail(display = "Failed to create header, {}", _0)] //! Header(#[cause] InvalidHeaderValue), //! } //! //! impl From<ToStrError> for MyError { //! fn from(e: ToStrError) -> Self { //! MyError::Convert(e) //! } //! } //! //! impl From<InvalidHeaderValue> for MyError { //! fn from(e: InvalidHeaderValue) -> Self { //! MyError::Header(e) //! } //! } //! ``` use actix_web::http::{ header::{HeaderMap, InvalidHeaderValue, ToStrError}, uri::PathAndQuery, Method, }; use failure::Fail; use futures::future::IntoFuture; use std::{collections::BTreeMap, fmt::Display}; mod sign; #[cfg(feature = "digest")] pub mod digest; pub mod create; pub mod middleware; /// Useful types and traits for using this library in Actix Web pub mod prelude { pub use crate::{ middleware::{SignatureVerified, VerifySignature}, verify::Unverified, Config, PrepareVerifyError, Sign, SignatureVerify, }; #[cfg(feature = "digest")] pub use crate::digest::{ middleware::{DigestVerified, VerifyDigest}, DigestClient, DigestCreate, DigestPart, DigestVerify, SignExt, }; pub use actix_web::http::header::{InvalidHeaderValue, ToStrError}; } /// Types for Verifying an HTTP Signature pub mod verify { pub use http_signature_normalization::verify::{ Algorithm, DeprecatedAlgorithm, ParseSignatureError, ParsedHeader, Unvalidated, Unverified, ValidateError, }; } use self::{ create::Unsigned, verify::{Algorithm, Unverified}, }; /// 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: IntoFuture<Item = bool, Error = 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<Algorithm>, key_id: &str, signature: &str, signing_string: &str, ) -> Self::Future; } /// A trait implemented by the Actix Web 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>(self, config: &Config, key_id: K, f: F) -> Result<Self, E> where F: FnOnce(&str) -> Result<String, E>, E: From<ToStrError> + From<InvalidHeaderValue>, K: Display, Self: Sized; /// Add a Signature to the request fn signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Self, E> where F: FnOnce(&str) -> Result<String, E>, E: From<ToStrError> + From<InvalidHeaderValue>, K: Display, Self: Sized; } #[derive(Clone, Debug, Default)] /// A thin wrapper around the underlying library's config type pub struct Config { /// The inner config type pub config: http_signature_normalization::Config, } #[derive(Debug, Fail)] /// An error when preparing to verify a request pub enum PrepareVerifyError { #[fail(display = "Signature error, {}", _0)] /// An error validating the request Sig(#[cause] http_signature_normalization::PrepareVerifyError), #[fail(display = "Failed to read header, {}", _0)] /// An error converting the header to a string for validation Header(#[cause] ToStrError), } impl Config { /// Begin the process of singing a request pub fn begin_sign( &self, method: &Method, path_and_query: Option<&PathAndQuery>, headers: HeaderMap, ) -> Result<Unsigned, ToStrError> { 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(String::from("/")); let unsigned = self .config .begin_sign(&method.to_string(), &path_and_query, headers); Ok(Unsigned { unsigned }) } /// Begin the proess of verifying a request pub fn begin_verify( &self, method: &Method, path_and_query: Option<&PathAndQuery>, headers: HeaderMap, ) -> Result<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(String::from("/")); let unverified = self .config .begin_verify(&method.to_string(), &path_and_query, headers)?; Ok(unverified) } } impl From<http_signature_normalization::PrepareVerifyError> for PrepareVerifyError { fn from(e: http_signature_normalization::PrepareVerifyError) -> Self { PrepareVerifyError::Sig(e) } } impl From<ToStrError> for PrepareVerifyError { fn from(e: ToStrError) -> Self { PrepareVerifyError::Header(e) } }