Skip to main content

rust_embed_url/
lib.rs

1//! # rust-embed-url
2//!
3//! A procedural macro for embedding URL content at compile time with SHA-256 hash verification.
4//!
5//! ## Features
6//!
7//! - Fetches URL content during compilation
8//! - Verifies content integrity using SHA-256 checksums
9//! - Returns embedded bytes as `Box<[u8]>`
10//! - Fails fast with clear error messages on mismatch or network failures
11//!
12//! ## Usage
13//!
14//! ```rust,ignore
15//! use rust_embed_url::embed_url;
16//!
17//! fn main() {
18//!     let data = embed_url!(
19//!         "https://example.com",
20//!         "ZmY2N2E5ZDc2NGQ2YTIzNjdhMTg3NzM0ZTY5N2Y2YTUzMjE3ZGI5YTIxYzEwMWQ0MTBhMTEzY2E4NzFhMjk5ZAo="
21//!     );
22//!     let content = String::from_utf8(data.into()).unwrap();
23//!     println!("{}", content);
24//! }
25//! ```
26//!
27//! ## Computing the Hash
28//!
29//! To compute the SHA-256 hash (base64 encoded) for your URL:
30//!
31//! ```bash
32//! curl -s "https://example.com" | sha256sum | cut -d' ' -f1 | base64
33//! ```
34
35use base64::prelude::*;
36use reqwest::Url;
37use sha2::{Digest, Sha256};
38use std::str::FromStr;
39use syn::{LitStr, Token, parse::Parse, parse_macro_input};
40
41/// Parsed macro input containing URL and expected hash.
42struct UrlWithHash {
43    /// The URL to fetch content from.
44    url: LitStr,
45    /// Expected SHA-256 hash (base64 encoded) of the content.
46    hash: LitStr,
47}
48
49impl Parse for UrlWithHash {
50    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
51        let url = input.parse()?;
52        let _: Token![,] = input.parse()?;
53        let hash = input.parse()?;
54        Ok(UrlWithHash { url, hash })
55    }
56}
57
58/// Computes SHA-256 hash of bytes and returns base64-encoded result.
59fn hash_bytes_b64_sha256(data: &[u8]) -> String {
60    BASE64_STANDARD.encode(Sha256::digest(data))
61}
62
63/// Procedural macro that embeds URL content at compile time with hash verification.
64///
65/// # Arguments
66///
67/// * `url` - The URL to fetch (string literal)
68/// * `hash` - Expected SHA-256 hash of the content, base64 encoded (string literal)
69///
70/// # Returns
71///
72/// Returns a `Box<[u8]>` containing the fetched content.
73///
74/// # Compile-time Errors
75///
76/// This macro will fail to compile if:
77/// - The URL is invalid
78/// - The network request fails
79/// - The response status is not 2xx
80/// - The computed hash doesn't match the expected hash
81///
82/// # Example
83///
84/// ```rust,ignore
85/// let html = embed_url!("https://example.com", "ZmY2N2E5...");
86/// ```
87#[proc_macro]
88pub fn embed_url(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
89    let UrlWithHash { url, hash } = parse_macro_input!(item as UrlWithHash);
90
91    let url_str = url.value();
92    let expected_hash = hash.value();
93
94    // Validate and parse URL
95    let url = Url::parse(url_str.as_str()).unwrap_or_else(|e| {
96        panic!("Invalid URL '{}': {}", url_str, e);
97    });
98
99    // Fetch content from URL
100    let response = reqwest::blocking::get(url.as_str()).unwrap_or_else(|e| {
101        panic!("Failed to fetch URL '{}': {}", url_str, e);
102    });
103
104    // Verify HTTP status code
105    let status_code = response.status().as_u16();
106    if !(200..300).contains(&status_code) {
107        let error_body = response.text().unwrap_or_default();
108        panic!(
109            "Failed to fetch URL '{}': HTTP {} {}",
110            url_str,
111            status_code,
112            error_body.lines().next().unwrap_or("Unknown error")
113        );
114    }
115
116    // Extract response bytes
117    let bytes = response.bytes().unwrap_or_else(|e| {
118        panic!("Failed to read response body from '{}': {}", url_str, e);
119    });
120
121    // Verify content integrity using SHA-256 hash
122    let computed_hash = hash_bytes_b64_sha256(&bytes);
123    if computed_hash != expected_hash {
124        panic!(
125            "Hash verification failed for URL '{}'.\n\
126             Expected: {}\n\
127             Computed: {}",
128            url_str, expected_hash, computed_hash
129        );
130    }
131
132    // Generate Rust byte array literal
133    let byte_literals: Vec<String> = bytes.iter().map(|b| format!("0x{:02x}", b)).collect();
134    let array_content = byte_literals.join(",");
135
136    // Return as Box<[u8]> via intermediate array
137    let output = format!(
138        "{{ let data = [{}]; let bytes: Box<[u8]> = data.into(); bytes }}",
139        array_content
140    );
141
142    proc_macro::TokenStream::from_str(&output).unwrap()
143}