tablo_core/auth/hook.rs
1//! [`AuthHook`]: the work a panel does when auth changes who a request acts as.
2
3use std::future::Future;
4
5use jiff::Timestamp;
6use toasty::Executor;
7use topcoat::{Result, context::Cx};
8
9use super::{PanelUser, SignedIn, infrastructure_failure, realm::Realm};
10use crate::{BoxFuture, PanelId, TenantId};
11
12/// Work a panel does inside the transaction of each [`AuthEvent`], registered by
13/// [`Panel::auth_hook`](crate::Panel::auth_hook): an audit trail of who acted as whom.
14///
15/// Run every statement through `ex`. An `Err` on an event that grants or changes something (a
16/// sign-in, a start of impersonation, a change of credentials, address or second factor) rolls it
17/// back and fails the request. An `Err` on a stop of impersonation, a sign-out or a refused
18/// attempt rolls back what the hooks wrote and is logged, and the event stands: a session that
19/// cannot stop acting as someone else, or sign out, is worse than one the trail misses.
20///
21/// ```rust
22/// # use tablo_core::{AuthEvent, AuthEventKind, AuthHook};
23/// # use topcoat::{Result, context::Cx};
24/// struct Trace;
25///
26/// impl AuthHook for Trace {
27/// async fn on_event(
28/// _cx: &Cx,
29/// event: &AuthEvent<'_>,
30/// _ex: &mut dyn toasty::Executor,
31/// ) -> Result<()> {
32/// if let (AuthEventKind::Impersonate { .. }, Some(actor), Some(target)) =
33/// (event.kind(), event.actor(), event.target_id())
34/// {
35/// tracing::info!("{} acts as {target}", actor.user_id());
36/// }
37/// Ok(())
38/// }
39/// }
40/// ```
41pub trait AuthHook: 'static {
42 /// Work inside the event's transaction.
43 fn on_event(
44 cx: &Cx,
45 event: &AuthEvent<'_>,
46 ex: &mut dyn Executor,
47 ) -> impl Future<Output = Result<()>> + Send;
48}
49
50/// What auth did, as an [`AuthHook`] receives it: on which panel, for which tenant, by whom, to
51/// which account.
52///
53/// The request may not know the user yet: a sign-in has no session before it, and a session that
54/// lapsed is stopped while auth resolves it, so read the actor and the tenant here, not through
55/// [`auth::actor`](crate::auth::actor) and [`tenant_id`](crate::tenant_id).
56#[derive(Clone)]
57pub struct AuthEvent<'a> {
58 kind: AuthEventKind<'a>,
59 panel: &'a PanelId,
60 tenant: Option<TenantId>,
61 actor: Option<&'a dyn PanelUser>,
62 target_id: Option<String>,
63 target_name: Option<&'a str>,
64}
65
66impl<'a> AuthEvent<'a> {
67 /// `actor` did `kind` to the account `target_id` names.
68 pub(crate) fn new(
69 kind: AuthEventKind<'a>,
70 panel: &'a PanelId,
71 tenant: Option<TenantId>,
72 actor: &'a dyn PanelUser,
73 target_id: &str,
74 target_name: Option<&'a str>,
75 ) -> Self {
76 Self {
77 kind,
78 panel,
79 tenant,
80 actor: Some(actor),
81 target_id: Some(target_id.to_owned()),
82 target_name,
83 }
84 }
85
86 /// `user` did `kind` to their own account.
87 pub(crate) fn own(
88 kind: AuthEventKind<'a>,
89 panel: &'a PanelId,
90 tenant: Option<TenantId>,
91 user: &'a dyn PanelUser,
92 ) -> Self {
93 Self {
94 kind,
95 panel,
96 tenant,
97 actor: Some(user),
98 target_id: Some(user.user_id()),
99 target_name: Some(user.display_name()),
100 }
101 }
102
103 /// `kind` happened to the account `target_id` names with no one signed in: a mailed link
104 /// opened without a session, or a sign-in no account answered.
105 pub(crate) fn unsigned(
106 kind: AuthEventKind<'a>,
107 panel: &'a PanelId,
108 target_id: Option<&str>,
109 ) -> Self {
110 Self {
111 kind,
112 panel,
113 tenant: None,
114 actor: None,
115 target_id: target_id.map(str::to_owned),
116 target_name: None,
117 }
118 }
119
120 /// What happened.
121 pub fn kind(&self) -> AuthEventKind<'a> {
122 self.kind
123 }
124
125 /// The panel it happened on.
126 pub fn panel(&self) -> &'a PanelId {
127 self.panel
128 }
129
130 /// The tenant the session acted for; `None` outside every tenant, and before a session
131 /// exists.
132 pub fn tenant(&self) -> Option<TenantId> {
133 self.tenant
134 }
135
136 /// The user who did it; `None` when no one was signed in: a sign-in no account answered, or
137 /// a mailed link opened without a session.
138 pub fn actor(&self) -> Option<&'a dyn PanelUser> {
139 self.actor
140 }
141
142 /// The [`PanelUser::user_id`] of the account it was done to, the actor's own outside
143 /// impersonation; `None` when a sign-in named no account.
144 pub fn target_id(&self) -> Option<&str> {
145 self.target_id.as_deref()
146 }
147
148 /// The [`display_name`](PanelUser::display_name) of the account it was done to; `None` when
149 /// the account was not loaded.
150 pub fn target_name(&self) -> Option<&'a str> {
151 self.target_name
152 }
153}
154
155impl std::fmt::Debug for AuthEvent<'_> {
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 f.debug_struct("AuthEvent")
158 .field("kind", &self.kind)
159 .field("panel", &self.panel.to_string())
160 .field("tenant", &self.tenant)
161 .field("actor", &self.actor.map(PanelUser::user_id))
162 .field("target_id", &self.target_id)
163 .field("target_name", &self.target_name)
164 .finish()
165 }
166}
167
168/// Which [`AuthEvent`] auth recorded.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170#[non_exhaustive]
171pub enum AuthEventKind<'a> {
172 /// The actor starts acting as the target through
173 /// [`Auth::impersonation`](crate::Auth::impersonation), until this time at the latest: a
174 /// session that runs out unseen records no stop.
175 Impersonate { until: Timestamp },
176 /// The actor stops acting as the target: with the banner's Stop button, by signing out, or on
177 /// the first request after the lifetime ran out or the rule refused.
178 StopImpersonating,
179 /// The actor got a session on the panel: by password, by a provider, after their second
180 /// factor, by signing up, or from the app's own sign-in under
181 /// [`Auth::external`](crate::Auth::external).
182 SignIn,
183 /// A sign-in the panel refused, as `login` was typed. The actor is the account when its
184 /// password was right and it may not enter the panel, else `None`: a wrong password and an
185 /// unknown login read alike. An attempt past the throttle records nothing.
186 SignInFailed { login: &'a str },
187 /// The actor's password was right and the second-factor code they gave was wrong.
188 SecondFactorFailed,
189 /// The actor signed out of the panel.
190 SignOut,
191 /// The actor changed something they sign in with, such as their password, on the profile
192 /// page: a [`ProfileUpdate::Credentials`](crate::ProfileUpdate::Credentials).
193 CredentialsChanged,
194 /// The target's password was set through a mailed reset link.
195 PasswordReset,
196 /// The target's address changed, by the link mailed to the new one.
197 EmailChanged,
198 /// The actor turned two-factor sign-in on.
199 TwoFactorEnabled,
200 /// The actor turned two-factor sign-in off.
201 TwoFactorDisabled,
202 /// The actor replaced their recovery codes.
203 RecoveryCodesReplaced,
204}
205
206/// A registered [`AuthHook`], its type erased.
207pub(crate) type AuthHookFn =
208 for<'a> fn(&'a Cx, &'a AuthEvent<'a>, &'a mut dyn Executor) -> BoxFuture<'a, Result<()>>;
209
210/// `H`'s [`AuthHook::on_event`], its type erased.
211pub(crate) fn erased<'a, H: AuthHook>(
212 cx: &'a Cx,
213 event: &'a AuthEvent<'a>,
214 ex: &'a mut dyn Executor,
215) -> BoxFuture<'a, Result<()>> {
216 Box::pin(H::on_event(cx, event, ex))
217}
218
219/// Runs each of `hooks` on `event` through `ex`, stopping at the first error.
220pub(crate) async fn run(
221 cx: &Cx,
222 hooks: &[AuthHookFn],
223 event: &AuthEvent<'_>,
224 ex: &mut dyn Executor,
225) -> Result<()> {
226 for hook in hooks {
227 hook(cx, event, &mut *ex).await.map_err(|error| {
228 crate::error::driver_failure(error, crate::error::DATABASE_UNAVAILABLE)
229 })?;
230 }
231 Ok(())
232}
233
234/// Runs the hooks of `realm` on `event` in a transaction of its own. A failure is logged, not
235/// returned: for an event that stands whether or not the trail holds it.
236pub(crate) async fn note(cx: &Cx, realm: &Realm, event: &AuthEvent<'_>) {
237 if realm.auth_hooks.is_empty() {
238 return;
239 }
240 let noted = async {
241 let mut db = crate::db::db(cx)?;
242 let mut tx = db.transaction().await.map_err(infrastructure_failure)?;
243 match run(cx, &realm.auth_hooks, event, &mut tx).await {
244 Ok(()) => tx.commit().await.map_err(infrastructure_failure),
245 Err(error) => {
246 tx.rollback().await.map_err(infrastructure_failure)?;
247 Err(error)
248 }
249 }
250 }
251 .await;
252 if let Err(error) = noted {
253 tracing::error!(error = %error, ?event, "an auth hook failed to record an event");
254 }
255}
256
257/// Runs the hooks of the panel `signed` acts on through `ex`, on the `kind` its user did to their
258/// own account.
259pub(crate) async fn run_own(
260 cx: &Cx,
261 signed: &SignedIn,
262 kind: AuthEventKind<'_>,
263 ex: &mut dyn Executor,
264) -> Result<()> {
265 let event = AuthEvent::own(
266 kind,
267 &signed.realm.id,
268 signed.acting_tenant(cx),
269 &*signed.user,
270 );
271 run(cx, &signed.realm.auth_hooks, &event, ex).await
272}