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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
use crate::internal::take_lock;
use crate::proto::transform::EncryptedDek as EncryptedDekP;
use crate::proto::transform::EncryptedDekData as EncryptedDekDataP;
use crate::proto::transform::EncryptedDeks as EncryptedDeksP;
use crate::{
    crypto::{
        aes::{self, AesEncryptedValue},
        transform,
    },
    internal::{
        self,
        document_api::requests::UserOrGroupWithKey,
        group_api::{GroupId, GroupName},
        user_api::UserId,
        validate_id, validate_name, IronOxideErr, PrivateKey, PublicKey, RequestAuth, WithKey,
    },
    policy::PolicyGrant,
    DeviceSigningKeyPair,
};
use chrono::{DateTime, Utc};
use futures::prelude::*;
use hex::encode;
use itertools::{Either, Itertools};
use protobuf::{Message, ProtobufError, RepeatedField};
use rand::{self, CryptoRng, RngCore};
use recrypt::{api::Plaintext, prelude::*};
pub use requests::policy_get::PolicyResult;
use requests::{
    document_create,
    document_list::{DocumentListApiResponse, DocumentListApiResponseItem},
    DocumentMetaApiResponse,
};
use std::ops::DerefMut;
use std::sync::Mutex;
use std::{
    convert::{TryFrom, TryInto},
    fmt::Formatter,
};

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(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DocumentId(pub(crate) String);
impl DocumentId {
    pub fn id(&self) -> &String {
        &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()
    }
}

/// Document name type. Validates that the provided document name isn't an empty string
#[derive(Debug, Clone, 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)
    }
}

/// Represents a parsed document header which is decoded from JSON
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct DocumentHeader {
    #[serde(rename = "_did_")]
    pub document_id: DocumentId,
    #[serde(rename = "_sid_")]
    pub segment_id: usize,
}

// 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()?,
            ))
        })
    }
}

// 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 generate_document_header(document_id: DocumentId, segment_id: usize) -> Vec<u8> {
    let mut header_json_bytes = serde_json::to_vec(&DocumentHeader {
        document_id,
        segment_id,
    })
    .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);
    header
}

/// Represents the reason a document can be viewed by the requesting user.
#[derive(Serialize, Deserialize, Debug, Clone, Hash, PartialEq, Eq)]
#[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(Serialize, Deserialize, Debug, Clone, PartialEq)]
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(Serialize, Deserialize, Debug, Clone, PartialEq)]
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)]
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(Debug)]
pub struct DocumentListResult {
    result: Vec<DocumentListMeta>,
}
impl DocumentListResult {
    pub fn result(&self) -> &Vec<DocumentListMeta> {
        &self.result
    }
}

/// Full metadata for a document.
#[derive(Clone)]
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(Debug)]
pub struct DocumentEncryptUnmanagedResult {
    id: DocumentId,
    encrypted_data: Vec<u8>,
    encrypted_deks: Vec<u8>,
    grants: Vec<UserOrGroup>,
    access_errs: Vec<DocAccessEditErr>,
}

impl DocumentEncryptUnmanagedResult {
    fn new(
        doc_id: &DocumentId,
        segment_id: usize,
        encryption_result: EncryptionResult,
        access_errs: Vec<DocAccessEditErr>,
    ) -> Result<Self, IronOxideErr> {
        let proto_edek_vec_results: Result<Vec<_>, _> = encryption_result
            .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 = doc_id.id().as_str().into();
        proto_edeks.segmentId = segment_id as i32; // okay since the ironcore-ws defines this to be an i32

        let edek_bytes = proto_edeks.write_to_bytes()?;

        Ok(DocumentEncryptUnmanagedResult {
            id: doc_id.clone(),
            access_errs,
            encrypted_data: encryption_result.encrypted_data.bytes(),
            encrypted_deks: edek_bytes,
            grants: encryption_result
                .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(Debug)]
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(Debug)]
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(Debug, Clone)]
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(Debug)]
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
    }
}

/// Either a user or a group. Allows for containing both.
#[derive(Clone, Debug, PartialEq, Eq, Hash, 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 fn document_list(
    auth: &RequestAuth,
) -> impl Future<Item = DocumentListResult, Error = IronOxideErr> {
    requests::document_list::document_list_request(auth).map(
        |DocumentListApiResponse { result }| DocumentListResult {
            result: result.into_iter().map(DocumentListMeta).collect(),
        },
    )
}

/// Get the metadata ane encrypted key for a specific document given its ID.
pub fn document_get_metadata(
    auth: &RequestAuth,
    id: &DocumentId,
) -> impl Future<Item = DocumentMetadataResult, Error = IronOxideErr> {
    requests::document_get::document_get_request(auth, id).map(DocumentMetadataResult)
}

// 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 fn encrypt_document<
    'a,
    R1: rand::CryptoRng + rand::RngCore,
    R2: rand::CryptoRng + rand::RngCore,
>(
    auth: &'a RequestAuth,
    recrypt: &'a Recrypt<Sha256, Ed25519, RandomBytes<R1>>,
    user_master_pub_key: &'a PublicKey,
    rng: &'a Mutex<R2>,
    plaintext: &'a [u8],
    document_id: Option<DocumentId>,
    document_name: Option<DocumentName>,
    grant_to_author: bool,
    user_grants: &'a Vec<UserId>,
    group_grants: &'a Vec<GroupId>,
    policy_grant: Option<&'a PolicyGrant>,
) -> impl Future<Item = DocumentEncryptResult, Error = IronOxideErr> + 'a {
    let (dek, doc_sym_key) = transform::generate_new_doc_key(recrypt);
    let doc_id = document_id.unwrap_or(DocumentId::goo_id(rng));
    aes::encrypt_future(rng, &plaintext.to_vec(), *doc_sym_key.bytes())
        .join(resolve_keys_for_grants(
            auth,
            user_grants,
            group_grants,
            policy_grant,
            if grant_to_author {
                Some(&user_master_pub_key)
            } else {
                None
            },
        ))
        .and_then(move |(encrypted_doc, (grants, key_errs))| {
            recrypt_document(
                &auth.signing_keys,
                recrypt,
                dek,
                encrypted_doc,
                &doc_id,
                grants,
            )
            .into_future()
            .and_then(move |r| {
                let encryption_errs = r.encryption_errs.clone();
                document_create(
                    &auth,
                    r,
                    doc_id,
                    &document_name,
                    [key_errs, encryption_errs].concat(),
                )
            })
        })
}

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
fn resolve_keys_for_grants<'a>(
    auth: &'a RequestAuth,
    user_grants: &'a Vec<UserId>,
    group_grants: &'a Vec<GroupId>,
    policy_grant: Option<&'a PolicyGrant>,
    maybe_user_master_pub_key: Option<&'a UserMasterPublicKey>,
) -> impl Future<Item = (Vec<WithKey<UserOrGroup>>, Vec<DocAccessEditErr>), Error = IronOxideErr> + 'a
{
    internal::user_api::get_user_keys(auth, user_grants)
        .join3(
            internal::group_api::get_group_keys(auth, group_grants),
            policy_grant.map(|p| requests::policy_get::policy_get_request(auth, p)),
        )
        .map(move |(users, groups, maybe_policy_res)| {
            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) = match maybe_policy_res {
                None => (vec![], vec![]),
                Some(res) => process_policy(&res),
            };
            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![]
                }
            };

            (
                { [maybe_self_grant, explicit_grants, applied_policy_grants].concat() },
                [group_errs, user_errs, policy_errs].concat(),
            )
        })
}

/// 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 fn edek_encrypt_document<'a, R1, R2: 'a>(
    auth: &'a RequestAuth,
    recrypt: &'a Recrypt<Sha256, Ed25519, RandomBytes<R1>>,
    user_master_pub_key: &'a PublicKey,
    rng: &Mutex<R2>,
    plaintext: &[u8],
    document_id: Option<DocumentId>,
    grant_to_author: bool,
    user_grants: &'a Vec<UserId>,
    group_grants: &'a Vec<GroupId>,
    policy_grant: Option<&'a PolicyGrant>,
) -> impl Future<Item = DocumentEncryptUnmanagedResult, Error = IronOxideErr> + 'a
where
    R1: rand::CryptoRng + rand::RngCore,
    R2: rand::CryptoRng + rand::RngCore,
{
    let (dek, doc_sym_key) = transform::generate_new_doc_key(recrypt);
    let doc_id = document_id.unwrap_or(DocumentId::goo_id(rng));

    aes::encrypt_future(rng, &plaintext.to_vec(), *doc_sym_key.bytes())
        .join(resolve_keys_for_grants(
            auth,
            user_grants,
            group_grants,
            policy_grant,
            if grant_to_author {
                Some(&user_master_pub_key)
            } else {
                None
            },
        ))
        .and_then(move |(encryption_result, (grants, key_errs))| {
            Ok({
                let encryption_result = recrypt_document(
                    &auth.signing_keys,
                    recrypt,
                    dek,
                    encryption_result,
                    &doc_id,
                    grants,
                )?;
                let access_errs = [&key_errs[..], &encryption_result.encryption_errs[..]].concat();
                DocumentEncryptUnmanagedResult::new(
                    &doc_id,
                    auth.segment_id,
                    encryption_result,
                    access_errs,
                )?
            })
        })
}

impl From<ProtobufError> for IronOxideErr {
    fn from(e: ProtobufError) -> Self {
        internal::IronOxideErr::ProtobufSerdeError(e)
    }
}

/// 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<'a, CR: rand::CryptoRng + rand::RngCore>(
    signing_keys: &'a DeviceSigningKeyPair,
    recrypt: &'a Recrypt<Sha256, Ed25519, RandomBytes<CR>>,
    dek: Plaintext,
    encrypted_doc: AesEncryptedValue,
    doc_id: &DocumentId,
    grants: Vec<WithKey<UserOrGroup>>,
) -> Result<EncryptionResult, 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),
            );

            EncryptionResult {
                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(Debug, Clone, 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()[..].into());
                proto_edek_data
                    .set_ephemeralPublicKey(PublicKey::from(ephemeral_public_key).into());
                proto_edek_data.set_signature(signature.bytes()[..].into());
                proto_edek_data.set_authHash(auth_hash.bytes()[..].into());
                proto_edek_data.set_publicSigningKey(public_signing_key.bytes()[..].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)
    }
}

#[derive(Debug, Clone)]
pub struct EncryptionResult {
    edeks: Vec<EncryptedDek>,
    encrypted_data: AesEncryptedValue,
    encryption_errs: Vec<DocAccessEditErr>,
}

/// Creates an encrypted document entry in the IronCore webservice.
pub fn document_create<'a>(
    auth: &'a RequestAuth,
    encryption_result: EncryptionResult,
    doc_id: DocumentId,
    doc_name: &Option<DocumentName>,
    accum_errs: Vec<DocAccessEditErr>,
) -> impl Future<Item = DocumentEncryptResult, Error = IronOxideErr> + 'a {
    document_create::document_create_request(
        auth,
        doc_id.clone(),
        doc_name.clone(),
        encryption_result.edeks.to_vec(),
    )
    .map(move |resp| {
        (
            doc_id,
            resp,
            encryption_result.encrypted_data.clone(),
            encryption_result.encryption_errs.clone(),
        )
    })
    .map(move |(doc_id, api_resp, encrypted_data, encrypt_errs)| {
        //Generate and prepend the document header to the encrypted document
        let encrypted_payload = [
            generate_document_header(doc_id.clone(), auth.segment_id()),
            encrypted_data.bytes(),
        ]
        .concat();
        DocumentEncryptResult {
            id: api_resp.id,
            name: api_resp.name,
            created: api_resp.created,
            updated: api_resp.updated,
            encrypted_data: encrypted_payload,
            grants: api_resp.shared_with.iter().map(|sw| sw.into()).collect(),
            access_errs: [accum_errs, encrypt_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 fn document_update_bytes<
    'a,
    R1: rand::CryptoRng + rand::RngCore,
    R2: rand::CryptoRng + rand::RngCore,
>(
    auth: &'a RequestAuth,
    recrypt: &'a Recrypt<Sha256, Ed25519, RandomBytes<R1>>,
    device_private_key: &'a PrivateKey,
    rng: &'a Mutex<R2>,
    document_id: &'a DocumentId,
    plaintext: &'a [u8],
) -> impl Future<Item = DocumentEncryptResult, Error = IronOxideErr> + 'a {
    document_get_metadata(auth, &document_id).and_then(move |doc_meta| {
        let (_, sym_key) = transform::decrypt_plaintext(
            &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 =
                        generate_document_header(document_id.clone(), auth.segment_id());
                    encrypted_payload.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,
                        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 it's decrypted bytes.
pub fn decrypt_document<'a, CR: rand::CryptoRng + rand::RngCore>(
    auth: &'a RequestAuth,
    recrypt: &'a Recrypt<Sha256, Ed25519, RandomBytes<CR>>,
    device_private_key: &'a PrivateKey,
    encrypted_doc: &'a [u8],
) -> impl Future<Item = DocumentDecryptResult, Error = IronOxideErr> + 'a {
    parse_document_parts(encrypted_doc)
        .into_future()
        .and_then(move |mut enc_doc_parts| {
            document_get_metadata(auth, &enc_doc_parts.0.document_id).and_then(move |doc_meta| {
                let (_, sym_key) = transform::decrypt_plaintext(
                    &recrypt,
                    doc_meta.0.encrypted_symmetric_key.clone().try_into()?,
                    &device_private_key.recrypt_key(),
                )?;
                aes::decrypt(&mut enc_doc_parts.1, *sym_key.bytes())
                    .map_err(|e| e.into())
                    .map(move |decrypted_doc| DocumentDecryptResult {
                        id: doc_meta.0.id,
                        name: doc_meta.0.name,
                        created: doc_meta.0.created,
                        updated: doc_meta.0.updated,
                        decrypted_data: decrypted_doc.to_vec(),
                    })
            })
        })
}

// Update a documents name. Value can be updated to either a new name with a Some or the name value can be cleared out
// by providing a None.
pub fn update_document_name<'a>(
    auth: &'a RequestAuth,
    id: &'a DocumentId,
    name: Option<&'a DocumentName>,
) -> impl Future<Item = DocumentMetadataResult, Error = IronOxideErr> + 'a {
    requests::document_update::document_update_request(auth, id, name).map(DocumentMetadataResult)
}

pub fn document_grant_access<'a, CR: rand::CryptoRng + rand::RngCore>(
    auth: &'a RequestAuth,
    recrypt: &'a Recrypt<Sha256, Ed25519, RandomBytes<CR>>,
    id: &'a DocumentId,
    user_master_pub_key: &'a PublicKey,
    priv_device_key: &'a PrivateKey,
    user_grants: &'a Vec<UserId>,
    group_grants: &'a Vec<GroupId>,
) -> impl Future<Item = DocumentAccessResult, Error = IronOxideErr> + 'a {
    // get the document metadata
    document_get_metadata(auth, id)
        // and the public keys for the users and groups
        .join3(
            internal::user_api::get_user_keys(auth, user_grants),
            internal::group_api::get_group_keys(auth, group_grants),
        )
        .and_then(move |(doc_meta, users, groups)| {
            Ok({
                // decrypt the dek
                let edek = doc_meta.to_encrypted_symmetric_key()?;
                let dek = recrypt.decrypt(edek, &priv_device_key.clone().into())?;

                let (group_errs, groups_with_key) = process_groups(groups);
                let (user_errs, users_with_key) = process_users(users);
                let users_and_groups =
                    dedupe_grants(&[&users_with_key[..], &groups_with_key[..]].concat());

                // encrypt to all the users and groups
                let (grant_errs, grants) = transform::encrypt_to_with_key(
                    recrypt,
                    &dek,
                    &auth.signing_keys().into(),
                    users_and_groups,
                );

                // squish all accumulated errors into one list
                let other_errs = vec![
                    group_errs,
                    user_errs,
                    grant_errs.into_iter().map(|e| e.into()).collect(),
                ]
                .into_iter()
                .concat();
                (grants, other_errs)
            })
        })
        .and_then(move |(grants, other_errs)| {
            requests::document_access::grant_access_request(auth, id, user_master_pub_key, grants)
                .map(|resp| {
                    requests::document_access::resp::document_access_api_resp_to_result(
                        resp, other_errs,
                    )
                })
        })
}

/// Remove access to a document from the provided list of users and/or groups
pub fn document_revoke_access<'a>(
    auth: &'a RequestAuth,
    id: &'a DocumentId,
    revoke_list: &Vec<UserOrGroup>,
) -> impl Future<Item = DocumentAccessResult, Error = IronOxideErr> + 'a {
    use requests::document_access::{self, resp};

    let revoke_request_list: Vec<_> = revoke_list
        .into_iter()
        .map(|entity| match entity {
            UserOrGroup::User { id } => resp::UserOrGroupAccess::User { id: id.0.clone() },
            UserOrGroup::Group { id } => resp::UserOrGroupAccess::Group { id: id.0.clone() },
        })
        .collect();

    document_access::revoke_access_request(auth, id, revoke_request_list)
        .map(|resp| resp::document_access_api_resp_to_result(resp, vec![]))
}

/// Map the groups that come back from the server into a common value/err structure
fn process_groups(
    (group_errs, groups_with_key): (Vec<GroupId>, Vec<WithKey<GroupId>>),
) -> (Vec<DocAccessEditErr>, Vec<WithKey<UserOrGroup>>) {
    let group_errs = group_errs
        .into_iter()
        .map(|gid| {
            DocAccessEditErr::new(
                UserOrGroup::Group { id: gid },
                "Group could not be found".to_string(),
            )
        })
        .collect();

    let groups_with_key: Vec<WithKey<UserOrGroup>> = groups_with_key
        .into_iter()
        .map(|WithKey { id, public_key }| WithKey {
            id: UserOrGroup::Group { id },
            public_key,
        })
        .collect();

    (group_errs, groups_with_key)
}

/// Map the users that come back from the server into a common value/err structure
fn process_users(
    (user_errs, users_with_key): (Vec<UserId>, Vec<WithKey<UserId>>),
) -> (Vec<DocAccessEditErr>, Vec<WithKey<UserOrGroup>>) {
    let users_with_key: Vec<WithKey<UserOrGroup>> = users_with_key
        .into_iter()
        .map(|WithKey { id, public_key }| WithKey {
            id: UserOrGroup::User { id },
            public_key,
        })
        .collect();

    // convert all user list errors to AccessErr
    let user_errs: Vec<DocAccessEditErr> = user_errs
        .into_iter()
        .map(|uid| {
            DocAccessEditErr::new(
                UserOrGroup::User { id: uid },
                "User could not be found".to_string(),
            )
        })
        .collect();
    (user_errs, users_with_key)
}

/// Extract users/groups + keys from a PolicyResult (Right). Errors from applying the policy are Left.
fn process_policy(
    policy_result: &PolicyResult,
) -> (Vec<DocAccessEditErr>, Vec<WithKey<UserOrGroup>>) {
    let (pubkey_errs, policy_eval_results): (Vec<DocAccessEditErr>, Vec<WithKey<UserOrGroup>>) =
        policy_result
            .users_and_groups
            .iter()
            .partition_map(|uog| match uog {
                UserOrGroupWithKey::User {
                    id,
                    master_public_key: Some(key),
                } => {
                    let user = UserOrGroup::User {
                        // okay since these came back from the service
                        id: UserId::unsafe_from_string(id.clone()),
                    };

                    Either::from(
                        key.clone()
                            .try_into()
                            .map(|k| WithKey::new(user.clone(), k))
                            .map_err(|_e| {
                                DocAccessEditErr::new(
                                    user,
                                    format!("Error parsing user public key {:?}", &key),
                                )
                            }),
                    )
                }
                UserOrGroupWithKey::Group {
                    id,
                    master_public_key: Some(key),
                } => {
                    let group = UserOrGroup::Group {
                        // okay since these came back from the service
                        id: GroupId::unsafe_from_string(id.clone()),
                    };

                    Either::from(
                        key.clone()
                            .try_into()
                            .map(|k| WithKey::new(group.clone(), k))
                            .map_err(|_e| {
                                DocAccessEditErr::new(
                                    group,
                                    format!("Error parsing group public key {:?}", &key),
                                )
                            }),
                    )
                }

                any => {
                    let uog: UserOrGroup = any.clone().into();
                    let err_msg =
                        format!("{} does not have associated public key", &uog).to_string();
                    Either::Left(DocAccessEditErr::new(uog, err_msg))
                }
            });

    (
        [
            pubkey_errs,
            policy_result
                .invalid_users_and_groups
                .iter()
                .map(|uog| {
                    DocAccessEditErr::new(
                        uog.clone(),
                        format!("Policy refers to unknown user or group '{}'", &uog),
                    )
                })
                .collect(),
        ]
        .concat(),
        policy_eval_results,
    )
}

#[cfg(test)]
mod tests {
    use crate::internal::test::contains;
    use base64::decode;
    use galvanic_assert::matchers::{collection::*, *};

    use super::*;
    use std::borrow::Borrow;

    #[test]
    fn document_id_validate_good() {
        let doc_id1 = "an_actual_good_doc_id$";
        let doc_id2 = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
        assert_eq!(
            DocumentId(doc_id1.to_string()),
            DocumentId::try_from(doc_id1).unwrap()
        );
        assert_eq!(
            DocumentId(doc_id2.to_string()),
            DocumentId::try_from(doc_id2).unwrap()
        )
    }

    #[test]
    fn document_id_rejects_invalid() {
        let doc_id1 = DocumentId::try_from("not a good ID!");
        let doc_id2 = DocumentId::try_from("!!");
        let doc_id3 = DocumentId::try_from("01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567891");

        assert_that!(
            &doc_id1.unwrap_err(),
            is_variant!(IronOxideErr::ValidationError)
        );
        assert_that!(
            &doc_id2.unwrap_err(),
            is_variant!(IronOxideErr::ValidationError)
        );
        assert_that!(
            &doc_id3.unwrap_err(),
            is_variant!(IronOxideErr::ValidationError)
        );
    }

    #[test]
    fn doc_id_rejects_empty() {
        let doc_id = DocumentId::try_from("");
        println!("{:?}", doc_id);
        assert_that!(&doc_id, is_variant!(Err));
        assert_that!(
            &doc_id.unwrap_err(),
            is_variant!(IronOxideErr::ValidationError)
        );

        let doc_id = DocumentId::try_from("\n \t  ");
        assert_that!(&doc_id, is_variant!(Err));
        assert_that!(
            &doc_id.unwrap_err(),
            is_variant!(IronOxideErr::ValidationError)
        );
    }

    #[test]
    fn doc_name_rejects_empty() {
        let doc_name = DocumentName::try_from("");
        assert_that!(&doc_name, is_variant!(Err));
        assert_that!(
            &doc_name.unwrap_err(),
            is_variant!(IronOxideErr::ValidationError)
        );

        let doc_name = DocumentName::try_from("\n \t  ");
        assert_that!(&doc_name, is_variant!(Err));
        assert_that!(
            &doc_name.unwrap_err(),
            is_variant!(IronOxideErr::ValidationError)
        );
    }

    #[test]
    fn doc_name_rejects_too_long() {
        let doc_name = DocumentName::try_from("01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567891");

        assert_that!(
            &doc_name.unwrap_err(),
            is_variant!(IronOxideErr::ValidationError)
        )
    }

    #[test]
    fn err_on_bad_doc_header() {
        let doc_with_wrong_version = decode("AQA4eyJfZGlkXyI6ImNjOTIyZTA3NzRhM2MwZWViZTI2NDM2Yzk2ZjdiYzkzIiwiX3NpZF8iOjYwOH1ciL4su5SPZh4eFGuG+5rJ+/I2gDSZAs+2dXw097gU8fBkMWzRo0dDIW0dOxHg/1mio1yMRdDZDA==").unwrap();
        let doc_with_invalid_json = decode("AgA4Z2NfZGlkXyI6ImNjOTIyZTA3NzRhM2MwZWViZTI2NDM2Yzk2ZjdiYzkzIiwiX3NpZF8iOjYwOH1ciL4su5SPZh4eFGuG+5rJ+/I2gDSZAs+2dXw097gU8fBkMWzRo0dDIW0dOxHg/1mio1yMRdDZDA==").unwrap();

        assert_that!(
            &get_id_from_bytes(&doc_with_wrong_version).unwrap_err(),
            has_structure!(
                IronOxideErr::DocumentHeaderParseFailure
                    [contains(&"not a supported version".to_string())]
            )
        );

        assert_that!(
            &get_id_from_bytes(&doc_with_invalid_json).unwrap_err(),
            has_structure!(
                IronOxideErr::DocumentHeaderParseFailure
                    [contains(&"Header value is corrupted".to_string())]
            )
        );
    }

    #[test]
    fn read_good_document_header_test() {
        let enc_doc = decode("AgA4eyJfZGlkXyI6ImNjOTIyZTA3NzRhM2MwZWViZTI2NDM2Yzk2ZjdiYzkzIiwiX3NpZF8iOjYwOH1ciL4su5SPZh4eFGuG+5rJ+/I2gDSZAs+2dXw097gU8fBkMWzRo0dDIW0dOxHg/1mio1yMRdDZDA==").unwrap();

        let doc_id = get_id_from_bytes(&enc_doc).unwrap();

        assert_that!(
            &doc_id,
            has_structure!(DocumentId[eq("cc922e0774a3c0eebe26436c96f7bc93".to_string())])
        );

        let doc_parts = parse_document_parts(&enc_doc).unwrap();

        assert_that!(
            &doc_parts.0,
            has_structure!(DocumentHeader {
                document_id: eq(DocumentId("cc922e0774a3c0eebe26436c96f7bc93".to_string())),
                segment_id: eq(608),
            })
        );

        assert_that!(
            &doc_parts.1.bytes(),
            eq(vec![
                92, 136, 190, 44, 187, 148, 143, 102, 30, 30, 20, 107, 134, 251, 154, 201, 251,
                242, 54, 128, 52, 153, 2, 207, 182, 117, 124, 52, 247, 184, 20, 241, 240, 100, 49,
                108, 209, 163, 71, 67, 33, 109, 29, 59, 17, 224, 255, 89, 162, 163, 92, 140, 69,
                208, 217, 12
            ])
        )
    }

    #[test]
    fn generate_document_header_test() {
        let header = generate_document_header("123abc".try_into().unwrap(), 18usize);

        assert_that!(
            &header,
            eq(vec![
                2, 0, 29, 123, 34, 95, 100, 105, 100, 95, 34, 58, 34, 49, 50, 51, 97, 98, 99, 34,
                44, 34, 95, 115, 105, 100, 95, 34, 58, 49, 56, 125
            ])
        );
    }
    #[test]
    fn process_policy_good() {
        let recrypt = recrypt::api::Recrypt::new();
        let (_, pubk) = recrypt.generate_key_pair().unwrap();

        let policy = PolicyResult {
            users_and_groups: vec![
                UserOrGroupWithKey::User {
                    id: "userid1".to_string(),
                    master_public_key: Some(pubk.into()),
                },
                UserOrGroupWithKey::Group {
                    id: "groupid1".to_string(),
                    master_public_key: Some(pubk.into()),
                },
            ],
            invalid_users_and_groups: vec![],
        };

        let (errs, results) = process_policy(&policy);
        assert_that!(results.len() == 2);
        assert_that!(errs.len() == 0);

        let ex_user = WithKey {
            id: UserOrGroup::User {
                id: UserId::unsafe_from_string("userid1".to_string()),
            },
            public_key: pubk.into(),
        };

        let ex_group = WithKey {
            id: UserOrGroup::Group {
                id: GroupId::unsafe_from_string("groupid1".to_string()),
            },
            public_key: pubk.into(),
        };

        assert_that!(&results, contains_in_any_order(vec![ex_user, ex_group]));
    }

    #[test]
    fn dedupe_grants_removes_dupes() {
        let recrypt = recrypt::api::Recrypt::new();
        let (_, pubk) = recrypt.generate_key_pair().unwrap();

        let u1 = &UserId::unsafe_from_string("user1".into());
        let g1 = &GroupId::unsafe_from_string("group1".into());
        let grants_w_dupes: Vec<WithKey<UserOrGroup>> = vec![
            WithKey::new(u1.into(), pubk.into()),
            WithKey::new(g1.into(), pubk.into()),
            WithKey::new(u1.into(), pubk.into()),
            WithKey::new(g1.into(), pubk.into()),
        ];

        let deduplicated_grants = dedupe_grants(&grants_w_dupes);
        assert_that!(&deduplicated_grants.len(), eq(2))
    }

    #[test]
    fn encode_encrypted_dek_proto() {
        use recrypt::api::Hashable;
        use recrypt::prelude::*;
        let recrypt_api = recrypt::api::Recrypt::new();
        let (_, pubk) = recrypt_api.generate_key_pair().unwrap();
        let signing_keys = recrypt_api.generate_ed25519_key_pair();
        let plaintext = recrypt_api.gen_plaintext();
        let encrypted_value = recrypt_api
            .encrypt(&plaintext, &pubk, &signing_keys)
            .unwrap();
        let user_str = "userid".to_string();

        let edek = EncryptedDek {
            encrypted_dek_data: encrypted_value.clone(),
            grant_to: WithKey {
                public_key: pubk.into(),
                id: UserId::unsafe_from_string(user_str.clone()).borrow().into(),
            },
        };

        let proto_edek: EncryptedDekP = edek.borrow().try_into().unwrap();

        assert_eq!(
            &user_str,
            &proto_edek.get_userOrGroup().get_userId().to_string()
        );
        let (x, y) = pubk.bytes_x_y();
        assert_eq!(
            (x.to_vec(), y.to_vec()),
            (
                proto_edek
                    .get_userOrGroup()
                    .get_masterPublicKey()
                    .get_x()
                    .to_vec(),
                proto_edek
                    .get_userOrGroup()
                    .get_masterPublicKey()
                    .get_y()
                    .to_vec()
            )
        );

        if let recrypt::api::EncryptedValue::EncryptedOnceValue {
            ephemeral_public_key,
            encrypted_message,
            auth_hash,
            public_signing_key,
            signature,
        } = encrypted_value
        {
            assert_eq!(
                (
                    ephemeral_public_key.bytes_x_y().0.to_vec(),
                    ephemeral_public_key.bytes_x_y().1.to_vec()
                ),
                (
                    proto_edek
                        .get_encryptedDekData()
                        .get_ephemeralPublicKey()
                        .get_x()
                        .to_vec(),
                    proto_edek
                        .get_encryptedDekData()
                        .get_ephemeralPublicKey()
                        .get_y()
                        .to_vec()
                )
            );

            assert_eq!(
                encrypted_message.bytes().to_vec(),
                proto_edek
                    .get_encryptedDekData()
                    .get_encryptedBytes()
                    .to_vec()
            );

            assert_eq!(
                auth_hash.bytes().to_vec(),
                proto_edek.get_encryptedDekData().get_authHash().to_vec()
            );

            assert_eq!(
                public_signing_key.to_bytes(),
                proto_edek
                    .get_encryptedDekData()
                    .get_publicSigningKey()
                    .to_vec()
            );

            assert_eq!(
                signature.bytes().to_vec(),
                proto_edek.get_encryptedDekData().get_signature().to_vec()
            );
        } else {
            panic!("Should be EncryptedOnceValue");
        }
    }
    #[test]
    pub fn compare_grants_to_edek_encoded() -> Result<(), IronOxideErr> {
        use crate::proto::transform::UserOrGroup as UserOrGroupP;
        use crate::proto::transform::UserOrGroup_oneof_UserOrGroupId as UserOrGroupIdP;
        use recrypt::prelude::*;

        let recr = recrypt::api::Recrypt::new();
        let signingkeys = DeviceSigningKeyPair::from(recr.generate_ed25519_key_pair());
        let aes_value = AesEncryptedValue::try_from(&[42u8; 32][..])?;
        let uid = UserId::unsafe_from_string("userid".into());
        let gid = GroupId::unsafe_from_string("groupid".into());
        let user: UserOrGroup = uid.borrow().into();
        let group: UserOrGroup = gid.borrow().into();
        let (_, pubk) = recr.generate_key_pair()?;
        let with_keys = vec![
            WithKey::new(user, pubk.clone().into()),
            WithKey::new(group, pubk.into()),
        ];
        let doc_id = DocumentId("docid".into());

        let encryption_result = recrypt_document(
            &signingkeys,
            &recr,
            recr.gen_plaintext(),
            aes_value,
            &doc_id,
            with_keys,
        )?;

        // create an unmanged result, which does the proto serialization
        let doc_encrypt_unmanaged_result =
            DocumentEncryptUnmanagedResult::new(&doc_id, 1, encryption_result, vec![])?;

        // then deserialize and extract the user/groups from the edeks
        let proto_edeks: EncryptedDeksP =
            protobuf::parse_from_bytes(doc_encrypt_unmanaged_result.encrypted_deks())?;
        let result: Result<Vec<UserOrGroup>, IronOxideErr> = proto_edeks
            .edeks
            .as_slice()
            .iter()
            .map(|edek| {
                if let Some(UserOrGroupP {
                    UserOrGroupId: Some(proto_uog),
                    ..
                }) = edek.userOrGroup.as_ref()
                {
                    match proto_uog {
                        UserOrGroupIdP::userId(user_chars) => Ok(UserOrGroup::User {
                            id: user_chars.to_string().try_into()?,
                        }),
                        UserOrGroupIdP::groupId(group_chars) => Ok(UserOrGroup::Group {
                            id: group_chars.to_string().try_into()?,
                        }),
                    }
                } else {
                    Err(IronOxideErr::ProtobufValidationError(
                        format!(
                            "EncryptedDek does not have a valid user or group: {:?}",
                            &edek
                        )
                        .into(),
                    ))
                }
            })
            .collect();

        // show that grants() and the edeks contain the same users/groups
        assert_that!(
            &result?,
            contains_in_any_order(vec![
                UserOrGroup::Group { id: gid.clone() },
                UserOrGroup::User { id: uid.clone() }
            ])
        );

        assert_that!(
            &doc_encrypt_unmanaged_result.grants().to_vec(),
            contains_in_any_order(vec![
                UserOrGroup::Group { id: gid },
                UserOrGroup::User { id: uid }
            ])
        );

        Ok(())
    }
}