1use std::sync::Arc;
2use std::time::{Duration, SystemTime, UNIX_EPOCH};
3
4use anyhow::{Result, anyhow};
5use chrono::{DateTime, Utc};
6use hmac::{Hmac, Mac};
7use jsonwebtoken::crypto::{CryptoProvider, JwkUtils, JwtSigner, JwtVerifier};
8use jsonwebtoken::errors::{ErrorKind, Result as JwtResult, new_error};
9use jsonwebtoken::signature::{Signer, Verifier};
10use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
11use serde::{Deserialize, Serialize};
12use sha2::{Sha256, Sha384, Sha512};
13use uuid::Uuid;
14
15use super::store::TokenStore;
16
17type HmacSha256 = Hmac<Sha256>;
18type HmacSha384 = Hmac<Sha384>;
19type HmacSha512 = Hmac<Sha512>;
20
21macro_rules! define_hmac_signer {
22 ($name:ident, $alg:expr, $hmac_type:ty) => {
23 struct $name($hmac_type);
24
25 impl $name {
26 fn new(encoding_key: &EncodingKey) -> JwtResult<Self> {
27 let inner = <$hmac_type>::new_from_slice(encoding_key.try_get_hmac_secret()?)
28 .map_err(|_| new_error(ErrorKind::InvalidKeyFormat))?;
29 Ok(Self(inner))
30 }
31 }
32
33 impl Signer<Vec<u8>> for $name {
34 fn try_sign(
35 &self,
36 msg: &[u8],
37 ) -> std::result::Result<Vec<u8>, jsonwebtoken::signature::Error> {
38 let mut signer = self.0.clone();
39 signer.update(msg);
40 Ok(signer.finalize().into_bytes().to_vec())
41 }
42 }
43
44 impl JwtSigner for $name {
45 fn algorithm(&self) -> Algorithm {
46 $alg
47 }
48 }
49 };
50}
51
52macro_rules! define_hmac_verifier {
53 ($name:ident, $alg:expr, $hmac_type:ty) => {
54 struct $name($hmac_type);
55
56 impl $name {
57 fn new(decoding_key: &DecodingKey) -> JwtResult<Self> {
58 let inner = <$hmac_type>::new_from_slice(decoding_key.try_get_hmac_secret()?)
59 .map_err(|_| new_error(ErrorKind::InvalidKeyFormat))?;
60 Ok(Self(inner))
61 }
62 }
63
64 impl Verifier<Vec<u8>> for $name {
65 fn verify(
66 &self,
67 msg: &[u8],
68 signature: &Vec<u8>,
69 ) -> std::result::Result<(), jsonwebtoken::signature::Error> {
70 let mut verifier = self.0.clone();
71 verifier.update(msg);
72 verifier
73 .verify_slice(signature)
74 .map_err(jsonwebtoken::signature::Error::from_source)
75 }
76 }
77
78 impl JwtVerifier for $name {
79 fn algorithm(&self) -> Algorithm {
80 $alg
81 }
82 }
83 };
84}
85
86define_hmac_signer!(Hs256Signer, Algorithm::HS256, HmacSha256);
87define_hmac_signer!(Hs384Signer, Algorithm::HS384, HmacSha384);
88define_hmac_signer!(Hs512Signer, Algorithm::HS512, HmacSha512);
89define_hmac_verifier!(Hs256Verifier, Algorithm::HS256, HmacSha256);
90define_hmac_verifier!(Hs384Verifier, Algorithm::HS384, HmacSha384);
91define_hmac_verifier!(Hs512Verifier, Algorithm::HS512, HmacSha512);
92
93static HMAC_ONLY_JWT_PROVIDER: CryptoProvider = CryptoProvider {
94 signer_factory: hmac_signer_factory,
95 verifier_factory: hmac_verifier_factory,
96 jwk_utils: JwkUtils::new_unimplemented(),
97};
98
99fn hmac_signer_factory(algorithm: &Algorithm, key: &EncodingKey) -> JwtResult<Box<dyn JwtSigner>> {
100 match algorithm {
101 Algorithm::HS256 => Ok(Box::new(Hs256Signer::new(key)?)),
102 Algorithm::HS384 => Ok(Box::new(Hs384Signer::new(key)?)),
103 Algorithm::HS512 => Ok(Box::new(Hs512Signer::new(key)?)),
104 _ => Err(new_error(ErrorKind::InvalidAlgorithm)),
105 }
106}
107
108fn hmac_verifier_factory(
109 algorithm: &Algorithm,
110 key: &DecodingKey,
111) -> JwtResult<Box<dyn JwtVerifier>> {
112 match algorithm {
113 Algorithm::HS256 => Ok(Box::new(Hs256Verifier::new(key)?)),
114 Algorithm::HS384 => Ok(Box::new(Hs384Verifier::new(key)?)),
115 Algorithm::HS512 => Ok(Box::new(Hs512Verifier::new(key)?)),
116 _ => Err(new_error(ErrorKind::InvalidAlgorithm)),
117 }
118}
119
120fn install_hmac_jwt_provider() {
121 let _ = HMAC_ONLY_JWT_PROVIDER.install_default();
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct TokenClaims {
127 pub sub: String,
128 pub iss: String,
129 pub exp: usize,
130 pub iat: usize,
131 pub jti: String,
132 pub device_id: Option<String>,
133 pub tenant_id: Option<String>,
134}
135
136pub struct TokenService {
138 secret: String,
139 issuer: String,
140 ttl: Duration,
141 encoding_key: EncodingKey,
142 decoding_key: DecodingKey,
143 store: Option<Arc<dyn TokenStore>>,
144}
145
146impl TokenService {
147 pub fn new(secret: impl Into<String>, issuer: impl Into<String>, ttl_seconds: u64) -> Self {
149 install_hmac_jwt_provider();
150
151 let secret = secret.into();
152 let issuer = issuer.into();
153 let encoding_key = EncodingKey::from_secret(secret.as_bytes());
154 let decoding_key = DecodingKey::from_secret(secret.as_bytes());
155 Self {
156 secret,
157 issuer,
158 ttl: Duration::from_secs(ttl_seconds.max(60)),
159 encoding_key,
160 decoding_key,
161 store: None,
162 }
163 }
164
165 pub fn with_store(mut self, store: Arc<dyn TokenStore>) -> Self {
167 self.store = Some(store);
168 self
169 }
170
171 pub fn generate_token(
173 &self,
174 user_id: &str,
175 device_id: Option<&str>,
176 tenant_id: Option<&str>,
177 ) -> Result<String> {
178 let now = SystemTime::now()
179 .duration_since(UNIX_EPOCH)
180 .map_err(|err| anyhow!("system time error: {err}"))?;
181 let iat = now.as_secs() as usize;
182 let exp = (now + self.ttl).as_secs() as usize;
183
184 let claims = TokenClaims {
185 sub: user_id.to_string(),
186 iss: self.issuer.clone(),
187 exp,
188 iat,
189 jti: Uuid::new_v4().to_string(),
190 device_id: device_id.map(|v| v.to_string()),
191 tenant_id: tenant_id.map(|v| v.to_string()),
192 };
193
194 let token = encode(&Header::default(), &claims, &self.encoding_key)
195 .map_err(|err| anyhow!("failed to encode token: {err}"))?;
196
197 if let Some(store) = self.store.as_ref() {
198 store.register(&claims.sub, &claims.jti, self.ttl)?;
199 }
200
201 Ok(token)
202 }
203
204 pub fn validate_token(&self, token: &str) -> Result<TokenClaims> {
206 let claims = self.decode_claims(token)?;
207
208 if let Some(store) = self.store.as_ref()
209 && store.is_revoked(&claims.jti)?
210 {
211 return Err(anyhow!("token revoked"));
212 }
213
214 Ok(claims)
215 }
216
217 pub fn ttl(&self) -> Duration {
219 self.ttl
220 }
221
222 pub fn issuer(&self) -> &str {
224 &self.issuer
225 }
226
227 pub fn secret(&self) -> &str {
229 &self.secret
230 }
231
232 fn decode_claims(&self, token: &str) -> Result<TokenClaims> {
233 let mut validation = Validation::new(jsonwebtoken::Algorithm::HS256);
234 validation.set_issuer(&[self.issuer.as_str()]);
235
236 decode::<TokenClaims>(token, &self.decoding_key, &validation)
237 .map(|data| data.claims)
238 .map_err(|err| anyhow!("invalid token: {err}"))
239 }
240}
241
242impl TokenClaims {
243 pub fn issued_at(&self) -> DateTime<Utc> {
244 DateTime::<Utc>::from_timestamp(self.iat as i64, 0).unwrap_or_else(Utc::now)
245 }
246
247 pub fn expires_at(&self) -> DateTime<Utc> {
248 DateTime::<Utc>::from_timestamp(self.exp as i64, 0).unwrap_or_else(Utc::now)
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use super::TokenService;
255
256 #[test]
257 fn hs256_token_roundtrip_uses_hmac_provider() {
258 let service = TokenService::new("insecure-secret", "flare-im-core", 3600);
259 let token = service
260 .generate_token("user-1", Some("device-1"), Some("tenant-1"))
261 .expect("token should be generated with HMAC provider");
262
263 let claims = service
264 .validate_token(&token)
265 .expect("token should be validated with HMAC provider");
266
267 assert_eq!(claims.sub, "user-1");
268 assert_eq!(claims.iss, "flare-im-core");
269 assert_eq!(claims.device_id.as_deref(), Some("device-1"));
270 assert_eq!(claims.tenant_id.as_deref(), Some("tenant-1"));
271 }
272}