geolith-dataset-builder 0.4.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
//! A hand-written `SigV4` signer for the dataset bucket and the `CDSE` `S3` endpoints.
//!
//! Four canonical pieces (method, URI, query, headers) and one `HMAC` chain;
//! the AWS documentation's published examples are the tests' expected
//! values. Keys and the secret never leave [`Credentials`], whose `Debug`
//! prints the secret as `<redacted>`.

use std::fmt;

use crate::error::{DatasetError, Result};
use hmac::{Hmac, KeyInit as _, Mac as _};
use sha2::{Digest as _, Sha256};

/// The service the requests go to.
pub const SERVICE: &str = "s3";

/// An access key id and its secret. The `Debug` impl never prints the secret.
#[derive(Clone, PartialEq, Eq)]
pub struct Credentials {
    /// Access key id.
    pub key_id: String,
    /// Secret access key.
    pub secret: String,
}

impl fmt::Debug for Credentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Credentials")
            .field("key_id", &self.key_id)
            .field("secret", &"<redacted>")
            .finish()
    }
}

/// A request to sign: what the client is about to send.
#[derive(Debug, Clone)]
pub struct SignableRequest<'a> {
    /// `GET`, `PUT`, `POST`, `DELETE`, `HEAD`.
    pub method: &'a str,
    /// Host header value, port included when not 443/80.
    pub host: &'a str,
    /// Path with a leading `/` (already includes the bucket).
    pub path: &'a str,
    /// Query parameters, in any order.
    pub query: Vec<(String, String)>,
    /// Headers to sign (host and the `x-amz-*` ones are added).
    pub headers: Vec<(String, String)>,
    /// `sha256` of the payload; the empty payload's digest for no body.
    pub payload_sha256: [u8; 32],
}

/// The lower-case hex of a digest.
fn hex(digest: &[u8]) -> String {
    use std::fmt::Write as _;
    digest.iter().fold(String::new(), |mut out, byte| {
        let _ = write!(out, "{byte:02x}");
        out
    })
}

/// The `sha256` of `bytes`.
#[must_use]
pub fn sha256(bytes: &[u8]) -> [u8; 32] {
    Sha256::digest(bytes).into()
}

/// The `sha256` of the empty payload.
#[must_use]
pub fn empty_payload_sha256() -> [u8; 32] {
    sha256(b"")
}

/// RFC 3986 percent-encoding; `/` is kept when `keep_slash`.
fn encode(text: &str, keep_slash: bool) -> String {
    use std::fmt::Write as _;
    let mut out = String::with_capacity(text.len());
    for byte in text.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
            out.push(char::from(byte));
        } else if byte == b'/' && keep_slash {
            out.push('/');
        } else {
            let _ = write!(out, "%{byte:02X}");
        }
    }
    out
}

/// The canonical query string: encoded, sorted by key then value.
#[must_use]
pub fn canonical_query(query: &[(String, String)]) -> String {
    let mut pairs: Vec<(String, String)> = query
        .iter()
        .map(|(key, value)| (encode(key, false), encode(value, false)))
        .collect();
    pairs.sort();
    pairs
        .into_iter()
        .map(|(key, value)| format!("{key}={value}"))
        .collect::<Vec<_>>()
        .join("&")
}

/// `HMAC-SHA256(key, data)`.
fn hmac(key: &[u8], data: &[u8]) -> [u8; 32] {
    let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC accepts any key length");
    mac.update(data);
    mac.finalize().into_bytes().into()
}

/// The signature of a canonical request, given its string to sign pieces.
fn signature(secret: &str, region: &str, date: &str, string_to_sign: &str) -> String {
    let key = hmac(format!("AWS4{secret}").as_bytes(), date.as_bytes());
    let key = hmac(&key, region.as_bytes());
    let key = hmac(&key, SERVICE.as_bytes());
    let key = hmac(&key, b"aws4_request");
    hex(&hmac(&key, string_to_sign.as_bytes()))
}

/// The canonical request of `request`, its headers already sorted and its
/// signed-header list joined.
#[must_use]
pub fn canonical_request(
    request: &SignableRequest<'_>,
    canonical_headers: &str,
    signed_headers: &str,
    payload: &str,
) -> String {
    format!(
        "{}\n{}\n{}\n{canonical_headers}\n{signed_headers}\n{payload}",
        request.method,
        encode(request.path, true),
        canonical_query(&request.query),
    )
}

/// Sign `request`; returns the headers to add (`Authorization`, `x-amz-date`,
/// `x-amz-content-sha256`).
///
/// # Errors
///
/// Fails when `amz_date` is not `YYYYMMDDTHHMMSSZ`.
pub fn sign(
    request: &SignableRequest<'_>,
    credentials: &Credentials,
    region: &str,
    amz_date: &str,
) -> Result<Vec<(String, String)>> {
    let bytes = amz_date.as_bytes();
    if bytes.len() != 16 || bytes[8] != b'T' || bytes[15] != b'Z' {
        return Err(DatasetError::storage(format!(
            "amz_date {amz_date:?} is not YYYYMMDDTHHMMSSZ"
        )));
    }
    let payload = hex(&request.payload_sha256);
    let mut headers: Vec<(String, String)> = request
        .headers
        .iter()
        .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_owned()))
        .filter(|(name, _)| {
            !matches!(
                name.as_str(),
                "host" | "x-amz-date" | "x-amz-content-sha256"
            )
        })
        .collect();
    headers.push(("host".to_owned(), request.host.to_owned()));
    headers.push(("x-amz-content-sha256".to_owned(), payload.clone()));
    headers.push(("x-amz-date".to_owned(), amz_date.to_owned()));
    headers.sort_by(|a, b| a.0.cmp(&b.0));

    let signed: Vec<String> = headers.iter().map(|(name, _)| name.clone()).collect();
    let signed_headers = signed.join(";");
    let canonical_headers: String = headers
        .iter()
        .map(|(name, value)| format!("{name}:{value}\n"))
        .collect();
    let canonical_request =
        canonical_request(request, &canonical_headers, &signed_headers, &payload);
    let date = &amz_date[..8];
    let scope = format!("{date}/{region}/{SERVICE}/aws4_request");
    let string_to_sign = format!(
        "AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}",
        hex(&sha256(canonical_request.as_bytes()))
    );
    let signature = signature(&credentials.secret, region, date, &string_to_sign);
    Ok(vec![
        (
            "Authorization".to_owned(),
            format!(
                "AWS4-HMAC-SHA256 Credential={}/{scope}, SignedHeaders={signed_headers}, Signature={signature}",
                credentials.key_id
            ),
        ),
        ("x-amz-date".to_owned(), amz_date.to_owned()),
        ("x-amz-content-sha256".to_owned(), payload),
    ])
}

/// `YYYYMMDDTHHMMSSZ` of the Unix second `unix`.
#[must_use]
pub fn amz_date(unix: i64) -> String {
    let iso = crate::layout::format_utc(unix);
    iso.replace(['-', ':'], "")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn header<'a>(headers: &'a [(String, String)], name: &str) -> &'a str {
        headers
            .iter()
            .find(|(key, _)| key.eq_ignore_ascii_case(name))
            .map_or("", |(_, value)| value.as_str())
    }

    /// The AWS documentation's "Signature Calculations for the Authorization
    /// Header": `GET /test.txt`, empty body, 24 May 2013.
    #[test]
    fn the_aws_sigv4_test_suite_get_object_signature_matches() {
        let request = SignableRequest {
            method: "GET",
            host: "examplebucket.s3.amazonaws.com",
            path: "/test.txt",
            query: Vec::new(),
            headers: vec![("range".to_owned(), "bytes=0-9".to_owned())],
            payload_sha256: empty_payload_sha256(),
        };
        let headers = sign(
            &request,
            &Credentials {
                key_id: "AKIAIOSFODNN7EXAMPLE".to_owned(),
                secret: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_owned(),
            },
            "us-east-1",
            "20130524T000000Z",
        )
        .expect("sign");
        assert_eq!(
            header(&headers, "Authorization"),
            "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, \
SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, \
Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
        );
    }

    /// The documented canonical request and its hash.
    #[test]
    fn the_documented_canonical_request_hashes_to_its_published_value() {
        let request = SignableRequest {
            method: "GET",
            host: "examplebucket.s3.amazonaws.com",
            path: "/test.txt",
            query: Vec::new(),
            headers: vec![("range".to_owned(), "bytes=0-9".to_owned())],
            payload_sha256: empty_payload_sha256(),
        };
        let payload = hex(&empty_payload_sha256());
        let canonical = canonical_request(
            &request,
            "host:examplebucket.s3.amazonaws.com\nrange:bytes=0-9\nx-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\nx-amz-date:20130524T000000Z\n",
            "host;range;x-amz-content-sha256;x-amz-date",
            &payload,
        );
        println!("{canonical:?}");
        assert_eq!(
            hex(&sha256(canonical.as_bytes())),
            "7344ae5b7ee6c3e7e6b0fe0640412a37625d1fbfff95c48bbb2dc43964946972"
        );
    }

    /// RFC 4231 test case 1: the `HMAC` primitive the chain is built from.
    #[test]
    fn the_rfc4231_hmac_sha256_vector_matches() {
        assert_eq!(
            hex(&hmac(&[0x0b; 20], b"Hi There")),
            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
        );
    }

    #[test]
    fn credentials_never_print_their_secret() {
        let credentials = Credentials {
            key_id: "id".to_owned(),
            secret: "SECRETX".to_owned(),
        };
        assert!(!format!("{credentials:?}").contains("SECRETX"));
    }

    #[test]
    fn a_query_is_encoded_and_sorted() {
        assert_eq!(
            canonical_query(&[
                ("uploadId".to_owned(), "a b".to_owned()),
                ("partNumber".to_owned(), "2".to_owned()),
                ("list-type".to_owned(), "2".to_owned()),
            ]),
            "list-type=2&partNumber=2&uploadId=a%20b"
        );
    }

    #[test]
    fn a_path_keeps_its_slashes_and_encodes_the_rest() {
        assert_eq!(
            encode("/datasets/rain fall/x.json", true),
            "/datasets/rain%20fall/x.json"
        );
        assert_eq!(encode("a/b", false), "a%2Fb");
    }

    #[test]
    fn an_amz_date_is_the_compact_utc_stamp() {
        assert_eq!(amz_date(1_369_353_600), "20130524T000000Z");
    }
}