1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
use super::{
errors::{IndexerError, LoadIndexerError},
mapping::{Mapping, MappingWithMeta},
vector::{EncryptedTerm, TermVector, VectorTerm},
};
use crate::record::{Record, Value};
use hex_literal::hex;
use lazy_static::lazy_static;
use num_bigint::{BigUint, ToBigUint};
use ore_encoding_rs::{siphash, OrePlaintext};
use ore_rs::{scheme::bit2::OREAES128, ORECipher, OREEncrypt};
use regex::Regex;
fn encrypt_string_terms(
ore: &mut OREAES128,
index_id: &[u8; 16],
record_id: &[u8; 16],
terms: Vec<String>,
) -> Result<Option<TermVector>, IndexerError> {
let terms = terms
.into_iter()
.map(|term| OrePlaintext::from(siphash(term.as_bytes())))
.map(|plaintext| {
plaintext
.0
.encrypt(ore)
.map(EncryptedTerm::from)
.map(|term| VectorTerm {
term,
link: *record_id,
})
})
.collect::<Result<Vec<_>, _>>()?;
if terms.is_empty() {
return Ok(None);
}
Ok(Some(TermVector {
terms,
index_id: *index_id,
}))
}
fn encrypt_u64_terms(
ore: &mut OREAES128,
index_id: &[u8; 16],
record_id: &[u8; 16],
terms: Vec<u64>,
) -> Result<Option<TermVector>, IndexerError> {
let terms = terms
.into_iter()
.map(|term| OrePlaintext::from(term))
.map(|plaintext| plaintext.0.encrypt(ore))
.collect::<Result<Vec<_>, _>>()?;
if terms.is_empty() {
return Ok(None);
}
Ok(Some(TermVector {
terms: vec![VectorTerm {
term: EncryptedTerm(terms),
link: *record_id,
}],
index_id: *index_id,
}))
}
fn orderise_string(s: &str) -> Result<Vec<u64>, IndexerError> {
if !s.is_ascii() {
return Err(IndexerError::InvalidRecordError(
"Can only order strings that are pure ASCII".to_string(),
));
}
lazy_static! {
static ref NON_ALPHANUMERIC_OR_SPACE_REGEX: Regex = Regex::new("[^a-z0-9[:space:]]+").unwrap();
}
lazy_static! {
static ref SPACE_REGEX: Regex = Regex::new("[[:space:]]+").unwrap();
}
lazy_static! {
static ref DIGIT_REGEX: Regex = Regex::new("[0-9]").unwrap();
}
let mut s = s.to_lowercase();
s = NON_ALPHANUMERIC_OR_SPACE_REGEX
.replace_all(&s, "~")
.to_string();
s = SPACE_REGEX.replace_all(&s, "{").to_string();
s = DIGIT_REGEX.replace_all(&s, "|").to_string();
let mut n = s
.bytes()
.map(|c| BigUint::from(c - 96))
.fold(0.to_biguint().unwrap(), |i, c| (i << 5) + c);
n = n << (64 - (s.len() * 5) % 64);
let mut terms = Vec::new();
let two_pow_64 = 2.to_biguint().unwrap().pow(64);
while n > 0.to_biguint().unwrap() {
let term = (&n % &two_pow_64).try_into().unwrap();
terms.insert(0, term);
n >>= 64;
}
terms.truncate(6);
Ok(terms)
}
pub struct MappingIndexer {
ore: OREAES128,
pub(crate) index_id: [u8; 16],
pub(crate) mapping: Mapping,
}
impl MappingIndexer {
pub fn from_mapping(mapping: MappingWithMeta) -> Result<Self, LoadIndexerError> {
let seed = hex!("00010203 04050607");
let ore = OREAES128::init(mapping.prf_key, mapping.prp_key, &seed)
.map_err(|e| LoadIndexerError::Other(format!("ORE init failed: {:?}", e)))?;
Ok(Self {
ore,
index_id: mapping.index_id,
mapping: mapping.mapping,
})
}
pub fn vector_from_term(&self, term: VectorTerm) -> TermVector {
TermVector {
terms: vec![term],
index_id: self.index_id,
}
}
pub fn encrypt(&mut self, record: &Record) -> Result<Option<TermVector>, IndexerError> {
let id = record.id;
Ok(match &self.mapping {
Mapping::Exact { field } => {
if let Some(plaintext) = record
.index_with_dot_notation(field)
.and_then(|x| x.as_plaintext())
{
let term = plaintext.0.encrypt(&mut self.ore)?.into();
Some(self.vector_from_term(VectorTerm { term, link: id }))
} else {
None
}
}
Mapping::Range { field } => {
if let Some(val) = record.index_with_dot_notation(field) {
if let Value::String(s) = val {
let terms = orderise_string(s)?;
encrypt_u64_terms(&mut self.ore, &self.index_id, &record.id, terms)?
} else if let Some(plaintext) = val.as_plaintext() {
let term = plaintext.0.encrypt(&mut self.ore)?.into();
Some(self.vector_from_term(VectorTerm { term, link: id }))
} else {
None
}
} else {
None
}
}
Mapping::Match { fields, pipeline } => encrypt_string_terms(
&mut self.ore,
&self.index_id,
&record.id,
pipeline.process(record.extract_string_fields(fields)),
)?,
Mapping::DynamicMatch { pipeline } => encrypt_string_terms(
&mut self.ore,
&self.index_id,
&record.id,
pipeline.process(record.extract_all_string_fields()),
)?,
Mapping::FieldDynamicMatch { pipeline } => encrypt_string_terms(
&mut self.ore,
&self.index_id,
&record.id,
record
.extract_all_string_fields_and_keys()
.into_iter()
.flat_map(|(k, v)| {
pipeline
.process(vec![v])
.into_iter()
.map(move |t| format!("{}:{}", k, t))
})
.collect(),
)?,
})
}
}
#[cfg(test)]
mod tests {
use crate::{
indexer::{
errors,
mapping::{Mapping, MappingWithMeta},
},
record::Record,
test_utils::collection,
};
use super::{orderise_string, MappingIndexer};
use serde::Deserialize;
use std::fs;
use std::path::Path;
#[test]
fn test_compare_exact_matches() {
let record = Record {
id: [0; 16],
fields: collection! {
"test" => "test-string"
},
};
let mut left_indexer = MappingIndexer::from_mapping(MappingWithMeta {
mapping: Mapping::Exact {
field: "test".into(),
},
prp_key: [0; 16],
prf_key: [1; 16],
index_id: [2; 16],
})
.expect("Failed to gen left indexer");
let mut right_indexer = MappingIndexer::from_mapping(MappingWithMeta {
mapping: Mapping::Exact {
field: "test".into(),
},
prp_key: [0; 16],
prf_key: [1; 16],
index_id: [2; 16],
})
.expect("Failed to gen right indexer");
let left = left_indexer
.encrypt(&record)
.expect("Failed to encrypt")
.unwrap();
let right = right_indexer
.encrypt(&record)
.expect("Failed to encrypt")
.unwrap();
assert_eq!(left.terms[0], right.terms[0]);
}
#[test]
fn test_compare_not_exact() {
let first = Record {
id: [0; 16],
fields: collection! {
"test" => "test-string"
},
};
let second = Record {
id: [1; 16],
fields: collection! {
"test" => "test-different-string"
},
};
let mut indexer = MappingIndexer::from_mapping(MappingWithMeta {
mapping: Mapping::Exact {
field: "test".into(),
},
prp_key: [0; 16],
prf_key: [1; 16],
index_id: [2; 16],
})
.expect("Failed to gen left indexer");
let left = indexer.encrypt(&first).expect("Failed to encrypt").unwrap();
let right = indexer
.encrypt(&second)
.expect("Failed to encrypt")
.unwrap();
assert_ne!(left.terms[0], right.terms[0]);
}
#[test]
fn test_compare_range() {
let first = Record {
id: [0; 16],
fields: collection! {
"test" => 10
},
};
let second = Record {
id: [1; 16],
fields: collection! {
"test" => 20
},
};
let mut indexer = MappingIndexer::from_mapping(MappingWithMeta {
mapping: Mapping::Range {
field: "test".into(),
},
prp_key: [0; 16],
prf_key: [1; 16],
index_id: [2; 16],
})
.expect("Failed to gen left indexer");
let left = indexer.encrypt(&first).expect("Failed to encrypt").unwrap();
let right = indexer
.encrypt(&second)
.expect("Failed to encrypt")
.unwrap();
assert!(left.terms[0] < right.terms[0]);
}
#[test]
fn test_compare_range_with_strings() {
let second = Record {
id: [0; 16],
fields: collection! {
"test" => "b"
},
};
let first = Record {
id: [1; 16],
fields: collection! {
"test" => "a"
},
};
let third = Record {
id: [2; 16],
fields: collection! {
"test" => "c"
},
};
let mut indexer = MappingIndexer::from_mapping(MappingWithMeta {
mapping: Mapping::Range {
field: "test".into(),
},
prp_key: [0; 16],
prf_key: [1; 16],
index_id: [2; 16],
})
.expect("Failed to gen left indexer");
let first_encrypted = indexer.encrypt(&first).expect("Failed to encrypt").unwrap();
let second_encrypted = indexer
.encrypt(&second)
.expect("Failed to encrypt")
.unwrap();
let third_encrypted = indexer.encrypt(&third).expect("Failed to encrypt").unwrap();
assert!(first_encrypted.terms[0].term < second_encrypted.terms[0].term);
assert!(second_encrypted.terms[0].term < third_encrypted.terms[0].term);
}
#[test]
fn test_range_comparison_gets_same_result_as_ruby_client() {
#[derive(Deserialize, Debug)]
struct TestCase {
input: Vec<String>,
output: String,
}
let case_file_path =
Path::new(env!("CARGO_MANIFEST_DIR")).join("./string_comparison_test_cases.json");
let json_str = fs::read_to_string(case_file_path).expect("couldn't read test case file");
let test_cases: Vec<TestCase> =
serde_json::from_str(&json_str).expect("couldn't parse test cases");
for test_case in test_cases {
let mut indexer = MappingIndexer::from_mapping(MappingWithMeta {
mapping: Mapping::Range {
field: "test".into(),
},
prp_key: [0; 16],
prf_key: [1; 16],
index_id: [2; 16],
})
.expect("Failed to gen left indexer");
let str_a = &test_case.input[0];
let str_b = &test_case.input[1];
let record_a = Record {
id: [0; 16],
fields: collection! {
"test" => str_a.clone()
},
};
let record_b = Record {
id: [1; 16],
fields: collection! {
"test" => str_b.clone()
},
};
let a_encrypted = indexer
.encrypt(&record_a)
.expect("Failed to encrypt")
.unwrap();
let b_encrypted = indexer
.encrypt(&record_b)
.expect("Failed to encrypt")
.unwrap();
let a_term = &a_encrypted.terms[0].term;
let b_term = &b_encrypted.terms[0].term;
match test_case.output.as_str() {
"<" => {
assert!(
a_term < b_term,
"expected {:?} to be < {:?} but it was not",
&str_a,
&str_b,
)
}
"==" => {
assert!(
a_term == b_term,
"expected {:?} to be == {:?} but it was not",
&str_a,
&str_b,
)
}
">" => {
assert!(
a_term > b_term,
"expected {:?} to be > {:?} but it was not",
&str_a,
&str_b,
)
}
op => panic!("unexpected operator: {:?}", op),
}
}
}
#[test]
fn test_orderise_string_non_ascii() {
let result = orderise_string("Jalapeño");
assert!(matches!(
result,
Err(errors::IndexerError::InvalidRecordError(_))
));
let message = result.err().unwrap().to_string();
assert_eq!(message, "Can only order strings that are pure ASCII")
}
#[test]
fn test_orderise_string_gives_same_output_as_ruby_clint() {
#[derive(Deserialize, Debug)]
struct TestCase {
input: String,
output: Vec<u64>,
}
let case_file_path =
Path::new(env!("CARGO_MANIFEST_DIR")).join("./orderise_string_test_cases.json");
let json_str = fs::read_to_string(case_file_path).expect("couldn't read test case file");
let test_cases: Vec<TestCase> =
serde_json::from_str(&json_str).expect("couldn't parse test cases");
for test_case in test_cases {
let result = orderise_string(&test_case.input);
assert!(
result.is_ok(),
"Expected orderise_string to succeed given {:?}, but got error: {:?}",
&test_case.input,
result
);
assert_eq!(
result.unwrap(),
test_case.output,
"\n orderise_string didn't match for input: {:?}",
test_case.input
);
}
}
}