calmlens 0.41.0

Rust SDK for CalmLens moderation, storage and CDN delivery
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! Upload presets, project settings and metadata fields in the in-memory API. An API-key upload
//! naming a preset takes its settings and keeps to its limits; otherwise the mock keeps these
//! definitions only: it doesn't check that a preset's folder and policy exist when saving it, or
//! apply the settings to assets.
use super::Backend;
use super::{bounded, cursor_ordering, fail, keyset_page, merge_patch, text, validation, Outcome};
use crate::error::ErrorCode;
use serde_json::{json, Map, Value};
use std::collections::{HashMap, HashSet};

/// The project's configuration. Settings and metadata fields share one revision.
#[derive(Debug)]
pub(super) struct Configuration {
    /// The upload presets, oldest first.
    presets: Vec<Value>,
    revision: u64,
    /// The settings the last update sent; those it left out hold their defaults.
    settings: Map<String, Value>,
    /// The metadata fields, in display order.
    fields: Vec<Value>,
}
impl Default for Configuration {
    fn default() -> Self {
        Self {
            presets: Vec::new(),
            revision: 1,
            settings: Map::new(),
            fields: Vec::new(),
        }
    }
}

/// A preset's list field as the API stores it: without repeats, and `null` when empty.
fn unique_list(value: Option<&Value>) -> Value {
    let Some(items) = value
        .and_then(Value::as_array)
        .filter(|items| !items.is_empty())
    else {
        return Value::Null;
    };
    let mut seen = HashSet::new();
    Value::Array(
        items
            .iter()
            .filter(|item| seen.insert(item.to_string()))
            .cloned()
            .collect(),
    )
}

/// A definition's whole set of stored values: fields left out take their defaults. Refuses what
/// the API refuses before saving anything.
fn preset_values(definition: &Value, index: usize) -> Outcome<Map<String, Value>> {
    for key in ["key", "name"] {
        if text(&definition[key]).is_empty() {
            return Err(validation(
                "invalid-type",
                &format!("uploadPresets.{index}.{key}"),
            ));
        }
    }
    let or = |key: &str, default: Value| match &definition[key] {
        Value::Null => default,
        value => value.clone(),
    };
    let values = json!({
        "key": definition["key"],
        "name": definition["name"],
        "access": or("access", "token".into()),
        "enabled": or("enabled", true.into()),
        "allowedContentTypes": unique_list(definition.get("allowedContentTypes")),
        "maxSizeInBytes": definition["maxSizeInBytes"],
        "folderId": definition["folderId"],
        "policyId": definition["policyId"],
        "visibility": or("visibility", "private".into()),
        "processingOptions": definition["processingOptions"],
        "revealDecision": or("revealDecision", false.into()),
        "dailyUploadLimit": definition["dailyUploadLimit"],
        "allowedOrigins": unique_list(definition.get("allowedOrigins")),
    });
    if values["access"] == "anyone" && values["dailyUploadLimit"].as_u64().unwrap_or(0) == 0 {
        return Err(fail(
            ErrorCode::UploadPresetDailyLimitRequired,
            "A preset that anyone can upload to needs a daily upload limit.",
        ));
    }
    let Value::Object(values) = values else {
        unreachable!("the values are an object");
    };
    Ok(values)
}

/// Whether an upload named `name` of type `content_type` matches an allowed type: a type, a
/// wildcard such as `image/*`, or a file extension such as `.pdf`.
fn allows_type(allowed: &Value, name: &str, content_type: &str) -> bool {
    let (name, content_type) = (name.to_lowercase(), content_type.to_lowercase());
    allowed.as_array().into_iter().flatten().any(|pattern| {
        let pattern = text(pattern).trim().to_lowercase();
        if pattern == "*" || pattern == "*/*" {
            true
        } else if let Some(prefix) = pattern.strip_suffix('*').filter(|p| p.ends_with('/')) {
            content_type.starts_with(prefix)
        } else if pattern.starts_with('.') {
            name.ends_with(&pattern)
        } else {
            content_type == pattern
        }
    })
}

impl Backend {
    /// Checks a browser upload through preset `preset_id` before it is created, as the API does:
    /// the preset must exist, and one whose access is `token` (or any upload sending a token)
    /// needs `token`, signed with the mock's key for this preset, unexpired and unused. Returns
    /// the external ID the token sets and its nonce.
    pub(crate) fn check_preset_upload(
        &self,
        preset_id: &str,
        token: Option<&str>,
    ) -> crate::Result<(Option<String>, Option<String>)> {
        let error = |code: ErrorCode| {
            let status = code.http_status().map_or(400, |status| status.as_u16());
            crate::Error::new(code.clone(), code.as_str()).with_http_status(status)
        };
        let preset = self
            .configuration
            .presets
            .iter()
            .find(|preset| preset["id"] == preset_id)
            .ok_or_else(|| error(ErrorCode::UploadPresetNotFound))?;
        if token.is_none() && preset["access"] != "token" {
            return Ok((None, None));
        }
        let claims = read_upload_token(token.unwrap_or(""), &self.options.api_key)
            .filter(|claims| {
                claims["v"] == 1 && claims["u"] == preset_id && !text(&claims["n"]).is_empty()
            })
            .ok_or_else(|| error(ErrorCode::UploadTokenInvalid))?;
        if claims["e"]
            .as_u64()
            .is_none_or(|expires| expires <= self.now())
        {
            return Err(error(ErrorCode::UploadTokenExpired));
        }
        let nonce = text(&claims["n"]).to_owned();
        if self.used_upload_tokens.contains(&nonce) {
            return Err(error(ErrorCode::UploadTokenUsed));
        }
        let external_id = claims["x"].as_str().map(str::to_owned);
        Ok((external_id, Some(nonce)))
    }

    /// An API-key upload through a preset, as the API applies it: the preset gives the folder and
    /// visibility, which the upload can't change, and the processing options unless the upload
    /// sets its own, and refuses types and sizes it doesn't accept. `content_type` and `size` are
    /// `None` for an upload without content of its own.
    pub(super) fn apply_upload_preset(
        &self,
        options: &mut Map<String, Value>,
        content_type: Option<&str>,
        size: Option<u64>,
    ) -> Outcome<()> {
        let Some(id) = options.get("uploadPresetId").and_then(Value::as_str) else {
            return Ok(());
        };
        let preset = self
            .configuration
            .presets
            .iter()
            .find(|preset| preset["id"] == id)
            .ok_or_else(|| fail(ErrorCode::UploadPresetNotFound, "Upload preset not found"))?;
        if preset["enabled"] != true {
            return Err(fail(
                ErrorCode::UploadPresetDisabled,
                "This upload preset is disabled",
            ));
        }
        let differs = |field: &str| {
            options
                .get(field)
                .is_some_and(|sent| !sent.is_null() && *sent != preset[field])
        };
        let not_allowed = ["folderId", "visibility"]
            .into_iter()
            .filter(|field| !preset[*field].is_null())
            .find(|field| differs(field));
        if let Some(field) = not_allowed {
            let mut failure = fail(
                ErrorCode::UploadPresetFieldNotAllowed,
                "This upload preset sets this field",
            );
            failure.details = json!({ "field": field });
            return Err(failure);
        }
        let allowed = &preset["allowedContentTypes"];
        if let Some(content_type) = content_type {
            let name = options.get("name").map_or("", text);
            if !allowed.is_null() && !allows_type(allowed, name, content_type) {
                let mut failure = fail(
                    ErrorCode::UnsupportedUploadType,
                    "This upload preset doesn't accept this type of file",
                );
                failure.details = json!({
                    "source": "preset", "contentType": content_type,
                    "allowedContentTypes": allowed,
                });
                return Err(failure);
            }
        }
        if let Some(limit) = preset["maxSizeInBytes"].as_u64() {
            if size.is_some_and(|size| size > limit) {
                let mut failure = fail(
                    ErrorCode::UploadTooLarge,
                    "The upload is larger than this upload preset accepts",
                );
                failure.details = json!({ "limitBytes": limit, "source": "preset" });
                return Err(failure);
            }
        }
        if !preset["folderId"].is_null() {
            options.insert("folderId".into(), preset["folderId"].clone());
        }
        options.insert("visibility".into(), preset["visibility"].clone());
        let own_options = options
            .get("processingOptions")
            .is_some_and(|processing| !processing.is_null());
        if !own_options && !preset["processingOptions"].is_null() {
            options.insert(
                "processingOptions".into(),
                preset["processingOptions"].clone(),
            );
        }
        let mut processing = options
            .get("processingOptions")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        if processing.get("retainContent").is_none_or(Value::is_null) {
            processing.insert(
                "retainContent".into(),
                preset["processingOptions"]["retainContent"].clone(),
            );
        }
        options.insert("processingOptions".into(), Value::Object(processing));
        Ok(())
    }

    /// A page of the project's upload presets, oldest first unless `sort` says otherwise.
    pub(super) fn list_upload_presets(&self, q: &HashMap<String, String>) -> Outcome<Value> {
        let size = bounded(q.get("pageSize"), 50, 1, 100, "pageSize")?;
        let ordering = cursor_ordering(q, ("createdAt", true))?;
        let scope = json!(["upload-presets", self.options.project_id]).to_string();
        keyset_page(
            self.configuration.presets.iter().collect(),
            &ordering,
            q.get("cursor"),
            &scope,
            size,
        )
    }

    /// Like the API: every preset's revision and settings are checked before any is saved.
    pub(super) fn ensure_upload_presets(
        &mut self,
        body: &Map<String, Value>,
        now: u64,
    ) -> Outcome<Value> {
        let definitions = body
            .get("uploadPresets")
            .and_then(Value::as_array)
            .filter(|definitions| !definitions.is_empty())
            .ok_or_else(|| validation("too-small", "uploadPresets"))?;
        let mut plans = Vec::with_capacity(definitions.len());
        for (index, definition) in definitions.iter().enumerate() {
            let values = preset_values(definition, index)?;
            let existing = self
                .configuration
                .presets
                .iter()
                .find(|preset| preset["key"] == values["key"])
                .cloned();
            let revision = existing
                .as_ref()
                .map_or(0, |preset| preset["revision"].as_u64().unwrap_or_default());
            if let Some(sent) = definition.get("revision") {
                if sent.as_u64() != Some(revision) {
                    let mut failure = fail(
                        ErrorCode::UploadPresetRevisionConflict,
                        "The upload preset changed, or was created or deleted, since you read it. Retrieve it again and retry with its current revision.",
                    );
                    failure.details = json!({ "key": values["key"], "revision": revision });
                    return Err(failure);
                }
            }
            plans.push((existing, values, revision));
        }
        let mut saved = Vec::with_capacity(plans.len());
        for (existing, values, revision) in plans {
            if let Some(existing) = &existing {
                if values.iter().all(|(key, value)| existing[key] == *value) {
                    saved.push(existing.clone());
                    continue;
                }
            }
            let mut preset = values;
            let id = existing
                .as_ref()
                .map_or_else(|| self.create_id("preset").into(), |old| old["id"].clone());
            let created_at = existing
                .as_ref()
                .map_or_else(|| now.into(), |old| old["createdAt"].clone());
            preset.insert("id".into(), id);
            preset.insert("projectId".into(), self.options.project_id.clone().into());
            preset.insert("createdByUserId".into(), Value::Null);
            preset.insert("revision".into(), (revision + 1).into());
            preset.insert("createdAt".into(), created_at);
            preset.insert("updatedAt".into(), now.into());
            let preset = Value::Object(preset);
            let presets = &mut self.configuration.presets;
            match presets.iter_mut().find(|old| old["key"] == preset["key"]) {
                Some(old) => *old = preset.clone(),
                None => presets.push(preset.clone()),
            }
            saved.push(preset);
        }
        Ok(json!({ "uploadPresets": saved }))
    }

    pub(super) fn delete_upload_preset(&mut self, id: &str) -> Outcome<Value> {
        let presets = &mut self.configuration.presets;
        let Some(index) = presets.iter().position(|preset| preset["id"] == id) else {
            return Err(fail(
                ErrorCode::UploadPresetNotFound,
                "Upload preset not found",
            ));
        };
        presets.remove(index);
        Ok(json!({}))
    }

    /// The settings with every default filled in.
    pub(super) fn full_settings(&self) -> Value {
        let mut settings = json!({
            "optOutJurisdictions": [],
            "retainContent": true,
            "blockUnmoderatedAssets": true,
            "storeSensitiveMetadata": false,
            "streamingEnabled": false,
            "aiMediaSearchEnabled": false,
            "remoteUrlRule": null,
            "humanReview": {
                "allowedSamplePercent": 0,
                "restrictedSamplePercent": 0,
                "uncertaintyMarginPercent": 0,
                "reviewMissingEvidence": false,
            },
        });
        for (key, value) in &self.configuration.settings {
            if key == "humanReview" {
                for (key, value) in value.as_object().into_iter().flatten() {
                    settings["humanReview"][key] = value.clone();
                }
            } else {
                settings[key] = value.clone();
            }
        }
        settings
    }

    pub(super) fn project_settings_json(&self) -> Value {
        json!({
            "projectId": self.options.project_id,
            "revision": self.configuration.revision,
            "settings": self.full_settings(),
        })
    }

    fn check_settings_revision(&self, sent: Option<u64>) -> Outcome<()> {
        if sent.is_some_and(|sent| sent != self.configuration.revision) {
            return Err(fail(
                ErrorCode::ProjectSettingsRevisionConflict,
                "The project's settings or metadata fields changed since you read them. Retrieve them again and retry with the current revision.",
            ));
        }
        Ok(())
    }

    /// Replaces the settings: those left out return to their defaults. A real change moves the
    /// revision.
    pub(super) fn update_project_settings(&mut self, body: &Map<String, Value>) -> Outcome<Value> {
        self.check_settings_revision(body.get("revision").and_then(Value::as_u64))?;
        let settings = body
            .get("settings")
            .and_then(Value::as_object)
            .ok_or_else(|| validation("invalid-type", "settings"))?;
        let before = self.full_settings();
        let previous = std::mem::replace(&mut self.configuration.settings, settings.clone());
        if self.full_settings() == before {
            self.configuration.settings = previous;
        } else {
            self.configuration.revision += 1;
        }
        Ok(self.project_settings_json())
    }

    /// Changes some settings like the API (`PATCH`): `settings` is a JSON Merge Patch of the
    /// stored settings, where `null` returns a setting to its default, and the patched settings
    /// are checked whole. A real change moves the revision.
    pub(super) fn patch_project_settings(&mut self, body: &Map<String, Value>) -> Outcome<Value> {
        self.check_settings_revision(body.get("revision").and_then(Value::as_u64))?;
        let patch = body
            .get("settings")
            .filter(|patch| patch.is_object())
            .ok_or_else(|| validation("invalid-type", "settings"))?;
        let mut settings = Value::Object(self.configuration.settings.clone());
        merge_patch(&mut settings, patch);
        let Value::Object(settings) = settings else {
            unreachable!("a patch of an object is an object");
        };
        if let Some(rule) = settings.get("remoteUrlRule") {
            for key in ["mode", "domains"] {
                if rule[key].is_null() {
                    return Err(validation(
                        "invalid-type",
                        &format!("settings.remoteUrlRule.{key}"),
                    ));
                }
            }
        }
        let before = self.full_settings();
        let previous = std::mem::replace(&mut self.configuration.settings, settings);
        if self.full_settings() == before {
            self.configuration.settings = previous;
        } else {
            self.configuration.revision += 1;
        }
        Ok(self.project_settings_json())
    }

    pub(super) fn metadata_fields_json(&self) -> Value {
        json!({
            "projectId": self.options.project_id,
            "revision": self.configuration.revision,
            "fields": self.configuration.fields,
        })
    }

    /// Creates or replaces fields by ID, keeping the others in order.
    pub(super) fn ensure_metadata_fields(&mut self, body: &Map<String, Value>) -> Outcome<Value> {
        self.check_settings_revision(body.get("revision").and_then(Value::as_u64))?;
        let fields = body
            .get("fields")
            .and_then(Value::as_array)
            .filter(|fields| !fields.is_empty())
            .ok_or_else(|| validation("too-small", "fields"))?;
        let current = &self.configuration.fields;
        let replaced = current.iter().map(|field| {
            fields
                .iter()
                .find(|sent| sent["id"] == field["id"])
                .unwrap_or(field)
        });
        let added = fields
            .iter()
            .filter(|sent| !current.iter().any(|field| field["id"] == sent["id"]));
        let merged: Vec<Value> = replaced.chain(added).cloned().collect();
        if merged != self.configuration.fields {
            self.configuration.fields = merged;
            self.configuration.revision += 1;
        }
        Ok(self.metadata_fields_json())
    }

    pub(super) fn delete_metadata_field(
        &mut self,
        id: &str,
        q: &HashMap<String, String>,
    ) -> Outcome<Value> {
        let Some(index) = self
            .configuration
            .fields
            .iter()
            .position(|field| field["id"] == id)
        else {
            let mut failure = fail(
                ErrorCode::MetadataFieldNotFound,
                "The project has no metadata field with this ID.",
            );
            failure.details = json!({ "fieldId": id });
            return Err(failure);
        };
        let sent = q
            .get("revision")
            .map(|revision| {
                revision
                    .parse()
                    .map_err(|_| validation("invalid-type", "revision"))
            })
            .transpose()?;
        self.check_settings_revision(sent)?;
        self.configuration.fields.remove(index);
        self.configuration.revision += 1;
        Ok(self.metadata_fields_json())
    }
}

/// The claims of an upload token signed with `api_key`, or `None` when it isn't one or its
/// signature doesn't match.
fn read_upload_token(token: &str, api_key: &str) -> Option<Value> {
    use base64::Engine;
    use hmac::{Hmac, Mac};
    use sha2::{Digest, Sha256};
    let (body, signature) = token.strip_prefix("clut_")?.split_once('.')?;
    let signature: Vec<u8> = (0..signature.len())
        .step_by(2)
        .map(|at| u8::from_str_radix(signature.get(at..at + 2)?, 16).ok())
        .collect::<Option<_>>()?;
    let secret: String = Sha256::digest(api_key.as_bytes())
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).ok()?;
    mac.update(format!("calmlens-upload-token:v1:{body}").as_bytes());
    mac.verify_slice(&signature).ok()?;
    let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(body)
        .ok()?;
    serde_json::from_slice(&claims).ok()
}