1pub(crate) mod account;
8mod columns;
9pub(crate) mod config;
10mod email_change;
11pub(crate) mod external;
12mod gate;
13pub(crate) mod hook;
14pub(crate) mod impersonation;
15pub(crate) mod input;
16mod login;
17pub(crate) mod mail;
18pub(crate) mod mount;
19pub(crate) mod oidc;
20mod page;
21pub(crate) mod panel_user;
22pub(crate) mod password;
23pub(crate) mod password_reset;
24pub(crate) mod profile;
25mod realm;
26pub(crate) mod registration;
27pub(crate) mod session;
28pub(crate) mod tenant_profile;
29pub(crate) mod tenant_registration;
30pub(crate) mod throttle;
31mod token;
32#[cfg(feature = "two-factor")]
33pub(crate) mod two_factor;
34pub(crate) mod verification;
35
36use std::{
37 any::{Any, TypeId},
38 sync::Arc,
39};
40
41use topcoat::{
42 context::{Cx, try_context},
43 router::{
44 error::{forbidden, redirect, unauthorized},
45 request::{method, original_headers, original_method, uri},
46 },
47};
48
49use self::realm::realms;
50#[cfg(feature = "testing")]
51pub use self::session::mint_session;
52#[cfg(feature = "two-factor")]
53pub use self::two_factor::{AuthFactor, FactorKind};
54#[cfg(feature = "two-factor")]
56pub(crate) use self::two_factor::{
57 TwoFactor, offered as two_factor_offered, settings_url as two_factor_url,
58};
59pub use self::{
60 account::normalize_email,
61 columns::ColumnPreference,
62 email_change::{EmailChange, request_email_change},
63 impersonation::{IMPERSONATE_FIELD, impersonate, impersonate_button, impersonator},
64 login::{LOGIN_FIELD, NEXT_FIELD, PASSWORD_FIELD, TENANT_FIELD, safe_next},
65 password::{AdminUser, create_admin, hash_password, verify_password},
66 password_reset::RESET_LIFETIME,
67 registration::{MIN_PASSWORD_CHARS, new_password_errors},
68 session::{
69 AuthSession, SESSION_COOKIE_PREFIX, SESSION_LIFETIME, revoke_sessions_for_user,
70 session_cookie,
71 },
72 throttle::AuthThrottle,
73 token::{AuthToken, TokenPurpose},
74 verification::VERIFICATION_LIFETIME,
75};
76pub(crate) use self::{
77 account::{PasswordAccount, PasswordAuth},
78 columns::{load_choice, save_choice},
79 config::{Auth, AuthConfig},
80 gate::{PagePanelStamp, PanelGate, RuntimeGate, still_signed_in},
81 impersonation::{may_impersonate, stop_url as stop_impersonating_url},
82 login::{logout_url, tenant_url},
83 mail::AuthMail,
84 panel_user::{Authenticator, PanelUser},
85 password::end_changed_credentials,
86 password_reset::PasswordReset,
87 profile::{
88 Profile, ProfileEditor, ProfileField, ProfileUpdate, offered as profile_offered,
89 profile_url,
90 },
91 realm::{
92 AuthHost, CurrentRealm, Host, Realm, SettingsPage, SettingsPaths, current_realm,
93 declared_host, panel_prefix,
94 },
95 registration::{Registrar, SignUp},
96 tenant_profile::{TenantEditor, offered as tenant_profile_offered, tenant_profile_url},
97 tenant_registration::{
98 TenantRegistration, offered as tenant_registration_offered, register_tenant_url,
99 },
100 throttle::LoginThrottle,
101 verification::EmailVerification,
102};
103use crate::{
104 BoxFuture,
105 tenancy::{Membership, TenantId},
106};
107
108pub(crate) trait DynAuthenticator: Send + Sync {
110 fn verify<'a>(
111 &'a self,
112 cx: &'a Cx,
113 login: &'a str,
114 password: &'a str,
115 ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>>;
116 fn find_by_id<'a>(
117 &'a self,
118 cx: &'a Cx,
119 id: &'a str,
120 ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>>;
121 #[cfg(feature = "two-factor")]
123 fn confirm_password<'a>(
124 &'a self,
125 cx: &'a Cx,
126 user: &'a dyn PanelUser,
127 password: &'a str,
128 ) -> BoxFuture<'a, topcoat::Result<bool>>;
129 fn store_locale<'a>(
131 &'a self,
132 cx: &'a Cx,
133 user: &'a dyn PanelUser,
134 locale: &'a topcoat::l10n::Locale,
135 ) -> BoxFuture<'a, topcoat::Result<()>>;
136 fn user_type(&self) -> TypeId;
139 fn user_type_name(&self) -> &'static str;
141 fn changed_credentials(&self, before: &dyn Any, after: &dyn Any) -> Option<String>;
143}
144
145impl<A: Authenticator> DynAuthenticator for A {
146 fn verify<'a>(
147 &'a self,
148 cx: &'a Cx,
149 login: &'a str,
150 password: &'a str,
151 ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>> {
152 Box::pin(async move {
153 let user = Authenticator::verify(self, cx, login, password).await?;
154 Ok(user.map(|user| Arc::new(user) as Arc<dyn PanelUser>))
155 })
156 }
157
158 fn find_by_id<'a>(
159 &'a self,
160 cx: &'a Cx,
161 id: &'a str,
162 ) -> BoxFuture<'a, topcoat::Result<Option<Arc<dyn PanelUser>>>> {
163 Box::pin(async move {
164 let user = Authenticator::find_by_id(self, cx, id).await?;
165 Ok(user.map(|user| Arc::new(user) as Arc<dyn PanelUser>))
166 })
167 }
168
169 #[cfg(feature = "two-factor")]
170 fn confirm_password<'a>(
171 &'a self,
172 cx: &'a Cx,
173 user: &'a dyn PanelUser,
174 password: &'a str,
175 ) -> BoxFuture<'a, topcoat::Result<bool>> {
176 Box::pin(async move {
177 let user: &dyn Any = user;
178 match user.downcast_ref::<A::User>() {
179 Some(user) => Authenticator::confirm_password(self, cx, user, password).await,
180 None => Ok(false),
181 }
182 })
183 }
184
185 fn store_locale<'a>(
186 &'a self,
187 cx: &'a Cx,
188 user: &'a dyn PanelUser,
189 locale: &'a topcoat::l10n::Locale,
190 ) -> BoxFuture<'a, topcoat::Result<()>> {
191 Box::pin(async move {
192 let user: &dyn Any = user;
193 match user.downcast_ref::<A::User>() {
194 Some(user) => Authenticator::store_locale(self, cx, user, locale).await,
195 None => Ok(()),
196 }
197 })
198 }
199
200 fn user_type(&self) -> TypeId {
201 TypeId::of::<A::User>()
202 }
203
204 fn user_type_name(&self) -> &'static str {
205 std::any::type_name::<A::User>()
206 }
207
208 fn changed_credentials(&self, before: &dyn Any, after: &dyn Any) -> Option<String> {
209 Authenticator::changed_credentials(self, before, after)
210 }
211}
212
213#[derive(Clone)]
215pub(crate) struct SignedIn {
216 pub(crate) user: Arc<dyn PanelUser>,
217 pub(crate) realm: Arc<Realm>,
220 pub(crate) tenant: Option<TenantId>,
223 pub(crate) impersonator: Option<Arc<dyn PanelUser>>,
226}
227
228impl SignedIn {
229 pub(crate) fn may_enter(&self) -> bool {
231 self.user.can_access_panel(&self.realm.id)
232 }
233
234 pub(crate) fn sign_into(self, cx: &Cx) -> Cx {
238 let cx = if self.refuses_writes() {
239 cx.with(crate::policy::WritesRefused)
240 } else {
241 cx.clone()
242 };
243 if crate::i18n::chose_locale(&cx) {
244 return cx.with(self);
245 }
246 crate::i18n::addressed_to(&cx, self.user.locale().as_ref()).with(self)
247 }
248
249 pub(crate) fn acting_tenant(&self, cx: &Cx) -> Option<TenantId> {
253 acting_tenant(&self.realm, &*self.user, self.tenant, cx)
254 }
255}
256
257pub(crate) fn acting_tenant(
260 realm: &Realm,
261 user: &dyn PanelUser,
262 selected: Option<TenantId>,
263 cx: &Cx,
264) -> Option<TenantId> {
265 if !realm.serves_tenants {
266 return None;
267 }
268 let tenants = user.tenants();
269 let member = |tenant: TenantId| tenants.iter().find(|m| m.tenant == tenant);
270 claimed_tenant(cx)
271 .and_then(member)
272 .or_else(|| selected.and_then(member))
273 .or_else(|| user.default_tenant().and_then(member))
274 .or_else(|| tenants.first())
275 .map(|membership| membership.tenant)
276}
277
278fn claimed_tenant(cx: &Cx) -> Option<TenantId> {
280 try_context::<http::request::Parts>(cx)
281 .and_then(|parts| parts.extensions.get::<crate::tenancy::ClaimedTenant>())
282 .map(|claimed| claimed.0)
283}
284
285pub(crate) fn resolved(cx: &Cx) -> Option<&SignedIn> {
288 let signed = try_context::<SignedIn>(cx)?;
289 match current_realm(cx) {
290 Some(realm) if !Arc::ptr_eq(&signed.realm, realm) => None,
291 _ => Some(signed),
292 }
293}
294
295pub(crate) fn signed(cx: &Cx) -> Option<&SignedIn> {
298 resolved(cx).filter(|signed| signed.may_enter())
299}
300
301pub fn membership(cx: &Cx) -> Option<&Membership> {
308 let tenant = crate::tenant_id(cx)?;
309 signed(cx)?
310 .user
311 .tenants()
312 .iter()
313 .find(|m| m.tenant == tenant)
314}
315
316pub(crate) fn session_tenant(cx: &Cx) -> Option<TenantId> {
320 match signed(cx) {
321 Some(signed) => signed.acting_tenant(cx),
322 None => claimed_tenant(cx),
323 }
324}
325
326pub(crate) fn session_time_zone(cx: &Cx) -> Option<jiff::tz::TimeZone> {
330 signed(cx)
331 .and_then(|signed| signed.user.time_zone())
332 .or_else(|| current_realm(cx).map(|realm| realm.time_zone.clone()))
333}
334
335pub(crate) fn session_catalog(cx: &Cx) -> Option<&crate::i18n::Catalog> {
338 current_realm(cx).map(|realm| &*realm.catalog)
339}
340
341pub fn user<U: PanelUser>(cx: &Cx) -> Option<&U> {
365 let found = signed(cx).and_then(|signed| {
366 let user: &dyn Any = &*signed.user;
367 user.downcast_ref()
368 });
369 if found.is_none() {
370 report_unloaded::<U>(cx);
371 }
372 found
373}
374
375fn report_unloaded<U: PanelUser>(cx: &Cx) {
377 static REPORTED: std::sync::Mutex<Vec<TypeId>> = std::sync::Mutex::new(Vec::new());
378 let Some(message) = unloaded_type::<U>(cx) else {
379 return;
380 };
381 let mut reported = REPORTED
382 .lock()
383 .unwrap_or_else(std::sync::PoisonError::into_inner);
384 if !reported.contains(&TypeId::of::<U>()) {
385 reported.push(TypeId::of::<U>());
386 tracing::error!("{message}");
387 }
388}
389
390fn unloaded_type<U: PanelUser>(cx: &Cx) -> Option<String> {
393 let mut mounted = realms(cx);
394 if mounted.is_empty() {
395 mounted.extend(current_realm(cx).cloned());
396 }
397 let loaded: Vec<&dyn DynAuthenticator> = mounted
398 .iter()
399 .filter_map(|realm| realm.auth.authenticator())
400 .collect();
401 if loaded.is_empty()
402 || loaded
403 .iter()
404 .any(|auth| auth.user_type() == TypeId::of::<U>())
405 {
406 return None;
407 }
408 let names: std::collections::BTreeSet<_> =
409 loaded.iter().map(|auth| auth.user_type_name()).collect();
410 Some(format!(
411 "auth::user::<{}> can never find a user: the mounted panels sign in {}",
412 std::any::type_name::<U>(),
413 names.into_iter().collect::<Vec<_>>().join(", "),
414 ))
415}
416
417pub fn actor(cx: &Cx) -> Option<&dyn PanelUser> {
431 signed(cx).map(|signed| &**signed.impersonator.as_ref().unwrap_or(&signed.user))
432}
433
434pub fn require_user<U: PanelUser>(cx: &Cx) -> topcoat::Result<&U> {
444 match signed(cx) {
445 Some(_) => user(cx).ok_or_else(|| forbidden().into()),
446 None => Err(unauthenticated_error(cx)),
447 }
448}
449
450pub fn signed_in(cx: &Cx) -> bool {
452 signed(cx).is_some()
453}
454
455pub fn enforced(cx: &Cx) -> bool {
460 match current_realm(cx) {
461 Some(realm) => realm.gates(),
462 None => realms(cx).iter().any(|realm| realm.gates()),
463 }
464}
465
466pub fn guard(cx: &Cx) -> topcoat::Result<()> {
478 if enforced(cx) && !signed_in(cx) {
479 return Err(unauthenticated_error(cx));
480 }
481 Ok(())
482}
483
484fn unauthenticated_error(cx: &Cx) -> topcoat::Error {
486 if page_load(cx) {
487 redirect(login::login_url_with_next(cx)).into()
488 } else {
489 unauthorized().into()
490 }
491}
492
493pub(crate) fn page_load(cx: &Cx) -> bool {
496 let page_method = matches!(*method(cx), http::Method::GET | http::Method::HEAD);
497 let rerun = !matches!(*original_method(cx), http::Method::GET | http::Method::HEAD)
501 && original_headers(cx).get(&topcoat::runtime::RUNTIME_HEADER) == Some(&RERUN_MARKER);
502 page_method
503 && !rerun
504 && !uri(cx)
505 .path()
506 .starts_with(crate::topcoat_compat::RUNTIME_PREFIX)
507}
508
509fn panel_root(cx: &Cx) -> String {
511 panel_prefix(cx)
512}
513
514fn infrastructure_failure(error: impl Into<topcoat::Error>) -> topcoat::Error {
526 crate::error::driver_failure(error, UNAVAILABLE_ERROR)
527}
528
529const UNAVAILABLE_ERROR: &str = "Sign-in is unavailable right now. Try again shortly.";
539
540static RERUN_MARKER: http::HeaderValue = http::HeaderValue::from_static("true");
543
544#[cfg(test)]
545mod tests;