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