calmlens 0.40.0

Rust SDK for CalmLens moderation, storage and CDN delivery
Documentation
//! Asset grants and the info resource in the in-memory CDN.
use super::{cdn_response, custom, fail, text};
use crate::error::ErrorCode;
use crate::testing::decision::REGIONAL_STATUSES;
use crate::testing::jurisdictions::{EU_COUNTRIES, OPTIONAL_JURISDICTIONS};
use serde_json::{json, Value};
use std::collections::HashMap;

/// The asset segment of a URL that names the asset by its external ID starts with this.
pub(super) const EXTERNAL_ID_PREFIX: &str = "ext:";

/// Whether the CDN withholds an asset that is still being moderated, like the CDN
/// (AssetAvailability.ts): while the project's `blockUnmoderatedAssets` setting is on, a queued
/// or processing asset is not available.
pub(super) fn withheld_unmoderated(asset: &Value, settings: &Value) -> bool {
    settings["blockUnmoderatedAssets"] == true
        && matches!(
            text(&asset["classification"]["status"]),
            "queued" | "processing"
        )
}

/// How strict a moderation status is: `allowed` (or none) 0, then the regional statuses in order.
fn strictness(status: &str) -> usize {
    REGIONAL_STATUSES
        .iter()
        .position(|known| *known == status)
        .map_or(0, |index| index + 1)
}

/// Why the CDN refuses a viewer an asset for their region.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum RegionalRefusal {
    /// The asset's outcome depends on the region and the viewer claims name none.
    RegionRequired,
    /// A regional outcome blocks or purges the asset for the viewer's region.
    NotAvailable,
}
impl RegionalRefusal {
    pub(super) fn response(self) -> super::MockResponse {
        match self {
            Self::RegionRequired => custom(
                "viewer/region-required",
                403,
                "This asset needs the viewer's region",
            ),
            Self::NotAvailable => custom("asset/not-available", 403, "Asset is not available"),
        }
        .response()
    }
}

/// The moderation status in force for the viewer the claims describe, like the CDN: a decision's
/// regional outcomes (`classification.moderation.regions`) in a jurisdiction the project serves
/// apply to viewers whose `region` claim falls under it (a country's own, or `EU` for an EU member
/// country), and the strictest one stricter than the asset's own status wins. An asset with such
/// an outcome needs the claim. A refused viewer gets the reason instead.
pub(super) fn viewer_status<'a>(
    asset: &'a Value,
    settings: &Value,
    claims: &Value,
) -> Result<&'a str, RegionalRefusal> {
    let moderation = &asset["classification"]["moderation"];
    let base = text(&moderation["decision"]);
    // A project serves every jurisdiction except the optional ones it opted out of.
    let opted_out = settings["optOutJurisdictions"].as_array();
    let served = |region: &str| {
        !OPTIONAL_JURISDICTIONS.contains(&region)
            || !opted_out
                .into_iter()
                .flatten()
                .any(|opted_out| opted_out == region)
    };
    let stricter: Vec<(&str, &str)> = moderation["regions"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|entry| (text(&entry["region"]), text(&entry["status"])))
        .filter(|(region, status)| served(region) && strictness(status) > strictness(base))
        .collect();
    if stricter.is_empty() {
        return Ok(base);
    }
    let Some(viewer) = claims["region"].as_str() else {
        return Err(RegionalRefusal::RegionRequired);
    };
    let in_eu = EU_COUNTRIES.contains(&viewer);
    let strictest = stricter
        .into_iter()
        .filter(|(region, _)| *region == viewer || (*region == "EU" && in_eu))
        .map(|(_, status)| status)
        .max_by_key(|status| strictness(status));
    match strictest {
        Some("blocked" | "purged") => Err(RegionalRefusal::NotAvailable),
        Some(status) => Ok(status),
        None => Ok(base),
    }
}

/// The info resource, like the CDN's (AssetInfo.ts): the allowlisted fields and whether the
/// viewer the claims describe can see the content, decided as the other resources decide it. A
/// private asset's info needs a grant or an API key with `assets:download`.
pub(super) fn serve_info(
    asset: &Value,
    authorised: bool,
    q: &HashMap<String, String>,
    settings: &Value,
) -> super::MockResponse {
    let private = asset["visibility"] != "public";
    if private && !authorised {
        return custom("asset/not-found", 404, "Asset not found").response();
    }
    let claims = match q.get("viewerClaims") {
        None => Value::Null,
        Some(raw) => match serde_json::from_str::<Value>(raw) {
            Ok(claims) => claims,
            Err(_) => {
                return fail(ErrorCode::InvalidViewerClaims, "Invalid viewer claims").response()
            }
        },
    };
    let content = &asset["content"];
    let classification = &asset["classification"];
    let status = text(&classification["moderation"]["decision"]);
    let restricted = private || status == "blocked" || status == "purged";
    if restricted && !authorised {
        return custom("asset/not-available", 403, "Asset is not available").response();
    }
    let availability = if !content["safetyHold"].is_null()
        || asset["upload"]["status"] == "uploading"
        || status == "blocked"
        || status == "purged"
        || classification["status"] == "failed"
        || withheld_unmoderated(asset, settings)
        || content["status"] == "removed"
    {
        "unavailable"
    } else {
        match viewer_status(asset, settings, &claims) {
            Err(_) => "unavailable",
            Ok("age-restricted") if claims["ageConfirmed"] != true => "age-restricted",
            Ok(_) => "available",
        }
    };
    let info = json!({
        "id": asset["id"], "projectId": asset["projectId"], "type": asset["type"],
        "externalUrl": asset["externalUrl"],
        "content": {
            "format": content["format"], "width": content["width"], "height": content["height"],
            "durationSeconds": content["durationSeconds"], "pageCount": content["pageCount"],
            "rendered": content["rendered"], "preview": content["preview"], "hls": content["hls"],
        },
        "availability": availability,
    });
    let cache = if restricted {
        "private, no-store"
    } else {
        "public, no-cache"
    };
    cdn_response(
        info.to_string().into_bytes(),
        &[
            ("content-type", "application/json".into()),
            ("cache-control", cache.into()),
            ("cache-tag", format!("asset-{}", text(&asset["id"]))),
        ],
    )
}