1mod endpoints;
46mod keys;
47mod model;
48pub mod verify;
49
50use std::future::Future;
51use std::pin::Pin;
52
53use fastauth_core::plugin_prelude::*;
54use fastauth_core::routes::GetSession;
55use http::header::ACCESS_CONTROL_EXPOSE_HEADERS;
56use http::{HeaderName, HeaderValue};
57use serde_json::{Map, Value};
58
59pub use endpoints::{
60 GetJwks, GetToken, Jwks, RotateKeys, RotatedKey, SignJwt, SignJwtInput, TokenOutput, VerifyJwt,
61 VerifyJwtInput, VerifyJwtOutput,
62};
63pub use jsonwebtoken;
64pub use model::JsonWebKey;
65pub use verify::{JwksVerifier, VerifyError};
66
67pub const SET_AUTH_JWT: &str = "set-auth-jwt";
69
70#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
72pub enum JwtAlgorithm {
73 #[default]
75 EdDSA,
76 ES256,
78 RS256,
80}
81
82impl JwtAlgorithm {
83 pub fn name(self) -> &'static str {
85 match self {
86 JwtAlgorithm::EdDSA => "EdDSA",
87 JwtAlgorithm::ES256 => "ES256",
88 JwtAlgorithm::RS256 => "RS256",
89 }
90 }
91}
92
93type Claims = Map<String, Value>;
94type DefinePayload = Arc<
95 dyn Fn(SessionView) -> Pin<Box<dyn Future<Output = Result<Claims, AuthError>> + Send>>
96 + Send
97 + Sync,
98>;
99
100#[derive(Clone)]
102pub struct Jwt {
103 alg: JwtAlgorithm,
104 issuer: Option<String>,
105 audience: Option<String>,
106 expiration_time: Duration,
107 rotation_interval: Option<Duration>,
108 grace_period: Duration,
109 set_jwt_header: bool,
110 define_payload: Option<DefinePayload>,
111}
112
113impl std::fmt::Debug for Jwt {
114 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115 f.debug_struct("Jwt")
116 .field("alg", &self.alg)
117 .field("issuer", &self.issuer)
118 .field("audience", &self.audience)
119 .field("expiration_time", &self.expiration_time)
120 .field("rotation_interval", &self.rotation_interval)
121 .field("grace_period", &self.grace_period)
122 .finish_non_exhaustive()
123 }
124}
125
126impl Default for Jwt {
127 fn default() -> Self {
128 Self {
129 alg: JwtAlgorithm::EdDSA,
130 issuer: None,
131 audience: None,
132 expiration_time: Duration::minutes(15),
133 rotation_interval: None,
134 grace_period: Duration::days(30),
135 set_jwt_header: true,
136 define_payload: None,
137 }
138 }
139}
140
141impl Jwt {
142 pub fn new() -> Self {
143 Self::default()
144 }
145
146 pub fn algorithm(mut self, alg: JwtAlgorithm) -> Self {
149 self.alg = alg;
150 self
151 }
152
153 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
155 self.issuer = Some(issuer.into());
156 self
157 }
158
159 pub fn audience(mut self, audience: impl Into<String>) -> Self {
161 self.audience = Some(audience.into());
162 self
163 }
164
165 pub fn expiration_time(mut self, ttl: Duration) -> Self {
167 self.expiration_time = ttl;
168 self
169 }
170
171 pub fn rotation_interval(mut self, interval: Duration) -> Self {
174 self.rotation_interval = Some(interval);
175 self
176 }
177
178 pub fn grace_period(mut self, grace: Duration) -> Self {
181 self.grace_period = grace;
182 self
183 }
184
185 pub fn disable_jwt_header(mut self) -> Self {
188 self.set_jwt_header = false;
189 self
190 }
191
192 pub fn define_payload<F, Fut>(mut self, define: F) -> Self
206 where
207 F: Fn(SessionView) -> Fut + Send + Sync + 'static,
208 Fut: Future<Output = Result<Map<String, Value>, AuthError>> + Send + 'static,
209 {
210 self.define_payload = Some(Arc::new(move |session| Box::pin(define(session))));
211 self
212 }
213}
214
215impl Plugin for Jwt {
216 const ID: &'static str = "jwt";
217 type Requires = ();
218 type UserFields = ();
219 type SessionFields = ();
220
221 fn schema(&self, schema: &mut SchemaBuilder) {
222 schema.model::<JsonWebKey>();
223 }
224
225 fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
226 app.endpoint(GetJwks)
227 .endpoint(GetToken)
228 .server_endpoint::<SignJwt>()
229 .server_endpoint::<VerifyJwt>()
230 .server_endpoint::<RotateKeys>();
231 if self.set_jwt_header {
232 app.hook::<GetSession>().after(set_jwt_header);
233 }
234 }
235}
236
237async fn set_jwt_header<D: Adapter>(
238 ctx: HookCtx<D>,
239 output: Option<Value>,
240) -> Result<After<Option<Value>>, AuthError> {
241 if let Some(session) = ctx.session() {
242 let token = keys::session_token(&ctx, ctx.plugin::<Jwt>(), session).await?;
243 let value = HeaderValue::from_str(&token).map_err(AuthError::internal)?;
244 ctx.set_header(HeaderName::from_static(SET_AUTH_JWT), value);
245 ctx.set_header(
246 ACCESS_CONTROL_EXPOSE_HEADERS,
247 HeaderValue::from_static(SET_AUTH_JWT),
248 );
249 }
250 Ok(After::Continue(output))
251}
252
253pub trait JwtExt: AuthInstance + Sized {
255 fn jwt<I>(&self) -> JwtApi<'_, Self>
256 where
257 Self: HasPlugin<Jwt, I>,
258 {
259 JwtApi {
260 auth: self,
261 headers: HeaderMap::new(),
262 }
263 }
264}
265
266impl<A: AuthInstance> JwtExt for A {}
267
268pub struct JwtApi<'a, A> {
270 auth: &'a A,
271 headers: HeaderMap,
272}
273
274impl<A> std::fmt::Debug for JwtApi<'_, A> {
275 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276 f.write_str("JwtApi")
277 }
278}
279
280impl<A: AuthInstance> JwtApi<'_, A> {
281 pub fn headers(mut self, headers: &HeaderMap) -> Self {
283 self.headers = headers.clone();
284 self
285 }
286
287 async fn call<E: Endpoint<A::Db>>(
288 &self,
289 endpoint: &E,
290 input: E::Input,
291 ) -> Result<E::Output, AuthError> {
292 Ok(self
293 .auth
294 .api()
295 .headers(&self.headers)
296 .call(endpoint, input)
297 .await?
298 .data)
299 }
300
301 pub async fn token(&self) -> Result<String, AuthError> {
304 Ok(self.call(&GetToken, Map::new()).await?.token)
305 }
306
307 pub async fn sign(&self, claims: Map<String, Value>) -> Result<String, AuthError> {
309 Ok(self
310 .call(&SignJwt, SignJwtInput { payload: claims })
311 .await?
312 .token)
313 }
314
315 pub async fn verify(&self, token: &str) -> Result<Option<Map<String, Value>>, AuthError> {
318 let input = VerifyJwtInput {
319 token: token.to_owned(),
320 issuer: None,
321 };
322 Ok(self.call(&VerifyJwt, input).await?.payload)
323 }
324
325 pub async fn jwks(&self) -> Result<Jwks, AuthError> {
327 self.call(&GetJwks, Map::new()).await
328 }
329
330 pub async fn rotate(&self) -> Result<Id, AuthError> {
333 Ok(self.call(&RotateKeys, Empty {}).await?.kid)
334 }
335}