publet-core 0.2.0

Objects, canonical CBOR, content identifiers, and signatures.
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
//! Detached signatures (Section 4.4).
//!
//! A signature is its own object referencing a target by identifier, so
//! signatures accrue to an object without changing its identifier (R3).
//! The signed message is domain-separated:
//!
//! ```text
//! "pub/v1/sig" || 0x00 || purpose || 0x00 || canonical-bytes-of-target
//! ```
//!
//! The separator matters more than it looks. Without it, a signature made
//! for one purpose could be presented as a signature for another, and an
//! endorsement could be replayed as a retraction. Section 4.4 therefore
//! requires rejecting a signature whose purpose does not match the context
//! it is being evaluated in, and [`verify`] takes the expected purpose as
//! an argument so that omitting the check is not possible.

use ed25519_dalek::{Signature, Signer as _, SigningKey, Verifier as _, VerifyingKey};
use thiserror::Error;

/// The domain separation prefix.
const DOMAIN: &[u8] = b"pub/v1/sig";

/// A signature algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SigAlg {
    /// Ed25519, required by Section 4.4.
    Ed25519,
}

impl SigAlg {
    /// The in-band identifier.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::SigAlg;
    ///
    /// assert_eq!(SigAlg::Ed25519.id(), "ed25519");
    /// ```
    #[must_use]
    pub fn id(self) -> &'static str {
        match self {
            Self::Ed25519 => "ed25519",
        }
    }

    /// Resolve an in-band identifier.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::SigAlg;
    ///
    /// assert_eq!(SigAlg::from_id("ed25519"), Some(SigAlg::Ed25519));
    /// assert_eq!(SigAlg::from_id("rsa"), None);
    /// ```
    #[must_use]
    pub fn from_id(id: &str) -> Option<Self> {
        match id {
            "ed25519" => Some(Self::Ed25519),
            _ => None,
        }
    }
}

/// Reasons a signature does not verify.
#[derive(Debug, Error, PartialEq, Eq, Clone)]
#[non_exhaustive]
pub enum SigError {
    /// The algorithm identifier is not implemented.
    #[error("unknown signature algorithm: {0}")]
    UnknownAlgorithm(String),

    /// The public key was not the right length or shape.
    #[error("malformed public key")]
    MalformedKey,

    /// The secret key was not the right length or shape.
    #[error("malformed secret key")]
    MalformedSecretKey,

    /// The signature was not the right length or shape.
    #[error("malformed signature")]
    MalformedSignature,

    /// The signature did not verify over the constructed message.
    #[error("signature does not verify")]
    BadSignature,

    /// The signature was made for a different purpose.
    #[error("purpose mismatch: signature is for {found:?}, context requires {expected:?}")]
    PurposeMismatch {
        /// The purpose recorded in the signature object.
        found: String,
        /// The purpose the evaluating context requires.
        expected: String,
    },

    /// A purpose contained the separator byte.
    #[error("purpose must not contain a NUL byte")]
    PurposeContainsNul,
}

/// Construct the message a signature covers.
///
/// # Errors
///
/// Returns [`SigError::PurposeContainsNul`] if `purpose` contains `0x00`,
/// which would make the separated encoding ambiguous.
///
/// # Example
///
/// ```
/// use publet_core::{SigError, signing_message};
///
/// let message = signing_message("authored", b"target bytes")?;
/// assert_eq!(message, b"pub/v1/sig\0authored\0target bytes");
///
/// // A purpose may not contain the separator.
/// assert_eq!(signing_message("a\0b", b""), Err(SigError::PurposeContainsNul));
/// # Ok::<(), SigError>(())
/// ```
pub fn signing_message(purpose: &str, target_bytes: &[u8]) -> Result<Vec<u8>, SigError> {
    if purpose.as_bytes().contains(&0) {
        return Err(SigError::PurposeContainsNul);
    }
    let mut message = Vec::with_capacity(DOMAIN.len() + purpose.len() + target_bytes.len() + 2);
    message.extend_from_slice(DOMAIN);
    message.push(0);
    message.extend_from_slice(purpose.as_bytes());
    message.push(0);
    message.extend_from_slice(target_bytes);
    Ok(message)
}

/// Verify a detached signature over `target_bytes` for `expected_purpose`.
///
/// `found_purpose` is the purpose recorded in the signature object;
/// `expected_purpose` is what the calling context requires. They must
/// match, and the mismatch is reported before any cryptography is done.
///
/// # Errors
///
/// Fails only if one of these checks fails, in this order:
///
/// - [`SigError::PurposeMismatch`] if `found_purpose` is not
///   `expected_purpose`. No cryptography is done.
/// - [`SigError::PurposeContainsNul`] if the purpose contains `0x00`.
/// - [`SigError::MalformedKey`] if `public_key` is not 32 bytes, or is not
///   the encoding of a curve point.
/// - [`SigError::MalformedSignature`] if `signature` is not 64 bytes.
/// - [`SigError::BadSignature`] if the signature does not verify over
///   [`signing_message`]`(found_purpose, target_bytes)`.
///
/// # Example
///
/// ```
/// use publet_core::{SigAlg, SigError, sign, verify, verifying_key};
///
/// // A real seed comes from a random source; this crate needs no RNG.
/// let seed = [7u8; 32];
/// let public = verifying_key(SigAlg::Ed25519, &seed)?;
/// let signature = sign(SigAlg::Ed25519, &seed, "authored", b"object")?;
///
/// verify(SigAlg::Ed25519, &public, &signature, "authored", "authored", b"object")?;
///
/// // The purpose the signature was made for must be the one asked about...
/// assert!(matches!(
///     verify(SigAlg::Ed25519, &public, &signature, "authored", "retracted", b"object"),
///     Err(SigError::PurposeMismatch { .. }),
/// ));
/// // ...and the bytes must be the ones signed.
/// assert_eq!(
///     verify(SigAlg::Ed25519, &public, &signature, "authored", "authored", b"altered"),
///     Err(SigError::BadSignature),
/// );
/// # Ok::<(), SigError>(())
/// ```
pub fn verify(
    alg: SigAlg,
    public_key: &[u8],
    signature: &[u8],
    found_purpose: &str,
    expected_purpose: &str,
    target_bytes: &[u8],
) -> Result<(), SigError> {
    if found_purpose != expected_purpose {
        return Err(SigError::PurposeMismatch {
            found: found_purpose.to_owned(),
            expected: expected_purpose.to_owned(),
        });
    }
    let message = signing_message(found_purpose, target_bytes)?;
    match alg {
        SigAlg::Ed25519 => {
            let key_bytes: [u8; 32] = public_key.try_into().map_err(|_| SigError::MalformedKey)?;
            let key = VerifyingKey::from_bytes(&key_bytes).map_err(|_| SigError::MalformedKey)?;
            let sig_bytes: [u8; 64] = signature
                .try_into()
                .map_err(|_| SigError::MalformedSignature)?;
            let sig = Signature::from_bytes(&sig_bytes);
            key.verify(&message, &sig)
                .map_err(|_| SigError::BadSignature)
        }
    }
}

/// Produce a detached signature over `target_bytes` for `purpose`.
///
/// Deterministic (RFC 8032): the same key, purpose, and target always
/// produce the same signature, so this needs no randomness at call time --
/// unlike generating the key itself, which does.
///
/// # Errors
///
/// Returns [`SigError`] if `secret_key` is not a 32-byte Ed25519 seed, or
/// if `purpose` contains the separator byte.
///
/// # Example
///
/// ```
/// use publet_core::{SigAlg, sign};
///
/// // A real seed comes from a random source; this crate needs no RNG.
/// let seed = [7u8; 32];
/// let signature = sign(SigAlg::Ed25519, &seed, "authored", b"object")?;
/// assert_eq!(signature.len(), 64);
///
/// // Deterministic: the same key, purpose and bytes give the same signature.
/// assert_eq!(sign(SigAlg::Ed25519, &seed, "authored", b"object")?, signature);
/// # Ok::<(), publet_core::SigError>(())
/// ```
pub fn sign(
    alg: SigAlg,
    secret_key: &[u8],
    purpose: &str,
    target_bytes: &[u8],
) -> Result<Vec<u8>, SigError> {
    let message = signing_message(purpose, target_bytes)?;
    match alg {
        SigAlg::Ed25519 => {
            let key_bytes: [u8; 32] = secret_key
                .try_into()
                .map_err(|_| SigError::MalformedSecretKey)?;
            let signing_key = SigningKey::from_bytes(&key_bytes);
            Ok(signing_key.sign(&message).to_bytes().to_vec())
        }
    }
}

/// Derive the public key matching a secret key.
///
/// Lets a caller holding a freshly generated seed (bytes only -- generating
/// them is not this crate's concern, since that needs an RNG source, not
/// cryptography) obtain the public half without reaching past this module
/// into `ed25519_dalek` directly.
///
/// # Errors
///
/// Returns [`SigError::MalformedSecretKey`] if `secret_key` is not a 32-byte
/// Ed25519 seed.
///
/// # Example
///
/// ```
/// use publet_core::{SigAlg, SigError, verifying_key};
///
/// let public = verifying_key(SigAlg::Ed25519, &[7u8; 32])?;
/// assert_eq!(public.len(), 32);
///
/// // A seed must be exactly 32 bytes.
/// assert_eq!(verifying_key(SigAlg::Ed25519, &[7u8; 31]), Err(SigError::MalformedSecretKey));
/// # Ok::<(), SigError>(())
/// ```
pub fn verifying_key(alg: SigAlg, secret_key: &[u8]) -> Result<Vec<u8>, SigError> {
    match alg {
        SigAlg::Ed25519 => {
            let key_bytes: [u8; 32] = secret_key
                .try_into()
                .map_err(|_| SigError::MalformedSecretKey)?;
            let signing_key = SigningKey::from_bytes(&key_bytes);
            Ok(signing_key.verifying_key().as_bytes().to_vec())
        }
    }
}

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

    fn key() -> SigningKey {
        // A fixed seed: these tests assert on behaviour, not on secrecy.
        SigningKey::from_bytes(&[7u8; 32])
    }

    // covers: signing_message, verify
    #[test]
    fn verifies_a_correct_signature() {
        let sk = key();
        let target = b"canonical bytes";
        let msg = signing_message("endorse", target).unwrap();
        let sig = sk.sign(&msg);
        assert!(
            verify(
                SigAlg::Ed25519,
                sk.verifying_key().as_bytes(),
                &sig.to_bytes(),
                "endorse",
                "endorse",
                target,
            )
            .is_ok()
        );
    }

    // covers: signing_message, verify
    #[test]
    fn rejects_a_signature_replayed_under_another_purpose() {
        let sk = key();
        let target = b"canonical bytes";
        let msg = signing_message("endorse", target).unwrap();
        let sig = sk.sign(&msg);

        // Presented honestly but in the wrong context.
        assert!(matches!(
            verify(
                SigAlg::Ed25519,
                sk.verifying_key().as_bytes(),
                &sig.to_bytes(),
                "endorse",
                "retract",
                target,
            ),
            Err(SigError::PurposeMismatch { .. })
        ));

        // Relabelled to match the context: the domain separation defeats it.
        assert!(matches!(
            verify(
                SigAlg::Ed25519,
                sk.verifying_key().as_bytes(),
                &sig.to_bytes(),
                "retract",
                "retract",
                target,
            ),
            Err(SigError::BadSignature)
        ));
    }

    // covers: signing_message, verify
    #[test]
    fn rejects_a_signature_over_different_bytes() {
        let sk = key();
        let msg = signing_message("endorse", b"original").unwrap();
        let sig = sk.sign(&msg);
        assert_eq!(
            verify(
                SigAlg::Ed25519,
                sk.verifying_key().as_bytes(),
                &sig.to_bytes(),
                "endorse",
                "endorse",
                b"tampered",
            ),
            Err(SigError::BadSignature)
        );
    }

    // covers: signing_message
    #[test]
    fn purposes_cannot_be_made_ambiguous() {
        assert_eq!(
            signing_message("a\0b", b""),
            Err(SigError::PurposeContainsNul)
        );
        // Without separation, ("ab", "c") and ("a", "bc") would collide.
        let x = signing_message("ab", b"c").unwrap();
        let y = signing_message("a", b"bc").unwrap();
        assert_ne!(x, y);
    }

    // covers: verify
    #[test]
    fn rejects_malformed_inputs() {
        let sk = key();
        assert_eq!(
            verify(SigAlg::Ed25519, b"short", &[0u8; 64], "p", "p", b""),
            Err(SigError::MalformedKey)
        );
        assert_eq!(
            verify(
                SigAlg::Ed25519,
                sk.verifying_key().as_bytes(),
                b"short",
                "p",
                "p",
                b""
            ),
            Err(SigError::MalformedSignature)
        );
    }

    // covers: sign, verify
    #[test]
    fn a_signature_this_module_produces_verifies_against_itself() {
        let sk = key();
        let target = b"canonical bytes";
        let produced = sign(
            SigAlg::Ed25519,
            sk.to_bytes().as_slice(),
            "authored",
            target,
        )
        .unwrap();
        assert!(
            verify(
                SigAlg::Ed25519,
                sk.verifying_key().as_bytes(),
                &produced,
                "authored",
                "authored",
                target,
            )
            .is_ok()
        );
    }

    // covers: sign
    #[test]
    fn sign_rejects_a_malformed_secret_key() {
        assert_eq!(
            sign(SigAlg::Ed25519, b"short", "p", b""),
            Err(SigError::MalformedSecretKey)
        );
    }
}