1mod linker;
6mod provider;
7
8use std::{marker::PhantomData, time::Duration};
9
10use topcoat::{
11 context::Cx,
12 cookie::{Cookie, Cookies, SameSite, cookies, try_private_cookies},
13 router::{
14 Body, RouteFuture,
15 error::{not_found, see_other},
16 request::{client_ip, uri},
17 response::{IntoResponse, Response},
18 },
19 view::{BoxView, ViewExt, view},
20};
21
22use self::{
23 linker::DynLinker,
24 provider::{Failure, Pending},
25};
26pub use self::{
27 linker::{IdentityLinker, ProviderIdentity},
28 provider::OidcProvider,
29};
30use super::{
31 Auth, PanelUser, infrastructure_failure,
32 login::{admit, login_url, next_from_query},
33 mail::private,
34 realm::{Realm, current_realm, panel_prefix},
35 registration::with_next,
36};
37use crate::{flash::set_notification, outcome::Notification};
38
39#[cfg(test)]
40mod tests;
41
42const PENDING_LIFETIME: Duration = Duration::from_mins(10);
44
45const COOKIE_NAME: &str = "__Host-tablo-oidc";
48
49const THROTTLE_SCOPE: &str = "provider-sign-in";
51
52pub struct Oidc<U> {
80 base_url: String,
82 linker: Box<dyn DynLinker>,
83 pub(super) providers: Vec<OidcProvider>,
84 user: PhantomData<fn() -> U>,
85}
86
87impl<U: PanelUser> Oidc<U> {
88 #[must_use]
97 pub fn new(base_url: impl Into<String>, linker: impl IdentityLinker<User = U>) -> Self {
98 Self {
99 base_url: base_url.into().trim_end_matches('/').to_string(),
100 linker: Box::new(linker),
101 providers: Vec::new(),
102 user: PhantomData,
103 }
104 }
105
106 #[must_use]
108 pub fn provider(mut self, provider: OidcProvider) -> Self {
109 self.providers.push(provider);
110 self
111 }
112
113 fn erase(self) -> Oidc<()> {
114 Oidc {
115 base_url: self.base_url,
116 linker: self.linker,
117 providers: self.providers,
118 user: PhantomData,
119 }
120 }
121}
122
123impl Oidc<()> {
124 fn find(&self, key: &str) -> Option<&OidcProvider> {
126 self.providers.iter().find(|provider| provider.key == key)
127 }
128
129 fn redirect_uri(&self, prefix: &str, key: &str) -> String {
131 format!("{}{prefix}/sign-in/{key}/callback", self.base_url)
132 }
133}
134
135impl<U> std::fmt::Debug for Oidc<U> {
136 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137 f.debug_struct("Oidc")
138 .field("base_url", &self.base_url)
139 .field("providers", &self.providers)
140 .finish_non_exhaustive()
141 }
142}
143
144impl<U: PanelUser> Auth<U> {
145 #[must_use]
158 pub fn oidc(mut self, oidc: Oidc<U>) -> Self {
159 self.config.oidc = Some(oidc.erase());
160 self
161 }
162}
163
164fn start_url(cx: &Cx, key: &str) -> String {
166 format!("{}/sign-in/{key}", panel_prefix(cx))
167}
168
169fn route_of<'a>(cx: &'a Cx, path: &str) -> Option<(&'a OidcProvider, bool)> {
172 let oidc = current_realm(cx)?.auth.oidc()?;
173 let rest = path
174 .strip_prefix(&panel_prefix(cx))?
175 .strip_prefix("/sign-in/")?;
176 let (key, callback) = match rest.strip_suffix("/callback") {
177 Some(key) => (key, true),
178 None => (rest, false),
179 };
180 Some((oidc.find(key)?, callback))
181}
182
183pub(super) fn serves(cx: &Cx, path: &str) -> bool {
186 route_of(cx, path).is_some()
187}
188
189pub(super) fn buttons<'a>(cx: &'a Cx, next: &str) -> Option<BoxView<'a>> {
192 let oidc = current_realm(cx)?.auth.oidc()?;
193 let links: Vec<(String, String, String)> = oidc
194 .providers
195 .iter()
196 .map(|provider| {
197 let label = crate::t!(
198 cx,
199 "tablo-oidc-continue",
200 provider = provider.label.localize(cx)
201 );
202 let href = with_next(start_url(cx, &provider.key), next);
203 (provider.key.clone(), href, label)
204 })
205 .collect();
206 let or = crate::t!(cx, "tablo-oidc-or");
207 Some(
208 view! {
209 <div class="flex flex-col gap-3">
210 <div
211 class="flex items-center gap-3 text-xs text-muted-foreground uppercase"
212 >
213 <span class="h-px flex-1 bg-border"></span>
214 (or)
215 <span class="h-px flex-1 bg-border"></span>
216 </div>
217 for (key, href, label) in links {
218 <a
221 href=(href)
222 data-oidc-provider=(key)
223 class=(tablo_ui::button_variants(
224 tablo_ui::ButtonVariant::Outline,
225 tablo_ui::ButtonSize::Md,
226 ))
227 data-slot="button"
228 data-tone="outline"
229 >
230 (label)
231 </a>
232 }
233 </div>
234 }
235 .boxed(),
236 )
237}
238
239pub(super) fn start(cx: &Cx, _body: Body) -> RouteFuture<'_> {
242 Box::pin(async move {
243 let panel = current_realm(cx).ok_or_else(not_found)?;
244 let oidc = panel.auth.oidc().ok_or_else(not_found)?;
245 let (provider, false) = route_of(cx, uri(cx).path()).ok_or_else(not_found)? else {
246 return Err(not_found().into());
247 };
248 let next = next_from_query(cx).unwrap_or_default();
249 let pending = Pending::new(panel.prefix.clone(), provider.key.clone(), next.clone());
250 let redirect_uri = oidc.redirect_uri(&panel.prefix, &provider.key);
251 let url = match provider.authorization_url(&redirect_uri, &pending).await {
252 Ok(url) => url,
253 Err(failure) => return refused(cx, provider, failure, &next),
254 };
255 let sealed = serde_json::to_string(&pending).map_err(topcoat::Error::from)?;
256 sealed_cookies(cx)?.add(
257 Cookie::build((COOKIE_NAME, sealed))
258 .path("/")
259 .http_only(true)
260 .secure(true)
261 .same_site(SameSite::Lax)
263 .max_age(topcoat::cookie::time::Duration::seconds(
264 i64::try_from(PENDING_LIFETIME.as_secs()).unwrap_or(i64::MAX),
265 ))
266 .build(),
267 );
268 private(see_other(url).into_response(cx)?)
269 })
270}
271
272pub(super) fn callback(cx: &Cx, _body: Body) -> RouteFuture<'_> {
275 Box::pin(async move {
276 let panel = current_realm(cx).ok_or_else(not_found)?;
277 let oidc = panel.auth.oidc().ok_or_else(not_found)?;
278 let (provider, true) = route_of(cx, uri(cx).path()).ok_or_else(not_found)? else {
279 return Err(not_found().into());
280 };
281 let pending = sealed_cookies(cx)?
283 .get(COOKIE_NAME)
284 .and_then(|cookie| serde_json::from_str::<Pending>(cookie.value()).ok());
285 cookies(cx).remove(Cookie::build((COOKIE_NAME, "")).path("/").secure(true));
286 let query = query(cx);
287 let read = |key: &str| query.iter().find(|(name, _)| name == key).map(|(_, v)| v);
288 let now = jiff::Timestamp::now().as_second();
289 let lifetime = i64::try_from(PENDING_LIFETIME.as_secs()).unwrap_or(i64::MAX);
290 let Some(pending) = pending.filter(|pending| {
291 (0..lifetime).contains(&(now - pending.started))
292 && pending.panel == panel.prefix
293 && pending.provider == provider.key
294 && read("state").is_some_and(|state| {
295 subtle::ConstantTimeEq::ct_eq(state.as_bytes(), pending.state.as_bytes()).into()
296 })
297 }) else {
298 return refused(cx, provider, Failure::Refused, "");
299 };
300 let next = pending.next.clone();
301 let Some(code) = read("code").filter(|code| !code.is_empty()) else {
302 return refused(cx, provider, Failure::Refused, &next);
304 };
305 let throttle = panel.auth.login_throttle();
308 let client = client_ip(cx);
309 if !throttle
310 .attempt(cx, THROTTLE_SCOPE, &provider.key, client)
311 .await?
312 {
313 tracing::warn!(panel = %panel.prefix, client = ?client, "provider sign-in throttled");
314 return refused(cx, provider, Failure::Refused, &next);
315 }
316 let redirect_uri = oidc.redirect_uri(&panel.prefix, &provider.key);
317 let identity = match provider.redeem(code, &redirect_uri, &pending).await {
318 Ok(identity) => identity,
319 Err(failure) => return refused(cx, provider, failure, &next),
320 };
321 throttle
322 .clear(cx, THROTTLE_SCOPE, &provider.key, client)
323 .await?;
324 let user = match oidc.linker.sign_in(cx, &identity).await {
325 Ok(user) => user,
326 Err(error) => {
327 let error = infrastructure_failure(error);
328 if crate::error::TabloError::is_infrastructure(&error) {
329 return refused(cx, provider, Failure::Unavailable, &next);
330 }
331 return Err(error);
332 }
333 };
334 let Some(user) = user.filter(|user| user.can_access_panel(&panel.id)) else {
335 return refused(cx, provider, Failure::Refused, &next);
336 };
337 admit(cx, panel, &*user, next).await
338 })
339}
340
341fn query(cx: &Cx) -> Vec<(String, String)> {
343 uri(cx)
344 .query()
345 .map(|query| {
346 form_urlencoded::parse(query.as_bytes())
347 .into_owned()
348 .collect()
349 })
350 .unwrap_or_default()
351}
352
353fn sealed_cookies(
355 cx: &Cx,
356) -> topcoat::Result<topcoat::cookie::PrivateJar<'_, &topcoat::cookie::CookieJar>> {
357 try_private_cookies(cx).ok_or_else(|| {
358 crate::error::declaration("provider sign-in needs the router's cookie `Key`".to_owned())
359 })
360}
361
362fn refused(
364 cx: &Cx,
365 provider: &OidcProvider,
366 failure: Failure,
367 next: &str,
368) -> topcoat::Result<Response> {
369 let message = match failure {
370 Failure::Refused => "tablo-oidc-failed",
371 Failure::Unavailable => "tablo-oidc-unavailable",
372 };
373 set_notification(
374 cx,
375 Notification::error(crate::t!(
376 cx,
377 message,
378 provider = provider.label.localize(cx)
379 )),
380 );
381 private(see_other(with_next(login_url(cx), next)).into_response(cx)?)
382}
383
384pub(super) fn routes(
386 mut builder: topcoat::router::RouterBuilder,
387 realm: &Realm,
388) -> topcoat::router::RouterBuilder {
389 use topcoat::router::RouteFn;
390
391 let Some(oidc) = realm.auth.oidc() else {
392 return builder;
393 };
394 for provider in &oidc.providers {
395 let path = format!("{}/sign-in/{}", realm.prefix, provider.key);
396 builder = builder
397 .route(RouteFn::new(
398 http::Method::GET,
399 crate::naming::route_path(&path),
400 start,
401 ))
402 .route(RouteFn::new(
403 http::Method::GET,
404 crate::naming::route_path(&format!("{path}/callback")),
405 callback,
406 ));
407 }
408 builder
409}
410
411pub(super) fn declaration_errors(
416 auth: &super::AuthConfig,
417 has_key: bool,
418) -> Vec<crate::DeclarationErrorKind> {
419 use crate::{DeclarationErrorKind, declaration::OidcFault};
420
421 let Some(oidc) = &auth.oidc else {
422 return Vec::new();
423 };
424 if auth.authenticator().is_none() {
425 return vec![DeclarationErrorKind::Oidc(OidcFault::AuthDisabled)];
426 }
427 let mut faults = Vec::new();
428 if auth.external().is_some() {
429 faults.push(OidcFault::ExternalAuth);
430 }
431 if !has_key {
432 faults.push(OidcFault::MissingKey);
433 }
434 let origin = url::Url::parse(&oidc.base_url)
435 .ok()
436 .filter(|url| url.path() == "/" && url.query().is_none() && url.fragment().is_none());
437 if !origin.is_some_and(|_| provider::secure_url(&oidc.base_url)) {
438 faults.push(OidcFault::BaseUrl(oidc.base_url.clone()));
439 }
440 if oidc.providers.is_empty() {
441 faults.push(OidcFault::NoProvider);
442 }
443 for (index, provider) in oidc.providers.iter().enumerate() {
444 if !provider.key_is_valid() {
445 faults.push(OidcFault::ProviderKey(provider.key.clone()));
446 } else if oidc.providers[..index]
447 .iter()
448 .any(|earlier| earlier.key == provider.key)
449 {
450 faults.push(OidcFault::DuplicateProvider(provider.key.clone()));
451 }
452 if !provider.issuer_is_valid() {
453 faults.push(OidcFault::Issuer(provider.key.clone()));
454 }
455 for (name, _) in &provider.params {
456 if provider::RESERVED_PARAMS.contains(&name.as_str()) {
457 faults.push(OidcFault::ReservedParam(provider.key.clone(), name.clone()));
458 }
459 }
460 }
461 faults.into_iter().map(DeclarationErrorKind::Oidc).collect()
462}