Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsided committed Jun 24, 2023
0 parents commit 4eec7ff
Show file tree
Hide file tree
Showing 6 changed files with 197 additions and 0 deletions.
24 changes: 24 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Rust

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

env:
CARGO_TERM_COLOR: always

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --tests --verbose
- name: Run doctests
run: cargo test --doc --verbose
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/target
/Cargo.lock
/.idea
16 changes: 16 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "headers-content-md5"
description = "typed Content-MD5 header"
version = "0.1.0"
readme = "README.md"
license-file = "LICENSE"
repository = "https://github.com/sunsided/hyperium-headers-content-md5"
authors = ["Markus Mayer <widemeadows@gmail.com>"]
keywords = ["http", "headers", "hyper", "hyperium"]
categories = ["web-programming"]
edition = "2021"

[dependencies]
base64 = "0.21.2"
headers = "0.3.8"
http = "0.2.0"
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright (c) 2023 Markus Mayer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Content-MD5 header support for hyperium/headers

This adds the [RFC1864](https://datatracker.ietf.org/doc/html/rfc1864) `Content-MD5` header as a typed header:

```rust
use headers::Header;
use http::HeaderValue;
use headers_content_md5::ContentMd5;

fn it_works() {
let value = HeaderValue::from_static("Q2hlY2sgSW50ZWdyaXR5IQ==");
let md5 = ContentMd5::decode(&mut [&value].into_iter()).unwrap();

let expected = "Check Integrity!".as_bytes().try_into().unwrap();
assert_eq!(md5, ContentMd5(expected))
}
```
117 changes: 117 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
//! Provides the [`ContentMd5`] typed header.
//!
//! # Example
//!
//! ```
//! use headers::Header;
//! use http::HeaderValue;
//! use headers_content_md5::ContentMd5;
//!
//! let value = HeaderValue::from_static("Q2hlY2sgSW50ZWdyaXR5IQ==");
//! let md5 = ContentMd5::decode(&mut [&value].into_iter()).unwrap();
//! assert_eq!(md5.0, "Check Integrity!".as_bytes())
//! ```

#![deny(unsafe_code)]
#![deny(unused_must_use)]

use base64::{engine::general_purpose::STANDARD as base64, Engine};
use headers::{Header, HeaderValue};

/// `Content-MD5` header, defined in
/// [RFC1864](https://datatracker.ietf.org/doc/html/rfc1864)
///
/// ## Example values
///
/// * `Q2hlY2sgSW50ZWdyaXR5IQ==`
///
/// # Example
///
/// Decoding:
///
/// ```
/// use headers::Header;
/// use http::HeaderValue;
/// use headers_content_md5::ContentMd5;
///
/// let value = HeaderValue::from_static("Q2hlY2sgSW50ZWdyaXR5IQ==");
/// let mut values = [&value].into_iter();
///
/// let md5 = ContentMd5::decode(&mut values).unwrap();
/// assert_eq!(md5.0, "Check Integrity!".as_bytes())
/// ```
///
/// Encoding:
///
/// ```
/// use headers::Header;
/// use http::HeaderValue;
/// use headers_content_md5::ContentMd5;
///
/// let value = HeaderValue::from_static("Q2hlY2sgSW50ZWdyaXR5IQ==");
/// let md5 = ContentMd5("Check Integrity!".as_bytes().try_into().unwrap());
///
/// let mut header = Vec::default();
/// md5.encode(&mut header);
/// assert_eq!(header[0], "Q2hlY2sgSW50ZWdyaXR5IQ==");
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContentMd5(pub [u8; 16]);

static CONTENT_MD5: http::header::HeaderName = http::header::HeaderName::from_static("content-md5");

impl Header for ContentMd5 {
fn name() -> &'static http::header::HeaderName {
&CONTENT_MD5
}

fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(
values: &mut I,
) -> Result<Self, headers::Error> {
let value = values.next().ok_or_else(headers::Error::invalid)?;

// Ensure base64 encoded length fits the expected MD5 digest length.
if value.len() < 22 || value.len() > 24 {
return Err(headers::Error::invalid());
}

let value = value.to_str().map_err(|_| headers::Error::invalid())?;
let mut buffer = [0; 18];
base64
.decode_slice(value, &mut buffer)
.map_err(|_| headers::Error::invalid())?;
let mut slice = [0; 16];
slice.copy_from_slice(&buffer[..16]);
Ok(Self(slice))
}

fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
let encoded = base64.encode(self.0);
if let Ok(value) = HeaderValue::from_str(&encoded) {
values.extend(std::iter::once(value));
}
}
}

#[cfg(test)]
mod tests {
use crate::ContentMd5;
use headers::Header;
use http::HeaderValue;

#[test]
fn decode_works() {
let value = HeaderValue::from_static("Q2hlY2sgSW50ZWdyaXR5IQ==");
let md5 = ContentMd5::decode(&mut [&value].into_iter()).unwrap();
assert_eq!(md5.0, "Check Integrity!".as_bytes())
}

#[test]
fn encode_works() {
let value = HeaderValue::from_static("Q2hlY2sgSW50ZWdyaXR5IQ==");
let md5 = ContentMd5("Check Integrity!".as_bytes().try_into().unwrap());
let mut header = Vec::default();
md5.encode(&mut header);
assert_eq!(header[0], "Q2hlY2sgSW50ZWdyaXR5IQ==");
}
}

0 comments on commit 4eec7ff

Please sign in to comment.