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
/* This file is part of Digest Header
 *
 * Digest Header is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Digest Header is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Digest Header  If not, see <http://www.gnu.org/licenses/>.
 */

//! Digest Header, a simple library for verifying the content of HTTP Requests.
//!
//! This library doesn't offer any verification of identity, it only ensures that the content of
//! the request matches the signature in the Digest header of the request. If you want to verify
//! that a request has not been tampered with, it is best to use this library in conjunction with
//! [http signatures](https://github.com/asonix/http-signatures). This way, the Headers are signed
//! with a key, validating identity and authenticity, and the Digest header validates the body of
//! the request.
//!
//! # Basic use without an HTTP library
//!
//! ```rust
//! use digest_headers::{Digest, ShaSize};
//!
//! let message = b"Some message";
//!
//! let digest = Digest::new(message, ShaSize::TwoFiftySix);
//!
//! assert!(digest.verify(message).is_ok());
//! ```
//!
//! # Getting a Digest from a 'raw' digest string
//!
//! ```rust
//! # fn run() -> Result<(), digest_headers::Error> {
//! use digest_headers::Digest;
//!
//! let raw_digest = "SHA-256=2EL3dJGSq4d5YyGi76VZ5ZHzq5km0aZ0k4L8g1c4Llk=";
//!
//! let digest = raw_digest.parse::<Digest>()?;
//!
//! assert!(digest.verify(br#"{"Library":"Hyper"}"#).is_ok());
//! #     Ok(())
//! # }
//! ```
//!
//! # Adding a Digest to a Hyper request
//! With the `as_string` method, a Digest can easily be added to an HTTP Request. This example
//! shows adding a `Digest` to a Hyper `Request` without using the included `DigestHeader` from the
//! `use_hyper` feature.
//!
//! ```rust
//! # extern crate digest_headers;
//! # extern crate hyper;
//! use digest_headers::{Digest, ShaSize};
//! use hyper::{Method, Request};
//!
//! # fn main() {
//! let uri = "http://example.com".parse().unwrap();
//!
//! let body = "Some body";
//! let digest = Digest::new(body.as_bytes(), ShaSize::TwoFiftySix);
//!
//! let mut req: Request = Request::new(Method::Post, uri);
//! req.headers_mut().set_raw("Digest", digest.as_string());
//! req.set_body(body);
//! # }
//! ```

extern crate base64;
#[cfg(feature = "use_hyper")]
extern crate futures;
#[cfg(feature = "use_hyper")]
extern crate hyper;
extern crate ring;
#[cfg(feature = "use_rocket")]
extern crate rocket;
#[cfg(feature = "use_hyper")]
extern crate tokio_core;

mod error;
pub mod prelude;
#[cfg(feature = "use_hyper")]
pub mod use_hyper;
#[cfg(feature = "use_rocket")]
pub mod use_rocket;

pub use self::error::Error;

use std::fmt;
use std::str::FromStr;

/// Defines variants for the size of SHA hash.
///
/// Since this isn't being used for encryption or identification, it doesn't need to be very
/// strong. That said, it's ultimately up to the user of this library, so we provide options for
/// 256, 384, and 512.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ShaSize {
    TwoFiftySix,
    ThreeEightyFour,
    FiveTwelve,
}

impl fmt::Display for ShaSize {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s = match *self {
            ShaSize::TwoFiftySix => "SHA-256",
            ShaSize::ThreeEightyFour => "SHA-384",
            ShaSize::FiveTwelve => "SHA-512",
        };

        write!(f, "{}", s)
    }
}

impl FromStr for ShaSize {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let res = match s {
            "SHA-256" => ShaSize::TwoFiftySix,
            "SHA-384" => ShaSize::ThreeEightyFour,
            "SHA-512" => ShaSize::FiveTwelve,
            _ => return Err(Error::ParseShaSize),
        };

        Ok(res)
    }
}

/// Defines a wrapper around an &[u8] that can be turned into a `Digest`.
#[derive(Clone, Debug, PartialEq, Eq)]
struct RequestBody<'a>(&'a [u8]);

impl<'a> RequestBody<'a> {
    /// Creates a new `RequestBody` struct from a `&[u8]` representing a plaintext body.
    pub fn new(body: &'a [u8]) -> Self {
        RequestBody(body)
    }

    /// Consumes the `RequestBody`, producing a `Digest`.
    pub fn digest(self, sha_size: ShaSize) -> Digest {
        let size = match sha_size {
            ShaSize::TwoFiftySix => &ring::digest::SHA256,
            ShaSize::ThreeEightyFour => &ring::digest::SHA384,
            ShaSize::FiveTwelve => &ring::digest::SHA512,
        };

        let d = ring::digest::digest(size, self.0);
        let b = base64::encode(&d);

        Digest::from_base64_and_size(b, sha_size)
    }
}

/// Defines the `Digest` type.
///
/// This type can be compared to another `Digest`, or turned into a `String` for use in request
/// headers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Digest {
    digest: String,
    size: ShaSize,
}

impl Digest {
    /// Creates a new `Digest` from a series of bytes representing a plaintext body and a
    /// `ShaSize`.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use digest_headers::{Digest, ShaSize};
    /// let body = "Here's some text!";
    /// let digest = Digest::new(body.as_bytes(), ShaSize::TwoFiftySix);
    ///
    /// println!("Digest: {}", digest);
    /// ```
    pub fn new(body: &[u8], size: ShaSize) -> Self {
        RequestBody::new(body).digest(size)
    }

    /// Creates a new `Digest` from a base64-encoded digest `String` and a `ShaSize`.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use digest_headers::{Digest, ShaSize};
    /// let sha_size = ShaSize::TwoFiftySix;
    /// let digest_str = "bFp1K/TT36l9YQ8frlh/cVGuWuFEy1rCUNpGwQCSEow=";
    ///
    /// let digest = Digest::from_base64_and_size(digest_str.to_owned(), sha_size);
    ///
    /// println!("Digest: {}", digest);
    /// ```
    pub fn from_base64_and_size(digest: String, size: ShaSize) -> Self {
        Digest { digest, size }
    }

    /// Get the `ShaSize` of the current `Digest`
    pub fn sha_size(&self) -> ShaSize {
        self.size
    }

    /// Represents the `Digest` as a `String`.
    ///
    /// This can be used to produce headers for HTTP Requests.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use digest_headers::{Digest, ShaSize};
    /// let digest = Digest::new(b"Hello, world!", ShaSize::TwoFiftySix);
    ///
    /// println!("Digest: {}", digest.as_string());
    /// ```
    pub fn as_string(&self) -> String {
        format!("{}={}", self.size, self.digest)
    }

    /// Verify a given message body with the digest.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use digest_headers::{Digest, ShaSize};
    /// let body = b"Some message body";
    /// let digest = Digest::new(body, ShaSize::TwoFiftySix);
    ///
    /// assert!(digest.verify(body).is_ok());
    /// ```
    pub fn verify(&self, body: &[u8]) -> Result<(), Error> {
        let digest = Digest::new(body, self.size);

        if *self == digest {
            Ok(())
        } else {
            Err(Error::InvalidDigest)
        }
    }
}

impl FromStr for Digest {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let eq_index = s.find('=').ok_or(Error::ParseDigest)?;
        let tup = s.split_at(eq_index);
        let val = tup.1.get(1..).ok_or(Error::ParseDigest)?;

        Ok(Digest {
            digest: val.to_owned(),
            size: tup.0.parse()?,
        })
    }
}

impl fmt::Display for Digest {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_string())
    }
}

#[cfg(test)]
mod tests {
    use super::{Digest, RequestBody, ShaSize};

    const D256: &'static str = "bFp1K/TT36l9YQ8frlh/cVGuWuFEy1rCUNpGwQCSEow=";
    const D384: &'static str = "wOx5d657W3O8k2P7SW18Y/Kj/Rqm02pzgFVBInHOj7hbc0IrYGVXwzid3vTH82um";
    const D512: &'static str =
        "t13li71PxOlxHbZRB3ICZxjwBkYxhellKbMEQjT2udmQRP1fzIrmT49EGy9zNdTS5/JKjxqidsIQBO3i+9DBDQ==";

    #[test]
    fn digest_256() {
        digest(D256.to_owned(), ShaSize::TwoFiftySix);
    }

    #[test]
    fn digest_384() {
        digest(D384.to_owned(), ShaSize::ThreeEightyFour);
    }

    #[test]
    fn digest_512() {
        digest(D512.to_owned(), ShaSize::FiveTwelve);
    }

    #[test]
    fn invalid_digest_256() {
        digest_ne(ShaSize::TwoFiftySix)
    }

    #[test]
    fn invalid_digest_384() {
        digest_ne(ShaSize::ThreeEightyFour)
    }

    #[test]
    fn invalid_digest_512() {
        digest_ne(ShaSize::FiveTwelve)
    }

    #[test]
    fn parse_digest_256() {
        parse_digest(format!("SHA-256={}", D256));
    }

    #[test]
    fn parse_digest_384() {
        parse_digest(format!("SHA-384={}", D384));
    }

    #[test]
    fn parse_digest_512() {
        parse_digest(format!("SHA-512={}", D512));
    }

    #[test]
    fn invalid_parse_digest() {
        parse_digest_ne("not a valid digest");
    }

    #[test]
    fn parse_sha_256() {
        parse_sha("SHA-256");
    }

    #[test]
    fn parse_sha_384() {
        parse_sha("SHA-384");
    }

    #[test]
    fn parse_sha_512() {
        parse_sha("SHA-512");
    }

    #[test]
    fn invalid_parse_sha() {
        parse_sha_ne("SHA-420");
    }

    fn digest(provided: String, sha_size: ShaSize) {
        let some_body = b"The content of a thing";
        let body = RequestBody::new(some_body);
        let digest = body.digest(sha_size);

        assert_eq!(Digest::from_base64_and_size(provided, sha_size), digest);
    }

    fn digest_ne(sha_size: ShaSize) {
        let some_body = b"The content of a thing";
        let body = RequestBody::new(some_body);
        let digest = body.digest(sha_size);

        assert_ne!(
            Digest::from_base64_and_size("not a hash".to_owned(), sha_size),
            digest
        );
    }

    fn parse_digest(digest: String) {
        let d = digest.parse::<Digest>();

        assert!(d.is_ok());
    }

    fn parse_digest_ne(digest: &str) {
        let d = digest.parse::<Digest>();

        assert!(d.is_err());
    }

    fn parse_sha(sha: &str) {
        let s = sha.parse::<ShaSize>();

        assert!(s.is_ok());
    }

    fn parse_sha_ne(sha: &str) {
        let s = sha.parse::<ShaSize>();

        assert!(s.is_err());
    }
}