Skip to main content

syncular_client/
values.rs

1//! Value conversions at the client's edges: driver JSON (`{"$bytes": hex}`
2//! convention) ↔ the §2.4 row-codec values ↔ SQLite storage, plus the §11.2
3//! canonical scope JSON (contractual across implementations).
4
5use std::collections::HashMap;
6
7use serde_json::{Map, Value};
8use ssp2::primitives::{RawJson, Reader, Writer};
9use ssp2::segment::{decode_row, encode_row, Column, ColumnType, ColumnValue, Row};
10use ssp2::util::utf16_lt;
11
12use crate::schema::TableSchema;
13
14/// §5.11 client-side encryption keys (`keyId → 32-byte key`) plus optional
15/// key selection. Empty ⇒ E2EE off. `key_id_for` defaults to per-table
16/// (`keyId = table`). Always present on the client; the crypto is compiled
17/// only under the `e2ee` feature.
18#[derive(Clone, Default)]
19pub struct EncryptionConfig {
20    pub keys: HashMap<String, Vec<u8>>,
21    /// Portable per-table selector: the named non-encrypted string column in
22    /// each plaintext row contains the key id used for new envelopes.
23    pub key_id_columns: HashMap<String, String>,
24}
25
26/// Manual Debug so a stray `{config:?}` log line stays free of key material:
27/// key entries render as `id → <N bytes>`.
28impl std::fmt::Debug for EncryptionConfig {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        struct Redacted(usize);
31        impl std::fmt::Debug for Redacted {
32            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33                write!(f, "<{} bytes>", self.0)
34            }
35        }
36        let keys: std::collections::BTreeMap<&String, Redacted> = self
37            .keys
38            .iter()
39            .map(|(id, key)| (id, Redacted(key.len())))
40            .collect();
41        f.debug_struct("EncryptionConfig")
42            .field("keys", &keys)
43            .field("key_id_columns", &self.key_id_columns)
44            .finish()
45    }
46}
47
48impl Drop for EncryptionConfig {
49    fn drop(&mut self) {
50        // Best-effort native key hygiene: replacement, preflight entry, and
51        // client shutdown overwrite every owned key buffer before release.
52        for key in self.keys.values_mut() {
53            key.fill(0);
54        }
55    }
56}
57
58impl EncryptionConfig {
59    pub fn is_empty(&self) -> bool {
60        self.keys.is_empty()
61    }
62
63    /// §5.11 portable key selection: configured row column, then table name.
64    pub fn key_id_for(&self, table: &TableSchema, row: &Row) -> Result<String, String> {
65        let Some(column_name) = self.key_id_columns.get(&table.name) else {
66            return Ok(table.name.clone());
67        };
68        let Some(index) = table
69            .columns
70            .iter()
71            .position(|column| &column.name == column_name)
72        else {
73            return Err(format!(
74                "client.decrypt_failed: encryption key-id column {column_name:?} is not present on table {:?}",
75                table.name
76            ));
77        };
78        if table
79            .encrypted_columns
80            .iter()
81            .any(|column| column.index == index)
82        {
83            return Err(format!(
84                "client.decrypt_failed: encryption key-id column {column_name:?} on table {:?} must not be encrypted",
85                table.name
86            ));
87        }
88        match row.get(index).and_then(|value| value.as_ref()) {
89            Some(ColumnValue::String(key_id)) if !key_id.is_empty() => Ok(key_id.clone()),
90            _ => Err(format!(
91                "client.decrypt_failed: encryption key-id column {column_name:?} on table {:?} must contain a non-empty string",
92                table.name
93            )),
94        }
95    }
96}
97
98/// The pinned §12 snake→camel conversion (DESIGN-queries.md §5) — the Rust
99/// copy of the typegen/TS-client algorithm, kept in lockstep by shared test
100/// vectors. Leading/trailing `_` runs are preserved; middle segments split
101/// on `_` (doubled underscores drop); no acronym awareness.
102pub fn snake_to_camel(name: &str) -> String {
103    let is_mappable = {
104        let bare = name.trim_start_matches('_');
105        !bare.is_empty()
106            && bare.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
107            && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
108    };
109    if !is_mappable {
110        return name.to_owned();
111    }
112    let lead_len = name.len() - name.trim_start_matches('_').len();
113    let (lead, bare) = name.split_at(lead_len);
114    let trail_len = bare.len() - bare.trim_end_matches('_').len();
115    let (middle, trail) = bare.split_at(bare.len() - trail_len);
116    let mut segments = middle.split('_').filter(|s| !s.is_empty());
117    let Some(first) = segments.next() else {
118        return name.to_owned();
119    };
120    let mut out = String::with_capacity(name.len());
121    out.push_str(lead);
122    out.push_str(first);
123    for segment in segments {
124        let mut chars = segment.chars();
125        if let Some(head) = chars.next() {
126            out.push(head.to_ascii_uppercase());
127            out.push_str(chars.as_str());
128        }
129    }
130    out.push_str(trail);
131    out
132}
133
134/// §5 mutate key normalization: accept BOTH casings for upsert value keys —
135/// the SQL-truth snake_case and the generated row types' camelCase. A camel
136/// key renames to its column's SQL name when that is unambiguous (the alias
137/// equals no other column's exact name, and no two columns share it). A
138/// column given in both casings is an error. Unknown keys fail loud, matching
139/// the TypeScript core; silently dropping an app field would corrupt a
140/// full-row mutation while appearing successful.
141pub fn normalize_values_casing(
142    table: &TableSchema,
143    mut values: Map<String, Value>,
144) -> Result<Map<String, Value>, String> {
145    for column in &table.columns {
146        let camel = snake_to_camel(&column.name);
147        if camel == column.name {
148            continue;
149        }
150        // Exact names always win; an alias colliding with another column's
151        // real name (or with another column's alias) is not an alias.
152        if table.columns.iter().any(|c| c.name == camel) {
153            continue;
154        }
155        if table
156            .columns
157            .iter()
158            .filter(|c| snake_to_camel(&c.name) == camel)
159            .count()
160            > 1
161        {
162            continue;
163        }
164        if let Some(value) = values.remove(&camel) {
165            if values.contains_key(&column.name) {
166                return Err(format!(
167                    "table {:?}: column {:?} appears twice in mutation values (as both snake_case and camelCase) — pass it once",
168                    table.name, column.name
169                ));
170            }
171            values.insert(column.name.clone(), value);
172        }
173    }
174    for key in values.keys() {
175        if !table.columns.iter().any(|column| column.name == *key) {
176            if key.starts_with("_sync_") {
177                return Err(format!(
178                    "table {:?}: {:?} is an internal sync column and cannot appear in mutation values",
179                    table.name, key
180                ));
181            }
182            return Err(format!(
183                "table {:?}: unknown column {:?} in mutation values (snake_case and camelCase keys are accepted)",
184                table.name, key
185            ));
186        }
187    }
188    Ok(values)
189}
190
191pub fn bytes_to_hex(bytes: &[u8]) -> String {
192    let mut out = String::with_capacity(bytes.len() * 2);
193    for b in bytes {
194        out.push_str(&format!("{b:02x}"));
195    }
196    out
197}
198
199pub fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, String> {
200    if !hex.len().is_multiple_of(2) {
201        return Err("odd-length hex string".to_owned());
202    }
203    let mut out = Vec::with_capacity(hex.len() / 2);
204    let bytes = hex.as_bytes();
205    for pair in bytes.chunks(2) {
206        let s = std::str::from_utf8(pair).map_err(|_| "non-ASCII hex".to_owned())?;
207        out.push(u8::from_str_radix(s, 16).map_err(|e| format!("bad hex: {e}"))?);
208    }
209    Ok(out)
210}
211
212/// Driver JSON value → row-codec value for one column. `null`/absent maps to
213/// NULL; bytes travel as `{"$bytes": "<hex>"}`.
214pub fn json_to_column_value(
215    column: &Column,
216    value: Option<&Value>,
217) -> Result<Option<ColumnValue>, String> {
218    let value = match value {
219        None | Some(Value::Null) => return Ok(None),
220        Some(v) => v,
221    };
222    let fail = |expected: &str| {
223        Err(format!(
224            "column {:?}: expected {expected}, got {value}",
225            column.name
226        ))
227    };
228    match column.ty {
229        ColumnType::String => match value.as_str() {
230            Some(s) => Ok(Some(ColumnValue::String(s.to_owned()))),
231            None => fail("a string"),
232        },
233        ColumnType::Integer => match value.as_i64() {
234            Some(i) => Ok(Some(ColumnValue::Integer(i))),
235            None => fail("an integer"),
236        },
237        ColumnType::Float => match value.as_f64() {
238            Some(f) => Ok(Some(ColumnValue::Float(f))),
239            None => fail("a number"),
240        },
241        ColumnType::Boolean => match value.as_bool() {
242            Some(b) => Ok(Some(ColumnValue::Boolean(b))),
243            None => fail("a boolean"),
244        },
245        // `json` columns stay raw strings at the driver boundary (§2.4).
246        ColumnType::Json => match value.as_str() {
247            Some(s) => Ok(Some(ColumnValue::Json(RawJson(s.to_owned())))),
248            None => fail("a raw JSON string"),
249        },
250        // `blob_ref` (tag 7) also stays a raw string at the boundary (§5.9.1).
251        ColumnType::BlobRef => match value.as_str() {
252            Some(s) => Ok(Some(ColumnValue::BlobRef(RawJson(s.to_owned())))),
253            None => fail("a raw BlobRef JSON string"),
254        },
255        ColumnType::Bytes => match value.get("$bytes").and_then(Value::as_str) {
256            Some(hex) => Ok(Some(ColumnValue::Bytes(hex_to_bytes(hex)?))),
257            None => fail("a {\"$bytes\": hex} object"),
258        },
259        // §5.10: crdt bytes cross the boundary as {"$bytes": hex}, like bytes.
260        ColumnType::Crdt => match value.get("$bytes").and_then(Value::as_str) {
261            Some(hex) => Ok(Some(ColumnValue::Crdt(hex_to_bytes(hex)?))),
262            None => fail("a {\"$bytes\": hex} object"),
263        },
264    }
265}
266
267/// Row-codec value → driver JSON value.
268pub fn column_value_to_json(value: &Option<ColumnValue>) -> Value {
269    match value {
270        None => Value::Null,
271        Some(ColumnValue::String(s)) => Value::from(s.clone()),
272        Some(ColumnValue::Integer(i)) => Value::from(*i),
273        Some(ColumnValue::Float(f)) => {
274            serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number)
275        }
276        Some(ColumnValue::Boolean(b)) => Value::from(*b),
277        Some(ColumnValue::Json(raw)) => Value::from(raw.0.clone()),
278        Some(ColumnValue::BlobRef(raw)) => Value::from(raw.0.clone()),
279        Some(ColumnValue::Bytes(bytes)) => {
280            let mut map = Map::new();
281            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(bytes)));
282            Value::Object(map)
283        }
284        Some(ColumnValue::Crdt(bytes)) => {
285            let mut map = Map::new();
286            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(bytes)));
287            Value::Object(map)
288        }
289    }
290}
291
292/// Encode one full row (driver JSON values keyed by column name) with the
293/// generated row codec (§2.4, §6.1). §5.11: encrypted columns are encrypted
294/// here — the encode-at-send seam — before the codec serializes them as
295/// ciphertext-envelope `bytes` using `wire_columns`.
296pub fn encode_row_json(
297    table: &TableSchema,
298    row_id: &str,
299    values: &Map<String, Value>,
300    encryption: &EncryptionConfig,
301) -> Result<Vec<u8>, String> {
302    // Build the row from the LOCAL (declared-type) columns.
303    let mut row: Row = Vec::with_capacity(table.columns.len());
304    for column in &table.columns {
305        let value = json_to_column_value(column, values.get(&column.name))?;
306        if value.is_none() && !column.nullable {
307            return Err(format!(
308                "table {:?}: column {:?} is not nullable (§6.1 full-row payloads)",
309                table.name, column.name
310            ));
311        }
312        row.push(value);
313    }
314    if table.has_encrypted_columns() {
315        encrypt_row(table, row_id, &mut row, encryption)?;
316    }
317    // Serialize with the WIRE columns (encrypted columns are `bytes`).
318    let mut w = Writer::new();
319    encode_row(&mut w, &table.wire_columns, &row);
320    Ok(w.into_bytes())
321}
322
323/// Decode one row-codec payload; trailing bytes are a decode error. §5.11:
324/// encrypted columns are decrypted here — the apply seam — back to their
325/// declared-type plaintext value for the local mirror.
326pub fn decode_row_bytes(
327    table: &TableSchema,
328    payload: &[u8],
329    encryption: &EncryptionConfig,
330) -> Result<Row, String> {
331    let mut r = Reader::new(payload);
332    // Decode with the WIRE columns (encrypted columns arrive as `bytes`).
333    let mut row = decode_row(&mut r, &table.wire_columns).map_err(|e| e.to_string())?;
334    if !r.is_empty() {
335        return Err("row payload has trailing bytes".to_owned());
336    }
337    if table.has_encrypted_columns() {
338        decrypt_row(table, &mut row, encryption)?;
339    }
340    Ok(row)
341}
342
343/// §5.11: decrypt the encrypted columns of an already-decoded segment row
344/// (rows segments decode via their own column table, so decryption is a
345/// post-decode pass over the positional values).
346pub fn decrypt_segment_row(
347    table: &TableSchema,
348    row: &mut Row,
349    encryption: &EncryptionConfig,
350) -> Result<(), String> {
351    decrypt_row(table, row, encryption)
352}
353
354// -- §5.11 encrypt/decrypt seam (feature-gated) ------------------------------
355
356#[cfg(feature = "e2ee")]
357fn encrypt_row(
358    table: &TableSchema,
359    _row_id: &str,
360    row: &mut Row,
361    encryption: &EncryptionConfig,
362) -> Result<(), String> {
363    use rand_core::RngCore;
364    use ssp2::crypto::{encrypt_value, NONCE_LENGTH};
365    for enc in &table.encrypted_columns {
366        let Some(value) = row.get(enc.index).and_then(|v| v.as_ref()) else {
367            continue; // NULL stays NULL (§5.11)
368        };
369        let plain = column_value_to_plain(value)?;
370        let key_id = encryption.key_id_for(table, row)?;
371        let key = encryption
372            .keys
373            .get(&key_id)
374            .ok_or_else(|| format!("client.decrypt_failed: no key for keyId {key_id:?}"))?;
375        let mut nonce = [0u8; NONCE_LENGTH];
376        rand_core::OsRng.fill_bytes(&mut nonce);
377        let envelope = encrypt_value(&plain, &key_id, key, nonce)?;
378        row[enc.index] = Some(ColumnValue::Bytes(envelope));
379    }
380    Ok(())
381}
382
383#[cfg(feature = "e2ee")]
384fn decrypt_row(
385    table: &TableSchema,
386    row: &mut Row,
387    encryption: &EncryptionConfig,
388) -> Result<(), String> {
389    use ssp2::crypto::{decrypt_value, DeclaredType};
390    for enc in &table.encrypted_columns {
391        let Some(value) = row.get(enc.index).and_then(|v| v.as_ref()) else {
392            continue;
393        };
394        let ColumnValue::Bytes(envelope) = value else {
395            return Err(format!(
396                "client.decrypt_failed: encrypted column at index {} is not bytes",
397                enc.index
398            ));
399        };
400        let declared = DeclaredType::from_name(&enc.declared_type)
401            .ok_or_else(|| format!("unknown declaredType {:?}", enc.declared_type))?;
402        let keys = &encryption.keys;
403        let plain = decrypt_value(declared, envelope, |id| keys.get(id).cloned())
404            .map_err(|e| e.to_string())?;
405        row[enc.index] = Some(plain_to_column_value(plain));
406    }
407    Ok(())
408}
409
410/// Without the `e2ee` feature, a schema with encrypted columns is a
411/// misconfiguration — fail loud rather than ship plaintext.
412#[cfg(not(feature = "e2ee"))]
413fn encrypt_row(
414    table: &TableSchema,
415    _row_id: &str,
416    _row: &mut Row,
417    _encryption: &EncryptionConfig,
418) -> Result<(), String> {
419    Err(format!(
420        "table {:?} has encrypted columns but this build lacks the e2ee feature (§5.11)",
421        table.name
422    ))
423}
424
425#[cfg(not(feature = "e2ee"))]
426fn decrypt_row(
427    table: &TableSchema,
428    _row: &mut Row,
429    _encryption: &EncryptionConfig,
430) -> Result<(), String> {
431    Err(format!(
432        "table {:?} has encrypted columns but this build lacks the e2ee feature (§5.11)",
433        table.name
434    ))
435}
436
437#[cfg(feature = "e2ee")]
438fn column_value_to_plain(value: &ColumnValue) -> Result<ssp2::crypto::PlainValue, String> {
439    use ssp2::crypto::PlainValue;
440    Ok(match value {
441        ColumnValue::String(s) => PlainValue::String(s.clone()),
442        ColumnValue::Integer(i) => PlainValue::Integer(*i),
443        ColumnValue::Float(f) => PlainValue::Float(*f),
444        ColumnValue::Boolean(b) => PlainValue::Boolean(*b),
445        ColumnValue::Json(j) => PlainValue::Json(j.0.clone()),
446        ColumnValue::BlobRef(j) => PlainValue::BlobRef(j.0.clone()),
447        ColumnValue::Bytes(b) => PlainValue::Bytes(b.clone()),
448        ColumnValue::Crdt(_) => return Err("crdt columns cannot be encrypted (§5.11)".to_owned()),
449    })
450}
451
452#[cfg(feature = "e2ee")]
453fn plain_to_column_value(value: ssp2::crypto::PlainValue) -> ColumnValue {
454    use ssp2::crypto::PlainValue;
455    match value {
456        PlainValue::String(s) => ColumnValue::String(s),
457        PlainValue::Integer(i) => ColumnValue::Integer(i),
458        PlainValue::Float(f) => ColumnValue::Float(f),
459        PlainValue::Boolean(b) => ColumnValue::Boolean(b),
460        PlainValue::Json(s) => ColumnValue::Json(RawJson(s)),
461        PlainValue::BlobRef(s) => ColumnValue::BlobRef(RawJson(s)),
462        PlainValue::Bytes(b) => ColumnValue::Bytes(b),
463    }
464}
465
466/// Render a primary-key value as the wire `rowId` string.
467pub fn render_row_id(value: &Option<ColumnValue>) -> Result<String, String> {
468    match value {
469        Some(ColumnValue::String(s)) => Ok(s.clone()),
470        Some(ColumnValue::Integer(i)) => Ok(i.to_string()),
471        Some(ColumnValue::Float(f)) => Ok(f.to_string()),
472        Some(ColumnValue::Boolean(b)) => Ok(b.to_string()),
473        Some(ColumnValue::Json(raw)) => Ok(raw.0.clone()),
474        Some(ColumnValue::BlobRef(_)) => Err("blob_ref column cannot be a rowId".to_owned()),
475        Some(ColumnValue::Bytes(_)) => Err("bytes column cannot be a rowId".to_owned()),
476        Some(ColumnValue::Crdt(_)) => Err("crdt column cannot be a rowId".to_owned()),
477        None => Err("primary key value is missing".to_owned()),
478    }
479}
480
481/// Driver JSON value → wire `rowId` string (for optimistic upserts).
482pub fn render_row_id_json(value: Option<&Value>) -> Result<String, String> {
483    match value {
484        Some(Value::String(s)) => Ok(s.clone()),
485        Some(Value::Number(n)) => Ok(n.to_string()),
486        Some(Value::Bool(b)) => Ok(b.to_string()),
487        _ => Err("primary key value is missing or not renderable".to_owned()),
488    }
489}
490
491fn sort_utf16(values: &mut [String]) {
492    values.sort_by(|a, b| {
493        if utf16_lt(a, b) {
494            std::cmp::Ordering::Less
495        } else if utf16_lt(b, a) {
496            std::cmp::Ordering::Greater
497        } else {
498            std::cmp::Ordering::Equal
499        }
500    });
501}
502
503/// Sort scope-map keys into ascending code-unit order (the canonical `map`
504/// encoding of the Conventions section).
505pub fn sort_scope_map(map: &mut [(String, Vec<String>)]) {
506    map.sort_by(|a, b| {
507        if utf16_lt(&a.0, &b.0) {
508            std::cmp::Ordering::Less
509        } else if utf16_lt(&b.0, &a.0) {
510            std::cmp::Ordering::Greater
511        } else {
512            std::cmp::Ordering::Equal
513        }
514    });
515}
516
517/// §11.2 canonical JSON of a scope map: keys sorted by code-unit, value
518/// lists sorted and deduplicated, no insignificant whitespace.
519pub fn canonical_scope_json(scopes: &[(String, Vec<String>)]) -> String {
520    let mut entries: Vec<(String, Vec<String>)> = scopes.to_vec();
521    sort_scope_map(&mut entries);
522    let mut out = String::from("{");
523    for (i, (key, values)) in entries.iter().enumerate() {
524        if i > 0 {
525            out.push(',');
526        }
527        let mut sorted = values.clone();
528        sort_utf16(&mut sorted);
529        sorted.dedup();
530        out.push_str(&serde_json::to_string(key).expect("string serializes"));
531        out.push_str(":[");
532        for (j, value) in sorted.iter().enumerate() {
533            if j > 0 {
534                out.push(',');
535            }
536            out.push_str(&serde_json::to_string(value).expect("string serializes"));
537        }
538        out.push(']');
539    }
540    out.push('}');
541    out
542}
543
544/// Scope map as a driver JSON object (`variable → list of values`, §3.2).
545pub fn scope_map_to_json(scopes: &[(String, Vec<String>)]) -> Value {
546    let mut map = Map::new();
547    for (key, values) in scopes {
548        map.insert(
549            key.clone(),
550            Value::Array(values.iter().map(|v| Value::from(v.clone())).collect()),
551        );
552    }
553    Value::Object(map)
554}
555
556/// Driver JSON object → scope map, preserving key order.
557pub fn json_to_scope_map(value: &Value) -> Result<Vec<(String, Vec<String>)>, String> {
558    let object = value
559        .as_object()
560        .ok_or_else(|| "scope map must be an object".to_owned())?;
561    let mut out = Vec::with_capacity(object.len());
562    for (key, values) in object {
563        let list = values
564            .as_array()
565            .ok_or_else(|| format!("scope values for {key:?} must be a list (§0)"))?;
566        let mut strings = Vec::with_capacity(list.len());
567        for v in list {
568            strings.push(
569                v.as_str()
570                    .ok_or_else(|| format!("scope value for {key:?} is not a string"))?
571                    .to_owned(),
572            );
573        }
574        out.push((key.clone(), strings));
575    }
576    Ok(out)
577}
578
579#[cfg(test)]
580mod naming_tests {
581    use serde_json::{json, Map, Value};
582    use ssp2::segment::{Column, ColumnType, ColumnValue, Row};
583
584    use super::{normalize_values_casing, snake_to_camel, EncryptionConfig};
585    use crate::schema::{EncryptedColumn, TableSchema};
586
587    #[test]
588    fn snake_to_camel_pinned_vectors() {
589        for (input, expected) in [
590            ("created_at", "createdAt"),
591            ("col_2", "col2"),
592            ("user_id", "userId"),
593            ("_internal", "_internal"),
594            ("__foo_bar", "__fooBar"),
595            ("row_", "row_"),
596            ("id_url", "idUrl"),
597            ("api_key", "apiKey"),
598            ("title", "title"),
599            ("alreadyCamel", "alreadyCamel"),
600            ("a__b", "aB"),
601            ("_lead_and_trail_", "_leadAndTrail_"),
602            ("count(*)", "count(*)"),
603        ] {
604            assert_eq!(snake_to_camel(input), expected, "input {input:?}");
605        }
606    }
607
608    #[test]
609    fn portable_key_selector_reads_a_non_encrypted_string_column() {
610        let columns = vec![
611            Column {
612                name: "id".to_owned(),
613                ty: ColumnType::String,
614                nullable: false,
615            },
616            Column {
617                name: "encryption_key_id".to_owned(),
618                ty: ColumnType::String,
619                nullable: false,
620            },
621            Column {
622                name: "note".to_owned(),
623                ty: ColumnType::String,
624                nullable: false,
625            },
626        ];
627        let table = TableSchema {
628            name: "patients".to_owned(),
629            columns: columns.clone(),
630            wire_columns: columns,
631            primary_key: "id".to_owned(),
632            pk_index: 0,
633            scope_variables: Vec::new(),
634            indexes: Vec::new(),
635            fts_indexes: Vec::new(),
636            encrypted_columns: vec![EncryptedColumn {
637                index: 2,
638                declared_type: "string".to_owned(),
639            }],
640        };
641        let mut config = EncryptionConfig::default();
642        config
643            .key_id_columns
644            .insert("patients".to_owned(), "encryption_key_id".to_owned());
645        let row: Row = vec![
646            Some(ColumnValue::String("patient-1".to_owned())),
647            Some(ColumnValue::String("practice-key-v1".to_owned())),
648            Some(ColumnValue::String("Identity".to_owned())),
649        ];
650        assert_eq!(
651            config.key_id_for(&table, &row).expect("selects key"),
652            "practice-key-v1"
653        );
654    }
655
656    #[test]
657    fn debug_render_redacts_key_material() {
658        let mut config = EncryptionConfig::default();
659        config
660            .keys
661            .insert("practice-key-v1".to_owned(), vec![0xAB; 32]);
662        config
663            .key_id_columns
664            .insert("patients".to_owned(), "encryption_key_id".to_owned());
665        let rendered = format!("{config:?}");
666        assert!(rendered.contains("practice-key-v1"), "{rendered}");
667        assert!(rendered.contains("<32 bytes>"), "{rendered}");
668        assert!(rendered.contains("encryption_key_id"), "{rendered}");
669        // Raw byte values never appear (0xAB renders as 171 under derive).
670        assert!(!rendered.contains("171"), "{rendered}");
671        assert!(!rendered.contains("0xAB"), "{rendered}");
672    }
673
674    fn table(names: &[&str]) -> TableSchema {
675        let columns: Vec<Column> = names
676            .iter()
677            .map(|n| Column {
678                name: (*n).to_owned(),
679                ty: ColumnType::String,
680                nullable: true,
681            })
682            .collect();
683        TableSchema {
684            name: "t".to_owned(),
685            columns: columns.clone(),
686            wire_columns: columns,
687            primary_key: "id".to_owned(),
688            pk_index: 0,
689            scope_variables: Vec::new(),
690            indexes: Vec::new(),
691            fts_indexes: Vec::new(),
692            encrypted_columns: Vec::new(),
693        }
694    }
695
696    fn map(entries: &[(&str, &str)]) -> Map<String, Value> {
697        entries
698            .iter()
699            .map(|(k, v)| ((*k).to_owned(), json!(v)))
700            .collect()
701    }
702
703    #[test]
704    fn camel_keys_normalize_to_sql_names() {
705        let t = table(&["id", "list_id", "updated_at_ms"]);
706        let out = normalize_values_casing(
707            &t,
708            map(&[("id", "x"), ("listId", "l"), ("updatedAtMs", "9")]),
709        )
710        .expect("normalizes");
711        assert_eq!(out.get("list_id"), Some(&json!("l")));
712        assert_eq!(out.get("updated_at_ms"), Some(&json!("9")));
713        assert!(!out.contains_key("listId"));
714    }
715
716    #[test]
717    fn snake_keys_pass_through() {
718        let t = table(&["id", "list_id"]);
719        let out = normalize_values_casing(&t, map(&[("id", "x"), ("list_id", "l")])).expect("ok");
720        assert_eq!(out.get("list_id"), Some(&json!("l")));
721    }
722
723    #[test]
724    fn both_casings_for_one_column_is_an_error() {
725        let t = table(&["id", "list_id"]);
726        let err = normalize_values_casing(&t, map(&[("list_id", "a"), ("listId", "b")]))
727            .expect_err("rejects");
728        assert!(err.contains("both snake_case and camelCase"), "{err}");
729    }
730
731    #[test]
732    fn an_alias_colliding_with_a_real_column_never_steals_it() {
733        // `col_2` camel-maps to `col2`, which IS a column: exact wins, no rename.
734        let t = table(&["id", "col_2", "col2"]);
735        let out = normalize_values_casing(&t, map(&[("id", "x"), ("col2", "v")])).expect("ok");
736        assert_eq!(out.get("col2"), Some(&json!("v")));
737        assert!(!out.contains_key("col_2"));
738    }
739
740    #[test]
741    fn unknown_and_internal_columns_fail_loud() {
742        let t = table(&["id", "title"]);
743        let unknown = normalize_values_casing(&t, map(&[("id", "x"), ("typo", "v")]))
744            .expect_err("unknown field");
745        assert!(unknown.contains("unknown column"), "{unknown}");
746        let internal = normalize_values_casing(&t, map(&[("id", "x"), ("_sync_version", "1")]))
747            .expect_err("internal field");
748        assert!(internal.contains("internal sync column"), "{internal}");
749    }
750}