cloudproof_cover_crypt 14.0.0

Cosmian Covercrypt 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
use cosmian_cover_crypt::abe_policy::{
    AccessPolicy, Attribute, DimensionBuilder, EncryptionHint, Policy,
};
use cosmian_ffi_utils::{ffi_read_bytes, ffi_read_string, ffi_unwrap, ffi_write_bytes, ErrorCode};

/// This macro handles deserializing the policy from JS, deserializing an
/// attribute from JS, and performing a specified action on the policy. It also
/// ensures proper error handling and serialization of the updated policy into
/// the response.
///
///
/// # Parameters
///
/// - `$updated_policy_ptr`: output serialized updated policy.
/// - `$updated_policy_len`: output serialized updated policy length.
/// - `$current_policy_ptr`: serialized policy to update.
/// - `$current_policy_len`: serialized policy length to update.
/// - `$attr_bytes`: serialized attribute to be processed.
/// - `$cc_policy`: placeholder name for the deserialized policy.
/// - `$cc_attr`: placeholder name for the deserialized attribute.
/// - `$action`: action to perform on the policy.
/// - `$error_msg`: error message to display in case of failures.
///
/// # Returns
///
/// The serialized updated Policy.
/// ```
macro_rules! update_policy {
    (
        $updated_policy_ptr:ident,
        $updated_policy_len:ident,
        $current_policy_ptr:ident,
        $current_policy_len:ident,
        $attr_bytes:ident,
        $cc_policy:ident,
        $cc_attr:ident,
        $action:expr,
        $error_msg:expr
    ) => {{
        let policy_bytes =
            ffi_read_bytes!("current policy", $current_policy_ptr, $current_policy_len);
        let mut $cc_policy = ffi_unwrap!(
            Policy::parse_and_convert(policy_bytes),
            "error deserializing policy",
            ErrorCode::Serialization
        );

        let attr_string = ffi_read_string!("attribute", $attr_bytes);
        let $cc_attr = ffi_unwrap!(
            Attribute::try_from(attr_string.as_str()),
            "error parsing attribute",
            ErrorCode::InvalidArgument("Attribute".to_string())
        );

        ffi_unwrap!($action, $error_msg, ErrorCode::Serialization);

        let policy_bytes = ffi_unwrap!(
            <Vec<u8>>::try_from(&$cc_policy),
            "error serializing policy",
            ErrorCode::Serialization
        );
        ffi_write_bytes!(
            "updated policy",
            &policy_bytes,
            $updated_policy_ptr,
            $updated_policy_len
        );
    }};
}

/// # Safety
#[no_mangle]
pub unsafe extern "C" fn h_policy(policy_ptr: *mut i8, policy_len: *mut i32) -> i32 {
    let policy = Policy::new();
    let policy_bytes = ffi_unwrap!(
        <Vec<u8>>::try_from(&policy),
        "error deserializing policy",
        ErrorCode::Serialization
    );
    ffi_write_bytes!("policy", &policy_bytes, policy_ptr, policy_len);
}

/// # Safety
#[no_mangle]
pub unsafe extern "C" fn h_add_policy_axis(
    updated_policy_ptr: *mut i8,
    updated_policy_len: *mut i32,
    current_policy_ptr: *const i8,
    current_policy_len: i32,
    axis_ptr: *const i8,
) -> i32 {
    let policy_bytes = ffi_read_bytes!("current policy", current_policy_ptr, current_policy_len);
    let mut policy = ffi_unwrap!(
        Policy::parse_and_convert(policy_bytes),
        "error deserializing policy",
        ErrorCode::Serialization
    );
    let axis_string = ffi_read_string!("axis", axis_ptr);
    let axis: DimensionBuilder = ffi_unwrap!(
        serde_json::from_str(&axis_string),
        "error deserializing policy axis",
        ErrorCode::Serialization
    );

    ffi_unwrap!(
        policy.add_dimension(axis),
        "error adding policy axis",
        ErrorCode::CovercryptPolicy
    );

    let policy_bytes = ffi_unwrap!(
        <Vec<u8>>::try_from(&policy),
        "error serializing policy",
        ErrorCode::Serialization
    );
    ffi_write_bytes!(
        "updated policy",
        &policy_bytes,
        updated_policy_ptr,
        updated_policy_len
    );
}

/// # Safety
#[no_mangle]
pub unsafe extern "C" fn h_remove_policy_axis(
    updated_policy_ptr: *mut i8,
    updated_policy_len: *mut i32,
    current_policy_ptr: *const i8,
    current_policy_len: i32,
    axis_name_ptr: *const i8,
) -> i32 {
    let policy_bytes = ffi_read_bytes!("current policy", current_policy_ptr, current_policy_len);
    let mut policy = ffi_unwrap!(
        Policy::parse_and_convert(policy_bytes),
        "error deserializing policy",
        ErrorCode::Serialization
    );

    let axis_name = ffi_read_string!("axis name", axis_name_ptr);

    ffi_unwrap!(
        policy.remove_dimension(&axis_name),
        "error removing policy axis",
        ErrorCode::CovercryptPolicy
    );

    let policy_bytes = ffi_unwrap!(
        <Vec<u8>>::try_from(&policy),
        "error serializing policy",
        ErrorCode::Serialization
    );
    ffi_write_bytes!(
        "updated policy",
        &policy_bytes,
        updated_policy_ptr,
        updated_policy_len
    );
}

/// # Safety
#[no_mangle]
pub unsafe extern "C" fn h_add_policy_attribute(
    updated_policy_ptr: *mut i8,
    updated_policy_len: *mut i32,
    current_policy_ptr: *const i8,
    current_policy_len: i32,
    attribute: *const i8,
    is_hybridized: bool,
) -> i32 {
    update_policy!(
        updated_policy_ptr,
        updated_policy_len,
        current_policy_ptr,
        current_policy_len,
        attribute,
        cc_policy,
        cc_attr,
        cc_policy.add_attribute(cc_attr, EncryptionHint::new(is_hybridized)),
        "error adding policy attribute"
    )
}

/// # Safety
#[no_mangle]
pub unsafe extern "C" fn h_remove_policy_attribute(
    updated_policy_ptr: *mut i8,
    updated_policy_len: *mut i32,
    current_policy_ptr: *const i8,
    current_policy_len: i32,
    attribute: *const i8,
) -> i32 {
    update_policy!(
        updated_policy_ptr,
        updated_policy_len,
        current_policy_ptr,
        current_policy_len,
        attribute,
        cc_policy,
        cc_attr,
        cc_policy.remove_attribute(&cc_attr),
        "error removing policy attribute"
    )
}

/// # Safety
#[no_mangle]
pub unsafe extern "C" fn h_disable_policy_attribute(
    updated_policy_ptr: *mut i8,
    updated_policy_len: *mut i32,
    current_policy_ptr: *const i8,
    current_policy_len: i32,
    attribute: *const i8,
) -> i32 {
    update_policy!(
        updated_policy_ptr,
        updated_policy_len,
        current_policy_ptr,
        current_policy_len,
        attribute,
        cc_policy,
        cc_attr,
        cc_policy.disable_attribute(&cc_attr),
        "error disabling policy attribute"
    )
}

#[no_mangle]
pub unsafe extern "C" fn h_rename_policy_attribute(
    updated_policy_ptr: *mut i8,
    updated_policy_len: *mut i32,
    current_policy_ptr: *const i8,
    current_policy_len: i32,
    attribute: *const i8,
    new_attribute_name_ptr: *const i8,
) -> i32 {
    let new_attribute_name = ffi_read_string!("new attribute name", new_attribute_name_ptr);

    update_policy!(
        updated_policy_ptr,
        updated_policy_len,
        current_policy_ptr,
        current_policy_len,
        attribute,
        cc_policy,
        cc_attr,
        cc_policy.rename_attribute(&cc_attr, new_attribute_name),
        "error renaming policy attribute"
    )
}

/// # Safety
#[no_mangle]
pub unsafe extern "C" fn h_validate_boolean_expression(boolean_expression_ptr: *const i8) -> i32 {
    let boolean_expression = ffi_read_string!("boolean expression", boolean_expression_ptr);
    ffi_unwrap!(
        AccessPolicy::from_boolean_expression(&boolean_expression),
        "error parsing boolean expression",
        ErrorCode::Serialization
    );
    0
}

/// # Safety
#[no_mangle]
pub unsafe extern "C" fn h_validate_attribute(attribute_ptr: *const i8) -> i32 {
    let attribute_str = ffi_read_string!("attribute", attribute_ptr);
    ffi_unwrap!(
        AccessPolicy::from_boolean_expression(&attribute_str),
        "error parsing attribute",
        ErrorCode::Serialization
    );
    0
}

#[cfg(test)]
mod tests {
    use std::{collections::HashSet, ffi::CString};

    use cosmian_cover_crypt::test_utils::policy;

    use super::*;

    #[test]
    fn test_create_policy() {
        let policy = Policy::new();
        let mut policy_bytes = <Vec<u8>>::try_from(&policy).unwrap();

        let ordered_dim = CString::new(
            r#"{ "name": "Security Level", "attributes_properties": [{ "name": "Protected", "encryption_hint": "Classic" }, { "name": "Confidential", "encryption_hint": "Classic" }, { "name": "Top Secret", "encryption_hint": "Hybridized" }], "hierarchical": true }"#,
        ).unwrap();
        policy_bytes = unsafe {
            let current_policy_ptr = policy_bytes.as_ptr().cast();
            let current_policy_len = policy_bytes.len() as i32;
            let mut updated_policy_bytes = vec![0u8; 4096];
            let updated_policy_ptr = updated_policy_bytes.as_mut_ptr().cast();
            let mut updated_policy_len = updated_policy_bytes.len() as i32;
            let res = h_add_policy_axis(
                updated_policy_ptr,
                &mut updated_policy_len,
                current_policy_ptr,
                current_policy_len,
                ordered_dim.as_ptr().cast(),
            );
            assert_eq!(res, 0);
            std::slice::from_raw_parts(updated_policy_ptr.cast(), updated_policy_len as usize)
                .to_vec()
        };

        let unordered_dim = CString::new(
            r#"{ "name": "Department", "attributes_properties": [{ "name": "HR", "encryption_hint": "Classic" }, { "name": "MKG", "encryption_hint": "Classic" }, { "name": "FIN", "encryption_hint": "Classic" }], "hierarchical": false }"#,
        ).unwrap();
        policy_bytes = unsafe {
            let current_policy_ptr = policy_bytes.as_ptr().cast();
            let current_policy_len = policy_bytes.len() as i32;
            let mut updated_policy_bytes = vec![0u8; 4096];
            let updated_policy_ptr = updated_policy_bytes.as_mut_ptr().cast();
            let mut updated_policy_len = updated_policy_bytes.len() as i32;
            let res = h_add_policy_axis(
                updated_policy_ptr,
                &mut updated_policy_len,
                current_policy_ptr,
                current_policy_len,
                unordered_dim.as_ptr().cast(),
            );
            assert_eq!(res, 0);
            std::slice::from_raw_parts(updated_policy_ptr.cast(), updated_policy_len as usize)
                .to_vec()
        };

        let ffi_policy = Policy::parse_and_convert(&policy_bytes).unwrap();
        let ffi_attributes = ffi_policy.attributes();

        // Check policy size
        assert_eq!(ffi_attributes.len(), 6);

        // Check ordered dimension
        assert_eq!(
            ffi_attributes
                .iter()
                .filter(|attr| attr.dimension == "Security Level")
                .map(|attr| &attr.name)
                .collect::<Vec<_>>(),
            vec!["Protected", "Confidential", "Top Secret"]
        );

        // Check unordered dimension
        let department_attrs = ffi_attributes
            .into_iter()
            .filter(|attr| attr.dimension == "Department")
            .map(|attr| attr.name)
            .collect::<HashSet<_>>();
        assert!(department_attrs.contains("HR"));
        assert!(department_attrs.contains("MKG"));
        assert!(department_attrs.contains("FIN"));
    }

    #[test]
    fn test_edit_policy() {
        let policy = policy().unwrap();
        let mut policy_bytes = <Vec<u8>>::try_from(&policy).unwrap();
        let attributes = policy.attributes();

        assert_eq!(attributes.len(), 9);
        // Remove Security Level axis
        policy_bytes = unsafe {
            let current_policy_ptr = policy_bytes.as_ptr().cast();
            let current_policy_len = policy_bytes.len() as i32;
            let mut updated_policy_bytes = vec![0u8; 8192];
            let updated_policy_ptr = updated_policy_bytes.as_mut_ptr().cast();
            let mut updated_policy_len = updated_policy_bytes.len() as i32;
            let axis_name = CString::new("Security Level").unwrap();

            let res = h_remove_policy_axis(
                updated_policy_ptr,
                &mut updated_policy_len,
                current_policy_ptr,
                current_policy_len,
                axis_name.as_ptr().cast(),
            );
            assert_eq!(res, 0);
            std::slice::from_raw_parts(updated_policy_ptr.cast(), updated_policy_len as usize)
                .to_vec()
        };

        let ffi_edited_policy = Policy::parse_and_convert(&policy_bytes).unwrap();
        let ffi_attributes = ffi_edited_policy.attributes();
        // Check policy size
        assert_eq!(ffi_attributes.len(), 4);

        // Add attribute Sales
        policy_bytes = unsafe {
            let current_policy_ptr = policy_bytes.as_ptr().cast();
            let current_policy_len = policy_bytes.len() as i32;
            let mut updated_policy_bytes = vec![0u8; 8192];
            let updated_policy_ptr = updated_policy_bytes.as_mut_ptr().cast();
            let mut updated_policy_len = updated_policy_bytes.len() as i32;
            let attr = Attribute::new("Department", "Sales");
            let c_attr = CString::new(attr.to_string()).unwrap();

            let res = h_add_policy_attribute(
                updated_policy_ptr,
                &mut updated_policy_len,
                current_policy_ptr,
                current_policy_len,
                c_attr.as_ptr().cast(),
                false,
            );
            assert_eq!(res, 0);
            std::slice::from_raw_parts(updated_policy_ptr.cast(), updated_policy_len as usize)
                .to_vec()
        };

        let ffi_edited_policy = Policy::parse_and_convert(&policy_bytes).unwrap();
        let ffi_attributes = ffi_edited_policy.attributes();
        // Check policy size
        assert_eq!(ffi_attributes.len(), 5);

        // Remove attribute
        policy_bytes = unsafe {
            let current_policy_ptr = policy_bytes.as_ptr().cast();
            let current_policy_len = policy_bytes.len() as i32;
            let mut updated_policy_bytes = vec![0u8; 8192];
            let updated_policy_ptr = updated_policy_bytes.as_mut_ptr().cast();
            let mut updated_policy_len = updated_policy_bytes.len() as i32;
            let attr = Attribute::new("Department", "R&D");
            let c_attr = CString::new(attr.to_string()).unwrap();

            let res = h_remove_policy_attribute(
                updated_policy_ptr,
                &mut updated_policy_len,
                current_policy_ptr,
                current_policy_len,
                c_attr.as_ptr().cast(),
            );
            assert_eq!(res, 0);
            std::slice::from_raw_parts(updated_policy_ptr.cast(), updated_policy_len as usize)
                .to_vec()
        };

        let ffi_edited_policy = Policy::parse_and_convert(&policy_bytes).unwrap();
        let ffi_attributes = ffi_edited_policy.attributes();
        // Check policy size
        assert_eq!(ffi_attributes.len(), 4);

        // Disable attribute
        policy_bytes = unsafe {
            let current_policy_ptr = policy_bytes.as_ptr().cast();
            let current_policy_len = policy_bytes.len() as i32;
            let mut updated_policy_bytes = vec![0u8; 8192];
            let updated_policy_ptr = updated_policy_bytes.as_mut_ptr().cast();
            let mut updated_policy_len = updated_policy_bytes.len() as i32;
            let attr = Attribute::new("Department", "MKG");
            let c_attr = CString::new(attr.to_string()).unwrap();

            let res = h_disable_policy_attribute(
                updated_policy_ptr,
                &mut updated_policy_len,
                current_policy_ptr,
                current_policy_len,
                c_attr.as_ptr().cast(),
            );
            assert_eq!(res, 0);
            std::slice::from_raw_parts(updated_policy_ptr.cast(), updated_policy_len as usize)
                .to_vec()
        };

        let ffi_edited_policy = Policy::parse_and_convert(&policy_bytes).unwrap();
        let ffi_attributes = ffi_edited_policy.attributes();
        // Check policy size
        assert_eq!(ffi_attributes.len(), 4);

        // Rename attribute
        policy_bytes = unsafe {
            let current_policy_ptr = policy_bytes.as_ptr().cast();
            let current_policy_len = policy_bytes.len() as i32;
            let mut updated_policy_bytes = vec![0u8; 8192];
            let updated_policy_ptr = updated_policy_bytes.as_mut_ptr().cast();
            let mut updated_policy_len = updated_policy_bytes.len() as i32;
            let attr = Attribute::new("Department", "FIN");
            let c_attr = CString::new(attr.to_string()).unwrap();
            let c_new_attribute_name = CString::new("Finance".to_string()).unwrap();

            let res = h_rename_policy_attribute(
                updated_policy_ptr,
                &mut updated_policy_len,
                current_policy_ptr,
                current_policy_len,
                c_attr.as_ptr().cast(),
                c_new_attribute_name.as_ptr().cast(),
            );
            assert_eq!(res, 0);
            std::slice::from_raw_parts(updated_policy_ptr.cast(), updated_policy_len as usize)
                .to_vec()
        };

        let ffi_edited_policy = Policy::parse_and_convert(&policy_bytes).unwrap();
        let ffi_attributes = ffi_edited_policy.attributes();
        // Check policy size
        assert_eq!(ffi_attributes.len(), 4);
    }
}