calmlens 0.44.0

Rust SDK for CalmLens moderation, storage and CDN delivery
Documentation
//! Asset grants signed with an API key, as `packages/shared/src/AssetUrlSigning.ts` signs them:
//! the segment of a signed asset URL that takes the asset's place. The CDN finds the key the grant
//! names among the project's keys and checks the signature against the key's stored hash.
use base64::Engine;
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};

/// The prefix of a grant's token.
const TOKEN_PREFIX: &str = "sig_";
/// A key-signed grant's payload starts with this version marker.
const VERSION: &str = "k1";
/// Bytes of the HMAC-SHA256 a grant keeps: 128 bits.
const MAC_BYTES: usize = 16;
/// Bytes of the key ID: 72 bits, 12 base64url characters.
const KEY_ID_BYTES: usize = 9;
// Domain-separate these hashes and signatures from every other made with the same secret.
const KEY_ID_CONTEXT: &str = "calmlens-asset-grant-key-id:v1:";
const MAC_CONTEXT: &str = "calmlens-asset-grant-key:v1";

/// The asset a grant names: by ID, or by the external ID it was uploaded with.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum GrantAsset {
    Id(String),
    ExternalId(String),
}

/// What a grant grants: one asset of one project, the original file or not, until it expires.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GrantClaims {
    pub project_id: String,
    pub asset: GrantAsset,
    pub original: bool,
    /// Milliseconds since the Unix epoch; the grant carries it rounded up to the second.
    pub expires_at: u64,
}

/// The signing secret: the lowercase hex SHA-256 of the API key, which CalmLens stores.
fn signing_secret(api_key: &str) -> String {
    hex(&Sha256::digest(api_key.as_bytes()))
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

/// The ID a grant names its key by: a hash of the key's signing secret.
fn key_id(secret: &str) -> String {
    let digest = Sha256::digest(format!("{KEY_ID_CONTEXT}{secret}").as_bytes());
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&digest[..KEY_ID_BYTES])
}

fn mac(secret: &str, project_id: &str, payload: &str) -> [u8; MAC_BYTES] {
    let mut mac =
        Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length");
    mac.update(format!("{MAC_CONTEXT}\n{project_id}\n{payload}").as_bytes());
    let mut truncated = [0; MAC_BYTES];
    truncated.copy_from_slice(&mac.finalize().into_bytes()[..MAC_BYTES]);
    truncated
}

/// Base 36, lowercase, as JavaScript's `Number.prototype.toString(36)` writes a whole number.
fn base36(mut value: u64) -> String {
    const DIGITS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
    let mut out = Vec::new();
    loop {
        out.push(DIGITS[(value % 36) as usize]);
        value /= 36;
        if value == 0 {
            break;
        }
    }
    out.reverse();
    String::from_utf8(out).expect("ASCII digits")
}

/// Signs `claims` with `api_key` and returns the grant's token: `sig_` and the base64url of the
/// payload `k1.<key ID>.<expiry in seconds, base 36>.<o or nothing>.<asset>` followed by its MAC.
pub(crate) fn sign(claims: &GrantClaims, api_key: &str) -> String {
    let secret = signing_secret(api_key);
    let asset = match &claims.asset {
        GrantAsset::Id(id) => id.clone(),
        GrantAsset::ExternalId(external_id) => format!("ext:{external_id}"),
    };
    let payload = [
        VERSION,
        &key_id(&secret),
        &base36(claims.expires_at.div_ceil(1000)),
        if claims.original { "o" } else { "" },
        &asset,
    ]
    .join(".");
    let mut signed = payload.clone().into_bytes();
    signed.extend_from_slice(&mac(&secret, &claims.project_id, &payload));
    format!(
        "{TOKEN_PREFIX}{}",
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signed)
    )
}

/// Reads and checks a grant token for `project_id` signed with `api_key`, as the CDN does:
/// `None` when it isn't one, names another key, or its signature doesn't match. The expiry is
/// returned for the caller to check.
#[cfg(feature = "testing")]
pub(crate) fn verify(token: &str, project_id: &str, api_key: &str) -> Option<GrantClaims> {
    let encoded = token.strip_prefix(TOKEN_PREFIX)?;
    let signed = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(encoded)
        .ok()?;
    let split = signed.len().checked_sub(MAC_BYTES)?;
    let (payload, given) = signed.split_at(split);
    let payload = std::str::from_utf8(payload).ok()?;
    let mut parts = payload.splitn(5, '.');
    let (version, key, expiry, flags, asset) = (
        parts.next()?,
        parts.next()?,
        parts.next()?,
        parts.next()?,
        parts.next()?,
    );
    let secret = signing_secret(api_key);
    if version != VERSION || key != key_id(&secret) || !matches!(flags, "" | "o") {
        return None;
    }
    if expiry.is_empty()
        || !expiry
            .bytes()
            .all(|byte| byte.is_ascii_digit() || byte.is_ascii_lowercase())
    {
        return None;
    }
    let expires_at = u64::from_str_radix(expiry, 36).ok()?.checked_mul(1000)?;
    let asset = match asset.strip_prefix("ext:") {
        Some("") => return None,
        Some(external_id) => GrantAsset::ExternalId(external_id.to_owned()),
        None if asset.starts_with("asset_") => GrantAsset::Id(asset.to_owned()),
        None => return None,
    };
    let expected = mac(&secret, project_id, payload);
    // Compare in constant time, as the CDN does.
    if given.len() != expected.len()
        || given
            .iter()
            .zip(expected)
            .fold(0, |diff, (a, b)| diff | (a ^ b))
            != 0
    {
        return None;
    }
    Some(GrantClaims {
        project_id: project_id.to_owned(),
        asset,
        original: flags == "o",
        expires_at,
    })
}

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

    const API_KEY: &str = "clsk_test_0123456789abcdefghijklmnopqrstuv";
    const PROJECT: &str = "proj_test1234567890abcd";

    // Tokens from `signAssetGrant` in packages/shared/src/AssetUrlSigning.ts with these inputs.
    #[test]
    fn signs_as_the_shared_reference_does() {
        let by_id = GrantClaims {
            project_id: PROJECT.into(),
            asset: GrantAsset::Id("asset_e5Gm2Rk8XqT3wLp9VbN4".into()),
            original: false,
            expires_at: 1_767_225_600_123,
        };
        assert_eq!(
            sign(&by_id, API_KEY),
            "sig_azEuZGtGMW9iaVBKSkhxLnQ4NXMwMS4uYXNzZXRfZTVHbTJSazhYcVQzd0xwOVZiTjRD9LDa-KsXMOUjzGydcus2"
        );
        let by_external_id = GrantClaims {
            project_id: PROJECT.into(),
            asset: GrantAsset::ExternalId("posts/9.v2 ünï".into()),
            original: true,
            expires_at: 1_767_225_600_000,
        };
        assert_eq!(
            sign(&by_external_id, API_KEY),
            "sig_azEuZGtGMW9iaVBKSkhxLnQ4NXMwMC5vLmV4dDpwb3N0cy85LnYyIMO8bsOvVyAmMtBvQMNQhVhBUIpgZA"
        );
    }

    #[cfg(feature = "testing")]
    #[test]
    fn verifies_only_its_own_key_and_project() {
        let claims = GrantClaims {
            project_id: PROJECT.into(),
            asset: GrantAsset::ExternalId("a.b".into()),
            original: true,
            expires_at: 1_767_225_601_000,
        };
        let token = sign(&claims, API_KEY);
        assert_eq!(verify(&token, PROJECT, API_KEY), Some(claims));
        assert_eq!(verify(&token, "proj_other", API_KEY), None);
        assert_eq!(verify(&token, PROJECT, "clsk_test_other"), None);
    }
}