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