forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

admin.rs174 lines, 6.8 KiBHistoryRawDownload
1//! Shared pieces of the administrator pages (`/settings`, `/rules`, `/logs`): the viewer for the topbar,
2//! the translation of a store refusal into an alert, the notice codes of the redirects, and the
3//! redirect itself. Each page file does its own gate, load and render.
4//!
5//! A refusal the admin can fix (a bad port, a duplicate name, a too-early message) is shown on the page
6//! with the form's values and status `422`. Anything else goes to the framework's error page.
7
8use serde::Deserialize;
9use topcoat::Result;
10use topcoat::router::error::see_other;
11use topcoat::router::response::Response;
12
13use crate::auth::CurrentMember;
14use crate::i18n::Lang;
15use crate::i18n::admin::{K, fill, t};
16use crate::i18n::structure::{K as StructureK, t as structure_t};
17use crate::pages::task::core_err;
18use crate::state::AppState;
19use crate::views::ViewerInfo;
20use iz_core::store::audit::AuditEntry;
21
22/// The status of a page re-rendered with a refusal.
23pub const REFUSED: topcoat::router::StatusCode = topcoat::router::StatusCode::UNPROCESSABLE_ENTITY;
24
25/// The topbar's view of the signed-in admin.
26pub fn viewer_of(me: &CurrentMember) -> ViewerInfo {
27 ViewerInfo {
28 name: me.member.name.clone(),
29 is_admin: true,
30 csrf: me.session.csrf_token.clone(),
31 }
32}
33
34/// The text of a refusal the admin can act on: the store's own message for `Invalid` and `Conflict`.
35/// Anything else is the framework's error page.
36pub fn user_text(error: iz_core::Error) -> Result<String> {
37 match error {
38 iz_core::Error::Invalid(text) | iz_core::Error::Conflict(text) => Ok(text),
39 other => Err(core_err(other)),
40 }
41}
42
43/// The translated confirmation for a notice code from a redirect's query. `queued` is the number of
44/// messages for `message`. Unknown codes give `None`, so a made-up query shows nothing.
45pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option<String> {
46 let text = match code {
47 "sender" => t(lang, K::NoticeSenderSaved).to_owned(),
48 "checked" => t(lang, K::NoticeCheckOk).to_owned(),
49 "test" => t(lang, K::NoticeTestSent).to_owned(),
50 "reminders" => t(lang, K::NoticeRemindersSaved).to_owned(),
51 "message" => fill(t(lang, K::NoticeMessageQueued), &[queued.unwrap_or("0")]),
52 "rule" => t(lang, K::NoticeRuleSaved).to_owned(),
53 "rule_deleted" => t(lang, K::NoticeRuleDeleted).to_owned(),
54 "rule_switched" => t(lang, K::NoticeRuleSwitched).to_owned(),
55 "retried" => t(lang, K::NoticeRetried).to_owned(),
56 "backup" => t(lang, K::NoticeBackupStarted).to_owned(),
57 "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(),
58 "task_restored" => t(lang, K::NoticeTaskRestored).to_owned(),
59 "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(),
60 "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(),
61 "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => {
62 return crate::pages::tags::tag_notice(lang, code);
63 }
64 "column_added" | "column_renamed" | "column_moved" | "column_retired" => {
65 return crate::pages::columns::column_notice(lang, code);
66 }
67 _ => return None,
68 };
69 Some(text)
70}
71
72/// A redirect (Post/Redirect/Get) to `path`. Returned as the handler's error, like the other pages.
73pub fn back(path: &str) -> Result<Response> {
74 Err(see_other(path).into())
75}
76
77/// A form that carries only the CSRF token: the enable switch, delete, retry and the check buttons.
78#[derive(Debug, Default, Deserialize)]
79#[serde(default)]
80pub struct CsrfForm {
81 /// The session's CSRF token.
82 pub csrf: String,
83}
84
85/// Writes one audit row for an administrator's write that has committed. The caller bumps the live
86/// topic of its section; this only records who did what. Never fails the request.
87pub async fn record(
88 state: &AppState,
89 me: &CurrentMember,
90 action: &'static str,
91 target_kind: &'static str,
92 target_id: Option<&str>,
93 data: serde_json::Value,
94) {
95 state
96 .store
97 .audit(AuditEntry {
98 actor: Some(&me.member.sub),
99 actor_kind: "admin",
100 action,
101 target_kind,
102 target_id,
103 ip: None,
104 data,
105 })
106 .await;
107}
108
109#[cfg(test)]
110mod tests {
111 use http::header::{CONTENT_TYPE, COOKIE};
112 use iz_core::authz::Role;
113 use topcoat::router::{Body, to_bytes};
114
115 use crate::boot::{router, test_state};
116 use crate::pages::board::{cookie_of, sign_in_as};
117
118 /// Sends one request and returns the status code.
119 async fn status_of(state: &crate::state::AppState, request: http::Request<Body>) -> u16 {
120 let response = router(state.clone()).handle(request).await;
121 let status = response.status().as_u16();
122 let _ = to_bytes(response.into_body(), 64 * 1024).await;
123 status
124 }
125
126 /// A member, an anonymous visitor and a wrong-role user all get `404` for admin pages, never `403` or
127 /// a sign-in redirect that would show the page exists.
128 #[tokio::test]
129 async fn an_admin_page_is_a_404_for_members_and_anonymous_visitors() {
130 let (_dir, state) = test_state().await;
131 let (member, _) = sign_in_as(&state, "01MEMBERAAAAAAAAAAAAAAAAA", Role::Member).await;
132 for path in ["/settings", "/tags", "/columns", "/logs", "/rules"] {
133 let as_member = http::Request::get(path)
134 .header(COOKIE, cookie_of(&member))
135 .body(Body::empty())
136 .expect("request");
137 assert_eq!(status_of(&state, as_member).await, 404, "member on {path}");
138 let anonymous = http::Request::get(path)
139 .body(Body::empty())
140 .expect("request");
141 assert_eq!(
142 status_of(&state, anonymous).await,
143 404,
144 "anonymous on {path}"
145 );
146 }
147 }
148
149 /// An administrator's write without the CSRF token is refused with `403` before any side effect.
150 #[tokio::test]
151 async fn an_admin_post_without_csrf_is_refused() {
152 let (_dir, state) = test_state().await;
153 let (token, _csrf) = sign_in_as(&state, "01ADMINAAAAAAAAAAAAAAAAAA", Role::Admin).await;
154 let board = state.store.ensure_board("IZ").await.expect("board");
155 let request = http::Request::post("/tags")
156 .header(COOKIE, cookie_of(&token))
157 .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
158 .body(Body::from("name=Sneaky"))
159 .expect("request");
160 assert_eq!(status_of(&state, request).await, 403);
161 let names: Vec<String> = state
162 .store
163 .tags(&board.id)
164 .await
165 .expect("tags")
166 .into_iter()
167 .map(|tag| tag.name)
168 .collect();
169 assert!(
170 !names.iter().any(|name| name == "Sneaky"),
171 "the write happened"
172 );
173 }
174}