dryoc 1.0.0

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

/// The input, output, or operation associated with an [`Error`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorContext {
    /// Associated data supplied to an authenticated operation.
    AssociatedData,
    /// An authenticated-encryption ciphertext.
    AeadCiphertext,
    /// An authenticated-encryption envelope.
    AeadEnvelope,
    /// A message authentication tag.
    AuthenticationTag,
    /// A BLAKE2b key.
    Blake2bKey,
    /// BLAKE2b output.
    Blake2bOutput,
    /// A BLAKE2b operation or state.
    Blake2b,
    /// An authenticated public-key box.
    Box,
    /// Ciphertext input or output.
    Ciphertext,
    /// A Curve25519 public key.
    Curve25519PublicKey,
    /// An in-place data buffer.
    Data,
    /// An Ed25519 public key.
    Ed25519PublicKey,
    /// An ephemeral public key.
    EphemeralPublicKey,
    /// An Argon2 memory-cost parameter.
    MemoryCost,
    /// A password-hashing memory limit.
    MemoryLimit,
    /// Plaintext message input or output.
    Message,
    /// A nonce.
    Nonce,
    /// A password-hashing operations limit.
    OperationsLimit,
    /// A generic output buffer.
    Output,
    /// An Argon2 parallelism parameter.
    Parallelism,
    /// A password.
    Password,
    /// An encoded password hash or its hash field.
    PasswordHash,
    /// A password-hash algorithm field.
    PasswordHashAlgorithm,
    /// A password-hash memory-cost field.
    PasswordHashMemoryCost,
    /// A password-hash parallelism field.
    PasswordHashParallelism,
    /// A password-hash salt field.
    PasswordHashSalt,
    /// A password-hash time-cost field.
    PasswordHashTimeCost,
    /// A password-hash version field.
    PasswordHashVersion,
    /// A protected-memory value or operation.
    ProtectedMemory,
    /// A public key.
    PublicKey,
    /// A sealed public-key box.
    SealedBox,
    /// An Argon2 secret input.
    Secret,
    /// An authenticated secret-key box.
    SecretBox,
    /// A secret key.
    SecretKey,
    /// A signature.
    Signature,
    /// A signed message.
    SignedMessage,
    /// A byte slice.
    Slice,
    /// A derived subkey.
    Subkey,
    /// A secretstream message tag.
    Tag,
    /// An Argon2 time-cost parameter.
    TimeCost,
}

impl Display for ErrorContext {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::AssociatedData => "associated data",
            Self::AeadCiphertext => "AEAD ciphertext",
            Self::AeadEnvelope => "AEAD envelope",
            Self::AuthenticationTag => "authentication tag",
            Self::Blake2bKey => "BLAKE2b key",
            Self::Blake2bOutput => "BLAKE2b output",
            Self::Blake2b => "BLAKE2b",
            Self::Box => "box",
            Self::Ciphertext => "ciphertext",
            Self::Curve25519PublicKey => "Curve25519 public key",
            Self::Data => "data",
            Self::Ed25519PublicKey => "Ed25519 public key",
            Self::EphemeralPublicKey => "ephemeral public key",
            Self::MemoryCost => "memory cost",
            Self::MemoryLimit => "memory limit",
            Self::Message => "message",
            Self::Nonce => "nonce",
            Self::OperationsLimit => "operations limit",
            Self::Output => "output",
            Self::Parallelism => "parallelism",
            Self::Password => "password",
            Self::PasswordHash => "password hash",
            Self::PasswordHashAlgorithm => "password hash algorithm",
            Self::PasswordHashMemoryCost => "password hash memory cost",
            Self::PasswordHashParallelism => "password hash parallelism",
            Self::PasswordHashSalt => "password hash salt",
            Self::PasswordHashTimeCost => "password hash time cost",
            Self::PasswordHashVersion => "password hash version",
            Self::ProtectedMemory => "protected memory",
            Self::PublicKey => "public key",
            Self::SealedBox => "sealed box",
            Self::Secret => "secret",
            Self::SecretBox => "secretbox",
            Self::SecretKey => "secret key",
            Self::Signature => "signature",
            Self::SignedMessage => "signed message",
            Self::Slice => "slice",
            Self::Subkey => "subkey",
            Self::Tag => "tag",
            Self::TimeCost => "time cost",
        })
    }
}

/// A constraint on a byte or buffer length.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LengthConstraint {
    /// The length must equal this value.
    Exact(usize),
    /// The length must be at least this value.
    AtLeast(usize),
    /// The length must be at most this value.
    AtMost(usize),
    /// The length must be within this inclusive range.
    Between { min: usize, max: usize },
}

impl Display for LengthConstraint {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Exact(expected) => write!(f, "exactly {expected}"),
            Self::AtLeast(min) => write!(f, "at least {min}"),
            Self::AtMost(max) => write!(f, "at most {max}"),
            Self::Between { min, max } => write!(f, "between {min} and {max} (inclusive)"),
        }
    }
}

/// A constraint on a numeric parameter.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ValueConstraint {
    /// The value must be within this inclusive range.
    Between { min: u64, max: u64 },
    /// Only bits present in this mask may be set.
    AllowedBits { mask: u64 },
}

impl Display for ValueConstraint {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Between { min, max } => write!(f, "between {min} and {max} (inclusive)"),
            Self::AllowedBits { mask } => {
                write!(f, "a value containing only bits from mask 0x{mask:x}")
            }
        }
    }
}

/// Errors generated by Dryoc.
///
/// Variants are structured so callers can handle failures without parsing the
/// human-readable message. Display text is not part of the API contract.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// Authentication or signature verification failed.
    AuthenticationFailed,

    /// A byte string or buffer had an invalid length.
    InvalidLength {
        /// The input or output whose length was invalid.
        context: ErrorContext,
        /// The supplied length.
        actual: usize,
        /// The required length constraint.
        constraint: LengthConstraint,
    },

    /// A numeric parameter was outside its supported range.
    InvalidValue {
        /// The parameter whose value was invalid.
        context: ErrorContext,
        /// The supplied value.
        actual: u64,
        /// The required value constraint.
        constraint: ValueConstraint,
    },

    /// Encoded data was malformed or unsupported.
    InvalidEncoding {
        /// The encoded field or format that was invalid.
        context: ErrorContext,
    },

    /// A cryptographic key was invalid or unsafe to use.
    InvalidKey {
        /// The key whose value was invalid.
        context: ErrorContext,
    },

    /// Required data was absent.
    MissingData {
        /// The missing field or value.
        context: ErrorContext,
    },

    /// The requested operation was invalid for the current state.
    InvalidState {
        /// The state or operation that was invalid.
        context: ErrorContext,
    },

    /// An arithmetic operation overflowed.
    ArithmeticOverflow {
        /// The value being calculated.
        context: ErrorContext,
    },

    /// Memory required for an operation could not be allocated.
    AllocationFailed {
        /// The input or operation requiring the allocation.
        context: ErrorContext,
    },

    /// An operating-system I/O operation failed.
    Io(std::io::Error),
}

impl Error {
    pub(crate) const fn invalid_encoding(context: ErrorContext) -> Self {
        Self::InvalidEncoding { context }
    }

    pub(crate) const fn invalid_key(context: ErrorContext) -> Self {
        Self::InvalidKey { context }
    }

    pub(crate) const fn missing_data(context: ErrorContext) -> Self {
        Self::MissingData { context }
    }

    pub(crate) const fn invalid_state(context: ErrorContext) -> Self {
        Self::InvalidState { context }
    }

    pub(crate) const fn arithmetic_overflow(context: ErrorContext) -> Self {
        Self::ArithmeticOverflow { context }
    }

    pub(crate) const fn allocation_failed(context: ErrorContext) -> Self {
        Self::AllocationFailed { context }
    }
}

impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        Self::Io(error)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::AuthenticationFailed => f.write_str("authentication failed"),
            Self::InvalidLength {
                context,
                actual,
                constraint,
            } => write!(
                f,
                "invalid {context} length: expected {constraint}, got {actual}"
            ),
            Self::InvalidValue {
                context,
                actual,
                constraint,
            } => write!(
                f,
                "invalid {context} value: expected {constraint}, got {actual}"
            ),
            Self::InvalidEncoding { context } => write!(f, "invalid {context} encoding"),
            Self::InvalidKey { context } => write!(f, "invalid {context}"),
            Self::MissingData { context } => write!(f, "missing {context}"),
            Self::InvalidState { context } => write!(f, "invalid {context} state"),
            Self::ArithmeticOverflow { context } => {
                write!(f, "arithmetic overflow while calculating {context} length")
            }
            Self::AllocationFailed { context } => {
                write!(f, "unable to allocate memory for {context}")
            }
            Self::Io(error) => write!(f, "I/O error: {error}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            _ => None,
        }
    }
}

macro_rules! length_error {
    ($context:expr_2021, $actual:expr_2021,exact $expected:expr_2021) => {
        crate::error::Error::InvalidLength {
            context: $context,
            actual: $actual,
            constraint: crate::error::LengthConstraint::Exact($expected),
        }
    };
    ($context:expr_2021, $actual:expr_2021,min $min:expr_2021) => {
        crate::error::Error::InvalidLength {
            context: $context,
            actual: $actual,
            constraint: crate::error::LengthConstraint::AtLeast($min),
        }
    };
    ($context:expr_2021, $actual:expr_2021,max $max:expr_2021) => {
        crate::error::Error::InvalidLength {
            context: $context,
            actual: $actual,
            constraint: crate::error::LengthConstraint::AtMost($max),
        }
    };
    ($context:expr_2021, $actual:expr_2021,range $min:expr_2021, $max:expr_2021) => {
        crate::error::Error::InvalidLength {
            context: $context,
            actual: $actual,
            constraint: crate::error::LengthConstraint::Between {
                min: $min,
                max: $max,
            },
        }
    };
}

macro_rules! validate_value {
    ($min:expr_2021, $max:expr_2021, $value:expr_2021, $context:expr_2021) => {
        if !($min..=$max).contains(&$value) {
            return Err(crate::error::Error::InvalidValue {
                context: $context,
                actual: $value as u64,
                constraint: crate::error::ValueConstraint::Between {
                    min: $min as u64,
                    max: $max as u64,
                },
            });
        }
    };
}

macro_rules! validate_length {
    (exact $expected:expr_2021, $value:expr_2021, $context:expr_2021) => {
        if $value != $expected {
            return Err(length_error!($context, $value, exact $expected));
        }
    };
    ($min:expr_2021, $max:expr_2021, $value:expr_2021, $context:expr_2021) => {
        if !($min..=$max).contains(&$value) {
            return Err(length_error!($context, $value, range $min, $max));
        }
    };
}

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

    #[test]
    fn contexts_have_clear_human_readable_names() {
        let cases = [
            (ErrorContext::AssociatedData, "associated data"),
            (ErrorContext::AeadCiphertext, "AEAD ciphertext"),
            (ErrorContext::AeadEnvelope, "AEAD envelope"),
            (ErrorContext::AuthenticationTag, "authentication tag"),
            (ErrorContext::Blake2bKey, "BLAKE2b key"),
            (ErrorContext::Blake2bOutput, "BLAKE2b output"),
            (ErrorContext::Blake2b, "BLAKE2b"),
            (ErrorContext::Box, "box"),
            (ErrorContext::Ciphertext, "ciphertext"),
            (ErrorContext::Curve25519PublicKey, "Curve25519 public key"),
            (ErrorContext::Data, "data"),
            (ErrorContext::Ed25519PublicKey, "Ed25519 public key"),
            (ErrorContext::EphemeralPublicKey, "ephemeral public key"),
            (ErrorContext::MemoryCost, "memory cost"),
            (ErrorContext::MemoryLimit, "memory limit"),
            (ErrorContext::Message, "message"),
            (ErrorContext::Nonce, "nonce"),
            (ErrorContext::OperationsLimit, "operations limit"),
            (ErrorContext::Output, "output"),
            (ErrorContext::Parallelism, "parallelism"),
            (ErrorContext::Password, "password"),
            (ErrorContext::PasswordHash, "password hash"),
            (
                ErrorContext::PasswordHashAlgorithm,
                "password hash algorithm",
            ),
            (
                ErrorContext::PasswordHashMemoryCost,
                "password hash memory cost",
            ),
            (
                ErrorContext::PasswordHashParallelism,
                "password hash parallelism",
            ),
            (ErrorContext::PasswordHashSalt, "password hash salt"),
            (
                ErrorContext::PasswordHashTimeCost,
                "password hash time cost",
            ),
            (ErrorContext::PasswordHashVersion, "password hash version"),
            (ErrorContext::ProtectedMemory, "protected memory"),
            (ErrorContext::PublicKey, "public key"),
            (ErrorContext::SealedBox, "sealed box"),
            (ErrorContext::Secret, "secret"),
            (ErrorContext::SecretBox, "secretbox"),
            (ErrorContext::SecretKey, "secret key"),
            (ErrorContext::Signature, "signature"),
            (ErrorContext::SignedMessage, "signed message"),
            (ErrorContext::Slice, "slice"),
            (ErrorContext::Subkey, "subkey"),
            (ErrorContext::Tag, "tag"),
            (ErrorContext::TimeCost, "time cost"),
        ];

        for (context, expected) in cases {
            assert_eq!(context.to_string(), expected);
        }
    }

    #[test]
    fn constraints_describe_their_requirements() {
        let length_cases = [
            (LengthConstraint::Exact(4), "exactly 4"),
            (LengthConstraint::AtLeast(4), "at least 4"),
            (LengthConstraint::AtMost(4), "at most 4"),
            (
                LengthConstraint::Between { min: 2, max: 4 },
                "between 2 and 4 (inclusive)",
            ),
        ];
        for (constraint, expected) in length_cases {
            assert_eq!(constraint.to_string(), expected);
        }

        let value_cases = [
            (
                ValueConstraint::Between { min: 2, max: 4 },
                "between 2 and 4 (inclusive)",
            ),
            (
                ValueConstraint::AllowedBits { mask: 0x3 },
                "a value containing only bits from mask 0x3",
            ),
        ];
        for (constraint, expected) in value_cases {
            assert_eq!(constraint.to_string(), expected);
        }
    }

    #[test]
    fn display_is_human_readable_without_source_locations() {
        let cases = [
            (Error::AuthenticationFailed, "authentication failed"),
            (
                Error::InvalidLength {
                    context: ErrorContext::Nonce,
                    actual: 12,
                    constraint: LengthConstraint::Exact(24),
                },
                "invalid nonce length: expected exactly 24, got 12",
            ),
            (
                Error::InvalidLength {
                    context: ErrorContext::Blake2bOutput,
                    actual: 0,
                    constraint: LengthConstraint::Between { min: 1, max: 64 },
                },
                "invalid BLAKE2b output length: expected between 1 and 64 (inclusive), got 0",
            ),
            (
                Error::InvalidValue {
                    context: ErrorContext::Parallelism,
                    actual: 8,
                    constraint: ValueConstraint::Between { min: 1, max: 4 },
                },
                "invalid parallelism value: expected between 1 and 4 (inclusive), got 8",
            ),
            (
                Error::InvalidValue {
                    context: ErrorContext::Tag,
                    actual: 128,
                    constraint: ValueConstraint::AllowedBits { mask: 3 },
                },
                "invalid tag value: expected a value containing only bits from mask 0x3, got 128",
            ),
            (
                Error::InvalidEncoding {
                    context: ErrorContext::PasswordHashSalt,
                },
                "invalid password hash salt encoding",
            ),
            (
                Error::InvalidKey {
                    context: ErrorContext::Ed25519PublicKey,
                },
                "invalid Ed25519 public key",
            ),
            (
                Error::MissingData {
                    context: ErrorContext::EphemeralPublicKey,
                },
                "missing ephemeral public key",
            ),
            (
                Error::InvalidState {
                    context: ErrorContext::Blake2b,
                },
                "invalid BLAKE2b state",
            ),
            (
                Error::ArithmeticOverflow {
                    context: ErrorContext::Ciphertext,
                },
                "arithmetic overflow while calculating ciphertext length",
            ),
            (
                Error::AllocationFailed {
                    context: ErrorContext::MemoryCost,
                },
                "unable to allocate memory for memory cost",
            ),
        ];

        for (error, expected) in cases {
            assert_eq!(error.to_string(), expected);
        }
    }

    #[test]
    fn debug_is_structured_and_does_not_include_internal_source_locations() {
        let error = Error::InvalidLength {
            context: ErrorContext::Ciphertext,
            actual: 7,
            constraint: LengthConstraint::AtLeast(16),
        };

        assert_eq!(
            format!("{error:?}"),
            "InvalidLength { context: Ciphertext, actual: 7, constraint: AtLeast(16) }"
        );
    }

    #[test]
    fn wrapped_errors_preserve_their_source() {
        use std::error::Error as _;

        let error = Error::from(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "access denied",
        ));
        assert_eq!(error.to_string(), "I/O error: access denied");
        let debug = format!("{error:?}");
        assert!(debug.contains("Io"));
        assert!(debug.contains("PermissionDenied"));
        assert!(debug.contains("access denied"));
        assert!(error.source().is_some());
        assert!(Error::AuthenticationFailed.source().is_none());
    }
}