Skip to main content

fastauth_core/
plugin.rs

1//! The plugin trait and the registration API plugins (and the app) use in `init`.
2
3use std::any::{Any, TypeId, type_name};
4use std::collections::HashMap;
5use std::future::Future;
6use std::marker::PhantomData;
7use std::sync::Arc;
8
9use http::Method;
10
11use crate::adapter::Adapter;
12use crate::endpoint::{
13    After, Before, BoxFuture, Ctx, Endpoint, EndpointHooks, Erased, ErasedAfter, ErasedBefore,
14    ErasedClaimHook, ErasedEndpoint, ErasedEventHandler, ErasedResolver, ErasedResponseHook,
15    ErasedSessionGate, ErasedSessionHook, ErasedUserInputHook, FixedExpiry, Gate, HookCtx,
16    OwnedGate, Response, SessionResolver, SessionUse, SignInAttempt,
17};
18use crate::error::{AuthError, ErrorCodes};
19use crate::events::Event;
20use crate::internal::{Claim, UserInput};
21use crate::model::Fields;
22use crate::rate_limit::{Limit, Rule};
23use crate::schema::SchemaBuilder;
24use crate::session::SessionView;
25
26/// A fastauth plugin. See `docs/reference/01-plugin-authoring.md`.
27pub trait Plugin: Send + Sync + Sized + 'static {
28    /// Unique id, used in error messages, schema ownership and derived keys.
29    const ID: &'static str;
30    /// Plugins that must be registered before this one, as a tuple: `()`, `(Organization,)`.
31    type Requires;
32    /// Columns this plugin adds to `user`; `()` for none.
33    type UserFields: Fields;
34    /// Columns this plugin adds to `session`; `()` for none.
35    type SessionFields: Fields;
36
37    /// Adds tables (`schema.model::<M>()`) or columns. `UserFields` and `SessionFields` are
38    /// added automatically.
39    fn schema(&self, schema: &mut SchemaBuilder) {
40        let _ = schema;
41    }
42
43    /// Registers endpoints, hooks, gates, resolvers, events, rate limits and error codes.
44    /// Runs once, inside `.build()`.
45    fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
46        let _ = app;
47    }
48}
49
50pub(crate) struct RouteDef<D> {
51    pub method: Method,
52    pub path: &'static str,
53    pub owner: &'static str,
54    pub type_id: TypeId,
55    pub endpoint: Arc<dyn ErasedEndpoint<D>>,
56}
57
58/// Everything registered during `.build()`, before it is frozen into `Shared`.
59pub struct Registry<D> {
60    pub(crate) schema: SchemaBuilder,
61    pub(crate) plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
62    pub(crate) routes: Vec<RouteDef<D>>,
63    pub(crate) hooks: HashMap<TypeId, EndpointHooks<D>>,
64    pub(crate) hook_targets: Vec<(TypeId, &'static str, &'static str)>,
65    pub(crate) server_endpoints: Vec<TypeId>,
66    pub(crate) gates: Vec<OwnedGate<D>>,
67    pub(crate) resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
68    pub(crate) response_hooks: Vec<ErasedResponseHook<D>>,
69    pub(crate) session_hooks: Vec<ErasedSessionHook<D>>,
70    pub(crate) session_gates: Vec<ErasedSessionGate<D>>,
71    pub(crate) fixed_expiry: Vec<FixedExpiry>,
72    pub(crate) claim_hooks: Vec<ErasedClaimHook<D>>,
73    pub(crate) user_input_hooks: Vec<ErasedUserInputHook<D>>,
74    pub(crate) events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
75    pub(crate) rate_rules: Vec<Rule>,
76    pub(crate) error_codes: Vec<(&'static str, &'static str)>,
77    pub(crate) errors: Vec<String>,
78    pub(crate) owner: &'static str,
79}
80
81impl<D: Adapter> Registry<D> {
82    pub(crate) fn new() -> Self {
83        Self {
84            schema: SchemaBuilder::new(),
85            plugins: HashMap::new(),
86            routes: Vec::new(),
87            hooks: HashMap::new(),
88            hook_targets: Vec::new(),
89            server_endpoints: Vec::new(),
90            gates: Vec::new(),
91            resolvers: Vec::new(),
92            response_hooks: Vec::new(),
93            session_hooks: Vec::new(),
94            session_gates: Vec::new(),
95            fixed_expiry: Vec::new(),
96            claim_hooks: Vec::new(),
97            user_input_hooks: Vec::new(),
98            events: HashMap::new(),
99            rate_rules: Vec::new(),
100            error_codes: Vec::new(),
101            errors: Vec::new(),
102            owner: "core",
103        }
104    }
105
106    pub(crate) fn set_owner(&mut self, owner: &'static str) {
107        self.owner = owner;
108        self.schema.owner = owner;
109    }
110
111    pub(crate) fn register_plugin<P: Plugin>(&mut self, plugin: &Arc<P>) {
112        if self
113            .plugins
114            .insert(TypeId::of::<P>(), plugin.clone())
115            .is_some()
116        {
117            self.errors
118                .push(format!("plugin `{}` is registered twice", P::ID));
119            return;
120        }
121        let previous = self.owner;
122        self.set_owner(P::ID);
123        self.schema.extend("user", P::UserFields::columns());
124        self.schema.extend("session", P::SessionFields::columns());
125        plugin.schema(&mut self.schema);
126        plugin.init(&mut PluginBuilder { registry: self });
127        self.set_owner(previous);
128    }
129}
130
131/// What `Plugin::init` (and `Builder::configure`) registers things with.
132pub struct PluginBuilder<'r, D> {
133    pub(crate) registry: &'r mut Registry<D>,
134}
135
136impl<D: Adapter> PluginBuilder<'_, D> {
137    /// Id of the plugin being initialised (`"app"` for `Builder::configure`).
138    pub fn owner(&self) -> &'static str {
139        self.registry.owner
140    }
141
142    /// Adds tables or columns (normally done in `Plugin::schema`).
143    pub fn schema(&mut self) -> &mut SchemaBuilder {
144        &mut self.registry.schema
145    }
146
147    pub fn endpoint<E: Endpoint<D>>(&mut self, endpoint: E) -> &mut Self {
148        let registry = &mut *self.registry;
149        if let Some(clash) = registry
150            .routes
151            .iter()
152            .find(|r| r.method == E::METHOD && r.path == E::PATH)
153        {
154            registry.errors.push(format!(
155                "route {} {} is registered by both `{}` and `{}`",
156                E::METHOD,
157                E::PATH,
158                clash.owner,
159                registry.owner
160            ));
161            return self;
162        }
163        registry.routes.push(RouteDef {
164            method: E::METHOD,
165            path: E::PATH,
166            owner: registry.owner,
167            type_id: TypeId::of::<E>(),
168            endpoint: Arc::new(Erased(endpoint)),
169        });
170        self
171    }
172
173    /// Declares an endpoint with no HTTP route, one only the server API calls through
174    /// `auth.api().call(..)`, so hooks may target it like a routed one.
175    pub fn server_endpoint<E: Endpoint<D>>(&mut self) -> &mut Self {
176        self.registry.server_endpoints.push(TypeId::of::<E>());
177        self
178    }
179
180    /// Hooks around endpoint `E`, for every caller: `app.hook::<SignUpEmail>().before(..)`.
181    pub fn hook<E: Endpoint<D>>(&mut self) -> HookBuilder<'_, D, E> {
182        self.registry
183            .hook_targets
184            .push((TypeId::of::<E>(), type_name::<E>(), self.registry.owner));
185        HookBuilder {
186            registry: self.registry,
187            _endpoint: PhantomData,
188        }
189    }
190
191    /// Runs after credentials check out and before a session exists, for every sign-in method.
192    /// Gates run in registration order. The gate belongs to [`owner`](Self::owner): when it
193    /// answers [`Gate::Challenge`], this plugin finishes the sign-in with
194    /// [`Internal::complete_sign_in`](crate::internal::Internal::complete_sign_in) and its own id.
195    pub fn sign_in_gate<F, Fut>(&mut self, gate: F) -> &mut Self
196    where
197        F: Fn(HookCtx<D>, SignInAttempt) -> Fut + Send + Sync + 'static,
198        Fut: Future<Output = Result<Gate, AuthError>> + Send + 'static,
199    {
200        let owner = self.registry.owner;
201        self.registry.gates.push(OwnedGate {
202            owner,
203            gate: Arc::new(move |ctx, attempt| Box::pin(gate(ctx, attempt))),
204        });
205        self
206    }
207
208    /// Checks every session a request resolves to (cookie, cookie cache, bearer token,
209    /// API key) and every [`Ctx::sensitive_session`]. `Err` refuses the session: the
210    /// request fails with that error. Unlike [`sign_in_gate`](Self::sign_in_gate), which
211    /// judges a sign-in once, this runs on every request, so keep it cheap; the
212    /// [`SessionUse`] says which check it is.
213    pub fn session_gate<F, Fut>(&mut self, gate: F) -> &mut Self
214    where
215        F: Fn(HookCtx<D>, SessionView, SessionUse) -> Fut + Send + Sync + 'static,
216        Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
217    {
218        self.registry
219            .session_gates
220            .push(Arc::new(move |ctx, session, usage| {
221                Box::pin(gate(ctx, session, usage))
222            }));
223        self
224    }
225
226    /// Marks sessions the refresh must not extend: when `fixed` answers true for a session,
227    /// it keeps the `expires_at` it was given, whatever `update_age`. For sessions a plugin
228    /// creates with a deliberately short life, such as admin's impersonation sessions.
229    pub fn fixed_session_expiry(
230        &mut self,
231        fixed: impl Fn(&SessionView) -> bool + Send + Sync + 'static,
232    ) -> &mut Self {
233        self.registry.fixed_expiry.push(Arc::new(fixed));
234        self
235    }
236
237    /// Turns non-cookie credentials (bearer tokens, API keys) into a session.
238    pub fn session_resolver(&mut self, resolver: impl SessionResolver<D>) -> &mut Self {
239        self.registry.resolvers.push(Arc::new(resolver));
240        self
241    }
242
243    /// Runs on the HTTP response of every routed endpoint, after its cookies and headers are
244    /// set, in registration order. For headers derived from the response itself, like a
245    /// bearer plugin copying the session cookie into `set-auth-token`. Server API calls
246    /// don't run it.
247    pub fn on_response(
248        &mut self,
249        hook: impl Fn(&Ctx<D>, &mut Response) + Send + Sync + 'static,
250    ) -> &mut Self {
251        self.registry.response_hooks.push(Arc::new(hook));
252        self
253    }
254
255    /// Runs inside the request right after [`Internal::create_session`] stored a session and
256    /// set its cookies, for every way a session is created (sign-in and sign-up of any
257    /// method, a finished challenge, impersonation). In registration order. The context
258    /// still carries the request's headers, so the session cookie the request came with is
259    /// the previous session; hooks may set cookies and query the database. An error fails
260    /// the request, though the session already exists.
261    ///
262    /// Unlike the [`SessionCreated`](crate::events::SessionCreated) event, which runs after
263    /// the endpoint without the request, this is for plugins that react to a sign-in in
264    /// place, like linking an anonymous user or remembering a device session.
265    ///
266    /// [`Internal::create_session`]: crate::internal::Internal::create_session
267    pub fn on_session_created<F, Fut>(&mut self, hook: F) -> &mut Self
268    where
269        F: Fn(HookCtx<D>, SessionView) -> Fut + Send + Sync + 'static,
270        Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
271    {
272        self.registry
273            .session_hooks
274            .push(Arc::new(move |ctx, session| Box::pin(hook(ctx, session))));
275        self
276    }
277
278    /// Removes this plugin's credentials and pending state of a user that proof of the email
279    /// claims ([`Internal::claim_user`]): anything the previous holder of the address could
280    /// sign in or finish a sign-in with, such as passkeys, API keys or a two-factor enrollment.
281    /// Runs inside the claim's transaction, after core deleted the user's accounts and
282    /// sessions; query through [`Claim::db`]. An error rolls the claim back and fails the
283    /// request, so the claim never commits with a cleanup missing.
284    ///
285    /// ```ignore
286    /// app.on_claim(|claim| {
287    ///     Box::pin(async move {
288    ///         claim.db().delete::<ApiKey>(ApiKey::USER_ID.eq(claim.user_id())).await?;
289    ///         Ok(())
290    ///     })
291    /// });
292    /// ```
293    ///
294    /// [`Internal::claim_user`]: crate::internal::Internal::claim_user
295    pub fn on_claim<F>(&mut self, cleanup: F) -> &mut Self
296    where
297        F: for<'a> Fn(Claim<'a, D>) -> BoxFuture<'a, Result<(), AuthError>> + Send + Sync + 'static,
298    {
299        self.registry.claim_hooks.push(Arc::new(cleanup));
300        self
301    }
302
303    /// Checks and rewrites the app and plugin columns a client sends for a user (the extra
304    /// camelCase keys of a sign-up, update-user or email-code sign-up body) before they are
305    /// parsed, on every route that writes them: [`Internal::user_fields`]. In registration
306    /// order; an error refuses the request. For plugins whose columns have rules, such as a
307    /// username that must be valid, normalized and free.
308    ///
309    /// [`Internal::user_fields`]: crate::internal::Internal::user_fields
310    pub fn prepare_user_input<F, Fut>(&mut self, hook: F) -> &mut Self
311    where
312        F: Fn(HookCtx<D>, serde_json::Map<String, serde_json::Value>, UserInput) -> Fut
313            + Send
314            + Sync
315            + 'static,
316        Fut: Future<Output = Result<serde_json::Map<String, serde_json::Value>, AuthError>>
317            + Send
318            + 'static,
319    {
320        self.registry
321            .user_input_hooks
322            .push(Arc::new(move |ctx, input, kind| {
323                Box::pin(hook(ctx, input, kind))
324            }));
325        self
326    }
327
328    /// Runs after any endpoint that emitted `Ev` succeeds. Errors are logged, not returned.
329    pub fn on<Ev, F, Fut>(&mut self, handler: F) -> &mut Self
330    where
331        Ev: Event,
332        F: Fn(Ev, Ctx<D>) -> Fut + Send + Sync + 'static,
333        Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
334    {
335        let erased: ErasedEventHandler<D> = Arc::new(move |event, ctx| {
336            let event = event
337                .downcast_ref::<Ev>()
338                .expect("event routed by TypeId")
339                .clone();
340            Box::pin(handler(event, ctx))
341        });
342        self.registry
343            .events
344            .entry(TypeId::of::<Ev>())
345            .or_default()
346            .push(erased);
347        self
348    }
349
350    /// A rate-limit rule for a path pattern (`/two-factor/*`). App rules win over plugin rules.
351    pub fn rate_limit(&mut self, pattern: impl Into<String>, limit: Limit) -> &mut Self {
352        self.registry.rate_rules.push(Rule {
353            pattern: pattern.into(),
354            limit,
355        });
356        self
357    }
358
359    /// Registers error codes so two plugins can't claim the same one.
360    pub fn errors<E: ErrorCodes>(&mut self) -> &mut Self {
361        let owner = self.registry.owner;
362        for code in E::CODES {
363            if let Some((_, first)) = self.registry.error_codes.iter().find(|(c, _)| c == code) {
364                self.registry.errors.push(format!(
365                    "error code `{code}` is registered by both `{first}` and `{owner}`"
366                ));
367                continue;
368            }
369            self.registry.error_codes.push((code, owner));
370        }
371        self
372    }
373}
374
375pub struct HookBuilder<'r, D, E> {
376    registry: &'r mut Registry<D>,
377    _endpoint: PhantomData<fn() -> E>,
378}
379
380impl<D: Adapter, E: Endpoint<D>> HookBuilder<'_, D, E> {
381    /// Runs before `E` with its typed input. Return `Before::Continue(input)` to proceed.
382    pub fn before<F, Fut>(self, hook: F) -> Self
383    where
384        F: Fn(HookCtx<D>, E::Input) -> Fut + Send + Sync + 'static,
385        Fut: Future<Output = Result<Before<E::Input>, AuthError>> + Send + 'static,
386    {
387        let hook = Arc::new(hook);
388        let erased: ErasedBefore<D> = Arc::new(move |ctx, input| {
389            let hook = hook.clone();
390            Box::pin(async move {
391                let input = *input.downcast::<E::Input>().expect("hook input type");
392                Ok(match hook(ctx, input).await? {
393                    Before::Continue(input) => {
394                        Before::Continue(Box::new(input) as Box<dyn Any + Send>)
395                    }
396                    Before::Respond(response) => Before::Respond(response),
397                })
398            })
399        });
400        self.registry
401            .hooks
402            .entry(TypeId::of::<E>())
403            .or_default()
404            .before
405            .push(erased);
406        self
407    }
408
409    /// Runs after `E` succeeds with its typed output.
410    pub fn after<F, Fut>(self, hook: F) -> Self
411    where
412        F: Fn(HookCtx<D>, E::Output) -> Fut + Send + Sync + 'static,
413        Fut: Future<Output = Result<After<E::Output>, AuthError>> + Send + 'static,
414    {
415        let hook = Arc::new(hook);
416        let erased: ErasedAfter<D> = Arc::new(move |ctx, output| {
417            let hook = hook.clone();
418            Box::pin(async move {
419                let output = *output.downcast::<E::Output>().expect("hook output type");
420                Ok(match hook(ctx, output).await? {
421                    After::Continue(output) => {
422                        After::Continue(Box::new(output) as Box<dyn Any + Send>)
423                    }
424                    After::Respond(response) => After::Respond(response),
425                })
426            })
427        });
428        self.registry
429            .hooks
430            .entry(TypeId::of::<E>())
431            .or_default()
432            .after
433            .push(erased);
434        self
435    }
436}