Skip to main content

pwt/
lib.rs

1mod errors;
2mod key;
3mod signing;
4
5pub mod pb {
6    include!(concat!(env!("OUT_DIR"), "/pwt.rs"));
7}
8
9pub use errors::{PwtError, SigningMethodError, TokenValidationError};
10pub use key::Key;
11pub use signing::{
12    SigningMethod, SigningMethodEdDSA, SigningMethodHS256, SigningMethodRS256,
13    SigningMethodRegistry,
14};
15
16use base64::engine::general_purpose::URL_SAFE_NO_PAD;
17use base64::Engine;
18use prost::Message;
19use std::sync::Arc;
20
21pub use pb::{TokenBody, TokenHeader};
22
23/// KeyFunc resolves the signing key for the provided token during parsing.
24pub type KeyFunc =
25    dyn Fn(&Token) -> Result<Key, Box<dyn std::error::Error + Send + Sync>> + Send + Sync;
26
27/// Token is a Protobuf Web Token consisting of a header, body, and signing method.
28#[derive(Clone)]
29pub struct Token {
30    pub header: TokenHeader,
31    pub body: TokenBody,
32    pub method: Arc<dyn SigningMethod>,
33}
34
35impl Token {
36    /// new creates a token using version "1.0" with the provided signing method.
37    pub fn new<M: SigningMethod + 'static>(method: M, body: TokenBody) -> Self {
38        Self::new_with_method(Arc::new(method), body, Some("1.0"))
39    }
40
41    /// new_versioned creates a token with the supplied version string.
42    pub fn new_versioned<M: SigningMethod + 'static>(
43        method: M,
44        body: TokenBody,
45        version: &str,
46    ) -> Self {
47        Self::new_with_method(Arc::new(method), body, Some(version))
48    }
49
50    /// new_with_claims mirrors jwt.NewWithClaims for compatibility.
51    pub fn new_with_claims<M: SigningMethod + 'static>(method: M, body: TokenBody) -> Self {
52        Self::new_with_method(Arc::new(method), body, None)
53    }
54
55    /// new_with_method creates a token using the provided signing method instance.
56    pub fn new_with_method(
57        method: Arc<dyn SigningMethod>,
58        body: TokenBody,
59        version: Option<&str>,
60    ) -> Self {
61        let mut header = TokenHeader::default();
62        if let Some(version) = version {
63            header.version = version.to_string();
64        }
65        header.alg = method.alg().to_string();
66
67        Token {
68            header,
69            body,
70            method,
71        }
72    }
73
74    /// signed_string marshals the token and returns a signed compact string.
75    pub fn signed_string(&self, key: &Key) -> Result<String, PwtError> {
76        let header_bytes = encode_proto(&self.header).map_err(PwtError::HeaderEncodingFailed)?;
77        let payload_bytes = encode_proto(&self.body).map_err(PwtError::PayloadEncodingFailed)?;
78        let signing_data = [header_bytes.as_slice(), payload_bytes.as_slice()].concat();
79
80        let signature = self
81            .method
82            .sign(&signing_data, key)
83            .map_err(PwtError::SigningFailed)?;
84
85        Ok(format!(
86            "{}.{}.{}",
87            base64_url_encode(&header_bytes),
88            base64_url_encode(&payload_bytes),
89            base64_url_encode(&signature)
90        ))
91    }
92
93    /// parse decodes token_string and verifies the signature using key_func.
94    pub fn parse(token_string: &str, key_func: Option<&KeyFunc>) -> Result<Self, PwtError> {
95        let segments: Vec<&str> = token_string.split('.').collect();
96        if segments.len() != 3 {
97            return Err(PwtError::InvalidSegmentCount(segments.len()));
98        }
99
100        let header_bytes =
101            base64_url_decode(segments[0]).map_err(|_| PwtError::Base64DecodingFailed("header"))?;
102        let header =
103            TokenHeader::decode(header_bytes.as_slice()).map_err(PwtError::HeaderDecodingFailed)?;
104
105        let method = SigningMethodRegistry::method(&header.alg)
106            .ok_or_else(|| PwtError::UnsupportedAlgorithm(header.alg.clone()))?;
107
108        let payload_bytes = base64_url_decode(segments[1])
109            .map_err(|_| PwtError::Base64DecodingFailed("payload"))?;
110        let body =
111            TokenBody::decode(payload_bytes.as_slice()).map_err(PwtError::PayloadDecodingFailed)?;
112
113        let key_func = key_func.ok_or(PwtError::KeyFuncNil)?;
114        let token = Token {
115            header,
116            body,
117            method: method.clone(),
118        };
119        let key = key_func(&token).map_err(PwtError::KeyFuncError)?;
120
121        let signature = base64_url_decode(segments[2])
122            .map_err(|err| PwtError::SignatureDecodingFailed(Box::new(err)))?;
123
124        let signing_data = [header_bytes.as_slice(), payload_bytes.as_slice()].concat();
125        method
126            .verify(&signing_data, &signature, &key)
127            .map_err(PwtError::SignatureVerificationFailed)?;
128
129        token
130            .body
131            .valid()
132            .map_err(PwtError::TokenValidationFailed)?;
133
134        Ok(token)
135    }
136}
137
138impl TokenBody {
139    /// valid validates time-based claims with no leeway.
140    pub fn valid(&self) -> Result<(), TokenValidationError> {
141        self.valid_with_leeway(0)
142    }
143
144    /// valid_with_leeway validates time-based claims with an allowed clock skew.
145    pub fn valid_with_leeway(&self, leeway_seconds: i64) -> Result<(), TokenValidationError> {
146        let leeway = leeway_seconds.abs();
147        let now = unix_timestamp();
148
149        if self.exp != 0 && now >= self.exp + leeway {
150            return Err(TokenValidationError::TokenExpired);
151        }
152
153        if self.nbf != 0 && now < self.nbf - leeway {
154            return Err(TokenValidationError::TokenNotValidYet);
155        }
156
157        Ok(())
158    }
159}
160
161fn encode_proto<M: Message>(message: &M) -> Result<Vec<u8>, prost::EncodeError> {
162    let mut buf = Vec::new();
163    message.encode(&mut buf)?;
164    Ok(buf)
165}
166
167fn unix_timestamp() -> i64 {
168    let now = std::time::SystemTime::now()
169        .duration_since(std::time::UNIX_EPOCH)
170        .unwrap_or_default();
171    now.as_secs() as i64
172}
173
174fn base64_url_encode(data: &[u8]) -> String {
175    URL_SAFE_NO_PAD.encode(data)
176}
177
178fn base64_url_decode(value: &str) -> Result<Vec<u8>, base64::DecodeError> {
179    URL_SAFE_NO_PAD.decode(value.as_bytes())
180}