Skip to main content

vcon_server/
masked.rs

1//! The masked view of a vCon (`GET /vcons/{uuid}?view=masked`): what it
2//! holds, without any name, subject, full number, address or content, so a
3//! client can show a vCon before anyone reveals a part of it.
4//!
5//! THE RULE is the console's: `summary` in console/format.js, which the
6//! browser applies to a vCon it has read whole. This module is its port, and
7//! tests/data/masked-cases.json holds the cases both are tested against
8//! (here and in console-tests/tests/format.spec.js), so the two give the
9//! same answer. A change to one is a change to both and to the cases.
10//!
11//! The parts a reveal shows (`section`, `links`) are ported here too, for
12//! the terminal UI, which shows a reveal as the console does.
13
14use base64::engine::DecodePaddingMode;
15use base64::engine::general_purpose::{GeneralPurpose, GeneralPurposeConfig};
16use base64::{Engine, alphabet};
17use serde::{Deserialize, Serialize, Serializer};
18use serde_json::{Map, Value};
19use time::{Date, Month, PrimitiveDateTime, Time, UtcOffset};
20
21use crate::query::{self, BadQuery};
22use crate::reveal::Part;
23
24/// The query parameter that asks a read for a view of the vCon.
25pub const PARAMETER: &str = "view";
26
27/// The one view there is: the vCon masked.
28pub const MASKED: &str = "masked";
29
30/// Whether a read's query asks for the masked view. A query that does not
31/// name the parameter is the read it always was.
32///
33/// # Errors
34///
35/// [`BadQuery`] if the query names the parameter and it is not exactly
36/// `view=masked`, alone and once.
37pub fn from_query(query: Option<&str>) -> Result<bool, BadQuery> {
38    if !query::names(query, PARAMETER) {
39        return Ok(false);
40    }
41    let read = query::pairs(query, &[PARAMETER])?;
42    match read.get(PARAMETER).map(String::as_str) {
43        Some(MASKED) => Ok(true),
44        _ => Err(BadQuery),
45    }
46}
47
48/// The form of each kind of body, and what the subject of an unread one is.
49const UNSIGNED: &str = "unsigned";
50const SIGNED: &str = "signed (JWS)";
51const ENCRYPTED: &str = "encrypted (JWE)";
52const NOT_JSON: &str = "not JSON";
53const NOT_OBJECT: &str = "not a JSON object";
54const NOT_READABLE: &str = "not readable";
55
56/// The dialog types the vCon format names; any other is not shown.
57const DIALOG_TYPES: [&str; 4] = ["recording", "text", "transfer", "incomplete"];
58
59/// The fewest digits a number needs before its last four may be shown.
60const MASKABLE_DIGITS: usize = 8;
61
62/// The encodings under which a body is media, not text to read.
63const MEDIA_ENCODINGS: [&str; 2] = ["base64url", "base64"];
64
65/// The parts of a vCon that may hold a link, and what one item is called.
66const LINKED: [(&str, &str); 3] = [
67    ("dialog", "dialog"),
68    ("attachments", "attachment"),
69    ("analysis", "analysis"),
70];
71
72/// Base64url as a browser's `atob` reads it: no padding needed, and bits
73/// after the last whole byte ignored.
74const FORGIVING: GeneralPurpose = GeneralPurpose::new(
75    &alphabet::URL_SAFE,
76    GeneralPurposeConfig::new()
77        .with_decode_padding_mode(DecodePaddingMode::Indifferent)
78        .with_decode_allow_trailing_bits(true),
79);
80
81/// A value's items when it is an array, or none.
82fn items(value: Option<&Value>) -> &[Value] {
83    value.and_then(Value::as_array).map_or(&[], Vec::as_slice)
84}
85
86/// A field of an object when it is text.
87fn text_field<'a>(object: &'a Map<String, Value>, name: &str) -> Option<&'a str> {
88    object.get(name).and_then(Value::as_str)
89}
90
91/// Base64url JSON as an object, or none when it is anything else. A
92/// leading byte order mark is dropped, as a browser's text decoder drops it.
93fn decoded(value: Option<&Value>) -> Option<Map<String, Value>> {
94    let text = value?.as_str()?;
95    if text.is_empty()
96        || !text
97            .bytes()
98            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
99    {
100        return None;
101    }
102    let bytes = FORGIVING.decode(text).ok()?;
103    let text = std::str::from_utf8(&bytes).ok()?;
104    match serde_json::from_str(text.strip_prefix('\u{feff}').unwrap_or(text)).ok()? {
105        Value::Object(object) => Some(object),
106        _ => None,
107    }
108}
109
110/// The vCon object a body holds, for reading its parts: the body itself,
111/// or a signed vCon's payload. None for an encrypted vCon and for anything
112/// that is not a JSON object.
113fn readable(text: &str) -> Option<Map<String, Value>> {
114    let Ok(Value::Object(vcon)) = serde_json::from_str::<Value>(text) else {
115        return None;
116    };
117    if vcon.contains_key("ciphertext") {
118        return None;
119    }
120    if vcon.contains_key("payload") && vcon.contains_key("signatures") {
121        return decoded(vcon.get("payload"));
122    }
123    Some(vcon)
124}
125
126/// A summary of nothing, in the given form.
127fn empty(form: &str, subject: &str) -> Summary {
128    Summary {
129        form: form.to_owned(),
130        created: String::new(),
131        subject: subject.to_owned(),
132        parties: Vec::new(),
133        dialogs: 0,
134        dialog: Vec::new(),
135        seconds: 0.0,
136        attachments: 0,
137        analyses: 0,
138        links: 0,
139        signature: None,
140    }
141}
142
143/// The counts and masked parties of an unsigned vCon object.
144fn counted(vcon: &Map<String, Value>, form: &str) -> Summary {
145    let dialog = items(vcon.get("dialog"));
146    let seconds = dialog
147        .iter()
148        .filter_map(|d| d.get("duration").and_then(Value::as_f64))
149        .filter(|duration| *duration > 0.0)
150        .fold(0.0, |sum, duration| sum + duration);
151    let subject = match text_field(vcon, "subject") {
152        Some(subject) if !subject.is_empty() => "present, hidden",
153        _ => "none",
154    };
155    Summary {
156        form: form.to_owned(),
157        created: vcon.get("created_at").map(instant).unwrap_or_default(),
158        subject: subject.to_owned(),
159        parties: items(vcon.get("parties"))
160            .iter()
161            .enumerate()
162            .map(|(index, party)| party_line(party, index))
163            .collect(),
164        dialogs: dialog.len(),
165        dialog: dialog
166            .iter()
167            .enumerate()
168            .map(|(index, d)| dialog_line(d, index))
169            .collect(),
170        seconds,
171        attachments: items(vcon.get("attachments")).len(),
172        analyses: items(vcon.get("analysis")).len(),
173        links: links_of(vcon).len(),
174        signature: None,
175    }
176}
177
178/// Every link in a vCon object, with where it is.
179fn links_of(vcon: &Map<String, Value>) -> Vec<Link> {
180    let mut found = Vec::new();
181    for (part, noun) in LINKED {
182        for (index, item) in items(vcon.get(part)).iter().enumerate() {
183            if let Some(url) = item.as_object().and_then(|item| text_field(item, "url"))
184                && !url.is_empty()
185            {
186                found.push(Link {
187                    place: format!("{noun} {}", index.saturating_add(1)),
188                    url: url.to_owned(),
189                });
190            }
191        }
192    }
193    found
194}
195
196/// A vCon's form and counts, its parties masked: the answer of the masked
197/// view, with the fields and the words of the console's summary.
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199pub struct Summary {
200    /// `unsigned`, `signed (JWS)`, `encrypted (JWE)`, `not JSON` or `not a
201    /// JSON object`.
202    pub form: String,
203    /// When it was made, in UTC (see [`instant`]); empty when not a time.
204    pub created: String,
205    /// `present, hidden`, `none`, or `not readable`.
206    pub subject: String,
207    /// One line for each party, masked (see [`party_line`]).
208    pub parties: Vec<String>,
209    /// How many dialogs it holds.
210    pub dialogs: usize,
211    /// One line for each dialog, with no content (see [`dialog_line`]).
212    pub dialog: Vec<String>,
213    /// The sum of the dialogs' positive lengths, in seconds.
214    #[serde(serialize_with = "as_js_number")]
215    pub seconds: f64,
216    /// How many attachments it holds.
217    pub attachments: usize,
218    /// How many analyses it holds.
219    pub analyses: usize,
220    /// How many links to outside the server it holds.
221    pub links: usize,
222    /// A signed vCon's first signature header, else none.
223    pub signature: Option<Signature>,
224}
225
226/// The fields of a signature's protected header the view names; each is
227/// empty when the header does not hold it as text.
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229pub struct Signature {
230    /// The signing algorithm, such as `ES256`.
231    pub alg: String,
232    /// The id of the signing key.
233    pub kid: String,
234    /// The thumbprint of the signing certificate.
235    pub x5t: String,
236}
237
238/// A number as JSON writes it in JavaScript: a whole number without a
239/// fraction, so `30` and not `30.0`.
240fn as_js_number<S: Serializer>(value: &f64, to: S) -> Result<S::Ok, S::Error> {
241    /// Below this every whole number is exact in a JavaScript number.
242    const EXACT: f64 = 9_007_199_254_740_992.0;
243    if value.fract() == 0.0 && value.abs() < EXACT {
244        // The value is whole and within the exact range, so the
245        // conversion keeps it.
246        #[expect(clippy::cast_possible_truncation, reason = "whole and below 2^53")]
247        to.serialize_i64(*value as i64)
248    } else {
249        to.serialize_f64(*value)
250    }
251}
252
253/// A body as the text a browser reads from it: UTF-8, any byte that is not
254/// replaced, and a leading byte order mark dropped.
255#[must_use]
256pub fn text_of(body: &[u8]) -> String {
257    let text = String::from_utf8_lossy(body);
258    text.strip_prefix('\u{feff}').unwrap_or(&text).to_owned()
259}
260
261/// What a vCon body holds, without any name, subject, full number or
262/// address: its form, counts and masked parties. A signed vCon's payload is
263/// read; an encrypted one is not decoded.
264#[must_use]
265pub fn summary(text: &str) -> Summary {
266    let Ok(value) = serde_json::from_str::<Value>(text) else {
267        return empty(NOT_JSON, NOT_READABLE);
268    };
269    let Value::Object(vcon) = value else {
270        return empty(NOT_OBJECT, NOT_READABLE);
271    };
272    if vcon.contains_key("ciphertext") {
273        return empty(ENCRYPTED, NOT_READABLE);
274    }
275    if vcon.contains_key("payload") && vcon.contains_key("signatures") {
276        let header = items(vcon.get("signatures"))
277            .first()
278            .and_then(Value::as_object)
279            .and_then(|first| decoded(first.get("protected")));
280        let field = |name: &str| {
281            header
282                .as_ref()
283                .and_then(|header| text_field(header, name))
284                .unwrap_or_default()
285                .to_owned()
286        };
287        let mut made = decoded(vcon.get("payload")).map_or_else(
288            || empty(SIGNED, NOT_READABLE),
289            |payload| counted(&payload, SIGNED),
290        );
291        made.signature = Some(Signature {
292            alg: field("alg"),
293            kid: field("kid"),
294            x5t: field("x5t"),
295        });
296        return made;
297    }
298    counted(&vcon, UNSIGNED)
299}
300
301/// The numbers of an RFC 3339 date-time, `YYYY-MM-DDTHH:MM:SS`, any
302/// fraction, then `Z` or `+HH:MM`/`-HH:MM` (either letter in either case):
303/// year, month, day, hour, minute, second and the offset in minutes. None
304/// for text of any other shape.
305fn date_time_numbers(text: &str) -> Option<([u16; 6], i32)> {
306    let bytes = text.as_bytes();
307    let number = |from: usize, to: usize| -> Option<u16> {
308        let digits = bytes.get(from..to)?;
309        digits
310            .iter()
311            .all(u8::is_ascii_digit)
312            .then(|| std::str::from_utf8(digits).ok()?.parse().ok())?
313    };
314    let at = |index: usize, wanted: &[u8]| bytes.get(index).is_some_and(|b| wanted.contains(b));
315    if !(at(4, b"-") && at(7, b"-") && at(10, b"Tt") && at(13, b":") && at(16, b":")) {
316        return None;
317    }
318    let fields = [
319        number(0, 4)?,
320        number(5, 7)?,
321        number(8, 10)?,
322        number(11, 13)?,
323        number(14, 16)?,
324        number(17, 19)?,
325    ];
326    let mut rest = 19;
327    if at(rest, b".") {
328        let digits = bytes
329            .get(rest.saturating_add(1)..)?
330            .iter()
331            .take_while(|b| b.is_ascii_digit())
332            .count();
333        if digits == 0 {
334            return None;
335        }
336        rest = rest.saturating_add(1).saturating_add(digits);
337    }
338    let zone = bytes.get(rest..)?;
339    let offset = match zone {
340        [b'Z' | b'z'] => 0,
341        [sign @ (b'+' | b'-'), _, _, b':', _, _] => {
342            let hours = number(rest.saturating_add(1), rest.saturating_add(3))?;
343            let minutes = number(rest.saturating_add(4), rest.saturating_add(6))?;
344            if hours > 23 || minutes > 59 {
345                return None;
346            }
347            let minutes = i32::from(hours) * 60 + i32::from(minutes);
348            if *sign == b'-' { -minutes } else { minutes }
349        }
350        _ => return None,
351    };
352    Some((fields, offset))
353}
354
355/// A vCon's time as `YYYY-MM-DD HH:MM:SS UTC+00:00`, or empty when it is
356/// not an RFC 3339 date-time of a day that exists, in the years 1 to 9999
357/// once in UTC. Text that is not a time is never shown.
358#[must_use]
359pub fn instant(value: &Value) -> String {
360    let read = || {
361        let (fields, offset) = date_time_numbers(value.as_str()?)?;
362        let [year, month, day, hour, minute, second] = fields;
363        let date = Date::from_calendar_date(
364            i32::from(year),
365            Month::try_from(u8::try_from(month).ok()?).ok()?,
366            u8::try_from(day).ok()?,
367        )
368        .ok()?;
369        let time = Time::from_hms(
370            u8::try_from(hour).ok()?,
371            u8::try_from(minute).ok()?,
372            u8::try_from(second).ok()?,
373        )
374        .ok()?;
375        let offset = UtcOffset::from_whole_seconds(offset.checked_mul(60)?).ok()?;
376        let at = PrimitiveDateTime::new(date, time)
377            .assume_offset(offset)
378            .checked_to_offset(UtcOffset::UTC)?;
379        (1..=9999).contains(&at.year()).then(|| {
380            format!(
381                "{:04}-{:02}-{:02} {:02}:{:02}:{:02} UTC+00:00",
382                at.year(),
383                u8::from(at.month()),
384                at.day(),
385                at.hour(),
386                at.minute(),
387                at.second()
388            )
389        })
390    };
391    read().unwrap_or_default()
392}
393
394/// A telephone number as its last four digits, or hidden whole.
395#[must_use]
396pub fn mask_tel(value: &Value) -> String {
397    let digits: Vec<char> = value
398        .as_str()
399        .unwrap_or_default()
400        .chars()
401        .filter(char::is_ascii_digit)
402        .collect();
403    match digits.len().checked_sub(4) {
404        Some(from) if digits.len() >= MASKABLE_DIGITS => {
405            let last: String = digits.get(from..).unwrap_or_default().iter().collect();
406            format!("number ending {last}")
407        }
408        _ => "number hidden".to_owned(),
409    }
410}
411
412/// Whether JavaScript's `trim` removes `c`: its white space and line
413/// terminators, the byte order mark among them.
414fn trimmed_by_javascript(c: char) -> bool {
415    matches!(
416        c,
417        '\u{9}'..='\u{d}'
418            | ' '
419            | '\u{a0}'
420            | '\u{1680}'
421            | '\u{2000}'..='\u{200a}'
422            | '\u{2028}'
423            | '\u{2029}'
424            | '\u{202f}'
425            | '\u{205f}'
426            | '\u{3000}'
427            | '\u{feff}'
428    )
429}
430
431/// An email address as its domain, or hidden whole.
432#[must_use]
433pub fn mask_mail(value: &Value) -> String {
434    let Some(address) = value.as_str() else {
435        return "address hidden".to_owned();
436    };
437    match address.rfind('@') {
438        Some(at) if at > 0 => {
439            let domain = address
440                .get(at.saturating_add(1)..)
441                .unwrap_or_default()
442                .trim_matches(trimmed_by_javascript)
443                .to_lowercase();
444            if domain.is_empty() {
445                "address hidden".to_owned()
446            } else {
447                format!("address at {domain}")
448            }
449        }
450        _ => "address hidden".to_owned(),
451    }
452}
453
454/// Party `index` (from 0) as a line that names what it holds and shows none
455/// of it.
456#[must_use]
457pub fn party_line(party: &Value, index: usize) -> String {
458    let label = format!("Party {}", index.saturating_add(1));
459    let Some(party) = party.as_object() else {
460        return format!("{label}: not an object");
461    };
462    let mut parts = Vec::new();
463    if let Some(tel) = party.get("tel") {
464        parts.push(mask_tel(tel));
465    }
466    if let Some(mailto) = party.get("mailto") {
467        parts.push(mask_mail(mailto));
468    }
469    if party.contains_key("name") {
470        parts.push("name hidden".to_owned());
471    }
472    if parts.is_empty() {
473        format!("{label}: no number, address or name")
474    } else {
475        format!("{label}: {}", parts.join("; "))
476    }
477}
478
479/// A value as a party's place in the parties list, if it is one: a whole
480/// number, zero or more.
481fn place(value: &Value) -> Option<f64> {
482    value
483        .as_f64()
484        .filter(|number| number.fract() == 0.0 && *number >= 0.0)
485}
486
487/// A dialog's parties as their numbers, counted from one.
488fn parties_of(parties: Option<&Value>) -> String {
489    if let Some(one) = parties.and_then(place) {
490        return format!("party {}", js_number(one + 1.0));
491    }
492    let places: Option<Vec<f64>> = parties
493        .and_then(Value::as_array)
494        .filter(|list| !list.is_empty())
495        .and_then(|list| list.iter().map(place).collect());
496    match places {
497        Some(places) => {
498            let numbers: Vec<String> = places.iter().map(|p| js_number(p + 1.0)).collect();
499            format!("parties {}", numbers.join(", "))
500        }
501        None => "no parties".to_owned(),
502    }
503}
504
505/// Dialog `index` (from 0) as a line with its type, start, length and
506/// parties, and whether it has content, never the content or a link.
507#[must_use]
508pub fn dialog_line(dialog: &Value, index: usize) -> String {
509    let label = format!("Dialog {}", index.saturating_add(1));
510    let Some(dialog) = dialog.as_object() else {
511        return format!("{label}: not an object");
512    };
513    let kind = text_field(dialog, "type")
514        .filter(|kind| DIALOG_TYPES.contains(kind))
515        .unwrap_or("other type");
516    let start = dialog.get("start").map(instant).unwrap_or_default();
517    let start = if start.is_empty() { "no start" } else { &start };
518    let length = dialog
519        .get("duration")
520        .and_then(Value::as_f64)
521        .filter(|duration| *duration > 0.0)
522        .map_or_else(|| "no length".to_owned(), |d| format!("{} s", js_number(d)));
523    let present = |name: &str| text_field(dialog, name).is_some_and(|text| !text.is_empty());
524    let content = if present("body") {
525        "content hidden"
526    } else if present("url") {
527        "content at a link outside the server"
528    } else {
529        "no content"
530    };
531    format!(
532        "{label}: {kind}, {start}, {length}, {}; {content}",
533        parties_of(dialog.get("parties"))
534    )
535}
536
537/// A number as JavaScript writes it in text: `30`, `12.5`, `1e+21`.
538#[must_use]
539pub fn js_number(value: f64) -> String {
540    if value == 0.0 {
541        return "0".to_owned();
542    }
543    let size = value.abs();
544    if size >= 1e21 || size < 1e-6 {
545        let written = format!("{value:e}");
546        return match written.split_once('e') {
547            Some((digits, power)) if !power.starts_with('-') => format!("{digits}e+{power}"),
548            _ => written,
549        };
550    }
551    format!("{value}")
552}
553
554/// A link of a vCon: where it is (`dialog 1`, `attachment 2`, `analysis
555/// 3`) and the address, which is never loaded.
556#[derive(Debug, Clone, PartialEq, Eq)]
557pub struct Link {
558    /// Where the link is, as `dialog 1`.
559    pub place: String,
560    /// Where it points.
561    pub url: String,
562}
563
564/// Every link in a vCon body, in the order of the console; none when the
565/// body cannot be read in parts.
566#[must_use]
567pub fn links(text: &str) -> Vec<Link> {
568    readable(text)
569        .map(|vcon| links_of(&vcon))
570        .unwrap_or_default()
571}
572
573/// The most characters of a vCon shown at once: 2 MiB, as in the console.
574pub const DISPLAY_LIMIT: usize = 2 * 1024 * 1024;
575
576/// `text` cut at [`DISPLAY_LIMIT`] characters, and how many were left out.
577#[must_use]
578pub fn shown(text: &str) -> (&str, usize) {
579    match text.char_indices().nth(DISPLAY_LIMIT) {
580        Some((cut, _)) => {
581            let (kept, left) = text.split_at(cut);
582            (kept, left.chars().count())
583        }
584        None => (text, 0),
585    }
586}
587
588/// Items as indented JSON, with inline media named by its size, not shown;
589/// `none` for no items.
590fn listed(value: Option<&Value>) -> String {
591    let made = items(value);
592    if made.is_empty() {
593        return "none".to_owned();
594    }
595    let readable: Vec<Value> = made
596        .iter()
597        .map(|item| {
598            let mut item = item.clone();
599            if let Some(object) = item.as_object_mut()
600                && let Some(encoding) = text_field(object, "encoding")
601                    .filter(|encoding| MEDIA_ENCODINGS.contains(encoding))
602                    .map(str::to_owned)
603                && let Some(length) =
604                    text_field(object, "body").map(|body| body.encode_utf16().count())
605            {
606                object.insert(
607                    "body".to_owned(),
608                    Value::String(format!("[{length} characters of {encoding}, not shown]")),
609                );
610            }
611            item
612        })
613        .collect();
614    let text = serde_json::to_string_pretty(&readable).unwrap_or_default();
615    shown(&text).0.to_owned()
616}
617
618/// One part of a vCon body as text, as the console shows a reveal of it:
619/// the parties, the dialog or the analysis as indented JSON with inline
620/// media named by its size, or the subject. None for any other part and for
621/// a body that cannot be read in parts.
622#[must_use]
623pub fn section(text: &str, part: Part) -> Option<String> {
624    let vcon = readable(text)?;
625    match part {
626        Part::Parties => Some(listed(vcon.get("parties"))),
627        Part::Dialog => Some(listed(vcon.get("dialog"))),
628        Part::Analysis => Some(listed(vcon.get("analysis"))),
629        Part::Subject => Some(
630            text_field(&vcon, "subject")
631                .filter(|subject| !subject.is_empty())
632                .unwrap_or("none")
633                .to_owned(),
634        ),
635        Part::Links | Part::All | Part::Audio => None,
636    }
637}
638
639#[cfg(test)]
640mod tests {
641    use serde_json::json;
642
643    use super::*;
644
645    /// The cases format.js is tested against too.
646    const CASES: &str = include_str!("../tests/data/masked-cases.json");
647
648    fn cases() -> Vec<(String, String, Value)> {
649        let cases: Vec<Value> = serde_json::from_str(CASES).expect("the cases are JSON");
650        cases
651            .into_iter()
652            .map(|case| {
653                (
654                    case["name"].as_str().expect("a name").to_owned(),
655                    case["body"].as_str().expect("a body").to_owned(),
656                    case["summary"].clone(),
657                )
658            })
659            .collect()
660    }
661
662    fn masked(vcon: &Value) -> Summary {
663        summary(&vcon.to_string())
664    }
665
666    // Success.
667
668    #[test]
669    fn each_case_is_summarized_as_format_js_summarizes_it() {
670        let cases = cases();
671        assert!(cases.len() > 20, "there are cases to compare");
672        for (name, body, wanted) in cases {
673            let made = serde_json::to_value(summary(&body)).expect("a summary is JSON");
674            assert_eq!(made, wanted, "the case {name}");
675        }
676    }
677
678    #[test]
679    fn view_masked_alone_asks_for_the_masked_view() {
680        assert_eq!(from_query(Some("view=masked")), Ok(true), "the view");
681    }
682
683    #[test]
684    fn a_read_without_the_parameter_is_not_the_masked_view() {
685        for query in [None, Some(""), Some("reveal=all"), Some("viewed=masked")] {
686            assert_eq!(from_query(query), Ok(false), "{query:?}");
687        }
688    }
689
690    #[test]
691    fn a_number_shows_its_last_four_digits() {
692        assert_eq!(
693            mask_tel(&json!("+1 212 555 0142")),
694            "number ending 0142",
695            "masked"
696        );
697    }
698
699    #[test]
700    fn an_address_shows_its_domain_in_lower_case() {
701        assert_eq!(
702            mask_mail(&json!("ada@Example.COM")),
703            "address at example.com",
704            "masked"
705        );
706    }
707
708    #[test]
709    fn a_party_line_names_number_address_and_name_in_that_order() {
710        let party =
711            json!({"name": "Ada Example", "mailto": "ada@example.com", "tel": "+12125550142"});
712        assert_eq!(
713            party_line(&party, 2),
714            "Party 3: number ending 0142; address at example.com; name hidden",
715            "the line"
716        );
717    }
718
719    #[test]
720    fn a_dialog_line_shows_type_start_length_and_parties_and_no_content() {
721        let dialog = json!({"type": "text", "start": "2026-11-10T09:15:05Z", "duration": 30,
722            "parties": [0, 1], "body": "Ada said hello"});
723        let line = dialog_line(&dialog, 0);
724        assert_eq!(
725            line,
726            "Dialog 1: text, 2026-11-10 09:15:05 UTC+00:00, 30 s, parties 1, 2; content hidden",
727            "the line"
728        );
729        assert!(!line.contains("hello"), "no content");
730    }
731
732    #[test]
733    fn a_time_with_an_offset_is_shown_in_utc() {
734        assert_eq!(
735            instant(&json!("2026-11-10T11:15:00+02:00")),
736            "2026-11-10 09:15:00 UTC+00:00",
737            "in UTC"
738        );
739    }
740
741    #[test]
742    fn a_whole_number_of_seconds_is_written_without_a_fraction() {
743        let made =
744            serde_json::to_string(&masked(&json!({"dialog": [{"duration": 30}]}))).expect("JSON");
745        assert!(made.contains(r#""seconds":30,"#), "{made}");
746    }
747
748    #[test]
749    fn numbers_are_written_as_javascript_writes_them() {
750        for (number, text) in [
751            (30.0, "30"),
752            (12.5, "12.5"),
753            (1e21, "1e+21"),
754            (1e-7, "1e-7"),
755            (1.5e-7, "1.5e-7"),
756            (1e20, "100000000000000000000"),
757            (0.1 + 0.2, "0.30000000000000004"),
758        ] {
759            assert_eq!(js_number(number), text, "{number}");
760        }
761    }
762
763    #[test]
764    fn a_signed_vcons_header_names_its_algorithm_key_and_thumbprint() {
765        let cases = cases();
766        let (_, body, _) = cases
767            .iter()
768            .find(|(name, _, _)| name == "a signed vCon")
769            .expect("the signed case");
770        let made = summary(body);
771        assert_eq!(made.form, "signed (JWS)", "the form");
772        assert_eq!(
773            made.signature,
774            Some(Signature {
775                alg: "ES256".to_owned(),
776                kid: "key-1".to_owned(),
777                x5t: "x5t-example".to_owned()
778            }),
779            "the header"
780        );
781    }
782
783    #[test]
784    fn links_say_where_they_are_in_the_consoles_order() {
785        let vcon = json!({"analysis": [{"url": "https://a.example.com/t"}],
786            "dialog": [{"url": "https://media.example.com/a.wav"}, {"body": "x"}],
787            "attachments": [{}, {"url": "https://files.example.com/x.pdf"}]});
788        let found: Vec<(String, String)> = links(&vcon.to_string())
789            .into_iter()
790            .map(|link| (link.place, link.url))
791            .collect();
792        assert_eq!(
793            found,
794            [
795                (
796                    "dialog 1".to_owned(),
797                    "https://media.example.com/a.wav".to_owned()
798                ),
799                (
800                    "attachment 2".to_owned(),
801                    "https://files.example.com/x.pdf".to_owned()
802                ),
803                (
804                    "analysis 1".to_owned(),
805                    "https://a.example.com/t".to_owned()
806                ),
807            ],
808            "the links"
809        );
810    }
811
812    #[test]
813    fn a_section_shows_the_part_with_inline_media_named_by_its_size() {
814        let vcon = json!({"dialog": [{"type": "recording", "encoding": "base64url", "body": "AAAABBBB"}],
815            "subject": "Renewal", "parties": [{"name": "Ada Example"}]});
816        let text = vcon.to_string();
817        let dialog = section(&text, Part::Dialog).expect("a dialog section");
818        assert!(
819            dialog.contains("[8 characters of base64url, not shown]"),
820            "{dialog}"
821        );
822        assert!(!dialog.contains("AAAABBBB"), "{dialog}");
823        assert_eq!(
824            section(&text, Part::Subject).as_deref(),
825            Some("Renewal"),
826            "the subject"
827        );
828        let parties = section(&text, Part::Parties).expect("a parties section");
829        assert!(parties.contains("Ada Example"), "{parties}");
830    }
831
832    // Failure.
833
834    #[test]
835    fn a_view_other_than_masked_is_refused() {
836        for query in ["view=whole", "view=MASKED", "view=masked2", "view="] {
837            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
838        }
839    }
840
841    #[test]
842    fn the_view_given_twice_is_refused() {
843        for query in ["view=masked&view=masked", "view=masked&view=whole"] {
844            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
845        }
846    }
847
848    /// The masked view and a reveal are two answers: one read cannot ask
849    /// for both.
850    #[test]
851    fn the_view_beside_a_reveal_or_another_parameter_is_refused() {
852        for query in [
853            "view=masked&reveal=all",
854            "reveal=parties&view=masked",
855            "limit=3&view=masked",
856        ] {
857            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
858        }
859    }
860
861    #[test]
862    fn the_parameter_with_no_value_is_refused() {
863        for query in ["view", "view&x=1"] {
864            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
865        }
866    }
867
868    #[test]
869    fn text_that_is_not_json_is_not_read() {
870        let made = summary("{\"subject\":");
871        assert_eq!(
872            (made.form.as_str(), made.subject.as_str()),
873            ("not JSON", "not readable"),
874            "not read"
875        );
876    }
877
878    #[test]
879    fn an_encrypted_vcon_is_not_decoded() {
880        let made =
881            masked(&json!({"ciphertext": "x", "subject": "Renewal", "parties": [{"name": "Ada"}]}));
882        assert_eq!(made.form, "encrypted (JWE)", "the form");
883        assert!(made.parties.is_empty(), "no party is read");
884    }
885
886    #[test]
887    fn a_number_too_short_or_not_text_is_hidden_whole() {
888        for value in [
889            json!("555-0101"),
890            json!(2_125_550_142_u64),
891            json!(null),
892            json!(""),
893        ] {
894            assert_eq!(mask_tel(&value), "number hidden", "{value}");
895        }
896    }
897
898    #[test]
899    fn an_address_without_a_local_part_or_a_domain_is_hidden_whole() {
900        for value in [
901            json!("@example.com"),
902            json!("ada@"),
903            json!("ada@  "),
904            json!("ada"),
905            json!(7),
906        ] {
907            assert_eq!(mask_mail(&value), "address hidden", "{value}");
908        }
909    }
910
911    #[test]
912    fn text_that_is_not_a_date_time_is_never_shown() {
913        for value in [
914            "Ada called about her account",
915            "1",
916            "Jan 2 2026",
917            "2026-11-10T09:15Z",
918            "2026-11-10 09:15:00Z",
919            "2026-11-10T09:15:00",
920            "2026-11-10T09:15:00.Z",
921            "x UTC+00:00",
922        ] {
923            assert_eq!(instant(&json!(value)), "", "{value}");
924        }
925    }
926
927    #[test]
928    fn a_day_hour_second_or_offset_that_does_not_exist_is_no_time() {
929        for value in [
930            "2026-02-30T00:00:00Z",
931            "2026-13-01T00:00:00Z",
932            "2026-01-01T24:00:00Z",
933            "2026-01-01T00:60:00Z",
934            "2026-01-01T23:59:60Z",
935            "2026-01-01T00:00:00+24:00",
936            "2026-01-01T00:00:00+01:60",
937        ] {
938            assert_eq!(instant(&json!(value)), "", "{value}");
939        }
940    }
941
942    #[test]
943    fn a_party_or_dialog_that_is_not_an_object_is_named_and_not_read() {
944        assert_eq!(
945            party_line(&json!("Ada Example"), 0),
946            "Party 1: not an object",
947            "party"
948        );
949        assert_eq!(
950            dialog_line(&json!(["hello"]), 1),
951            "Dialog 2: not an object",
952            "dialog"
953        );
954    }
955
956    #[test]
957    fn a_body_that_cannot_be_read_in_parts_has_no_section_and_no_links() {
958        for text in ["{\"ciphertext\":\"x\"}", "[1]", "not JSON"] {
959            assert_eq!(section(text, Part::Parties), None, "{text}");
960            assert_eq!(links(text), [], "{text}");
961        }
962    }
963
964    #[test]
965    fn only_the_four_parts_have_a_section() {
966        let text = json!({"subject": "Renewal"}).to_string();
967        for part in [Part::Links, Part::All, Part::Audio] {
968            assert_eq!(section(&text, part), None, "{part:?}");
969        }
970    }
971
972    // Edge.
973
974    #[test]
975    fn an_encoded_parameter_is_the_parameter() {
976        for query in ["%76iew=masked", "view=%6Dasked", "vi%65w=mask%65d"] {
977            assert_eq!(from_query(Some(query)), Ok(true), "{query}");
978        }
979    }
980
981    #[test]
982    fn an_empty_piece_beside_the_view_names_nothing() {
983        for query in ["view=masked&", "&view=masked", "&&view=masked&&"] {
984            assert_eq!(from_query(Some(query)), Ok(true), "{query}");
985        }
986    }
987
988    #[test]
989    fn a_fraction_of_a_second_is_dropped_not_rounded() {
990        assert_eq!(
991            instant(&json!("2026-11-10T09:15:00.999999999Z")),
992            "2026-11-10 09:15:00 UTC+00:00",
993            "dropped"
994        );
995    }
996
997    #[test]
998    fn lower_case_t_and_z_are_read() {
999        assert_eq!(
1000            instant(&json!("2026-11-10t09:15:00z")),
1001            "2026-11-10 09:15:00 UTC+00:00",
1002            "read"
1003        );
1004    }
1005
1006    #[test]
1007    fn a_time_outside_the_years_1_to_9999_in_utc_is_no_time() {
1008        for value in [
1009            "9999-12-31T23:30:00-01:00",
1010            "0001-01-01T00:30:00+01:00",
1011            "0000-06-01T00:00:00Z",
1012        ] {
1013            assert_eq!(instant(&json!(value)), "", "{value}");
1014        }
1015        assert_eq!(
1016            instant(&json!("0001-01-01T00:00:00Z")),
1017            "0001-01-01 00:00:00 UTC+00:00",
1018            "year 1"
1019        );
1020        assert_eq!(
1021            instant(&json!("9999-12-31T23:59:59Z")),
1022            "9999-12-31 23:59:59 UTC+00:00",
1023            "year 9999"
1024        );
1025    }
1026
1027    #[test]
1028    fn a_leap_day_is_a_day() {
1029        assert_eq!(
1030            instant(&json!("2024-02-29T12:00:00Z")),
1031            "2024-02-29 12:00:00 UTC+00:00",
1032            "2024"
1033        );
1034        assert_eq!(instant(&json!("2026-02-29T12:00:00Z")), "", "2026 has none");
1035    }
1036
1037    #[test]
1038    fn a_place_written_with_a_fraction_of_zero_is_a_place() {
1039        let line = dialog_line(&json!({"type": "text", "parties": [0.0, 2.0]}), 0);
1040        assert!(line.contains("parties 1, 3"), "{line}");
1041        let line = dialog_line(&json!({"type": "text", "parties": [0, 1.5]}), 0);
1042        assert!(line.contains("no parties"), "{line}");
1043    }
1044
1045    #[test]
1046    fn a_body_with_a_byte_order_mark_is_read_as_a_browser_reads_it() {
1047        let text = text_of(b"\xef\xbb\xbf{\"subject\":\"Renewal\"}");
1048        assert_eq!(
1049            summary(&text).subject,
1050            "present, hidden",
1051            "the mark is dropped"
1052        );
1053        assert_eq!(
1054            text_of(b"{\"a\":\"\xff\"}"),
1055            "{\"a\":\"\u{fffd}\"}",
1056            "a bad byte is replaced"
1057        );
1058    }
1059
1060    #[test]
1061    fn a_domain_loses_the_spaces_javascript_trims() {
1062        for value in [
1063            "ada@ example.com\u{a0}",
1064            "ada@\u{feff}example.com",
1065            "ada@\texample.com\n",
1066        ] {
1067            assert_eq!(
1068                mask_mail(&json!(value)),
1069                "address at example.com",
1070                "{value:?}"
1071            );
1072        }
1073    }
1074
1075    #[test]
1076    fn digits_are_counted_across_punctuation_and_only_ascii_digits_count() {
1077        assert_eq!(
1078            mask_tel(&json!("+1 (212) 555-0199")),
1079            "number ending 0199",
1080            "punctuation"
1081        );
1082        assert_eq!(
1083            mask_tel(&json!("\u{661}\u{662}\u{663}\u{664}5550199")),
1084            "number hidden",
1085            "Arabic-Indic digits"
1086        );
1087    }
1088
1089    #[test]
1090    fn the_summary_holds_no_name_subject_number_or_address() {
1091        let vcon = json!({"subject": "Ada's divorce", "created_at": "Ada's birthday",
1092            "parties": [{"name": "Ada Example", "tel": "+12125550142", "mailto": "ada@example.com"}],
1093            "dialog": [{"type": "text", "start": "Ada's call", "body": "Ada said hello"}]});
1094        let made = serde_json::to_string(&masked(&vcon)).expect("JSON");
1095        for hidden in ["Ada", "divorce", "2125550142", "ada@", "hello"] {
1096            assert!(!made.contains(hidden), "{hidden} in {made}");
1097        }
1098    }
1099
1100    #[test]
1101    fn a_long_text_is_cut_at_the_limit_and_says_what_was_left_out() {
1102        let text = "x".repeat(DISPLAY_LIMIT + 5);
1103        let (kept, left) = shown(&text);
1104        assert_eq!((kept.len(), left), (DISPLAY_LIMIT, 5), "cut");
1105        assert_eq!(shown("short"), ("short", 0), "kept whole");
1106    }
1107
1108    #[test]
1109    fn a_summary_read_back_is_the_summary() {
1110        let made =
1111            masked(&json!({"dialog": [{"duration": 12.5}], "parties": [{"tel": "+12125550142"}]}));
1112        let text = serde_json::to_string(&made).expect("JSON");
1113        let back: Summary = serde_json::from_str(&text).expect("read back");
1114        assert_eq!(back, made, "the same");
1115    }
1116
1117    #[test]
1118    fn an_empty_list_section_says_none() {
1119        let text = json!({"analysis": []}).to_string();
1120        assert_eq!(
1121            section(&text, Part::Analysis).as_deref(),
1122            Some("none"),
1123            "no analysis"
1124        );
1125        assert_eq!(
1126            section(&text, Part::Subject).as_deref(),
1127            Some("none"),
1128            "no subject"
1129        );
1130    }
1131}