Cotton code
246 lines · 9.7 KB · RustRaw
//! The blind index (plan §4): words of sealed columns made into tokens the//! Worker can match without reading a word.//!//! ```text//! normalise(text) = NFC( drop diacritical marks ( NFD( lowercase( NFKC(text) ) ) ) )//! words(text)     = maximal runs of [Alphabetic | Number | Mark] in normalise(text),//!                   kept when ≥ 2 characters and not a stopword (stopwords.json, every language at once)//! word token      = trunc64(HMAC-SHA256(BK(t), "w|" column "|" word))//! prefix token    = trunc64(HMAC-SHA256(BK(t), "p|" column "|" prefix))   prefixes of 3..=min(6, len) characters//! exact token     = trunc64(HMAC-SHA256(BK(t), "x|" column "|" NFKC(trim(value))))//! trunc64         = the first 8 bytes, big-endian, as a SIGNED 64-bit integer (SQLite's INTEGER)//! wire form       = that integer in decimal, as a string (JavaScript numbers cannot hold it)//! ```//!//! "Drop diacritical marks" drops only the combining-diacritics blocks//! (U+0300–036F, 1AB0–1AFF, 1DC0–1DFF, 20D0–20FF, FE20–FE2F), so `café` is//! `cafe` while a Devanagari vowel sign or virama stays: a Hindi word keeps its//! letters. A word is counted in Unicode scalar values (JavaScript `[...w]`).//!//! **A word's prefixes include the word itself when it is 3 to 6 long**, so a//! query's last word is ONE prefix token whether a row holds that word or a//! longer one. A last word longer than 6 queries its 6-character prefix and the//! opener verifies the hit in plaintext. A last word of 2 is an exact word.//!//! Exact columns (`blind_exact`: external ids, handles, addresses) are not//! lowercased: the caller normalises what its kind needs (E.164, a lowercased//! address) before asking.use std::collections::BTreeSet;use std::sync::OnceLock;use hmac::{Hmac, Mac};use serde_json::{Map, Value};use sha2::Sha256;use unicode_normalization::char::is_combining_mark;use unicode_normalization::UnicodeNormalization;use super::keys::Key32;use crate::definitions::SealSpec;/// Shortest word indexed, in characters.pub const MIN_WORD: usize = 2;/// Shortest and longest prefix indexed, in characters.pub const MIN_PREFIX: usize = 3;pub const MAX_PREFIX: usize = 6;/// One blind token.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]pub struct Token(pub i64);impl Token {    /// The decimal text `args.blind` and `GET /v1/blind` carry.    pub fn wire(self) -> String {        self.0.to_string()    }}/// The stopword lists, as shipped.pub const STOPWORDS_JSON: &str = include_str!("stopwords.json");fn stopwords() -> &'static BTreeSet<String> {    static SET: OnceLock<BTreeSet<String>> = OnceLock::new();    SET.get_or_init(|| {        let lists: std::collections::BTreeMap<String, Vec<String>> = serde_json::from_str(STOPWORDS_JSON).expect("stopwords.json is a map of lists");        lists.into_values().flatten().map(|w| normalise(&w)).collect()    })}fn is_diacritic(c: char) -> bool {    matches!(c as u32, 0x0300..=0x036F | 0x1AB0..=0x1AFF | 0x1DC0..=0x1DFF | 0x20D0..=0x20FF | 0xFE20..=0xFE2F)}/// The text a word is cut from.pub fn normalise(text: &str) -> String {    let folded: String = text.nfkc().collect::<String>().to_lowercase();    folded.nfd().filter(|c| !is_diacritic(*c)).nfc().collect()}fn is_word_char(c: char) -> bool {    c.is_alphabetic() || c.is_numeric() || is_combining_mark(c)}/// Every word of a text, normalised, in order, repeats kept: runs of letters,/// digits and marks, before the length and stopword filter.fn runs(text: &str) -> Vec<String> {    normalise(text)        .split(|c: char| !is_word_char(c))        .filter(|w| !w.is_empty())        .map(str::to_string)        .collect()}/// The words a text is indexed by, in order, repeats kept.pub fn words(text: &str) -> Vec<String> {    runs(text)        .into_iter()        .filter(|w| w.chars().count() >= MIN_WORD && !stopwords().contains(w))        .collect()}fn token(bk: &Key32, kind: &str, column: &str, value: &str) -> Token {    let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(bk.as_slice()).expect("HMAC takes any key length");    mac.update(format!("{kind}|{column}|{value}").as_bytes());    let digest = mac.finalize().into_bytes();    Token(i64::from_be_bytes(digest[..8].try_into().expect("8 bytes")))}pub fn word_token(bk: &Key32, column: &str, word: &str) -> Token {    token(bk, "w", column, word)}pub fn prefix_token(bk: &Key32, column: &str, prefix: &str) -> Token {    token(bk, "p", column, prefix)}/// The exact value as tokenised: NFKC, trimmed.pub fn normalise_exact(value: &str) -> String {    value.nfkc().collect::<String>().trim().to_string()}pub fn exact_token(bk: &Key32, column: &str, value: &str) -> Option<Token> {    let value = normalise_exact(value);    (!value.is_empty()).then(|| token(bk, "x", column, &value))}/// A row id only a holder of `bk` can make (sealing plan §2.2: "ids of/// sealed rows are random UUIDs"): uuid-shaped, from HMAC-SHA256(bk,/// `"i|" || domain || "|" || value`), the same for the same value every time,/// so two devices land a row made from the same plaintext on one id, and the/// Worker learns nothing of the value from the id. The `i` domain is apart/// from every token's (`w`, `p`, `x`).pub fn keyed_id(bk: &Key32, domain: &str, value: &str) -> String {    let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(bk.as_slice()).expect("HMAC takes any key length");    mac.update(format!("i|{domain}|{value}").as_bytes());    let mut b: [u8; 16] = mac.finalize().into_bytes()[..16].try_into().expect("16 bytes");    // Version 4 and the RFC 4122 variant, so it reads as any random id.    b[6] = (b[6] & 0x0f) | 0x40;    b[8] = (b[8] & 0x3f) | 0x80;    let h = hex::encode(b);    format!("{}-{}-{}-{}-{}", &h[0..8], &h[8..12], &h[12..16], &h[16..20], &h[20..32])}fn prefix(word: &str, n: usize) -> String {    word.chars().take(n).collect()}/// The tokens one text of a `blind` column adds to its row.pub fn text_tokens(bk: &Key32, column: &str, text: &str) -> BTreeSet<Token> {    let mut out = BTreeSet::new();    for word in words(text) {        out.insert(word_token(bk, column, &word));        let len = word.chars().count();        for n in MIN_PREFIX..=len.min(MAX_PREFIX) {            out.insert(prefix_token(bk, column, &prefix(&word, n)));        }    }    out}/// The text of a cell as indexed: a string, a number, or the strings and/// numbers of an array. Anything else adds no token.fn cell_texts(value: &Value) -> Vec<String> {    match value {        Value::String(s) => vec![s.clone()],        Value::Number(n) => vec![n.to_string()],        Value::Array(items) => items.iter().flat_map(cell_texts).collect(),        _ => Vec::new(),    }}/// Every token of a row (its plaintext, before sealing), de-duplicated: what/// travels as `args.blind`.pub fn row_tokens(bk: &Key32, spec: &SealSpec, row: &Map<String, Value>) -> BTreeSet<Token> {    let mut out = BTreeSet::new();    for column in &spec.blind {        for text in row.get(column).map(cell_texts).unwrap_or_default() {            out.extend(text_tokens(bk, column, spec.indexed(column, &text)));        }    }    for column in &spec.blind_exact {        for text in row.get(column).map(cell_texts).unwrap_or_default() {            out.extend(exact_token(bk, column, &text));        }    }    out}/// The tokens a query over one column intersects: each word's word token, the/// last word's prefix token (see the module header). Stopwords and one-letter/// words are dropped as the index drops them. Empty when nothing is left.pub fn query_tokens(bk: &Key32, column: &str, query: &str) -> Vec<Token> {    let words = words(query);    let mut out: Vec<Token> = Vec::new();    for (i, word) in words.iter().enumerate() {        let len = word.chars().count();        let token = if i + 1 == words.len() && len >= MIN_PREFIX {            prefix_token(bk, column, &prefix(word, len.min(MAX_PREFIX)))        } else {            word_token(bk, column, word)        };        if !out.contains(&token) {            out.push(token);        }    }    out}/// Whether `text` holds `query` as a blind search means it: every query/// word but the last is a word of the text, and the last starts one (or is/// one, at two characters). Words are the index's own ([`words`]), so a/// stopword or a one-letter word asks nothing, and a query left with no word/// holds nothing. It is what a hit by [`query_tokens`] is held to once opened/// (the TypeScript twin is `blindMatches`): the tokens find every row this/// holds, and this drops the rest — a longer word behind the last word's/// six-character prefix ("conferred" for "conference"), a truncated token's/// collision, a stored token the sealed text no longer holds.pub fn matches(text: &str, query: &str) -> bool {    let asked = words(query);    if asked.is_empty() {        return false;    }    let held = words(text);    asked.iter().enumerate().all(|(i, word)| {        if i + 1 == asked.len() && word.chars().count() >= MIN_PREFIX {            held.iter().any(|h| h.starts_with(word.as_str()))        } else {            held.contains(word)        }    })}/// The first `blind` column of an opened row that holds `query` ([`matches`]/// over the column's texts read together, as [`row_tokens`] reads them), or/// none.pub fn row_match<'a>(spec: &'a SealSpec, row: &Map<String, Value>, query: &str) -> Option<&'a str> {    spec.blind.iter().find(|column| matches(&row.get(column.as_str()).map(cell_texts).unwrap_or_default().join("\n"), query)).map(String::as_str)}/// The wire form of a set of tokens, in order.pub fn wire<'a>(tokens: impl IntoIterator<Item = &'a Token>) -> Vec<String> {    tokens.into_iter().map(|t| t.wire()).collect()}#[cfg(test)]#[path = "blind_tests.rs"]mod tests;