//! Searching a sealed table beyond this copy (sealing plan §4, lane //! blind-search L7). //! //! The copy holds plaintext of what it pulled, so ink and word-start search //! run over it as over any table. What it does not hold (a message older than //! its window) only the object holds, sealed. This asks the object by blind //! tokens: the device makes each blind column's query tokens with BK(t), //! `GET /v1/blind?table=&tok=…&rows=1` answers the rows holding every token //! as the object stores them, and the device opens each and holds it to the //! words in plaintext ([`blind::row_match`]), which drops a longer word behind //! the last word's six-letter prefix token and any token collision. //! //! **Nothing but tokens leaves the device:** the request names the table and //! decimal tokens, never a word. A row that does not open is answered by //! name (`unopened`), never dropped and never shown blank. No key is a //! refusal by name (`seal_key_missing`); nothing falls back to clear. use std::collections::HashSet; use serde_json::{Map, Value}; use cotton_core::definitions::seal::SealSpec; use cotton_core::seal::{blind, blind_key, SealError}; use super::Sealer; /// Most ids one column's ask reads (`/v1/blind` answers at most 1000). pub const BLIND_ROWS: usize = 1000; /// One row the object holds that holds the query, opened. #[derive(Debug, Clone, PartialEq)] pub struct BlindHit { pub id: String, /// The blind column holding every query word. pub column: String, /// The row as the copy would fold it: clear and sealed columns together. pub row: Map, } /// What a search beyond the copy found. #[derive(Debug, Clone, Default, PartialEq)] pub struct BlindFound { /// The hits, newest first by the table's date column when it names one. pub hits: Vec, /// Hits by token whose rows did not open, by id and code. pub unopened: Vec<(String, String)>, } impl Sealer { /// `query`'s tokens for each `blind` column of `table`, in wire form; a /// column whose query keeps no word is left out. pub fn query_tokens(&self, table: &str, spec: &SealSpec, query: &str) -> Result)>, SealError> { let bk = blind_key(&self.dk()?, &self.database_id, table)?; Ok(spec .blind .iter() .map(|column| (column.clone(), blind::wire(&blind::query_tokens(&bk, column, query)))) .filter(|(_, tokens)| !tokens.is_empty()) .collect()) } } /// The `/v1/blind` route of one column's ask. pub fn blind_path(table: &str, tokens: &[String], limit: usize) -> String { format!("/v1/blind?table={}&tok={}&limit={}&rows=1", url_part(table), tokens.join(","), limit.clamp(1, BLIND_ROWS)) } fn url_part(text: &str) -> String { text.bytes() .map(|b| match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), _ => format!("%{b:02X}"), }) .collect() } /// Search `table` on the object for `query`, skipping every row `held` says /// this copy holds already (its own search finds those). `get` answers a GET /// of a route on the object (the phone's door). At most `limit` hits. #[allow(clippy::too_many_arguments)] pub fn search_beyond( sealer: &Sealer, table: &str, spec: &SealSpec, date: Option<&str>, query: &str, limit: usize, held: &dyn Fn(&str) -> bool, get: &mut dyn FnMut(&str) -> Result, ) -> Result { let asks = sealer.query_tokens(table, spec, query).map_err(|error| format!("{}: {error}", error.code()))?; let mut found = BlindFound::default(); let mut seen: HashSet = HashSet::new(); for (_, tokens) in asks { let answer = get(&blind_path(table, &tokens, BLIND_ROWS))?; let rows = answer.get("rows").and_then(Value::as_array).ok_or_else(|| "the object's blind answer carried no rows".to_string())?; for row in rows { let Some(id) = row.get("id").and_then(Value::as_str) else { continue }; if held(id) || !seen.insert(id.to_string()) { continue; } let Some(data) = row.get("data").and_then(Value::as_object) else { continue }; match sealer.open(table, id, data) { Ok(open) => { if let Some(column) = blind::row_match(spec, &open, query) { found.hits.push(BlindHit { id: id.to_string(), column: column.to_string(), row: open }); } } Err(error) => found.unopened.push((id.to_string(), error.code().to_string())), } } } if let Some(date) = date { let at = |hit: &BlindHit| hit.row.get(date).and_then(Value::as_str).map(str::to_string); found.hits.sort_by(|a, b| at(b).cmp(&at(a)).then_with(|| a.id.cmp(&b.id))); } found.hits.truncate(limit); Ok(found) } #[cfg(test)] #[path = "search_tests.rs"] mod tests;