Skip to main content

scion_sdk_token_validator/
validator.rs

1// Copyright 2025 Anapaya Systems
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//   http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//! Token validator and token trait.
15
16use std::{marker::PhantomData, time::SystemTime};
17
18use ed25519_dalek::pkcs8::{EncodePrivateKey, EncodePublicKey};
19use jsonwebtoken::{
20    Algorithm, DecodingKey, TokenData, Validation, decode, errors::Error as JwtError,
21};
22use pem::Pem;
23use serde::Deserialize;
24use thiserror::Error;
25
26/// Token is the interface for tokens. It provides methods to get the expiration
27/// time and the required claims.
28pub trait Token: std::fmt::Debug + Send + Clone + 'static {
29    /// Returns the ID of the token.
30    fn id(&self) -> String;
31    /// Returns the absolute expiration time of the token.
32    fn exp_time(&self) -> SystemTime;
33    /// Returns the required claims for the token. This is enforced during
34    /// JWT validation.
35    fn required_claims() -> Vec<&'static str>;
36}
37
38/// TokenValidator is the interface to validate a JWT token and extract the
39/// claims.
40pub trait TokenValidator<C>: Send + Sync
41where
42    C: for<'de> Deserialize<'de> + Token + Clone,
43{
44    /// Validates the token and returns the claims if the token is valid.
45    fn validate(&self, now: SystemTime, token: &str) -> Result<C, TokenValidatorError>;
46}
47
48/// Token validation errors.
49#[derive(Clone, Debug, Error, PartialEq)]
50#[non_exhaustive]
51pub enum TokenValidatorError {
52    /// JWT errors.
53    #[error("JWT error: {0}")]
54    JwtError(JwtError),
55    /// JWT signature is invalid.
56    #[error("JWT signature is invalid")]
57    JwtSignatureInvalid(),
58    /// Expired token error.
59    #[error("token expired: {0:?}")]
60    TokenExpired(SystemTime),
61}
62
63/// A validator for JWT tokens using the EdDSA algorithm. The validator also
64/// checks for the required claims in the token and checks if the token is
65/// expired.
66#[derive(Clone)]
67pub struct Validator<C>
68where
69    C: for<'de> Deserialize<'de> + Token,
70{
71    public_key: DecodingKey,
72    validator: Validation,
73
74    // Here, we need to pull a type-foo trick to make `Validator: Sync`, even
75    // though `C` is `!Sync`: `fn() -> C` is `Sync`, even if `C: !Sync`.
76    _marker: PhantomData<fn() -> C>,
77}
78
79impl<C> Validator<C>
80where
81    C: for<'de> Deserialize<'de> + Token,
82{
83    /// Creates a new token validator.
84    ///
85    /// # Arguments
86    /// * `public_key`: The public key to verify the token signature.
87    /// * `audience`: Optional audience to validate the token against. If `None`, the audience is
88    ///   not validated.
89    pub fn new(public_key: DecodingKey, audience: Option<&[&str]>) -> Self {
90        let mut validator = Validation::new(Algorithm::EdDSA);
91        validator.set_required_spec_claims(&C::required_claims());
92        if let Some(audience) = audience {
93            validator.set_audience(audience);
94        } else {
95            validator.validate_aud = false;
96        }
97
98        Self {
99            public_key,
100            validator,
101            _marker: PhantomData,
102        }
103    }
104}
105
106impl<C> TokenValidator<C> for Validator<C>
107where
108    C: for<'de> Deserialize<'de> + Token,
109{
110    fn validate(&self, now: SystemTime, token: &str) -> Result<C, TokenValidatorError> {
111        let token_data: TokenData<C> = decode::<C>(token, &self.public_key, &self.validator)?;
112
113        let token_exp = token_data.claims.exp_time();
114        if now > token_exp {
115            return Err(TokenValidatorError::TokenExpired(token_exp));
116        }
117
118        Ok(token_data.claims)
119    }
120}
121
122/// Returns constant key pair in PEM format for testing purposes.
123pub fn insecure_const_ed25519_key_pair_pem() -> (Pem, Pem) {
124    let signing_key = insecure_const_ed25519_signing_key();
125
126    let public_key = ed25519_dalek::pkcs8::PublicKeyBytes(*signing_key.verifying_key().as_bytes());
127
128    let kp = ed25519_dalek::pkcs8::KeypairBytes {
129        secret_key: *signing_key.as_bytes(),
130        public_key: Some(public_key),
131    };
132
133    let private_pem = pem::Pem::new("PRIVATE KEY", kp.to_pkcs8_der().unwrap().as_bytes());
134    let public_pem = pem::Pem::new(
135        "PUBLIC KEY",
136        public_key.to_public_key_der().unwrap().as_bytes(),
137    );
138
139    (private_pem, public_pem)
140}
141
142/// Returns a constant Ed25519 signing key for testing purposes.
143pub fn insecure_const_ed25519_signing_key() -> ed25519_dalek::SigningKey {
144    let seed = [43u8; 32];
145    ed25519_dalek::SigningKey::from_bytes(&seed)
146}
147
148impl From<JwtError> for TokenValidatorError {
149    fn from(value: JwtError) -> Self {
150        use jsonwebtoken::errors::*;
151        // For now, we only explicitly expose signature errors and don't commit
152        // to report all other jsonwebtoken-errors, so we can swap out the
153        // underlying implementation.
154        if let ErrorKind::InvalidSignature = value.kind() {
155            return TokenValidatorError::JwtSignatureInvalid();
156        }
157        TokenValidatorError::JwtError(value)
158    }
159}