libkeycard 0.1.12

A digital certificate library for the Mensago platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use crate::base::LKCError;
use chrono::{prelude::*, Duration, NaiveDateTime};
use hex;
use lazy_static::lazy_static;
use rand::prelude::*;
use regex::Regex;
use std::fmt;

lazy_static! {
    #[doc(hidden)]
    pub static ref RANDOMID_PATTERN: regex::Regex =
        Regex::new(r"^[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}$")
        .unwrap();

    #[doc(hidden)]
    pub static ref USERID_PATTERN: regex::Regex =
        Regex::new(r"^([\p{L}\p{M}\p{N}\-_]|\.[^.])+$")
        .unwrap();

    #[doc(hidden)]
    pub static ref CONTROL_CHARS_PATTERN: regex::Regex =
        Regex::new(r#"\p{C}"#)
        .unwrap();

    #[doc(hidden)]
    pub static ref DOMAIN_PATTERN: regex::Regex =
        Regex::new(r"^([a-zA-Z0-9\-]+)(\.[a-zA-Z0-9\-]+)*$")
        .unwrap();

}

/// IDType identifies the type of RandomID used
#[derive(Debug, PartialEq, PartialOrd, Clone, Copy)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IDType {
    WorkspaceID,
    UserID,
}

/// The RandomID class is similar to v4 UUIDs. To obtain the maximum amount of entropy, all bits
/// are random and no version information is stored in them. The only null value for the RandomID
/// is all zeroes. Lastly, the only permissible format for the string version of the RandomID
/// has all letters in lowercase and dashes are placed in the same places as for UUIDs.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RandomID {
    data: String,
}

impl RandomID {
    /// Creates a new populated RandomID
    pub fn generate() -> RandomID {
        let mut rdata: [u8; 16] = [0; 16];
        rand::thread_rng().fill_bytes(&mut rdata[..]);
        let out = RandomID {
            data: format!(
                "{}-{}-{}-{}-{}",
                hex::encode(&rdata[0..4]),
                hex::encode(&rdata[4..6]),
                hex::encode(&rdata[6..8]),
                hex::encode(&rdata[8..10]),
                hex::encode(&rdata[10..])
            ),
        };

        out
    }

    /// Creates a RandomID from an existing string and ensures that formatting is correct.
    pub fn from(data: &str) -> Option<RandomID> {
        if !RANDOMID_PATTERN.is_match(data) {
            return None;
        }

        let mut out = RandomID {
            data: String::from("00000000-0000-0000-0000-000000000000"),
        };
        out.data = data.to_lowercase();

        Some(out)
    }

    /// Creates a RandomID from a Mensago UserID instance if compatible. All RandomIDs are valid
    /// UserIDs, but not the other way around.
    pub fn from_userid(uid: &UserID) -> Option<RandomID> {
        match uid.get_type() {
            IDType::UserID => None,
            IDType::WorkspaceID => Some(RandomID {
                data: uid.to_string(),
            }),
        }
    }

    /// Returns the RandomID as a string
    pub fn as_string(&self) -> &str {
        &self.data
    }
}

impl fmt::Display for RandomID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.data)
    }
}

/// A basic data type for housing Mensago user IDs. User IDs on the Mensago platform must be no
/// more than 64 ASCII characters. These characters may be from the following: lowercase a-z,
/// numbers, a dash, or an underscore. Periods may also be used so long as they are not consecutive.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UserID {
    data: String,
    idtype: IDType,
}

impl UserID {
    /// Creates a UserID from an existing string. If it contains illegal characters, it will
    /// return None. All capital letters will have their case squashed for compliance.
    pub fn from(data: &str) -> Option<UserID> {
        if data.len() > 64 || data.len() == 0 {
            return None;
        }

        if !USERID_PATTERN.is_match(data) {
            return None;
        }

        let mut out = UserID {
            data: String::from(data),
            idtype: IDType::UserID,
        };
        out.data = data.to_lowercase();

        out.idtype = if RANDOMID_PATTERN.is_match(&out.data) {
            IDType::WorkspaceID
        } else {
            IDType::UserID
        };

        Some(out)
    }

    /// Creates a UserID from a workspace ID
    pub fn from_wid(wid: &RandomID) -> UserID {
        UserID {
            data: String::from(wid.as_string()),
            idtype: IDType::WorkspaceID,
        }
    }

    /// Returns the UserID as a string
    pub fn as_string(&self) -> &str {
        &self.data
    }

    /// Returns the type of ID (Workspace ID vs Mensago ID)
    pub fn get_type(&self) -> IDType {
        self.idtype
    }
}

impl fmt::Display for UserID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.data)
    }
}

/// A basic data type for housing Internet domains.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Domain {
    data: String,
}

impl Domain {
    /// Creates a Domain from an existing string. If it contains illegal characters, it will
    /// return None. All capital letters will have their case squashed. This type exists to ensure
    /// that valid domains are used across the library
    pub fn from(data: &str) -> Option<Domain> {
        if !DOMAIN_PATTERN.is_match(data) {
            return None;
        }

        let mut out = Domain {
            data: String::from(data),
        };
        out.data = data.to_lowercase();

        Some(out)
    }

    /// Returns the Domain as a string
    pub fn as_string(&self) -> &str {
        &self.data
    }

    /// Returns the parent domain unless doing so would return a top-level domain, i.e. '.com', in
    /// which case it returns None.
    pub fn parent(&self) -> Option<Domain> {
        let domparts: Vec<&str> = self.data.split(".").collect();
        if domparts.len() < 3 {
            return None;
        }

        return Some(Domain {
            data: String::from(&domparts[1..].join(".")),
        });
    }

    /// Removes a level of subdomains from the item, working much like `parent()` except that the
    /// current object is modified. LKCError::ErrOutOfRange is returned if the call would
    /// result in the Domain object housing just a top-level domain, such as `com`.
    pub fn pop(&mut self) -> Result<(), LKCError> {
        let domparts: Vec<&str> = self.data.split(".").collect();
        if domparts.len() < 3 {
            return Err(LKCError::ErrOutOfRange);
        }

        self.data = String::from(&domparts[1..].join("."));
        Ok(())
    }

    /// Adds a subdomain to the object
    pub fn push(&mut self, subdom: &str) -> Result<(), LKCError> {
        let mut domparts: Vec<&str> = self.data.split(".").collect();
        let subdomparts: Vec<&str> = subdom.split(".").collect();

        for part in subdomparts.iter().rev() {
            domparts.insert(0, part);
        }

        self.data = String::from(&domparts.join("."));

        Ok(())
    }
}

impl fmt::Display for Domain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.data)
    }
}

/// A basic data type representing a full Mensago address. It is used to ensure passing around
/// valid data within the library.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MAddress {
    pub uid: UserID,
    pub domain: Domain,
    address: String,
}

impl MAddress {
    /// Creates a new MAddress from a string. If the string does not contain a valid Mensago
    /// address, None will be returned.
    pub fn from(data: &str) -> Option<MAddress> {
        let parts = data.split("/").collect::<Vec<&str>>();

        if parts.len() != 2 {
            return None;
        }

        let out = MAddress {
            uid: UserID::from(parts[0])?,
            domain: Domain::from(parts[1])?,
            address: format!("{}/{}", parts[0], parts[1]),
        };

        Some(out)
    }

    /// Creates an MAddress from an WAddress instance
    pub fn from_waddress(waddr: &WAddress) -> MAddress {
        let uid = UserID::from_wid(&waddr.wid);
        MAddress {
            address: format!("{}/{}", uid, waddr.domain),
            uid,
            domain: waddr.domain.clone(),
        }
    }

    /// Creates an MAddress from its components
    pub fn from_parts(uid: &UserID, domain: &Domain) -> MAddress {
        MAddress {
            uid: uid.clone(),
            domain: domain.clone(),
            address: format!("{}/{}", uid, domain),
        }
    }

    /// Returns the MAddress as a string
    pub fn as_string(&self) -> String {
        format!("{}/{}", self.uid, self.domain)
    }

    /// Returns the UserID portion of the address
    pub fn get_uid(&self) -> &UserID {
        &self.uid
    }

    /// Returns the Domain portion of the address
    pub fn get_domain(&self) -> &Domain {
        &self.domain
    }
}

impl fmt::Display for MAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.uid, self.domain)
    }
}

/// A basic data type representing a full Mensago address. It is used to ensure passing around
/// valid data within the library.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WAddress {
    wid: RandomID,
    domain: Domain,

    // We keep this extra copy around because converting the item to a full string is a very
    // common operation
    address: String,
}

impl WAddress {
    /// Creates a new WAddress from a string. If the string does not contain a valid workspace
    /// address, None will be returned.
    pub fn from(data: &str) -> Option<WAddress> {
        let parts = data.split("/").collect::<Vec<&str>>();

        if parts.len() != 2 {
            return None;
        }

        let out = WAddress {
            wid: RandomID::from(parts[0])?,
            domain: Domain::from(parts[1])?,
            address: format!("{}/{}", parts[0], parts[1]),
        };

        Some(out)
    }

    /// Creates a WAddress from an MAddress instance if compatible. This is because all workspace
    /// addresses are valid Mensago addresses, but not the other way around.
    pub fn from_maddress(maddr: &MAddress) -> Option<WAddress> {
        match maddr.uid.get_type() {
            IDType::UserID => None,
            IDType::WorkspaceID => Some(WAddress {
                wid: RandomID::from_userid(&maddr.uid).unwrap(),
                domain: maddr.domain.clone(),
                address: format!("{}/{}", maddr.uid, maddr.domain),
            }),
        }
    }

    /// Creates a WAddress from its components
    pub fn from_parts(wid: &RandomID, domain: &Domain) -> WAddress {
        WAddress {
            wid: wid.clone(),
            domain: domain.clone(),
            address: format!("{}/{}", wid, domain),
        }
    }

    /// Returns the WAddress as a string
    pub fn as_string(&self) -> String {
        format!("{}/{}", self.wid, self.domain)
    }

    /// Returns the RandomID portion of the address
    pub fn get_wid(&self) -> &RandomID {
        &self.wid
    }

    /// Returns the Domain portion of the address
    pub fn get_domain(&self) -> &Domain {
        &self.domain
    }
}

impl fmt::Display for WAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.wid, self.domain)
    }
}

/// A basic data type representing an Argon2id password hash. It is used to ensure passing around
/// valid data within the library. This might someday be genericized, but for now it's fine.
#[derive(Debug, PartialEq, PartialOrd, Clone)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ArgonHash {
    hash: String,
    hashtype: String,
}

impl ArgonHash {
    /// Creates a new ArgonHash from the provided password
    pub fn from(password: &str) -> ArgonHash {
        ArgonHash {
            hash: eznacl::hash_password(password, &eznacl::HashStrength::Basic),
            hashtype: String::from("argon2id"),
        }
    }

    /// Creates an ArgonHash object from a verified string
    pub fn from_hashstr(passhash: &str) -> ArgonHash {
        ArgonHash {
            hash: String::from(passhash),
            hashtype: String::from("argon2id"),
        }
    }

    /// Returns the object's hash string
    pub fn get_hash(&self) -> &str {
        &self.hash
    }

    /// Returns the object's hash type
    pub fn get_hashtype(&self) -> &str {
        &self.hashtype
    }
}

impl fmt::Display for ArgonHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.hash)
    }
}

/// A basic data type for timestamps as used on Mensago. The type is timezone-agnostic as the
/// platform operates on UTC time only. It can be used to just store dates or dates with times
#[derive(Debug, PartialEq, PartialOrd, Clone)]
#[cfg_attr(feature = "use_serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Timestamp {
    datetime: NaiveDateTime,
    data: String,
}

impl Timestamp {
    /// Creates a new Timestamp object using the current date and time
    pub fn new() -> Timestamp {
        let utc: DateTime<Utc> = Utc::now();
        let formatted = utc.format("%Y%m%dT%H%M%SZ");

        Timestamp::from_str(formatted.to_string().as_str()).unwrap()
    }

    /// Creates a new Timestamp from a correctly-formatted string, which is YYYYMMDDTHHMMSSZ.
    pub fn from_str(data: &str) -> Option<Timestamp> {
        let datetime = match chrono::NaiveDateTime::parse_from_str(data, "%Y%m%dT%H%M%SZ") {
            Ok(v) => v,
            Err(_) => return None,
        };

        Some(Timestamp {
            datetime,
            data: String::from(data.to_uppercase()),
        })
    }

    /// Creates a timestamp object from just a date, which internally is stored as midnight on
    /// that date.
    pub fn from_datestr(date: &str) -> Option<Self> {
        let datetime = format!("{}T000000Z", date);
        Timestamp::from_str(&datetime)
    }

    /// Returns the timestamp offset by the specified number of days
    pub fn with_offset(&self, days: i64) -> Option<Timestamp> {
        let offset_date = self.datetime.checked_add_signed(Duration::days(days))?;
        Some(Timestamp {
            datetime: offset_date,
            data: offset_date.format("%Y%m%dT%H%M%SZ").to_string(),
        })
    }

    /// Returns the Timestamp as a string with only the date in the format YYYYMMDD.
    pub fn as_datestr(&self) -> &str {
        &self.data[0..8]
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.data)
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn test_randomid() {
        let testid = RandomID::generate();

        let strid = RandomID::from(testid.as_string());
        assert_ne!(strid, None);
    }

    #[test]
    fn test_userid() {
        assert_ne!(UserID::from("valid_e-mail.123"), None);

        match UserID::from("11111111-1111-1111-1111-111111111111") {
            Some(v) => {
                assert!(v.get_type() == IDType::WorkspaceID)
            }
            None => {
                panic!("test_userid failed workspace ID assignment")
            }
        }

        match UserID::from("Valid.but.needs_case-squashed") {
            Some(v) => {
                assert_eq!(v.as_string(), "valid.but.needs_case-squashed")
            }
            None => {
                panic!("test_userid failed case-squashing check")
            }
        }

        assert_eq!(UserID::from("invalid..number1"), None);
        assert_eq!(UserID::from("invalid#2"), None);
    }

    #[test]
    fn test_domain() {
        // Test the basics

        assert!(Domain::from("foo-bar").is_some());
        assert!(Domain::from("foo-bar.baz.com").is_some());

        match Domain::from("FOO.bar.com") {
            Some(v) => {
                assert_eq!(v.as_string(), "foo.bar.com")
            }
            None => {
                panic!("test_domain failed case-squashing check")
            }
        }

        assert!(Domain::from("a bad-id.com").is_none());
        assert!(Domain::from("also_bad.org").is_none());

        // parent() testing

        assert!(Domain::from("foo-bar.baz.com").unwrap().parent().is_some());
        assert!(Domain::from("baz.com").unwrap().parent().is_none());
        assert_eq!(
            Domain::from("foo-bar.baz.com")
                .unwrap()
                .parent()
                .unwrap()
                .to_string(),
            "baz.com"
        );

        // push() and pop()

        let mut d = Domain::from("baz.com").unwrap();
        assert!(d.push("foo.bar").is_ok());
        assert_eq!(d.to_string(), "foo.bar.baz.com");
        assert!(d.pop().is_ok());
        assert_eq!(d.to_string(), "bar.baz.com");
        assert!(d.pop().is_ok());
        assert_eq!(d.to_string(), "baz.com");
        assert!(d.pop().is_err());
    }

    #[test]
    fn test_maddress() {
        assert_ne!(MAddress::from("cats4life/example.com"), None);
        assert_ne!(
            MAddress::from("5a56260b-aa5c-4013-9217-a78f094432c3/example.com"),
            None
        );

        let waddr = WAddress::from("5a56260b-aa5c-4013-9217-a78f094432c3/example.com").unwrap();
        assert_eq!(
            MAddress::from_waddress(&waddr).to_string(),
            "5a56260b-aa5c-4013-9217-a78f094432c3/example.com"
        );

        assert_eq!(MAddress::from("has spaces/example.com"), None);
        assert_eq!(MAddress::from(r#"has_a_"/example.com"#), None);
        assert_eq!(MAddress::from("\\not_allowed/example.com"), None);
        assert_eq!(MAddress::from("/example.com"), None);
        assert_eq!(
            MAddress::from("5a56260b-aa5c-4013-9217-a78f094432c3/example.com/example.com"),
            None
        );
        assert_eq!(MAddress::from("5a56260b-aa5c-4013-9217-a78f094432c3"), None);
    }

    #[test]
    fn test_waddress() {
        assert_ne!(
            WAddress::from("5a56260b-aa5c-4013-9217-a78f094432c3/example.com"),
            None
        );
        assert_eq!(WAddress::from("cats4life/example.com"), None);
        assert_eq!(
            WAddress::from_maddress(&MAddress::from("cats4life/example.com").unwrap()),
            None
        );
        assert!(WAddress::from_maddress(
            &MAddress::from("5a56260b-aa5c-4013-9217-a78f094432c3/example.com").unwrap()
        )
        .is_some());
    }

    #[test]
    fn test_timestamp() {
        assert_eq!(Timestamp::from_str("foobar"), None);

        let ts = Timestamp::from_str("20220501T131011Z").unwrap();
        assert_eq!(&ts.to_string(), "20220501T131011Z");
        assert_eq!(ts.as_datestr(), "20220501");
        assert_eq!(&ts.with_offset(1).unwrap().to_string(), "20220502T131011Z");

        let ds = Timestamp::from_datestr("20220502").unwrap();
        assert_eq!(ds.as_datestr(), "20220502");
        assert_eq!(&ds.to_string(), "20220502T000000Z");
    }
}