winterbaume-core 0.3.3

Core library for winterbaume - AWS service mocking for Rust
Documentation
/// Extract the AWS service name from a request URI.
///
/// Parses the host from URIs like `https://sts.us-east-1.amazonaws.com/`
/// and returns the service name (e.g., "sts").
pub fn extract_service_from_uri(uri: &str) -> Option<String> {
    let host = extract_host(uri)?;
    // AWS endpoint pattern: {service}.{region}.amazonaws.com
    // or: {service}.amazonaws.com (global)
    let first_dot = host.find('.')?;
    let service = &host[..first_dot];
    if service.is_empty() {
        return None;
    }
    Some(service.to_string())
}

/// Extract the AWS region from a request URI.
///
/// Parses URIs like `https://sts.us-east-1.amazonaws.com/`
/// and returns the region (e.g., "us-east-1").
/// Falls back to "us-east-1" if the region cannot be determined.
pub fn extract_region_from_uri(uri: &str) -> String {
    if let Some(host) = extract_host(uri) {
        // Pattern: {service}.{region}.amazonaws.com
        let parts: Vec<&str> = host.split('.').collect();
        if parts.len() >= 4 && parts[parts.len() - 2] == "amazonaws" {
            return parts[1].to_string();
        }
    }
    "us-east-1".to_string()
}

/// The AWS region of a request: from the endpoint host when it is an AWS
/// endpoint, otherwise from the SigV4 credential scope ( requests sent to
/// `winterbaume-server` at a local address ), otherwise `us-east-1`.
pub fn extract_region(uri: &str, headers: &http::HeaderMap) -> String {
    let from_host = extract_host(uri).and_then(|host| {
        let parts: Vec<&str> = host.split('.').collect();
        (parts.len() >= 4 && parts[parts.len() - 2] == "amazonaws").then(|| parts[1].to_string())
    });
    from_host
        .or_else(|| {
            credential_scope(uri, headers)
                .map(|scope| scope.region)
                .filter(|r| {
                    !r.is_empty() && r.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
                })
        })
        .unwrap_or_else(|| "us-east-1".to_string())
}

/// The SigV4 credential scope of a request:
/// `<access key>/<date>/<region>/<service>/aws4_request`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialScope {
    pub access_key: String,
    pub date: String,
    pub region: String,
    pub service: String,
}

impl CredentialScope {
    fn parse(credential: &str) -> Option<Self> {
        let mut parts = credential.split('/');
        let scope = Self {
            access_key: parts.next()?.to_string(),
            date: parts.next()?.to_string(),
            region: parts.next()?.to_string(),
            service: parts.next()?.to_string(),
        };
        (!scope.service.is_empty()).then_some(scope)
    }
}

/// The credential scope a request is signed with: from the SigV4
/// `Authorization` header, or from `X-Amz-Credential` of a presigned URL.
/// The signature is not checked.
pub fn credential_scope(uri: &str, headers: &http::HeaderMap) -> Option<CredentialScope> {
    extract_credential_from_headers(headers)
        .or_else(|| query_parameter(uri, "X-Amz-Credential"))
        .and_then(|credential| CredentialScope::parse(&credential))
}

/// Whether a request carries an AWS signature of any kind: an
/// `Authorization` header ( SigV4, or S3's SigV2 `AWS <key>:<signature>` ), or
/// a presigned URL ( SigV4 `X-Amz-Credential`, or SigV2 `AWSAccessKeyId` with
/// `Signature` ).  A request without one is anonymous.
pub fn is_signed(uri: &str, headers: &http::HeaderMap) -> bool {
    headers.contains_key(http::header::AUTHORIZATION)
        || query_parameter(uri, "X-Amz-Credential").is_some()
        || (query_parameter(uri, "AWSAccessKeyId").is_some()
            && query_parameter(uri, "Signature").is_some())
}

/// The service a request names through its signature, for a request sent
/// to an address that is not an AWS endpoint: the service of its SigV4
/// credential scope ( header or presigned URL ).  Requests without one, being
/// anonymous or signed with SigV2, can only be for S3, the one service that
/// still accepts them.
pub fn extract_service_from_signature(uri: &str, headers: &http::HeaderMap) -> String {
    credential_scope(uri, headers)
        .map(|scope| scope.service)
        .unwrap_or_else(|| "s3".to_string())
}

/// Extract the AWS service name from the Authorization header's SigV4 credential scope.
///
/// Parses headers like:
/// `AWS4-HMAC-SHA256 Credential=AKID/20260224/us-east-1/s3/aws4_request, ...`
/// and returns the service name (e.g., "s3").
pub fn extract_service_from_headers(headers: &http::HeaderMap) -> Option<String> {
    let credential = extract_credential_from_headers(headers)?;
    // Credential format: AKID/date/region/service/aws4_request
    let parts: Vec<&str> = credential.split('/').collect();
    if parts.len() >= 4 {
        Some(parts[3].to_string())
    } else {
        None
    }
}

/// Extract the AWS region from the Authorization header's SigV4 credential scope.
///
/// Parses headers like:
/// `AWS4-HMAC-SHA256 Credential=AKID/20260224/us-east-1/s3/aws4_request, ...`
/// and returns the region (e.g., "us-east-1").
pub fn extract_region_from_headers(headers: &http::HeaderMap) -> Option<String> {
    let credential = extract_credential_from_headers(headers)?;
    // Credential format: AKID/date/region/service/aws4_request
    let parts: Vec<&str> = credential.split('/').collect();
    if parts.len() >= 3 {
        Some(parts[2].to_string())
    } else {
        None
    }
}

/// Extract the access key ID from the Authorization header's SigV4 credential scope.
///
/// Parses headers like:
/// `AWS4-HMAC-SHA256 Credential=AKID/20260224/us-east-1/s3/aws4_request, ...`
/// and returns the access key ID (e.g., "AKID"). The signature is not checked.
pub fn extract_access_key_from_headers(headers: &http::HeaderMap) -> Option<String> {
    let credential = extract_credential_from_headers(headers)?;
    // Credential format: AKID/date/region/service/aws4_request
    let access_key = credential.split('/').next()?;
    if access_key.is_empty() {
        None
    } else {
        Some(access_key.to_string())
    }
}

/// Extract the Credential value from a SigV4 Authorization header.
fn extract_credential_from_headers(headers: &http::HeaderMap) -> Option<String> {
    let auth = headers.get(http::header::AUTHORIZATION)?.to_str().ok()?;
    // Format: AWS4-HMAC-SHA256 Credential=..., SignedHeaders=..., Signature=...
    let credential_start = auth.find("Credential=")?;
    let after = &auth[credential_start + "Credential=".len()..];
    let end = after.find(',')?;
    Some(after[..end].to_string())
}

/// The percent-decoded value of query parameter `name`, if present.
fn query_parameter(uri: &str, name: &str) -> Option<String> {
    let query = uri.split_once('?')?.1;
    let query = query.split('#').next().unwrap_or(query);
    query.split('&').find_map(|pair| {
        let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
        (crate::protocol::common::percent_decode(key) == name)
            .then(|| crate::protocol::common::percent_decode(value))
    })
}

fn extract_host(uri: &str) -> Option<&str> {
    // Strip scheme
    let after_scheme = uri
        .strip_prefix("https://")
        .or_else(|| uri.strip_prefix("http://"))?;
    // Take everything before the first '/' or end
    let host = after_scheme.split('/').next()?;
    // Strip port if present
    let host = host.split(':').next()?;
    if host.is_empty() {
        return None;
    }
    Some(host)
}

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

    #[test]
    fn test_extract_service_regional() {
        assert_eq!(
            extract_service_from_uri("https://sts.us-east-1.amazonaws.com/"),
            Some("sts".to_string())
        );
    }

    #[test]
    fn test_extract_service_global() {
        assert_eq!(
            extract_service_from_uri("https://sts.amazonaws.com/"),
            Some("sts".to_string())
        );
    }

    #[test]
    fn test_extract_region() {
        assert_eq!(
            extract_region_from_uri("https://sts.us-west-2.amazonaws.com/"),
            "us-west-2"
        );
    }

    #[test]
    fn test_extract_region_global_falls_back() {
        assert_eq!(
            extract_region_from_uri("https://sts.amazonaws.com/"),
            "us-east-1"
        );
    }

    pub(super) fn make_auth_header(credential: &str) -> http::HeaderMap {
        let mut headers = http::HeaderMap::new();
        headers.insert(
            http::header::AUTHORIZATION,
            format!(
                "AWS4-HMAC-SHA256 Credential={}, SignedHeaders=host;x-amz-date, Signature=abc123",
                credential
            )
            .parse()
            .unwrap(),
        );
        headers
    }

    #[test]
    fn test_extract_service_from_headers() {
        let headers = make_auth_header("AKID/20260224/us-east-1/s3/aws4_request");
        assert_eq!(
            extract_service_from_headers(&headers),
            Some("s3".to_string())
        );
    }

    #[test]
    fn test_extract_region_from_headers() {
        let headers = make_auth_header("AKID/20260224/us-west-2/s3/aws4_request");
        assert_eq!(
            extract_region_from_headers(&headers),
            Some("us-west-2".to_string())
        );
    }

    #[test]
    fn test_extract_service_from_headers_missing() {
        let headers = http::HeaderMap::new();
        assert_eq!(extract_service_from_headers(&headers), None);
    }

    #[test]
    fn test_extract_service_from_headers_sts() {
        let headers = make_auth_header("AKID/20260224/us-east-1/sts/aws4_request");
        assert_eq!(
            extract_service_from_headers(&headers),
            Some("sts".to_string())
        );
    }

    #[test]
    fn test_extract_access_key_from_headers() {
        let headers = make_auth_header("ASIAEXAMPLE/20260224/us-east-1/sts/aws4_request");
        assert_eq!(
            extract_access_key_from_headers(&headers),
            Some("ASIAEXAMPLE".to_string())
        );
        let headers = make_auth_header("/20260224/us-east-1/sts/aws4_request");
        assert_eq!(extract_access_key_from_headers(&headers), None);
        assert_eq!(
            extract_access_key_from_headers(&http::HeaderMap::new()),
            None
        );
    }
}

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

    #[test]
    fn presigned_urls_carry_their_credential_scope_in_the_query() {
        let uri = "http://127.0.0.1:4566/bucket/key.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256\
                   &X-Amz-Credential=test%2F20261125%2Feu-west-1%2Fs3%2Faws4_request\
                   &X-Amz-Date=20261125T000000Z&X-Amz-Expires=300&X-Amz-SignedHeaders=host\
                   &X-Amz-Signature=abc";
        let headers = http::HeaderMap::new();
        let scope = credential_scope(uri, &headers).unwrap();
        assert_eq!(scope.access_key, "test");
        assert_eq!(scope.region, "eu-west-1");
        assert_eq!(scope.service, "s3");
        assert_eq!(extract_service_from_signature(uri, &headers), "s3");
        assert_eq!(extract_region(uri, &headers), "eu-west-1");
        assert!(is_signed(uri, &headers));
    }

    #[test]
    fn the_authorization_header_wins_over_the_query() {
        let headers = super::tests::make_auth_header("AKID/20260224/us-west-2/sqs/aws4_request");
        let uri =
            "http://127.0.0.1/?X-Amz-Credential=other%2F20260224%2Feu-west-1%2Fs3%2Faws4_request";
        assert_eq!(extract_service_from_signature(uri, &headers), "sqs");
        assert_eq!(extract_region(uri, &headers), "us-west-2");
    }

    #[test]
    fn unsigned_and_sigv2_requests_are_for_s3() {
        let empty = http::HeaderMap::new();
        let uri = "http://127.0.0.1:4566/bucket/key";
        assert!(!is_signed(uri, &empty));
        assert_eq!(extract_service_from_signature(uri, &empty), "s3");
        assert!(credential_scope(uri, &empty).is_none());

        let mut sigv2 = http::HeaderMap::new();
        sigv2.insert(
            http::header::AUTHORIZATION,
            "AWS AKIAIOSFODNN7EXAMPLE:c2lnbmF0dXJl".parse().unwrap(),
        );
        assert!(is_signed(uri, &sigv2));
        assert_eq!(extract_service_from_signature(uri, &sigv2), "s3");

        let presigned_v2 = "http://127.0.0.1/b/k?AWSAccessKeyId=AKID&Expires=1&Signature=x";
        assert!(is_signed(presigned_v2, &empty));
        // A parameter that only starts like one does not count.
        assert!(!is_signed(
            "http://127.0.0.1/b/k?X-Amz-Credentials=x",
            &empty
        ));
    }

    #[test]
    fn region_comes_from_the_host_then_the_credential_scope() {
        let mut headers = http::HeaderMap::new();
        headers.insert(
            "authorization",
            "AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-west-1/lambda/aws4_request, SignedHeaders=host, Signature=0"
                .parse()
                .unwrap(),
        );
        assert_eq!(
            extract_region("https://lambda.ap-south-1.amazonaws.com/x", &headers),
            "ap-south-1"
        );
        assert_eq!(
            extract_region("https://127.0.0.1:5555/x", &headers),
            "eu-west-1"
        );
        assert_eq!(
            extract_region("https://127.0.0.1:5555/x", &http::HeaderMap::new()),
            "us-east-1"
        );
    }
}