cloudproof_findex 6.0.2

Cosmian Findex Cloudproof library
Documentation
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! Defines the Findex FFI API.

use std::{
    collections::{HashMap, HashSet},
    str::FromStr,
    sync::Mutex,
};

use cosmian_crypto_core::{
    bytes_ser_de::Serializer, reexport::rand_core::SeedableRng, CsRng, FixedSizeCBytes,
    RandomFixedSizeCBytes, SymmetricKey,
};
use cosmian_ffi_utils::{
    error::{h_get_error, set_last_error, FfiError},
    ffi_read_bytes, ffi_read_string, ffi_unwrap, ffi_write_bytes, ErrorCode,
};
use cosmian_findex::{
    Data, Error as FindexError, IndexedValue, IndexedValueToKeywordsMap, Keyword, Keywords, Label,
    USER_KEY_LENGTH,
};
use lazy_static::lazy_static;
use tracing::trace;

#[cfg(debug_assertions)]
use crate::logger::log_init;
use crate::{
    db_interfaces::{
        custom::ffi::{
            Delete, DumpTokens, Fetch, FfiCallbacks, FilterObsoleteData, Insert, Interrupt, Upsert,
        },
        rest::{AuthorizationToken, CallbackPrefix},
        DbInterfaceError,
    },
    ser_de::ffi_ser_de::{
        deserialize_data_set, deserialize_indexed_values, deserialize_keyword_set,
        get_upsert_output_size, serialize_data_set, serialize_intermediate_results,
        serialize_keyword_set,
    },
    Configuration, InstantiatedFindex,
};

lazy_static! {
    static ref FINDEX_INSTANCES: Mutex::<HashMap::<i32, (SymmetricKey<USER_KEY_LENGTH>, Label, InstantiatedFindex)>> =
        Mutex::new(HashMap::new());
}

/// Creates a new Findex instance using a custom FFI backend.
///
/// The new instance is stored in a cache and the handle returned.
///
/// # Safety
///
/// Cannot be safe since using FFI.
#[no_mangle]
#[tracing::instrument(ret, skip_all)]
pub unsafe extern "C" fn h_instantiate_with_custom_interface(
    findex_handle: *mut i32,
    key_ptr: *const u8,
    key_len: i32,
    label_ptr: *const i8,
    entry_table_number: u32,
    fetch_entry: Fetch,
    fetch_chain: Fetch,
    upsert_entry: Upsert,
    insert_entry: Insert,
    insert_chain: Insert,
    delete_entry: Delete,
    delete_chain: Delete,
    dump_tokens: DumpTokens,
) -> i32 {
    #[cfg(debug_assertions)]
    log_init();

    let key_bytes = ffi_read_bytes!("key", key_ptr, key_len);
    let key = ffi_unwrap!(
        SymmetricKey::try_from_slice(key_bytes),
        "error deserializing findex key",
        ErrorCode::Serialization
    );
    trace!("Key successfully parsed");

    let label_bytes = ffi_read_string!("label", label_ptr);
    let label = Label::from(label_bytes.as_str());
    trace!("Label successfully parsed: label: {label}");

    let config = Configuration::Ffi(
        // TODO: ensure null pointers are not given
        FfiCallbacks {
            table_number: entry_table_number as usize,
            fetch: Some(fetch_entry),
            upsert: Some(upsert_entry),
            insert: Some(insert_entry),
            delete: Some(delete_entry),
            dump_tokens: Some(dump_tokens),
        },
        FfiCallbacks {
            // Only one Chain table is allowed.
            table_number: 1,
            fetch: Some(fetch_chain),
            upsert: None,
            insert: Some(insert_chain),
            delete: Some(delete_chain),
            dump_tokens: None,
        },
    );

    let rt = ffi_unwrap!(
        tokio::runtime::Runtime::new(),
        "error creating Tokio runtime",
        ErrorCode::Tokio
    );
    let findex = ffi_unwrap!(
        rt.block_on(InstantiatedFindex::new(config)),
        "error instantiating Findex with custom backend",
        ErrorCode::Findex
    );

    let mut cache = FINDEX_INSTANCES
        .lock()
        .expect("Findex instance cache lock poisoned.");
    let handle = ffi_unwrap!(
        <i32>::try_from(cache.len()),
        "findex instance cache capacity overflow",
        ErrorCode::Findex
    );

    cache.insert(handle, (key, label, findex));

    *findex_handle = handle;

    ErrorCode::Success.into()
}

/// Instantiate a Findex using a REST backend.
///
/// # Parameters
///
/// - `label`   : label used by Findex
/// - `token`   : token containing authentication keys
/// - `url`     : REST server URL
///
/// # Safety
///
/// Cannot be safe since using FFI.
#[no_mangle]
#[tracing::instrument(ret, skip_all)]
pub unsafe extern "C" fn h_instantiate_with_rest_interface(
    findex_handle: *mut i32,
    label_ptr: *const i8,
    token_ptr: *const i8,
    entry_url_ptr: *const i8,
    chain_url_ptr: *const i8,
) -> i32 {
    #[cfg(debug_assertions)]
    log_init();

    let label_bytes = ffi_read_string!("label", label_ptr);
    let label = Label::from(label_bytes.as_str());
    trace!("Label successfully parsed: label: {label}");

    let token = ffi_read_string!("token", token_ptr);
    trace!("Authorization token read: {token}");
    let authorization_token = ffi_unwrap!(
        crate::db_interfaces::rest::AuthorizationToken::from_str(&token),
        "authorization token conversion failed",
        ErrorCode::Backend
    );

    let entry_url = if entry_url_ptr.is_null() {
        String::new()
    } else {
        ffi_read_string!("REST server Entry Table URL", entry_url_ptr)
    };

    let chain_url = if chain_url_ptr.is_null() {
        String::new()
    } else {
        ffi_read_string!("REST server Chain Table URL", chain_url_ptr)
    };
    let config = Configuration::Rest(authorization_token.clone(), entry_url, chain_url);

    let rt = ffi_unwrap!(
        tokio::runtime::Runtime::new(),
        "error creating Tokio runtime",
        ErrorCode::Tokio
    );
    let findex = ffi_unwrap!(
        rt.block_on(InstantiatedFindex::new(config)),
        "error instantiating Findex with REST backend",
        ErrorCode::Backend
    );

    let mut cache = FINDEX_INSTANCES
        .lock()
        .expect("Findex instance cache lock poisoned.");
    let handle = ffi_unwrap!(
        <i32>::try_from(cache.len()),
        "findex instance cache capacity overflow",
        ErrorCode::Findex
    );
    cache.insert(handle, (authorization_token.findex_key, label, findex));

    *findex_handle = handle;

    ErrorCode::Success.into()
}

/// Instantiate a Findex using a Redis backend.
///
/// # Parameters
///
/// - `key`                     : Findex key
/// - `label`                   : label used by Findex
/// - `entry_table_redis_url`   : Redis entry table URL
/// - `chain_table_redis_url`   : Redis chain table URL
///
/// # Safety
///
/// Cannot be safe since using FFI.
#[no_mangle]
#[tracing::instrument(ret, skip_all)]
pub unsafe extern "C" fn h_instantiate_with_redis_interface(
    findex_handle: *mut i32,
    key_ptr: *const u8,
    key_len: i32,
    label_ptr: *const i8,
    entry_table_redis_url_ptr: *const i8,
    chain_table_redis_url_ptr: *const i8,
) -> i32 {
    #[cfg(debug_assertions)]
    log_init();

    let key_bytes = ffi_read_bytes!("key", key_ptr, key_len);
    let key = ffi_unwrap!(
        SymmetricKey::try_from_slice(key_bytes),
        "error deserializing findex key",
        ErrorCode::Serialization
    );
    trace!("Key successfully parsed");

    let label_bytes = ffi_read_string!("label", label_ptr);
    let label = Label::from(label_bytes.as_str());
    trace!("Label successfully parsed: label: {label}");

    let entry_table_redis_url =
        ffi_read_string!("Redis entry table URL", entry_table_redis_url_ptr);
    let chain_table_redis_url =
        ffi_read_string!("Redis chain table URL", chain_table_redis_url_ptr);

    let config = Configuration::Redis(entry_table_redis_url, chain_table_redis_url);

    let rt = ffi_unwrap!(
        tokio::runtime::Runtime::new(),
        "error creating Tokio runtime",
        ErrorCode::Tokio
    );
    let findex = ffi_unwrap!(
        rt.block_on(InstantiatedFindex::new(config)),
        "error instantiating Findex with REST backend",
        ErrorCode::Findex
    );

    let mut cache = FINDEX_INSTANCES
        .lock()
        .expect("Findex instance cache lock poisoned.");
    let handle = ffi_unwrap!(
        <i32>::try_from(cache.len()),
        "findex instance cache capacity overflow",
        ErrorCode::Findex
    );
    cache.insert(handle, (key, label, findex));

    *findex_handle = handle;

    ErrorCode::Success.into()
}

/// Searches the index for the given keywords.
///
/// At each search recursion, the passed `interrupt` function is called with the
/// results from the current recursion level. The search is interrupted is
/// `true` is returned.
///
/// # Parameters
///
/// - `results`         : (output) search result
/// - `findex_handle`   : Findex handle on the instance cache
/// - `keywords`        : serialized list of keywords
/// - `interrupt`       : user interrupt called at each search iteration
///
/// # Safety
///
/// Cannot be safe since using FFI.
#[no_mangle]
#[tracing::instrument(ret, skip_all)]
pub unsafe extern "C" fn h_search(
    results_ptr: *mut u8,
    results_len: *mut i32,
    findex_handle: i32,
    keywords_ptr: *const u8,
    keywords_len: i32,
    interrupt: Interrupt,
) -> i32 {
    #[cfg(debug_assertions)]
    log_init();

    let keywords = ffi_unwrap!(
        deserialize_keyword_set(ffi_read_bytes!("keywords", keywords_ptr, keywords_len)),
        "error deserializing keywords",
        ErrorCode::Serialization
    );
    let keywords = Keywords::from(keywords);
    trace!("Keywords successfully parsed: keywords: {keywords}");

    let user_interrupt = |res: HashMap<Keyword, HashSet<IndexedValue<Keyword, Data>>>| async move {
        trace!("user interrupt input: {res:?}");
        let bytes = serialize_intermediate_results(&res).map_err(|e| e.to_string())?;
        let length = <u32>::try_from(bytes.len()).map_err(|e| e.to_string())?;
        let is_interrupted = 1 == (interrupt)(bytes.as_ptr(), length);
        trace!("user interrupt output: = {is_interrupted}");
        Ok(is_interrupted)
    };

    let cache = FINDEX_INSTANCES
        .lock()
        .expect("Findex instance cache lock poisoned.");
    let (key, label, findex) = ffi_unwrap!(
        cache
            .get(&findex_handle)
            .ok_or_else(|| format!("no matching instance for handle {findex_handle}")),
        "cannot get a hold on the Findex instance",
        ErrorCode::Findex
    );

    let rt = ffi_unwrap!(
        tokio::runtime::Runtime::new(),
        "error creating Tokio runtime",
        ErrorCode::Tokio
    );

    let res = rt.block_on(findex.search(key, label, keywords, &user_interrupt));

    let results = match res {
        Ok(res) => res,
        Err(FindexError::DbInterface(DbInterfaceError::Ffi(msg, code))) => {
            set_last_error(FfiError::Generic(format!(
                "backend error during `search` operation: {msg}"
            )));
            return code.into();
        }
        Err(e) => {
            set_last_error(FfiError::Generic(format!("findex `search` error: {e}")));
            return ErrorCode::Findex.into();
        }
    };

    // Serialize the results.
    // We should be able to use the output buffer as the `Serializer` sink to avoid
    // to copy the buffer (right now the `crypto_core` serializer doesn't provide a
    // constructor from an existing slice) <https://github.com/Cosmian/findex/issues/20>
    let mut serializer = Serializer::new();
    ffi_unwrap!(
        serializer.write_leb128_u64(results.len() as u64),
        "error serializing length",
        ErrorCode::Serialization
    );
    for (keyword, data) in results {
        ffi_unwrap!(
            serializer.write_vec(&keyword),
            "error serializing keyword",
            ErrorCode::Serialization
        );
        let serialized_data = ffi_unwrap!(
            serialize_data_set(&data),
            "error serializing set",
            ErrorCode::Serialization
        );
        ffi_unwrap!(
            serializer.write_array(&serialized_data),
            "error serializing data",
            ErrorCode::Serialization
        );
    }
    let serialized_uids = serializer.finalize();

    ffi_write_bytes!("search results", &serialized_uids, results_ptr, results_len);
}

/// Adds the given associations to the index.
///
/// # Parameters
///
/// - `results`         : (output) list of new keywords added to the index
/// - `findex_handle`   : Findex handle on the instance cache
/// - `associations`    : map of values to sets of keywords
///
/// # Safety
///
/// Cannot be safe since using FFI.
#[no_mangle]
#[tracing::instrument(ret, skip_all)]
pub unsafe extern "C" fn h_add(
    results_ptr: *mut u8,
    results_len: *mut i32,
    findex_handle: i32,
    associations_ptr: *const u8,
    associations_len: i32,
) -> i32 {
    #[cfg(debug_assertions)]
    log_init();

    let associations_bytes = ffi_read_bytes!("associations", associations_ptr, associations_len);
    let associations = IndexedValueToKeywordsMap::from(ffi_unwrap!(
        deserialize_indexed_values(associations_bytes),
        "failed deserialize indexed values (associations)",
        ErrorCode::Serialization
    ));

    let output_size = get_upsert_output_size(&associations);
    if *results_len < output_size as i32 {
        set_last_error(FfiError::Generic(format!(
            "The pre-allocated add results buffer is too small; need {} bytes, allocated {}",
            output_size, results_len as i32
        )));
        *results_len = output_size as i32;
        return ErrorCode::BufferTooSmall.into();
    }

    let cache = FINDEX_INSTANCES
        .lock()
        .expect("Findex instance cache lock poisoned.");

    let (key, label, findex) = ffi_unwrap!(
        cache
            .get(&findex_handle)
            .ok_or_else(|| format!("no matching instance for handle {findex_handle}")),
        "cannot get a hold on the Findex instance",
        ErrorCode::Findex
    );

    trace!("instantiated Findex: {findex:?}");

    let rt = ffi_unwrap!(
        tokio::runtime::Runtime::new(),
        "error creating Tokio runtime",
        ErrorCode::Tokio
    );

    let res = rt.block_on(findex.add(key, label, associations));

    let new_keywords = match res {
        Ok(new_keywords) => new_keywords,
        Err(FindexError::DbInterface(DbInterfaceError::Ffi(msg, code))) => {
            set_last_error(FfiError::Generic(format!(
                "backend error during `add` operation: {msg}"
            )));
            return code.into();
        }
        Err(e) => {
            set_last_error(FfiError::Generic(format!("findex `add` error: {e}")));
            return ErrorCode::Findex.into();
        }
    };

    // Serialize the results.
    let serialized_keywords = ffi_unwrap!(
        serialize_keyword_set(&new_keywords),
        "serialize new keywords",
        ErrorCode::Serialization
    );

    ffi_write_bytes!(
        "add results",
        &serialized_keywords,
        results_ptr,
        results_len
    );
}

/// Removes the given associations from the index.
///
/// # Parameters
///
/// - `results`         : Returns the list of new keywords added to the index
/// - `findex_handle`   : Findex handle on the instance cache
/// - `associations`    : map of values to sets of keywords
///
/// # Safety
///
/// Cannot be safe since using FFI.
#[no_mangle]
#[tracing::instrument(ret, skip_all)]
pub unsafe extern "C" fn h_delete(
    results_ptr: *mut u8,
    results_len: *mut i32,
    findex_handle: i32,
    associations_ptr: *const u8,
    associations_len: i32,
) -> i32 {
    #[cfg(debug_assertions)]
    log_init();

    let associations_bytes = ffi_read_bytes!("associations", associations_ptr, associations_len);
    let associations = IndexedValueToKeywordsMap::from(ffi_unwrap!(
        deserialize_indexed_values(associations_bytes),
        "failed deserialize indexed values (associations)",
        ErrorCode::Serialization
    ));

    let output_size = get_upsert_output_size(&associations);
    if *results_len < output_size as i32 {
        set_last_error(FfiError::Generic(format!(
            "The pre-allocated add results buffer is too small; need {} bytes, allocated {}",
            output_size, results_len as i32
        )));
        *results_len = output_size as i32;
        return ErrorCode::BufferTooSmall.into();
    }

    let cache = FINDEX_INSTANCES
        .lock()
        .expect("Findex instance cache lock poisoned.");

    let (key, label, findex) = ffi_unwrap!(
        cache
            .get(&findex_handle)
            .ok_or_else(|| format!("no matching instance for handle {findex_handle}")),
        "cannot get a hold on the Findex instance",
        ErrorCode::Findex
    );

    trace!("instantiated Findex: {findex:?}");

    let rt = ffi_unwrap!(
        tokio::runtime::Runtime::new(),
        "error creating Tokio runtime",
        ErrorCode::Tokio
    );

    let res = rt.block_on(findex.delete(key, label, associations));

    let new_keywords = match res {
        Ok(new_keywords) => new_keywords,
        Err(FindexError::DbInterface(DbInterfaceError::Ffi(msg, code))) => {
            set_last_error(FfiError::Generic(format!(
                "backend error during `delete` operation: {msg}"
            )));
            return code.into();
        }
        Err(e) => {
            set_last_error(FfiError::Generic(format!("findex `delete` error: {e}")));
            return ErrorCode::Findex.into();
        }
    };

    // Serialize the results.
    let serialized_keywords = ffi_unwrap!(
        serialize_keyword_set(&new_keywords),
        "serialize new keywords",
        ErrorCode::Serialization
    );

    ffi_write_bytes!(
        "delete results",
        &serialized_keywords,
        results_ptr,
        results_len
    );
}

/// Replaces all the Index Entry Table UIDs and values. New UIDs are derived
/// using the given label and the KMAC key derived from the new key. The
/// values are decrypted using the DEM key derived from the key and
/// re-encrypted using the DEM key derived from the new key.
///
/// Randomly selects index entries and recompact their associated chains. Chains
/// indexing no existing location are removed. Others are recomputed from a new
/// keying material. This removes unneeded paddings. New UIDs are derived for
/// the chain and values are re-encrypted using a DEM key derived from the new
/// keying material.
///
/// # Parameters
///
/// - `findex_handle`           : Findex handle on the instance cache
/// - `new_key`                 : new Findex key
/// - `new_label`               : public information used to derive UIDs
/// - `compacting_rate`         : see below
/// - `filter_obsolete_data`    : callback used to filter out obsolete data
///   among indexed data
///
/// `compacting_rate`: if you compact the
/// indexes every night this is the number of days to wait before
/// being sure that a big portion of the indexes were checked
/// (see the coupon problem to understand why it's not 100% sure)

/// # Safety
///
/// Cannot be safe since using FFI.
#[no_mangle]
#[tracing::instrument(ret, skip_all)]
pub unsafe extern "C" fn h_compact(
    findex_handle: i32,
    new_key_ptr: *const u8,
    new_key_len: i32,
    new_label_ptr: *const i8,
    compacting_rate: f64,
    filter_obsolete_data: FilterObsoleteData,
) -> i32 {
    #[cfg(debug_assertions)]
    log_init();

    let filter = |data: HashSet<Data>| async {
        let moved_data = data;
        let bytes =
            serialize_data_set(&moved_data).map_err(|e| format!("error serializing data: {e}"))?;
        let mut res = vec![0; bytes.len()];
        let mut res_length = res.len() as u32;
        let err = (filter_obsolete_data)(
            res.as_mut_ptr(),
            &mut res_length,
            bytes.as_ptr(),
            bytes.len() as u32,
        );

        if err != 0 {
            set_last_error(FfiError::Generic(format!("filter callback error: {err}")));
            return Err(String::from("Filter error."));
        }

        deserialize_data_set(&res).map_err(|e| format!("error deserializing filtered data: {e}"))
    };

    let new_key_bytes = ffi_read_bytes!("new key", new_key_ptr, new_key_len);
    let new_key = ffi_unwrap!(
        SymmetricKey::try_from_slice(new_key_bytes),
        "error deserializing new findex key",
        ErrorCode::Serialization
    );

    let new_label_bytes = ffi_read_string!("new label", new_label_ptr);
    let new_label = Label::from(new_label_bytes.as_str());

    let mut cache = FINDEX_INSTANCES
        .lock()
        .expect("Findex instance cache lock poisoned.");

    let (old_key, old_label, findex) = ffi_unwrap!(
        cache
            .get_mut(&findex_handle)
            .ok_or_else(|| format!("no matching instance for handle {findex_handle}")),
        "cannot get a hold on the Findex instance",
        ErrorCode::Findex
    );

    let rt = ffi_unwrap!(
        tokio::runtime::Runtime::new(),
        "error creating Tokio runtime",
        ErrorCode::Tokio
    );

    trace!("instantiated Findex: {findex:?}");
    let res = rt.block_on(findex.compact(
        old_key,
        &new_key,
        old_label,
        &new_label,
        compacting_rate,
        &filter,
    ));

    match res {
        Err(FindexError::DbInterface(DbInterfaceError::Ffi(msg, code))) => {
            set_last_error(FfiError::Generic(format!(
                "backend error during `compact` operation: {msg}"
            )));
            code.into()
        }
        Err(e) => {
            set_last_error(FfiError::Generic(format!("findex `compact` error: {e}")));
            ErrorCode::Findex.into()
        }
        Ok(()) => {
            *old_key = new_key;
            *old_label = new_label;
            ErrorCode::Success.into()
        }
    }
}

/// Generate a new Findex token from the provided index ID and signature seeds,
/// and a randomly generated Findex key inside Rust.
///
/// The token is output inside `token_ptr`, `token_len` is updated to match the
/// token length (this length should always be the same, right now, the length
/// is always below 200 bytes)
///
/// # Safety
///
/// Cannot be safe since using FFI.
#[no_mangle]
#[tracing::instrument(ret, skip_all)]
pub unsafe extern "C" fn h_generate_new_token(
    token_ptr: *mut u8,
    token_len: *mut i32,
    index_id_ptr: *const i8,
    fetch_entries_seed_ptr: *const u8,
    fetch_entries_seed_len: i32,
    fetch_chains_seed_ptr: *const u8,
    fetch_chains_seed_len: i32,
    upsert_entries_seed_ptr: *const u8,
    upsert_entries_seed_len: i32,
    insert_chains_seed_ptr: *const u8,
    insert_chains_seed_len: i32,
) -> i32 {
    #[cfg(debug_assertions)]
    log_init();

    let index_id: String = ffi_read_string!("index id", index_id_ptr);

    let fetch_entries_seed = ffi_read_bytes!(
        "fetch_entries_seed",
        fetch_entries_seed_ptr,
        fetch_entries_seed_len
    );
    let fetch_chains_seed = ffi_read_bytes!(
        "fetch_chains_seed",
        fetch_chains_seed_ptr,
        fetch_chains_seed_len
    );
    let upsert_entries_seed = ffi_read_bytes!(
        "upsert_entries_seed",
        upsert_entries_seed_ptr,
        upsert_entries_seed_len
    );
    let insert_chains_seed = ffi_read_bytes!(
        "insert_chains_seed",
        insert_chains_seed_ptr,
        insert_chains_seed_len
    );

    let mut seeds = HashMap::new();
    seeds.insert(
        CallbackPrefix::FetchEntry,
        ffi_unwrap!(
            SymmetricKey::try_from_slice(fetch_entries_seed),
            "fetch_entries_seed is of wrong size",
            ErrorCode::Serialization
        ),
    );
    seeds.insert(
        CallbackPrefix::FetchChain,
        ffi_unwrap!(
            SymmetricKey::try_from_slice(fetch_chains_seed),
            "fetch_chains_seed is of wrong size",
            ErrorCode::Serialization
        ),
    );
    seeds.insert(
        CallbackPrefix::Upsert,
        ffi_unwrap!(
            SymmetricKey::try_from_slice(upsert_entries_seed),
            "upsert_entries_seed is of wrong size",
            ErrorCode::Serialization
        ),
    );
    seeds.insert(
        CallbackPrefix::Insert,
        ffi_unwrap!(
            SymmetricKey::try_from_slice(insert_chains_seed),
            "insert_chains_seed is of wrong size",
            ErrorCode::Serialization
        ),
    );

    let mut rng = CsRng::from_entropy();
    let findex_key = SymmetricKey::new(&mut rng);

    let token = ffi_unwrap!(
        AuthorizationToken::new(index_id, findex_key, seeds),
        "generate authorization token",
        ErrorCode::Findex
    );

    ffi_write_bytes!(
        "search results",
        token.to_string().as_bytes(),
        token_ptr,
        token_len
    );
}

/// Re-export the `cosmian_ffi` `h_get_error` function to clients with the old
/// `get_last_error` name The `h_get_error` is available inside the final lib
/// (but tools like `ffigen` seems to not parse it…) Maybe we can find a
/// solution by changing the function name inside the clients.
///
/// # Safety
///
/// Cannot be safe since using FFI.
#[no_mangle]
pub unsafe extern "C" fn get_last_error(error_ptr: *mut i8, error_len: *mut i32) -> i32 {
    h_get_error(error_ptr, error_len)
}