//! Shared pieces of the administrator pages (`/settings`, `/rules`, `/logs`): the viewer for the topbar, //! the translation of a store refusal into an alert, the notice codes of the redirects, and the //! redirect itself. Each page file does its own gate, load and render. //! //! A refusal the admin can fix (a bad port, a duplicate name, a too-early message) is shown on the page //! with the form's values and status `422`. Anything else goes to the framework's error page. use serde::Deserialize; use topcoat::Result; use topcoat::router::error::see_other; use topcoat::router::response::Response; use crate::auth::CurrentMember; use crate::i18n::Lang; use crate::i18n::admin::{K, fill, t}; use crate::i18n::structure::{K as StructureK, t as structure_t}; use crate::pages::task::core_err; use crate::state::AppState; use crate::views::ViewerInfo; use iz_core::store::audit::AuditEntry; /// The status of a page re-rendered with a refusal. pub const REFUSED: topcoat::router::StatusCode = topcoat::router::StatusCode::UNPROCESSABLE_ENTITY; /// The topbar's view of the signed-in admin. pub fn viewer_of(me: &CurrentMember) -> ViewerInfo { ViewerInfo { name: me.member.name.clone(), is_admin: true, csrf: me.session.csrf_token.clone(), } } /// The text of a refusal the admin can act on: the store's own message for `Invalid` and `Conflict`. /// Anything else is the framework's error page. pub fn user_text(error: iz_core::Error) -> Result { match error { iz_core::Error::Invalid(text) | iz_core::Error::Conflict(text) => Ok(text), other => Err(core_err(other)), } } /// The translated confirmation for a notice code from a redirect's query. `queued` is the number of /// messages for `message`. Unknown codes give `None`, so a made-up query shows nothing. pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option { let text = match code { "sender" => t(lang, K::NoticeSenderSaved).to_owned(), "checked" => t(lang, K::NoticeCheckOk).to_owned(), "test" => t(lang, K::NoticeTestSent).to_owned(), "reminders" => t(lang, K::NoticeRemindersSaved).to_owned(), "message" => fill(t(lang, K::NoticeMessageQueued), &[queued.unwrap_or("0")]), "rule" => t(lang, K::NoticeRuleSaved).to_owned(), "rule_deleted" => t(lang, K::NoticeRuleDeleted).to_owned(), "rule_switched" => t(lang, K::NoticeRuleSwitched).to_owned(), "retried" => t(lang, K::NoticeRetried).to_owned(), "backup" => t(lang, K::NoticeBackupStarted).to_owned(), "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(), "task_restored" => t(lang, K::NoticeTaskRestored).to_owned(), "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(), "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(), "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => { return crate::pages::tags::tag_notice(lang, code); } "column_added" | "column_renamed" | "column_moved" | "column_retired" => { return crate::pages::columns::column_notice(lang, code); } _ => return None, }; Some(text) } /// A redirect (Post/Redirect/Get) to `path`. Returned as the handler's error, like the other pages. pub fn back(path: &str) -> Result { Err(see_other(path).into()) } /// A form that carries only the CSRF token: the enable switch, delete, retry and the check buttons. #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct CsrfForm { /// The session's CSRF token. pub csrf: String, } /// Writes one audit row for an administrator's write that has committed. The caller bumps the live /// topic of its section; this only records who did what. Never fails the request. pub async fn record( state: &AppState, me: &CurrentMember, action: &'static str, target_kind: &'static str, target_id: Option<&str>, data: serde_json::Value, ) { state .store .audit(AuditEntry { actor: Some(&me.member.sub), actor_kind: "admin", action, target_kind, target_id, ip: None, data, }) .await; } #[cfg(test)] mod tests { use http::header::{CONTENT_TYPE, COOKIE}; use iz_core::authz::Role; use topcoat::router::{Body, to_bytes}; use crate::boot::{router, test_state}; use crate::pages::board::{cookie_of, sign_in_as}; /// Sends one request and returns the status code. async fn status_of(state: &crate::state::AppState, request: http::Request) -> u16 { let response = router(state.clone()).handle(request).await; let status = response.status().as_u16(); let _ = to_bytes(response.into_body(), 64 * 1024).await; status } /// A member, an anonymous visitor and a wrong-role user all get `404` for admin pages, never `403` or /// a sign-in redirect that would show the page exists. #[tokio::test] async fn an_admin_page_is_a_404_for_members_and_anonymous_visitors() { let (_dir, state) = test_state().await; let (member, _) = sign_in_as(&state, "01MEMBERAAAAAAAAAAAAAAAAA", Role::Member).await; for path in ["/settings", "/tags", "/columns", "/logs", "/rules"] { let as_member = http::Request::get(path) .header(COOKIE, cookie_of(&member)) .body(Body::empty()) .expect("request"); assert_eq!(status_of(&state, as_member).await, 404, "member on {path}"); let anonymous = http::Request::get(path) .body(Body::empty()) .expect("request"); assert_eq!( status_of(&state, anonymous).await, 404, "anonymous on {path}" ); } } /// An administrator's write without the CSRF token is refused with `403` before any side effect. #[tokio::test] async fn an_admin_post_without_csrf_is_refused() { let (_dir, state) = test_state().await; let (token, _csrf) = sign_in_as(&state, "01ADMINAAAAAAAAAAAAAAAAAA", Role::Admin).await; let board = state.store.ensure_board("IZ").await.expect("board"); let request = http::Request::post("/tags") .header(COOKIE, cookie_of(&token)) .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body(Body::from("name=Sneaky")) .expect("request"); assert_eq!(status_of(&state, request).await, 403); let names: Vec = state .store .tags(&board.id) .await .expect("tags") .into_iter() .map(|tag| tag.name) .collect(); assert!( !names.iter().any(|name| name == "Sneaky"), "the write happened" ); } }