//! The web routes and the template environment, shared by the server
//! (`src/main.rs`) and the tests (which drive the real routes).
use std::sync::Arc;
use axum::routing::{get, post};
use axum::Router;
use minijinja::Environment;
use sea_orm::DatabaseConnection;
use crate::{handlers, middleware, AppState, Config};
/// The template environment: the embedded templates, a path loader over
/// them (live reloads in development), and the helpers templates call.
pub fn environment(config: &Config) -> Environment<'static> {
let mut jinja = Environment::new();
minijinja_embed::load_templates!(&mut jinja);
jinja.set_loader(minijinja::path_loader("templates"));
add_helpers(&mut jinja, config.require_email_verification);
// The composers' maxlength (the server refuses longer posts anyway).
jinja.add_global("max_post_chars", config.lameness.max_chars);
jinja
}
/// The functions and globals every template may use.
pub fn add_helpers(jinja: &mut Environment<'static>, require_email_verification: bool) {
// Theme-matched default avatar colors: templates call `avatar_color(name)`
// to pick a DaisyUI semantic color that resolves to the active theme.
jinja.add_function("avatar_color", |name: String| crate::avatar::avatar_color(&name).to_string());
// Unverified accounts read but can't write; templates hide the write
// controls and show the banner only while the gate is on.
jinja.add_global("require_email_verification", require_email_verification);
// Attribute values in <head>: escapes what can break out of a
// double-quoted attribute but leaves `/` alone, which autoescape turns
// into `/` (legal, but many unfurlers hand it back verbatim).
jinja.add_filter("attr", attr_escape);
// The <head> fallback for pages without link-preview metadata.
jinja.add_function("site_description", |app: String| crate::meta::site_description(&app));
jinja.add_function("tier_name", |level: i32| crate::trust::tier_name(level).to_string());
// The silence banner: the message while one is in force, else none.
jinja.add_function("silence_notice", |user: minijinja::Value| -> Option<String> {
let u: crate::entities::users::Model = serde_json::from_value(serde_json::to_value(&user).ok()?).ok()?;
crate::policy::silence(&u).map(|s| crate::policy::silence_message(&s))
});
}
/// Every page and form route, with its authentication.
/// Request headers that must never be logged: the session cookie and API
/// bearer tokens. Marked sensitive, a header's `Debug` prints `Sensitive`, so
/// tower_http's request spans (which list headers) leak nothing at any level.
const SENSITIVE: [axum::http::HeaderName; 3] = [
axum::http::header::COOKIE,
axum::http::header::AUTHORIZATION,
axum::http::header::PROXY_AUTHORIZATION,
];
/// Wrap the trace layer in this (apply it after `TraceLayer`).
pub fn sensitive_request_headers() -> tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer {
tower_http::sensitive_headers::SetSensitiveRequestHeadersLayer::new(SENSITIVE)
}
/// `Set-Cookie` on the way out (a fresh session token at sign-in).
pub fn sensitive_response_headers() -> tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer {
tower_http::sensitive_headers::SetSensitiveResponseHeadersLayer::new([axum::http::header::SET_COOKIE])
}
pub fn router(db: Arc<DatabaseConnection>) -> Router<AppState> {
// Browse routes read `Option<UserContext>` so they work for both anonymous
// visitors and signed-in users.
let public_routes = Router::new()
.route("/", get(handlers::home))
// The landing rows' full feeds; static, so they win over /p/{id}.
.route("/p/latest", get(handlers::feed_latest))
.route("/p/popular", get(handlers::feed_popular))
.route("/c", get(handlers::categories_index))
.route("/c/", get(handlers::categories_index))
.route("/c/{slug}", get(handlers::category_show))
.route("/t/{id}", get(handlers::topic_show))
.route("/p/{id}", get(handlers::post_permalink))
.route("/p/{id}/history", get(handlers::post_history))
.route("/u/{id}/avatar", get(handlers::serve_avatar))
.route("/out", get(handlers::out::out))
.route("/notifications", get(handlers::show_notifications))
.route("/notifications/unread", get(handlers::unread_badge))
.route("/reactions", get(handlers::show_reactions))
.route("/tags", get(handlers::tags_index))
.route("/tag/{slug}", get(handlers::tag_show))
.route("/search", get(handlers::search))
.route("/verify-email", get(handlers::verify_email))
.layer(axum::middleware::from_fn_with_state(
db.clone(),
middleware::optional_auth_middleware,
));
let protected_routes = Router::new()
.route("/profile", get(handlers::show_profile))
.route("/profile/avatar", post(handlers::upload_avatar))
.route("/profile/avatar/delete", post(handlers::delete_avatar))
.route("/bookmarks", get(handlers::show_bookmarks))
.route("/p/{id}/bookmark", post(handlers::toggle_bookmark))
.route("/p/{id}/react/{key}", post(handlers::toggle_react))
.route("/profile/settings", post(handlers::update_settings))
.route("/verify-email/resend", post(handlers::resend_verification))
.route("/notifications/{id}/read", post(handlers::mark_read))
.route("/notifications/read-all", post(handlers::mark_all_read))
.route(
"/admin/reactions",
get(handlers::manage_reactions).post(handlers::create_reaction),
)
.route("/admin/reactions/{id}/delete", post(handlers::delete_reaction))
.route("/admin/reactions/{id}/toggle", post(handlers::toggle_reaction_active))
.route(
"/invites",
get(handlers::show_invites).post(handlers::handle_create_invite),
)
.route("/invites/slot", get(handlers::invite_add_slot))
.route("/invites/inline", post(handlers::create_invite_inline))
// Paired devices (the Android app's tokens); /api-tokens was this page
// before there was an app.
.route("/devices", get(handlers::devices::show_devices).post(handlers::devices::handle_pair))
.route("/devices/{id}/rename", post(handlers::devices::handle_rename))
.route("/devices/{id}/delete", post(handlers::devices::handle_revoke))
.route("/api-tokens", get(handlers::devices::legacy_tokens_page))
// Forum write routes (auth required → redirect to /login when anonymous)
.route("/c/{slug}/new", get(handlers::new_topic_form))
.route("/c/{slug}/topics", post(handlers::create_topic))
.route("/t/{id}/posts", post(handlers::create_post))
// Topic soft-delete / restore (delete: author or staff; restore: staff-only)
.route("/t/{id}/delete", post(handlers::delete_topic))
.route("/t/{id}/restore", post(handlers::restore_topic))
// Topic tag editing (author or staff; minting new tags is trust-gated)
.route("/t/{id}/tags", post(handlers::update_topic_tags))
.route("/c/{slug}/watch", post(handlers::toggle_watch))
// Post edit / soft-delete / restore (author or staff; restore staff-only)
.route("/p/{id}/edit", get(handlers::edit_post_form))
.route("/p/{id}", post(handlers::update_post))
.route("/p/{id}/delete", post(handlers::delete_post))
.route("/p/{id}/restore", post(handlers::restore_post))
// Flags and staff moderation of a post (crate::moderation)
.route("/p/{id}/flag", post(handlers::posts::flag_post))
.route("/p/{id}/moderate", get(handlers::posts::moderate_form).post(handlers::posts::moderate_post))
.route("/p/{id}/moderation/restore", post(handlers::posts::restore_body))
.route("/p/{id}/history/hide", post(handlers::posts::hide_original))
.route("/p/{id}/history/unhide", post(handlers::posts::unhide_original))
// Topic lock and pin (staff)
.route("/t/{id}/lock", post(handlers::forum::lock_topic))
.route("/t/{id}/unlock", post(handlers::forum::unlock_topic))
.route("/t/{id}/pin", post(handlers::forum::pin_topic))
.route("/t/{id}/unpin", post(handlers::forum::unpin_topic))
// Staff: the flag queue, users and sanctions, the moderation log
.route("/admin/flags", get(handlers::moderation::flags_page))
.route("/admin/flags/{post}/dismiss", post(handlers::moderation::flags_dismiss))
.route("/admin/flags/{post}/delete", post(handlers::moderation::flags_delete))
.route("/admin/flags/{post}/moderate", post(handlers::moderation::flags_moderate))
.route("/admin/flags/{post}/lock", post(handlers::moderation::flags_lock))
.route("/admin/users", get(handlers::moderation::users_page))
.route("/admin/users/{id}", get(handlers::moderation::user_page))
.route("/admin/users/{id}/ips", get(handlers::moderation::user_ips))
.route("/admin/ips/{ip}", get(handlers::moderation::ip_page))
.route("/admin/users/{id}/{action}", post(handlers::moderation::user_action))
.route("/admin/log", get(handlers::moderation::log_page))
// Category management (staff only; non-staff get 403 inside the handler)
.route(
"/admin/categories",
get(handlers::manage_categories).post(handlers::create_category),
)
.route("/admin/categories/new", get(handlers::new_category_form))
.route("/admin/categories/slot", get(handlers::category_add_slot))
.route("/admin/categories/inline", post(handlers::create_category_inline))
.route(
"/admin/categories/{id}/edit",
get(handlers::edit_category_form),
)
.route("/admin/categories/{id}", post(handlers::update_category))
.route(
"/admin/categories/{id}/delete",
post(handlers::delete_category),
)
.layer(axum::middleware::from_fn_with_state(
db.clone(),
middleware::web_auth_middleware,
));
Router::new()
.route("/login", get(handlers::show_login))
.route("/register", get(handlers::show_register))
.route("/auth/login", post(handlers::handle_login))
.route("/auth/register", post(handlers::handle_register))
.route("/auth/logout", post(handlers::handle_logout))
.merge(public_routes)
.merge(protected_routes)
}
/// The `attr` filter (movie_monster's): `& < > "` escaped, nothing else.
fn attr_escape(value: String) -> minijinja::Value {
let mut out = String::with_capacity(value.len());
for c in value.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
_ => out.push(c),
}
}
minijinja::Value::from_safe_string(out)
}
#[cfg(test)]
mod attr_tests {
#[test]
fn attributes_keep_their_slashes_but_not_their_quotes() {
let escaped = super::attr_escape(r#"https://x/y?a=1&b=2 "q" <s> it's"#.to_string());
assert_eq!(escaped.as_str().unwrap(), "https://x/y?a=1&b=2 "q" <s> it's");
}
}
#[cfg(test)]
mod sensitive_tests {
use axum::body::Body;
use axum::http::Request;
use tower::{ServiceBuilder, ServiceExt};
#[tokio::test]
async fn session_cookies_and_tokens_are_never_printed() {
let seen = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
let s2 = seen.clone();
let svc = ServiceBuilder::new()
.layer(super::sensitive_response_headers())
.layer(super::sensitive_request_headers())
.service_fn(move |req: Request<Body>| {
let s2 = s2.clone();
async move {
// What a DEBUG span with include_headers(true) prints.
*s2.lock().unwrap() = format!("{:?}", req.headers());
let mut res = axum::http::Response::new(Body::empty());
res.headers_mut().insert("set-cookie", "session_token=fresh; HttpOnly".parse().unwrap());
Ok::<_, std::convert::Infallible>(res)
}
});
let req = Request::builder()
.header("cookie", "session_token=secret-session")
.header("authorization", "Bearer secret-token")
.header("user-agent", "test")
.body(Body::empty())
.unwrap();
let res = svc.oneshot(req).await.unwrap();
let printed = seen.lock().unwrap().clone();
assert!(!printed.contains("secret-session") && !printed.contains("secret-token"), "{printed}");
assert!(printed.contains("Sensitive") && printed.contains("test"));
assert!(!format!("{:?}", res.headers()).contains("fresh"));
// Still delivered to handlers and clients unchanged.
assert_eq!(res.headers()["set-cookie"], "session_token=fresh; HttpOnly");
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
12.9 KiB · text
History
dba9c4f