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::{
10    decode_row, encode_row, encode_sparse_row, Column, ColumnType, ColumnValue, Row, SparseRow,
11    SparseSlot,
12};
13use ssp2::util::utf16_lt;
14
15use crate::schema::TableSchema;
16
17/// §5.11 client-side encryption keys (`keyId → 32-byte key`) plus optional
18/// key selection. Empty ⇒ E2EE off. `key_id_for` defaults to per-table
19/// (`keyId = table`). Always present on the client; the crypto is compiled
20/// only under the `e2ee` feature.
21#[derive(Clone, Default)]
22pub struct EncryptionConfig {
23    pub keys: HashMap<String, Vec<u8>>,
24    /// Portable per-table selector: the named non-encrypted string column in
25    /// each plaintext row contains the key id used for new envelopes.
26    pub key_id_columns: HashMap<String, String>,
27}
28
29/// Manual Debug so a stray `{config:?}` log line stays free of key material:
30/// key entries render as `id → <N bytes>`.
31impl std::fmt::Debug for EncryptionConfig {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        struct Redacted(usize);
34        impl std::fmt::Debug for Redacted {
35            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36                write!(f, "<{} bytes>", self.0)
37            }
38        }
39        let keys: std::collections::BTreeMap<&String, Redacted> = self
40            .keys
41            .iter()
42            .map(|(id, key)| (id, Redacted(key.len())))
43            .collect();
44        f.debug_struct("EncryptionConfig")
45            .field("keys", &keys)
46            .field("key_id_columns", &self.key_id_columns)
47            .finish()
48    }
49}
50
51impl Drop for EncryptionConfig {
52    fn drop(&mut self) {
53        // Best-effort native key hygiene: replacement, preflight entry, and
54        // client shutdown overwrite every owned key buffer before release.
55        for key in self.keys.values_mut() {
56            key.fill(0);
57        }
58    }
59}
60
61impl EncryptionConfig {
62    pub fn is_empty(&self) -> bool {
63        self.keys.is_empty()
64    }
65
66    /// §5.11 portable key selection: configured row column, then table name.
67    /// Encode-seam failures carry `client.encrypt_failed` (never the apply-
68    /// seam `client.decrypt_failed`). The caller supplies the presence set
69    /// first with the stored local row merged into an absent selector.
70    pub fn key_id_for(&self, table: &TableSchema, row: &Row) -> Result<String, String> {
71        let Some(column_name) = self.key_id_columns.get(&table.name) else {
72            return Ok(table.name.clone());
73        };
74        let Some(index) = table
75            .columns
76            .iter()
77            .position(|column| &column.name == column_name)
78        else {
79            return Err(format!(
80                "client.encrypt_failed: encryption key-id column {column_name:?} is not present on table {:?}",
81                table.name
82            ));
83        };
84        if table
85            .encrypted_columns
86            .iter()
87            .any(|column| column.index == index)
88        {
89            return Err(format!(
90                "client.encrypt_failed: encryption key-id column {column_name:?} on table {:?} must not be encrypted",
91                table.name
92            ));
93        }
94        match row.get(index).and_then(|value| value.as_ref()) {
95            Some(ColumnValue::String(key_id)) if !key_id.is_empty() => Ok(key_id.clone()),
96            _ => Err(format!(
97                "client.encrypt_failed: encryption key-id column {column_name:?} on table {:?} must contain a non-empty string",
98                table.name
99            )),
100        }
101    }
102}
103
104/// The pinned snake→camel conversion. The Rust
105/// copy of the typegen/TS-client algorithm, kept in lockstep by shared test
106/// vectors. Leading/trailing `_` runs are preserved; middle segments split
107/// on `_` (doubled underscores drop); no acronym awareness.
108pub fn snake_to_camel(name: &str) -> String {
109    let is_mappable = {
110        let bare = name.trim_start_matches('_');
111        !bare.is_empty()
112            && bare.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
113            && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
114    };
115    if !is_mappable {
116        return name.to_owned();
117    }
118    let lead_len = name.len() - name.trim_start_matches('_').len();
119    let (lead, bare) = name.split_at(lead_len);
120    let trail_len = bare.len() - bare.trim_end_matches('_').len();
121    let (middle, trail) = bare.split_at(bare.len() - trail_len);
122    let mut segments = middle.split('_').filter(|s| !s.is_empty());
123    let Some(first) = segments.next() else {
124        return name.to_owned();
125    };
126    let mut out = String::with_capacity(name.len());
127    out.push_str(lead);
128    out.push_str(first);
129    for segment in segments {
130        let mut chars = segment.chars();
131        if let Some(head) = chars.next() {
132            out.push(head.to_ascii_uppercase());
133            out.push_str(chars.as_str());
134        }
135    }
136    out.push_str(trail);
137    out
138}
139
140/// §5 mutate key normalization: accept BOTH casings for upsert value keys —
141/// the SQL-truth snake_case and the generated row types' camelCase. A camel
142/// key renames to its column's SQL name when that is unambiguous (the alias
143/// equals no other column's exact name, and no two columns share it). A
144/// column given in both casings is an error. Unknown keys fail loud, matching
145/// the TypeScript core; silently dropping an app field would corrupt a
146/// full-row mutation while appearing successful.
147pub fn normalize_values_casing(
148    table: &TableSchema,
149    mut values: Map<String, Value>,
150) -> Result<Map<String, Value>, String> {
151    for column in &table.columns {
152        let camel = snake_to_camel(&column.name);
153        if camel == column.name {
154            continue;
155        }
156        // Exact names always win; an alias colliding with another column's
157        // real name (or with another column's alias) is not an alias.
158        if table.columns.iter().any(|c| c.name == camel) {
159            continue;
160        }
161        if table
162            .columns
163            .iter()
164            .filter(|c| snake_to_camel(&c.name) == camel)
165            .count()
166            > 1
167        {
168            continue;
169        }
170        if let Some(value) = values.remove(&camel) {
171            if values.contains_key(&column.name) {
172                return Err(format!(
173                    "sync.invalid_request: table {:?}: column {:?} appears twice in mutation values (as both snake_case and camelCase) — pass it once",
174                    table.name, column.name
175                ));
176            }
177            values.insert(column.name.clone(), value);
178        }
179    }
180    for key in values.keys() {
181        if !table.columns.iter().any(|column| column.name == *key) {
182            if key.starts_with("_sync_") {
183                return Err(format!(
184                    "sync.invalid_request: table {:?}: {:?} is an internal sync column and cannot appear in mutation values",
185                    table.name, key
186                ));
187            }
188            return Err(format!(
189                "sync.invalid_request: table {:?}: unknown column {:?} in mutation values (snake_case and camelCase keys are accepted)",
190                table.name, key
191            ));
192        }
193    }
194    Ok(values)
195}
196
197pub fn bytes_to_hex(bytes: &[u8]) -> String {
198    let mut out = String::with_capacity(bytes.len() * 2);
199    for b in bytes {
200        out.push(char::from(b"0123456789abcdef"[usize::from(b >> 4)]));
201        out.push(char::from(b"0123456789abcdef"[usize::from(b & 15)]));
202    }
203    out
204}
205
206pub fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, String> {
207    if !hex.len().is_multiple_of(2) {
208        return Err("odd-length hex string".to_owned());
209    }
210    let mut out = Vec::with_capacity(hex.len() / 2);
211    let nibble = |byte| match byte {
212        b'0'..=b'9' => byte - b'0',
213        b'a'..=b'f' => byte - b'a' + 10,
214        b'A'..=b'F' => byte - b'A' + 10,
215        _ => u8::MAX,
216    };
217    for pair in hex.as_bytes().as_chunks::<2>().0 {
218        // Preserve the prior radix parser's accepted +digit pair as well as
219        // uppercase input. Canonical encoders continue to emit lowercase hex.
220        let high = if pair[0] == b'+' { 0 } else { nibble(pair[0]) };
221        let low = nibble(pair[1]);
222        if high == u8::MAX || low == u8::MAX {
223            return Err(if std::str::from_utf8(pair).is_err() {
224                "non-ASCII hex".to_owned()
225            } else {
226                "bad hex: invalid digit found in string".to_owned()
227            });
228        }
229        out.push((high << 4) | low);
230    }
231    Ok(out)
232}
233
234/// Driver JSON value → row-codec value for one column. `null`/absent maps to
235/// NULL; bytes travel as `{"$bytes": "<hex>"}`.
236pub fn json_to_column_value(
237    column: &Column,
238    value: Option<&Value>,
239) -> Result<Option<ColumnValue>, String> {
240    let value = match value {
241        None | Some(Value::Null) => return Ok(None),
242        Some(v) => v,
243    };
244    let fail = |expected: &str| {
245        Err(format!(
246            "column {:?}: expected {expected}, got {value}",
247            column.name
248        ))
249    };
250    match column.ty {
251        ColumnType::String => match value.as_str() {
252            Some(s) => Ok(Some(ColumnValue::String(s.to_owned()))),
253            None => fail("a string"),
254        },
255        ColumnType::Integer => match value.as_i64() {
256            Some(i)
257                if (-ssp2::primitives::I64_SAFE_MAX..=ssp2::primitives::I64_SAFE_MAX)
258                    .contains(&i) =>
259            {
260                Ok(Some(ColumnValue::Integer(i)))
261            }
262            _ => fail("an integer within the JavaScript safe-integer range"),
263        },
264        ColumnType::Float => match value.as_f64() {
265            Some(f) => Ok(Some(ColumnValue::Float(f))),
266            None => fail("a number"),
267        },
268        ColumnType::Boolean => match value.as_bool() {
269            Some(b) => Ok(Some(ColumnValue::Boolean(b))),
270            None => fail("a boolean"),
271        },
272        // `json` columns stay raw strings at the driver boundary (§2.4).
273        ColumnType::Json => match value.as_str() {
274            Some(s) => Ok(Some(ColumnValue::Json(RawJson(s.to_owned())))),
275            None => fail("a raw JSON string"),
276        },
277        // `blob_ref` (tag 7) also stays a raw string at the boundary (§5.9.1).
278        ColumnType::BlobRef => match value.as_str() {
279            Some(s) => Ok(Some(ColumnValue::BlobRef(RawJson(s.to_owned())))),
280            None => fail("a raw BlobRef JSON string"),
281        },
282        ColumnType::Bytes => match value.get("$bytes").and_then(Value::as_str) {
283            Some(hex) => Ok(Some(ColumnValue::Bytes(hex_to_bytes(hex)?))),
284            None => fail("a {\"$bytes\": hex} object"),
285        },
286        // §5.10: crdt bytes cross the boundary as {"$bytes": hex}, like bytes.
287        ColumnType::Crdt => match value.get("$bytes").and_then(Value::as_str) {
288            Some(hex) => Ok(Some(ColumnValue::Crdt(hex_to_bytes(hex)?))),
289            None => fail("a {\"$bytes\": hex} object"),
290        },
291    }
292}
293
294/// Row-codec value → driver JSON value.
295pub fn column_value_to_json(value: &Option<ColumnValue>) -> Value {
296    match value {
297        None => Value::Null,
298        Some(ColumnValue::String(s)) => Value::from(s.clone()),
299        Some(ColumnValue::Integer(i)) => Value::from(*i),
300        Some(ColumnValue::Float(f)) => {
301            serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number)
302        }
303        Some(ColumnValue::Boolean(b)) => Value::from(*b),
304        Some(ColumnValue::Json(raw)) => Value::from(raw.0.clone()),
305        Some(ColumnValue::BlobRef(raw)) => Value::from(raw.0.clone()),
306        Some(ColumnValue::Bytes(bytes)) => {
307            let mut map = Map::new();
308            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(bytes)));
309            Value::Object(map)
310        }
311        Some(ColumnValue::Crdt(bytes)) => {
312            let mut map = Map::new();
313            map.insert("$bytes".to_owned(), Value::from(bytes_to_hex(bytes)));
314            Value::Object(map)
315        }
316    }
317}
318
319/// Turn an app-facing value map into a full-row map: every column present,
320/// a missing nullable column filled with NULL, a missing non-nullable column
321/// a loud error (§6.1 full-row payloads, §6.7 `mutate` marks every column).
322pub fn full_row_values(
323    table: &TableSchema,
324    mut values: Map<String, Value>,
325) -> Result<Map<String, Value>, String> {
326    for column in &table.columns {
327        if values.contains_key(&column.name) {
328            continue;
329        }
330        if !column.nullable {
331            return Err(format!(
332                "sync.invalid_request: table {:?}: column {:?} is not nullable (§6.1 full-row payloads)",
333                table.name, column.name
334            ));
335        }
336        values.insert(column.name.clone(), Value::Null);
337    }
338    Ok(values)
339}
340
341/// §7.1: exactly one `$bytes` key holding an even-length hexadecimal string.
342/// Uppercase digits are accepted; encoders emit lowercase.
343pub(crate) fn is_canonical_bytes_envelope(value: &Value) -> bool {
344    value
345        .as_object()
346        .filter(|map| map.len() == 1)
347        .and_then(|map| map.get("$bytes"))
348        .and_then(Value::as_str)
349        .is_some_and(|hex| {
350            hex.len().is_multiple_of(2) && hex.bytes().all(|byte| byte.is_ascii_hexdigit())
351        })
352}
353
354/// §7.1: a `bytes`/`crdt` column crosses the authoring boundary only as exactly
355/// one `$bytes` key holding an even-length hexadecimal string. The shared
356/// decoder keeps its tolerance for persisted payloads (§7.4.4 replay), so the
357/// canonical rule is enforced at the encode seams instead. `None` for every
358/// other column type and for a canonical envelope.
359fn author_bytes_envelope_error(column: &Column, value: &Value) -> Option<String> {
360    // An explicit `null` stays with `json_to_column_value`: a nullable column
361    // accepts it and a non-nullable one is classified by the required-column
362    // check, not by the envelope rule.
363    if value.is_null() || !matches!(column.ty, ColumnType::Bytes | ColumnType::Crdt) {
364        return None;
365    }
366    if is_canonical_bytes_envelope(value) {
367        return None;
368    }
369    Some(format!(
370        "sync.invalid_request: column {:?}: expected exactly {{\"$bytes\": hex}} with an even number of hexadecimal digits, got {value}",
371        column.name
372    ))
373}
374
375/// Encode one full row (driver JSON values keyed by column name) with the
376/// generated row codec (§2.4, §6.1). §5.11: encrypted columns are encrypted
377/// here — the encode-at-send seam — before the codec serializes them as
378/// ciphertext-envelope `bytes` using `wire_columns`.
379pub fn encode_row_json(
380    table: &TableSchema,
381    row_id: &str,
382    values: &Map<String, Value>,
383    encryption: &EncryptionConfig,
384) -> Result<Vec<u8>, String> {
385    // Build the row from the LOCAL (declared-type) columns.
386    let mut row: Row = Vec::with_capacity(table.columns.len());
387    for column in &table.columns {
388        if let Some(raw) = values.get(&column.name) {
389            if let Some(error) = author_bytes_envelope_error(column, raw) {
390                return Err(error);
391            }
392        }
393        // §6.1/§7.1: a caller value the codec rejects is an invalid request,
394        // never an internal authoring failure; the dynamic cause stays in
395        // `details.legacyCause` at the `ClientError` boundary.
396        let value = json_to_column_value(column, values.get(&column.name))
397            .map_err(|error| format!("sync.invalid_request: {error}"))?;
398        if value.is_none() && !column.nullable {
399            return Err(format!(
400                "sync.invalid_request: table {:?}: column {:?} is not nullable (§6.1 full-row payloads)",
401                table.name, column.name
402            ));
403        }
404        row.push(value);
405    }
406    if table.has_encrypted_columns() {
407        encrypt_row(table, row_id, &mut row, encryption)?;
408    }
409    // Serialize with the WIRE columns (encrypted columns are `bytes`).
410    let mut w = Writer::new();
411    encode_row(&mut w, &table.wire_columns, &row);
412    Ok(w.into_bytes())
413}
414
415/// Encode one SPARSE push payload (§2.4, §6.1): the keys of `values` ARE the
416/// presence set — a column with no key stays absent. §5.11: only present
417/// encrypted columns are encrypted, and key resolution runs only then;
418/// absent selector slots fall back to `fallback` (the stored local row).
419/// Serialized with the `wire_columns` table.
420pub fn encode_sparse_row_json(
421    table: &TableSchema,
422    row_id: &str,
423    values: &Map<String, Value>,
424    encryption: &EncryptionConfig,
425    fallback: Option<&Row>,
426) -> Result<Vec<u8>, String> {
427    let mut row: SparseRow = Vec::with_capacity(table.columns.len());
428    for column in &table.columns {
429        let Some(raw) = values.get(&column.name) else {
430            row.push(SparseSlot::Absent);
431            continue;
432        };
433        if let Some(error) = author_bytes_envelope_error(column, raw) {
434            return Err(error);
435        }
436        let value = json_to_column_value(column, Some(raw))
437            .map_err(|error| format!("sync.invalid_request: {error}"))?;
438        if value.is_none() && !column.nullable {
439            return Err(format!(
440                "sync.invalid_request: table {:?}: column {:?} is not nullable (§6.1)",
441                table.name, column.name
442            ));
443        }
444        row.push(value.map_or(SparseSlot::Null, SparseSlot::Value));
445    }
446    if table.has_encrypted_columns() {
447        encrypt_sparse_row(table, row_id, &mut row, encryption, fallback)?;
448    }
449    Ok(encode_sparse_row(&table.wire_columns, table.pk_index, &row))
450}
451
452/// Decode one row-codec payload; trailing bytes are a decode error. §5.11:
453/// encrypted columns are decrypted here — the apply seam — back to their
454/// declared-type plaintext value for the local mirror.
455pub fn decode_row_bytes(
456    table: &TableSchema,
457    payload: &[u8],
458    encryption: &EncryptionConfig,
459) -> Result<Row, String> {
460    let mut r = Reader::new(payload);
461    // Decode with the WIRE columns (encrypted columns arrive as `bytes`).
462    let mut row = decode_row(&mut r, &table.wire_columns).map_err(|e| e.to_string())?;
463    if !r.is_empty() {
464        return Err("row payload has trailing bytes".to_owned());
465    }
466    if table.has_encrypted_columns() {
467        decrypt_row(table, &mut row, encryption)?;
468    }
469    Ok(row)
470}
471
472/// §5.11: decrypt the encrypted columns of an already-decoded segment row
473/// (rows segments decode via their own column table, so decryption is a
474/// post-decode pass over the positional values).
475pub fn decrypt_segment_row(
476    table: &TableSchema,
477    row: &mut Row,
478    encryption: &EncryptionConfig,
479) -> Result<(), String> {
480    decrypt_row(table, row, encryption)
481}
482
483// -- §5.11 encrypt/decrypt seam (feature-gated) ------------------------------
484
485#[cfg(feature = "e2ee")]
486fn encrypt_row(
487    table: &TableSchema,
488    _row_id: &str,
489    row: &mut Row,
490    encryption: &EncryptionConfig,
491) -> Result<(), String> {
492    use rand_core::RngCore;
493    use ssp2::crypto::{encrypt_value, NONCE_LENGTH};
494    for enc in &table.encrypted_columns {
495        let Some(value) = row.get(enc.index).and_then(|v| v.as_ref()) else {
496            continue; // NULL stays NULL (§5.11)
497        };
498        let plain = column_value_to_plain(value)?;
499        let key_id = encryption.key_id_for(table, row)?;
500        let key = encryption
501            .keys
502            .get(&key_id)
503            .ok_or_else(|| format!("client.encrypt_failed: no key for keyId {key_id:?}"))?;
504        let mut nonce = [0u8; NONCE_LENGTH];
505        rand_core::OsRng.fill_bytes(&mut nonce);
506        let envelope = encrypt_value(&plain, &key_id, key, nonce)?;
507        row[enc.index] = Some(ColumnValue::Bytes(envelope));
508    }
509    Ok(())
510}
511
512#[cfg(feature = "e2ee")]
513fn encrypt_sparse_row(
514    table: &TableSchema,
515    _row_id: &str,
516    row: &mut SparseRow,
517    encryption: &EncryptionConfig,
518    fallback: Option<&Row>,
519) -> Result<(), String> {
520    use rand_core::RngCore;
521    use ssp2::crypto::{encrypt_value, NONCE_LENGTH};
522    // Sparse semantics: absent and NULL columns are never re-encrypted, so
523    // a patch presenting no encrypted value needs no key (§5.11).
524    let has_present_encrypted = table
525        .encrypted_columns
526        .iter()
527        .any(|enc| matches!(row.get(enc.index), Some(SparseSlot::Value(_))));
528    if !has_present_encrypted {
529        return Ok(());
530    }
531    // Densify absent columns to NULL for key-id selection only; an absent
532    // selector falls back to the stored local row. Absent ≠ NULL (§6.1):
533    // only an ABSENT slot reads the fallback, a present NULL never does.
534    let mut dense: Row = row
535        .iter()
536        .map(|slot| match slot {
537            SparseSlot::Value(value) => Some(value.clone()),
538            _ => None,
539        })
540        .collect();
541    if let Some(selector) = encryption.key_id_columns.get(&table.name) {
542        if let Some(index) = table
543            .columns
544            .iter()
545            .position(|column| &column.name == selector)
546        {
547            if matches!(row.get(index), None | Some(SparseSlot::Absent)) {
548                let stored: Option<&str> = match fallback
549                    .and_then(|row| row.get(index))
550                    .and_then(|value| value.as_ref())
551                {
552                    Some(ColumnValue::String(key_id)) => Some(key_id),
553                    _ => None,
554                };
555                if let Some(key_id) = stored.filter(|key_id| !key_id.is_empty()) {
556                    dense[index] = Some(ColumnValue::String(key_id.to_owned()));
557                }
558            }
559        }
560    }
561    let key_id = encryption.key_id_for(table, &dense)?;
562    for enc in &table.encrypted_columns {
563        let Some(SparseSlot::Value(value)) = row.get(enc.index) else {
564            continue; // absent or NULL stays untouched (§5.11)
565        };
566        let plain = column_value_to_plain(value)?;
567        let key = encryption
568            .keys
569            .get(&key_id)
570            .ok_or_else(|| format!("client.encrypt_failed: no key for keyId {key_id:?}"))?;
571        let mut nonce = [0u8; NONCE_LENGTH];
572        rand_core::OsRng.fill_bytes(&mut nonce);
573        let envelope = encrypt_value(&plain, &key_id, key, nonce)?;
574        row[enc.index] = SparseSlot::Value(ColumnValue::Bytes(envelope));
575    }
576    Ok(())
577}
578
579#[cfg(not(feature = "e2ee"))]
580fn encrypt_sparse_row(
581    table: &TableSchema,
582    _row_id: &str,
583    row: &mut SparseRow,
584    _encryption: &EncryptionConfig,
585    _fallback: Option<&Row>,
586) -> Result<(), String> {
587    if !table
588        .encrypted_columns
589        .iter()
590        .any(|enc| matches!(row.get(enc.index), Some(SparseSlot::Value(_))))
591    {
592        return Ok(());
593    }
594    Err(format!(
595        "table {:?} has encrypted columns but this build lacks the e2ee feature (§5.11)",
596        table.name
597    ))
598}
599
600#[cfg(feature = "e2ee")]
601fn decrypt_row(
602    table: &TableSchema,
603    row: &mut Row,
604    encryption: &EncryptionConfig,
605) -> Result<(), String> {
606    use ssp2::crypto::{decrypt_value, DeclaredType};
607    for enc in &table.encrypted_columns {
608        let Some(value) = row.get(enc.index).and_then(|v| v.as_ref()) else {
609            continue;
610        };
611        let ColumnValue::Bytes(envelope) = value else {
612            return Err(format!(
613                "client.decrypt_failed: encrypted column at index {} is not bytes",
614                enc.index
615            ));
616        };
617        let declared = DeclaredType::from_name(&enc.declared_type)
618            .ok_or_else(|| format!("unknown declaredType {:?}", enc.declared_type))?;
619        let keys = &encryption.keys;
620        let plain = decrypt_value(declared, envelope, |id| keys.get(id).cloned())
621            .map_err(|e| e.to_string())?;
622        row[enc.index] = Some(plain_to_column_value(plain));
623    }
624    Ok(())
625}
626
627/// Without the `e2ee` feature, a schema with encrypted columns is a
628/// misconfiguration — fail loud rather than ship plaintext.
629#[cfg(not(feature = "e2ee"))]
630fn encrypt_row(
631    table: &TableSchema,
632    _row_id: &str,
633    _row: &mut Row,
634    _encryption: &EncryptionConfig,
635) -> Result<(), String> {
636    Err(format!(
637        "table {:?} has encrypted columns but this build lacks the e2ee feature (§5.11)",
638        table.name
639    ))
640}
641
642#[cfg(not(feature = "e2ee"))]
643fn decrypt_row(
644    table: &TableSchema,
645    _row: &mut Row,
646    _encryption: &EncryptionConfig,
647) -> Result<(), String> {
648    Err(format!(
649        "table {:?} has encrypted columns but this build lacks the e2ee feature (§5.11)",
650        table.name
651    ))
652}
653
654#[cfg(feature = "e2ee")]
655fn column_value_to_plain(value: &ColumnValue) -> Result<ssp2::crypto::PlainValue, String> {
656    use ssp2::crypto::PlainValue;
657    Ok(match value {
658        ColumnValue::String(s) => PlainValue::String(s.clone()),
659        ColumnValue::Integer(i) => PlainValue::Integer(*i),
660        ColumnValue::Float(f) => PlainValue::Float(*f),
661        ColumnValue::Boolean(b) => PlainValue::Boolean(*b),
662        ColumnValue::Json(j) => PlainValue::Json(j.0.clone()),
663        ColumnValue::BlobRef(j) => PlainValue::BlobRef(j.0.clone()),
664        ColumnValue::Bytes(b) => PlainValue::Bytes(b.clone()),
665        ColumnValue::Crdt(_) => return Err("crdt columns cannot be encrypted (§5.11)".to_owned()),
666    })
667}
668
669#[cfg(feature = "e2ee")]
670fn plain_to_column_value(value: ssp2::crypto::PlainValue) -> ColumnValue {
671    use ssp2::crypto::PlainValue;
672    match value {
673        PlainValue::String(s) => ColumnValue::String(s),
674        PlainValue::Integer(i) => ColumnValue::Integer(i),
675        PlainValue::Float(f) => ColumnValue::Float(f),
676        PlainValue::Boolean(b) => ColumnValue::Boolean(b),
677        PlainValue::Json(s) => ColumnValue::Json(RawJson(s)),
678        PlainValue::BlobRef(s) => ColumnValue::BlobRef(RawJson(s)),
679        PlainValue::Bytes(b) => ColumnValue::Bytes(b),
680    }
681}
682
683/// Render a primary-key value as the wire `rowId` string.
684pub fn render_row_id(value: &Option<ColumnValue>) -> Result<String, String> {
685    match value {
686        Some(ColumnValue::String(s)) => Ok(s.clone()),
687        Some(ColumnValue::Integer(i)) => Ok(i.to_string()),
688        Some(ColumnValue::Float(f)) => Ok(f.to_string()),
689        Some(ColumnValue::Boolean(b)) => Ok(b.to_string()),
690        Some(ColumnValue::Json(raw)) => Ok(raw.0.clone()),
691        Some(ColumnValue::BlobRef(_)) => Err("blob_ref column cannot be a rowId".to_owned()),
692        Some(ColumnValue::Bytes(_)) => Err("bytes column cannot be a rowId".to_owned()),
693        Some(ColumnValue::Crdt(_)) => Err("crdt column cannot be a rowId".to_owned()),
694        None => Err("primary key value is missing".to_owned()),
695    }
696}
697
698/// Driver JSON value → wire `rowId` string (for optimistic upserts).
699pub fn render_row_id_json(value: Option<&Value>) -> Result<String, String> {
700    match value {
701        Some(Value::String(s)) => Ok(s.clone()),
702        Some(Value::Number(n)) => Ok(n.to_string()),
703        Some(Value::Bool(b)) => Ok(b.to_string()),
704        _ => Err("sync.invalid_request: primary key value is missing or not renderable".to_owned()),
705    }
706}
707
708fn sort_utf16(values: &mut [String]) {
709    values.sort_by(|a, b| {
710        if utf16_lt(a, b) {
711            std::cmp::Ordering::Less
712        } else if utf16_lt(b, a) {
713            std::cmp::Ordering::Greater
714        } else {
715            std::cmp::Ordering::Equal
716        }
717    });
718}
719
720/// Sort scope-map keys into ascending code-unit order (the canonical `map`
721/// encoding of the Conventions section).
722pub fn sort_scope_map(map: &mut [(String, Vec<String>)]) {
723    map.sort_by(|a, b| {
724        if utf16_lt(&a.0, &b.0) {
725            std::cmp::Ordering::Less
726        } else if utf16_lt(&b.0, &a.0) {
727            std::cmp::Ordering::Greater
728        } else {
729            std::cmp::Ordering::Equal
730        }
731    });
732}
733
734/// §11.2 canonical JSON of a scope map: keys sorted by code-unit, value
735/// lists sorted and deduplicated, no insignificant whitespace.
736pub fn canonical_scope_json(scopes: &[(String, Vec<String>)]) -> String {
737    let mut entries: Vec<(String, Vec<String>)> = scopes.to_vec();
738    sort_scope_map(&mut entries);
739    let mut out = String::from("{");
740    for (i, (key, values)) in entries.iter().enumerate() {
741        if i > 0 {
742            out.push(',');
743        }
744        let mut sorted = values.clone();
745        sort_utf16(&mut sorted);
746        sorted.dedup();
747        out.push_str(&serde_json::to_string(key).expect("string serializes"));
748        out.push_str(":[");
749        for (j, value) in sorted.iter().enumerate() {
750            if j > 0 {
751                out.push(',');
752            }
753            out.push_str(&serde_json::to_string(value).expect("string serializes"));
754        }
755        out.push(']');
756    }
757    out.push('}');
758    out
759}
760
761/// Scope map as a driver JSON object (`variable → list of values`, §3.2).
762pub fn scope_map_to_json(scopes: &[(String, Vec<String>)]) -> Value {
763    let mut map = Map::new();
764    for (key, values) in scopes {
765        map.insert(
766            key.clone(),
767            Value::Array(values.iter().map(|v| Value::from(v.clone())).collect()),
768        );
769    }
770    Value::Object(map)
771}
772
773/// Driver JSON object → scope map, preserving key order.
774pub fn json_to_scope_map(value: &Value) -> Result<Vec<(String, Vec<String>)>, String> {
775    let object = value
776        .as_object()
777        .ok_or_else(|| "scope map must be an object".to_owned())?;
778    let mut out = Vec::with_capacity(object.len());
779    for (key, values) in object {
780        let list = values
781            .as_array()
782            .ok_or_else(|| format!("scope values for {key:?} must be a list (§0)"))?;
783        let mut strings = Vec::with_capacity(list.len());
784        for v in list {
785            strings.push(
786                v.as_str()
787                    .ok_or_else(|| format!("scope value for {key:?} is not a string"))?
788                    .to_owned(),
789            );
790        }
791        out.push((key.clone(), strings));
792    }
793    Ok(out)
794}
795
796#[cfg(test)]
797mod naming_tests {
798    use serde_json::{json, Map, Value};
799    use ssp2::segment::{Column, ColumnType, ColumnValue, Row};
800
801    use super::{
802        bytes_to_hex, hex_to_bytes, normalize_values_casing, snake_to_camel, EncryptionConfig,
803    };
804    use crate::schema::{EncryptedColumn, TableSchema};
805
806    #[test]
807    fn authored_integer_cells_respect_the_wire_safe_range() {
808        let column = Column {
809            name: "n".into(),
810            ty: ColumnType::Integer,
811            nullable: false,
812        };
813        for value in [
814            9007199254740992_i64,
815            9007199254740993,
816            i64::MAX,
817            -9007199254740992,
818            i64::MIN,
819        ] {
820            assert!(super::json_to_column_value(&column, Some(&json!(value))).is_err());
821        }
822        for value in [-9007199254740991_i64, 0, 9007199254740991] {
823            assert!(super::json_to_column_value(&column, Some(&json!(value))).is_ok());
824        }
825    }
826
827    #[test]
828    fn byte_envelopes_preserve_canonical_hex_for_every_byte() {
829        let bytes: Vec<u8> = (0..=255).collect();
830        let expected: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
831        assert_eq!(bytes_to_hex(&bytes), expected);
832        assert_eq!(hex_to_bytes(&expected).expect("decode"), bytes);
833        assert_eq!(bytes_to_hex(&[]), "");
834        assert_eq!(bytes_to_hex(&[0, 15, 16, 255]), "000f10ff");
835        let large = bytes.repeat(8192);
836        assert_eq!(bytes_to_hex(&large), expected.repeat(8192));
837        assert_eq!(
838            hex_to_bytes(&bytes_to_hex(&large)).expect("large decode"),
839            large
840        );
841    }
842
843    #[test]
844    fn byte_decoder_preserves_radix_parser_inputs_and_errors() {
845        for first in 0_u8..=127 {
846            for second in 0_u8..=127 {
847                let pair = [first, second];
848                let input = std::str::from_utf8(&pair).unwrap();
849                let expected = u8::from_str_radix(input, 16)
850                    .map(|byte| vec![byte])
851                    .map_err(|error| format!("bad hex: {error}"));
852                assert_eq!(hex_to_bytes(input), expected, "ASCII pair {pair:?}");
853            }
854        }
855        assert_eq!(hex_to_bytes("+fA0+100"), Ok(vec![15, 160, 1, 0]));
856        for input in [
857            "", "0", "abc", "é", "雪", "😀", "0é0", "é00", "00é", "00😀", "😀00", "\0\0",
858        ] {
859            let expected = if !input.len().is_multiple_of(2) {
860                Err("odd-length hex string".to_owned())
861            } else {
862                input
863                    .as_bytes()
864                    .chunks(2)
865                    .map(|pair| {
866                        let text =
867                            std::str::from_utf8(pair).map_err(|_| "non-ASCII hex".to_owned())?;
868                        u8::from_str_radix(text, 16).map_err(|error| format!("bad hex: {error}"))
869                    })
870                    .collect::<Result<Vec<_>, _>>()
871            };
872            assert_eq!(hex_to_bytes(input), expected, "input {input:?}");
873        }
874    }
875
876    #[test]
877    fn snake_to_camel_pinned_vectors() {
878        for (input, expected) in [
879            ("created_at", "createdAt"),
880            ("col_2", "col2"),
881            ("user_id", "userId"),
882            ("_internal", "_internal"),
883            ("__foo_bar", "__fooBar"),
884            ("row_", "row_"),
885            ("id_url", "idUrl"),
886            ("api_key", "apiKey"),
887            ("title", "title"),
888            ("alreadyCamel", "alreadyCamel"),
889            ("a__b", "aB"),
890            ("_lead_and_trail_", "_leadAndTrail_"),
891            ("count(*)", "count(*)"),
892        ] {
893            assert_eq!(snake_to_camel(input), expected, "input {input:?}");
894        }
895    }
896
897    #[test]
898    fn portable_key_selector_reads_a_non_encrypted_string_column() {
899        let columns = vec![
900            Column {
901                name: "id".to_owned(),
902                ty: ColumnType::String,
903                nullable: false,
904            },
905            Column {
906                name: "encryption_key_id".to_owned(),
907                ty: ColumnType::String,
908                nullable: false,
909            },
910            Column {
911                name: "note".to_owned(),
912                ty: ColumnType::String,
913                nullable: false,
914            },
915        ];
916        let table = TableSchema {
917            name: "patients".to_owned(),
918            columns: columns.clone(),
919            wire_columns: columns,
920            primary_key: "id".to_owned(),
921            pk_index: 0,
922            scope_variables: Vec::new(),
923            indexes: Vec::new(),
924            fts_indexes: Vec::new(),
925            encrypted_columns: vec![EncryptedColumn {
926                index: 2,
927                declared_type: "string".to_owned(),
928            }],
929        };
930        let mut config = EncryptionConfig::default();
931        config
932            .key_id_columns
933            .insert("patients".to_owned(), "encryption_key_id".to_owned());
934        let row: Row = vec![
935            Some(ColumnValue::String("patient-1".to_owned())),
936            Some(ColumnValue::String("practice-key-v1".to_owned())),
937            Some(ColumnValue::String("Identity".to_owned())),
938        ];
939        assert_eq!(
940            config.key_id_for(&table, &row).expect("selects key"),
941            "practice-key-v1"
942        );
943    }
944
945    #[test]
946    fn debug_render_redacts_key_material() {
947        let mut config = EncryptionConfig::default();
948        config
949            .keys
950            .insert("practice-key-v1".to_owned(), vec![0xAB; 32]);
951        config
952            .key_id_columns
953            .insert("patients".to_owned(), "encryption_key_id".to_owned());
954        let rendered = format!("{config:?}");
955        assert!(rendered.contains("practice-key-v1"), "{rendered}");
956        assert!(rendered.contains("<32 bytes>"), "{rendered}");
957        assert!(rendered.contains("encryption_key_id"), "{rendered}");
958        // Raw byte values never appear (0xAB renders as 171 under derive).
959        assert!(!rendered.contains("171"), "{rendered}");
960        assert!(!rendered.contains("0xAB"), "{rendered}");
961    }
962
963    fn table(names: &[&str]) -> TableSchema {
964        let columns: Vec<Column> = names
965            .iter()
966            .map(|n| Column {
967                name: (*n).to_owned(),
968                ty: ColumnType::String,
969                nullable: true,
970            })
971            .collect();
972        TableSchema {
973            name: "t".to_owned(),
974            columns: columns.clone(),
975            wire_columns: columns,
976            primary_key: "id".to_owned(),
977            pk_index: 0,
978            scope_variables: Vec::new(),
979            indexes: Vec::new(),
980            fts_indexes: Vec::new(),
981            encrypted_columns: Vec::new(),
982        }
983    }
984
985    fn map(entries: &[(&str, &str)]) -> Map<String, Value> {
986        entries
987            .iter()
988            .map(|(k, v)| ((*k).to_owned(), json!(v)))
989            .collect()
990    }
991
992    #[test]
993    fn camel_keys_normalize_to_sql_names() {
994        let t = table(&["id", "list_id", "updated_at_ms"]);
995        let out = normalize_values_casing(
996            &t,
997            map(&[("id", "x"), ("listId", "l"), ("updatedAtMs", "9")]),
998        )
999        .expect("normalizes");
1000        assert_eq!(out.get("list_id"), Some(&json!("l")));
1001        assert_eq!(out.get("updated_at_ms"), Some(&json!("9")));
1002        assert!(!out.contains_key("listId"));
1003    }
1004
1005    #[test]
1006    fn snake_keys_pass_through() {
1007        let t = table(&["id", "list_id"]);
1008        let out = normalize_values_casing(&t, map(&[("id", "x"), ("list_id", "l")])).expect("ok");
1009        assert_eq!(out.get("list_id"), Some(&json!("l")));
1010    }
1011
1012    #[test]
1013    fn both_casings_for_one_column_is_an_error() {
1014        let t = table(&["id", "list_id"]);
1015        let err = normalize_values_casing(&t, map(&[("list_id", "a"), ("listId", "b")]))
1016            .expect_err("rejects");
1017        assert!(err.contains("both snake_case and camelCase"), "{err}");
1018    }
1019
1020    #[test]
1021    fn an_alias_colliding_with_a_real_column_never_steals_it() {
1022        // `col_2` camel-maps to `col2`, which IS a column: exact wins, no rename.
1023        let t = table(&["id", "col_2", "col2"]);
1024        let out = normalize_values_casing(&t, map(&[("id", "x"), ("col2", "v")])).expect("ok");
1025        assert_eq!(out.get("col2"), Some(&json!("v")));
1026        assert!(!out.contains_key("col_2"));
1027    }
1028
1029    #[test]
1030    fn unknown_and_internal_columns_fail_loud() {
1031        let t = table(&["id", "title"]);
1032        let unknown = normalize_values_casing(&t, map(&[("id", "x"), ("typo", "v")]))
1033            .expect_err("unknown field");
1034        assert!(unknown.contains("unknown column"), "{unknown}");
1035        let internal = normalize_values_casing(&t, map(&[("id", "x"), ("_sync_version", "1")]))
1036            .expect_err("internal field");
1037        assert!(internal.contains("internal sync column"), "{internal}");
1038    }
1039}
1040
1041#[cfg(test)]
1042mod sparse_key_tests {
1043    use ssp2::segment::{Column, ColumnType, ColumnValue, Row};
1044
1045    use super::EncryptionConfig;
1046    use crate::schema::{EncryptedColumn, TableSchema};
1047
1048    #[cfg(feature = "e2ee")]
1049    use super::encode_sparse_row_json;
1050    #[cfg(feature = "e2ee")]
1051    use serde_json::{json, Map, Value};
1052
1053    fn keyed_table() -> TableSchema {
1054        let columns = vec![
1055            Column {
1056                name: "id".to_owned(),
1057                ty: ColumnType::String,
1058                nullable: false,
1059            },
1060            Column {
1061                name: "encryption_key_id".to_owned(),
1062                ty: ColumnType::String,
1063                nullable: true,
1064            },
1065            Column {
1066                name: "note".to_owned(),
1067                ty: ColumnType::String,
1068                nullable: true,
1069            },
1070        ];
1071        let wire_columns = vec![
1072            Column {
1073                name: "id".to_owned(),
1074                ty: ColumnType::String,
1075                nullable: false,
1076            },
1077            Column {
1078                name: "encryption_key_id".to_owned(),
1079                ty: ColumnType::String,
1080                nullable: true,
1081            },
1082            Column {
1083                name: "note".to_owned(),
1084                ty: ColumnType::Bytes,
1085                nullable: true,
1086            },
1087        ];
1088        TableSchema {
1089            name: "t".to_owned(),
1090            columns,
1091            wire_columns,
1092            primary_key: "id".to_owned(),
1093            pk_index: 0,
1094            scope_variables: Vec::new(),
1095            indexes: Vec::new(),
1096            fts_indexes: Vec::new(),
1097            encrypted_columns: vec![EncryptedColumn {
1098                index: 2,
1099                declared_type: "string".to_owned(),
1100            }],
1101        }
1102    }
1103
1104    fn keyed_config() -> EncryptionConfig {
1105        let mut config = EncryptionConfig::default();
1106        config.keys.insert("k1".to_owned(), vec![0x2A; 32]);
1107        config
1108            .key_id_columns
1109            .insert("t".to_owned(), "encryption_key_id".to_owned());
1110        config
1111    }
1112
1113    #[cfg(feature = "e2ee")]
1114    fn values(entries: &[(&str, Value)]) -> Map<String, Value> {
1115        entries
1116            .iter()
1117            .map(|(key, value)| ((*key).to_owned(), value.clone()))
1118            .collect()
1119    }
1120
1121    #[test]
1122    fn key_selection_failures_carry_the_encode_seam_code() {
1123        let table = keyed_table();
1124        let config = keyed_config();
1125        // Absent selector: absent is not NULL and never densifies into one.
1126        let row: Row = vec![
1127            Some(ColumnValue::String("r1".to_owned())),
1128            None,
1129            Some(ColumnValue::String("hi".to_owned())),
1130        ];
1131        let error = config.key_id_for(&table, &row).expect_err("rejects");
1132        assert!(error.starts_with("client.encrypt_failed"), "{error}");
1133        assert!(!error.starts_with("client.decrypt_failed"), "{error}");
1134    }
1135
1136    #[cfg(feature = "e2ee")]
1137    #[test]
1138    fn sparse_patch_without_an_encrypted_slot_needs_no_key() {
1139        let table = keyed_table();
1140        // No keys at all: resolution must be skipped, not failed.
1141        let config = EncryptionConfig::default();
1142        let payload =
1143            encode_sparse_row_json(&table, "r1", &values(&[("id", json!("r1"))]), &config, None)
1144                .expect("encodes without key resolution");
1145        assert!(!payload.is_empty());
1146    }
1147
1148    #[cfg(feature = "e2ee")]
1149    #[test]
1150    fn sparse_patch_falls_back_to_the_stored_key_id() {
1151        let table = keyed_table();
1152        let config = keyed_config();
1153        // The patch presents an encrypted column but not the selector.
1154        let sparse = values(&[("id", json!("r1")), ("note", json!("hi"))]);
1155        let error = encode_sparse_row_json(&table, "r1", &sparse, &config, None)
1156            .expect_err("absent selector with no fallback fails");
1157        assert!(error.contains("client.encrypt_failed"), "{error}");
1158        let fallback: Row = vec![
1159            Some(ColumnValue::String("r1".to_owned())),
1160            Some(ColumnValue::String("k1".to_owned())),
1161            None,
1162        ];
1163        encode_sparse_row_json(&table, "r1", &sparse, &config, Some(&fallback))
1164            .expect("stored key id encrypts the patch");
1165    }
1166
1167    #[cfg(feature = "e2ee")]
1168    #[test]
1169    fn sparse_patch_keeps_a_present_null_selector() {
1170        let table = keyed_table();
1171        let config = keyed_config();
1172        // The patch presents the selector explicitly as NULL alongside an
1173        // encrypted column. Absent is not NULL: the stored row must not
1174        // rescue a present NULL, and a NULL key id is unusable.
1175        let sparse = values(&[
1176            ("id", json!("r1")),
1177            ("encryption_key_id", json!(null)),
1178            ("note", json!("hi")),
1179        ]);
1180        let fallback: Row = vec![
1181            Some(ColumnValue::String("r1".to_owned())),
1182            Some(ColumnValue::String("k1".to_owned())),
1183            None,
1184        ];
1185        let error = encode_sparse_row_json(&table, "r1", &sparse, &config, Some(&fallback))
1186            .expect_err("a present NULL selector must not read the stored fallback");
1187        assert!(error.contains("client.encrypt_failed"), "{error}");
1188    }
1189}