-
Notifications
You must be signed in to change notification settings - Fork 3
/
mod.rs
1909 lines (1733 loc) · 66.2 KB
/
mod.rs
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{
config::{IronOxideConfig, PolicyCachingConfig},
crypto::{
aes::{self, AesEncryptedValue},
transform,
},
internal::{
self,
document_api::requests::UserOrGroupWithKey,
group_api::{GroupId, GroupName},
take_lock,
user_api::UserId,
validate_id, validate_name, IronOxideErr, PrivateKey, PublicKey, RequestAuth, WithKey,
},
policy::PolicyGrant,
proto::transform::{
EncryptedDek as EncryptedDekP, EncryptedDekData as EncryptedDekDataP,
EncryptedDeks as EncryptedDeksP,
},
DeviceSigningKeyPair, PolicyCache,
};
use chrono::{DateTime, Utc};
use futures::{try_join, Future};
use hex::encode;
use itertools::{Either, Itertools};
use protobuf::{Message, RepeatedField};
use rand::{self, CryptoRng, RngCore};
use recrypt::{api::Plaintext, prelude::*};
pub use requests::policy_get::PolicyResponse;
use requests::{
document_create,
document_list::{DocumentListApiResponse, DocumentListApiResponseItem},
DocumentMetaApiResponse,
};
use std::{
convert::{TryFrom, TryInto},
fmt::Formatter,
ops::DerefMut,
sync::Mutex,
};
mod requests;
const DOC_VERSION_HEADER_LENGTH: usize = 1;
const HEADER_META_LENGTH_LENGTH: usize = 2;
const CURRENT_DOCUMENT_ID_VERSION: u8 = 2;
/// Document ID. Unique within the segment. Must match the regex `^[a-zA-Z0-9_.$#|@/:;=+'-]+$`
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct DocumentId(pub(crate) String);
impl DocumentId {
pub fn id(&self) -> &str {
&self.0
}
/// Generate a random id for a document
pub(crate) fn goo_id<R: CryptoRng + RngCore>(rng: &Mutex<R>) -> DocumentId {
let mut id = [0u8; 16];
take_lock(rng).deref_mut().fill_bytes(&mut id);
DocumentId(encode(id))
}
}
impl TryFrom<&str> for DocumentId {
type Error = IronOxideErr;
fn try_from(id: &str) -> Result<Self, Self::Error> {
validate_id(id, "document_id").map(DocumentId)
}
}
impl TryFrom<String> for DocumentId {
type Error = IronOxideErr;
fn try_from(doc_id: String) -> Result<Self, Self::Error> {
doc_id.as_str().try_into()
}
}
/// (unencrypted) name of a document. Construct via `try_from(&str)`
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct DocumentName(pub(crate) String);
impl DocumentName {
pub fn name(&self) -> &String {
&self.0
}
}
impl TryFrom<&str> for DocumentName {
type Error = IronOxideErr;
fn try_from(name: &str) -> Result<Self, Self::Error> {
validate_name(name, "document_name").map(DocumentName)
}
}
/// Binary version of the document header. Appropriate for using in edoc serialization.
struct DocHeaderPacked(Vec<u8>);
/// Represents a parsed document header which is decoded from JSON
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct DocumentHeader {
#[serde(rename = "_did_")]
document_id: DocumentId,
#[serde(rename = "_sid_")]
segment_id: usize,
}
impl DocumentHeader {
fn new(document_id: DocumentId, segment_id: usize) -> DocumentHeader {
DocumentHeader {
document_id,
segment_id,
}
}
/// Generate a documents header given its ID and internal segment ID that is is associated with. Generates
/// a Vec<u8> which includes the document version, header size, and header JSON as bytes.
fn pack(&self) -> DocHeaderPacked {
let mut header_json_bytes =
serde_json::to_vec(&self).expect("Serialization of DocumentHeader failed."); //Serializing a string and number shouldn't fail
let header_json_len = header_json_bytes.len();
//Make header vector with size of header plus 1 byte for version and 2 bytes for header length
let mut header = Vec::with_capacity(header_json_len + 3);
header.push(CURRENT_DOCUMENT_ID_VERSION);
//Push the header length representation as two bytes, most significant digit first (BigEndian)
header.push((header_json_len >> 8) as u8);
header.push(header_json_len as u8);
header.append(&mut header_json_bytes);
DocHeaderPacked(header)
}
}
/// Take an encrypted document and extract out the header metadata. Return that metadata as well as the AESEncryptedValue
/// that contains the AES IV and encrypted content. Will fail if the provided document doesn't contain the latest version
/// which contains the header bytes.
fn parse_document_parts(
encrypted_document: &[u8],
) -> Result<(DocumentHeader, aes::AesEncryptedValue), IronOxideErr> {
//We're explicitly erroring on version 1 documents since there are so few of them and it seems extremely unlikely
//that anybody will use them with this SDK which was released after we went to version 2.
if encrypted_document[0] != CURRENT_DOCUMENT_ID_VERSION {
Err(IronOxideErr::DocumentHeaderParseFailure(
"Document is not a supported version and may not be an encrypted file.".to_string(),
))
} else {
let header_len_end = DOC_VERSION_HEADER_LENGTH + HEADER_META_LENGTH_LENGTH;
//The 2nd and 3rd bytes of the header are a big-endian u16 that tell us how long the subsequent JSON
//header is in bytes. So we need to convert these two u8s into a single u16.
let encoded_header_size =
encrypted_document[1] as usize * 256 + encrypted_document[2] as usize;
serde_json::from_slice(
&encrypted_document[header_len_end..(header_len_end + encoded_header_size)],
)
.map_err(|_| {
IronOxideErr::DocumentHeaderParseFailure(
"Unable to parse document header. Header value is corrupted.".to_string(),
)
})
.and_then(|header_json| {
//Convert the remaining document bytes into an AesEncryptedValue which splits out the IV/data
Ok((
header_json,
encrypted_document[(header_len_end + encoded_header_size)..].try_into()?,
))
})
}
}
/// Represents the reason a document can be viewed by the requesting user.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AssociationType {
/// User created the document
Owner,
/// User directly granted access to the document
FromUser,
/// User granted access to the document via a group they are a member of
FromGroup,
}
/// Represents a User struct which is returned from doc get to show the IDs of users the document is visible to
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct VisibleUser {
id: UserId,
}
impl VisibleUser {
pub fn id(&self) -> &UserId {
&self.id
}
}
/// Represents a Group struct which is returned from doc get to show the IDs and names of groups the document is visible to
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct VisibleGroup {
id: GroupId,
name: Option<GroupName>,
}
impl VisibleGroup {
pub fn id(&self) -> &GroupId {
&self.id
}
pub fn name(&self) -> Option<&GroupName> {
self.name.as_ref()
}
}
/// Single document's (abbreviated) metadata. Returned as part of a `DocumentListResult`.
///
/// If you want full metadata for a document, see `DocumentMetadataResult`
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentListMeta(DocumentListApiResponseItem);
impl DocumentListMeta {
pub fn id(&self) -> &DocumentId {
&self.0.id
}
pub fn name(&self) -> Option<&DocumentName> {
self.0.name.as_ref()
}
pub fn association_type(&self) -> &AssociationType {
&self.0.association.typ
}
pub fn created(&self) -> &DateTime<Utc> {
&self.0.created
}
pub fn last_updated(&self) -> &DateTime<Utc> {
&self.0.updated
}
}
/// Metadata for each of the documents that the current user has access to decrypt.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentListResult {
result: Vec<DocumentListMeta>,
}
impl DocumentListResult {
pub fn result(&self) -> &Vec<DocumentListMeta> {
&self.result
}
}
/// Full metadata for a document.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentMetadataResult(DocumentMetaApiResponse);
impl DocumentMetadataResult {
pub fn id(&self) -> &DocumentId {
&self.0.id
}
pub fn name(&self) -> Option<&DocumentName> {
self.0.name.as_ref()
}
pub fn created(&self) -> &DateTime<Utc> {
&self.0.created
}
pub fn last_updated(&self) -> &DateTime<Utc> {
&self.0.updated
}
pub fn association_type(&self) -> &AssociationType {
&self.0.association.typ
}
pub fn visible_to_users(&self) -> &Vec<VisibleUser> {
&self.0.visible_to.users
}
pub fn visible_to_groups(&self) -> &Vec<VisibleGroup> {
&self.0.visible_to.groups
}
pub(crate) fn to_encrypted_symmetric_key(
&self,
) -> Result<recrypt::api::EncryptedValue, IronOxideErr> {
self.0.encrypted_symmetric_key.clone().try_into()
}
}
/// Result for encrypt operations that do not store document access information with the webservice,
/// but rather return the access information as `encrypted_deks`. Both the `encrypted_data` and
/// `encrypted_deks` must be used to decrypt. See `document_edek_decrypt`
///
/// - `id` - Unique (within the segment) id of the document
/// - `encrypted_data` - Bytes of encrypted document content
/// - `encrypted_deks` - List of encrypted document encryption keys (EDEK) of users/groups that have been granted access to `encrypted_data`
/// - `access_errs` - Users and groups that could not be granted access
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentEncryptUnmanagedResult {
id: DocumentId,
encrypted_data: Vec<u8>,
encrypted_deks: Vec<u8>,
grants: Vec<UserOrGroup>,
access_errs: Vec<DocAccessEditErr>,
}
impl DocumentEncryptUnmanagedResult {
fn new(
encryption_result: EncryptedDoc,
access_errs: Vec<DocAccessEditErr>,
) -> Result<Self, IronOxideErr> {
let edek_bytes = encryption_result.edek_bytes()?;
Ok(DocumentEncryptUnmanagedResult {
id: encryption_result.header.document_id.clone(),
access_errs,
encrypted_data: encryption_result.edoc_bytes().to_vec(),
encrypted_deks: edek_bytes,
grants: encryption_result
.value
.edeks
.iter()
.map(|edek| edek.grant_to.id.clone())
.collect(),
})
}
pub fn id(&self) -> &DocumentId {
&self.id
}
pub fn encrypted_data(&self) -> &[u8] {
&self.encrypted_data
}
pub fn encrypted_deks(&self) -> &[u8] {
&self.encrypted_deks
}
pub fn access_errs(&self) -> &[DocAccessEditErr] {
&self.access_errs
}
pub fn grants(&self) -> &[UserOrGroup] {
&self.grants
}
}
/// Result for encrypt operations.
///
/// - `id` - Unique (within the segment) id of the document
/// - `name` Non-unique document name. The document name is *not* encrypted.
/// - `updated` - When the document was last updated
/// - `created` - When the document was created
/// - `encrypted_data` - Bytes of encrypted document content
/// - `grants` - Users and groups that have access to decrypt the `encrypted_data`
/// - `access_errs` - Users and groups that could not be granted access
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentEncryptResult {
id: DocumentId,
name: Option<DocumentName>,
updated: DateTime<Utc>,
created: DateTime<Utc>,
encrypted_data: Vec<u8>,
grants: Vec<UserOrGroup>,
access_errs: Vec<DocAccessEditErr>,
}
impl DocumentEncryptResult {
pub fn id(&self) -> &DocumentId {
&self.id
}
pub fn name(&self) -> Option<&DocumentName> {
self.name.as_ref()
}
pub fn created(&self) -> &DateTime<Utc> {
&self.created
}
pub fn last_updated(&self) -> &DateTime<Utc> {
&self.updated
}
pub fn encrypted_data(&self) -> &[u8] {
&self.encrypted_data
}
pub fn grants(&self) -> &[UserOrGroup] {
&self.grants
}
pub fn access_errs(&self) -> &[DocAccessEditErr] {
&self.access_errs
}
}
/// Result of decrypting a document. Includes minimal metadata as well as the decrypted bytes.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentDecryptResult {
id: DocumentId,
name: Option<DocumentName>,
updated: DateTime<Utc>,
created: DateTime<Utc>,
decrypted_data: Vec<u8>,
}
impl DocumentDecryptResult {
pub fn id(&self) -> &DocumentId {
&self.id
}
pub fn name(&self) -> Option<&DocumentName> {
self.name.as_ref()
}
pub fn created(&self) -> &DateTime<Utc> {
&self.created
}
pub fn last_updated(&self) -> &DateTime<Utc> {
&self.updated
}
pub fn decrypted_data(&self) -> &[u8] {
&self.decrypted_data
}
}
/// A failure to edit the access list of a document.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocAccessEditErr {
/// User or group whose access was to be granted/revoked
pub user_or_group: UserOrGroup,
/// Reason for failure
pub err: String,
}
impl DocAccessEditErr {
pub(crate) fn new(user_or_group: UserOrGroup, err_msg: String) -> DocAccessEditErr {
DocAccessEditErr {
user_or_group,
err: err_msg,
}
}
}
/// Result of granting or revoking access to a document. Both grant and revoke support partial
/// success.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentAccessResult {
succeeded: Vec<UserOrGroup>,
failed: Vec<DocAccessEditErr>,
}
impl DocumentAccessResult {
pub(crate) fn new(
succeeded: Vec<UserOrGroup>,
failed: Vec<DocAccessEditErr>,
) -> DocumentAccessResult {
DocumentAccessResult { succeeded, failed }
}
/// Users whose access was successfully changed.
pub fn succeeded(&self) -> &[UserOrGroup] {
&self.succeeded
}
/// Users whose access was not changed.
pub fn failed(&self) -> &[DocAccessEditErr] {
&self.failed
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct DecryptedData(Vec<u8>);
/// Result of successful unmanaged decryption
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentDecryptUnmanagedResult {
id: DocumentId,
access_via: UserOrGroup,
decrypted_data: DecryptedData,
}
impl DocumentDecryptUnmanagedResult {
pub fn id(&self) -> &DocumentId {
&self.id
}
/// user/group that granted access to the encrypted data. More specifically, the
/// user/group associated with the EDEK that was chosen and transformed by the webservice
pub fn access_via(&self) -> &UserOrGroup {
&self.access_via
}
/// plaintext user data
pub fn decrypted_data(&self) -> &[u8] {
&self.decrypted_data.0
}
}
/// Either a user or a group. Allows for containing both.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum UserOrGroup {
User { id: UserId },
Group { id: GroupId },
}
impl std::fmt::Display for UserOrGroup {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
UserOrGroup::User { id } => write!(f, "'{}' [user]", &id.0),
UserOrGroup::Group { id } => write!(f, "'{}' [group]", &id.0),
}
}
}
impl From<&UserId> for UserOrGroup {
fn from(u: &UserId) -> Self {
UserOrGroup::User { id: u.clone() }
}
}
impl From<&GroupId> for UserOrGroup {
fn from(g: &GroupId) -> Self {
UserOrGroup::Group { id: g.clone() }
}
}
/// List all documents that the current user has the ability to see. Either documents that are encrypted
/// to them directly (owner) or documents shared to them via user (fromUser) or group (fromGroup).
pub async fn document_list(auth: &RequestAuth) -> Result<DocumentListResult, IronOxideErr> {
let DocumentListApiResponse { result } =
requests::document_list::document_list_request(auth).await?;
Ok(DocumentListResult {
result: result.into_iter().map(DocumentListMeta).collect(),
})
}
/// Get the metadata ane encrypted key for a specific document given its ID.
pub async fn document_get_metadata(
auth: &RequestAuth,
id: &DocumentId,
) -> Result<DocumentMetadataResult, IronOxideErr> {
Ok(DocumentMetadataResult(
requests::document_get::document_get_request(auth, id).await?,
))
}
/// Attempt to parse the provided encrypted document header and extract out the ID if present
pub fn get_id_from_bytes(encrypted_document: &[u8]) -> Result<DocumentId, IronOxideErr> {
parse_document_parts(encrypted_document).map(|header| header.0.document_id)
}
/// Encrypt a new document and share it with explicit users/groups and with users/groups specified by a policy
pub async fn encrypt_document<
R1: rand::CryptoRng + rand::RngCore,
R2: rand::CryptoRng + rand::RngCore,
>(
auth: &RequestAuth,
config: &IronOxideConfig,
recrypt: &Recrypt<Sha256, Ed25519, RandomBytes<R1>>,
user_master_pub_key: &PublicKey,
rng: &Mutex<R2>,
plaintext: &[u8],
document_id: Option<DocumentId>,
document_name: Option<DocumentName>,
grant_to_author: bool,
user_grants: &Vec<UserId>,
group_grants: &Vec<GroupId>,
policy_grant: Option<&PolicyGrant>,
policy_cache: &PolicyCache,
) -> Result<DocumentEncryptResult, IronOxideErr> {
let (dek, doc_sym_key) = transform::generate_new_doc_key(recrypt);
let doc_id = document_id.unwrap_or_else(|| DocumentId::goo_id(rng));
let pt_bytes = plaintext.to_vec();
let (encrypted_doc, (grants, key_errs)) = try_join!(
aes::encrypt_async(rng, &pt_bytes, *doc_sym_key.bytes()),
resolve_keys_for_grants(
auth,
config,
user_grants,
group_grants,
policy_grant,
if grant_to_author {
Some(&user_master_pub_key)
} else {
None
},
policy_cache
)
)?;
let r = recrypt_document(
&auth.signing_private_key,
recrypt,
dek,
encrypted_doc,
&doc_id,
grants,
)?;
let encryption_errs = r.encryption_errs.clone();
document_create(
auth,
r.into_edoc(DocumentHeader::new(doc_id.clone(), auth.segment_id)),
doc_id,
&document_name,
[key_errs, encryption_errs].concat(),
)
.await
}
type UserMasterPublicKey = PublicKey;
/// Get the public keys for a document grant.
///
/// # Arguments
/// `auth` - info to make webservice requests
/// `user_grants` - list of user ids to which document access should be granted
/// `group_grants` - list of groups ids to which document access should be granted
/// `policy_grant` - policy to apply for document access
/// `maybe_user_master_pub_key`
/// - if Some, contains the logged in user's master public key for self-grant
///
/// # Returns
/// A Future that will resolve to:
/// (Left) list of keys for all users and groups that should be granted access to the document
/// (Right) errors for any invalid users/groups that were passed
async fn resolve_keys_for_grants(
auth: &RequestAuth,
config: &IronOxideConfig,
user_grants: &Vec<UserId>,
group_grants: &Vec<GroupId>,
policy_grant: Option<&PolicyGrant>,
maybe_user_master_pub_key: Option<&UserMasterPublicKey>,
policy_cache: &PolicyCache,
) -> Result<(Vec<WithKey<UserOrGroup>>, Vec<DocAccessEditErr>), IronOxideErr> {
let get_user_keys_f = internal::user_api::get_user_keys(auth, user_grants);
let get_group_keys_f = internal::group_api::get_group_keys(auth, group_grants);
let maybe_policy_grants_f =
policy_grant.map(|p| (p, requests::policy_get::policy_get_request(auth, p)));
let policy_grants_f = async {
if let Some((p, policy_eval_f)) = maybe_policy_grants_f {
get_cached_policy_or(&config.policy_caching, p, policy_cache, policy_eval_f).await
} else {
// No policies were included
Ok((vec![], vec![]))
}
};
let (users, groups, policy_result) =
try_join!(get_user_keys_f, get_group_keys_f, policy_grants_f)?;
let (group_errs, groups_with_key) = process_groups(groups);
let (user_errs, users_with_key) = process_users(users);
let explicit_grants = [users_with_key, groups_with_key].concat();
let (policy_errs, applied_policy_grants) = policy_result;
let maybe_self_grant = {
if let Some(user_master_pub_key) = maybe_user_master_pub_key {
vec![WithKey::new(
UserOrGroup::User {
id: auth.account_id.clone(),
},
user_master_pub_key.clone(),
)]
} else {
vec![]
}
};
Ok((
{ [maybe_self_grant, explicit_grants, applied_policy_grants].concat() },
[group_errs, user_errs, policy_errs].concat(),
))
}
/// Get a cached policy or run the given Future to get the evaluated policy from the webservice.
/// Policies that evaluate cleanly with no invalid users or groups are cached for future use.
async fn get_cached_policy_or<F>(
config: &PolicyCachingConfig,
grant: &PolicyGrant,
policy_cache: &PolicyCache,
get_policy_f: F,
) -> Result<(Vec<DocAccessEditErr>, Vec<WithKey<UserOrGroup>>), IronOxideErr>
where
F: Future<Output = Result<PolicyResponse, IronOxideErr>>,
{
// if there's a value in the cache, use it
if let Some(cached_policy) = policy_cache.get(grant) {
Ok((vec![], cached_policy.clone()))
} else {
// otherwise query the webservice and cache the result if there are no errors
get_policy_f.await.map(|policy_resp| {
let (errs, public_keys) = process_policy(&policy_resp);
if errs.is_empty() {
//if the cache has grown too large, clear it prior to adding new entries
if policy_cache.len() >= config.max_entries {
policy_cache.clear()
}
policy_cache.insert(grant.clone(), public_keys.clone());
}
(errs, public_keys)
})
}
}
/// Encrypts a document but does not create the document in the IronCore system.
/// The resultant DocumentDetachedEncryptResult contains both the EncryptedDeks and the AesEncryptedValue
/// Both pieces will be required for decryption.
pub async fn encrypt_document_unmanaged<R1, R2>(
auth: &RequestAuth,
recrypt: &Recrypt<Sha256, Ed25519, RandomBytes<R1>>,
user_master_pub_key: &PublicKey,
rng: &Mutex<R2>,
plaintext: &[u8],
document_id: Option<DocumentId>,
grant_to_author: bool,
user_grants: &Vec<UserId>,
group_grants: &Vec<GroupId>,
policy_grant: Option<&PolicyGrant>,
) -> Result<DocumentEncryptUnmanagedResult, IronOxideErr>
where
R1: rand::CryptoRng + rand::RngCore,
R2: rand::CryptoRng + rand::RngCore,
{
let policy_cache = dashmap::DashMap::new();
let config = IronOxideConfig::default();
let (dek, doc_sym_key) = transform::generate_new_doc_key(recrypt);
let doc_id = document_id.unwrap_or_else(|| DocumentId::goo_id(rng));
let pt_bytes = plaintext.to_vec();
let (encryption_result, (grants, key_errs)) = try_join!(
aes::encrypt_async(rng, &pt_bytes, *doc_sym_key.bytes()),
resolve_keys_for_grants(
auth,
&config,
user_grants,
group_grants,
policy_grant,
if grant_to_author {
Some(&user_master_pub_key)
} else {
None
},
&policy_cache
)
)?;
let r = recrypt_document(
&auth.signing_private_key,
recrypt,
dek,
encryption_result,
&doc_id,
grants,
)?;
let enc_result = EncryptedDoc {
header: DocumentHeader::new(doc_id.clone(), auth.segment_id),
value: r,
};
let access_errs = [&key_errs[..], &enc_result.value.encryption_errs[..]].concat();
DocumentEncryptUnmanagedResult::new(enc_result, access_errs)
}
/// Remove any duplicates in the grant list. Uses ids (not keys) for comparison.
fn dedupe_grants(grants: &[WithKey<UserOrGroup>]) -> Vec<WithKey<UserOrGroup>> {
grants
.iter()
.unique_by(|i| &i.id)
.map(Clone::clone)
.collect_vec()
}
/// Encrypt the document using transform crypto (recrypt).
/// Can be called once you have public keys for users/groups that should have access as well as the
/// AES encrypted data.
fn recrypt_document<CR: rand::CryptoRng + rand::RngCore>(
signing_keys: &DeviceSigningKeyPair,
recrypt: &Recrypt<Sha256, Ed25519, RandomBytes<CR>>,
dek: Plaintext,
encrypted_doc: AesEncryptedValue,
doc_id: &DocumentId,
grants: Vec<WithKey<UserOrGroup>>,
) -> Result<RecryptionResult, IronOxideErr> {
// check to make sure that we are granting to something
if grants.is_empty() {
Err(IronOxideErr::ValidationError(
"grants".into(),
format!(
"Access must be granted to document {:?} by explicit grant or via a policy",
&doc_id
),
))
} else {
Ok({
// encrypt to all the users and groups
let (encrypt_errs, grants) = transform::encrypt_to_with_key(
recrypt,
&dek,
&signing_keys.into(),
dedupe_grants(&grants),
);
RecryptionResult {
edeks: grants
.into_iter()
.map(|(wk, ev)| EncryptedDek {
grant_to: wk,
encrypted_dek_data: ev,
})
.collect(),
encrypted_data: encrypted_doc,
encryption_errs: vec![encrypt_errs.into_iter().map(|e| e.into()).collect()]
.into_iter()
.concat(),
}
})
}
}
/// An encrypted document encryption key.
///
/// Once decrypted, the DEK serves as a symmetric encryption key.
///
/// It can also be useful to think of an EDEK as representing a "document access grant" to a user/group.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct EncryptedDek {
grant_to: WithKey<UserOrGroup>,
encrypted_dek_data: recrypt::api::EncryptedValue,
}
impl TryFrom<&EncryptedDek> for EncryptedDekP {
type Error = IronOxideErr;
fn try_from(edek: &EncryptedDek) -> Result<Self, Self::Error> {
use crate::proto::transform;
use recrypt::api as re;
// encode the recrypt EncryptedValue to a edek proto
let proto_edek_data = match edek.encrypted_dek_data {
re::EncryptedValue::EncryptedOnceValue {
ephemeral_public_key,
encrypted_message,
auth_hash,
public_signing_key,
signature,
} => {
let mut proto_edek_data = EncryptedDekDataP::default();
proto_edek_data.set_encryptedBytes(encrypted_message.bytes().to_vec().into());
proto_edek_data
.set_ephemeralPublicKey(PublicKey::from(ephemeral_public_key).into());
proto_edek_data.set_signature(signature.bytes().to_vec().into());
proto_edek_data.set_authHash(auth_hash.bytes().to_vec().into());
proto_edek_data.set_publicSigningKey(public_signing_key.bytes().to_vec().into());
Ok(proto_edek_data)
}
re::EncryptedValue::TransformedValue { .. } => Err(
IronOxideErr::InvalidRecryptEncryptedValue("Expected".to_string()),
),
}?;
//convert the grants
let proto_uog = match edek.grant_to.clone() {
WithKey {
id:
UserOrGroup::User {
id: UserId(user_string),
},
public_key,
} => {
let mut proto_uog = transform::UserOrGroup::default();
proto_uog.set_userId(user_string.into());
proto_uog.set_masterPublicKey(public_key.into());
proto_uog
}
WithKey {
id:
UserOrGroup::Group {
id: GroupId(group_string),
},
public_key,
} => {
let mut proto_uog = transform::UserOrGroup::default();
proto_uog.set_groupId(group_string.into());
proto_uog.set_masterPublicKey(public_key.into());
proto_uog
}
};
let mut proto_edek = EncryptedDekP::default();
proto_edek.set_userOrGroup(proto_uog);
proto_edek.set_encryptedDekData(proto_edek_data);
Ok(proto_edek)
}
}
/// Result of recrypt encryption. Contains the encrypted DEKs and the encrypted (user) data.
/// `RecryptionResult` is an intermediate value as it cannot be serialized to bytes directly.
/// To serialize to bytes, first construct an `EncryptedDoc`
#[derive(Clone, Debug)]
struct RecryptionResult {
edeks: Vec<EncryptedDek>,
encrypted_data: AesEncryptedValue,
encryption_errs: Vec<DocAccessEditErr>,
}
impl RecryptionResult {
fn into_edoc(self, header: DocumentHeader) -> EncryptedDoc {
EncryptedDoc {
value: self,
header,
}
}
}
/// An ironoxide encrypted document
#[derive(Debug)]
struct EncryptedDoc {
header: DocumentHeader,
value: RecryptionResult,
}
impl EncryptedDoc {
/// bytes of the encrypted data with the edoc header prepended
fn edoc_bytes(&self) -> Vec<u8> {
[
&self.header.pack().0[..],
&self.value.encrypted_data.bytes(),
]
.concat()
}
/// associated EncryptedDeks for this EncryptedDoc
fn edek_vec(&self) -> Vec<EncryptedDek> {
self.value.edeks.clone()
}
/// binary blob for associated edeks, or error if encoding the edeks failed
fn edek_bytes(&self) -> Result<Vec<u8>, IronOxideErr> {
let proto_edek_vec_results: Result<Vec<_>, _> = self
.value
.edeks
.iter()
.map(|edek| edek.try_into())
.collect();
let proto_edek_vec = proto_edek_vec_results?;
let mut proto_edeks = EncryptedDeksP::default();
proto_edeks.edeks = RepeatedField::from_vec(proto_edek_vec);
proto_edeks.documentId = self.header.document_id.id().into();
proto_edeks.segmentId = self.header.segment_id as i32; // okay since the ironcore-ws defines this to be an i32
let edek_bytes = proto_edeks.write_to_bytes()?;
Ok(edek_bytes)
}
}
/// Creates an encrypted document entry in the IronCore webservice.
async fn document_create(
auth: &RequestAuth,
edoc: EncryptedDoc,
doc_id: DocumentId,
doc_name: &Option<DocumentName>,
accum_errs: Vec<DocAccessEditErr>,
) -> Result<DocumentEncryptResult, IronOxideErr> {
let api_resp = document_create::document_create_request(
auth,
doc_id.clone(),
doc_name.clone(),
edoc.edek_vec(),
)
.await?;
Ok(DocumentEncryptResult {
id: api_resp.id,
name: api_resp.name,
created: api_resp.created,
updated: api_resp.updated,
encrypted_data: edoc.edoc_bytes().to_vec(),
grants: api_resp.shared_with.iter().map(|sw| sw.into()).collect(),
access_errs: [accum_errs, edoc.value.encryption_errs].concat(),
})
}
/// Encrypt the provided plaintext using the DEK from the provided document ID but with a new AES IV. Allows updating the encrypted bytes
/// of a document without having to change document access.
pub async fn document_update_bytes<
R1: rand::CryptoRng + rand::RngCore,
R2: rand::CryptoRng + rand::RngCore,
>(
auth: &RequestAuth,
recrypt: &Recrypt<Sha256, Ed25519, RandomBytes<R1>>,
device_private_key: &PrivateKey,
rng: &Mutex<R2>,
document_id: &DocumentId,
plaintext: &[u8],
) -> Result<DocumentEncryptResult, IronOxideErr> {
let doc_meta = document_get_metadata(auth, document_id).await?;
let sym_key = transform::decrypt_as_symmetric_key(
recrypt,
doc_meta.0.encrypted_symmetric_key.clone().try_into()?,
device_private_key.recrypt_key(),
)?;
Ok(
aes::encrypt(rng, &plaintext.to_vec(), *sym_key.bytes()).map(move |encrypted_doc| {
let mut encrypted_payload =
DocumentHeader::new(document_id.clone(), auth.segment_id()).pack();
encrypted_payload.0.append(&mut encrypted_doc.bytes());
DocumentEncryptResult {
id: doc_meta.0.id,
name: doc_meta.0.name,
created: doc_meta.0.created,
updated: doc_meta.0.updated,
encrypted_data: encrypted_payload.0,
grants: vec![], // grants can't currently change via update
access_errs: vec![], // no grants, no access errs
}
})?,
)
}
/// Decrypt the provided document with the provided device private key. Return metadata about the document
/// that was decrypted along with its decrypted bytes.
pub async fn decrypt_document<CR: rand::CryptoRng + rand::RngCore>(
auth: &RequestAuth,
recrypt: &Recrypt<Sha256, Ed25519, RandomBytes<CR>>,
device_private_key: &PrivateKey,
encrypted_doc: &[u8],
) -> Result<DocumentDecryptResult, IronOxideErr> {
let (doc_header, mut enc_doc) = parse_document_parts(encrypted_doc)?;
let doc_meta = document_get_metadata(auth, &doc_header.document_id).await?;
let sym_key = transform::decrypt_as_symmetric_key(
recrypt,
doc_meta.0.encrypted_symmetric_key.clone().try_into()?,
device_private_key.recrypt_key(),
)?;
Ok(