publet_core/sig.rs
1//! Detached signatures (Section 4.4).
2//!
3//! A signature is its own object referencing a target by identifier, so
4//! signatures accrue to an object without changing its identifier (R3).
5//! The signed message is domain-separated:
6//!
7//! ```text
8//! "pub/v1/sig" || 0x00 || purpose || 0x00 || canonical-bytes-of-target
9//! ```
10//!
11//! The separator matters more than it looks. Without it, a signature made
12//! for one purpose could be presented as a signature for another, and an
13//! endorsement could be replayed as a retraction. Section 4.4 therefore
14//! requires rejecting a signature whose purpose does not match the context
15//! it is being evaluated in, and [`verify`] takes the expected purpose as
16//! an argument so that omitting the check is not possible.
17
18use ed25519_dalek::{Signature, Signer as _, SigningKey, Verifier as _, VerifyingKey};
19use thiserror::Error;
20
21/// The domain separation prefix.
22const DOMAIN: &[u8] = b"pub/v1/sig";
23
24/// A signature algorithm.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26#[non_exhaustive]
27pub enum SigAlg {
28 /// Ed25519, required by Section 4.4.
29 Ed25519,
30}
31
32impl SigAlg {
33 /// The in-band identifier.
34 ///
35 /// # Example
36 ///
37 /// ```
38 /// use publet_core::SigAlg;
39 ///
40 /// assert_eq!(SigAlg::Ed25519.id(), "ed25519");
41 /// ```
42 #[must_use]
43 pub fn id(self) -> &'static str {
44 match self {
45 Self::Ed25519 => "ed25519",
46 }
47 }
48
49 /// Resolve an in-band identifier.
50 ///
51 /// # Example
52 ///
53 /// ```
54 /// use publet_core::SigAlg;
55 ///
56 /// assert_eq!(SigAlg::from_id("ed25519"), Some(SigAlg::Ed25519));
57 /// assert_eq!(SigAlg::from_id("rsa"), None);
58 /// ```
59 #[must_use]
60 pub fn from_id(id: &str) -> Option<Self> {
61 match id {
62 "ed25519" => Some(Self::Ed25519),
63 _ => None,
64 }
65 }
66}
67
68/// Reasons a signature does not verify.
69#[derive(Debug, Error, PartialEq, Eq, Clone)]
70#[non_exhaustive]
71pub enum SigError {
72 /// The algorithm identifier is not implemented.
73 #[error("unknown signature algorithm: {0}")]
74 UnknownAlgorithm(String),
75
76 /// The public key was not the right length or shape.
77 #[error("malformed public key")]
78 MalformedKey,
79
80 /// The secret key was not the right length or shape.
81 #[error("malformed secret key")]
82 MalformedSecretKey,
83
84 /// The signature was not the right length or shape.
85 #[error("malformed signature")]
86 MalformedSignature,
87
88 /// The signature did not verify over the constructed message.
89 #[error("signature does not verify")]
90 BadSignature,
91
92 /// The signature was made for a different purpose.
93 #[error("purpose mismatch: signature is for {found:?}, context requires {expected:?}")]
94 PurposeMismatch {
95 /// The purpose recorded in the signature object.
96 found: String,
97 /// The purpose the evaluating context requires.
98 expected: String,
99 },
100
101 /// A purpose contained the separator byte.
102 #[error("purpose must not contain a NUL byte")]
103 PurposeContainsNul,
104}
105
106/// Construct the message a signature covers.
107///
108/// # Errors
109///
110/// Returns [`SigError::PurposeContainsNul`] if `purpose` contains `0x00`,
111/// which would make the separated encoding ambiguous.
112///
113/// # Example
114///
115/// ```
116/// use publet_core::{SigError, signing_message};
117///
118/// let message = signing_message("authored", b"target bytes")?;
119/// assert_eq!(message, b"pub/v1/sig\0authored\0target bytes");
120///
121/// // A purpose may not contain the separator.
122/// assert_eq!(signing_message("a\0b", b""), Err(SigError::PurposeContainsNul));
123/// # Ok::<(), SigError>(())
124/// ```
125pub fn signing_message(purpose: &str, target_bytes: &[u8]) -> Result<Vec<u8>, SigError> {
126 if purpose.as_bytes().contains(&0) {
127 return Err(SigError::PurposeContainsNul);
128 }
129 let mut message = Vec::with_capacity(DOMAIN.len() + purpose.len() + target_bytes.len() + 2);
130 message.extend_from_slice(DOMAIN);
131 message.push(0);
132 message.extend_from_slice(purpose.as_bytes());
133 message.push(0);
134 message.extend_from_slice(target_bytes);
135 Ok(message)
136}
137
138/// Verify a detached signature over `target_bytes` for `expected_purpose`.
139///
140/// `found_purpose` is the purpose recorded in the signature object;
141/// `expected_purpose` is what the calling context requires. They must
142/// match, and the mismatch is reported before any cryptography is done.
143///
144/// # Errors
145///
146/// Fails only if one of these checks fails, in this order:
147///
148/// - [`SigError::PurposeMismatch`] if `found_purpose` is not
149/// `expected_purpose`. No cryptography is done.
150/// - [`SigError::PurposeContainsNul`] if the purpose contains `0x00`.
151/// - [`SigError::MalformedKey`] if `public_key` is not 32 bytes, or is not
152/// the encoding of a curve point.
153/// - [`SigError::MalformedSignature`] if `signature` is not 64 bytes.
154/// - [`SigError::BadSignature`] if the signature does not verify over
155/// [`signing_message`]`(found_purpose, target_bytes)`.
156///
157/// # Example
158///
159/// ```
160/// use publet_core::{SigAlg, SigError, sign, verify, verifying_key};
161///
162/// // A real seed comes from a random source; this crate needs no RNG.
163/// let seed = [7u8; 32];
164/// let public = verifying_key(SigAlg::Ed25519, &seed)?;
165/// let signature = sign(SigAlg::Ed25519, &seed, "authored", b"object")?;
166///
167/// verify(SigAlg::Ed25519, &public, &signature, "authored", "authored", b"object")?;
168///
169/// // The purpose the signature was made for must be the one asked about...
170/// assert!(matches!(
171/// verify(SigAlg::Ed25519, &public, &signature, "authored", "retracted", b"object"),
172/// Err(SigError::PurposeMismatch { .. }),
173/// ));
174/// // ...and the bytes must be the ones signed.
175/// assert_eq!(
176/// verify(SigAlg::Ed25519, &public, &signature, "authored", "authored", b"altered"),
177/// Err(SigError::BadSignature),
178/// );
179/// # Ok::<(), SigError>(())
180/// ```
181pub fn verify(
182 alg: SigAlg,
183 public_key: &[u8],
184 signature: &[u8],
185 found_purpose: &str,
186 expected_purpose: &str,
187 target_bytes: &[u8],
188) -> Result<(), SigError> {
189 if found_purpose != expected_purpose {
190 return Err(SigError::PurposeMismatch {
191 found: found_purpose.to_owned(),
192 expected: expected_purpose.to_owned(),
193 });
194 }
195 let message = signing_message(found_purpose, target_bytes)?;
196 match alg {
197 SigAlg::Ed25519 => {
198 let key_bytes: [u8; 32] = public_key.try_into().map_err(|_| SigError::MalformedKey)?;
199 let key = VerifyingKey::from_bytes(&key_bytes).map_err(|_| SigError::MalformedKey)?;
200 let sig_bytes: [u8; 64] = signature
201 .try_into()
202 .map_err(|_| SigError::MalformedSignature)?;
203 let sig = Signature::from_bytes(&sig_bytes);
204 key.verify(&message, &sig)
205 .map_err(|_| SigError::BadSignature)
206 }
207 }
208}
209
210/// Produce a detached signature over `target_bytes` for `purpose`.
211///
212/// Deterministic (RFC 8032): the same key, purpose, and target always
213/// produce the same signature, so this needs no randomness at call time --
214/// unlike generating the key itself, which does.
215///
216/// # Errors
217///
218/// Returns [`SigError`] if `secret_key` is not a 32-byte Ed25519 seed, or
219/// if `purpose` contains the separator byte.
220///
221/// # Example
222///
223/// ```
224/// use publet_core::{SigAlg, sign};
225///
226/// // A real seed comes from a random source; this crate needs no RNG.
227/// let seed = [7u8; 32];
228/// let signature = sign(SigAlg::Ed25519, &seed, "authored", b"object")?;
229/// assert_eq!(signature.len(), 64);
230///
231/// // Deterministic: the same key, purpose and bytes give the same signature.
232/// assert_eq!(sign(SigAlg::Ed25519, &seed, "authored", b"object")?, signature);
233/// # Ok::<(), publet_core::SigError>(())
234/// ```
235pub fn sign(
236 alg: SigAlg,
237 secret_key: &[u8],
238 purpose: &str,
239 target_bytes: &[u8],
240) -> Result<Vec<u8>, SigError> {
241 let message = signing_message(purpose, target_bytes)?;
242 match alg {
243 SigAlg::Ed25519 => {
244 let key_bytes: [u8; 32] = secret_key
245 .try_into()
246 .map_err(|_| SigError::MalformedSecretKey)?;
247 let signing_key = SigningKey::from_bytes(&key_bytes);
248 Ok(signing_key.sign(&message).to_bytes().to_vec())
249 }
250 }
251}
252
253/// Derive the public key matching a secret key.
254///
255/// Lets a caller holding a freshly generated seed (bytes only -- generating
256/// them is not this crate's concern, since that needs an RNG source, not
257/// cryptography) obtain the public half without reaching past this module
258/// into `ed25519_dalek` directly.
259///
260/// # Errors
261///
262/// Returns [`SigError::MalformedSecretKey`] if `secret_key` is not a 32-byte
263/// Ed25519 seed.
264///
265/// # Example
266///
267/// ```
268/// use publet_core::{SigAlg, SigError, verifying_key};
269///
270/// let public = verifying_key(SigAlg::Ed25519, &[7u8; 32])?;
271/// assert_eq!(public.len(), 32);
272///
273/// // A seed must be exactly 32 bytes.
274/// assert_eq!(verifying_key(SigAlg::Ed25519, &[7u8; 31]), Err(SigError::MalformedSecretKey));
275/// # Ok::<(), SigError>(())
276/// ```
277pub fn verifying_key(alg: SigAlg, secret_key: &[u8]) -> Result<Vec<u8>, SigError> {
278 match alg {
279 SigAlg::Ed25519 => {
280 let key_bytes: [u8; 32] = secret_key
281 .try_into()
282 .map_err(|_| SigError::MalformedSecretKey)?;
283 let signing_key = SigningKey::from_bytes(&key_bytes);
284 Ok(signing_key.verifying_key().as_bytes().to_vec())
285 }
286 }
287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
292
293 fn key() -> SigningKey {
294 // A fixed seed: these tests assert on behaviour, not on secrecy.
295 SigningKey::from_bytes(&[7u8; 32])
296 }
297
298 // covers: signing_message, verify
299 #[test]
300 fn verifies_a_correct_signature() {
301 let sk = key();
302 let target = b"canonical bytes";
303 let msg = signing_message("endorse", target).unwrap();
304 let sig = sk.sign(&msg);
305 assert!(
306 verify(
307 SigAlg::Ed25519,
308 sk.verifying_key().as_bytes(),
309 &sig.to_bytes(),
310 "endorse",
311 "endorse",
312 target,
313 )
314 .is_ok()
315 );
316 }
317
318 // covers: signing_message, verify
319 #[test]
320 fn rejects_a_signature_replayed_under_another_purpose() {
321 let sk = key();
322 let target = b"canonical bytes";
323 let msg = signing_message("endorse", target).unwrap();
324 let sig = sk.sign(&msg);
325
326 // Presented honestly but in the wrong context.
327 assert!(matches!(
328 verify(
329 SigAlg::Ed25519,
330 sk.verifying_key().as_bytes(),
331 &sig.to_bytes(),
332 "endorse",
333 "retract",
334 target,
335 ),
336 Err(SigError::PurposeMismatch { .. })
337 ));
338
339 // Relabelled to match the context: the domain separation defeats it.
340 assert!(matches!(
341 verify(
342 SigAlg::Ed25519,
343 sk.verifying_key().as_bytes(),
344 &sig.to_bytes(),
345 "retract",
346 "retract",
347 target,
348 ),
349 Err(SigError::BadSignature)
350 ));
351 }
352
353 // covers: signing_message, verify
354 #[test]
355 fn rejects_a_signature_over_different_bytes() {
356 let sk = key();
357 let msg = signing_message("endorse", b"original").unwrap();
358 let sig = sk.sign(&msg);
359 assert_eq!(
360 verify(
361 SigAlg::Ed25519,
362 sk.verifying_key().as_bytes(),
363 &sig.to_bytes(),
364 "endorse",
365 "endorse",
366 b"tampered",
367 ),
368 Err(SigError::BadSignature)
369 );
370 }
371
372 // covers: signing_message
373 #[test]
374 fn purposes_cannot_be_made_ambiguous() {
375 assert_eq!(
376 signing_message("a\0b", b""),
377 Err(SigError::PurposeContainsNul)
378 );
379 // Without separation, ("ab", "c") and ("a", "bc") would collide.
380 let x = signing_message("ab", b"c").unwrap();
381 let y = signing_message("a", b"bc").unwrap();
382 assert_ne!(x, y);
383 }
384
385 // covers: verify
386 #[test]
387 fn rejects_malformed_inputs() {
388 let sk = key();
389 assert_eq!(
390 verify(SigAlg::Ed25519, b"short", &[0u8; 64], "p", "p", b""),
391 Err(SigError::MalformedKey)
392 );
393 assert_eq!(
394 verify(
395 SigAlg::Ed25519,
396 sk.verifying_key().as_bytes(),
397 b"short",
398 "p",
399 "p",
400 b""
401 ),
402 Err(SigError::MalformedSignature)
403 );
404 }
405
406 // covers: sign, verify
407 #[test]
408 fn a_signature_this_module_produces_verifies_against_itself() {
409 let sk = key();
410 let target = b"canonical bytes";
411 let produced = sign(
412 SigAlg::Ed25519,
413 sk.to_bytes().as_slice(),
414 "authored",
415 target,
416 )
417 .unwrap();
418 assert!(
419 verify(
420 SigAlg::Ed25519,
421 sk.verifying_key().as_bytes(),
422 &produced,
423 "authored",
424 "authored",
425 target,
426 )
427 .is_ok()
428 );
429 }
430
431 // covers: sign
432 #[test]
433 fn sign_rejects_a_malformed_secret_key() {
434 assert_eq!(
435 sign(SigAlg::Ed25519, b"short", "p", b""),
436 Err(SigError::MalformedSecretKey)
437 );
438 }
439}