multi-key 1.0.6

Multikey self-describing cryptographic key data
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
// SPDX-License-Identifier: Apache-2.0
/// Errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Attributes error
    #[error(transparent)]
    Attributes(#[from] AttributesError),
    /// Conversions error
    #[error(transparent)]
    Conversions(#[from] ConversionsError),
    /// Cipher error
    #[error(transparent)]
    Cipher(#[from] CipherError),
    /// Kdf error
    #[error(transparent)]
    Kdf(#[from] KdfError),
    /// Nonce error
    #[error(transparent)]
    Nonce(#[from] NonceError),
    /// Seal error
    #[error(transparent)]
    Seal(#[from] SealError),
    /// Sign error
    #[error(transparent)]
    Sign(#[from] SignError),
    /// Threshold error
    #[error(transparent)]
    Threshold(#[from] ThresholdError),
    /// Verify error
    #[error(transparent)]
    Verify(#[from] VerifyError),
    /// Key split/combine error
    #[error("key split error: {0}")]
    KeySplit(String),

    /// Multibase conversion error
    #[error(transparent)]
    Multibase(#[from] multi_base::Error),
    /// Multicodec decoding error
    #[error(transparent)]
    Multicodec(#[from] multi_codec::Error),
    /// Multiutil error
    #[error(transparent)]
    Multiutil(#[from] multi_util::Error),
    /// Multisig error
    #[error(transparent)]
    Multisig(#[from] multi_sig::Error),
    /// Multitrait error
    #[error(transparent)]
    Multitrait(#[from] multi_trait::Error),
    /// Multihash error
    #[error(transparent)]
    Multihash(#[from] multi_hash::Error),

    /// Utf8 error
    #[error(transparent)]
    Utf8(#[from] std::string::FromUtf8Error),
    /// Duplicate attribute error
    #[error("Duplicate Multikey attribute: {0}")]
    DuplicateAttribute(u8),
    /// Incorrect Multikey sigil
    #[error("Missing Multikey sigil")]
    MissingSigil,
    /// Unsupported key algorithm
    #[error("Unsupported key algorithm: {0}")]
    UnsupportedAlgorithm(String),
}

/// Attributes errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AttributesError {
    /// Error with the key codec
    #[error("Unsupported key codec: {0}")]
    UnsupportedCodec(multi_codec::Codec),
    /// No key data attribute
    #[error("Key data unit missing")]
    MissingKey,
    /// Not a secret key
    #[error("Not a secret key {0}")]
    NotSecretKey(multi_codec::codec::Codec),
    /// Key is encrypted
    #[error("Key is encrypted")]
    EncryptedKey,
    /// Invalid attribute name
    #[error("Invalid attribute name {0}")]
    InvalidAttributeName(String),
    /// Invalid attribute value
    #[error("Invalid attribute value {0}")]
    InvalidAttributeValue(u8),
    /// No threshold
    #[error("Missing threshold")]
    MissingThreshold,
    /// No limit
    #[error("Missing limit")]
    MissingLimit,
    /// No key share identifier
    #[error("Missing share identifier")]
    MissingShareIdentifier,
    /// No threshold data
    #[error("Missing threshold data")]
    MissingThresholdData,
    /// No group public key
    #[error("Missing group public key")]
    MissingGroupPublicKey,
    /// No participant map
    #[error("Missing threshold participants")]
    MissingThresholdParticipants,
    /// CBOR (de)serialization error for a threshold marker attribute
    #[error("Threshold marker CBOR error: {0}")]
    ThresholdMarkerCbor(String),
    /// The threshold marker bundle carries no authenticating signature.
    #[error("Missing threshold marker signature")]
    MissingThresholdMarkerSig,
    /// The threshold marker signature failed verification (tampered marker).
    #[error("Threshold marker signature verification failed")]
    ThresholdMarkerSigInvalid,
}

/// Conversions errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ConversionsError {
    /// Ssh key error
    #[error(transparent)]
    Ssh(#[from] SshErrors),
    /// Public key operation failure
    #[error("Public key error: {0}")]
    PublicKeyFailure(String),
    /// Secret key operation failure
    #[error("Secret key error: {0}")]
    SecretKeyFailure(String),
    /// Error converting from ssh keys
    #[error("Unsupported SSH key algorithm: {0}")]
    UnsupportedAlgorithm(String),
    /// Error with the key codec
    #[error("Unsupported key codec: {0}")]
    UnsupportedCodec(multi_codec::Codec),
}

/// SSH Encoding Errors that cannot be handled by thiserror since they may not use the std feature
/// in the case of wasm32 target.
#[derive(Debug)]
pub enum SshErrors {
    /// Error from [ssh_key::Error]
    Key(ssh_key::Error),
    /// Invalid label from [ssh_encoding::LabelError]
    KeyLabel(ssh_encoding::LabelError),
    /// Unexpected trailing data at end of message from [ssh_encoding::Error]
    Encoding(ssh_encoding::Error),
}

/// Impl Display for EncodingError
impl std::fmt::Display for SshErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SshErrors::Key(err) => write!(f, "{}", err),
            SshErrors::KeyLabel(err) => write!(f, "{}", err),
            SshErrors::Encoding(err) => write!(f, "{}", err),
        }
    }
}

impl std::error::Error for SshErrors {}

impl From<ssh_encoding::Error> for SshErrors {
    fn from(err: ssh_encoding::Error) -> Self {
        SshErrors::Encoding(err)
    }
}

impl From<ssh_key::Error> for SshErrors {
    fn from(err: ssh_key::Error) -> Self {
        SshErrors::Key(err)
    }
}

impl From<ssh_encoding::LabelError> for SshErrors {
    fn from(err: ssh_encoding::LabelError) -> Self {
        SshErrors::KeyLabel(err)
    }
}

/// Cipher errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CipherError {
    /// Error with the cipher codec
    #[error("Unsupported cipher codec: {0}")]
    UnsupportedCodec(multi_codec::Codec),
    /// Missing codec
    #[error("Missing cipher codec")]
    MissingCodec,
    /// Missing nonce error
    #[error("Missing cipher nonce")]
    MissingNonce,
    /// Missing nonce length error
    #[error("Invalid cipher nonce length")]
    InvalidNonceLen,
    /// Invalid nonce error
    #[error("Invalid cipher nonce")]
    InvalidNonce,
    /// Missing key error
    #[error("Missing cipher key")]
    MissingKey,
    /// Missing key length error
    #[error("Missing cipher key length")]
    MissingKeyLen,
    /// Invalid key error
    #[error("Invalid cipher key")]
    InvalidKey,
    /// Encryption error
    #[error("Encryption error: {0}")]
    EncryptionFailed(String),
    /// Decryption error
    #[error("Decryption failed")]
    DecryptionFailed,
}

/// Kdf errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum KdfError {
    /// Bcrypt PBKDF error
    #[error(transparent)]
    Bcrypt(#[from] bcrypt_pbkdf::Error),
    /// Error with the KDF codec
    #[error("Unsupported KDF codec: {0}")]
    UnsupportedCodec(multi_codec::Codec),
    /// Missing codec
    #[error("Missing KDF codec")]
    MissingCodec,
    /// Missing salt error
    #[error("Missing KDF salt")]
    MissingSalt,
    /// Invalid salt length error
    #[error("Invalid KDF salt length")]
    InvalidSaltLen,
    /// Missing rounds error
    #[error("Missing KDF rounds")]
    MissingRounds,
}

/// Nonce errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum NonceError {
    /// Missing sigil
    #[error("Missing Nonce codec")]
    MissingSigil,
    /// Missing bytes
    #[error("Missing Nonce bytes")]
    MissingBytes,
}

/// Seal/Open (encryption) errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SealError {
    /// Not an encryption key
    #[error("Not an encryption key")]
    NotEncryptionKey,
    /// Not a decapsulation (private) key
    #[error("Not a decapsulation key")]
    NotDecapsulationKey,
    /// Not an encapsulation (public) key
    #[error("Not an encapsulation key")]
    NotEncapsulationKey,
    /// Unsupported AEAD codec
    #[error("Unsupported AEAD codec: {0}")]
    UnsupportedAeadCodec(multi_codec::Codec),
    /// Encapsulation failed
    #[error("Encapsulation failed: {0}")]
    EncapsulationFailed(String),
    /// Decapsulation failed
    #[error("Decapsulation failed: {0}")]
    DecapsulationFailed(String),
    /// AEAD seal failed
    #[error("AEAD seal failed: {0}")]
    AeadSealFailed(String),
    /// AEAD open failed
    #[error("AEAD open failed")]
    AeadOpenFailed,
    /// Invalid format
    #[error("Invalid sealed message format: {0}")]
    InvalidFormat(String),
    /// Key derivation failed
    #[error("Key derivation failed: {0}")]
    KeyDerivationFailed(String),
}

/// Sign errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SignError {
    /// Not a signing key
    #[error("Not a signing key")]
    NotSigningKey,
    /// Signing failed
    #[error("Signing failed: {0}")]
    SigningFailed(String),
    /// Missing scheme
    #[error("Missing signature scheme")]
    MissingScheme,
}

/// Threshold errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ThresholdError {
    /// Bls error
    #[error(transparent)]
    Bls(#[from] blsful::BlsError),
    /// Invalid threshold and limit
    #[error("Invalid threshold ({0}) and limit ({1}). Limit must be greater than threshold")]
    InvalidThresholdLimit(usize, usize),
    /// Not a secret key
    #[error("Not a secret key; only secret keys may be split and combined")]
    NotASecretKey,
    /// Is a key share when we expect a key
    #[error("Is a key share when we expect a key")]
    IsAKeyShare,
    /// Not enough shares
    #[error("Not enough shares to combine")]
    NotEnoughShares,
    /// Share combine failed
    #[error("Combining secret key shares failed: {0}")]
    ShareCombineFailed(String),
    /// Threshold metadata encryption/decryption error
    #[error("Threshold metadata error: {0}")]
    MetaEncryption(String),
    /// Missing threshold metadata key for decrypting t/n
    #[error("Missing threshold metadata key")]
    MissingMetaKey,
    /// Threshold disclosure mode mismatch between shares
    #[error("Threshold disclosure mode mismatch: expected {expected}, found {found}")]
    DisclosureMismatch {
        /// Expected disclosure mode code
        expected: u8,
        /// Found disclosure mode code
        found: u8,
    },
    /// Duplicate share identifier in threshold data
    #[error("Duplicate share identifier")]
    DuplicateShare,
}

/// Verify errors created by this library
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum VerifyError {
    /// Missing signature
    #[error("Missing signature")]
    MissingSignature,
    /// Missing message
    #[error("Missing message")]
    MissingMessage,
    /// Bad signature
    #[error("Bad signature: {0}")]
    BadSignature(String),
}

impl Error {
    /// Get the error kind as a string
    pub fn kind(&self) -> &str {
        match self {
            Self::Attributes(_) => "Attributes",
            Self::Conversions(_) => "Conversions",
            Self::Cipher(_) => "Cipher",
            Self::Kdf(_) => "Kdf",
            Self::Nonce(_) => "Nonce",
            Self::Seal(_) => "Seal",
            Self::Sign(_) => "Sign",
            Self::Threshold(_) => "Threshold",
            Self::Verify(_) => "Verify",
            Self::KeySplit(_) => "KeySplit",
            Self::Multibase(_) => "Multibase",
            Self::Multicodec(_) => "Multicodec",
            Self::Multiutil(_) => "Multiutil",
            Self::Multisig(_) => "Multisig",
            Self::Multitrait(_) => "Multitrait",
            Self::Multihash(_) => "Multihash",
            Self::Utf8(_) => "Utf8",
            Self::DuplicateAttribute(_) => "DuplicateAttribute",
            Self::MissingSigil => "MissingSigil",
            Self::UnsupportedAlgorithm(_) => "UnsupportedAlgorithm",
        }
    }
}

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

    #[test]
    fn test_error_kind() {
        let err = Error::MissingSigil;
        assert_eq!(err.kind(), "MissingSigil");
    }

    #[test]
    fn test_error_display() {
        let err = Error::MissingSigil;
        assert!(!err.to_string().is_empty());
    }

    #[test]
    fn test_error_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}

        assert_send::<Error>();
        assert_sync::<Error>();
    }
}