Skip to main content

relay_auth/
lib.rs

1//! Authentication and crypto for Relay.
2//!
3//! This library contains the [`PublicKey`] and [`SecretKey`] types, which can be used to validate
4//! and sign traffic between Relays in authenticated endpoints. Additionally, Relays identify via a
5//! [`RelayId`], which is included in the request signature and headers.
6//!
7//! Relay uses Ed25519 at the moment. This is considered an implementation detail and is subject to
8//! change at any time. Do not rely on a specific signing mechanism.
9//!
10//! # Generating Credentials
11//!
12//! Use the [`generate_relay_id`] and [`generate_key_pair`] function to generate credentials:
13//!
14//! ```
15//! let relay_id = relay_auth::generate_relay_id();
16//! let (private_key, public_key) = relay_auth::generate_key_pair();
17//! ```
18
19#![warn(missing_docs)]
20#![doc(
21    html_logo_url = "https://raw.githubusercontent.com/getsentry/relay/master/artwork/relay-icon.png",
22    html_favicon_url = "https://raw.githubusercontent.com/getsentry/relay/master/artwork/relay-icon.png"
23)]
24
25use std::fmt;
26use std::fmt::Display;
27use std::str::FromStr;
28
29use chrono::{DateTime, Duration, Utc};
30use data_encoding::BASE64URL_NOPAD;
31use ed25519_dalek::pkcs8::{DecodePrivateKey as _, DecodePublicKey as _};
32use ed25519_dalek::{Digest, DigestSigner, DigestVerifier, Signer, Verifier};
33use hmac::{Hmac, Mac};
34use rand::rngs::OsRng;
35use rand::{RngCore as _, TryRngCore as _};
36use serde::de::DeserializeOwned;
37use serde::{Deserialize, Serialize};
38use sha2::Sha512;
39use uuid::Uuid;
40
41include!(concat!(env!("OUT_DIR"), "/constants.gen.rs"));
42
43/// The latest Relay version known to this Relay. This is the current version.
44const LATEST_VERSION: RelayVersion = RelayVersion::new(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
45
46/// The oldest downstream Relay version still supported by this Relay.
47const OLDEST_VERSION: RelayVersion = RelayVersion::new(0, 0, 0); // support all
48
49/// The maximum time a timestamp is allowed to be in the future.
50///
51/// Timestamps are always expected to be in the past, but due to time sync inconsistencies
52/// we allow a certain leniency for timestamps to be in the future.
53const MAX_TIME_IN_FUTURE: Duration = Duration::seconds(15);
54
55/// Alias for Relay IDs (UUIDs).
56pub type RelayId = Uuid;
57
58/// The version of a Relay.
59#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
60pub struct RelayVersion {
61    major: u8,
62    minor: u8,
63    patch: u8,
64}
65
66impl RelayVersion {
67    /// Returns the current Relay version.
68    pub fn current() -> Self {
69        LATEST_VERSION
70    }
71
72    /// Returns the oldest compatible Relay version.
73    ///
74    /// Relays older than this cannot authenticate with this Relay. It is possible for newer Relays
75    /// to authenticate.
76    pub fn oldest() -> Self {
77        OLDEST_VERSION
78    }
79
80    /// Creates a new version with the given components.
81    pub const fn new(major: u8, minor: u8, patch: u8) -> Self {
82        Self {
83            major,
84            minor,
85            patch,
86        }
87    }
88
89    /// Returns `true` if this version is still supported.
90    pub fn supported(self) -> bool {
91        self >= Self::oldest()
92    }
93
94    /// Returns `true` if this version is older than the current version.
95    pub fn outdated(self) -> bool {
96        self < Self::current()
97    }
98}
99
100impl fmt::Display for RelayVersion {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
103    }
104}
105
106/// Raised if Relay cannot parse the provided version.
107#[derive(Clone, Copy, Debug, Default, thiserror::Error)]
108#[error("invalid relay version string")]
109pub struct ParseRelayVersionError;
110
111impl FromStr for RelayVersion {
112    type Err = ParseRelayVersionError;
113
114    fn from_str(s: &str) -> Result<Self, Self::Err> {
115        let mut iter = s
116            .split(&['.', '-'][..])
117            .map(|s| s.parse().map_err(|_| ParseRelayVersionError));
118
119        let major = iter.next().ok_or(ParseRelayVersionError)??;
120        let minor = iter.next().ok_or(ParseRelayVersionError)??;
121        let patch = iter.next().ok_or(ParseRelayVersionError)??;
122
123        Ok(Self::new(major, minor, patch))
124    }
125}
126
127relay_common::impl_str_serde!(RelayVersion, "a version string");
128
129/// Raised if a key could not be parsed.
130#[derive(Debug, Eq, Hash, PartialEq, thiserror::Error)]
131pub enum KeyParseError {
132    /// Invalid key encoding.
133    #[error("bad key encoding")]
134    BadEncoding,
135    /// Invalid key data.
136    #[error("bad key data")]
137    BadKey,
138}
139
140/// Raised if the signature timestamp is not valid.
141#[derive(Debug, thiserror::Error, PartialEq, Eq)]
142pub enum TimeError {
143    /// The signature timestamp is too far in the future.
144    #[error("the timestamp is too far in the future")]
145    TooFarInFuture,
146    /// The signature timestamp is too far in the past.
147    #[error("the timestamp is too far in the past")]
148    TooFarInPast,
149}
150
151/// Raised to indicate errors when verifying a signature.
152#[derive(Debug, thiserror::Error, PartialEq, Eq)]
153pub enum SignatureError {
154    /// Raised if the signature is structurally invalid.
155    #[error("invalid signature")]
156    Invalid,
157    /// Raised if the signature is structurally valid but cannot be verified.
158    #[error("signature cannot be verified")]
159    Unverifiable,
160    /// Raised if the signature timestamp cannot be verified.
161    #[error("{0}")]
162    Time(#[from] TimeError),
163}
164
165/// Raised to indicate failure on unpacking.
166#[derive(Debug, thiserror::Error)]
167pub enum UnpackError {
168    /// Raised if the signature is invalid.
169    #[error("invalid signature on data")]
170    BadSignature,
171    /// Invalid key encoding.
172    #[error("bad key encoding")]
173    BadEncoding,
174    /// Raised if deserializing of data failed.
175    #[error("could not deserialize payload")]
176    BadPayload(#[source] serde_json::Error),
177    /// Raised on unpacking if the data carries an invalid timestamp.
178    #[error("{0}")]
179    Time(#[from] TimeError),
180    /// Raised if the Relay ID in a register response does not match the signed register state.
181    #[error("relay id does not match the register challenge")]
182    RelayIdMismatch,
183}
184
185impl From<SignatureError> for UnpackError {
186    fn from(value: SignatureError) -> Self {
187        match value {
188            SignatureError::Invalid | SignatureError::Unverifiable => Self::BadSignature,
189            SignatureError::Time(time) => Self::Time(time),
190        }
191    }
192}
193
194/// Used to tell which algorithm was used for signature creation.
195#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
196pub enum SignatureAlgorithm {
197    /// Regular signature creation which clones the data internally.
198    #[serde(rename = "v0")]
199    Regular,
200    /// Pre-hashed signature which allows incremental hashing.
201    #[serde(rename = "v1")]
202    Prehashed,
203}
204
205/// A wrapper around packed data that adds a timestamp.
206///
207/// This is internally automatically used when data is signed.
208#[derive(Serialize, Deserialize, Debug)]
209pub struct SignatureHeader {
210    /// The timestamp of when the data was packed and signed.
211    #[serde(rename = "t")]
212    pub timestamp: DateTime<Utc>,
213
214    /// Represents how this signature was created and how it needs to be verified.
215    ///
216    /// Defaults to [`SignatureAlgorithm::Regular`] because that was used before the introduction
217    /// of this field.
218    #[serde(rename = "a", skip_serializing_if = "Option::is_none")]
219    pub signature_algorithm: Option<SignatureAlgorithm>,
220}
221
222impl Default for SignatureHeader {
223    fn default() -> SignatureHeader {
224        SignatureHeader {
225            timestamp: Utc::now(),
226            signature_algorithm: None,
227        }
228    }
229}
230
231/// A [`SignatureHeader`] which has been verified.
232#[derive(Debug)]
233pub struct VerifiedSignatureHeader {
234    timestamp: DateTime<Utc>,
235    signature_algorithm: SignatureAlgorithm,
236}
237
238impl VerifiedSignatureHeader {
239    /// Returns the [`SignatureHeader::timestamp`] of the verified header.
240    pub fn timestamp(&self) -> DateTime<Utc> {
241        self.timestamp
242    }
243
244    /// Returns the [`SignatureHeader::signature_algorithm`] of the verified header.
245    pub fn signature_algorithm(&self) -> SignatureAlgorithm {
246        self.signature_algorithm
247    }
248}
249
250/// Represents the secret key of an Relay.
251///
252/// Secret keys are based on ed25519 but this should be considered an
253/// implementation detail for now.  We only ever represent public keys
254/// on the wire as opaque ascii encoded strings of arbitrary format or length.
255#[derive(Clone)]
256pub struct SecretKey {
257    inner: ed25519_dalek::SigningKey,
258}
259
260/// Represents the final registration.
261#[derive(Serialize, Deserialize, Debug)]
262pub struct Registration {
263    relay_id: RelayId,
264}
265
266/// Creates a digest for signature verification/signing.
267fn create_digest(header: &[u8], data: &[u8]) -> Sha512 {
268    let mut digest = Sha512::default();
269    digest.update(header);
270    digest.update(b"\x00");
271    digest.update(data);
272    digest
273}
274
275impl SecretKey {
276    /// Signs some data with the secret key and returns the signature.
277    ///
278    /// This is will sign with the default header.
279    pub fn sign(&self, data: &[u8]) -> Signature {
280        self.sign_with_header(data, &SignatureHeader::default())
281    }
282
283    /// Signs some data with the secret key and a specific header and
284    /// then returns the signature.
285    ///
286    /// The default behavior is to attach the timestamp in the header to the
287    /// signature so that old signatures on verification can be rejected.
288    pub fn sign_with_header(&self, data: &[u8], sig_header: &SignatureHeader) -> Signature {
289        let mut header =
290            serde_json::to_vec(&sig_header).expect("attempted to pack non json safe header");
291        let header_encoded = BASE64URL_NOPAD.encode(&header);
292        let sig = match sig_header
293            .signature_algorithm
294            .unwrap_or(SignatureAlgorithm::Regular)
295        {
296            SignatureAlgorithm::Regular => {
297                header.push(b'\x00');
298                header.extend_from_slice(data);
299                self.inner.sign(&header)
300            }
301            SignatureAlgorithm::Prehashed => {
302                let digest = create_digest(&header, data);
303                self.inner.sign_digest(digest)
304            }
305        };
306
307        let mut sig_encoded = BASE64URL_NOPAD.encode(&sig.to_bytes());
308        sig_encoded.push('.');
309        sig_encoded.push_str(&header_encoded);
310        Signature(sig_encoded)
311    }
312
313    /// Packs some serializable data into JSON and signs it with the default header.
314    pub fn pack<S: Serialize>(&self, data: S) -> (Vec<u8>, Signature) {
315        self.pack_with_header(data, &SignatureHeader::default())
316    }
317
318    /// Packs some serializable data into JSON and signs it with the specified header.
319    pub fn pack_with_header<S: Serialize>(
320        &self,
321        data: S,
322        header: &SignatureHeader,
323    ) -> (Vec<u8>, Signature) {
324        // this can only fail if we deal with badly formed data.  In that case we
325        // consider that a panic.  Should not happen.
326        let json = serde_json::to_vec(&data).expect("attempted to pack non json safe data");
327        let sig = self.sign_with_header(&json, header);
328        (json, sig)
329    }
330}
331
332impl PartialEq for SecretKey {
333    fn eq(&self, other: &SecretKey) -> bool {
334        self.inner.to_keypair_bytes() == other.inner.to_keypair_bytes()
335    }
336}
337
338impl Eq for SecretKey {}
339
340impl FromStr for SecretKey {
341    type Err = KeyParseError;
342
343    fn from_str(s: &str) -> Result<SecretKey, KeyParseError> {
344        if let Ok(inner) = ed25519_dalek::SigningKey::from_pkcs8_pem(s) {
345            return Ok(Self { inner });
346        }
347
348        let bytes = match BASE64URL_NOPAD.decode(s.as_bytes()) {
349            Ok(bytes) => bytes,
350            _ => return Err(KeyParseError::BadEncoding),
351        };
352
353        let inner = if let Ok(keypair) = bytes.as_slice().try_into() {
354            ed25519_dalek::SigningKey::from_keypair_bytes(&keypair)
355                .map_err(|_| KeyParseError::BadKey)?
356        } else if let Ok(secret_key) = bytes.try_into() {
357            ed25519_dalek::SigningKey::from_bytes(&secret_key)
358        } else {
359            return Err(KeyParseError::BadKey);
360        };
361
362        Ok(SecretKey { inner })
363    }
364}
365
366impl fmt::Display for SecretKey {
367    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368        if f.alternate() {
369            write!(
370                f,
371                "{}",
372                BASE64URL_NOPAD.encode(&self.inner.to_keypair_bytes())
373            )
374        } else {
375            write!(f, "{}", BASE64URL_NOPAD.encode(&self.inner.to_bytes()))
376        }
377    }
378}
379
380impl fmt::Debug for SecretKey {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        write!(f, "SecretKey(\"{self}\")")
383    }
384}
385
386relay_common::impl_str_serde!(SecretKey, "a secret key");
387
388/// Represents the public key of a Relay.
389///
390/// Public keys are based on ed25519 but this should be considered an
391/// implementation detail for now.  We only ever represent public keys
392/// on the wire as opaque ascii encoded strings of arbitrary format or length.
393#[derive(Clone, Eq, PartialEq)]
394pub struct PublicKey {
395    inner: ed25519_dalek::VerifyingKey,
396}
397
398impl PublicKey {
399    /// Verifies the signature and returns the embedded signature header.
400    ///
401    /// Returns [`SignatureError`] when the signature cannot be verified.
402    pub fn verify(
403        &self,
404        data: &[u8],
405        sig: SignatureRef<'_>,
406        start_time: DateTime<Utc>,
407        max_age: Duration,
408    ) -> Result<VerifiedSignatureHeader, SignatureError> {
409        let mut iter = sig.0.splitn(2, '.');
410        let sig_bytes = {
411            let sig_encoded = iter.next().ok_or(SignatureError::Invalid)?;
412            BASE64URL_NOPAD
413                .decode(sig_encoded.as_bytes())
414                .map_err(|_| SignatureError::Invalid)?
415        };
416        let sig = ed25519_dalek::Signature::from_slice(&sig_bytes)
417            .map_err(|_| SignatureError::Invalid)?;
418
419        let header = {
420            let header_encoded = iter.next().ok_or(SignatureError::Invalid)?;
421            BASE64URL_NOPAD
422                .decode(header_encoded.as_bytes())
423                .map_err(|_| SignatureError::Invalid)?
424        };
425        let parsed: SignatureHeader =
426            serde_json::from_slice(&header).map_err(|_| SignatureError::Invalid)?;
427
428        let signature_algorithm = parsed
429            .signature_algorithm
430            // Default to the regular algorithm for backwards compatibility.
431            .unwrap_or(SignatureAlgorithm::Regular);
432
433        let verification_result = match signature_algorithm {
434            SignatureAlgorithm::Regular => {
435                let mut to_verify = header.clone();
436                to_verify.push(b'\x00');
437                to_verify.extend_from_slice(data);
438                self.inner.verify(&to_verify, &sig)
439            }
440            SignatureAlgorithm::Prehashed => {
441                let digest = create_digest(&header, data);
442                self.inner.verify_digest(digest, &sig)
443            }
444        };
445
446        let Ok(()) = verification_result else {
447            return Err(SignatureError::Unverifiable);
448        };
449
450        let timestamp = verify_time(parsed.timestamp, start_time, max_age)?;
451
452        Ok(VerifiedSignatureHeader {
453            timestamp,
454            signature_algorithm,
455        })
456    }
457
458    /// Unpacks signed data and returns it with header.
459    pub fn unpack<D: DeserializeOwned>(
460        &self,
461        data: &[u8],
462        signature: SignatureRef<'_>,
463        start_time: DateTime<Utc>,
464        max_age_diff: Duration,
465    ) -> Result<D, UnpackError> {
466        let _verified = self.verify(data, signature, start_time, max_age_diff)?;
467        serde_json::from_slice(data).map_err(UnpackError::BadPayload)
468    }
469}
470
471impl FromStr for PublicKey {
472    type Err = KeyParseError;
473
474    fn from_str(s: &str) -> Result<PublicKey, KeyParseError> {
475        if let Ok(inner) = ed25519_dalek::VerifyingKey::from_public_key_pem(s) {
476            return Ok(Self { inner });
477        }
478
479        let Ok(bytes) = BASE64URL_NOPAD.decode(s.as_bytes()) else {
480            return Err(KeyParseError::BadEncoding);
481        };
482
483        let inner = match bytes.try_into() {
484            Ok(bytes) => ed25519_dalek::VerifyingKey::from_bytes(&bytes)
485                .map_err(|_| KeyParseError::BadKey)?,
486            Err(_) => return Err(KeyParseError::BadKey),
487        };
488
489        Ok(PublicKey { inner })
490    }
491}
492
493impl fmt::Display for PublicKey {
494    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495        write!(f, "{}", BASE64URL_NOPAD.encode(&self.inner.to_bytes()))
496    }
497}
498
499impl fmt::Debug for PublicKey {
500    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501        write!(f, "PublicKey(\"{self}\")")
502    }
503}
504
505relay_common::impl_str_serde!(PublicKey, "a public key");
506
507/// Generates an Relay ID.
508pub fn generate_relay_id() -> RelayId {
509    Uuid::new_v4()
510}
511
512/// Generates a secret + public key pair.
513pub fn generate_key_pair() -> (SecretKey, PublicKey) {
514    let mut csprng = OsRng;
515    let mut secret = [0; 32];
516    csprng
517        .try_fill_bytes(&mut secret)
518        .expect("os rng should be available");
519    let kp = ed25519_dalek::SigningKey::from_bytes(&secret);
520    let pk = kp.verifying_key();
521    (SecretKey { inner: kp }, PublicKey { inner: pk })
522}
523
524/// An encoded and signed `RegisterState`.
525///
526/// This signature can be used by the upstream server to ensure that the downstream client did not
527/// tamper with the token without keeping state between requests. For more information, see
528/// `RegisterState`.
529///
530/// The format and contents of `SignedRegisterState` are intentionally opaque. Downstream clients
531/// do not need to interpret it, and the upstream can change its contents at any time. Parsing and
532/// validation is only performed on the upstream.
533///
534/// In the current implementation, the serialized state has the format `{state}:{signature}`, where
535/// each component is:
536///  - `state`: A URL-safe base64 encoding of the JSON serialized `RegisterState`.
537///  - `signature`: A URL-safe base64 encoding of the SHA512 HMAC of the encoded state.
538///
539/// To create a signed state, use `RegisterChallenge::sign`. To validate the signature and read
540/// the state, use `SignedRegisterChallenge::unpack`. In both cases, a secret for signing has to be
541/// supplied.
542#[derive(Clone, Debug, Deserialize, Serialize)]
543pub struct SignedRegisterState(String);
544
545impl SignedRegisterState {
546    /// Creates an Hmac instance for signing the `RegisterState`.
547    fn mac(secret: &[u8]) -> Hmac<Sha512> {
548        Hmac::new_from_slice(secret).expect("HMAC takes variable keys")
549    }
550
551    /// Signs the given `RegisterState` and serializes it into a single string.
552    fn sign(state: RegisterState, secret: &[u8]) -> Self {
553        let json = serde_json::to_string(&state).expect("relay register state serializes to JSON");
554        let token = BASE64URL_NOPAD.encode(json.as_bytes());
555
556        let mut mac = Self::mac(secret);
557        mac.update(token.as_bytes());
558        let signature = BASE64URL_NOPAD.encode(&mac.finalize().into_bytes());
559
560        Self(format!("{token}:{signature}"))
561    }
562
563    /// Splits the signed state into the encoded state and encoded signature.
564    fn split(&self) -> (&str, &str) {
565        let mut split = self.as_str().splitn(2, ':');
566        (split.next().unwrap_or(""), split.next().unwrap_or(""))
567    }
568
569    /// Returns the string representation of the token.
570    pub fn as_str(&self) -> &str {
571        self.0.as_str()
572    }
573
574    /// Unpacks the encoded state and validates the signature.
575    ///
576    /// The timestamp in the state is validated against the current timestamp.
577    pub fn unpack(
578        &self,
579        secret: &[u8],
580        start_time: DateTime<Utc>,
581        max_age: Duration,
582    ) -> Result<RegisterState, UnpackError> {
583        let (token, signature) = self.split();
584        let code = BASE64URL_NOPAD
585            .decode(signature.as_bytes())
586            .map_err(|_| UnpackError::BadEncoding)?;
587
588        let mut mac = Self::mac(secret);
589        mac.update(token.as_bytes());
590        mac.verify_slice(&code)
591            .map_err(|_| UnpackError::BadSignature)?;
592
593        let json = BASE64URL_NOPAD
594            .decode(token.as_bytes())
595            .map_err(|_| UnpackError::BadEncoding)?;
596        let state =
597            serde_json::from_slice::<RegisterState>(&json).map_err(UnpackError::BadPayload)?;
598
599        let _ = verify_time(state.timestamp, start_time, max_age)?;
600
601        Ok(state)
602    }
603}
604
605impl fmt::Display for SignedRegisterState {
606    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607        self.as_str().fmt(f)
608    }
609}
610
611/// A state structure containing relevant information from `RegisterRequest`.
612///
613/// This structure is used to carry over information between the downstream register request and
614/// register response. In addition to identifying information, it contains a random bit to avoid
615/// replay attacks.
616#[derive(Clone, Deserialize, Serialize)]
617pub struct RegisterState {
618    #[serde(with = "chrono::serde::ts_seconds")]
619    timestamp: DateTime<Utc>,
620    relay_id: RelayId,
621    public_key: PublicKey,
622    rand: String,
623}
624
625impl RegisterState {
626    /// Returns the timestamp at which the challenge was created.
627    pub fn timestamp(&self) -> DateTime<Utc> {
628        self.timestamp
629    }
630
631    /// Returns the identifier of the requesting downstream Relay.
632    pub fn relay_id(&self) -> RelayId {
633        self.relay_id
634    }
635
636    /// Returns the public key of the requesting downstream Relay.
637    pub fn public_key(&self) -> &PublicKey {
638        &self.public_key
639    }
640}
641
642/// Generates a new random token for the register state.
643fn nonce() -> String {
644    let mut rng = rand::rng();
645    let mut bytes = vec![0u8; 64];
646    rng.fill_bytes(&mut bytes);
647    BASE64URL_NOPAD.encode(&bytes)
648}
649
650/// Represents a request for registration with the upstream.
651///
652/// This is created if the Relay signs in for the first time.  The server needs
653/// to respond to this request with a unique token that is then used to sign
654/// the response.
655#[derive(Serialize, Deserialize, Debug)]
656pub struct RegisterRequest {
657    relay_id: RelayId,
658    public_key: PublicKey,
659    #[serde(default)]
660    version: RelayVersion,
661}
662
663impl RegisterRequest {
664    /// Creates a new request to register an Relay upstream.
665    pub fn new(relay_id: &RelayId, public_key: &PublicKey) -> RegisterRequest {
666        RegisterRequest {
667            relay_id: *relay_id,
668            public_key: public_key.clone(),
669            version: RelayVersion::current(),
670        }
671    }
672
673    /// Unpacks a signed register request for bootstrapping.
674    ///
675    /// This unpacks the embedded public key first, then verifies if the
676    /// self signature was made by that public key.  If all is well then
677    /// the data is returned.
678    pub fn bootstrap_unpack(
679        data: &[u8],
680        signature: SignatureRef<'_>,
681        start_time: DateTime<Utc>,
682        max_age: Duration,
683    ) -> Result<RegisterRequest, UnpackError> {
684        let req: RegisterRequest = serde_json::from_slice(data).map_err(UnpackError::BadPayload)?;
685        let pk = req.public_key();
686        pk.unpack(data, signature, start_time, max_age)
687    }
688
689    /// Returns the Relay ID of the registering Relay.
690    pub fn relay_id(&self) -> RelayId {
691        self.relay_id
692    }
693
694    /// Returns the new public key of registering Relay.
695    pub fn public_key(&self) -> &PublicKey {
696        &self.public_key
697    }
698
699    /// Creates a register challenge for this request.
700    pub fn into_challenge(self, secret: &[u8]) -> RegisterChallenge {
701        let state = RegisterState {
702            timestamp: Utc::now(),
703            relay_id: self.relay_id,
704            public_key: self.public_key,
705            rand: nonce(),
706        };
707
708        RegisterChallenge {
709            relay_id: self.relay_id,
710            token: SignedRegisterState::sign(state, secret),
711        }
712    }
713}
714
715/// Represents the response the server is supposed to send to a register request.
716#[derive(Serialize, Deserialize, Debug)]
717pub struct RegisterChallenge {
718    relay_id: RelayId,
719    token: SignedRegisterState,
720}
721
722impl RegisterChallenge {
723    /// Returns the Relay ID of the registering Relay.
724    pub fn relay_id(&self) -> &RelayId {
725        &self.relay_id
726    }
727
728    /// Returns the token that needs signing.
729    pub fn token(&self) -> &str {
730        self.token.as_str()
731    }
732
733    /// Creates a register response.
734    pub fn into_response(self) -> RegisterResponse {
735        RegisterResponse {
736            relay_id: self.relay_id,
737            token: self.token,
738            version: RelayVersion::current(),
739        }
740    }
741}
742
743/// Represents a response to a register challenge.
744///
745/// The response contains the same data as the register challenge. By signing this payload
746/// successfully, this Relay authenticates with the upstream.
747#[derive(Serialize, Deserialize, Debug)]
748pub struct RegisterResponse {
749    relay_id: RelayId,
750    token: SignedRegisterState,
751    #[serde(default)]
752    version: RelayVersion,
753}
754
755impl RegisterResponse {
756    /// Unpacks the register response and validates signatures.
757    ///
758    /// The Relay ID of the response must match the Relay ID in the signed register state.
759    pub fn unpack(
760        data: &[u8],
761        signature: SignatureRef<'_>,
762        secret: &[u8],
763        start_time: DateTime<Utc>,
764        max_age: Duration,
765    ) -> Result<(Self, RegisterState), UnpackError> {
766        let response: Self = serde_json::from_slice(data).map_err(UnpackError::BadPayload)?;
767        let state = response.token.unpack(secret, start_time, max_age)?;
768
769        let _verified = state
770            .public_key()
771            .verify(data, signature, start_time, max_age)?;
772
773        if response.relay_id != state.relay_id() {
774            return Err(UnpackError::RelayIdMismatch);
775        }
776
777        Ok((response, state))
778    }
779
780    /// Returns the Relay ID of the registering Relay.
781    pub fn relay_id(&self) -> RelayId {
782        self.relay_id
783    }
784
785    /// Returns the token that needs signing.
786    pub fn token(&self) -> &str {
787        self.token.as_str()
788    }
789
790    /// Returns the version of the registering Relay.
791    pub fn version(&self) -> RelayVersion {
792        self.version
793    }
794}
795
796/// A wrapper around a String that represents a signature.
797#[derive(Debug, Clone, PartialEq)]
798pub struct Signature(pub String);
799
800impl Display for Signature {
801    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802        write!(f, "{}", self.0)
803    }
804}
805
806impl Signature {
807    /// Verifies the signature against any of the provided public keys.
808    ///
809    /// Returns `true` if the signature is valid with one of the given
810    /// public keys and satisfies the timestamp constraints defined by `start_time`
811    /// and `max_age`.
812    pub fn verify_any<'a>(
813        &self,
814        public_key: &'a [PublicKey],
815        start_time: DateTime<Utc>,
816        max_age: Duration,
817    ) -> Option<(&'a PublicKey, VerifiedSignatureHeader)> {
818        public_key.iter().find_map(|p| {
819            let verified = self.verify(&[], p, start_time, max_age).ok()?;
820            Some((p, verified))
821        })
822    }
823
824    /// Verifies the signature using the specified public key.
825    ///
826    /// The signature is considered valid if it can be verified using the given
827    /// public key and its embedded timestamp falls within the valid time range,
828    /// starting from `start_time` and not exceeding `max_age`.
829    pub fn verify(
830        &self,
831        data: &[u8],
832        public_key: &PublicKey,
833        start_time: DateTime<Utc>,
834        max_age_diff: Duration,
835    ) -> Result<VerifiedSignatureHeader, SignatureError> {
836        public_key.verify(data, self.as_signature_ref(), start_time, max_age_diff)
837    }
838
839    /// Returns a borrowed view of the signature as a `SignatureRef`.
840    ///
841    /// This method provides a lightweight reference wrapper over the internal
842    /// signature data.
843    pub fn as_signature_ref(&self) -> SignatureRef<'_> {
844        SignatureRef(self.0.as_str())
845    }
846}
847
848/// A borrowed reference to a signature string used for validation.
849///
850/// `SignatureRef` provides a view into the signature data as a string slice,
851/// allowing verification to work with borrowed data without unnecessary allocations.
852/// This type is typically obtained by borrowing from an owned [`Signature`].
853pub struct SignatureRef<'a>(pub &'a str);
854
855/// Verifies a timestamp `ts` is not in the future and not expired.
856fn verify_time(
857    ts: DateTime<Utc>,
858    start_time: DateTime<Utc>,
859    max_age: Duration,
860) -> Result<DateTime<Utc>, TimeError> {
861    let diff = start_time - ts;
862    if diff > max_age {
863        Err(TimeError::TooFarInPast)
864    } else if diff < -MAX_TIME_IN_FUTURE {
865        Err(TimeError::TooFarInFuture)
866    } else {
867        Ok(ts)
868    }
869}
870
871#[cfg(test)]
872mod tests {
873    use super::*;
874
875    #[test]
876    fn test_keys() {
877        let sk: SecretKey =
878        "OvXFVm1tIUi8xDTuyHX1SSqdMc8nCt2qU9IUaH5p7oUk5pHZsdnfXNiMWiMLtSE86J3N9Peo5CBP1YQHDUkApQ"
879            .parse()
880            .unwrap();
881        let pk: PublicKey = "JOaR2bHZ31zYjFojC7UhPOidzfT3qOQgT9WEBw1JAKU"
882            .parse()
883            .unwrap();
884
885        assert_eq!(
886            sk.to_string(),
887            "OvXFVm1tIUi8xDTuyHX1SSqdMc8nCt2qU9IUaH5p7oU"
888        );
889        assert_eq!(
890            format!("{sk:#}"),
891            "OvXFVm1tIUi8xDTuyHX1SSqdMc8nCt2qU9IUaH5p7oUk5pHZsdnfXNiMWiMLtSE86J3N9Peo5CBP1YQHDUkApQ"
892        );
893        assert_eq!(
894            pk.to_string(),
895            "JOaR2bHZ31zYjFojC7UhPOidzfT3qOQgT9WEBw1JAKU"
896        );
897
898        assert_eq!(
899            "bad data".parse::<SecretKey>(),
900            Err(KeyParseError::BadEncoding)
901        );
902        assert_eq!("OvXF".parse::<SecretKey>(), Err(KeyParseError::BadKey));
903
904        assert_eq!(
905            "bad data".parse::<PublicKey>(),
906            Err(KeyParseError::BadEncoding)
907        );
908        assert_eq!("OvXF".parse::<PublicKey>(), Err(KeyParseError::BadKey));
909    }
910
911    #[test]
912    fn test_serializing() {
913        let sk: SecretKey =
914        "OvXFVm1tIUi8xDTuyHX1SSqdMc8nCt2qU9IUaH5p7oUk5pHZsdnfXNiMWiMLtSE86J3N9Peo5CBP1YQHDUkApQ"
915            .parse()
916            .unwrap();
917        let pk: PublicKey = "JOaR2bHZ31zYjFojC7UhPOidzfT3qOQgT9WEBw1JAKU"
918            .parse()
919            .unwrap();
920
921        let sk_json = serde_json::to_string(&sk).unwrap();
922        assert_eq!(sk_json, "\"OvXFVm1tIUi8xDTuyHX1SSqdMc8nCt2qU9IUaH5p7oU\"");
923
924        let pk_json = serde_json::to_string(&pk).unwrap();
925        assert_eq!(pk_json, "\"JOaR2bHZ31zYjFojC7UhPOidzfT3qOQgT9WEBw1JAKU\"");
926
927        assert_eq!(serde_json::from_str::<SecretKey>(&sk_json).unwrap(), sk);
928        assert_eq!(serde_json::from_str::<PublicKey>(&pk_json).unwrap(), pk);
929    }
930
931    #[test]
932    fn test_signatures() {
933        let (sk, pk) = generate_key_pair();
934        let data = b"Hello World!";
935
936        let sig = sk.sign(data);
937        let _verified = pk.verify(
938            data,
939            sig.as_signature_ref(),
940            Utc::now(),
941            Duration::seconds(1),
942        );
943
944        let bad_sig = "jgubwSf2wb2wuiRpgt2H9_bdDSMr88hXLp5zVuhbr65EGkSxOfT5ILIWr623twLgLd0bDgHg6xzOaUCX7XvUCw";
945        assert_eq!(
946            pk.verify(data, SignatureRef(bad_sig), Utc::now(), Duration::MAX)
947                .unwrap_err(),
948            SignatureError::Invalid
949        );
950    }
951
952    #[test]
953    fn test_registration() {
954        let max_age = Duration::minutes(15);
955
956        // initial setup
957        let relay_id = generate_relay_id();
958        let (sk, pk) = generate_key_pair();
959
960        // create a register request
961        let request = RegisterRequest::new(&relay_id, &pk);
962
963        // sign it
964        let (request_bytes, request_sig) = sk.pack(request);
965
966        // attempt to get the data through bootstrap unpacking.
967        let request = RegisterRequest::bootstrap_unpack(
968            &request_bytes,
969            request_sig.as_signature_ref(),
970            Utc::now(),
971            max_age,
972        )
973        .unwrap();
974        assert_eq!(request.relay_id(), relay_id);
975        assert_eq!(request.public_key(), &pk);
976
977        let upstream_secret = b"secret";
978
979        // create a challenge
980        let challenge = request.into_challenge(upstream_secret);
981        let challenge_token = challenge.token().to_owned();
982        assert_eq!(challenge.relay_id(), &relay_id);
983        assert!(challenge.token().len() > 40);
984
985        // check the challenge contains the expected info
986        let state = SignedRegisterState(challenge_token.clone());
987        let register_state = state.unpack(upstream_secret, Utc::now(), max_age).unwrap();
988        assert_eq!(register_state.public_key, pk);
989        assert_eq!(register_state.relay_id, relay_id);
990
991        // create a response from the challenge
992        let response = challenge.into_response();
993
994        // sign and unsign it
995        let (response_bytes, response_sig) = sk.pack(response);
996        let (response, _) = RegisterResponse::unpack(
997            &response_bytes,
998            response_sig.as_signature_ref(),
999            upstream_secret,
1000            Utc::now(),
1001            max_age,
1002        )
1003        .unwrap();
1004
1005        assert_eq!(response.relay_id(), relay_id);
1006        assert_eq!(response.token(), challenge_token);
1007        assert_eq!(response.version, LATEST_VERSION);
1008    }
1009
1010    #[test]
1011    fn test_registration_relay_id_mismatch() {
1012        let max_age = Duration::minutes(15);
1013        let upstream_secret = b"secret";
1014        let (sk, pk) = generate_key_pair();
1015
1016        let request = RegisterRequest::new(&generate_relay_id(), &pk);
1017        let challenge = request.into_challenge(upstream_secret);
1018
1019        // Respond to the challenge with a different Relay ID than the one it was issued for.
1020        let mut response = challenge.into_response();
1021        response.relay_id = generate_relay_id();
1022
1023        let (response_bytes, response_sig) = sk.pack(response);
1024        let result = RegisterResponse::unpack(
1025            &response_bytes,
1026            response_sig.as_signature_ref(),
1027            upstream_secret,
1028            Utc::now(),
1029            max_age,
1030        );
1031
1032        assert!(matches!(result, Err(UnpackError::RelayIdMismatch)));
1033    }
1034
1035    /// This is a pseudo-test to easily generate the strings used by test_auth.py
1036    /// You can copy the output to the top of the test_auth.py when there are changes in the
1037    /// exchanged authentication structures.
1038    /// It follows test_registration but instead of asserting it prints the strings
1039    #[test]
1040    #[allow(clippy::print_stdout, reason = "helper test to generate output")]
1041    fn test_generate_strings_for_test_auth_py() {
1042        let max_age = Duration::minutes(15);
1043        println!("Generating test data for test_auth.py...");
1044
1045        // initial setup
1046        let relay_id = generate_relay_id();
1047        println!("RELAY_ID = b\"{relay_id}\"");
1048        let (sk, pk) = generate_key_pair();
1049        println!("RELAY_KEY = b\"{pk}\"");
1050
1051        // create a register request
1052        let request = RegisterRequest::new(&relay_id, &pk);
1053        println!("REQUEST = b'{}'", serde_json::to_string(&request).unwrap());
1054
1055        // sign it
1056        let (request_bytes, request_sig) = sk.pack(&request);
1057        println!("REQUEST_SIG = \"{request_sig}\"");
1058
1059        // attempt to get the data through bootstrap unpacking.
1060        let request = RegisterRequest::bootstrap_unpack(
1061            &request_bytes,
1062            request_sig.as_signature_ref(),
1063            Utc::now(),
1064            max_age,
1065        )
1066        .unwrap();
1067
1068        let upstream_secret = b"secret";
1069
1070        // create a challenge
1071        let challenge = request.into_challenge(upstream_secret);
1072        let challenge_token = challenge.token().to_owned();
1073        println!("TOKEN = \"{challenge_token}\"");
1074
1075        // create a response from the challenge
1076        let response = challenge.into_response();
1077        let serialized_response = serde_json::to_string(&response).unwrap();
1078        let (_, response_sig) = sk.pack(&response);
1079
1080        println!("RESPONSE = b'{serialized_response}'");
1081        println!("RESPONSE_SIG = \"{response_sig}\"");
1082
1083        println!("RELAY_VERSION = \"{LATEST_VERSION}\"");
1084    }
1085
1086    /// Test we can still deserialize an old response that does not contain the version
1087    #[test]
1088    fn test_deserialize_old_response() {
1089        let serialized_challenge = "{\"relay_id\":\"6b7d15b8-cee2-4354-9fee-dae7ef43e434\",\"token\":\"eyJ0aW1lc3RhbXAiOjE1OTg5Njc0MzQsInJlbGF5X2lkIjoiNmI3ZDE1YjgtY2VlMi00MzU0LTlmZWUtZGFlN2VmNDNlNDM0IiwicHVibGljX2tleSI6ImtNcEdieWRIWlN2b2h6ZU1sZ2hjV3dIZDhNa3JlS0d6bF9uY2RrWlNPTWciLCJyYW5kIjoiLUViNG9Hal80dUZYOUNRRzFBVmdqTjRmdGxaNU9DSFlNOFl2d1podmlyVXhUY0tFSWYtQzhHaldsZmgwQTNlMzYxWE01dVh0RHhvN00tbWhZeXpWUWcifQ:KJUDXlwvibKNQmex-_Cu1U0FArlmoDkyqP7bYIDGrLXudfjGfCjH-UjNsUHWVDnbM28YdQ-R2MBSyF51aRLQcw\"}";
1090        let result: RegisterResponse = serde_json::from_str(serialized_challenge).unwrap();
1091        assert_eq!(
1092            result.relay_id,
1093            Uuid::parse_str("6b7d15b8-cee2-4354-9fee-dae7ef43e434").unwrap()
1094        )
1095    }
1096
1097    #[test]
1098    fn test_relay_version_current() {
1099        assert_eq!(
1100            env!("CARGO_PKG_VERSION"),
1101            RelayVersion::current().to_string()
1102        );
1103    }
1104
1105    #[test]
1106    fn test_relay_version_oldest() {
1107        // Regression test against unintentional changes.
1108        assert_eq!("0.0.0", RelayVersion::oldest().to_string());
1109    }
1110
1111    #[test]
1112    fn test_relay_version_parse() {
1113        assert_eq!(
1114            RelayVersion::new(20, 7, 0),
1115            "20.7.0-beta.0".parse().unwrap()
1116        );
1117    }
1118
1119    #[test]
1120    fn test_relay_version_oldest_supported() {
1121        assert!(RelayVersion::oldest().supported());
1122    }
1123
1124    #[test]
1125    fn test_relay_version_any_supported() {
1126        // Every version must be supported at the moment.
1127        // This test can be changed when dropping support for older versions.
1128        assert!(RelayVersion::default().supported());
1129    }
1130
1131    #[test]
1132    fn test_relay_version_from_str() {
1133        assert_eq!(RelayVersion::new(20, 7, 0), "20.7.0".parse().unwrap());
1134    }
1135
1136    #[test]
1137    fn test_verify_any() {
1138        let (_, p1) = generate_key_pair();
1139        let (_, p2) = generate_key_pair();
1140        let (s3, p3) = generate_key_pair();
1141
1142        let keys = [p1, p2, p3];
1143        let signature = s3.sign(&[]);
1144
1145        let verification = signature
1146            .verify_any(&keys, Utc::now(), Duration::seconds(10))
1147            .unwrap();
1148        assert_eq!(verification.0, &keys[2]);
1149    }
1150
1151    #[test]
1152    fn test_verify_max_age() {
1153        let pair = generate_key_pair();
1154        let start_time = Utc::now();
1155        let header = SignatureHeader {
1156            timestamp: start_time,
1157            signature_algorithm: None,
1158        };
1159        let signature = pair.0.sign_with_header(&[], &header);
1160
1161        // The signature is valid in general
1162        let verified = signature
1163            .verify(&[], &pair.1, start_time, Duration::seconds(10))
1164            .unwrap();
1165        assert_eq!(verified.timestamp(), start_time);
1166
1167        // Future timestamps within the allowed clock skew are valid.
1168        let verified = signature
1169            .verify(
1170                &[],
1171                &pair.1,
1172                start_time - MAX_TIME_IN_FUTURE,
1173                Duration::seconds(10),
1174            )
1175            .unwrap();
1176        assert_eq!(verified.timestamp(), start_time);
1177
1178        // Future timestamps beyond the allowed clock skew are invalid.
1179        let err = signature
1180            .verify(
1181                &[],
1182                &pair.1,
1183                start_time - MAX_TIME_IN_FUTURE - Duration::milliseconds(1),
1184                Duration::seconds(10),
1185            )
1186            .unwrap_err();
1187        assert_eq!(err, SignatureError::Time(TimeError::TooFarInFuture));
1188
1189        // Signature is no longer valid because too much time elapsed
1190        let err = signature
1191            .verify(
1192                &[],
1193                &pair.1,
1194                start_time + Duration::seconds(1),
1195                Duration::milliseconds(500),
1196            )
1197            .unwrap_err();
1198        assert_eq!(err, SignatureError::Time(TimeError::TooFarInPast));
1199    }
1200
1201    #[test]
1202    fn test_verify_any_max_age() {
1203        let start_time = Utc::now();
1204        let pair1 = generate_key_pair();
1205        let pair2 = generate_key_pair();
1206        let pair3 = generate_key_pair();
1207
1208        let header = SignatureHeader {
1209            timestamp: start_time,
1210            signature_algorithm: Some(SignatureAlgorithm::Regular),
1211        };
1212        let signature = pair3.0.sign_with_header(&[], &header);
1213
1214        let public_keys = &[pair1.1, pair2.1, pair3.1];
1215
1216        // Signature still valid after 1 second
1217        let v = signature
1218            .verify_any(
1219                public_keys,
1220                start_time + Duration::seconds(1),
1221                Duration::seconds(2),
1222            )
1223            .unwrap();
1224        assert_eq!(v.0, &public_keys[2]);
1225        // Signature is no longer valid because too much time elapsed
1226        assert!(
1227            signature
1228                .verify_any(
1229                    public_keys,
1230                    start_time + Duration::seconds(3),
1231                    Duration::seconds(2)
1232                )
1233                .is_none()
1234        );
1235        // Signature is valid (and verification doesn't panic) with `Duration::MAX`.
1236        let v = signature
1237            .verify_any(public_keys, start_time, Duration::MAX)
1238            .unwrap();
1239        assert_eq!(v.0, &public_keys[2]);
1240    }
1241
1242    #[test]
1243    fn test_regular_algorithm() {
1244        let (secret, public) = generate_key_pair();
1245        let signature = secret.sign(&[]);
1246        let _verified = signature
1247            .verify(&[], &public, Utc::now(), Duration::seconds(10))
1248            .unwrap();
1249    }
1250
1251    #[test]
1252    fn test_prehashed_algorithm() {
1253        let (secret, public) = generate_key_pair();
1254        let header = SignatureHeader {
1255            timestamp: Utc::now(),
1256            signature_algorithm: Some(SignatureAlgorithm::Prehashed),
1257        };
1258        let signature = secret.sign_with_header(&[], &header);
1259        let _verified = signature
1260            .verify(&[], &public, Utc::now(), Duration::seconds(10))
1261            .unwrap();
1262    }
1263
1264    #[test]
1265    fn test_legacy_signature_can_be_verified() {
1266        // TestHeader struct is used to mimic old version that do not have
1267        // the `signature_variant` fields.
1268        #[derive(Serialize)]
1269        struct TestHeader {
1270            #[serde(rename = "t")]
1271            timestamp: Option<DateTime<Utc>>,
1272        }
1273        let header = serde_json::to_string(&TestHeader {
1274            timestamp: Some(Utc::now()),
1275        })
1276        .unwrap();
1277
1278        let data: &[u8] = &[];
1279        let (secret, public) = generate_key_pair();
1280        let mut to_sign = header.clone().into_bytes();
1281        to_sign.push(b'\x00');
1282        to_sign.extend_from_slice(data);
1283        let sig = secret.inner.sign(to_sign.as_slice());
1284        let mut sig_encoded = BASE64URL_NOPAD.encode(sig.to_bytes().as_slice());
1285        sig_encoded.push('.');
1286        sig_encoded.push_str(BASE64URL_NOPAD.encode(header.as_bytes()).as_str());
1287
1288        let _verified = public
1289            .verify(
1290                data,
1291                SignatureRef(sig_encoded.as_str()),
1292                Utc::now(),
1293                Duration::seconds(3),
1294            )
1295            .unwrap();
1296    }
1297
1298    #[test]
1299    fn test_parse_private_pem() {
1300        let s = r#"-----BEGIN PRIVATE KEY-----
1301MC4CAQAwBQYDK2VwBCIEIPBFGz4q5QW27KNimPqb3dr9/pO4o6XR7QIKE1rxGAIK
1302-----END PRIVATE KEY-----"#;
1303        let key: SecretKey = s.parse().unwrap();
1304        assert_eq!(
1305            key.to_string(),
1306            "8EUbPirlBbbso2KY-pvd2v3-k7ijpdHtAgoTWvEYAgo"
1307        );
1308    }
1309
1310    #[test]
1311    fn test_parse_public_pem() {
1312        let s = r#"-----BEGIN PUBLIC KEY-----
1313MCowBQYDK2VwAyEATQCO/kpf2pyVjQyTuzr2qhi8IBxmBm2apZrUjJALYeA=
1314-----END PUBLIC KEY-----"#;
1315        let key: PublicKey = s.parse().unwrap();
1316        assert_eq!(
1317            key.to_string(),
1318            "TQCO_kpf2pyVjQyTuzr2qhi8IBxmBm2apZrUjJALYeA"
1319        );
1320    }
1321}