OXYGENHUB

Coverage / crates/hub/src/web/mod.rs 90.5%

659 of 728 lines run, 152 of 335 functions · run #543 on main · run missed

1
//! Pages (hub spec §6): the router, the shell every template extends, the
2
//! error page, viewer-aware lookups and askama filters. Handlers are thin:
3
//! they resolve names, call the view layer under the repository lock, and
4
//! render.
5
6
mod admin;
7
mod artifacts;
8
pub(crate) mod assistants;
9
mod avatar;
10
pub(crate) mod backups;
11
pub mod board_charts;
12
pub mod chain;
13
pub mod charts;
14
pub mod coverage;
15
mod device;
16
mod diffusion;
17
mod drops;
18
pub mod edit;
19
pub mod filters;
20
pub mod flow;
21
mod forks;
22
pub mod help;
23
pub mod history;
24
pub mod home;
25
pub mod icons;
26
mod insights;
27
mod live_stream;
28
mod security_txt;
29
mod transparency;
30
31
/// A state as people read it (oxygenhub#170): `02a6c9d4746a+… (14 heads)`
32
/// for heads joined by `+`, which can run to hundreds of characters; a
33
/// single head, or text that is not heads, unchanged.
3437×
pub fn state_label(text: &str) -> String {
3537×
    let parts: Vec<&str> = text.split('+').collect();
36756×
    let heads = parts.len() > 1 && parts.iter().all(|p| p.len() >= 7 && p.chars().all(|c| c.is_ascii_hexdigit()));
3737×
    if !heads {
3820×
        return text.to_string();
3917×
    }
4017×
    format!("{}+… ({} heads)", &parts[0][..12.min(parts[0].len())], parts.len())
4137×
}
42
mod inbox;
43
pub mod issues;
44
mod orgs;
45
pub mod projects;
46
pub mod proposals;
47
mod recovery;
48
mod refs;
49
pub mod release_trust;
50
pub mod releases;
51
mod repo;
52
mod repo_settings;
53
pub mod reports;
54
mod resolve;
55
pub mod runner_updates;
56
pub mod runners;
57
mod secrets;
58
mod session;
59
pub(crate) mod settings;
60
mod signin;
61
mod statics;
62
mod sudo;
63
pub mod test_reports;
64
mod variables;
65
mod webhooks;
66
mod wiki;
67
68
use crate::auth::{self, Access, Role, Viewer};
69
use crate::repos::RepoError;
70
use crate::{db, Shared};
71
use askama::Template;
72
use axum::extract::DefaultBodyLimit;
73
use axum::http::{header, StatusCode};
74
use axum::response::{Html, IntoResponse, Redirect, Response};
75
use axum::routing::{any, get, post};
76
use axum::Router;
77
use tower_http::compression::CompressionLayer;
78
use tower_http::trace::TraceLayer;
79
802935×
pub fn router(app: Shared) -> Router {
812935×
    let push_limit = app.config.limits.push_body_limit.0 as usize;
822935×
    Router::new()
832935×
        .route("/", get(home::index))
842935×
        .route("/explore", get(home::explore))
852935×
        .route("/avatar/agent/{name}", get(avatar::agent))
862935×
        .route("/avatar/{name}", get(avatar::avatar))
872935×
        .route("/health", get(home::health))
882935×
        .route("/about", get(home::about))
892935×
        .route("/.well-known/oxyhub-key", get(home::hub_key))
902935×
        .route("/.well-known/assetlinks.json", get(home::assetlinks))
912935×
        .route("/metrics", get(crate::metrics::metrics))
922935×
        .route("/log", get(transparency::page))
932935×
        .route("/log/checkpoint", get(crate::tlog::checkpoint))
942935×
        .route("/log/witnesses", get(crate::tlog::witnesses))
952935×
        .route("/log/tile/{*path}", get(crate::tlog::tile))
962935×
        .route("/log/witness/add-checkpoint", axum::routing::post(crate::tlog::add_checkpoint))
972935×
        .route("/.well-known/oxyhub-ca.pem", get(home::hub_ca))
982935×
        .route("/.well-known/oxyhub-signing.pem", get(flow::signing_key))
992935×
        .route("/.well-known/openid-configuration", get(crate::oidc::discovery))
1002935×
        .route("/.well-known/jwks.json", get(crate::oidc::jwks))
1012935×
        .route("/live", get(live_stream::stream))
1022935×
        .route("/.well-known/security.txt", get(security_txt::serve))
1032935×
        .route("/security.txt", get(security_txt::serve))
1042935×
        .route("/security-contact", get(security_txt::contact_page))
1052935×
        .route("/style.css", get(statics::style))
1062935×
        .route("/favicon.svg", get(statics::favicon))
1072935×
        .route("/favicon.ico", get(statics::favicon))
1082935×
        .route("/static/{*path}", get(statics::asset))
1092935×
        .route("/login", get(session::login_form).post(session::login))
1102935×
        .route("/login/approval", post(session::approval_state))
1112935×
        .route("/sudo", get(sudo::show).post(sudo::confirm))
1122935×
        .route("/sudo/phone", post(sudo::ask_phone))
1132935×
        .route("/sudo/approval/{id}", get(sudo::approval_state))
1142935×
        .route("/device", get(device::form).post(device::answer))
1152935×
        .route(crate::headers::REPORT_PATH, post(crate::headers::csp_report).layer(DefaultBodyLimit::max(16 * 1024)))
1162935×
        .route("/logout", post(session::logout))
1172935×
        .route("/register", get(session::register_form).post(session::register))
1182935×
        .route("/settings", get(settings::profile).post(settings::update_profile))
1192935×
        .route("/settings/password", post(settings::change_password))
1202935×
        .route("/settings/appearance", post(settings::appearance))
1212935×
        .route("/settings/security", get(settings::security))
1222935×
        .route("/settings/security/totp/begin", post(settings::totp_begin))
1232935×
        .route("/settings/security/totp/enable", post(settings::totp_enable))
1242935×
        .route("/settings/security/totp/disable", post(settings::totp_disable))
1252935×
        .route("/settings/security/sessions", post(settings::sessions_reset))
1262935×
        .route("/settings/security/sessions/{id}/end", post(settings::session_end))
1272935×
        .route("/settings/security/phones/{id}/remove", post(settings::phone_remove))
1282935×
        .route("/settings/keys", get(settings::keys))
1292935×
        .route("/settings/keys/upload", post(settings::keys_upload))
1302935×
        .route("/settings/keys/verify", post(settings::keys_verify))
1312935×
        .route("/settings/keys/unlink", post(settings::keys_unlink))
1322935×
        .route("/settings/tokens", get(settings::tokens).post(settings::tokens_create))
1332935×
        .route("/sky/arrivals", get(home::arrivals))
1342935×
        .route("/settings/backups", get(backups::user).post(backups::user_save))
1352935×
        .route("/settings/backups/run", post(backups::user_run))
1362935×
        .route("/settings/backups/test", post(backups::user_test))
1372935×
        .route("/orgs/{name}/settings/backups", get(backups::org).post(backups::org_save))
1382935×
        .route("/orgs/{name}/settings/backups/run", post(backups::org_run))
1392935×
        .route("/orgs/{name}/settings/backups/test", post(backups::org_test))
1402935×
        .route("/settings/tokens/{id}/delete", post(settings::tokens_delete))
1412935×
        .route("/settings/tokens/{id}/agent", post(settings::tokens_agent))
1422935×
        .route("/new", get(repo_settings::new_form).post(repo_settings::create))
1432935×
        .route("/new/check", get(repo_settings::check_name))
1442935×
        .route("/orgs/new", get(orgs::new_form).post(orgs::create))
1452935×
        .route("/orgs/{name}/settings", get(orgs::settings).post(orgs::update))
1462935×
        .route("/orgs/{name}/settings/members", post(orgs::member))
1472935×
        .route("/orgs/{name}/settings/teams", post(orgs::team))
1482935×
        .route("/orgs/{name}/settings/hooks", post(orgs::hooks))
1492935×
        .route("/orgs/{name}/settings/assistants", post(orgs::assistants))
1502935×
        .route("/orgs/{name}/settings/assistants/models", post(orgs::assistant_models))
1512935×
        .route("/orgs/{name}/settings/variables", post(orgs::variables))
1522935×
        .route("/orgs/{name}/settings/secrets", post(orgs::secrets))
1532935×
        .route("/orgs/{name}/settings/storage", post(orgs::storage))
1542935×
        .route("/orgs/{name}/settings/flow-priority", post(orgs::flow_priority))
1552935×
        .route("/orgs/{name}/settings/runners/token", post(orgs::runner_token))
1562935×
        .route("/orgs/{name}/settings/runners/{id}/remove", post(orgs::runner_remove))
1572935×
        .route("/orgs/{name}/settings/runners/updates/policy", post(orgs::runner_updates_policy))
1582935×
        .route("/orgs/{name}/settings/runners/updates/groups", post(orgs::runner_updates_group_new))
1592935×
        .route("/orgs/{name}/settings/runners/updates/groups/{id}", post(orgs::runner_updates_group))
1602935×
        .route("/orgs/{name}/settings/runners/updates/groups/{id}/delete", post(orgs::runner_updates_group_delete))
1612935×
        .route("/orgs/{name}/settings/hooks/{id}/deliveries", get(orgs::deliveries))
1622935×
        .route("/orgs/{name}/settings/hooks/{id}/redeliver/{delivery}", post(orgs::redeliver))
1632935×
        .route("/orgs/{name}/settings/avatar", post(orgs::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10))))
1642935×
        .route("/settings/avatar", post(settings::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10))))
1652935×
        .route("/notifications", get(inbox::inbox))
1662935×
        .route("/notifications/read", post(inbox::mark_read))
1672935×
        .route("/settings/notifications", get(inbox::unsubscribe).post(inbox::prefs))
1682935×
        .route("/search", get(inbox::search))
1692935×
        .route("/admin", get(admin::index))
1702935×
        .route("/admin/accounts", get(admin::section))
1712935×
        .route("/admin/organisations", get(admin::section))
1722935×
        .route("/admin/audit", get(admin::section))
1732935×
        .route("/admin/registration", get(admin::section).post(admin::set_mode))
1742935×
        .route("/admin/invite", post(admin::invite))
1752935×
        .route("/admin/account", post(admin::account))
1762935×
        .route("/admin/storage", get(admin::storage).post(admin::maintain))
1772935×
        .route("/admin/runners", get(runners::list))
1782935×
        .route("/admin/runners/settings", get(runners::settings).post(runners::save_settings))
1792935×
        .route("/admin/runners/priority", post(runners::save_priority))
1802935×
        .route("/admin/runners/images", get(runners::images))
1812935×
        .route("/admin/runners/updates", get(runner_updates::show))
1822935×
        .route("/admin/runners/updates/source", post(runner_updates::save_source))
1832935×
        .route("/admin/runners/updates/policy", post(runner_updates::save_policy))
1842935×
        .route("/admin/runners/updates/groups", post(runner_updates::create_group))
1852935×
        .route("/admin/runners/updates/holds/lift", post(runner_updates::lift_hold))
1862935×
        .route("/admin/runners/updates/groups/{id}", post(runner_updates::save_group))
1872935×
        .route("/admin/runners/updates/groups/{id}/delete", post(runner_updates::delete_group))
1882935×
        .route("/admin/insights", get(insights::site))
1892935×
        .route("/insights/{owner}", get(insights::owner))
1902935×
        .route("/admin/diffusion", get(diffusion::admin))
1912935×
        .route("/admin/backups", get(backups::admin))
1922935×
        .route("/{owner}/{name}/diffusion", get(diffusion::page))
1932935×
        .route("/admin/runners/token", post(runners::new_token))
1942935×
        .route("/admin/runners/{id}", get(runners::show))
1952935×
        .route("/admin/runners/{id}/state", post(runners::set_state))
1962935×
        .route("/admin/runners/{id}/scope", post(runners::set_scope))
1972935×
        .route("/admin/runners/{id}/limits", post(runners::set_limits))
1982935×
        .route("/admin/mail", get(admin::section).post(admin::set_mail))
1992935×
        .route("/admin/mail/test", post(admin::test_mail))
2002935×
        .route("/admin/assistants", get(admin::section).post(admin::assistants))
2012935×
        .route("/admin/assistants/models", post(admin::assistant_models))
2022935×
        .route("/admin/signin", get(admin::section).post(admin::signin))
2032935×
        .route("/admin/security", get(admin::section).post(security_txt::save))
2042935×
        .route("/login/{provider}", get(signin::start))
2052935×
        .route("/login/{provider}/callback", get(signin::callback))
2062935×
        .route("/settings/security/connect/{provider}", get(signin::connect))
2072935×
        .route("/settings/security/disconnect/{provider}", post(signin::disconnect))
2082935×
        .route("/admin/variables", get(admin::section).post(admin::variables))
2092935×
        .route("/admin/secrets", get(admin::section).post(admin::secrets))
2102935×
        .route("/admin/runners/{id}/remove", post(runners::remove))
2112935×
        .nest("/api/v1", crate::api::router(app.config.limits.asset_limit.0 as usize))
212
        // Drops (#279): `drops` is reserved, as an owner and as a repository name.
2132935×
        .route("/drops", get(drops::mine))
2142935×
        .route("/drops/new", get(drops::new_form).post(drops::create))
2152935×
        .route("/{owner}/drops", get(drops::list))
2162935×
        .route("/{owner}/drops/{id}", get(drops::show))
2172935×
        .route("/{owner}/drops/{id}/tree/{r}", get(drops::show_at))
2182935×
        .route("/{owner}/drops/{id}/edit", get(drops::edit_form).post(drops::save))
2192935×
        .route("/{owner}/drops/{id}/delete", post(drops::delete))
2202935×
        .route("/{owner}/drops/{id}/fork", post(drops::fork))
2212935×
        .route("/{owner}/drops/{id}/star", post(drops::star))
2222935×
        .route("/{owner}/drops/{id}/embed", get(drops::embed))
2232935×
        .route("/{owner}/drops/{id}/comment", post(drops::comment))
2242935×
        .route("/{owner}/drops/{id}/comment/{n}/delete", post(drops::delete_comment))
2252935×
        .route("/{owner}/drops/{id}/changes/{r}", get(drops::changes))
2262935×
        .route("/{owner}/drops/{id}/change/{hash}", get(drops::change))
2272935×
        .route("/{owner}/drops/{id}/raw/{r}/{*path}", get(drops::raw))
2282935×
        .route("/{owner}/drops/{id}/file/{r}/{*path}", get(drops::file))
2292935×
        .route("/{owner}/drops/{id}/oxy/v1/{endpoint}", any(crate::protocol::dispatch_drop).layer(DefaultBodyLimit::max(push_limit)))
2302935×
        .route("/{owner}", get(home::owner))
2312935×
        .route("/{owner}/{name}", get(repo::overview))
2322935×
        .route("/{owner}/{name}/tree/{r}", get(repo::tree_root))
2332935×
        .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree))
2342935×
        .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file))
2352935×
        .route("/{owner}/{name}/function/{r}/{*path}", get(history::function))
2362935×
        .route("/{owner}/{name}/lanes/{r}", get(history::lanes))
2372935×
        .route("/{owner}/{name}/lanes/{r}/plan", post(history::plan))
2382935×
        .route("/{owner}/{name}/raw/{r}/{*path}", get(repo::raw_file))
2392935×
        .route("/{owner}/{name}/last/{r}", get(repo::last_changes))
2402935×
        .route("/{owner}/{name}/changes/{r}", get(history::history))
2412935×
        .route("/{owner}/{name}/change/{hash}", get(history::change))
2422935×
        .route("/apt", get(crate::apt::home))
2432935×
        .route("/apt/{file}", get(crate::apt::key))
2442935×
        .route("/apt/dists/{suite}/{*rest}", get(crate::apt::dists))
2452935×
        .route("/apt/pool/{*path}", get(crate::apt::pool))
2462935×
        .route("/help", get(help::help))
2472935×
        .route("/projects/{owner}", get(projects::list).post(projects::create))
2482935×
        .route("/projects/{owner}/{number}", get(projects::show).post(projects::act))
2492935×
        .route("/projects/{owner}/{number}/charts", get(board_charts::show))
2502935×
        .route("/notifications/thread", post(inbox::thread))
2512935×
        .route("/notifications/open/{id}", get(inbox::open))
2522935×
        .route("/login/reset", get(recovery::request_form).post(recovery::request))
2532935×
        .route("/login/reset/{secret}", get(recovery::new_password_form).post(recovery::set_new_password))
2542935×
        .route("/verify/{secret}", get(recovery::verify))
2552935×
        .route("/settings/email/verify", post(settings::resend_verification))
2562935×
        .route("/{owner}/{name}/compare", get(history::compare_index))
2572935×
        .route("/{owner}/{name}/compare/{spec}", get(history::compare))
2582935×
        .route("/{owner}/{name}/bookmarks", get(refs::bookmarks))
2592935×
        .route("/{owner}/{name}/bookmarks/delete", post(refs::delete_bookmark))
2602935×
        .route("/{owner}/{name}/bookmarks/create", post(refs::create_bookmark))
2612935×
        .route("/{owner}/{name}/tags", get(refs::tags))
2622935×
        .route("/{owner}/{name}/tags/create", post(refs::create_tag))
2632935×
        .route("/{owner}/{name}/tags/withdraw", post(refs::withdraw_tag))
2642935×
        .route("/{owner}/{name}/artifacts", get(artifacts::artifacts))
2652935×
        .route("/{owner}/{name}/images", get(artifacts::images))
2662935×
        .route("/{owner}/{name}/terraform", get(artifacts::terraform))
2672935×
        .route("/{owner}/{name}/insights", get(insights::repo))
2682935×
        .route("/{owner}/{name}/terraform/{state}/download", get(artifacts::download))
2692935×
        .route("/{owner}/{name}/terraform/{state}/restore", post(artifacts::restore))
2702935×
        .route("/{owner}/{name}/conflicts", get(refs::conflicts))
2712935×
        .route("/{owner}/{name}/trust", get(refs::trust))
2722935×
        .route("/{owner}/{name}/pushes", get(refs::pushes))
2732935×
        .route("/{owner}/{name}/fork", get(forks::form).post(forks::create))
2742935×
        .route("/{owner}/{name}/forks", get(forks::list))
2752935×
        .route("/{owner}/{name}/settings", get(repo_settings::settings).post(repo_settings::update))
276
        // One page per setting (#278); some share their form's path.
2772935×
        .route("/{owner}/{name}/settings/{page}", get(repo_settings::page))
2782935×
        .route("/{owner}/{name}/settings/collaborators", get(repo_settings::page).post(repo_settings::collaborator))
2792935×
        .route("/{owner}/{name}/settings/delete", post(repo_settings::delete))
2802935×
        .route("/{owner}/{name}/settings/transfer", post(repo_settings::transfer))
2812935×
        .route("/{owner}/{name}/settings/archive", post(repo_settings::archive))
2822935×
        .route("/{owner}/{name}/settings/wiki/delete", post(repo_settings::wiki_delete))
2832935×
        .route("/{owner}/{name}/wiki", get(wiki::home))
2842935×
        .route("/{owner}/{name}/wiki/_pages", get(wiki::pages))
2852935×
        .route("/{owner}/{name}/wiki/_new", get(wiki::new_form))
2862935×
        .route("/{owner}/{name}/wiki/_raw/{*path}", get(wiki::raw))
2872935×
        .route("/{owner}/{name}/wiki/{slug}", get(wiki::show))
2882935×
        .route("/{owner}/{name}/wiki/{slug}/edit", get(wiki::edit_form).post(wiki::save))
2892935×
        .route("/{owner}/{name}/wiki/{slug}/history", get(wiki::history))
2902935×
        .route("/{owner}/{name}/wiki/{slug}/delete", post(wiki::delete))
2912935×
        .route("/{owner}/{name}/settings/requirements", post(repo_settings::requirements))
2922935×
        .route("/{owner}/{name}/proposals", get(proposals::list))
2932935×
        .route("/{owner}/{name}/proposals/new", get(proposals::new_form).post(proposals::create))
2942935×
        .route("/{owner}/{name}/proposals/new/draft", post(proposals::new_draft))
2952935×
        .route("/{owner}/{name}/proposals/new/draft/stream", post(proposals::new_draft_stream))
2962935×
        .route("/{owner}/{name}/proposal/{number}", get(proposals::show))
2972935×
        .route("/{owner}/{name}/proposal/{number}/comment", post(proposals::comment))
2982935×
        .route("/{owner}/{name}/proposal/{number}/comment/{id}/resolve", post(proposals::resolve_comment))
2992935×
        .route("/{owner}/{name}/proposal/{number}/resolve", post(proposals::resolve_on_web))
3002935×
        .route("/{owner}/{name}/proposal/{number}/review", post(proposals::review))
3012935×
        .route("/{owner}/{name}/proposal/{number}/reviewers", post(proposals::reviewers))
3022935×
        .route("/{owner}/{name}/proposal/{number}/assistant", post(proposals::assistant))
3032935×
        .route("/{owner}/{name}/proposal/{number}/draft", post(proposals::draft))
3042935×
        .route("/{owner}/{name}/proposal/{number}/draft/stream", post(proposals::draft_stream))
3052935×
        .route("/{owner}/{name}/proposal/{number}/edit", post(proposals::edit))
3062935×
        .route("/{owner}/{name}/proposal/{number}/state", post(proposals::state))
3072935×
        .route("/{owner}/{name}/proposal/{number}/land", post(proposals::land))
3082935×
        .route("/{owner}/{name}/proposal/{number}/auto-land", post(proposals::auto_land))
3092935×
        .route("/{owner}/{name}/proposal/{number}/labels", post(proposals::set_labels))
3102935×
        .route("/{owner}/{name}/proposal/{number}/project", post(projects::place_proposal))
3112935×
        .route("/{owner}/{name}/issue/{number}/project", post(projects::place_issue))
3122935×
        .route("/{owner}/{name}/proposal/{number}/events", get(proposals::events))
3132935×
        .route("/{owner}/{name}/settings/hooks", post(repo_settings::hooks))
3142935×
        .route("/{owner}/{name}/settings/assistants", get(repo_settings::page).post(repo_settings::assistants))
3152935×
        .route("/{owner}/{name}/settings/assistants/models", post(repo_settings::assistant_models))
3162935×
        .route("/{owner}/{name}/settings/variables", get(repo_settings::page).post(repo_settings::variables))
3172935×
        .route("/{owner}/{name}/settings/secrets", get(repo_settings::page).post(repo_settings::secrets))
3182935×
        .route("/{owner}/{name}/settings/hooks/{id}/deliveries", get(repo_settings::deliveries))
3192935×
        .route("/{owner}/{name}/settings/hooks/{id}/redeliver/{delivery}", post(repo_settings::redeliver))
3202935×
        .route("/{owner}/{name}/settings/checks", get(repo_settings::page).post(repo_settings::required_checks))
3212935×
        .route("/{owner}/{name}/watch", post(issues::watch))
3222935×
        .route("/{owner}/{name}/star", post(issues::star))
3232935×
        .route("/{owner}/{name}/edit/{r}", post(edit::save))
3242935×
        .route("/{owner}/{name}/edit/{r}/{*path}", get(edit::edit_form))
3252935×
        .route("/{owner}/{name}/resolve/{bookmark}/{*path}", get(resolve::form).post(resolve::save))
3262935×
        .route("/{owner}/{name}/resolve-live/{bookmark}/{*path}", get(resolve::live_events).post(resolve::live_choose))
3272935×
        .route("/{owner}/{name}/newfile/{r}", get(edit::new_form))
3282935×
        .route("/{owner}/{name}/flow", get(flow::runs))
3292935×
        .route("/{owner}/{name}/flow/badge.svg", get(flow::badge))
3302935×
        .route("/{owner}/{name}/flow/tab", get(flow::tab))
3312935×
        .route("/{owner}/{name}/tests", get(test_reports::overview))
3322935×
        .route("/{owner}/{name}/tests/case", get(test_reports::case))
3332935×
        .route("/{owner}/{name}/reports", get(reports::overview))
3342935×
        .route("/{owner}/{name}/reports/files/{id}/{mac}/{*path}", get(reports::file))
3352935×
        .route("/{owner}/{name}/reports/{report}", get(reports::show))
3362935×
        .route("/{owner}/{name}/coverage", get(coverage::overview))
3372935×
        .route("/{owner}/{name}/coverage/badge.svg", get(coverage::badge))
3382935×
        .route("/{owner}/{name}/coverage/{id}/file/{*path}", get(coverage::file))
3392935×
        .route("/{owner}/{name}/deployments", get(flow::deployments))
3402935×
        .route("/{owner}/{name}/flow/{id}", get(flow::run))
3412935×
        .route("/{owner}/{name}/flow/{id}/live", get(flow::live))
3422935×
        .route("/{owner}/{name}/flow/start", post(flow::start))
3432935×
        .route("/{owner}/{name}/flow/{id}/rerun", post(flow::rerun))
3442935×
        .route("/{owner}/{name}/flow/{id}/jobs/{job}/rerun", post(flow::rerun_job))
3452935×
        .route("/{owner}/{name}/flow/{id}/jobs/{job}/decide", post(flow::decide))
3462935×
        .route("/{owner}/{name}/flow/{id}/cancel", post(flow::cancel))
3472935×
        .route("/{owner}/{name}/flow/{id}/expedite", post(flow::expedite))
3482935×
        .route("/{owner}/{name}/flow/stamp/{r}", get(flow::stamp))
3492935×
        .route("/{owner}/{name}/flow/at/{r}", get(flow::at))
3502935×
        .route("/{owner}/{name}/receipts/{attest}", get(flow::receipt_file))
3512935×
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}", get(flow::artifact_file))
3522935×
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/attach", post(flow::attach))
3532935×
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/provenance", get(flow::provenance))
3542935×
        .route("/{owner}/{name}/releases", get(releases::list))
3552935×
        .route("/{owner}/{name}/releases/new", get(releases::new_form).post(releases::create))
3562935×
        .route("/{owner}/{name}/releases/tag/{*tag}", get(releases::show))
3572935×
        .route("/{owner}/{name}/releases/download/{tag}/{file}", get(releases::download_by_tag))
3582935×
        .route("/{owner}/{name}/releases/trust/{*tag}", get(release_trust::page))
3592935×
        .route("/{owner}/{name}/releases/edit/{id}", post(releases::edit))
3602935×
        .route(
3612935×
            "/{owner}/{name}/releases/upload/{id}",
3622935×
            post(releases::upload).layer(DefaultBodyLimit::max(app.config.limits.asset_limit.0 as usize + (1 << 20))),
363
        )
3642935×
        .route("/{owner}/{name}/asset/{id}/{file}", get(releases::download))
3652935×
        .route("/{owner}/{name}/attachments/{id}/{file}", get(releases::attachment))
3662935×
        .route("/{owner}/{name}/archive", get(releases::source_archive))
3672935×
        .route("/{owner}/{name}/search", get(repo::code_search))
3682935×
        .route("/{owner}/{name}/info/{*rest}", any(git_info))
3692935×
        .route("/{owner}/{name}/HEAD", get(git_head))
3702935×
        .route("/{owner}/{name}/objects/{*rest}", get(git_objects))
3712935×
        .route("/{owner}/{name}/git-upload-pack", post(git_upload_pack))
3722935×
        .route("/{owner}/{name}/git-receive-pack", post(git_receive_pack))
3732935×
        .route("/{owner}/{name}/settings/mirror", post(repo_settings::mirror))
3742935×
        .route("/{owner}/{name}/settings/flow", get(repo_settings::page).post(repo_settings::flow))
3752935×
        .route("/{owner}/{name}/settings/flow-priority", post(repo_settings::flow_priority))
3762935×
        .route("/{owner}/{name}/settings/agent-gates", post(repo_settings::agent_gates))
3772935×
        .route("/{owner}/{name}/settings/push-protection", get(repo_settings::page).post(repo_settings::push_protection))
3782935×
        .route("/{owner}/{name}/settings/secret-bypass", post(repo_settings::secret_bypass))
3792935×
        .route("/{owner}/{name}/settings/secret-bypass/remove", post(repo_settings::secret_bypass_remove))
3802935×
        .route("/{owner}/{name}/settings/secret-resolve", post(repo_settings::secret_resolve))
3812935×
        .route("/{owner}/{name}/settings/secret-scan", post(repo_settings::secret_scan))
3822935×
        .route("/{owner}/{name}/settings/flow-supersede", post(repo_settings::flow_supersede))
3832935×
        .route("/{owner}/{name}/settings/flow-skip", post(repo_settings::flow_skip))
3842935×
        .route("/{owner}/{name}/settings/flow-reuse", post(repo_settings::flow_reuse))
3852935×
        .route("/{owner}/{name}/settings/diffusion", get(repo_settings::page).post(repo_settings::diffusion))
3862935×
        .route("/{owner}/{name}/settings/backup", get(repo_settings::page).post(repo_settings::backup))
3872935×
        .route("/{owner}/{name}/settings/storage", get(repo_settings::page).post(repo_settings::storage))
3882935×
        .route("/{owner}/{name}/settings/coverage", get(repo_settings::page).post(repo_settings::coverage))
3892935×
        .route("/{owner}/{name}/settings/runners/token", post(repo_settings::runner_token))
3902935×
        .route("/{owner}/{name}/settings/runners/{id}/remove", post(repo_settings::runner_remove))
3912935×
        .route("/{owner}/{name}/issues", get(issues::list))
3922935×
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
3932935×
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
3942935×
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
3952935×
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
3962935×
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
3972935×
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
3982935×
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
3992935×
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
4002935×
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
4012935×
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
4022935×
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
4032935×
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
4042935×
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
4052935×
        .fallback(not_found)
4062935×
        .layer(axum::middleware::from_fn_with_state(app.clone(), sudo::gate))
4072935×
        .layer(axum::middleware::from_fn_with_state(app.clone(), rejections_as_pages))
4082935×
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
4092935×
        .layer(CompressionLayer::new())
4102935×
        .layer(TraceLayer::new_for_http())
4112935×
        .with_state(app)
4122935×
}
413
414
// Git's smart HTTP paths under `/{owner}/{name}.git/`, forwarded to the
415
// mirror (hub spec §14).
4165×
async fn git_info(
4175×
    st: axum::extract::State<Shared>,
4185×
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
4195×
    m: axum::http::Method,
4205×
    q: axum::extract::RawQuery,
4215×
    h: axum::http::HeaderMap,
4225×
    b: axum::body::Bytes,
4235×
) -> Response {
4245×
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await
4255×
}
426
4270×
async fn git_head(
4280×
    st: axum::extract::State<Shared>,
4290×
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
4300×
    m: axum::http::Method,
4310×
    q: axum::extract::RawQuery,
4320×
    h: axum::http::HeaderMap,
4330×
    b: axum::body::Bytes,
4340×
) -> Response {
4350×
    crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await
4360×
}
437
4380×
async fn git_objects(
4390×
    st: axum::extract::State<Shared>,
4400×
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
4410×
    m: axum::http::Method,
4420×
    q: axum::extract::RawQuery,
4430×
    h: axum::http::HeaderMap,
4440×
    b: axum::body::Bytes,
4450×
) -> Response {
4460×
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await
4470×
}
448
4495×
async fn git_upload_pack(
4505×
    st: axum::extract::State<Shared>,
4515×
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
4525×
    m: axum::http::Method,
4535×
    q: axum::extract::RawQuery,
4545×
    h: axum::http::HeaderMap,
4555×
    b: axum::body::Bytes,
4565×
) -> Response {
4575×
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await
4585×
}
459
4600×
async fn git_receive_pack(
4610×
    st: axum::extract::State<Shared>,
4620×
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
4630×
    m: axum::http::Method,
4640×
    q: axum::extract::RawQuery,
4650×
    h: axum::http::HeaderMap,
4660×
    b: axum::body::Bytes,
4670×
) -> Response {
4680×
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await
4690×
}
470
471
/// Cross-site form posts are refused (hub spec §15.2): a browser that
472
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
473
/// API clients send neither.
4743960×
async fn same_origin(
4753960×
    axum::extract::State(app): axum::extract::State<Shared>,
4763960×
    req: axum::extract::Request,
4773960×
    next: axum::middleware::Next,
4783960×
) -> Response {
4793960×
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
4801893×
        let headers = req.headers();
4811893×
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
4820×
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
4831893×
        }
4841893×
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
4850×
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
4860×
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
4870×
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
4880×
            if !ok && origin != "null" {
4890×
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
4900×
            }
4911893×
        }
4922067×
    }
4933960×
    next.run(req).await
4943960×
}
495
496
/// What every page's chrome needs.
497
#[derive(Clone, Debug)]
498
pub struct Shell {
499
    pub site: String,
500
    pub base_url: String,
501
    pub path: String,
502
    pub version: &'static str,
503
    /// What was built: `oxy describe` at deploy, a Flow build's heads, or "local build".
504
    pub build: &'static str,
505
    /// The signed-in username, if any.
506
    pub user: Option<String>,
507
    pub is_admin: bool,
508
    pub csrf: String,
509
    pub unread: i64,
510
    /// The signed-in viewer's live topic, `user:<id>` (docs/live.md L4),
511
    /// or empty.
512
    pub live_user: String,
513
}
514
515
impl Shell {
516
    /// The version in the stylesheet and script URLs (`statics::assets_version`).
5175192×
    pub fn assets(&self) -> &'static str {
5185192×
        statics::assets_version()
5195192×
    }
520
5211693×
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
522
        Shell {
5231693×
            site: app.config.site.name.clone(),
5241693×
            base_url: app.config.base_url().to_string(),
5251693×
            path: path.to_string(),
526
            version: env!("CARGO_PKG_VERSION"),
527
            build: env!("OXY_BUILD_ID"),
5281693×
            user: viewer.account().map(|a| a.username.clone()),
5291693×
            is_admin: viewer.is_admin(),
5301693×
            csrf: viewer.csrf().to_string(),
5311693×
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
5321693×
            live_user: viewer.account().map(|a| format!("user:{}", a.id)).unwrap_or_default(),
533
        }
5341693×
    }
535
5360×
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
5370×
        Shell::new(app, path, &Viewer(None))
5380×
    }
539
}
540
541
/// The repository chrome: tabs and counts.
542
#[derive(Clone, Debug)]
543
pub struct RepoShell {
544
    /// The repository's row id: its live topics name it (docs/live.md).
545
    pub id: i64,
546
    pub owner: String,
547
    pub name: String,
548
    pub url: String,
549
    pub description: String,
550
    pub default_bookmark: String,
551
    pub visibility: String,
552
    pub tab: &'static str,
553
    pub clone_url: String,
554
    /// The Git mirror's address, when the mirror is on (oxygenhub#215).
555
    pub git_url: Option<String>,
556
    /// The viewer's role, for showing settings and write actions.
557
    pub role: Option<Role>,
558
    /// Open issues and proposals, shown on their tabs.
559
    pub open_issues: i64,
560
    pub open_proposals: i64,
561
    /// Read-only (#108).
562
    pub archived: bool,
563
    /// Whether the repository has a wiki (§6.11).
564
    pub wiki: bool,
565
    /// The bucket its data lives in, when not this hub's disk (#96), as
566
    /// the header's provider icon shows it (#123).
567
    pub stored_in: Option<crate::storage::StoreBadge>,
568
    /// Whether it has coverage reports, for the Coverage tab (#113).
569
    pub coverage: bool,
570
    /// Whether it has test reports, for the Tests tab (#114).
571
    pub tests: bool,
572
    /// Whether it has reports of its own (#127); with coverage or tests,
573
    /// the Reports tab.
574
    pub reports: bool,
575
    /// Whether it pins, or is pinned by, another repository here: the
576
    /// Diffusion tab (#150).
577
    pub diffusion: bool,
578
    /// The backdrop's data, a sky of this repository alone; empty for none
579
    /// (docs/backgrounds.md, oxygenhub#196).
580
    pub backdrop: String,
581
    /// A drop (#279): its pages show the drop's own bar, not the
582
    /// repository's tabs. Its title, for that bar.
583
    pub is_drop: bool,
584
    pub drop_title: String,
585
}
586
587
impl RepoShell {
588540×
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
589
        RepoShell {
590540×
            id: row.id,
591540×
            owner: row.owner.clone(),
592540×
            name: row.name.clone(),
593540×
            url: format!("/{}/{}", row.owner, row.name),
594540×
            description: row.description.clone(),
595540×
            default_bookmark: row.default_bookmark.clone(),
596540×
            visibility: row.visibility.clone(),
597540×
            tab,
598540×
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
599540×
            git_url: row.git_mirror.then(|| format!("{}/{}/{}.git", app.config.base_url(), row.owner, row.name)),
600540×
            role: None,
601540×
            open_issues: row.open_issues,
602540×
            open_proposals: row.open_proposals,
603540×
            archived: row.archived,
604540×
            wiki: crate::repos::RepoName::new(&row.owner, &row.name).is_some_and(|n| app.wikis.exists(&n)),
605540×
            stored_in: crate::storage::location(app, &row.owner, &row.name).and_then(|u| crate::storage::StoreBadge::of(&u)),
606540×
            coverage: crate::coverage::has_reports(app, row.id),
607540×
            tests: crate::junit::has_reports(app, row.id),
608540×
            reports: crate::reports::has_reports(app, row.id),
609540×
            diffusion: crate::diffusion::involved(app, row.id),
610540×
            backdrop: String::new(),
611540×
            is_drop: row.is_drop(),
612540×
            drop_title: row.title.clone(),
613
        }
614540×
    }
615
616
    /// Give the page a backdrop: this repository's sky, its activity of the
617
    /// last 30 days from the database (#196).
618148×
    pub async fn with_sky(mut self, app: &Shared, row: &db::repos::RepoRow) -> RepoShell {
619148×
        self.backdrop = home::repo_sky(app, row).await;
620148×
        self
621148×
    }
622
623
    /// The repository's live topic (docs/live.md).
624116×
    pub fn live_topic(&self) -> String {
625116×
        crate::events::topic::repo(self.id)
626116×
    }
627
628
    /// Its Diffusion topic: bumps and pills.
6295×
    pub fn diffusion_topic(&self) -> String {
6305×
        crate::events::topic::diffusion(self.id)
6315×
    }
632
633540×
    pub fn with_role(mut self, role: Role) -> RepoShell {
634540×
        self.role = Some(role);
635540×
        self
636540×
    }
637
6381138×
    pub fn can(&self, access: Access) -> bool {
6391138×
        auth::roles::allows(self.role, access)
6401138×
    }
641
642517×
    pub fn can_maintain(&self) -> bool {
643517×
        self.can(Access::Maintain)
644517×
    }
645
}
646
647
/// Render a template as an HTML response.
648
/// One page of a long list: which page, how many, and links that keep
649
/// the rest of the query.
650
#[derive(Clone, Debug)]
651
pub struct Pager {
652
    pub page: usize,
653
    pub pages: usize,
654
    pub total: usize,
655
    /// The query without `page`, each pair encoded, joined with `&`.
656
    query: String,
657
}
658
659
impl Pager {
660
    pub const PER_PAGE: usize = 25;
661
662
    /// `page` counts from 1; out-of-range pages clamp to the last.
66312×
    pub fn new(total: usize, page: Option<usize>, query: &[(&str, &str)]) -> Pager {
66412×
        let pages = total.div_ceil(Self::PER_PAGE).max(1);
66512×
        let page = page.unwrap_or(1).clamp(1, pages);
66612×
        let query = query
66712×
            .iter()
66836×
            .filter(|(_, v)| !v.is_empty())
66930×
            .map(|(k, v)| format!("{k}={}", settings::urlencode(v).replace('/', "%2F")))
67012×
            .collect::<Vec<_>>()
67112×
            .join("&");
67212×
        Pager { page, pages, total, query }
67312×
    }
674
675
    /// This page's items.
67612×
    pub fn slice<T>(&self, all: Vec<T>) -> Vec<T> {
67712×
        all.into_iter().skip((self.page - 1) * Self::PER_PAGE).take(Self::PER_PAGE).collect()
67812×
    }
679
6803×
    pub fn url(&self, page: usize) -> String {
6813×
        if self.query.is_empty() {
6820×
            format!("?page={page}")
683
        } else {
6843×
            format!("?{}&page={page}", self.query)
685
        }
6863×
    }
687
688
    /// The same query with another sort, back on page one.
68943×
    pub fn sorted(&self, sort: &str) -> String {
690107×
        let rest: Vec<&str> = self.query.split('&').filter(|p| !p.is_empty() && !p.starts_with("sort=")).collect();
69143×
        let mut q = rest.join("&");
69243×
        if !q.is_empty() {
69343×
            q.push('&');
69443×
        }
69543×
        format!("?{q}sort={sort}")
69643×
    }
697
}
698
699
pub struct Page<T: Template>(pub T);
700
701
impl<T: Template> IntoResponse for Page<T> {
7021106×
    fn into_response(self) -> Response {
7031106×
        match self.0.render() {
7041106×
            Ok(s) => Html(s).into_response(),
7050×
            Err(e) => {
7060×
                tracing::error!("template: {e}");
7070×
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
708
            }
709
        }
7101106×
    }
711
}
712
713
#[derive(Template)]
714
#[template(path = "error.html")]
715
struct ErrorPage {
716
    shell: Shell,
717
    status: u16,
718
    title: String,
719
    detail: String,
720
}
721
722
/// A page-level failure, rendered inside the shell, or a redirect.
723
#[derive(Debug)]
724
pub struct Error {
725
    pub status: StatusCode,
726
    pub detail: String,
727
    shell: Option<Box<Shell>>,
728
    redirect: Option<String>,
729
}
730
731
impl Error {
73214×
    pub fn redirect(to: String) -> Error {
73314×
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
73414×
    }
735
73675×
    pub fn not_found(shell: Shell) -> Error {
73775×
        Error {
73875×
            status: StatusCode::NOT_FOUND,
73975×
            detail: "There is nothing at this address.".into(),
74075×
            shell: Some(Box::new(shell)),
74175×
            redirect: None,
74275×
        }
74375×
    }
744
74515×
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
74615×
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
74715×
    }
748
7493×
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
7501×
        match e {
7512×
            RepoError::NotFound => Error::not_found(shell),
7521×
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
7531×
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
754
            }
7550×
            other => {
7560×
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
757
            }
758
        }
7593×
    }
760
7610×
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
7620×
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
7630×
    }
764
}
765
766
impl IntoResponse for Error {
767105×
    fn into_response(self) -> Response {
768105×
        if let Some(to) = self.redirect {
76914×
            return Redirect::to(&to).into_response();
77091×
        }
77191×
        let title = match self.status {
77291×
            StatusCode::NOT_FOUND => "Not found",
77315×
            StatusCode::BAD_REQUEST => "Bad request",
7740×
            _ => "Something went wrong",
775
        };
77691×
        if self.status.is_server_error() {
7770×
            tracing::error!("{}", self.detail);
77891×
        }
77991×
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
78091×
            site: "OxygenHub".into(),
78191×
            base_url: String::new(),
78291×
            path: String::new(),
78391×
            version: "",
78491×
            build: "",
78591×
            user: None,
78691×
            is_admin: false,
78791×
            csrf: String::new(),
78891×
            unread: 0,
78991×
            live_user: String::new(),
79091×
        });
79191×
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
79291×
        match page.render() {
79391×
            Ok(s) => (self.status, Html(s)).into_response(),
7940×
            Err(_) => (self.status, title).into_response(),
795
        }
796105×
    }
797
}
798
799
/// A page address the router matched but could not read (a number that is
800
/// not one, a malformed query): axum answers that in plain text before any
801
/// handler runs. For pages, that is the site's not-found page instead
802
/// (#294); the oxy protocol and anything not asked for with GET or HEAD keep
803
/// the plain answer.
8043960×
async fn rejections_as_pages(
8053960×
    axum::extract::State(app): axum::extract::State<Shared>,
8063960×
    req: axum::extract::Request,
8073960×
    next: axum::middleware::Next,
8083960×
) -> Response {
8093960×
    let page = matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) && !req.uri().path().contains("/oxy/v1/");
8103960×
    if !page {
8112622×
        return next.run(req).await;
8121338×
    }
8131338×
    let (uri, headers) = (req.uri().clone(), req.headers().clone());
8141338×
    let res = next.run(req).await;
8151338×
    let plain = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/plain"));
8161338×
    if !(plain && matches!(res.status(), StatusCode::BAD_REQUEST | StatusCode::UNPROCESSABLE_ENTITY)) {
8171333×
        return res;
8185×
    }
819
    // Only axum's own rejections: a handler's plain 400 (the live stream's
820
    // "unknown topic") is the handler's answer and stays.
8215×
    let (head, body) = res.into_parts();
8225×
    let Ok(bytes) = axum::body::to_bytes(body, 4096).await else { return StatusCode::BAD_REQUEST.into_response() };
8235×
    let rejected = [&b"Invalid URL"[..], b"Failed to deserialize query string", b"Failed to deserialize the query string"]
8245×
        .iter()
8259×
        .any(|p| bytes.starts_with(p));
8265×
    if !rejected {
8272×
        return Response::from_parts(head, axum::body::Body::from(bytes));
8283×
    }
8293×
    let mut probe = axum::http::Request::builder().uri(uri.clone()).body(()).expect("a request");
8303×
    *probe.headers_mut() = headers;
8313×
    let (mut parts, ()) = probe.into_parts();
8323×
    let viewer = match <Viewer as axum::extract::FromRequestParts<Shared>>::from_request_parts(&mut parts, &app).await {
8333×
        Ok(v) => v,
834
        Err(never) => match never {},
835
    };
8363×
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
8373960×
}
838
8392×
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
8402×
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
8412×
}
842
843
/// A raw file response with a safe content type (hub spec §15.2).
84419×
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
84519×
    let mime = mime_of(name);
84619×
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
84719×
    (
84819×
        [
84919×
            (header::CONTENT_TYPE, mime.to_string()),
85019×
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
85119×
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
85219×
        ],
85319×
        bytes,
85419×
    )
85519×
        .into_response()
85619×
}
857
85826×
pub fn mime_of(name: &str) -> &'static str {
85926×
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
86026×
        Some("png") => "image/png",
86125×
        Some("jpg" | "jpeg") => "image/jpeg",
86225×
        Some("gif") => "image/gif",
86325×
        Some("webp") => "image/webp",
86425×
        Some("svg") => "image/svg+xml",
86525×
        Some("pdf") => "application/pdf",
866
        Some(
86725×
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
86824×
        ) => "text/plain; charset=utf-8",
8691×
        _ => "application/octet-stream",
870
    }
87126×
}
872
873
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
874
/// a repository the viewer may not see does not exist for them (hub spec
875
/// §4.4). Returns the viewer's role too.
876808×
pub async fn lookup_role(
877808×
    app: &Shared,
878808×
    shell: &Shell,
879808×
    viewer: &Viewer,
880808×
    owner: &str,
881808×
    name: &str,
882808×
    access: Access,
883808×
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
884808×
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
885808×
    let row = match db::repos::get(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))? {
886807×
        Some(row) => row,
887
        None => {
888
            // A transferred repository: the old URL goes to the new one (#108),
889
            // the rest of the path kept, when the viewer may see it.
8901×
            let moved = db::repos::moved_to(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))?;
8911×
            let Some(moved) = moved else { return Err(Error::not_found(shell.clone())) };
8921×
            let role = auth::roles::role_for(&app.db, viewer.account(), &moved).await.map_err(|e| Error::from_db(shell.clone(), e))?;
8931×
            if !auth::roles::allows(role, Access::Read) {
8940×
                return Err(Error::not_found(shell.clone()));
8951×
            }
8961×
            let old = format!("/{owner}/{name}");
8971×
            let rest = shell.path.strip_prefix(&old).unwrap_or("");
8981×
            return Err(Error::redirect(format!("/{}/{}{rest}", moved.owner, moved.name)));
899
        }
900
    };
901807×
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
902807×
    if !auth::roles::allows(role, access) {
90311×
        return Err(Error::not_found(shell.clone()));
904796×
    }
905
    // A drop's repository pages are read-only (its history, changes and
906
    // raw files, #279): it is changed from the drop's own page.
907796×
    if row.is_drop() && access != Access::Read {
9080×
        return Err(Error::not_found(shell.clone()));
909796×
    }
910796×
    if row.archived && matches!(access, Access::Write | Access::Maintain) {
9110×
        return Err(archived(shell));
912796×
    }
913796×
    Ok((repo, row, role.unwrap_or(Role::Read)))
914808×
}
915
916
/// The error for a write to an archived repository (#108).
9171×
pub fn archived(shell: &Shell) -> Error {
9181×
    Error::bad(shell.clone(), "This repository is archived and read-only. Its admins can bring it back under Settings › Advanced.")
9191×
}
920
921
/// Refuse a change to an archived repository, for handlers that open it
922
/// for reading and then write.
92335×
pub fn writable(row: &db::repos::RepoRow, shell: &Shell) -> Result<(), Error> {
92435×
    if row.archived {
9251×
        Err(archived(shell))
926
    } else {
92734×
        Ok(())
928
    }
92935×
}
930
931
/// `lookup_role` for reading.
932482×
pub async fn lookup(
933482×
    app: &Shared,
934482×
    shell: &Shell,
935482×
    viewer: &Viewer,
936482×
    owner: &str,
937482×
    name: &str,
938482×
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
939482×
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
940482×
}
941
942
/// Fill `account` on change authors whose key is linked to an account.
943117×
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
944117×
    if changes.is_empty() {
9453×
        return;
946114×
    }
947114×
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
948114×
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
949159×
    for c in changes.iter_mut() {
950159×
        if let Some(u) = map.get(&c.author.key) {
95173×
            c.author.account = Some(u.clone());
95286×
        }
953
    }
954117×
}
955
956
/// The part of a rendered page between `<!--frag:NAME-->` and
957
/// `<!--/frag:NAME-->` (live pages, docs/live.md): what a page fetches again
958
/// when its topic changes. `None` when the page has no such part.
9597×
pub fn fragment(html: &str, name: &str) -> Option<String> {
96031×
    if !name.bytes().all(|b| b.is_ascii_lowercase() || b == b'-') || name.is_empty() {
9611×
        return None;
9626×
    }
9636×
    let open = format!("<!--frag:{name}-->");
9646×
    let close = format!("<!--/frag:{name}-->");
9656×
    let start = html.find(&open)? + open.len();
9664×
    let end = start + html[start..].find(&close)?;
9674×
    Some(html[start..end].to_string())
9687×
}
969
970
#[cfg(test)]
971
mod fragment_tests {
972
    #[test]
9731×
    fn a_fragment_is_cut_from_the_page_by_its_markers() {
9741×
        let page = "<p>a</p><div data-fragment=\"x\"><!--frag:x--><b>inside</b><!--/frag:x--></div>";
9751×
        assert_eq!(super::fragment(page, "x").as_deref(), Some("<b>inside</b>"));
9761×
        assert_eq!(super::fragment(page, "y"), None);
9771×
        assert_eq!(super::fragment(page, "x--><b"), None, "names are plain");
9781×
    }
979
}