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