calmlens 0.46.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 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:";

/// The ISO 3166-1 alpha-2 countries a viewer's region can be, as the CDN's schema lists them. EU
/// is not a viewer country.
const VIEWER_COUNTRIES: &str = "AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW";

/// The viewer claims in the `viewerClaims` query parameter, like the CDN (ViewerClaims.ts):
/// absent claims are `null`; claims that aren't JSON, or aren't an object with an optional
/// country `region` and an optional boolean `ageConfirmed`, are `None`, which the CDN refuses
/// with [`invalid_viewer_claims`].
pub(super) fn read_viewer_claims(q: &HashMap<String, String>) -> Option<Value> {
    let Some(raw) = q.get("viewerClaims") else {
        return Some(Value::Null);
    };
    serde_json::from_str::<Value>(raw).ok().filter(|claims| {
        claims.is_object()
            && claims.get("region").is_none_or(|region| {
                region
                    .as_str()
                    .is_some_and(|region| VIEWER_COUNTRIES.split(' ').any(|c| c == region))
            })
            && claims
                .get("ageConfirmed")
                .is_none_or(serde_json::Value::is_boolean)
    })
}
/// The CDN's refusal of viewer claims [`read_viewer_claims`] can't read.
pub(super) fn invalid_viewer_claims() -> super::MockResponse {
    fail(ErrorCode::ViewerClaimsInvalid, "Invalid viewer claims").response()
}

/// 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`) apply to viewers whose `region` claim
/// names their jurisdiction, 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,
    claims: &Value,
) -> Result<&'a str, RegionalRefusal> {
    let moderation = &asset["classification"]["moderation"];
    let base = text(&moderation["decision"]);
    let stricter: Vec<(&str, &str)> = moderation["regions"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|entry| (text(&entry["region"]), text(&entry["status"])))
        .filter(|(_, status)| 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 strictest = stricter
        .into_iter()
        .filter(|(region, _)| *region == viewer)
        .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 Some(claims) = read_viewer_claims(q) else {
        return invalid_viewer_claims();
    };
    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, &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"]))),
        ],
    )
}