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