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, Gate, HookCtx, OwnedGate, SessionResolver, SignInAttempt,
15};
16use crate::error::{AuthError, ErrorCodes};
17use crate::events::Event;
18use crate::model::Fields;
19use crate::rate_limit::{Limit, Rule};
20use crate::schema::SchemaBuilder;
21
22/// A fastauth plugin. See `docs/05-plugins.md`.
23pub trait Plugin: Send + Sync + Sized + 'static {
24    /// Unique id, used in error messages, schema ownership and derived keys.
25    const ID: &'static str;
26    /// Plugins that must be registered before this one, as a tuple: `()`, `(Organization,)`.
27    type Requires;
28    /// Columns this plugin adds to `user`; `()` for none.
29    type UserFields: Fields;
30    /// Columns this plugin adds to `session`; `()` for none.
31    type SessionFields: Fields;
32
33    /// Adds tables (`schema.model::<M>()`) or columns. `UserFields` and `SessionFields` are
34    /// added automatically.
35    fn schema(&self, schema: &mut SchemaBuilder) {
36        let _ = schema;
37    }
38
39    /// Registers endpoints, hooks, gates, resolvers, events, rate limits and error codes.
40    /// Runs once, inside `.build()`.
41    fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
42        let _ = app;
43    }
44}
45
46pub(crate) struct RouteDef<D> {
47    pub method: Method,
48    pub path: &'static str,
49    pub owner: &'static str,
50    pub type_id: TypeId,
51    pub endpoint: Arc<dyn ErasedEndpoint<D>>,
52}
53
54/// Everything registered during `.build()`, before it is frozen into `Shared`.
55pub struct Registry<D> {
56    pub(crate) schema: SchemaBuilder,
57    pub(crate) plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
58    pub(crate) routes: Vec<RouteDef<D>>,
59    pub(crate) hooks: HashMap<TypeId, EndpointHooks<D>>,
60    pub(crate) hook_targets: Vec<(TypeId, &'static str, &'static str)>,
61    pub(crate) server_endpoints: Vec<TypeId>,
62    pub(crate) gates: Vec<OwnedGate<D>>,
63    pub(crate) resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
64    pub(crate) events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
65    pub(crate) rate_rules: Vec<Rule>,
66    pub(crate) error_codes: Vec<(&'static str, &'static str)>,
67    pub(crate) errors: Vec<String>,
68    pub(crate) owner: &'static str,
69}
70
71impl<D: Adapter> Registry<D> {
72    pub(crate) fn new() -> Self {
73        Self {
74            schema: SchemaBuilder::new(),
75            plugins: HashMap::new(),
76            routes: Vec::new(),
77            hooks: HashMap::new(),
78            hook_targets: Vec::new(),
79            server_endpoints: Vec::new(),
80            gates: Vec::new(),
81            resolvers: Vec::new(),
82            events: HashMap::new(),
83            rate_rules: Vec::new(),
84            error_codes: Vec::new(),
85            errors: Vec::new(),
86            owner: "core",
87        }
88    }
89
90    pub(crate) fn set_owner(&mut self, owner: &'static str) {
91        self.owner = owner;
92        self.schema.owner = owner;
93    }
94
95    pub(crate) fn register_plugin<P: Plugin>(&mut self, plugin: &Arc<P>) {
96        if self
97            .plugins
98            .insert(TypeId::of::<P>(), plugin.clone())
99            .is_some()
100        {
101            self.errors
102                .push(format!("plugin `{}` is registered twice", P::ID));
103            return;
104        }
105        let previous = self.owner;
106        self.set_owner(P::ID);
107        self.schema.extend("user", P::UserFields::columns());
108        self.schema.extend("session", P::SessionFields::columns());
109        plugin.schema(&mut self.schema);
110        plugin.init(&mut PluginBuilder { registry: self });
111        self.set_owner(previous);
112    }
113}
114
115/// What `Plugin::init` (and `Builder::configure`) registers things with.
116pub struct PluginBuilder<'r, D> {
117    pub(crate) registry: &'r mut Registry<D>,
118}
119
120impl<D: Adapter> PluginBuilder<'_, D> {
121    /// Id of the plugin being initialised (`"app"` for `Builder::configure`).
122    pub fn owner(&self) -> &'static str {
123        self.registry.owner
124    }
125
126    /// Adds tables or columns (normally done in `Plugin::schema`).
127    pub fn schema(&mut self) -> &mut SchemaBuilder {
128        &mut self.registry.schema
129    }
130
131    pub fn endpoint<E: Endpoint<D>>(&mut self, endpoint: E) -> &mut Self {
132        let registry = &mut *self.registry;
133        if let Some(clash) = registry
134            .routes
135            .iter()
136            .find(|r| r.method == E::METHOD && r.path == E::PATH)
137        {
138            registry.errors.push(format!(
139                "route {} {} is registered by both `{}` and `{}`",
140                E::METHOD,
141                E::PATH,
142                clash.owner,
143                registry.owner
144            ));
145            return self;
146        }
147        registry.routes.push(RouteDef {
148            method: E::METHOD,
149            path: E::PATH,
150            owner: registry.owner,
151            type_id: TypeId::of::<E>(),
152            endpoint: Arc::new(Erased(endpoint)),
153        });
154        self
155    }
156
157    /// Declares an endpoint with no HTTP route, one only the server API calls through
158    /// `auth.api().call(..)`, so hooks may target it like a routed one.
159    pub fn server_endpoint<E: Endpoint<D>>(&mut self) -> &mut Self {
160        self.registry.server_endpoints.push(TypeId::of::<E>());
161        self
162    }
163
164    /// Hooks around endpoint `E`, for every caller: `app.hook::<SignUpEmail>().before(..)`.
165    pub fn hook<E: Endpoint<D>>(&mut self) -> HookBuilder<'_, D, E> {
166        self.registry
167            .hook_targets
168            .push((TypeId::of::<E>(), type_name::<E>(), self.registry.owner));
169        HookBuilder {
170            registry: self.registry,
171            _endpoint: PhantomData,
172        }
173    }
174
175    /// Runs after credentials check out and before a session exists, for every sign-in method.
176    /// Gates run in registration order. The gate belongs to [`owner`](Self::owner): when it
177    /// answers [`Gate::Challenge`], this plugin finishes the sign-in with
178    /// [`Internal::complete_sign_in`](crate::internal::Internal::complete_sign_in) and its own id.
179    pub fn sign_in_gate<F, Fut>(&mut self, gate: F) -> &mut Self
180    where
181        F: Fn(HookCtx<D>, SignInAttempt) -> Fut + Send + Sync + 'static,
182        Fut: Future<Output = Result<Gate, AuthError>> + Send + 'static,
183    {
184        let owner = self.registry.owner;
185        self.registry.gates.push(OwnedGate {
186            owner,
187            gate: Arc::new(move |ctx, attempt| Box::pin(gate(ctx, attempt))),
188        });
189        self
190    }
191
192    /// Turns non-cookie credentials (bearer tokens, API keys) into a session.
193    pub fn session_resolver(&mut self, resolver: impl SessionResolver<D>) -> &mut Self {
194        self.registry.resolvers.push(Arc::new(resolver));
195        self
196    }
197
198    /// Runs after any endpoint that emitted `Ev` succeeds. Errors are logged, not returned.
199    pub fn on<Ev, F, Fut>(&mut self, handler: F) -> &mut Self
200    where
201        Ev: Event,
202        F: Fn(Ev, Ctx<D>) -> Fut + Send + Sync + 'static,
203        Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
204    {
205        let erased: ErasedEventHandler<D> = Arc::new(move |event, ctx| {
206            let event = event
207                .downcast_ref::<Ev>()
208                .expect("event routed by TypeId")
209                .clone();
210            Box::pin(handler(event, ctx))
211        });
212        self.registry
213            .events
214            .entry(TypeId::of::<Ev>())
215            .or_default()
216            .push(erased);
217        self
218    }
219
220    /// A rate-limit rule for a path pattern (`/two-factor/*`). App rules win over plugin rules.
221    pub fn rate_limit(&mut self, pattern: impl Into<String>, limit: Limit) -> &mut Self {
222        self.registry.rate_rules.push(Rule {
223            pattern: pattern.into(),
224            limit,
225        });
226        self
227    }
228
229    /// Registers error codes so two plugins can't claim the same one.
230    pub fn errors<E: ErrorCodes>(&mut self) -> &mut Self {
231        let owner = self.registry.owner;
232        for code in E::CODES {
233            if let Some((_, first)) = self.registry.error_codes.iter().find(|(c, _)| c == code) {
234                self.registry.errors.push(format!(
235                    "error code `{code}` is registered by both `{first}` and `{owner}`"
236                ));
237                continue;
238            }
239            self.registry.error_codes.push((code, owner));
240        }
241        self
242    }
243}
244
245pub struct HookBuilder<'r, D, E> {
246    registry: &'r mut Registry<D>,
247    _endpoint: PhantomData<fn() -> E>,
248}
249
250impl<D: Adapter, E: Endpoint<D>> HookBuilder<'_, D, E> {
251    /// Runs before `E` with its typed input. Return `Before::Continue(input)` to proceed.
252    pub fn before<F, Fut>(self, hook: F) -> Self
253    where
254        F: Fn(HookCtx<D>, E::Input) -> Fut + Send + Sync + 'static,
255        Fut: Future<Output = Result<Before<E::Input>, AuthError>> + Send + 'static,
256    {
257        let hook = Arc::new(hook);
258        let erased: ErasedBefore<D> = Arc::new(move |ctx, input| {
259            let hook = hook.clone();
260            Box::pin(async move {
261                let input = *input.downcast::<E::Input>().expect("hook input type");
262                Ok(match hook(ctx, input).await? {
263                    Before::Continue(input) => {
264                        Before::Continue(Box::new(input) as Box<dyn Any + Send>)
265                    }
266                    Before::Respond(response) => Before::Respond(response),
267                })
268            })
269        });
270        self.registry
271            .hooks
272            .entry(TypeId::of::<E>())
273            .or_default()
274            .before
275            .push(erased);
276        self
277    }
278
279    /// Runs after `E` succeeds with its typed output.
280    pub fn after<F, Fut>(self, hook: F) -> Self
281    where
282        F: Fn(HookCtx<D>, E::Output) -> Fut + Send + Sync + 'static,
283        Fut: Future<Output = Result<After<E::Output>, AuthError>> + Send + 'static,
284    {
285        let hook = Arc::new(hook);
286        let erased: ErasedAfter<D> = Arc::new(move |ctx, output| {
287            let hook = hook.clone();
288            Box::pin(async move {
289                let output = *output.downcast::<E::Output>().expect("hook output type");
290                Ok(match hook(ctx, output).await? {
291                    After::Continue(output) => {
292                        After::Continue(Box::new(output) as Box<dyn Any + Send>)
293                    }
294                    After::Respond(response) => After::Respond(response),
295                })
296            })
297        });
298        self.registry
299            .hooks
300            .entry(TypeId::of::<E>())
301            .or_default()
302            .after
303            .push(erased);
304        self
305    }
306}