| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use im_core::accounts; |
| 6 | use im_core::events; |
| 7 | use im_core::model::{User, UserId}; |
| 8 | use im_core::settings::{self, Smtp}; |
| 9 | use serde::Deserialize; |
| 10 | use topcoat::Result; |
| 11 | use topcoat::context::Cx; |
| 12 | use topcoat::cookie::Cookies; |
| 13 | use topcoat::router::content::Form; |
| 14 | use topcoat::router::response::{IntoResponse, Response}; |
| 15 | use topcoat::router::{HeaderValue, StatusCode, header, route}; |
| 16 | use topcoat::view::{Child, ViewExt, view}; |
| 17 | |
| 18 | use crate::health::{Probe, probe_family}; |
| 19 | use crate::i18n::{self, Key, lang_of, t}; |
| 20 | use crate::layout::shell; |
| 21 | use crate::mailer; |
| 22 | use crate::pages::{error_text, query_value}; |
| 23 | use crate::server::{self, App}; |
| 24 | |
| 25 | fn app(cx: &Cx) -> &App { |
| 26 | server::app(cx) |
| 27 | } |
| 28 | |
| 29 | |
| 30 | async fn require_admin(cx: &Cx) -> std::result::Result<User, Box<Response>> { |
| 31 | match server::current_user(cx).await { |
| 32 | Some(user) if user.admin => Ok(user), |
| 33 | _ => Err(Box::new( |
| 34 | ( |
| 35 | StatusCode::SEE_OTHER, |
| 36 | [(header::LOCATION, HeaderValue::from_static("/"))], |
| 37 | ) |
| 38 | .into_response(cx) |
| 39 | .expect("a redirect can always be built"), |
| 40 | )), |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | |
| 45 | |
| 46 | fn escape(raw: &str) -> String { |
| 47 | raw.replace('&', "&") |
| 48 | .replace('<', "<") |
| 49 | .replace('>', ">") |
| 50 | .replace('"', """) |
| 51 | .replace('\'', "'") |
| 52 | } |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | struct AdminDialog<'a> { |
| 63 | id: &'a str, |
| 64 | word: &'a str, |
| 65 | extra_class: &'a str, |
| 66 | title: &'a str, |
| 67 | body: &'a str, |
| 68 | wide: bool, |
| 69 | } |
| 70 | |
| 71 | |
| 72 | |
| 73 | fn dialog_id(action: &str, field: &str, id: &str) -> String { |
| 74 | let raw = format!("{action}\0{field}\0{id}"); |
| 75 | let hash = raw.bytes().fold(0xcbf29ce484222325u64, |hash, byte| { |
| 76 | (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3) |
| 77 | }); |
| 78 | format!("d{hash:x}") |
| 79 | } |
| 80 | |
| 81 | fn admin_dialog(ask: AdminDialog<'_>) -> String { |
| 82 | let wide = if ask.wide { " admin-dialog-wide" } else { "" }; |
| 83 | format!( |
| 84 | r#"<button type="button" class="admin-action{extra}" popovertarget="{id}">{word}</button><div id="{id}" popover="auto" class="admin-dialog{wide}"><div class="admin-dialog-title">{title}</div>{body}</div>"#, |
| 85 | extra = ask.extra_class, |
| 86 | id = ask.id, |
| 87 | word = ask.word, |
| 88 | title = ask.title, |
| 89 | body = ask.body, |
| 90 | wide = wide, |
| 91 | ) |
| 92 | } |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | struct ConfirmAction<'a> { |
| 99 | field: &'a str, |
| 100 | id: &'a str, |
| 101 | action: &'a str, |
| 102 | word: &'a str, |
| 103 | extra_class: &'a str, |
| 104 | title: &'a str, |
| 105 | cost: &'a str, |
| 106 | confirm: &'a str, |
| 107 | } |
| 108 | fn confirm_action(ask: ConfirmAction<'_>) -> String { |
| 109 | let ConfirmAction { |
| 110 | field, |
| 111 | id, |
| 112 | action, |
| 113 | word, |
| 114 | extra_class, |
| 115 | title, |
| 116 | cost, |
| 117 | confirm, |
| 118 | } = ask; |
| 119 | let dialog = dialog_id(action, field, id); |
| 120 | let body = format!( |
| 121 | r#"<div class="muted">{cost}</div><form method="post" action="{action}"><input type="hidden" name="{field}" value="{id}"><button class="admin-action{extra_class}" type="submit">{confirm}</button></form>"# |
| 122 | ); |
| 123 | admin_dialog(AdminDialog { |
| 124 | id: &dialog, |
| 125 | word, |
| 126 | extra_class, |
| 127 | title, |
| 128 | body: &body, |
| 129 | wide: false, |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | |
| 134 | |
| 135 | const ADMIN_SCRIPT: &str = r#"<script>(function () { |
| 136 | if (window.__imAdmin) { return; } |
| 137 | window.__imAdmin = true; |
| 138 | document.addEventListener('click', function (e) { |
| 139 | var b = e.target.closest && e.target.closest('.admin-copy'); |
| 140 | if (!b) { return; } |
| 141 | var row = b.closest('.admin-copy-row'); |
| 142 | var v = row && row.querySelector('.admin-copy-value'); |
| 143 | if (!v) { return; } |
| 144 | var done = function () { b.textContent = b.getAttribute('data-copied-label'); }; |
| 145 | if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(v.textContent).then(done, done); } else { try { document.execCommand('copy'); } catch (err) {} done(); } |
| 146 | }, true); |
| 147 | })();</script>"#; |
| 148 | |
| 149 | fn back(cx: &Cx, section: &str, extra: &str) -> Result<Response> { |
| 150 | ( |
| 151 | StatusCode::SEE_OTHER, |
| 152 | [( |
| 153 | header::LOCATION, |
| 154 | HeaderValue::from_str(&format!("/admin?section={section}{extra}")) |
| 155 | .unwrap_or_else(|_| HeaderValue::from_static("/admin")), |
| 156 | )], |
| 157 | ) |
| 158 | .into_response(cx) |
| 159 | } |
| 160 | |
| 161 | #[route(GET "/admin")] |
| 162 | async fn admin_page(cx: &Cx) -> Result<Response> { |
| 163 | let me = match require_admin(cx).await { |
| 164 | Ok(me) => me, |
| 165 | Err(redirect) => return Ok(*redirect), |
| 166 | }; |
| 167 | let lang = lang_of(Some(&me)); |
| 168 | let query = topcoat::router::request::uri(cx) |
| 169 | .query() |
| 170 | .unwrap_or("") |
| 171 | .to_string(); |
| 172 | let section = query_value(&query, "section").unwrap_or_else(|| "users".to_string()); |
| 173 | let error = query_value(&query, "error"); |
| 174 | let ok = query_value(&query, "ok"); |
| 175 | let why = query_value(&query, "why"); |
| 176 | let invited = query_value(&query, "invited"); |
| 177 | |
| 178 | |
| 179 | let shown = query_value(&query, "shown") |
| 180 | .as_deref() |
| 181 | .and_then(server::take_shown_secret); |
| 182 | |
| 183 | let nav = |current: &str| { |
| 184 | [ |
| 185 | ("users", t(lang, Key::NavUsers)), |
| 186 | ("services", t(lang, Key::NavServices)), |
| 187 | ("message", t(lang, Key::NavMessage)), |
| 188 | ("settings", t(lang, Key::NavSettings)), |
| 189 | ("logs", t(lang, Key::NavLogs)), |
| 190 | ("health", t(lang, Key::NavHealth)), |
| 191 | ] |
| 192 | .into_iter() |
| 193 | .map(|(id, label)| { |
| 194 | format!( |
| 195 | r#"<a class="admin-nav{}" href="/admin?section={id}">{label}</a>"#, |
| 196 | if id == current { " admin-nav-on" } else { "" } |
| 197 | ) |
| 198 | }) |
| 199 | .collect::<String>() |
| 200 | }; |
| 201 | |
| 202 | let section_html = match section.as_str() { |
| 203 | "mail" => mail_section(cx, lang).await?, |
| 204 | "message" => message_section(cx, lang).await?, |
| 205 | "settings" => settings_section(cx, lang).await?, |
| 206 | "logs" => logs_section(cx, lang).await?, |
| 207 | "health" => health_section(cx, lang).await?, |
| 208 | |
| 209 | |
| 210 | "services" | "clients" => services_section(cx, shown, lang).await?, |
| 211 | _ => users_section(cx, &me, invited.as_deref(), lang).await?, |
| 212 | }; |
| 213 | |
| 214 | let banner = match (ok.as_deref(), error.as_deref()) { |
| 215 | (Some(code), _) => Some(format!( |
| 216 | r#"<div class="auth-ok">{}</div>"#, |
| 217 | match code { |
| 218 | "invited" => t(lang, Key::OkInvited), |
| 219 | "revoked" => t(lang, Key::OkRevoked), |
| 220 | "session_revoked" => t(lang, Key::OkSessionRevoked), |
| 221 | "disabled" => t(lang, Key::OkDisabled), |
| 222 | "enabled" => t(lang, Key::OkEnabled), |
| 223 | "smtp" => t(lang, Key::OkSmtpSaved), |
| 224 | "smtp_test" => t(lang, Key::OkSmtpTest), |
| 225 | "message" => t(lang, Key::OkMessageSent), |
| 226 | "uninvited" => t(lang, Key::OkUninvited), |
| 227 | "deleted" => t(lang, Key::OkDeleted), |
| 228 | "settings" => t(lang, Key::OkSettingsSaved), |
| 229 | "services" => t(lang, Key::OkServicesSaved), |
| 230 | "email_changed" => t(lang, Key::OkEmailChanged), |
| 231 | "client_revoked" => t(lang, Key::OkClientRevoked), |
| 232 | _ => t(lang, Key::OkDone), |
| 233 | } |
| 234 | )), |
| 235 | (_, Some(code)) => Some(format!( |
| 236 | r#"<div class="auth-problem">{}{}</div>"#, |
| 237 | error_text(code, lang), |
| 238 | why.as_deref() |
| 239 | .map(|detail| format!("<div class=\"muted\">{}</div>", escape(detail))) |
| 240 | .unwrap_or_default(), |
| 241 | )), |
| 242 | _ => None, |
| 243 | }; |
| 244 | |
| 245 | let my_email = me.email.clone(); |
| 246 | let stage = view! { |
| 247 | cx => |
| 248 | <main class="admin-shell"> |
| 249 | <div class="admin-column"> |
| 250 | <div class="admin-bar"> |
| 251 | // The brand is the way back to the landing, as in iz's |
| 252 | // topbar; the address stays a link too. |
| 253 | <a class="wordmark-text wordmark-home" href="/">"im"</a> |
| 254 | <nav class="admin-tabs">(topcoat::view::Unescaped::new_unchecked(nav(§ion)))</nav> |
| 255 | <a class="auth-alt" href="/">(my_email)</a> |
| 256 | </div> |
| 257 | if let Some(banner) = banner { |
| 258 | (topcoat::view::Unescaped::new_unchecked(banner)) |
| 259 | } |
| 260 | (topcoat::view::Unescaped::new_unchecked(section_html)) |
| 261 | (topcoat::view::Unescaped::new_unchecked(ADMIN_SCRIPT.to_string())) |
| 262 | </div> |
| 263 | </main> |
| 264 | }; |
| 265 | shell(cx, t(lang, Key::TitleAdmin), Some(me), Child::new(stage)) |
| 266 | .await? |
| 267 | .first() |
| 268 | .await? |
| 269 | .into_response(cx) |
| 270 | } |
| 271 | |
| 272 | /// One person's folded strip under their row: the live sessions — a small |
| 273 | /// table with a per-session revoke, or the muted line when nothing is live — |
| 274 | /// and, beside it, the address edit. The admin's own row gets both: "you" |
| 275 | /// still signs in from somewhere, and the rescue reaches their own address. |
| 276 | fn sessions_row( |
| 277 | user: &User, |
| 278 | sessions: &[im_core::sessions::SessionInfo], |
| 279 | lang: i18n::Lang, |
| 280 | ) -> String { |
| 281 | let id = escape(&user.id.to_string()); |
| 282 | let body = if sessions.is_empty() { |
| 283 | format!( |
| 284 | r#"<div class="muted">{}</div>"#, |
| 285 | t(lang, Key::AdminSessionsEmpty) |
| 286 | ) |
| 287 | } else { |
| 288 | let mut rows = String::new(); |
| 289 | for session in sessions { |
| 290 | let seen_at = session.seen_at.unwrap_or(session.created_at); |
| 291 | let seen = seen_at |
| 292 | .format(&time::macros::format_description!( |
| 293 | "[year]-[month]-[day] [hour]:[minute]" |
| 294 | )) |
| 295 | .unwrap_or_else(|_| seen_at.date().to_string()); |
| 296 | let created = session |
| 297 | .created_at |
| 298 | .format(&time::macros::format_description!( |
| 299 | "[year]-[month]-[day] [hour]:[minute]" |
| 300 | )) |
| 301 | .unwrap_or_else(|_| session.created_at.date().to_string()); |
| 302 | rows.push_str(&format!( |
| 303 | concat!( |
| 304 | r#"<tr><td title="{}">{}</td>"#, |
| 305 | r#"<td class="mono">{}</td>"#, |
| 306 | r#"<td class="muted">{}</td>"#, |
| 307 | r#"<td class="muted">{}</td>"#, |
| 308 | r#"<td class="actions">"#, |
| 309 | r#"<form method="post" action="/admin/session_revoke">"#, |
| 310 | r#"<input type="hidden" name="user" value="{id}">"#, |
| 311 | r#"<input type="hidden" name="session" value="{}">"#, |
| 312 | r#"<button class="admin-action" type="submit">{}</button>"#, |
| 313 | r#"</form></td></tr>"# |
| 314 | ), |
| 315 | // The cell reads as a device; the raw agent rides the title |
| 316 | // for the admin who needs the whole string. |
| 317 | session |
| 318 | .agent |
| 319 | .as_deref() |
| 320 | .filter(|agent| !agent.is_empty()) |
| 321 | .map(escape) |
| 322 | .unwrap_or_default(), |
| 323 | escape(&crate::pages::device_label(session.agent.as_deref(), lang)), |
| 324 | session |
| 325 | .ip |
| 326 | .as_deref() |
| 327 | .map(escape) |
| 328 | .unwrap_or_else(|| "—".to_string()), |
| 329 | created, |
| 330 | seen, |
| 331 | escape(&session.token_hash), |
| 332 | t(lang, Key::RevokeButton), |
| 333 | id = id, |
| 334 | )); |
| 335 | } |
| 336 | format!( |
| 337 | concat!( |
| 338 | r#"<div class="admin-table-wrap"><table class="admin-table"><thead><tr>"#, |
| 339 | r#"<th>{device}</th><th>{address}</th><th>{signed_in}</th><th>{last_seen}</th><th></th>"#, |
| 340 | r#"</tr></thead><tbody>{rows}</tbody></table></div>"# |
| 341 | ), |
| 342 | device = t(lang, Key::DeviceLabel), |
| 343 | address = t(lang, Key::AddressLabel), |
| 344 | signed_in = t(lang, Key::SignedInLabel), |
| 345 | last_seen = t(lang, Key::LastSeenLabel), |
| 346 | rows = rows, |
| 347 | ) |
| 348 | }; |
| 349 | format!( |
| 350 | concat!( |
| 351 | r#"<tr><td colspan="4">"#, |
| 352 | r#"<details class="admin-sessions"><summary class="muted">{sessions_summary}</summary>{body}</details>"#, |
| 353 | r#"<details class="admin-sessions"><summary class="muted">{email_summary}</summary>"#, |
| 354 | r#"<div class="admin-fold-form"><form method="post" action="/admin/user_email" class="admin-form"><input type="hidden" name="user" value="{id}"><label class="auth-field"><span class="auth-label">{email_label}</span><input class="auth-input auth-input-mono" type="email" name="email" value="{email}" required></label><button class="admin-action" type="submit">{save}</button></form></div>"#, |
| 355 | r#"</details></td></tr>"# |
| 356 | ), |
| 357 | body = body, |
| 358 | sessions_summary = i18n::sessions_summary(lang, sessions.len()), |
| 359 | email_summary = i18n::email_fold_summary(lang), |
| 360 | id = id, |
| 361 | email_label = t(lang, Key::EmailCol), |
| 362 | email = escape(&user.email), |
| 363 | save = t(lang, Key::SaveButton), |
| 364 | ) |
| 365 | } |
| 366 | |
| 367 | async fn users_section( |
| 368 | cx: &Cx, |
| 369 | me: &User, |
| 370 | invited: Option<&str>, |
| 371 | lang: i18n::Lang, |
| 372 | ) -> Result<String, topcoat::Error> { |
| 373 | let users = accounts::list_users(&app(cx).store).await?; |
| 374 | let pending = accounts::list_pending_invites(&app(cx).store).await?; |
| 375 | let mut rows = String::new(); |
| 376 | for user in &users { |
| 377 | let flags = [ |
| 378 | user.admin.then_some(t(lang, Key::FlagAdmin)), |
| 379 | user.disabled.then_some(t(lang, Key::FlagDisabled)), |
| 380 | (!user.totp_confirmed).then_some(t(lang, Key::FlagNo2fa)), |
| 381 | ] |
| 382 | .into_iter() |
| 383 | .flatten() |
| 384 | .collect::<Vec<_>>() |
| 385 | .join(" · "); |
| 386 | let id = escape(&user.id.to_string()); |
| 387 | let email = escape(&user.email); |
| 388 | let actions = if user.id == me.id { |
| 389 | format!(r#"<span class="muted">{}</span>"#, t(lang, Key::YouWord)) |
| 390 | } else { |
| 391 | // Every row action opens the shared top-layer dialog. The word |
| 392 | // is the trigger; the dialog holds the button that posts. |
| 393 | let toggle = if user.disabled { |
| 394 | confirm_action(ConfirmAction { |
| 395 | field: "user", |
| 396 | id: &id, |
| 397 | action: "/admin/enable", |
| 398 | word: t(lang, Key::EnableWord), |
| 399 | extra_class: "", |
| 400 | title: &i18n::enable_title(lang, &email), |
| 401 | cost: t(lang, Key::EnableCost), |
| 402 | confirm: t(lang, Key::ConfirmEnable), |
| 403 | }) |
| 404 | } else { |
| 405 | confirm_action(ConfirmAction { |
| 406 | field: "user", |
| 407 | id: &id, |
| 408 | action: "/admin/disable", |
| 409 | word: t(lang, Key::DisableWord), |
| 410 | extra_class: "", |
| 411 | title: &i18n::disable_title(lang, &email), |
| 412 | cost: t(lang, Key::DisableCost), |
| 413 | confirm: t(lang, Key::ConfirmDisable), |
| 414 | }) |
| 415 | }; |
| 416 | let remove = confirm_action(ConfirmAction { |
| 417 | field: "user", |
| 418 | id: &id, |
| 419 | action: "/admin/delete", |
| 420 | word: t(lang, Key::DeleteWord), |
| 421 | extra_class: " admin-danger", |
| 422 | title: &i18n::delete_title(lang, &email), |
| 423 | cost: t(lang, Key::DeleteCost), |
| 424 | confirm: t(lang, Key::ConfirmDelete), |
| 425 | }); |
| 426 | format!( |
| 427 | r#"{toggle}<form method="post" action="/admin/revoke"><input type="hidden" name="user" value="{id}"><button class="admin-action" type="submit">{sign_out}</button></form>{remove}"#, |
| 428 | sign_out = t(lang, Key::SignOutEverywhere), |
| 429 | ) |
| 430 | }; |
| 431 | rows.push_str(&format!( |
| 432 | "<tr><td class=\"mono\">{}</td><td>{}</td><td class=\"muted\">{}</td><td class=\"actions\">{}</td></tr>", |
| 433 | escape(&user.email), |
| 434 | escape(&user.name), |
| 435 | flags, |
| 436 | actions |
| 437 | )); |
| 438 | let sessions = im_core::sessions::list_sessions(&app(cx).store, &user.id).await?; |
| 439 | rows.push_str(&sessions_row(user, &sessions, lang)); |
| 440 | } |
| 441 | |
| 442 | |
| 443 | for row in &pending { |
| 444 | let flags = [ |
| 445 | Some(t(lang, Key::FlagInvited)), |
| 446 | row.admin.then_some(t(lang, Key::FlagAdmin)), |
| 447 | ] |
| 448 | .into_iter() |
| 449 | .flatten() |
| 450 | .collect::<Vec<_>>() |
| 451 | .join(" · "); |
| 452 | let expires = row |
| 453 | .expires_at |
| 454 | .format(&time::macros::format_description!("[year]-[month]-[day]")) |
| 455 | .unwrap_or_default(); |
| 456 | rows.push_str(&format!( |
| 457 | r#"<tr><td class="mono">{}</td><td class="muted">{}</td><td class="muted">{}</td><td class="actions"><form method="post" action="/admin/uninvite"><input type="hidden" name="invite" value="{}"><button class="admin-action" type="submit">{}</button></form></td></tr>"#, |
| 458 | escape(&row.email), |
| 459 | i18n::waiting_label(lang, &expires), |
| 460 | flags, |
| 461 | escape(&row.token_hash), |
| 462 | t(lang, Key::InvalidateButton), |
| 463 | )); |
| 464 | } |
| 465 | let invited_html = invited |
| 466 | .map(|link| { |
| 467 | format!( |
| 468 | r#"<div class="auth-note">{}<br><span class="mono">{}</span></div>"#, |
| 469 | t(lang, Key::InviteLinkNote), |
| 470 | escape(link) |
| 471 | ) |
| 472 | }) |
| 473 | .unwrap_or_default(); |
| 474 | Ok(format!( |
| 475 | r#"<div class="admin-card"> |
| 476 | <div class="auth-title">{title}</div> |
| 477 | {invited_html} |
| 478 | <div class="admin-table-wrap"> |
| 479 | <table class="admin-table"> |
| 480 | <thead><tr><th>{email}</th><th>{name}</th><th></th><th></th></tr></thead> |
| 481 | <tbody>{rows}</tbody> |
| 482 | </table> |
| 483 | </div> |
| 484 | <form method="post" action="/admin/invite" class="admin-invite"> |
| 485 | <input class="auth-input auth-input-mono" type="email" name="email" placeholder="person@example.com" required> |
| 486 | <select class="auth-input admin-role" name="role"> |
| 487 | <option value="member">{member}</option> |
| 488 | <option value="admin">{admin}</option> |
| 489 | </select> |
| 490 | <button class="auth-submit admin-invite-go" type="submit"><span class="auth-submit-text">{invite}</span></button> |
| 491 | </form> |
| 492 | </div>"#, |
| 493 | title = t(lang, Key::PeopleTitle), |
| 494 | email = t(lang, Key::EmailCol), |
| 495 | name = t(lang, Key::NameCol), |
| 496 | member = t(lang, Key::RoleMember), |
| 497 | admin = t(lang, Key::RoleAdmin), |
| 498 | invite = t(lang, Key::InviteButton), |
| 499 | )) |
| 500 | } |
| 501 | |
| 502 | |
| 503 | |
| 504 | |
| 505 | |
| 506 | |
| 507 | |
| 508 | |
| 509 | |
| 510 | async fn services_section( |
| 511 | cx: &Cx, |
| 512 | shown: Option<(String, String)>, |
| 513 | lang: i18n::Lang, |
| 514 | ) -> Result<String, topcoat::Error> { |
| 515 | let services = im_core::services::list(&app(cx).store).await?; |
| 516 | let clients = im_core::oidc::list_clients(&app(cx).store).await?; |
| 517 | |
| 518 | |
| 519 | let linked = |id: Option<&String>| { |
| 520 | id.and_then(|cid| clients.iter().find(|client| &client.client_id.to_string() == cid)) |
| 521 | }; |
| 522 | let mut rows = String::new(); |
| 523 | for service in &services { |
| 524 | let key = escape(&service.key); |
| 525 | let name = escape(&service.name); |
| 526 | let url = escape(&service.url); |
| 527 | |
| 528 | |
| 529 | |
| 530 | let kept = service.owner.is_some(); |
| 531 | |
| 532 | |
| 533 | |
| 534 | |
| 535 | |
| 536 | |
| 537 | |
| 538 | |
| 539 | |
| 540 | let address_field = if kept { |
| 541 | format!( |
| 542 | r#"<input type="hidden" name="url" value="{url}">"#, |
| 543 | url = url |
| 544 | ) |
| 545 | } else { |
| 546 | format!( |
| 547 | r#"<label class="auth-field"><span class="auth-label">{url_label}</span><input class="auth-input auth-input-mono" type="text" name="url" value="{url}" required></label>"#, |
| 548 | url_label = t(lang, Key::AddressLabel), |
| 549 | url = url, |
| 550 | ) |
| 551 | }; |
| 552 | let (limit_amount, limit_unit) = service |
| 553 | .storage_limit_bytes |
| 554 | .map(bytes_as_unit) |
| 555 | .unwrap_or_default(); |
| 556 | let limit_field = format!( |
| 557 | r#"<label class="auth-field"><span class="auth-label">{limit_label}</span><input class="auth-input auth-input-mono" type="number" name="limit_amount" min="0" step="any" value="{limit_amount}"></label><select class="auth-input admin-role" name="limit_unit" aria-label="{limit_label}"><option value="MiB"{mib}>MiB</option><option value="GiB"{gib}>GiB</option></select>"#, |
| 558 | limit_label = t(lang, Key::ServicesStorageLimit), |
| 559 | limit_amount = limit_amount, |
| 560 | mib = if limit_unit == "MiB" { " selected" } else { "" }, |
| 561 | gib = if limit_unit == "GiB" { " selected" } else { "" }, |
| 562 | ); |
| 563 | let edit_body = format!( |
| 564 | r#"<form method="post" action="/admin/services_edit" class="admin-form"><input type="hidden" name="key" value="{key}"><label class="auth-field"><span class="auth-label">{name_label}</span><input class="auth-input auth-input-mono" type="text" name="name" value="{name}" required></label>{address_field}{limit_field}<button class="admin-action" type="submit">{save}</button></form>"#, |
| 565 | key = key, |
| 566 | name = name, |
| 567 | name_label = t(lang, Key::NameCol), |
| 568 | save = t(lang, Key::SaveButton), |
| 569 | ); |
| 570 | let edit = admin_dialog(AdminDialog { |
| 571 | id: &dialog_id("/admin/services_edit", "key", &key), |
| 572 | word: t(lang, Key::EditWord), |
| 573 | extra_class: "", |
| 574 | title: &i18n::edit_service_title(lang, &name), |
| 575 | body: &edit_body, |
| 576 | wide: true, |
| 577 | }); |
| 578 | let up = format!( |
| 579 | r#"<form method="post" action="/admin/services_move"><input type="hidden" name="key" value="{key}"><input type="hidden" name="dir" value="up"><button class="admin-action" type="submit" aria-label="{up_label}">↑</button></form>"#, |
| 580 | key = key, |
| 581 | up_label = t(lang, Key::ServiceMoveUp), |
| 582 | ); |
| 583 | let down = format!( |
| 584 | r#"<form method="post" action="/admin/services_move"><input type="hidden" name="key" value="{key}"><input type="hidden" name="dir" value="down"><button class="admin-action" type="submit" aria-label="{down_label}">↓</button></form>"#, |
| 585 | key = key, |
| 586 | down_label = t(lang, Key::ServiceMoveDown), |
| 587 | ); |
| 588 | let remove = if kept { |
| 589 | format!( |
| 590 | r#"<span class="muted">{kept_word}</span>"#, |
| 591 | kept_word = t(lang, Key::ServiceKept), |
| 592 | ) |
| 593 | } else { |
| 594 | confirm_action(ConfirmAction { |
| 595 | field: "key", |
| 596 | id: &key, |
| 597 | action: "/admin/services_remove", |
| 598 | word: t(lang, Key::Remove), |
| 599 | extra_class: " admin-danger", |
| 600 | title: &i18n::remove_service_title(lang, &name), |
| 601 | cost: t(lang, Key::RemoveCost), |
| 602 | confirm: t(lang, Key::ConfirmRemove), |
| 603 | }) |
| 604 | }; |
| 605 | let (client_cell, uris_cell, registered_cell, client_actions) = |
| 606 | match linked(service.client_id.as_ref()) { |
| 607 | Some(client) => { |
| 608 | let id = escape(&client.client_id.to_string()); |
| 609 | let uris = client |
| 610 | .redirect_uris |
| 611 | .iter() |
| 612 | .map(|uri| escape(uri)) |
| 613 | .collect::<Vec<_>>() |
| 614 | .join("<br>"); |
| 615 | let registered = client |
| 616 | .created_at |
| 617 | .format(&time::macros::format_description!( |
| 618 | "[year]-[month]-[day]" |
| 619 | )) |
| 620 | .unwrap_or_default(); |
| 621 | let controls = client_controls( |
| 622 | &id, |
| 623 | &escape(&client.name), |
| 624 | lang, |
| 625 | ); |
| 626 | (id, uris, registered, controls) |
| 627 | } |
| 628 | None => ("—".to_string(), "—".to_string(), "—".to_string(), String::new()), |
| 629 | }; |
| 630 | rows.push_str(&format!( |
| 631 | r#"<tr><td class="mono">{key}</td><td>{name}</td><td class="mono">{url}</td><td class="mono">{client_cell}</td><td class="mono">{uris_cell}</td><td class="muted">{registered_cell}</td><td class="actions">{edit}{up}{down}{remove}{client_actions}</td></tr>"#, |
| 632 | )); |
| 633 | } |
| 634 | |
| 635 | |
| 636 | for client in &clients { |
| 637 | let id = client.client_id.to_string(); |
| 638 | if services |
| 639 | .iter() |
| 640 | .any(|service| service.client_id.as_deref() == Some(id.as_str())) |
| 641 | { |
| 642 | continue; |
| 643 | } |
| 644 | let name = escape(&client.name); |
| 645 | let uris = client |
| 646 | .redirect_uris |
| 647 | .iter() |
| 648 | .map(|uri| escape(uri)) |
| 649 | .collect::<Vec<_>>() |
| 650 | .join("<br>"); |
| 651 | let registered = client |
| 652 | .created_at |
| 653 | .format(&time::macros::format_description!("[year]-[month]-[day]")) |
| 654 | .unwrap_or_default(); |
| 655 | let controls = client_controls(&id, &name, lang); |
| 656 | rows.push_str(&format!( |
| 657 | r#"<tr><td class="muted">—</td><td>{name}</td><td class="muted">—</td><td class="mono">{}</td><td class="mono">{uris}</td><td class="muted">{registered}</td><td class="actions">{controls}</td></tr>"#, |
| 658 | escape(&id), |
| 659 | )); |
| 660 | } |
| 661 | |
| 662 | |
| 663 | let shown_html = shown |
| 664 | .map(|(client_id, secret)| { |
| 665 | format!( |
| 666 | r#"<div class="auth-note">{note}<div class="admin-copy-row"><div class="muted">{id_label}: <span class="mono">{client_id}</span></div><div class="auth-secret admin-copy-value">{secret}</div><button class="admin-action admin-copy" type="button" data-copied-label="{copied}">{copy}</button></div></div>"#, |
| 667 | note = t(lang, Key::SecretShownNote), |
| 668 | id_label = t(lang, Key::ClientIdLabel), |
| 669 | client_id = escape(&client_id), |
| 670 | secret = escape(&secret), |
| 671 | copied = t(lang, Key::CopiedWord), |
| 672 | copy = t(lang, Key::CopyWord), |
| 673 | ) |
| 674 | }) |
| 675 | .unwrap_or_default(); |
| 676 | Ok(format!( |
| 677 | r#"<div class="admin-card"> |
| 678 | <div class="auth-title">{title}</div> |
| 679 | {shown_html} |
| 680 | <div class="admin-table-wrap"> |
| 681 | <table class="admin-table admin-clients"> |
| 682 | <thead><tr><th>{key_label}</th><th>{name_label}</th><th>{url_label}</th><th>{id_label}</th><th>{uris_label}</th><th>{registered_label}</th><th></th></tr></thead> |
| 683 | <tbody>{rows}</tbody> |
| 684 | </table> |
| 685 | </div> |
| 686 | <div class="muted">{service_add_label}</div> |
| 687 | <form method="post" action="/admin/services_add" class="admin-invite"> |
| 688 | <input class="auth-input auth-input-mono" type="text" name="key" placeholder="in" aria-label="{key_label}" required> |
| 689 | <input class="auth-input" type="text" name="name" placeholder="{name_label}" aria-label="{name_label}" required> |
| 690 | <input class="auth-input auth-input-mono" type="text" name="url" placeholder="{url_placeholder}" aria-label="{url_label}" required> |
| 691 | <button class="auth-submit admin-invite-go" type="submit"><span class="auth-submit-text">{add}</span></button> |
| 692 | </form> |
| 693 | <div class="muted">{client_add_label}</div> |
| 694 | <form method="post" action="/admin/clients_add" class="admin-invite"> |
| 695 | <input class="auth-input" type="text" name="name" placeholder="drive" aria-label="{name_label}" required> |
| 696 | <input class="auth-input auth-input-mono" type="text" name="redirect_uris" placeholder="{uris_placeholder}" aria-label="{uris_label}" required> |
| 697 | <button class="auth-submit admin-invite-go" type="submit"><span class="auth-submit-text">{client_add}</span></button> |
| 698 | </form> |
| 699 | </div>"#, |
| 700 | title = t(lang, Key::ServicesTitle), |
| 701 | key_label = t(lang, Key::ServiceKeyLabel), |
| 702 | name_label = t(lang, Key::NameCol), |
| 703 | url_label = t(lang, Key::AddressLabel), |
| 704 | url_placeholder = t(lang, Key::ServiceUrlPlaceholder), |
| 705 | id_label = t(lang, Key::ClientIdLabel), |
| 706 | uris_label = t(lang, Key::RedirectUrisLabel), |
| 707 | uris_placeholder = t(lang, Key::RedirectUrisPlaceholder), |
| 708 | registered_label = t(lang, Key::RegisteredCol), |
| 709 | service_add_label = t(lang, Key::ServiceAdd), |
| 710 | add = t(lang, Key::ServiceAdd), |
| 711 | client_add_label = t(lang, Key::ClientAdd), |
| 712 | client_add = t(lang, Key::ClientAdd), |
| 713 | )) |
| 714 | } |
| 715 | |
| 716 | |
| 717 | |
| 718 | fn client_controls(client_id: &str, name_html: &str, lang: i18n::Lang) -> String { |
| 719 | let rotate = confirm_action(ConfirmAction { |
| 720 | field: "client", |
| 721 | id: client_id, |
| 722 | action: "/admin/clients_rotate", |
| 723 | word: t(lang, Key::RotateWord), |
| 724 | extra_class: "", |
| 725 | title: &i18n::rotate_client_title(lang, name_html), |
| 726 | cost: t(lang, Key::RotateCost), |
| 727 | confirm: t(lang, Key::ConfirmRotate), |
| 728 | }); |
| 729 | let revoke_action = confirm_action(ConfirmAction { |
| 730 | field: "client", |
| 731 | id: client_id, |
| 732 | action: "/admin/clients_revoke", |
| 733 | word: t(lang, Key::RevokeWord), |
| 734 | extra_class: " admin-danger", |
| 735 | title: &i18n::revoke_client_title(lang, name_html), |
| 736 | cost: t(lang, Key::RevokeCost), |
| 737 | confirm: t(lang, Key::ConfirmRevoke), |
| 738 | }); |
| 739 | format!("{rotate}{revoke_action}") |
| 740 | } |
| 741 | |
| 742 | |
| 743 | |
| 744 | |
| 745 | const MIB_BYTES: f64 = 1_048_576.0; |
| 746 | const GIB_BYTES: f64 = 1_073_741_824.0; |
| 747 | |
| 748 | |
| 749 | |
| 750 | |
| 751 | fn bytes_as_unit(bytes: u64) -> (String, &'static str) { |
| 752 | if bytes >= GIB_BYTES as u64 { |
| 753 | (trim_amount(bytes as f64 / GIB_BYTES), "GiB") |
| 754 | } else { |
| 755 | (trim_amount(bytes as f64 / MIB_BYTES), "MiB") |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | |
| 760 | |
| 761 | |
| 762 | fn trim_amount(value: f64) -> String { |
| 763 | let rounded = (value * 100.0).round() / 100.0; |
| 764 | let text = format!("{rounded:.2}"); |
| 765 | text.trim_end_matches('0').trim_end_matches('.').to_string() |
| 766 | } |
| 767 | |
| 768 | |
| 769 | |
| 770 | |
| 771 | fn unit_bytes(amount: &str, unit: &str) -> Option<u64> { |
| 772 | let per = match unit { |
| 773 | "MiB" => MIB_BYTES, |
| 774 | "GiB" => GIB_BYTES, |
| 775 | _ => return None, |
| 776 | }; |
| 777 | let value: f64 = amount.trim().parse().ok()?; |
| 778 | if !value.is_finite() || value < 0.0 { |
| 779 | return None; |
| 780 | } |
| 781 | Some((value * per).round() as u64) |
| 782 | } |
| 783 | |
| 784 | |
| 785 | |
| 786 | |
| 787 | |
| 788 | fn posted_limit( |
| 789 | amount: &Option<String>, |
| 790 | unit: &Option<String>, |
| 791 | ) -> Result<Option<u64>, ()> { |
| 792 | let Some(amount) = amount |
| 793 | .as_deref() |
| 794 | .map(str::trim) |
| 795 | .filter(|amount| !amount.is_empty()) |
| 796 | else { |
| 797 | return Ok(None); |
| 798 | }; |
| 799 | match unit_bytes(amount, unit.as_deref().unwrap_or_default()) { |
| 800 | Some(bytes) => Ok(Some(bytes)), |
| 801 | None => Err(()), |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | |
| 806 | |
| 807 | |
| 808 | #[derive(Deserialize)] |
| 809 | struct ServiceForm { |
| 810 | key: String, |
| 811 | name: String, |
| 812 | url: String, |
| 813 | limit_amount: Option<String>, |
| 814 | limit_unit: Option<String>, |
| 815 | } |
| 816 | |
| 817 | #[route(POST "/admin/services_add")] |
| 818 | async fn services_add(cx: &Cx, Form(input): Form<ServiceForm>) -> Result<Response> { |
| 819 | let me = match require_admin(cx).await { |
| 820 | Ok(me) => me, |
| 821 | Err(redirect) => return Ok(*redirect), |
| 822 | }; |
| 823 | let limit = match posted_limit(&input.limit_amount, &input.limit_unit) { |
| 824 | Ok(limit) => limit, |
| 825 | Err(()) => return back(cx, "services", "&error=bad_service"), |
| 826 | }; |
| 827 | let outcome = im_core::services::add( |
| 828 | &app(cx).store, |
| 829 | &im_core::services::Service { |
| 830 | key: input.key, |
| 831 | name: input.name, |
| 832 | url: input.url, |
| 833 | owner: None, |
| 834 | client_id: None, |
| 835 | storage_limit_bytes: limit, |
| 836 | }, |
| 837 | ) |
| 838 | .await; |
| 839 | service_outcome(cx, &me, outcome).await |
| 840 | } |
| 841 | |
| 842 | #[route(POST "/admin/services_edit")] |
| 843 | async fn services_edit(cx: &Cx, Form(input): Form<ServiceForm>) -> Result<Response> { |
| 844 | let me = match require_admin(cx).await { |
| 845 | Ok(me) => me, |
| 846 | Err(redirect) => return Ok(*redirect), |
| 847 | }; |
| 848 | let limit = match posted_limit(&input.limit_amount, &input.limit_unit) { |
| 849 | Ok(limit) => limit, |
| 850 | Err(()) => return back(cx, "services", "&error=bad_service"), |
| 851 | }; |
| 852 | let outcome = im_core::services::edit( |
| 853 | &app(cx).store, |
| 854 | &input.key, |
| 855 | &input.name, |
| 856 | &input.url, |
| 857 | limit, |
| 858 | ) |
| 859 | .await; |
| 860 | service_outcome(cx, &me, outcome).await |
| 861 | } |
| 862 | |
| 863 | #[derive(Deserialize)] |
| 864 | struct ServiceKeyForm { |
| 865 | key: String, |
| 866 | } |
| 867 | |
| 868 | #[route(POST "/admin/services_remove")] |
| 869 | async fn services_remove(cx: &Cx, Form(input): Form<ServiceKeyForm>) -> Result<Response> { |
| 870 | let me = match require_admin(cx).await { |
| 871 | Ok(me) => me, |
| 872 | Err(redirect) => return Ok(*redirect), |
| 873 | }; |
| 874 | let outcome = im_core::services::remove(&app(cx).store, &input.key).await; |
| 875 | service_outcome(cx, &me, outcome).await |
| 876 | } |
| 877 | |
| 878 | #[derive(Deserialize)] |
| 879 | struct ServiceMoveForm { |
| 880 | key: String, |
| 881 | dir: String, |
| 882 | } |
| 883 | |
| 884 | |
| 885 | #[route(POST "/admin/services_move")] |
| 886 | async fn services_move(cx: &Cx, Form(input): Form<ServiceMoveForm>) -> Result<Response> { |
| 887 | let me = match require_admin(cx).await { |
| 888 | Ok(me) => me, |
| 889 | Err(redirect) => return Ok(*redirect), |
| 890 | }; |
| 891 | let up = match input.dir.as_str() { |
| 892 | "up" => true, |
| 893 | "down" => false, |
| 894 | _ => return back(cx, "services", "&error=bad_service"), |
| 895 | }; |
| 896 | let outcome = im_core::services::move_service(&app(cx).store, &input.key, up).await; |
| 897 | service_outcome(cx, &me, outcome).await |
| 898 | } |
| 899 | |
| 900 | |
| 901 | |
| 902 | |
| 903 | |
| 904 | async fn service_outcome( |
| 905 | cx: &Cx, |
| 906 | me: &User, |
| 907 | outcome: im_core::store::Result<()>, |
| 908 | ) -> Result<Response> { |
| 909 | match outcome { |
| 910 | Ok(()) => { |
| 911 | server::log_event(cx, "services_updated", Some(&me.email), None).await; |
| 912 | back(cx, "services", "&ok=services") |
| 913 | } |
| 914 | Err(im_core::store::StoreError::Invalid(_) | im_core::store::StoreError::Conflict(_)) => { |
| 915 | back(cx, "services", "&error=bad_service") |
| 916 | } |
| 917 | Err(e) => Err(e.into()), |
| 918 | } |
| 919 | } |
| 920 | |
| 921 | |
| 922 | |
| 923 | |
| 924 | #[derive(Deserialize)] |
| 925 | struct ClientForm { |
| 926 | name: String, |
| 927 | redirect_uris: String, |
| 928 | } |
| 929 | |
| 930 | #[route(POST "/admin/clients_add")] |
| 931 | async fn clients_add(cx: &Cx, Form(input): Form<ClientForm>) -> Result<Response> { |
| 932 | let me = match require_admin(cx).await { |
| 933 | Ok(me) => me, |
| 934 | Err(redirect) => return Ok(*redirect), |
| 935 | }; |
| 936 | let name = input.name.trim().to_string(); |
| 937 | let uris: Vec<String> = input |
| 938 | .redirect_uris |
| 939 | .split(|c: char| c.is_whitespace() || c == ',') |
| 940 | .map(str::trim) |
| 941 | .filter(|uri| !uri.is_empty()) |
| 942 | .map(str::to_string) |
| 943 | .collect(); |
| 944 | if name.is_empty() || uris.is_empty() { |
| 945 | return back(cx, "clients", "&error=bad_client"); |
| 946 | } |
| 947 | let (id, secret) = im_core::oidc::create_client(&app(cx).store, &name, uris).await?; |
| 948 | server::log_event(cx, "client_created", Some(&me.email), Some(&name)).await; |
| 949 | let shown = server::stash_shown_secret(id.to_string(), secret.expose().to_string()); |
| 950 | back(cx, "clients", &format!("&shown={shown}")) |
| 951 | } |
| 952 | |
| 953 | #[derive(Deserialize)] |
| 954 | struct ClientAction { |
| 955 | client: String, |
| 956 | } |
| 957 | |
| 958 | #[route(POST "/admin/clients_rotate")] |
| 959 | async fn clients_rotate(cx: &Cx, Form(input): Form<ClientAction>) -> Result<Response> { |
| 960 | let me = match require_admin(cx).await { |
| 961 | Ok(me) => me, |
| 962 | Err(redirect) => return Ok(*redirect), |
| 963 | }; |
| 964 | |
| 965 | |
| 966 | let name = match im_core::oidc::client_by_id(&app(cx).store, &input.client).await? { |
| 967 | Some(client) => client.name, |
| 968 | None => return back(cx, "clients", "&error=no_such_client"), |
| 969 | }; |
| 970 | match im_core::oidc::rotate_client_secret(&app(cx).store, &input.client).await? { |
| 971 | Some(secret) => { |
| 972 | server::log_event(cx, "client_rotated", Some(&me.email), Some(&name)).await; |
| 973 | let shown = |
| 974 | server::stash_shown_secret(input.client.clone(), secret.expose().to_string()); |
| 975 | back(cx, "clients", &format!("&shown={shown}")) |
| 976 | } |
| 977 | None => back(cx, "clients", "&error=no_such_client"), |
| 978 | } |
| 979 | } |
| 980 | |
| 981 | #[route(POST "/admin/clients_revoke")] |
| 982 | async fn clients_revoke(cx: &Cx, Form(input): Form<ClientAction>) -> Result<Response> { |
| 983 | let me = match require_admin(cx).await { |
| 984 | Ok(me) => me, |
| 985 | Err(redirect) => return Ok(*redirect), |
| 986 | }; |
| 987 | let name = match im_core::oidc::client_by_id(&app(cx).store, &input.client).await? { |
| 988 | Some(client) => client.name, |
| 989 | None => return back(cx, "clients", "&error=no_such_client"), |
| 990 | }; |
| 991 | if !im_core::oidc::revoke_client(&app(cx).store, &input.client).await? { |
| 992 | return back(cx, "clients", "&error=no_such_client"); |
| 993 | } |
| 994 | server::log_event(cx, "client_revoked", Some(&me.email), Some(&name)).await; |
| 995 | back(cx, "clients", "&ok=client_revoked") |
| 996 | } |
| 997 | |
| 998 | |
| 999 | |
| 1000 | |
| 1001 | async fn settings_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> { |
| 1002 | let policy = settings::policy(&app(cx).store).await?; |
| 1003 | Ok(format!( |
| 1004 | r#"<div class="admin-card"> |
| 1005 | <div class="auth-title">{title}</div> |
| 1006 | <div class="auth-sub">{sub}</div> |
| 1007 | <form method="post" action="/admin/settings" class="admin-form"> |
| 1008 | <label class="auth-field"><span class="auth-label">{invite_days}</span> |
| 1009 | <input class="auth-input auth-input-mono" type="number" name="invite_days" min="1" value="{}"></label> |
| 1010 | <label class="auth-field"><span class="auth-label">{session_days}</span> |
| 1011 | <input class="auth-input auth-input-mono" type="number" name="session_days" min="1" value="{}"></label> |
| 1012 | <label class="auth-field"><span class="auth-label">{max_sessions}</span> |
| 1013 | <input class="auth-input auth-input-mono" type="number" name="max_sessions" min="1" value="{}"></label> |
| 1014 | <label class="auth-field"><span class="auth-label">{pending_minutes}</span> |
| 1015 | <input class="auth-input auth-input-mono" type="number" name="pending_minutes" min="1" value="{}"></label> |
| 1016 | <label class="auth-field"><span class="auth-label">{reset_minutes}</span> |
| 1017 | <input class="auth-input auth-input-mono" type="number" name="reset_minutes" min="1" value="{}"></label> |
| 1018 | <label class="auth-field"><span class="auth-label">{attempts}</span> |
| 1019 | <input class="auth-input auth-input-mono" type="number" name="login_attempts_per_hour" min="1" value="{}"></label> |
| 1020 | <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">{save}</span></button> |
| 1021 | </form> |
| 1022 | </div>"#, |
| 1023 | policy.invite_days, |
| 1024 | policy.session_days, |
| 1025 | policy.max_sessions, |
| 1026 | policy.pending_minutes, |
| 1027 | policy.reset_minutes, |
| 1028 | policy.login_attempts_per_hour, |
| 1029 | title = t(lang, Key::SettingsTitle), |
| 1030 | sub = t(lang, Key::SettingsSub), |
| 1031 | invite_days = t(lang, Key::InviteDaysLabel), |
| 1032 | session_days = t(lang, Key::SessionDaysLabel), |
| 1033 | max_sessions = t(lang, Key::MaxSessionsLabel), |
| 1034 | pending_minutes = t(lang, Key::PendingMinutesLabel), |
| 1035 | reset_minutes = t(lang, Key::ResetMinutesLabel), |
| 1036 | attempts = t(lang, Key::LoginAttemptsLabel), |
| 1037 | save = t(lang, Key::SaveButton), |
| 1038 | )) |
| 1039 | } |
| 1040 | |
| 1041 | #[derive(Deserialize)] |
| 1042 | struct PolicyForm { |
| 1043 | invite_days: i64, |
| 1044 | session_days: i64, |
| 1045 | max_sessions: i64, |
| 1046 | pending_minutes: i64, |
| 1047 | reset_minutes: i64, |
| 1048 | login_attempts_per_hour: i64, |
| 1049 | } |
| 1050 | |
| 1051 | #[route(POST "/admin/settings")] |
| 1052 | async fn settings_save(cx: &Cx, Form(input): Form<PolicyForm>) -> Result<Response> { |
| 1053 | let me = match require_admin(cx).await { |
| 1054 | Ok(me) => me, |
| 1055 | Err(redirect) => return Ok(*redirect), |
| 1056 | }; |
| 1057 | let store = &app(cx).store; |
| 1058 | settings::set_policy( |
| 1059 | store, |
| 1060 | &settings::Policy { |
| 1061 | invite_days: input.invite_days, |
| 1062 | session_days: input.session_days, |
| 1063 | max_sessions: input.max_sessions, |
| 1064 | pending_minutes: input.pending_minutes, |
| 1065 | reset_minutes: input.reset_minutes, |
| 1066 | login_attempts_per_hour: input.login_attempts_per_hour, |
| 1067 | }, |
| 1068 | ) |
| 1069 | .await?; |
| 1070 | server::log_event(cx, "settings_updated", Some(&me.email), None).await; |
| 1071 | back(cx, "settings", "&ok=settings") |
| 1072 | } |
| 1073 | |
| 1074 | async fn mail_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> { |
| 1075 | let store = &app(cx).store; |
| 1076 | let smtp = settings::smtp(store).await?; |
| 1077 | let password_note = if smtp.password.is_some() { |
| 1078 | t(lang, Key::PasswordSetNote) |
| 1079 | } else { |
| 1080 | t(lang, Key::NoPasswordNote) |
| 1081 | }; |
| 1082 | |
| 1083 | |
| 1084 | |
| 1085 | |
| 1086 | let stamp = |at: time::OffsetDateTime| { |
| 1087 | at.format(&time::macros::format_description!( |
| 1088 | "[year]-[month]-[day] [hour]:[minute] UTC" |
| 1089 | )) |
| 1090 | .unwrap_or_default() |
| 1091 | }; |
| 1092 | let (chip_class, chip_text, lede) = match settings::standing(store).await? { |
| 1093 | settings::Standing::NotConfigured => ( |
| 1094 | "chip chip-muted", |
| 1095 | t(lang, Key::ChipNotConfigured).to_string(), |
| 1096 | String::new(), |
| 1097 | ), |
| 1098 | settings::Standing::Unchecked => ( |
| 1099 | "chip chip-muted", |
| 1100 | t(lang, Key::ChipUnchecked).to_string(), |
| 1101 | t(lang, Key::UncheckedNote).to_string(), |
| 1102 | ), |
| 1103 | settings::Standing::Connected { at, took_ms } => ( |
| 1104 | "chip chip-connected", |
| 1105 | i18n::connected_chip(lang, took_ms), |
| 1106 | i18n::checked_note(lang, &stamp(at)), |
| 1107 | ), |
| 1108 | settings::Standing::Refused { at, said } => ( |
| 1109 | "chip chip-refused", |
| 1110 | t(lang, Key::ChipRefused).to_string(), |
| 1111 | format!("{} — {}", stamp(at), escape(&said)), |
| 1112 | ), |
| 1113 | }; |
| 1114 | let lede_html = if lede.is_empty() { |
| 1115 | String::new() |
| 1116 | } else { |
| 1117 | format!(r#"<div class="admin-standing">{lede}</div>"#) |
| 1118 | }; |
| 1119 | Ok(format!( |
| 1120 | r#"<div class="admin-card"> |
| 1121 | <div class="admin-card-head"><div class="auth-title">{title}</div><span class="{chip_class}">{chip_text}</span></div> |
| 1122 | <div class="auth-sub">{sub}</div> |
| 1123 | <form method="post" action="/admin/smtp" class="admin-form"> |
| 1124 | <label class="auth-field"><span class="auth-label">{host}</span> |
| 1125 | <input class="auth-input auth-input-mono" type="text" name="host" value="{}" placeholder="smtp.example.com"></label> |
| 1126 | <label class="auth-field"><span class="auth-label">{port}</span> |
| 1127 | <input class="auth-input auth-input-mono" type="number" name="port" value="{}"></label> |
| 1128 | <label class="auth-field"><span class="auth-label">{username}</span> |
| 1129 | <input class="auth-input auth-input-mono" type="text" name="username" value="{}"></label> |
| 1130 | <label class="auth-field"><span class="auth-label">{password}</span> |
| 1131 | <input class="auth-input auth-input-mono" type="password" name="password" placeholder="{password_note}" autocomplete="off"></label> |
| 1132 | <label class="auth-field"><span class="auth-label">{from_name}</span> |
| 1133 | <input class="auth-input auth-input-mono" type="text" name="from_name" value="{}" placeholder="im"></label> |
| 1134 | <label class="auth-field"><span class="auth-label">{from_address}</span> |
| 1135 | <input class="auth-input auth-input-mono" type="text" name="from" value="{}" placeholder="auth@example.com"></label> |
| 1136 | <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">{save}</span></button> |
| 1137 | </form> |
| 1138 | {lede_html} |
| 1139 | <div class="admin-pair"> |
| 1140 | <form method="post" action="/admin/smtp_check"><button class="admin-action" type="submit">{check}</button></form> |
| 1141 | <form method="post" action="/admin/smtp_test"><button class="admin-action" type="submit">{test}</button></form> |
| 1142 | </div> |
| 1143 | </div>"#, |
| 1144 | escape(&smtp.host), |
| 1145 | smtp.port, |
| 1146 | escape(&smtp.username), |
| 1147 | escape(&smtp.from_name), |
| 1148 | escape(&smtp.from), |
| 1149 | title = t(lang, Key::MailTitle), |
| 1150 | sub = i18n::mail_sub(lang), |
| 1151 | host = t(lang, Key::HostLabel), |
| 1152 | port = t(lang, Key::PortLabel), |
| 1153 | username = t(lang, Key::UsernameLabel), |
| 1154 | password = t(lang, Key::MailPasswordLabel), |
| 1155 | from_name = t(lang, Key::FromNameLabel), |
| 1156 | from_address = t(lang, Key::FromAddressLabel), |
| 1157 | save = t(lang, Key::SaveButton), |
| 1158 | check = t(lang, Key::CheckConnectionButton), |
| 1159 | test = t(lang, Key::SendTestMailButton), |
| 1160 | )) |
| 1161 | } |
| 1162 | |
| 1163 | |
| 1164 | |
| 1165 | |
| 1166 | async fn message_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> { |
| 1167 | let store = &app(cx).store; |
| 1168 | let users = accounts::list_users(store).await?; |
| 1169 | let mut options = format!( |
| 1170 | r#"<option value="everyone">{}</option>"#, |
| 1171 | t(lang, Key::EveryoneOption) |
| 1172 | ); |
| 1173 | for person in &users { |
| 1174 | options.push_str(&format!( |
| 1175 | r#"<option value="{}">{} · {}</option>"#, |
| 1176 | escape(person.id.as_str()), |
| 1177 | escape(&person.name), |
| 1178 | escape(&person.email), |
| 1179 | )); |
| 1180 | } |
| 1181 | Ok(format!( |
| 1182 | r#"<div class="admin-card"> |
| 1183 | <div class="admin-card-head"><div class="auth-title">{msg_title}</div></div> |
| 1184 | <form method="post" action="/admin/message" class="admin-form"> |
| 1185 | <label class="auth-field"><span class="auth-label">{to_label}</span> |
| 1186 | <select class="auth-input" name="to">{options}</select></label> |
| 1187 | <label class="auth-field"><span class="auth-label">{subject_label}</span> |
| 1188 | <input class="auth-input" type="text" name="subject" required></label> |
| 1189 | <label class="auth-field"><span class="auth-label">{body_label}</span> |
| 1190 | <textarea class="auth-input" name="body" rows="5" required></textarea></label> |
| 1191 | <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">{send}</span></button> |
| 1192 | </form> |
| 1193 | </div>"#, |
| 1194 | msg_title = t(lang, Key::MessageTitle), |
| 1195 | to_label = t(lang, Key::MessageToLabel), |
| 1196 | subject_label = t(lang, Key::MessageSubjectLabel), |
| 1197 | body_label = t(lang, Key::MessageBodyLabel), |
| 1198 | send = t(lang, Key::SendMessageButton), |
| 1199 | )) |
| 1200 | } |
| 1201 | |
| 1202 | |
| 1203 | |
| 1204 | const LOGS_LIMIT: i64 = 50; |
| 1205 | |
| 1206 | |
| 1207 | |
| 1208 | |
| 1209 | |
| 1210 | |
| 1211 | fn resolve_log_limit(cx: &Cx) -> i64 { |
| 1212 | topcoat::cookie::cookies(cx) |
| 1213 | .get("im_rows_logs") |
| 1214 | .and_then(|c| c.value().parse::<i64>().ok()) |
| 1215 | .map(|rows| rows.clamp(5, 200)) |
| 1216 | .unwrap_or(LOGS_LIMIT) |
| 1217 | } |
| 1218 | |
| 1219 | |
| 1220 | fn cursor_q(cursor: &events::EventCursor) -> String { |
| 1221 | crate::oidc::urlencode(&format!("{}~{}", events_cursor_stamp(cursor), cursor.id)) |
| 1222 | } |
| 1223 | |
| 1224 | fn events_cursor_stamp(cursor: &events::EventCursor) -> String { |
| 1225 | cursor |
| 1226 | .at |
| 1227 | .format(&time::macros::format_description!( |
| 1228 | "[year]-[month]-[day]T[hour]:[minute]:[second]Z" |
| 1229 | )) |
| 1230 | .unwrap_or_default() |
| 1231 | } |
| 1232 | |
| 1233 | fn parse_cursor(raw: Option<String>) -> Option<events::EventCursor> { |
| 1234 | let raw = raw?; |
| 1235 | let (at, id) = raw.split_once('~')?; |
| 1236 | let at = |
| 1237 | time::OffsetDateTime::parse(at, &time::format_description::well_known::Rfc3339).ok()?; |
| 1238 | if id.is_empty() { |
| 1239 | return None; |
| 1240 | } |
| 1241 | Some(events::EventCursor { |
| 1242 | at, |
| 1243 | id: id.to_string(), |
| 1244 | }) |
| 1245 | } |
| 1246 | |
| 1247 | |
| 1248 | |
| 1249 | fn parse_day(raw: Option<String>) -> Option<time::OffsetDateTime> { |
| 1250 | let raw = raw?; |
| 1251 | let date = time::Date::parse( |
| 1252 | &raw, |
| 1253 | &time::macros::format_description!("[year]-[month]-[day]"), |
| 1254 | ) |
| 1255 | .ok()?; |
| 1256 | date.with_hms(0, 0, 0).ok().map(|dt| dt.assume_utc()) |
| 1257 | } |
| 1258 | |
| 1259 | async fn logs_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> { |
| 1260 | let store = &app(cx).store; |
| 1261 | let query = topcoat::router::request::uri(cx) |
| 1262 | .query() |
| 1263 | .unwrap_or("") |
| 1264 | .to_string(); |
| 1265 | let pick = |name: &str| query_value(&query, name).filter(|v| !v.is_empty()); |
| 1266 | |
| 1267 | let from = parse_day(pick("from")); |
| 1268 | let to = parse_day(pick("to")).and_then(|d| d.checked_add(time::Duration::days(1))); |
| 1269 | let day = match (from, to) { |
| 1270 | (Some(a), Some(b)) if a > b => Some((b, a)), |
| 1271 | (Some(a), Some(b)) => Some((a, b)), |
| 1272 | (Some(a), None) => Some((a, time::Date::MAX.with_hms(0, 0, 0).unwrap().assume_utc())), |
| 1273 | (None, Some(b)) => Some((time::OffsetDateTime::UNIX_EPOCH, b)), |
| 1274 | (None, None) => None, |
| 1275 | }; |
| 1276 | let filter = events::EventFilter { |
| 1277 | kind: pick("kind"), |
| 1278 | actor: pick("actor"), |
| 1279 | day, |
| 1280 | q: pick("q") |
| 1281 | .map(|raw| raw.trim().to_string()) |
| 1282 | .filter(|s| !s.is_empty()), |
| 1283 | }; |
| 1284 | let dir = if pick("dir").as_deref() == Some("oldest") { |
| 1285 | events::Dir::Oldest |
| 1286 | } else { |
| 1287 | events::Dir::Newest |
| 1288 | }; |
| 1289 | let mut page = match (parse_cursor(pick("before")), parse_cursor(pick("after"))) { |
| 1290 | (Some(cursor), _) => events::EventPage::Before(cursor), |
| 1291 | (None, Some(cursor)) => events::EventPage::After(cursor), |
| 1292 | _ => events::EventPage::Newest, |
| 1293 | }; |
| 1294 | let limit = resolve_log_limit(cx); |
| 1295 | let mut window = events::list_filtered(store, limit + 1, &page, dir, &filter).await?; |
| 1296 | |
| 1297 | if matches!(page, events::EventPage::After(_)) && window.is_empty() { |
| 1298 | page = events::EventPage::Newest; |
| 1299 | window = events::list_filtered(store, limit + 1, &page, dir, &filter).await?; |
| 1300 | } |
| 1301 | let has_more = window.len() as i64 > limit; |
| 1302 | window.truncate(limit as usize); |
| 1303 | |
| 1304 | let total = events::count_filtered(store, &filter).await?; |
| 1305 | let preceding = events::count_preceding( |
| 1306 | store, |
| 1307 | &filter, |
| 1308 | dir, |
| 1309 | window |
| 1310 | .first() |
| 1311 | .map(|e| events::EventCursor { |
| 1312 | at: e.at, |
| 1313 | id: e.id.clone(), |
| 1314 | }) |
| 1315 | .as_ref(), |
| 1316 | ) |
| 1317 | .await?; |
| 1318 | |
| 1319 | |
| 1320 | let mut suffix = String::new(); |
| 1321 | if let Some(kind) = &filter.kind { |
| 1322 | suffix += &format!("&kind={}", crate::oidc::urlencode(kind)); |
| 1323 | } |
| 1324 | if let Some(actor) = &filter.actor { |
| 1325 | suffix += &format!("&actor={}", crate::oidc::urlencode(actor)); |
| 1326 | } |
| 1327 | if let Some(raw) = pick("from") { |
| 1328 | suffix += &format!("&from={}", crate::oidc::urlencode(&raw)); |
| 1329 | } |
| 1330 | if let Some(raw) = pick("to") { |
| 1331 | suffix += &format!("&to={}", crate::oidc::urlencode(&raw)); |
| 1332 | } |
| 1333 | if dir == events::Dir::Oldest { |
| 1334 | suffix += "&dir=oldest"; |
| 1335 | } |
| 1336 | if let Some(q) = &filter.q { |
| 1337 | suffix += &format!("&q={}", crate::oidc::urlencode(q)); |
| 1338 | } |
| 1339 | |
| 1340 | let kinds = events::distinct_kinds(store).await?; |
| 1341 | let actors = events::distinct_actors(store).await?; |
| 1342 | let mut kind_options = format!(r#"<option value="">{}</option>"#, t(lang, Key::AllOption)); |
| 1343 | for kind in &kinds { |
| 1344 | kind_options.push_str(&format!( |
| 1345 | r#"<option value="{}"{}>{}</option>"#, |
| 1346 | escape(kind), |
| 1347 | if filter.kind.as_deref() == Some(kind) { |
| 1348 | " selected" |
| 1349 | } else { |
| 1350 | "" |
| 1351 | }, |
| 1352 | escape(&i18n::kind_word(lang, kind)), |
| 1353 | )); |
| 1354 | } |
| 1355 | let mut actor_options = format!(r#"<option value="">{}</option>"#, t(lang, Key::AllOption)); |
| 1356 | for actor in &actors { |
| 1357 | actor_options.push_str(&format!( |
| 1358 | r#"<option value="{}"{}>{}</option>"#, |
| 1359 | escape(actor), |
| 1360 | if filter.actor.as_deref() == Some(actor) { |
| 1361 | " selected" |
| 1362 | } else { |
| 1363 | "" |
| 1364 | }, |
| 1365 | escape(actor), |
| 1366 | )); |
| 1367 | } |
| 1368 | |
| 1369 | let mut rows = String::new(); |
| 1370 | for event in &window { |
| 1371 | rows.push_str(&format!( |
| 1372 | "<tr><td class=\"mono muted\">{}</td><td class=\"mono\">{}</td><td>{}</td><td class=\"muted\">{}</td></tr>", |
| 1373 | escape(&event.at.format(&time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]")).unwrap_or_default()), |
| 1374 | escape(&i18n::kind_word(lang, &event.kind)), |
| 1375 | escape(event.actor.as_deref().unwrap_or("")), |
| 1376 | escape(event.detail.as_deref().unwrap_or("")), |
| 1377 | )); |
| 1378 | } |
| 1379 | |
| 1380 | let body = if window.is_empty() { |
| 1381 | format!(r#"<div class="muted">{}</div>"#, t(lang, Key::LogsEmpty)) |
| 1382 | } else { |
| 1383 | format!( |
| 1384 | r#"<div class="admin-table-wrap"><table class="admin-table log-list" data-rows="{limit}" data-section="logs"> |
| 1385 | <thead><tr><th>{when}</th><th>{what}</th><th>{who}</th><th>{detail}</th></tr></thead> |
| 1386 | <tbody>{rows}</tbody> |
| 1387 | </table></div>"#, |
| 1388 | when = t(lang, Key::WhenCol), |
| 1389 | what = t(lang, Key::WhatCol), |
| 1390 | who = t(lang, Key::WhoCol), |
| 1391 | detail = t(lang, Key::DetailCol), |
| 1392 | ) |
| 1393 | }; |
| 1394 | |
| 1395 | |
| 1396 | |
| 1397 | let mut foot = String::new(); |
| 1398 | if !window.is_empty() { |
| 1399 | let newest = events::EventCursor { |
| 1400 | at: window.first().unwrap().at, |
| 1401 | id: window.first().unwrap().id.clone(), |
| 1402 | }; |
| 1403 | let oldest = events::EventCursor { |
| 1404 | at: window.last().unwrap().at, |
| 1405 | id: window.last().unwrap().id.clone(), |
| 1406 | }; |
| 1407 | let show_older = matches!(page, events::EventPage::After(_)) || has_more; |
| 1408 | let show_newer = matches!(page, events::EventPage::Before(_)) |
| 1409 | || (matches!(page, events::EventPage::After(_)) && has_more); |
| 1410 | let mut links = String::new(); |
| 1411 | if show_newer { |
| 1412 | links += &format!( |
| 1413 | r#"<a class="auth-alt" href="/admin?section=logs{suffix}&after={}">{}</a>"#, |
| 1414 | cursor_q(&newest), |
| 1415 | t(lang, Key::NewerLink), |
| 1416 | ); |
| 1417 | } |
| 1418 | if show_older { |
| 1419 | links += &format!( |
| 1420 | r#"<a class="auth-alt" href="/admin?section=logs{suffix}&before={}">{}</a>"#, |
| 1421 | cursor_q(&oldest), |
| 1422 | t(lang, Key::OlderLink), |
| 1423 | ); |
| 1424 | } |
| 1425 | foot = format!( |
| 1426 | r#"<div class="logs-foot"><span class="log-count">{}–{} / {}</span><div class="logs-links">{links}</div></div>"#, |
| 1427 | preceding + 1, |
| 1428 | preceding + window.len() as u64, |
| 1429 | total, |
| 1430 | ); |
| 1431 | } |
| 1432 | |
| 1433 | let dir_options = format!( |
| 1434 | r#"<option value=""{}>{}</option><option value="oldest"{}>{}</option>"#, |
| 1435 | if dir == events::Dir::Newest { |
| 1436 | " selected" |
| 1437 | } else { |
| 1438 | "" |
| 1439 | }, |
| 1440 | t(lang, Key::NewestFirst), |
| 1441 | if dir == events::Dir::Oldest { |
| 1442 | " selected" |
| 1443 | } else { |
| 1444 | "" |
| 1445 | }, |
| 1446 | t(lang, Key::OldestFirst), |
| 1447 | ); |
| 1448 | |
| 1449 | Ok(format!( |
| 1450 | r#"<div class="admin-card"> |
| 1451 | <div class="auth-title">{title}</div> |
| 1452 | <div class="auth-sub">{sub}</div> |
| 1453 | <form method="get" action="/admin" class="logs-filters"> |
| 1454 | <input type="hidden" name="section" value="logs"> |
| 1455 | <label class="auth-field"><span class="auth-label">{kind_label}</span> |
| 1456 | <select class="auth-input" name="kind" data-autosubmit>{kind_options}</select></label> |
| 1457 | <label class="auth-field"><span class="auth-label">{actor_label}</span> |
| 1458 | <select class="auth-input" name="actor" data-autosubmit>{actor_options}</select></label> |
| 1459 | <label class="auth-field"><span class="auth-label">{from_label}</span> |
| 1460 | <input class="auth-input" type="date" name="from" value="{from_value}" data-autosubmit></label> |
| 1461 | <label class="auth-field"><span class="auth-label">{to_label}</span> |
| 1462 | <input class="auth-input" type="date" name="to" value="{to_value}" data-autosubmit></label> |
| 1463 | <label class="auth-field"><span class="auth-label">{dir_label}</span> |
| 1464 | <select class="auth-input" name="dir" data-autosubmit>{dir_options}</select></label> |
| 1465 | <label class="auth-field logs-q"><span class="auth-label">{search_label}</span> |
| 1466 | <input class="auth-input" type="text" name="q" value="{q_value}"></label> |
| 1467 | </form> |
| 1468 | {body} |
| 1469 | {foot} |
| 1470 | </div>"#, |
| 1471 | title = t(lang, Key::LogsTitle), |
| 1472 | sub = t(lang, Key::LogsSub), |
| 1473 | kind_label = t(lang, Key::KindLabel), |
| 1474 | actor_label = t(lang, Key::ActorLabel), |
| 1475 | from_label = t(lang, Key::FromLabel), |
| 1476 | to_label = t(lang, Key::ToLabel), |
| 1477 | dir_label = t(lang, Key::OrderLabel), |
| 1478 | search_label = t(lang, Key::SearchLabel), |
| 1479 | q_value = escape(filter.q.as_deref().unwrap_or("")), |
| 1480 | from_value = escape(&pick("from").unwrap_or_default()), |
| 1481 | to_value = escape(&pick("to").unwrap_or_default()), |
| 1482 | dir_options = dir_options, |
| 1483 | )) |
| 1484 | .map(|card| card + LOG_FIT_SCRIPT) |
| 1485 | } |
| 1486 | |
| 1487 | |
| 1488 | |
| 1489 | |
| 1490 | |
| 1491 | |
| 1492 | |
| 1493 | async fn health_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat::Error> { |
| 1494 | let services = im_core::services::list(&app(cx).store).await?; |
| 1495 | |
| 1496 | |
| 1497 | |
| 1498 | let urls = services |
| 1499 | .iter() |
| 1500 | .map(|service| format!("{}/healthz", service.url.trim_end_matches('/'))) |
| 1501 | .collect::<Vec<_>>(); |
| 1502 | let probes = probe_family(&urls).await; |
| 1503 | |
| 1504 | let mut rows = String::new(); |
| 1505 | for (service, probe) in services.iter().zip(probes) { |
| 1506 | let key = escape(&service.key); |
| 1507 | let name = escape(&service.name); |
| 1508 | let url = escape(&service.url); |
| 1509 | let state = match probe { |
| 1510 | Probe::Up { body, ms } => format!( |
| 1511 | r#"<span class="health-dot health-on"></span>{} <span class="muted">· {ms} ms</span>"#, |
| 1512 | escape(&body) |
| 1513 | ), |
| 1514 | Probe::Down => format!( |
| 1515 | r#"<span class="health-dot health-off"></span><span class="muted">{}</span>"#, |
| 1516 | t(lang, Key::HealthUnreachable), |
| 1517 | ), |
| 1518 | }; |
| 1519 | rows.push_str(&format!( |
| 1520 | r#"<tr><td class="mono">{key}</td><td>{name}</td><td class="mono"><a href="{url}" target="_blank" rel="noopener noreferrer">{url}</a></td><td>{state}</td></tr>"#, |
| 1521 | )); |
| 1522 | } |
| 1523 | Ok(format!( |
| 1524 | r#"<div class="admin-card"> |
| 1525 | <div class="auth-title">{title}</div> |
| 1526 | <div class="admin-table-wrap"> |
| 1527 | <table class="admin-table"> |
| 1528 | <thead><tr><th>{key_label}</th><th>{name_label}</th><th>{url_label}</th><th>{state_label}</th></tr></thead> |
| 1529 | <tbody>{rows}</tbody> |
| 1530 | </table> |
| 1531 | </div> |
| 1532 | </div>"#, |
| 1533 | title = t(lang, Key::HealthTitle), |
| 1534 | key_label = t(lang, Key::ServiceKeyLabel), |
| 1535 | name_label = t(lang, Key::NameCol), |
| 1536 | url_label = t(lang, Key::AddressLabel), |
| 1537 | state_label = t(lang, Key::HealthStateCol), |
| 1538 | )) |
| 1539 | } |
| 1540 | |
| 1541 | |
| 1542 | |
| 1543 | |
| 1544 | |
| 1545 | |
| 1546 | |
| 1547 | |
| 1548 | |
| 1549 | |
| 1550 | |
| 1551 | const LOG_FIT_SCRIPT: &str = r#"<script>(function () { |
| 1552 | var waits = 0; |
| 1553 | function measure() { |
| 1554 | // Never measure while the document's fonts are still arriving — every |
| 1555 | // fresh document repaints the rows in the fallback face first, and a |
| 1556 | // fit confirmed under it is wrong by half. Defer until the set is done; |
| 1557 | // after forty waits the CDN is presumed dead and the fallback face is |
| 1558 | // the truth the page will keep. |
| 1559 | if (document.fonts && document.fonts.status === 'loading' && waits < 40) { |
| 1560 | waits++; |
| 1561 | setTimeout(measure, 300); |
| 1562 | return; |
| 1563 | } |
| 1564 | var list = document.querySelector('.log-list[data-rows]'); |
| 1565 | if (!list) { return; } |
| 1566 | var current = parseInt(list.dataset.rows, 10); |
| 1567 | |
| 1568 | var row = list.querySelector('tbody tr'); |
| 1569 | if (!row || !row.offsetHeight) { return; } |
| 1570 | var avail = window.innerHeight - list.getBoundingClientRect().top - 100; |
| 1571 | var fit = Math.min(200, Math.max(5, Math.floor(avail / row.offsetHeight))); |
| 1572 | if (fit === current) { lastFit = -1; window.sessionStorage.removeItem('imLogFitHops'); return; } |
| 1573 | // A fit is committed only when two measures in a row — geometry events |
| 1574 | // are at least the debounce apart — agree on it. The font swap flips |
| 1575 | // row heights once, so the transient value never confirms; the settled |
| 1576 | // one always does. The hop budget — not a per-value veto — stops the |
| 1577 | // loop if the geometry never settles: a vetoed value would otherwise |
| 1578 | // stay wrong for the whole session. |
| 1579 | if (fit !== lastFit) { lastFit = fit; setTimeout(measure, 350); return; } |
| 1580 | var hops = parseInt(window.sessionStorage.getItem('imLogFitHops') || '0', 10); |
| 1581 | if (hops >= 5) { return; } |
| 1582 | window.sessionStorage.setItem('imLogFitHops', String(hops + 1)); |
| 1583 | document.cookie = 'im_rows_logs=' + fit + ';path=/'; |
| 1584 | location.replace(location.href); |
| 1585 | } |
| 1586 | var lastFit = -1; |
| 1587 | // No event is the right moment to measure: `load` can precede the |
| 1588 | // webfont, and a face that arrives late redraws every row taller. So the |
| 1589 | // measurement is driven by the geometry itself — a ResizeObserver on the |
| 1590 | // first row re-measures whenever its height changes (font swap, layout |
| 1591 | // settle), a window resize re-measures for the new viewport, and the |
| 1592 | // debounce folds the burst into one. A wrong early value is corrected by |
| 1593 | // the next firing. A resize also re-opens the reload budget — the hops |
| 1594 | // spent against the old geometry say nothing about the new one. |
| 1595 | var timer = null; |
| 1596 | function schedule() { |
| 1597 | if (timer) { clearTimeout(timer); } |
| 1598 | timer = setTimeout(function () { timer = null; measure(); }, 200); |
| 1599 | } |
| 1600 | var row = document.querySelector('.log-list[data-rows] tbody tr'); |
| 1601 | if (row && window.ResizeObserver) { new ResizeObserver(schedule).observe(row); } |
| 1602 | window.addEventListener('resize', function () { window.sessionStorage.removeItem('imLogFitHops'); schedule(); }); |
| 1603 | schedule(); |
| 1604 | })();</script>"#; |
| 1605 | |
| 1606 | |
| 1607 | |
| 1608 | |
| 1609 | |
| 1610 | #[derive(Deserialize)] |
| 1611 | struct InviteForm { |
| 1612 | email: String, |
| 1613 | role: Option<String>, |
| 1614 | } |
| 1615 | |
| 1616 | #[route(POST "/admin/invite")] |
| 1617 | async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Result<Response> { |
| 1618 | let me = match require_admin(cx).await { |
| 1619 | Ok(me) => me, |
| 1620 | Err(redirect) => return Ok(*redirect), |
| 1621 | }; |
| 1622 | let store = &app(cx).store; |
| 1623 | let email = input.email.trim().to_string(); |
| 1624 | let admin = input.role.as_deref() == Some("admin"); |
| 1625 | let token = match accounts::create_invite(store, &email, Some(me.id.clone()), admin).await { |
| 1626 | Ok(token) => token, |
| 1627 | Err(accounts::AccountError::EmailTaken) => { |
| 1628 | return back(cx, "users", "&error=email_taken"); |
| 1629 | } |
| 1630 | Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), |
| 1631 | }; |
| 1632 | |
| 1633 | let mailed = mailer::send_invite(store, &app(cx).config.issuer, &email, token.expose()) |
| 1634 | .await |
| 1635 | .is_ok(); |
| 1636 | server::log_event( |
| 1637 | cx, |
| 1638 | "invite_created", |
| 1639 | Some(&me.email), |
| 1640 | Some(&format!( |
| 1641 | "for {email}{}", |
| 1642 | if admin { " (admin)" } else { "" } |
| 1643 | )), |
| 1644 | ) |
| 1645 | .await; |
| 1646 | if mailed { |
| 1647 | back(cx, "users", "&ok=invited") |
| 1648 | } else { |
| 1649 | let link = format!("{}/invite/{}", app(cx).config.issuer, token.expose()); |
| 1650 | back( |
| 1651 | cx, |
| 1652 | "users", |
| 1653 | &format!("&ok=invited&invited={}", crate::oidc::urlencode(&link)), |
| 1654 | ) |
| 1655 | } |
| 1656 | } |
| 1657 | |
| 1658 | #[derive(Deserialize)] |
| 1659 | struct UserEmailForm { |
| 1660 | user: String, |
| 1661 | email: String, |
| 1662 | } |
| 1663 | |
| 1664 | |
| 1665 | |
| 1666 | |
| 1667 | |
| 1668 | #[route(POST "/admin/user_email")] |
| 1669 | async fn user_email(cx: &Cx, Form(input): Form<UserEmailForm>) -> Result<Response> { |
| 1670 | let me = match require_admin(cx).await { |
| 1671 | Ok(me) => me, |
| 1672 | Err(redirect) => return Ok(*redirect), |
| 1673 | }; |
| 1674 | let store = &app(cx).store; |
| 1675 | let user_id = UserId::from(input.user); |
| 1676 | match accounts::set_email(store, &user_id, &input.email).await { |
| 1677 | Ok(()) => server::notify_profile(cx, &user_id).await, |
| 1678 | Err(accounts::AccountError::EmailTaken) => return back(cx, "users", "&error=email_taken"), |
| 1679 | Err(accounts::AccountError::InvalidEmail) => return back(cx, "users", "&error=bad_email"), |
| 1680 | Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), |
| 1681 | } |
| 1682 | let email = input.email.trim().to_lowercase(); |
| 1683 | server::log_event(cx, "email_changed", Some(&me.email), Some(&email)).await; |
| 1684 | back(cx, "users", "&ok=email_changed") |
| 1685 | } |
| 1686 | |
| 1687 | #[derive(Deserialize)] |
| 1688 | struct InviteAction { |
| 1689 | invite: String, |
| 1690 | } |
| 1691 | |
| 1692 | |
| 1693 | #[route(POST "/admin/uninvite")] |
| 1694 | async fn uninvite(cx: &Cx, Form(input): Form<InviteAction>) -> Result<Response> { |
| 1695 | let me = match require_admin(cx).await { |
| 1696 | Ok(me) => me, |
| 1697 | Err(redirect) => return Ok(*redirect), |
| 1698 | }; |
| 1699 | let store = &app(cx).store; |
| 1700 | let email = accounts::revoke_invite(store, &input.invite).await?; |
| 1701 | server::log_event(cx, "invite_revoked", Some(&me.email), email.as_deref()).await; |
| 1702 | back(cx, "users", "&ok=uninvited") |
| 1703 | } |
| 1704 | |
| 1705 | |
| 1706 | |
| 1707 | |
| 1708 | #[route(POST "/admin/delete")] |
| 1709 | async fn delete(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { |
| 1710 | let me = match require_admin(cx).await { |
| 1711 | Ok(me) => me, |
| 1712 | Err(redirect) => return Ok(*redirect), |
| 1713 | }; |
| 1714 | let store = &app(cx).store; |
| 1715 | let user_id = UserId::from(input.user); |
| 1716 | let email = accounts::user_by_id(store, &user_id) |
| 1717 | .await? |
| 1718 | .map(|u| u.email); |
| 1719 | accounts::delete_user(store, &user_id).await?; |
| 1720 | |
| 1721 | |
| 1722 | server::note_revoked(cx, user_id.as_str(), None).await; |
| 1723 | server::log_event(cx, "user_deleted", Some(&me.email), email.as_deref()).await; |
| 1724 | back(cx, "users", "&ok=deleted") |
| 1725 | } |
| 1726 | |
| 1727 | #[derive(Deserialize)] |
| 1728 | struct UserAction { |
| 1729 | user: String, |
| 1730 | } |
| 1731 | #[route(POST "/admin/revoke")] |
| 1732 | async fn revoke(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { |
| 1733 | let me = match require_admin(cx).await { |
| 1734 | Ok(me) => me, |
| 1735 | Err(redirect) => return Ok(*redirect), |
| 1736 | }; |
| 1737 | let store = &app(cx).store; |
| 1738 | let user_id = UserId::from(input.user); |
| 1739 | let sessions = im_core::sessions::revoke_user_sessions(store, &user_id).await?; |
| 1740 | |
| 1741 | server::note_revoked(cx, user_id.as_str(), None).await; |
| 1742 | let email = accounts::user_by_id(store, &user_id) |
| 1743 | .await? |
| 1744 | .map(|u| u.email); |
| 1745 | server::log_event( |
| 1746 | cx, |
| 1747 | "sessions_revoked", |
| 1748 | Some(&me.email), |
| 1749 | Some(&format!( |
| 1750 | "{}: {sessions} session(s)", |
| 1751 | email.as_deref().unwrap_or("unknown") |
| 1752 | )), |
| 1753 | ) |
| 1754 | .await; |
| 1755 | back(cx, "users", "&ok=revoked") |
| 1756 | } |
| 1757 | |
| 1758 | #[derive(Deserialize)] |
| 1759 | struct SessionRevokeForm { |
| 1760 | user: String, |
| 1761 | session: String, |
| 1762 | } |
| 1763 | |
| 1764 | |
| 1765 | |
| 1766 | #[route(POST "/admin/session_revoke")] |
| 1767 | async fn session_revoke(cx: &Cx, Form(input): Form<SessionRevokeForm>) -> Result<Response> { |
| 1768 | let me = match require_admin(cx).await { |
| 1769 | Ok(me) => me, |
| 1770 | Err(redirect) => return Ok(*redirect), |
| 1771 | }; |
| 1772 | let user_id = UserId::from(input.user.clone()); |
| 1773 | if !im_core::sessions::revoke_owned_session(&app(cx).store, &user_id, &input.session).await? { |
| 1774 | return back(cx, "users", "&error=session_unknown"); |
| 1775 | } |
| 1776 | server::note_revoked(cx, user_id.as_str(), Some(&input.session)).await; |
| 1777 | server::log_event(cx, "session_revoked", Some(&me.email), Some(&input.user)).await; |
| 1778 | back(cx, "users", "&ok=session_revoked") |
| 1779 | } |
| 1780 | |
| 1781 | #[route(POST "/admin/disable")] |
| 1782 | async fn disable(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { |
| 1783 | set_disabled(cx, input, true).await |
| 1784 | } |
| 1785 | |
| 1786 | #[route(POST "/admin/enable")] |
| 1787 | async fn enable(cx: &Cx, Form(input): Form<UserAction>) -> Result<Response> { |
| 1788 | set_disabled(cx, input, false).await |
| 1789 | } |
| 1790 | |
| 1791 | async fn set_disabled(cx: &Cx, input: UserAction, disabled: bool) -> Result<Response> { |
| 1792 | let me = match require_admin(cx).await { |
| 1793 | Ok(me) => me, |
| 1794 | Err(redirect) => return Ok(*redirect), |
| 1795 | }; |
| 1796 | let store = &app(cx).store; |
| 1797 | let user_id = UserId::from(input.user); |
| 1798 | |
| 1799 | |
| 1800 | accounts::set_disabled(store, &user_id, disabled).await?; |
| 1801 | if disabled { |
| 1802 | |
| 1803 | im_core::sessions::revoke_user_sessions(store, &user_id).await?; |
| 1804 | |
| 1805 | |
| 1806 | server::note_revoked(cx, user_id.as_str(), None).await; |
| 1807 | } |
| 1808 | |
| 1809 | |
| 1810 | server::notify_profile(cx, &user_id).await; |
| 1811 | let email = accounts::user_by_id(store, &user_id) |
| 1812 | .await? |
| 1813 | .map(|u| u.email); |
| 1814 | server::log_event( |
| 1815 | cx, |
| 1816 | if disabled { |
| 1817 | "user_disabled" |
| 1818 | } else { |
| 1819 | "user_enabled" |
| 1820 | }, |
| 1821 | Some(&me.email), |
| 1822 | email.as_deref(), |
| 1823 | ) |
| 1824 | .await; |
| 1825 | back( |
| 1826 | cx, |
| 1827 | "users", |
| 1828 | if disabled { |
| 1829 | "&ok=disabled" |
| 1830 | } else { |
| 1831 | "&ok=enabled" |
| 1832 | }, |
| 1833 | ) |
| 1834 | } |
| 1835 | |
| 1836 | #[derive(Deserialize)] |
| 1837 | struct SmtpForm { |
| 1838 | host: String, |
| 1839 | port: u16, |
| 1840 | username: String, |
| 1841 | password: Option<String>, |
| 1842 | #[serde(default)] |
| 1843 | from_name: String, |
| 1844 | from: String, |
| 1845 | } |
| 1846 | |
| 1847 | #[route(POST "/admin/smtp")] |
| 1848 | async fn smtp_save(cx: &Cx, Form(input): Form<SmtpForm>) -> Result<Response> { |
| 1849 | let me = match require_admin(cx).await { |
| 1850 | Ok(me) => me, |
| 1851 | Err(redirect) => return Ok(*redirect), |
| 1852 | }; |
| 1853 | let store = &app(cx).store; |
| 1854 | let value = Smtp { |
| 1855 | host: input.host.trim().to_string(), |
| 1856 | port: input.port, |
| 1857 | username: input.username.trim().to_string(), |
| 1858 | from: input.from.trim().to_string(), |
| 1859 | from_name: input.from_name.trim().to_string(), |
| 1860 | password: None, |
| 1861 | }; |
| 1862 | settings::set_smtp(store, &value, input.password.as_deref()).await?; |
| 1863 | server::log_event(cx, "smtp_updated", Some(&me.email), None).await; |
| 1864 | |
| 1865 | |
| 1866 | tokio::spawn(probe(store_of(cx), app(cx).live.clone())); |
| 1867 | back(cx, "mail", "&ok=smtp") |
| 1868 | } |
| 1869 | |
| 1870 | #[route(POST "/admin/smtp_test")] |
| 1871 | async fn smtp_test(cx: &Cx) -> Result<Response> { |
| 1872 | let me = match require_admin(cx).await { |
| 1873 | Ok(me) => me, |
| 1874 | Err(redirect) => return Ok(*redirect), |
| 1875 | }; |
| 1876 | if !settings::smtp(&app(cx).store).await?.configured() { |
| 1877 | return back(cx, "mail", "&error=sender_unset"); |
| 1878 | } |
| 1879 | match mailer::send_test(&app(cx).store, &me.email, lang_of(Some(&me))).await { |
| 1880 | Ok(()) => { |
| 1881 | server::log_event(cx, "smtp_test_sent", Some(&me.email), None).await; |
| 1882 | back(cx, "mail", "&ok=smtp_test") |
| 1883 | } |
| 1884 | Err(e) => { |
| 1885 | server::log_event( |
| 1886 | cx, |
| 1887 | "smtp_test_failed", |
| 1888 | Some(&me.email), |
| 1889 | Some(&e.to_string()), |
| 1890 | ) |
| 1891 | .await; |
| 1892 | back( |
| 1893 | cx, |
| 1894 | "mail", |
| 1895 | &format!( |
| 1896 | "&error=smtp_test&why={}", |
| 1897 | crate::oidc::urlencode(&e.to_string()) |
| 1898 | ), |
| 1899 | ) |
| 1900 | } |
| 1901 | } |
| 1902 | } |
| 1903 | |
| 1904 | #[derive(Deserialize)] |
| 1905 | struct MessageForm { |
| 1906 | to: String, |
| 1907 | subject: String, |
| 1908 | body: String, |
| 1909 | } |
| 1910 | |
| 1911 | |
| 1912 | |
| 1913 | |
| 1914 | |
| 1915 | #[route(POST "/admin/message")] |
| 1916 | async fn message(cx: &Cx, Form(input): Form<MessageForm>) -> Result<Response> { |
| 1917 | let me = match require_admin(cx).await { |
| 1918 | Ok(me) => me, |
| 1919 | Err(redirect) => return Ok(*redirect), |
| 1920 | }; |
| 1921 | let store = &app(cx).store; |
| 1922 | if !settings::smtp(store).await?.configured() { |
| 1923 | return back(cx, "message", "&error=sender_unset"); |
| 1924 | } |
| 1925 | let subject = input.subject.trim(); |
| 1926 | if subject.is_empty() { |
| 1927 | return back(cx, "message", "&error=empty_subject"); |
| 1928 | } |
| 1929 | let body = input.body.trim(); |
| 1930 | if body.is_empty() { |
| 1931 | return back(cx, "message", "&error=empty_body"); |
| 1932 | } |
| 1933 | let users = accounts::list_users(store).await?; |
| 1934 | let recipients: Vec<String> = if input.to == "everyone" { |
| 1935 | users |
| 1936 | .into_iter() |
| 1937 | .filter(|person| person.id != me.id) |
| 1938 | .map(|person| person.email) |
| 1939 | .collect() |
| 1940 | } else { |
| 1941 | match users |
| 1942 | .into_iter() |
| 1943 | .find(|person| person.id.as_str() == input.to) |
| 1944 | { |
| 1945 | Some(person) => vec![person.email], |
| 1946 | None => return back(cx, "message", "&error=no_such_user"), |
| 1947 | } |
| 1948 | }; |
| 1949 | if recipients.is_empty() { |
| 1950 | return back(cx, "message", "&error=no_such_user"); |
| 1951 | } |
| 1952 | for recipient in &recipients { |
| 1953 | if let Err(e) = mailer::send_message(store, recipient, subject, body.to_string()).await { |
| 1954 | server::log_event(cx, "message_failed", Some(&me.email), Some(&e.to_string())).await; |
| 1955 | return back( |
| 1956 | cx, |
| 1957 | "message", |
| 1958 | &format!( |
| 1959 | "&error=message&why={}", |
| 1960 | crate::oidc::urlencode(&e.to_string()) |
| 1961 | ), |
| 1962 | ); |
| 1963 | } |
| 1964 | } |
| 1965 | server::log_event(cx, "message_sent", Some(&me.email), Some(subject)).await; |
| 1966 | back(cx, "message", "&ok=message") |
| 1967 | } |
| 1968 | |
| 1969 | |
| 1970 | |
| 1971 | #[route(POST "/admin/smtp_check")] |
| 1972 | async fn smtp_check(cx: &Cx) -> Result<Response> { |
| 1973 | let me = match require_admin(cx).await { |
| 1974 | Ok(me) => me, |
| 1975 | Err(redirect) => return Ok(*redirect), |
| 1976 | }; |
| 1977 | if !settings::smtp(&app(cx).store).await?.configured() { |
| 1978 | return back(cx, "mail", "&error=sender_unset"); |
| 1979 | } |
| 1980 | probe(store_of(cx), app(cx).live.clone()).await; |
| 1981 | server::log_event(cx, "smtp_checked", Some(&me.email), None).await; |
| 1982 | back(cx, "mail", "") |
| 1983 | } |
| 1984 | |
| 1985 | fn store_of(cx: &Cx) -> std::sync::Arc<im_core::store::Store> { |
| 1986 | app(cx).store.clone() |
| 1987 | } |
| 1988 | |
| 1989 | |
| 1990 | |
| 1991 | |
| 1992 | |
| 1993 | async fn probe( |
| 1994 | store: std::sync::Arc<im_core::store::Store>, |
| 1995 | live: tokio::sync::broadcast::Sender<server::LiveEvent>, |
| 1996 | ) { |
| 1997 | let check = match mailer::check(&store).await { |
| 1998 | Ok(took_ms) => settings::SenderCheck { |
| 1999 | at: time::OffsetDateTime::now_utc(), |
| 2000 | took_ms, |
| 2001 | error: None, |
| 2002 | }, |
| 2003 | Err(problem) => settings::SenderCheck { |
| 2004 | at: time::OffsetDateTime::now_utc(), |
| 2005 | took_ms: 0, |
| 2006 | error: Some(problem.to_string()), |
| 2007 | }, |
| 2008 | }; |
| 2009 | if let Err(problem) = settings::record_check(&store, &check).await { |
| 2010 | eprintln!("im: failed to record the sender check: {problem}"); |
| 2011 | } |
| 2012 | |
| 2013 | let _ = live.send(server::LiveEvent::Tick); |
| 2014 | } |
| 2015 | |
| 2016 | #[cfg(test)] |
| 2017 | mod tests { |
| 2018 | use std::path::Path; |
| 2019 | use std::sync::Arc; |
| 2020 | |
| 2021 | use im_core::accounts::{create_invite, create_user_from_invite}; |
| 2022 | use im_core::model::{ClientId, UserId}; |
| 2023 | use im_core::oidc::{introspect_app_session, issue_app_session, list_clients}; |
| 2024 | use im_core::sessions::{SessionMeta, create_session}; |
| 2025 | use im_core::store::Store; |
| 2026 | use topcoat::asset::RouterBuilderAssetExt as _; |
| 2027 | use topcoat::cookie::RouterBuilderCookieExt as _; |
| 2028 | use topcoat::router::{ |
| 2029 | Body, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes, |
| 2030 | }; |
| 2031 | |
| 2032 | use crate::config::Config; |
| 2033 | use crate::health::Probe; |
| 2034 | use crate::server::{self, SESSION_COOKIE}; |
| 2035 | |
| 2036 | struct Setup { |
| 2037 | router: Router, |
| 2038 | store: Arc<Store>, |
| 2039 | admin_id: UserId, |
| 2040 | admin_cookie: String, |
| 2041 | plain_cookie: String, |
| 2042 | |
| 2043 | |
| 2044 | |
| 2045 | |
| 2046 | assets: bool, |
| 2047 | } |
| 2048 | |
| 2049 | async fn setup() -> Setup { |
| 2050 | let store = Store::open(Path::new(":memory:")).await.unwrap(); |
| 2051 | let invite = create_invite(&store, "root@example.com", None, true) |
| 2052 | .await |
| 2053 | .unwrap(); |
| 2054 | let admin = create_user_from_invite(&store, invite.expose(), "Root", "tDLr9!mZQ2xv") |
| 2055 | .await |
| 2056 | .unwrap(); |
| 2057 | let bare = create_invite(&store, "sid@example.com", None, false) |
| 2058 | .await |
| 2059 | .unwrap(); |
| 2060 | let plain = create_user_from_invite(&store, bare.expose(), "Sid", "tDLr9!mZQ2xv") |
| 2061 | .await |
| 2062 | .unwrap(); |
| 2063 | let admin_session = create_session(&store, &admin.id, &SessionMeta::default()) |
| 2064 | .await |
| 2065 | .unwrap(); |
| 2066 | let plain_session = create_session(&store, &plain.id, &SessionMeta::default()) |
| 2067 | .await |
| 2068 | .unwrap(); |
| 2069 | let (live, _) = tokio::sync::broadcast::channel(64); |
| 2070 | let store = Arc::new(store); |
| 2071 | let app = server::App { |
| 2072 | store: store.clone(), |
| 2073 | config: Config { |
| 2074 | database: ":memory:".into(), |
| 2075 | listen: "127.0.0.1:7650".parse().unwrap(), |
| 2076 | issuer: "http://127.0.0.1:7650".into(), |
| 2077 | services: Vec::new(), |
| 2078 | }, |
| 2079 | live, |
| 2080 | }; |
| 2081 | |
| 2082 | |
| 2083 | |
| 2084 | let bundle = std::env::current_exe() |
| 2085 | .ok() |
| 2086 | .and_then(|exe| exe.parent().and_then(|deps| deps.parent()).map(|p| p.join("assets"))) |
| 2087 | .and_then(|dir| topcoat::asset::AssetBundle::load_dir(dir).ok()); |
| 2088 | let assets = bundle.is_some(); |
| 2089 | let mut builder = Router::builder().discover().cookies(); |
| 2090 | if let Some(bundle) = bundle { |
| 2091 | builder = builder.assets(bundle); |
| 2092 | } |
| 2093 | let router = builder.app_context(app).build(); |
| 2094 | Setup { |
| 2095 | router, |
| 2096 | store, |
| 2097 | admin_id: admin.id, |
| 2098 | admin_cookie: format!("{SESSION_COOKIE}={}", admin_session.expose()), |
| 2099 | plain_cookie: format!("{SESSION_COOKIE}={}", plain_session.expose()), |
| 2100 | assets, |
| 2101 | } |
| 2102 | } |
| 2103 | |
| 2104 | |
| 2105 | async fn post_form( |
| 2106 | router: &Router, |
| 2107 | uri: &str, |
| 2108 | body: &str, |
| 2109 | cookie: Option<&str>, |
| 2110 | ) -> (StatusCode, Option<String>, String) { |
| 2111 | let mut builder = http::Request::builder() |
| 2112 | .method(http::Method::POST) |
| 2113 | .uri(uri) |
| 2114 | .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); |
| 2115 | if let Some(cookie) = cookie { |
| 2116 | builder = builder.header(header::COOKIE, cookie); |
| 2117 | } |
| 2118 | let response = router |
| 2119 | .handle(builder.body(Body::from(body.to_string())).unwrap()) |
| 2120 | .await; |
| 2121 | let (parts, body) = response.into_parts(); |
| 2122 | let location = parts |
| 2123 | .headers |
| 2124 | .get(header::LOCATION) |
| 2125 | .and_then(|v| v.to_str().ok()) |
| 2126 | .map(str::to_string); |
| 2127 | let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); |
| 2128 | (parts.status, location, String::from_utf8(bytes).unwrap()) |
| 2129 | } |
| 2130 | |
| 2131 | |
| 2132 | |
| 2133 | async fn get_full( |
| 2134 | router: &Router, |
| 2135 | uri: &str, |
| 2136 | cookie: Option<&str>, |
| 2137 | ) -> (StatusCode, Option<String>, String) { |
| 2138 | let mut builder = http::Request::builder().uri(uri); |
| 2139 | if let Some(cookie) = cookie { |
| 2140 | builder = builder.header(header::COOKIE, cookie); |
| 2141 | } |
| 2142 | let response = router.handle(builder.body(Body::empty()).unwrap()).await; |
| 2143 | let (parts, body) = response.into_parts(); |
| 2144 | let location = parts |
| 2145 | .headers |
| 2146 | .get(header::LOCATION) |
| 2147 | .and_then(|v| v.to_str().ok()) |
| 2148 | .map(str::to_string); |
| 2149 | let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); |
| 2150 | ( |
| 2151 | parts.status, |
| 2152 | location, |
| 2153 | String::from_utf8(bytes).unwrap(), |
| 2154 | ) |
| 2155 | } |
| 2156 | |
| 2157 | fn basic(client_id: &str, secret: &str) -> String { |
| 2158 | use base64::Engine as _; |
| 2159 | format!( |
| 2160 | "Basic {}", |
| 2161 | base64::engine::general_purpose::STANDARD.encode(format!("{client_id}:{secret}")) |
| 2162 | ) |
| 2163 | } |
| 2164 | |
| 2165 | |
| 2166 | |
| 2167 | |
| 2168 | async fn create_via_panel(setup: &Setup, name: &str) -> (String, String) { |
| 2169 | let (status, location, _) = post_form( |
| 2170 | &setup.router, |
| 2171 | "/admin/clients_add", |
| 2172 | &format!("name={name}&redirect_uris=http://127.0.0.1:9000/callback"), |
| 2173 | Some(&setup.admin_cookie), |
| 2174 | ) |
| 2175 | .await; |
| 2176 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2177 | let location = location.expect("a 303 back to the section"); |
| 2178 | assert!(location.starts_with("/admin?section=clients&shown=")); |
| 2179 | let ticket = location.trim_start_matches("/admin?section=clients&shown="); |
| 2180 | let (id, secret) = server::take_shown_secret(ticket).expect("the one showing"); |
| 2181 | let stored = list_clients(&setup.store).await.unwrap(); |
| 2182 | let row = stored |
| 2183 | .iter() |
| 2184 | .find(|client| client.name == name) |
| 2185 | .expect("the fresh row"); |
| 2186 | assert_eq!(id, row.client_id.to_string()); |
| 2187 | (id, secret) |
| 2188 | } |
| 2189 | |
| 2190 | |
| 2191 | async fn directory(router: &Router, authorization: String) -> StatusCode { |
| 2192 | let response = router |
| 2193 | .handle( |
| 2194 | http::Request::builder() |
| 2195 | .uri("/directory") |
| 2196 | .header(header::AUTHORIZATION, authorization) |
| 2197 | .body(Body::empty()) |
| 2198 | .unwrap(), |
| 2199 | ) |
| 2200 | .await; |
| 2201 | response.into_parts().0.status |
| 2202 | } |
| 2203 | |
| 2204 | #[tokio::test] |
| 2205 | async fn clients_add_shows_the_secret_once_and_the_pair_authenticates() { |
| 2206 | let setup = setup().await; |
| 2207 | |
| 2208 | |
| 2209 | |
| 2210 | let (status, location, _) = post_form( |
| 2211 | &setup.router, |
| 2212 | "/admin/clients_add", |
| 2213 | "name=drive&redirect_uris=http://127.0.0.1:9000/callback", |
| 2214 | Some(&setup.admin_cookie), |
| 2215 | ) |
| 2216 | .await; |
| 2217 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2218 | let location = location.expect("a 303 back to the section"); |
| 2219 | assert!(location.starts_with("/admin?section=clients&shown=")); |
| 2220 | assert!(!location.contains("secret")); |
| 2221 | |
| 2222 | |
| 2223 | |
| 2224 | let ticket = location.trim_start_matches("/admin?section=clients&shown="); |
| 2225 | let (id, secret) = server::take_shown_secret(ticket).expect("the one showing"); |
| 2226 | assert!(server::take_shown_secret(ticket).is_none()); |
| 2227 | assert!( |
| 2228 | server::take_shown_secret("a-forged-ticket").is_none(), |
| 2229 | "a forged ticket shows nothing" |
| 2230 | ); |
| 2231 | |
| 2232 | |
| 2233 | assert_eq!( |
| 2234 | directory(&setup.router, basic(&id, &secret)).await, |
| 2235 | StatusCode::OK |
| 2236 | ); |
| 2237 | |
| 2238 | |
| 2239 | |
| 2240 | let rows = list_clients(&setup.store).await.unwrap(); |
| 2241 | assert_eq!(rows.len(), 1); |
| 2242 | assert_eq!(rows[0].name, "drive"); |
| 2243 | assert_ne!(rows[0].client_id.to_string(), secret); |
| 2244 | } |
| 2245 | |
| 2246 | #[tokio::test] |
| 2247 | async fn clients_rotate_kills_the_old_pair_and_shows_a_new_secret_once() { |
| 2248 | let setup = setup().await; |
| 2249 | let (id, old_secret) = create_via_panel(&setup, "drive").await; |
| 2250 | |
| 2251 | let (status, location, _) = post_form( |
| 2252 | &setup.router, |
| 2253 | "/admin/clients_rotate", |
| 2254 | &format!("client={id}"), |
| 2255 | Some(&setup.admin_cookie), |
| 2256 | ) |
| 2257 | .await; |
| 2258 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2259 | let location = location.expect("a 303 back to the section"); |
| 2260 | assert!(location.starts_with("/admin?section=clients&shown=")); |
| 2261 | let ticket = location.trim_start_matches("/admin?section=clients&shown="); |
| 2262 | let (rotated_id, new_secret) = server::take_shown_secret(ticket).expect("the one showing"); |
| 2263 | assert_eq!(rotated_id, id, "the shelf names the same client"); |
| 2264 | assert_ne!(old_secret, new_secret); |
| 2265 | |
| 2266 | |
| 2267 | assert_eq!( |
| 2268 | directory(&setup.router, basic(&id, &old_secret)).await, |
| 2269 | StatusCode::UNAUTHORIZED |
| 2270 | ); |
| 2271 | assert_eq!( |
| 2272 | directory(&setup.router, basic(&id, &new_secret)).await, |
| 2273 | StatusCode::OK |
| 2274 | ); |
| 2275 | |
| 2276 | |
| 2277 | let (status, location, _) = post_form( |
| 2278 | &setup.router, |
| 2279 | "/admin/clients_rotate", |
| 2280 | "client=no-such-client", |
| 2281 | Some(&setup.admin_cookie), |
| 2282 | ) |
| 2283 | .await; |
| 2284 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2285 | assert_eq!( |
| 2286 | location.as_deref(), |
| 2287 | Some("/admin?section=clients&error=no_such_client") |
| 2288 | ); |
| 2289 | } |
| 2290 | |
| 2291 | #[tokio::test] |
| 2292 | async fn clients_revoke_kills_the_pair_and_its_tokens() { |
| 2293 | let setup = setup().await; |
| 2294 | let (id, secret) = create_via_panel(&setup, "drive").await; |
| 2295 | let client_id = ClientId::from(id.clone()); |
| 2296 | |
| 2297 | |
| 2298 | let session = create_session(&setup.store, &setup.admin_id, &SessionMeta::default()) |
| 2299 | .await |
| 2300 | .unwrap(); |
| 2301 | let app_token = |
| 2302 | issue_app_session(&setup.store, &setup.admin_id, &client_id, &session.hash()) |
| 2303 | .await |
| 2304 | .unwrap(); |
| 2305 | assert!( |
| 2306 | introspect_app_session(&setup.store, app_token.expose(), &id) |
| 2307 | .await |
| 2308 | .unwrap() |
| 2309 | .is_some() |
| 2310 | ); |
| 2311 | |
| 2312 | let (status, location, _) = post_form( |
| 2313 | &setup.router, |
| 2314 | "/admin/clients_revoke", |
| 2315 | &format!("client={id}"), |
| 2316 | Some(&setup.admin_cookie), |
| 2317 | ) |
| 2318 | .await; |
| 2319 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2320 | assert_eq!( |
| 2321 | location.as_deref(), |
| 2322 | Some("/admin?section=clients&ok=client_revoked") |
| 2323 | ); |
| 2324 | |
| 2325 | |
| 2326 | |
| 2327 | |
| 2328 | assert_eq!( |
| 2329 | directory(&setup.router, basic(&id, &secret)).await, |
| 2330 | StatusCode::UNAUTHORIZED |
| 2331 | ); |
| 2332 | assert!( |
| 2333 | introspect_app_session(&setup.store, app_token.expose(), &id) |
| 2334 | .await |
| 2335 | .unwrap() |
| 2336 | .is_none(), |
| 2337 | "no ghost app session after revocation" |
| 2338 | ); |
| 2339 | assert_eq!( |
| 2340 | im_core::sessions::list_sessions(&setup.store, &setup.admin_id) |
| 2341 | .await |
| 2342 | .unwrap() |
| 2343 | .len(), |
| 2344 | 2, |
| 2345 | "the admin's two sign-in sessions — the cookie's and the one that \ |
| 2346 | minted the app token — both stay" |
| 2347 | ); |
| 2348 | } |
| 2349 | |
| 2350 | #[tokio::test] |
| 2351 | async fn client_routes_refuse_non_admins() { |
| 2352 | let setup = setup().await; |
| 2353 | |
| 2354 | |
| 2355 | |
| 2356 | let (status, location, _) = post_form( |
| 2357 | &setup.router, |
| 2358 | "/admin/clients_add", |
| 2359 | "name=drive&redirect_uris=http://127.0.0.1:9000/callback", |
| 2360 | Some(&setup.plain_cookie), |
| 2361 | ) |
| 2362 | .await; |
| 2363 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2364 | assert_eq!(location.as_deref(), Some("/")); |
| 2365 | let (status, location, _) = post_form( |
| 2366 | &setup.router, |
| 2367 | "/admin/clients_revoke", |
| 2368 | "client=no-such-client", |
| 2369 | Some(&setup.plain_cookie), |
| 2370 | ) |
| 2371 | .await; |
| 2372 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2373 | assert_eq!(location.as_deref(), Some("/")); |
| 2374 | assert!(list_clients(&setup.store).await.unwrap().is_empty()); |
| 2375 | |
| 2376 | |
| 2377 | let (status, location, _) = get_full( |
| 2378 | &setup.router, |
| 2379 | "/admin?section=clients", |
| 2380 | Some(&setup.plain_cookie), |
| 2381 | ) |
| 2382 | .await; |
| 2383 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2384 | assert_eq!(location.as_deref(), Some("/")); |
| 2385 | |
| 2386 | let (status, _, _) = post_form( |
| 2387 | &setup.router, |
| 2388 | "/admin/clients_add", |
| 2389 | "name=drive&redirect_uris=http://127.0.0.1:9000/callback", |
| 2390 | None, |
| 2391 | ) |
| 2392 | .await; |
| 2393 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2394 | } |
| 2395 | |
| 2396 | #[tokio::test] |
| 2397 | async fn shown_ticket_renders_the_banner_exactly_once() { |
| 2398 | let setup = setup().await; |
| 2399 | let (status, location, _) = post_form( |
| 2400 | &setup.router, |
| 2401 | "/admin/clients_add", |
| 2402 | "name=drive&redirect_uris=http://127.0.0.1:9000/callback", |
| 2403 | Some(&setup.admin_cookie), |
| 2404 | ) |
| 2405 | .await; |
| 2406 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2407 | let location = location.expect("a 303 back to the section"); |
| 2408 | |
| 2409 | |
| 2410 | |
| 2411 | |
| 2412 | if !setup.assets { |
| 2413 | return; |
| 2414 | } |
| 2415 | |
| 2416 | |
| 2417 | |
| 2418 | let (page, _, body) = |
| 2419 | get_full(&setup.router, &location, Some(&setup.admin_cookie)).await; |
| 2420 | assert_eq!(page, StatusCode::OK); |
| 2421 | assert!( |
| 2422 | body.contains("<div class=\"auth-secret admin-copy-value\">"), |
| 2423 | "banner renders" |
| 2424 | ); |
| 2425 | let secret = body |
| 2426 | .split("admin-copy-value\">") |
| 2427 | .nth(1) |
| 2428 | .expect("the banner's value box") |
| 2429 | .split("</div>") |
| 2430 | .next() |
| 2431 | .unwrap() |
| 2432 | .to_string(); |
| 2433 | assert!(!secret.is_empty()); |
| 2434 | let id = list_clients(&setup.store).await.unwrap()[0] |
| 2435 | .client_id |
| 2436 | .to_string(); |
| 2437 | assert!(body.contains(&id), "the client id rides the banner too"); |
| 2438 | |
| 2439 | |
| 2440 | let (_, _, replay) = |
| 2441 | get_full(&setup.router, &location, Some(&setup.admin_cookie)).await; |
| 2442 | assert!(!replay.contains("<div class=\"auth-secret")); |
| 2443 | let (_, _, forged) = get_full( |
| 2444 | &setup.router, |
| 2445 | "/admin?section=clients&shown=forged-ticket", |
| 2446 | Some(&setup.admin_cookie), |
| 2447 | ) |
| 2448 | .await; |
| 2449 | assert!(!forged.contains("<div class=\"auth-secret")); |
| 2450 | } |
| 2451 | |
| 2452 | #[tokio::test] |
| 2453 | async fn merged_section_renders_linked_unlinked_and_bare_rows() { |
| 2454 | let setup = setup().await; |
| 2455 | |
| 2456 | |
| 2457 | |
| 2458 | let (id, _secret) = create_via_panel(&setup, "drive").await; |
| 2459 | im_core::services::register( |
| 2460 | &setup.store, |
| 2461 | "drive", |
| 2462 | "Drive", |
| 2463 | "https://drive.dizey.sh", |
| 2464 | &id, |
| 2465 | Some(&id), |
| 2466 | ) |
| 2467 | .await |
| 2468 | .unwrap(); |
| 2469 | |
| 2470 | |
| 2471 | create_via_panel(&setup, "stray").await; |
| 2472 | im_core::services::add( |
| 2473 | &setup.store, |
| 2474 | &im_core::services::Service { |
| 2475 | key: "wiki".into(), |
| 2476 | name: "Wiki".into(), |
| 2477 | url: "https://wiki.dizey.sh".into(), |
| 2478 | owner: None, |
| 2479 | client_id: None, |
| 2480 | storage_limit_bytes: None, |
| 2481 | }, |
| 2482 | ) |
| 2483 | .await |
| 2484 | .unwrap(); |
| 2485 | |
| 2486 | |
| 2487 | |
| 2488 | if !setup.assets { |
| 2489 | return; |
| 2490 | } |
| 2491 | let (status, _, body) = get_full( |
| 2492 | &setup.router, |
| 2493 | "/admin?section=services", |
| 2494 | Some(&setup.admin_cookie), |
| 2495 | ) |
| 2496 | .await; |
| 2497 | assert_eq!(status, StatusCode::OK); |
| 2498 | |
| 2499 | |
| 2500 | assert!(body.contains(">Drive</td>"), "the service name renders"); |
| 2501 | assert!(body.contains(&id), "the linked client id renders"); |
| 2502 | assert!(body.contains("https://drive.dizey.sh"), "the url renders"); |
| 2503 | assert!(body.contains("http://127.0.0.1:9000/callback"), "uris render"); |
| 2504 | |
| 2505 | assert!(body.contains(">stray</td>"), "the stray client renders"); |
| 2506 | |
| 2507 | assert!(body.contains(">Wiki</td>"), "the bare service renders"); |
| 2508 | assert!( |
| 2509 | body.contains("<td class=\"muted\">—</td>"), |
| 2510 | "client-less halves read as the dash" |
| 2511 | ); |
| 2512 | |
| 2513 | |
| 2514 | let (status, _, alias) = get_full( |
| 2515 | &setup.router, |
| 2516 | "/admin?section=clients", |
| 2517 | Some(&setup.admin_cookie), |
| 2518 | ) |
| 2519 | .await; |
| 2520 | assert_eq!(status, StatusCode::OK); |
| 2521 | assert_eq!(alias.contains(">Drive</td>"), body.contains(">Drive</td>")); |
| 2522 | } |
| 2523 | |
| 2524 | #[tokio::test] |
| 2525 | async fn services_edit_saves_the_limit_and_the_rest_is_refused() { |
| 2526 | let setup = setup().await; |
| 2527 | im_core::services::add( |
| 2528 | &setup.store, |
| 2529 | &im_core::services::Service { |
| 2530 | key: "in".into(), |
| 2531 | name: "Files".into(), |
| 2532 | url: "https://in.dizey.sh".into(), |
| 2533 | owner: None, |
| 2534 | client_id: None, |
| 2535 | storage_limit_bytes: None, |
| 2536 | }, |
| 2537 | ) |
| 2538 | .await |
| 2539 | .unwrap(); |
| 2540 | |
| 2541 | |
| 2542 | let (status, location, _) = post_form( |
| 2543 | &setup.router, |
| 2544 | "/admin/services_edit", |
| 2545 | "key=in&name=Files&url=https://in.dizey.sh&limit_amount=2&limit_unit=GiB", |
| 2546 | Some(&setup.admin_cookie), |
| 2547 | ) |
| 2548 | .await; |
| 2549 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2550 | assert_eq!( |
| 2551 | location.as_deref(), |
| 2552 | Some("/admin?section=services&ok=services") |
| 2553 | ); |
| 2554 | assert_eq!( |
| 2555 | im_core::services::list(&setup.store).await.unwrap()[0].storage_limit_bytes, |
| 2556 | Some(2 * 1024 * 1024 * 1024) |
| 2557 | ); |
| 2558 | |
| 2559 | |
| 2560 | let (status, location, _) = post_form( |
| 2561 | &setup.router, |
| 2562 | "/admin/services_edit", |
| 2563 | "key=in&name=Files&url=https://in.dizey.sh&limit_amount=&limit_unit=GiB", |
| 2564 | Some(&setup.admin_cookie), |
| 2565 | ) |
| 2566 | .await; |
| 2567 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2568 | assert_eq!( |
| 2569 | location.as_deref(), |
| 2570 | Some("/admin?section=services&ok=services") |
| 2571 | ); |
| 2572 | assert_eq!( |
| 2573 | im_core::services::list(&setup.store).await.unwrap()[0].storage_limit_bytes, |
| 2574 | None |
| 2575 | ); |
| 2576 | |
| 2577 | |
| 2578 | |
| 2579 | let (status, location, _) = post_form( |
| 2580 | &setup.router, |
| 2581 | "/admin/services_edit", |
| 2582 | "key=in&name=Files&url=https://in.dizey.sh&limit_amount=abc&limit_unit=GiB", |
| 2583 | Some(&setup.admin_cookie), |
| 2584 | ) |
| 2585 | .await; |
| 2586 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2587 | assert_eq!( |
| 2588 | location.as_deref(), |
| 2589 | Some("/admin?section=services&error=bad_service") |
| 2590 | ); |
| 2591 | assert_eq!( |
| 2592 | im_core::services::list(&setup.store).await.unwrap()[0].storage_limit_bytes, |
| 2593 | None |
| 2594 | ); |
| 2595 | |
| 2596 | |
| 2597 | let (status, location, _) = post_form( |
| 2598 | &setup.router, |
| 2599 | "/admin/services_edit", |
| 2600 | "key=in&name=Files&url=https://in.dizey.sh&limit_amount=2&limit_unit=GiB", |
| 2601 | Some(&setup.plain_cookie), |
| 2602 | ) |
| 2603 | .await; |
| 2604 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2605 | assert_eq!(location.as_deref(), Some("/")); |
| 2606 | assert_eq!( |
| 2607 | im_core::services::list(&setup.store).await.unwrap()[0].storage_limit_bytes, |
| 2608 | None |
| 2609 | ); |
| 2610 | |
| 2611 | |
| 2612 | |
| 2613 | if setup.assets { |
| 2614 | let (status, _, body) = get_full( |
| 2615 | &setup.router, |
| 2616 | "/admin?section=services", |
| 2617 | Some(&setup.admin_cookie), |
| 2618 | ) |
| 2619 | .await; |
| 2620 | assert_eq!(status, StatusCode::OK); |
| 2621 | assert!(body.contains("name=\"limit_amount\""), "{body}"); |
| 2622 | assert!(body.contains("name=\"limit_unit\""), "{body}"); |
| 2623 | assert!(body.contains(">GiB</option>"), "{body}"); |
| 2624 | assert!( |
| 2625 | body.contains("name=\"limit_amount\" min=\"0\" step=\"any\" value=\"\""), |
| 2626 | "a no-limit row edits empty: {body}" |
| 2627 | ); |
| 2628 | } |
| 2629 | } |
| 2630 | |
| 2631 | |
| 2632 | |
| 2633 | #[tokio::test] |
| 2634 | async fn healthz_answers_the_baked_sha() { |
| 2635 | let setup = setup().await; |
| 2636 | let (status, _, body) = get_full(&setup.router, "/healthz", None).await; |
| 2637 | assert_eq!(status, StatusCode::OK); |
| 2638 | assert!( |
| 2639 | body.starts_with("ok "), |
| 2640 | "healthz must answer `ok <build sha>`, got {body:?}" |
| 2641 | ); |
| 2642 | } |
| 2643 | |
| 2644 | |
| 2645 | |
| 2646 | |
| 2647 | #[tokio::test] |
| 2648 | async fn health_probe_reads_ok_and_refuses_the_rest() { |
| 2649 | use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; |
| 2650 | |
| 2651 | let http = reqwest::Client::new(); |
| 2652 | |
| 2653 | |
| 2654 | use crate::health::probe_healthz; |
| 2655 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 2656 | |
| 2657 | let addr = listener.local_addr().unwrap(); |
| 2658 | let talker = tokio::spawn(async move { |
| 2659 | let (mut sock, _) = listener.accept().await.unwrap(); |
| 2660 | let mut buf = [0u8; 1024]; |
| 2661 | let _ = sock.read(&mut buf).await; |
| 2662 | sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 6\r\n\r\nok dev") |
| 2663 | .await |
| 2664 | .unwrap(); |
| 2665 | }); |
| 2666 | let probe = probe_healthz(&http, &format!("http://{addr}/healthz")).await; |
| 2667 | talker.await.unwrap(); |
| 2668 | let Probe::Up { body, .. } = probe else { |
| 2669 | panic!("a service answering `ok dev` must read Up"); |
| 2670 | }; |
| 2671 | assert_eq!(body, "ok dev"); |
| 2672 | |
| 2673 | |
| 2674 | let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 2675 | let addr = dark.local_addr().unwrap(); |
| 2676 | drop(dark); |
| 2677 | let probe = probe_healthz(&http, &format!("http://{addr}/healthz")).await; |
| 2678 | assert!(matches!(probe, Probe::Down), "a dark port must read Down"); |
| 2679 | } |
| 2680 | |
| 2681 | |
| 2682 | |
| 2683 | #[tokio::test] |
| 2684 | async fn health_section_is_admin_only_and_renders() { |
| 2685 | let setup = setup().await; |
| 2686 | |
| 2687 | |
| 2688 | |
| 2689 | |
| 2690 | let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 2691 | let dead_url = format!("http://{}", dark.local_addr().unwrap()); |
| 2692 | drop(dark); |
| 2693 | im_core::services::add( |
| 2694 | &setup.store, |
| 2695 | &im_core::services::Service { |
| 2696 | key: "xy".into(), |
| 2697 | name: "Fixture".into(), |
| 2698 | url: dead_url, |
| 2699 | owner: None, |
| 2700 | client_id: None, |
| 2701 | storage_limit_bytes: None, |
| 2702 | }, |
| 2703 | ) |
| 2704 | .await |
| 2705 | .unwrap(); |
| 2706 | let (status, location, _) = |
| 2707 | get_full(&setup.router, "/admin?section=health", Some(&setup.plain_cookie)).await; |
| 2708 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 2709 | assert_eq!(location.as_deref(), Some("/")); |
| 2710 | if setup.assets { |
| 2711 | let (status, _, body) = |
| 2712 | get_full(&setup.router, "/admin?section=health", Some(&setup.admin_cookie)).await; |
| 2713 | assert_eq!(status, StatusCode::OK); |
| 2714 | assert!(body.contains("Family health"), "{body}"); |
| 2715 | assert!(body.contains("/admin?section=health"), "the nav carries the section: {body}"); |
| 2716 | assert!(body.contains("health-dot"), "{body}"); |
| 2717 | assert!(body.contains(">xy</td>"), "the fixture row renders: {body}"); |
| 2718 | assert!(body.contains("Unreachable"), "the dark row reads Down: {body}"); |
| 2719 | } |
| 2720 | } |
| 2721 | |
| 2722 | |
| 2723 | |
| 2724 | |
| 2725 | |
| 2726 | |
| 2727 | |
| 2728 | #[tokio::test] |
| 2729 | async fn family_flyout_marks_siblings_with_health_dots() { |
| 2730 | use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; |
| 2731 | |
| 2732 | let setup = setup().await; |
| 2733 | |
| 2734 | |
| 2735 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 2736 | let live_url = format!("http://{}", listener.local_addr().unwrap()); |
| 2737 | let dark = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 2738 | let dark_url = format!("http://{}", dark.local_addr().unwrap()); |
| 2739 | drop(dark); |
| 2740 | |
| 2741 | for (key, url) in [("iz", live_url), ("in", dark_url.clone()), ("im", dark_url)] { |
| 2742 | im_core::services::add( |
| 2743 | &setup.store, |
| 2744 | &im_core::services::Service { |
| 2745 | key: key.into(), |
| 2746 | name: "Fixture".into(), |
| 2747 | url, |
| 2748 | owner: None, |
| 2749 | client_id: None, |
| 2750 | storage_limit_bytes: None, |
| 2751 | }, |
| 2752 | ) |
| 2753 | .await |
| 2754 | .unwrap(); |
| 2755 | } |
| 2756 | |
| 2757 | |
| 2758 | |
| 2759 | if setup.assets { |
| 2760 | let talker = tokio::spawn(async move { |
| 2761 | let (mut sock, _) = listener.accept().await.unwrap(); |
| 2762 | let mut buf = [0u8; 1024]; |
| 2763 | let _ = sock.read(&mut buf).await; |
| 2764 | sock.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 6\r\n\r\nok dev") |
| 2765 | .await |
| 2766 | .unwrap(); |
| 2767 | }); |
| 2768 | let (_, _, body) = get_full(&setup.router, "/", Some(&setup.plain_cookie)).await; |
| 2769 | talker.await.unwrap(); |
| 2770 | assert!(body.contains("service-trio"), "{body}"); |
| 2771 | assert!( |
| 2772 | body.contains(r#"<a class="trio-mark" href="http://127.0.0.1:"#), |
| 2773 | "the marks stay links: {body}" |
| 2774 | ); |
| 2775 | assert!(body.contains("health-dot health-on"), "the ok sibling reads on: {body}"); |
| 2776 | assert!(body.contains(">iz</a>"), "the live sibling renders: {body}"); |
| 2777 | assert!(body.contains("health-dot health-off"), "the dark sibling reads off: {body}"); |
| 2778 | assert!(body.contains(">in</a>"), "the dark sibling renders: {body}"); |
| 2779 | assert!(!body.contains(">im</a>"), "im's own row stays out: {body}"); |
| 2780 | assert!(!body.contains("ok dev"), "the flyout carries dots only: {body}"); |
| 2781 | assert!(!body.contains(" ms</span>"), "the flyout carries no latency: {body}"); |
| 2782 | } |
| 2783 | |
| 2784 | } |
| 2785 | |
| 2786 | |
| 2787 | |
| 2788 | #[tokio::test] |
| 2789 | async fn family_flyout_without_siblings_is_the_bare_mark() { |
| 2790 | let setup = setup().await; |
| 2791 | if setup.assets { |
| 2792 | let (_, _, body) = get_full(&setup.router, "/", Some(&setup.plain_cookie)).await; |
| 2793 | assert!(!body.contains("service-trio"), "{body}"); |
| 2794 | assert!(!body.contains("wordmark-family"), "{body}"); |
| 2795 | assert!(!body.contains("health-dot"), "{body}"); |
| 2796 | assert!(body.contains("wordmark-text"), "the bare mark stays: {body}"); |
| 2797 | } else { |
| 2798 | |
| 2799 | |
| 2800 | |
| 2801 | let marks = crate::layout::trio_marks([( |
| 2802 | "im", |
| 2803 | "http://127.0.0.1:7650", |
| 2804 | Probe::Up { body: "ok dev".into(), ms: 1 }, |
| 2805 | )]); |
| 2806 | assert!(marks.is_empty(), "an im-only family has no flyout: {marks}"); |
| 2807 | } |
| 2808 | } |
| 2809 | |
| 2810 | |
| 2811 | |
| 2812 | |
| 2813 | |
| 2814 | |
| 2815 | |
| 2816 | #[test] |
| 2817 | fn family_flyout_marks_pure_html() { |
| 2818 | let marks = crate::layout::trio_marks([ |
| 2819 | ("iz", "http://127.0.0.1:9001", Probe::Up { body: "ok dev".into(), ms: 12 }), |
| 2820 | ("in", "http://127.0.0.1:9002", Probe::Down), |
| 2821 | |
| 2822 | ("im", "http://127.0.0.1:7650", Probe::Up { body: "ok dev".into(), ms: 1 }), |
| 2823 | ]); |
| 2824 | assert!( |
| 2825 | marks.contains(r#"<a class="trio-mark" href="http://127.0.0.1:9001">"#), |
| 2826 | "the marks stay links: {marks}" |
| 2827 | ); |
| 2828 | assert!(marks.contains("health-dot health-on"), "the ok sibling reads on: {marks}"); |
| 2829 | assert!(marks.contains(">iz</a>"), "the live sibling renders: {marks}"); |
| 2830 | assert!(marks.contains("health-dot health-off"), "the dark sibling reads off: {marks}"); |
| 2831 | assert!(marks.contains(">in</a>"), "the dark sibling renders: {marks}"); |
| 2832 | assert!(!marks.contains(">im</a>"), "im's own row stays out: {marks}"); |
| 2833 | assert!(!marks.contains("ok dev"), "the flyout carries dots only: {marks}"); |
| 2834 | assert!(!marks.contains(" ms</span>"), "the flyout carries no latency: {marks}"); |
| 2835 | assert!( |
| 2836 | marks.contains(r#"<span class="trio-sep">·</span>"#), |
| 2837 | "the marks join on middots: {marks}" |
| 2838 | ); |
| 2839 | } |
| 2840 | } |