Skip to main content

tablo_core/auth/
impersonation.rs

1//! [`Auth::impersonation`]: a panel user acting as another, to see the panel as they see it, for a
2//! short while and never as far as their credentials.
3
4use std::{
5    any::Any,
6    sync::Arc,
7    time::{Duration, SystemTime},
8};
9
10use jiff::Timestamp;
11use topcoat::{
12    context::Cx,
13    icon::icon,
14    router::{
15        Body, RouteFuture,
16        error::{forbidden, see_other},
17        request::uri,
18        response::IntoResponse,
19    },
20    view::{BoxView, ViewExt, attributes, view},
21};
22
23use super::{
24    Auth, AuthConfig, DynAuthenticator, PanelUser, SignedIn,
25    hook::{self, AuthEvent, AuthEventKind},
26    infrastructure_failure, panel_root,
27    realm::{Realm, panel_prefix},
28    session::{self, AuthSession},
29    signed, unauthenticated_error,
30};
31
32/// The field of a `POST {prefix}/impersonate` form naming the user to act as: their
33/// [`PanelUser::user_id`].
34pub const IMPERSONATE_FIELD: &str = "user";
35
36/// The rule an [`Impersonation`] asks: whether `actor` may act as `target`.
37type Rule<U> = dyn Fn(&Cx, &U, &U) -> bool + Send + Sync;
38
39/// Who a panel's users may act as, and for how long, set by [`Auth::impersonation`].
40///
41/// ```rust
42/// # use tablo_core::{Auth, Impersonation, auth::AdminUser};
43/// # fn is_support(user: &AdminUser) -> bool { user.email.ends_with("@support.example") }
44/// let auth = Auth::password().impersonation(
45///     // Support acts as customers, never as another member of support.
46///     Impersonation::new(|_cx, actor: &AdminUser, target: &AdminUser| {
47///         is_support(actor) && !is_support(target)
48///     })
49///     .lifetime(std::time::Duration::from_secs(30 * 60)),
50/// );
51/// ```
52pub struct Impersonation<U> {
53    allows: Arc<Rule<U>>,
54    lifetime: Duration,
55    across_tenants: bool,
56    writable: bool,
57}
58
59/// The longest an [`Impersonation`] lasts, whatever its [`lifetime`](Impersonation::lifetime).
60const LONGEST: Duration = Duration::from_hours(24);
61
62impl<U: PanelUser> Impersonation<U> {
63    /// Lets a user act as another when `allows(cx, actor, target)` answers `true`, for an hour.
64    ///
65    /// It is asked again on every request while the actor acts as the target, so a change to
66    /// either user, or to the rule, ends it at once. A user never acts as themselves, nor as a
67    /// user who may not enter the panel, whatever it answers; on a panel that acts for tenants,
68    /// nor as a user who belongs to a tenant the actor does not, unless
69    /// [`across_tenants`](Self::across_tenants) says otherwise.
70    ///
71    /// Decide from `actor` and `target` alone: `cx` carries the request, but whom
72    /// [`auth::user`](crate::auth::user) names inside it depends on when the rule is asked.
73    pub fn new(allows: impl Fn(&Cx, &U, &U) -> bool + Send + Sync + 'static) -> Self {
74        Self {
75            allows: Arc::new(allows),
76            lifetime: Duration::from_hours(1),
77            across_tenants: false,
78            writable: false,
79        }
80    }
81
82    /// How long acting as a user lasts before the actor is themselves again; defaults to an hour,
83    /// and never exceeds a day.
84    #[must_use]
85    pub fn lifetime(mut self, lifetime: Duration) -> Self {
86        self.lifetime = lifetime.min(LONGEST);
87        self
88    }
89
90    /// Let the actor act as a user of tenants they are no member of, such as a platform's own
91    /// staff acting as any customer. Off by default: on a panel that acts for tenants, every
92    /// tenant the target belongs to must be one of the actor's, so acting as them reaches no
93    /// tenant the actor could not already.
94    #[must_use]
95    pub fn across_tenants(mut self) -> Self {
96        self.across_tenants = true;
97        self
98    }
99
100    /// Let the actor write as the target: create, edit and delete records, run actions and header
101    /// actions, and clear the target's notifications, as far as the policies allow the target.
102    ///
103    /// Off by default: acting as someone reads the panel as they read it, and writes nothing. Every
104    /// resource answers as if mounted [`ReadOnly`](crate::ReadOnly), so its buttons are gone and
105    /// its write routes answer 403, [`can`](crate::can) included; no header action runs, on a
106    /// resource or a page; and the notification bell offers nothing to mark or remove. A route
107    /// of the app's own, outside the panel's resources and pages, asks
108    /// [`impersonator`](crate::auth::impersonator) itself.
109    ///
110    /// Writable or not, the actor never reaches the target's credentials: see
111    /// [`Auth::impersonation`].
112    #[must_use]
113    pub fn writable(mut self) -> Self {
114        self.writable = true;
115        self
116    }
117}
118
119impl<U: PanelUser> Auth<U> {
120    /// Lets a signed-in user act as another user of the panel, as [`Impersonation`] allows: to see
121    /// what they see, and to reproduce what they report.
122    ///
123    /// - `POST {prefix}/impersonate`, carrying the CSRF field and [`IMPERSONATE_FIELD`], starts it,
124    ///   and [`Impersonate`](crate::Impersonate) places a button for it on a users resource. It
125    ///   answers 403 to a user already acting as another, and for a target the rule refuses or no
126    ///   account matches, alike.
127    /// - Every page then reads the target as the signed-in user, tenant included, under a banner
128    ///   naming them with a Stop button, which posts to `{prefix}/impersonate/stop` and restores
129    ///   the actor. So does the end of the lifetime, or the rule refusing again.
130    /// - The actor writes nothing meanwhile: every resource answers as
131    ///   [`ReadOnly`](crate::ReadOnly) does and no header action runs, unless
132    ///   [`Impersonation::writable`] says otherwise.
133    /// - The profile, two-factor, tenant settings, tenant registration and email-verification pages
134    ///   answer 403 while it lasts, and an email-change link ignores the session: the actor never
135    ///   changes the target's credentials.
136    /// - The panel's [`AuthHook`](crate::AuthHook)s run on the start and on the stop, inside its
137    ///   transaction: Stop, a sign-out, and the first request past the end or after the rule
138    ///   refuses each stop it. A session that ends unseen records no stop, so the start names when
139    ///   it ends at the latest. [`auth::actor`](crate::auth::actor) names the actor, not the
140    ///   target, on every request made meanwhile.
141    ///
142    /// The session row stores the target in two columns, see [`AuthSession`]. Mounting refuses it
143    /// behind [`Auth::external`].
144    #[must_use]
145    pub fn impersonation(mut self, impersonation: Impersonation<U>) -> Self {
146        let allows = impersonation.allows;
147        self.config.impersonation = Some(ImpersonationConfig {
148            allows: Arc::new(move |cx, actor, target| {
149                let (actor, target): (&dyn Any, &dyn Any) = (actor, target);
150                match (actor.downcast_ref::<U>(), target.downcast_ref::<U>()) {
151                    (Some(actor), Some(target)) => allows(cx, actor, target),
152                    _ => false,
153                }
154            }),
155            lifetime: impersonation.lifetime,
156            across_tenants: impersonation.across_tenants,
157            writable: impersonation.writable,
158        });
159        self
160    }
161}
162
163type Allows = dyn Fn(&Cx, &dyn PanelUser, &dyn PanelUser) -> bool + Send + Sync;
164
165/// An [`Impersonation`] with its user type erased.
166#[derive(Clone)]
167pub(crate) struct ImpersonationConfig {
168    allows: Arc<Allows>,
169    lifetime: Duration,
170    across_tenants: bool,
171    writable: bool,
172}
173
174impl std::fmt::Debug for ImpersonationConfig {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        f.debug_struct("Impersonation")
177            .field("lifetime", &self.lifetime)
178            .field("across_tenants", &self.across_tenants)
179            .field("writable", &self.writable)
180            .finish_non_exhaustive()
181    }
182}
183
184impl ImpersonationConfig {
185    /// Whether `actor` may act as `target` on `panel`: two users, both admitted to it, the target
186    /// in no tenant the actor is not, on a panel that acts for tenants, and the app's rule
187    /// agreeing.
188    fn permits(
189        &self,
190        cx: &Cx,
191        panel: &Realm,
192        actor: &dyn PanelUser,
193        target: &dyn PanelUser,
194    ) -> bool {
195        let within_tenants = !panel.serves_tenants
196            || self.across_tenants
197            || target.tenants().iter().all(|membership| {
198                actor
199                    .tenants()
200                    .iter()
201                    .any(|own| own.tenant == membership.tenant)
202            });
203        actor.user_id() != target.user_id()
204            && actor.can_access_panel(&panel.id)
205            && target.can_access_panel(&panel.id)
206            && within_tenants
207            && (self.allows)(cx, actor, target)
208    }
209}
210
211impl AuthConfig {
212    /// The impersonation rule, or `None` when no user may act as another.
213    pub(crate) fn impersonation(&self) -> Option<&ImpersonationConfig> {
214        self.authenticator().and(self.impersonation.as_ref())
215    }
216}
217
218impl SignedIn {
219    /// Whether the panel refuses this request's writes: an actor acts as the user, under an
220    /// impersonation that is not [`writable`](Impersonation::writable).
221    pub(super) fn refuses_writes(&self) -> bool {
222        self.impersonator.is_some()
223            && !self
224                .realm
225                .auth
226                .impersonation()
227                .is_some_and(|config| config.writable)
228    }
229}
230
231/// The user acting as the signed-in user, as `U`; `None` while the signed-in user acts as
232/// themselves, or when the actor is not a `U`.
233pub fn impersonator<U: PanelUser>(cx: &Cx) -> Option<&U> {
234    let actor: &dyn Any = &**signed(cx)?.impersonator.as_ref()?;
235    actor.downcast_ref()
236}
237
238/// Resolves a session whose `actor` acts as another user: the target, with the actor beside, while
239/// the lifetime lasts and the rule still allows it; else the actor, the row cleared.
240pub(super) async fn resolve(
241    cx: &Cx,
242    row: AuthSession,
243    actor: Arc<dyn PanelUser>,
244    panel: &Arc<Realm>,
245    authenticator: &dyn DynAuthenticator,
246) -> topcoat::Result<SignedIn> {
247    if let Some(target) = live_target(cx, &row, &*actor, panel, authenticator).await? {
248        return Ok(SignedIn {
249            user: target,
250            realm: Arc::clone(panel),
251            tenant: row.tenant,
252            impersonator: Some(actor),
253        });
254    }
255    // Ended by its lifetime, the rule or either user: cleared and recorded together, or cleared
256    // alone when a hook fails to record it.
257    let mut db = crate::db::db(cx)?;
258    let mut tx = db.transaction().await.map_err(infrastructure_failure)?;
259    session::set_impersonation(&mut tx, &row.token_hash, None).await?;
260    let recorded = match row.impersonating.as_deref() {
261        Some(target) => {
262            let event = AuthEvent::new(
263                AuthEventKind::StopImpersonating,
264                &panel.id,
265                crate::auth::acting_tenant(panel, &*actor, row.tenant, cx),
266                &*actor,
267                target,
268                None,
269            );
270            record_stop(cx, &panel.auth_hooks, &event, tx).await?
271        }
272        None => tx
273            .commit()
274            .await
275            .map_err(infrastructure_failure)
276            .map(|()| true)?,
277    };
278    if !recorded {
279        session::set_impersonation(&mut db, &row.token_hash, None).await?;
280    }
281    Ok(SignedIn {
282        user: actor,
283        realm: Arc::clone(panel),
284        tenant: None,
285        impersonator: None,
286    })
287}
288
289async fn live_target(
290    cx: &Cx,
291    row: &AuthSession,
292    actor: &dyn PanelUser,
293    panel: &Realm,
294    authenticator: &dyn DynAuthenticator,
295) -> topcoat::Result<Option<Arc<dyn PanelUser>>> {
296    let (Some(id), Some(until), Some(config)) = (
297        row.impersonating.as_deref(),
298        row.impersonating_until,
299        panel.auth.impersonation(),
300    ) else {
301        return Ok(None);
302    };
303    // An actor who owes a step, such as setting up a factor the panel now requires, goes to it.
304    if until <= Timestamp::now() || super::gate::owes_step(cx, panel, actor).await? {
305        return Ok(None);
306    }
307    let target = authenticator
308        .find_by_id(cx, id)
309        .await
310        .map_err(infrastructure_failure)?;
311    Ok(target.filter(|target| config.permits(cx, panel, actor, &**target)))
312}
313
314/// The signed-in user who may start acting as another, with the panel's rule: one acting as
315/// themselves, on a panel with [`Auth::impersonation`].
316fn actor(cx: &Cx) -> Option<(&SignedIn, &ImpersonationConfig)> {
317    let signed = signed(cx).filter(|signed| signed.impersonator.is_none())?;
318    Some((signed, signed.realm.auth.impersonation()?))
319}
320
321/// A button that acts as `target`, for a page of the app's own, such as a staff list over a user
322/// type that is no model, where the [`Impersonate`](crate::Impersonate) action cannot go: a form
323/// that posts `target`'s [`user_id`](PanelUser::user_id) to `{prefix}/impersonate` with the CSRF
324/// field.
325///
326/// It renders nothing unless the signed-in user may act as `target` under the panel's
327/// [`Impersonation`] rule, as the action's button shows only then; the route asks the rule again.
328///
329/// ```rust
330/// # use tablo_core::{PanelUser, auth};
331/// # use topcoat::{context::Cx, view::{View, view}};
332/// fn act_as<'a>(cx: &'a Cx, colleague: &dyn PanelUser) -> impl View + 'a {
333///     let button = auth::impersonate_button(cx, colleague);
334///     view! { <td>(button)</td> }
335/// }
336/// ```
337pub fn impersonate_button<'a>(cx: &'a Cx, target: &dyn PanelUser) -> BoxView<'a> {
338    if !may_impersonate(cx, target) {
339        return view! {}.boxed();
340    }
341    let token = crate::csrf::ensure_token(cx);
342    let action = format!("{}/impersonate", panel_prefix(cx));
343    let id = target.user_id();
344    view! {
345        <form method="post" action=(action) data-impersonate=(id.clone())>
346            (crate::csrf::field(cx, &token))
347            <input type="hidden" name=(IMPERSONATE_FIELD) value=(id)>
348            tablo_ui::button(
349                variant: tablo_ui::ButtonVariant::Outline,
350                size: tablo_ui::ButtonSize::Sm,
351                attrs: attributes! { type="submit" },
352                icon(data: tablo_ui::icons::EYE)
353                (crate::t!(cx, "tablo-impersonation-start"))
354            )
355        </form>
356    }
357    .boxed()
358}
359
360/// Whether the signed-in user may act as `target`: what shows the
361/// [`Impersonate`](crate::Impersonate) button.
362pub(crate) fn may_impersonate(cx: &Cx, target: &dyn PanelUser) -> bool {
363    actor(cx)
364        .is_some_and(|(signed, config)| config.permits(cx, &signed.realm, &*signed.user, target))
365}
366
367/// Makes the request's session act as `target` through `ex`, and records it through `ex` too, so
368/// a transaction commits both or neither; 403 when the signed-in user may not under the panel's
369/// [`Impersonation`] rule, or acts as someone already.
370///
371/// It is what the [`Impersonate`](crate::Impersonate) action runs, for an action of the app's own
372/// where that one cannot go: a resource whose model is not the panel's user type, such as the
373/// record a [`PanelUser`] wraps. The action loads the user it acts as, since `target` is what the
374/// rule reads.
375///
376/// ```rust
377/// # use tablo_core::{PanelUser, auth};
378/// # use topcoat::context::Cx;
379/// async fn act_as(
380///     cx: &Cx,
381///     ex: &mut dyn toasty::Executor,
382///     target: &dyn PanelUser,
383/// ) -> topcoat::Result<()> {
384///     auth::impersonate(cx, ex, target).await
385/// }
386/// ```
387pub async fn impersonate(
388    cx: &Cx,
389    ex: &mut dyn toasty::Executor,
390    target: &dyn PanelUser,
391) -> topcoat::Result<()> {
392    let Some((signed, config)) = actor(cx) else {
393        return Err(forbidden().into());
394    };
395    if !config.permits(cx, &signed.realm, &*signed.user, target) {
396        return Err(forbidden().into());
397    }
398    let until =
399        Timestamp::try_from(SystemTime::now() + config.lifetime).map_err(topcoat::Error::from)?;
400    session::impersonate(cx, &mut *ex, Some((target.user_id(), until))).await?;
401    let target_id = target.user_id();
402    let event = AuthEvent::new(
403        AuthEventKind::Impersonate { until },
404        &signed.realm.id,
405        crate::tenant_id(cx),
406        &*signed.user,
407        &target_id,
408        Some(target.display_name()),
409    );
410    hook::run(cx, &signed.realm.auth_hooks, &event, ex).await?;
411    crate::bus::bus(cx).wake(&signed.realm.prefix, &signed.user.user_id());
412    Ok(())
413}
414
415/// `POST {prefix}/impersonate`: act as the user [`IMPERSONATE_FIELD`] names, then land on the
416/// panel root.
417pub(super) fn start_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
418    Box::pin(async move {
419        let Some(signed) = signed(cx) else {
420            return Err(unauthenticated_error(cx));
421        };
422        let parts = super::input::read_form(cx, body).await?;
423        crate::csrf::verify(cx, parts.last(crate::csrf::FIELD_NAME))?;
424        let authenticator = signed.realm.auth.authenticator().ok_or_else(forbidden)?;
425        let id = parts.last(IMPERSONATE_FIELD).ok_or_else(forbidden)?;
426        // An unknown id answers as a refused one does, so the route tells no one who exists.
427        let target = authenticator
428            .find_by_id(cx, id)
429            .await
430            .map_err(infrastructure_failure)?
431            .ok_or_else(forbidden)?;
432        let mut db = crate::db::db(cx)?;
433        let mut tx = db.transaction().await.map_err(infrastructure_failure)?;
434        impersonate(cx, &mut tx, &*target).await?;
435        tx.commit().await.map_err(infrastructure_failure)?;
436        see_other(panel_root(cx)).into_response(cx)
437    })
438}
439
440/// `POST {prefix}/impersonate/stop`: the actor is themselves again, on the panel root.
441pub(super) fn stop_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
442    Box::pin(async move {
443        let Some(signed) = signed(cx) else {
444            return Err(unauthenticated_error(cx));
445        };
446        let parts = super::input::read_form(cx, body).await?;
447        crate::csrf::verify(cx, parts.last(crate::csrf::FIELD_NAME))?;
448        if let Some(actor) = &signed.impersonator {
449            let mut db = crate::db::db(cx)?;
450            let mut tx = db.transaction().await.map_err(infrastructure_failure)?;
451            session::impersonate(cx, &mut tx, None).await?;
452            if !stopped(cx, signed, actor, tx).await? {
453                session::impersonate(cx, &mut db, None).await?;
454            }
455            crate::bus::bus(cx).wake(&signed.realm.prefix, &actor.user_id());
456        }
457        see_other(panel_root(cx)).into_response(cx)
458    })
459}
460
461/// Records that `signed` stops acting as another user, when they do, as they sign out: the stop a
462/// sign-out ends without the Stop button.
463pub(super) async fn stop_on_sign_out(cx: &Cx, signed: &SignedIn) -> topcoat::Result<()> {
464    let Some(actor) = &signed.impersonator else {
465        return Ok(());
466    };
467    let mut db = crate::db::db(cx)?;
468    let tx = db.transaction().await.map_err(infrastructure_failure)?;
469    // A stop the hooks fail to record is logged, and the sign-out goes on.
470    stopped(cx, signed, actor, tx).await.map(drop)
471}
472
473/// Records, through [`record_stop`], that `actor` no longer acts as the signed-in user of
474/// `signed`.
475async fn stopped(
476    cx: &Cx,
477    signed: &SignedIn,
478    actor: &Arc<dyn PanelUser>,
479    tx: toasty::Transaction<'_>,
480) -> topcoat::Result<bool> {
481    let target_id = signed.user.user_id();
482    let event = AuthEvent::new(
483        AuthEventKind::StopImpersonating,
484        &signed.realm.id,
485        crate::tenant_id(cx),
486        &**actor,
487        &target_id,
488        Some(signed.user.display_name()),
489    );
490    record_stop(cx, &signed.realm.auth_hooks, &event, tx).await
491}
492
493/// Runs `hooks` on the stop `event` inside `tx`, then commits it: `true`. A failing hook rolls
494/// `tx` back, with whatever else it held, and is logged rather than returned: `false`, and the
495/// caller ends the impersonation without the record, since a session that cannot stop acting as
496/// someone else is worse than a stop the trail misses.
497async fn record_stop(
498    cx: &Cx,
499    hooks: &[hook::AuthHookFn],
500    event: &AuthEvent<'_>,
501    mut tx: toasty::Transaction<'_>,
502) -> topcoat::Result<bool> {
503    match hook::run(cx, hooks, event, &mut tx).await {
504        Ok(()) => tx
505            .commit()
506            .await
507            .map_err(infrastructure_failure)
508            .map(|()| true),
509        Err(error) => {
510            tracing::error!(error = %error, ?event, "an auth hook failed to record a stop");
511            tx.rollback().await.map_err(infrastructure_failure)?;
512            Ok(false)
513        }
514    }
515}
516
517/// Where the banner's Stop button posts: `{prefix}/impersonate/stop`.
518pub(crate) fn stop_url(cx: &Cx) -> String {
519    format!("{}/impersonate/stop", panel_prefix(cx))
520}
521
522/// Whether someone acts as another user on this request: the pages [`refused`] names are then
523/// neither linked nor served.
524pub(crate) fn acting(cx: &Cx) -> bool {
525    signed(cx).is_some_and(|signed| signed.impersonator.is_some())
526}
527
528/// Whether the request reaches a page the actor may not use while acting as another user: one
529/// that changes the target's credentials, address, factors or tenants.
530pub(super) fn refused(cx: &Cx, panel: &Realm) -> bool {
531    let path = uri(cx).path();
532    let prefix = &panel.prefix;
533    [
534        panel.pages.profile.clone(),
535        panel.pages.two_factor.clone(),
536        panel.pages.tenant_profile.clone(),
537        format!("{prefix}/register-tenant"),
538        format!("{prefix}/verify-email"),
539    ]
540    .iter()
541    .any(|root| {
542        path.strip_prefix(root.as_str())
543            .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
544    })
545}