OXYGENHUB

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

657 of 726 lines run, 152 of 335 functions · run #542 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
802923×
pub fn router(app: Shared) -> Router {
812923×
    let push_limit = app.config.limits.push_body_limit.0 as usize;
822923×
    Router::new()
832923×
        .route("/", get(home::index))
842923×
        .route("/explore", get(home::explore))
852923×
        .route("/avatar/agent/{name}", get(avatar::agent))
862923×
        .route("/avatar/{name}", get(avatar::avatar))
872923×
        .route("/health", get(home::health))
882923×
        .route("/about", get(home::about))
892923×
        .route("/.well-known/oxyhub-key", get(home::hub_key))
902923×
        .route("/metrics", get(crate::metrics::metrics))
912923×
        .route("/log", get(transparency::page))
922923×
        .route("/log/checkpoint", get(crate::tlog::checkpoint))
932923×
        .route("/log/witnesses", get(crate::tlog::witnesses))
942923×
        .route("/log/tile/{*path}", get(crate::tlog::tile))
952923×
        .route("/log/witness/add-checkpoint", axum::routing::post(crate::tlog::add_checkpoint))
962923×
        .route("/.well-known/oxyhub-ca.pem", get(home::hub_ca))
972923×
        .route("/.well-known/oxyhub-signing.pem", get(flow::signing_key))
982923×
        .route("/.well-known/openid-configuration", get(crate::oidc::discovery))
992923×
        .route("/.well-known/jwks.json", get(crate::oidc::jwks))
1002923×
        .route("/live", get(live_stream::stream))
1012923×
        .route("/.well-known/security.txt", get(security_txt::serve))
1022923×
        .route("/security.txt", get(security_txt::serve))
1032923×
        .route("/security-contact", get(security_txt::contact_page))
1042923×
        .route("/style.css", get(statics::style))
1052923×
        .route("/favicon.svg", get(statics::favicon))
1062923×
        .route("/favicon.ico", get(statics::favicon))
1072923×
        .route("/static/{*path}", get(statics::asset))
1082923×
        .route("/login", get(session::login_form).post(session::login))
1092923×
        .route("/login/approval", post(session::approval_state))
1102923×
        .route("/sudo", get(sudo::show).post(sudo::confirm))
1112923×
        .route("/sudo/phone", post(sudo::ask_phone))
1122923×
        .route("/sudo/approval/{id}", get(sudo::approval_state))
1132923×
        .route("/device", get(device::form).post(device::answer))
1142923×
        .route(crate::headers::REPORT_PATH, post(crate::headers::csp_report).layer(DefaultBodyLimit::max(16 * 1024)))
1152923×
        .route("/logout", post(session::logout))
1162923×
        .route("/register", get(session::register_form).post(session::register))
1172923×
        .route("/settings", get(settings::profile).post(settings::update_profile))
1182923×
        .route("/settings/password", post(settings::change_password))
1192923×
        .route("/settings/appearance", post(settings::appearance))
1202923×
        .route("/settings/security", get(settings::security))
1212923×
        .route("/settings/security/totp/begin", post(settings::totp_begin))
1222923×
        .route("/settings/security/totp/enable", post(settings::totp_enable))
1232923×
        .route("/settings/security/totp/disable", post(settings::totp_disable))
1242923×
        .route("/settings/security/sessions", post(settings::sessions_reset))
1252923×
        .route("/settings/security/sessions/{id}/end", post(settings::session_end))
1262923×
        .route("/settings/security/phones/{id}/remove", post(settings::phone_remove))
1272923×
        .route("/settings/keys", get(settings::keys))
1282923×
        .route("/settings/keys/upload", post(settings::keys_upload))
1292923×
        .route("/settings/keys/verify", post(settings::keys_verify))
1302923×
        .route("/settings/keys/unlink", post(settings::keys_unlink))
1312923×
        .route("/settings/tokens", get(settings::tokens).post(settings::tokens_create))
1322923×
        .route("/sky/arrivals", get(home::arrivals))
1332923×
        .route("/settings/backups", get(backups::user).post(backups::user_save))
1342923×
        .route("/settings/backups/run", post(backups::user_run))
1352923×
        .route("/settings/backups/test", post(backups::user_test))
1362923×
        .route("/orgs/{name}/settings/backups", get(backups::org).post(backups::org_save))
1372923×
        .route("/orgs/{name}/settings/backups/run", post(backups::org_run))
1382923×
        .route("/orgs/{name}/settings/backups/test", post(backups::org_test))
1392923×
        .route("/settings/tokens/{id}/delete", post(settings::tokens_delete))
1402923×
        .route("/settings/tokens/{id}/agent", post(settings::tokens_agent))
1412923×
        .route("/new", get(repo_settings::new_form).post(repo_settings::create))
1422923×
        .route("/orgs/new", get(orgs::new_form).post(orgs::create))
1432923×
        .route("/orgs/{name}/settings", get(orgs::settings).post(orgs::update))
1442923×
        .route("/orgs/{name}/settings/members", post(orgs::member))
1452923×
        .route("/orgs/{name}/settings/teams", post(orgs::team))
1462923×
        .route("/orgs/{name}/settings/hooks", post(orgs::hooks))
1472923×
        .route("/orgs/{name}/settings/assistants", post(orgs::assistants))
1482923×
        .route("/orgs/{name}/settings/assistants/models", post(orgs::assistant_models))
1492923×
        .route("/orgs/{name}/settings/variables", post(orgs::variables))
1502923×
        .route("/orgs/{name}/settings/secrets", post(orgs::secrets))
1512923×
        .route("/orgs/{name}/settings/storage", post(orgs::storage))
1522923×
        .route("/orgs/{name}/settings/flow-priority", post(orgs::flow_priority))
1532923×
        .route("/orgs/{name}/settings/runners/token", post(orgs::runner_token))
1542923×
        .route("/orgs/{name}/settings/runners/{id}/remove", post(orgs::runner_remove))
1552923×
        .route("/orgs/{name}/settings/runners/updates/policy", post(orgs::runner_updates_policy))
1562923×
        .route("/orgs/{name}/settings/runners/updates/groups", post(orgs::runner_updates_group_new))
1572923×
        .route("/orgs/{name}/settings/runners/updates/groups/{id}", post(orgs::runner_updates_group))
1582923×
        .route("/orgs/{name}/settings/runners/updates/groups/{id}/delete", post(orgs::runner_updates_group_delete))
1592923×
        .route("/orgs/{name}/settings/hooks/{id}/deliveries", get(orgs::deliveries))
1602923×
        .route("/orgs/{name}/settings/hooks/{id}/redeliver/{delivery}", post(orgs::redeliver))
1612923×
        .route("/orgs/{name}/settings/avatar", post(orgs::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10))))
1622923×
        .route("/settings/avatar", post(settings::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10))))
1632923×
        .route("/notifications", get(inbox::inbox))
1642923×
        .route("/notifications/read", post(inbox::mark_read))
1652923×
        .route("/settings/notifications", get(inbox::unsubscribe).post(inbox::prefs))
1662923×
        .route("/search", get(inbox::search))
1672923×
        .route("/admin", get(admin::index))
1682923×
        .route("/admin/accounts", get(admin::section))
1692923×
        .route("/admin/organisations", get(admin::section))
1702923×
        .route("/admin/audit", get(admin::section))
1712923×
        .route("/admin/registration", get(admin::section).post(admin::set_mode))
1722923×
        .route("/admin/invite", post(admin::invite))
1732923×
        .route("/admin/account", post(admin::account))
1742923×
        .route("/admin/storage", get(admin::storage).post(admin::maintain))
1752923×
        .route("/admin/runners", get(runners::list))
1762923×
        .route("/admin/runners/settings", get(runners::settings).post(runners::save_settings))
1772923×
        .route("/admin/runners/priority", post(runners::save_priority))
1782923×
        .route("/admin/runners/images", get(runners::images))
1792923×
        .route("/admin/runners/updates", get(runner_updates::show))
1802923×
        .route("/admin/runners/updates/source", post(runner_updates::save_source))
1812923×
        .route("/admin/runners/updates/policy", post(runner_updates::save_policy))
1822923×
        .route("/admin/runners/updates/groups", post(runner_updates::create_group))
1832923×
        .route("/admin/runners/updates/holds/lift", post(runner_updates::lift_hold))
1842923×
        .route("/admin/runners/updates/groups/{id}", post(runner_updates::save_group))
1852923×
        .route("/admin/runners/updates/groups/{id}/delete", post(runner_updates::delete_group))
1862923×
        .route("/admin/insights", get(insights::site))
1872923×
        .route("/insights/{owner}", get(insights::owner))
1882923×
        .route("/admin/diffusion", get(diffusion::admin))
1892923×
        .route("/admin/backups", get(backups::admin))
1902923×
        .route("/{owner}/{name}/diffusion", get(diffusion::page))
1912923×
        .route("/admin/runners/token", post(runners::new_token))
1922923×
        .route("/admin/runners/{id}", get(runners::show))
1932923×
        .route("/admin/runners/{id}/state", post(runners::set_state))
1942923×
        .route("/admin/runners/{id}/scope", post(runners::set_scope))
1952923×
        .route("/admin/runners/{id}/limits", post(runners::set_limits))
1962923×
        .route("/admin/mail", get(admin::section).post(admin::set_mail))
1972923×
        .route("/admin/mail/test", post(admin::test_mail))
1982923×
        .route("/admin/assistants", get(admin::section).post(admin::assistants))
1992923×
        .route("/admin/assistants/models", post(admin::assistant_models))
2002923×
        .route("/admin/signin", get(admin::section).post(admin::signin))
2012923×
        .route("/admin/security", get(admin::section).post(security_txt::save))
2022923×
        .route("/login/{provider}", get(signin::start))
2032923×
        .route("/login/{provider}/callback", get(signin::callback))
2042923×
        .route("/settings/security/connect/{provider}", get(signin::connect))
2052923×
        .route("/settings/security/disconnect/{provider}", post(signin::disconnect))
2062923×
        .route("/admin/variables", get(admin::section).post(admin::variables))
2072923×
        .route("/admin/secrets", get(admin::section).post(admin::secrets))
2082923×
        .route("/admin/runners/{id}/remove", post(runners::remove))
2092923×
        .nest("/api/v1", crate::api::router(app.config.limits.asset_limit.0 as usize))
210
        // Drops (#279): `drops` is reserved, as an owner and as a repository name.
2112923×
        .route("/drops", get(drops::mine))
2122923×
        .route("/drops/new", get(drops::new_form).post(drops::create))
2132923×
        .route("/{owner}/drops", get(drops::list))
2142923×
        .route("/{owner}/drops/{id}", get(drops::show))
2152923×
        .route("/{owner}/drops/{id}/tree/{r}", get(drops::show_at))
2162923×
        .route("/{owner}/drops/{id}/edit", get(drops::edit_form).post(drops::save))
2172923×
        .route("/{owner}/drops/{id}/delete", post(drops::delete))
2182923×
        .route("/{owner}/drops/{id}/fork", post(drops::fork))
2192923×
        .route("/{owner}/drops/{id}/star", post(drops::star))
2202923×
        .route("/{owner}/drops/{id}/embed", get(drops::embed))
2212923×
        .route("/{owner}/drops/{id}/comment", post(drops::comment))
2222923×
        .route("/{owner}/drops/{id}/comment/{n}/delete", post(drops::delete_comment))
2232923×
        .route("/{owner}/drops/{id}/changes/{r}", get(drops::changes))
2242923×
        .route("/{owner}/drops/{id}/change/{hash}", get(drops::change))
2252923×
        .route("/{owner}/drops/{id}/raw/{r}/{*path}", get(drops::raw))
2262923×
        .route("/{owner}/drops/{id}/file/{r}/{*path}", get(drops::file))
2272923×
        .route("/{owner}/drops/{id}/oxy/v1/{endpoint}", any(crate::protocol::dispatch_drop).layer(DefaultBodyLimit::max(push_limit)))
2282923×
        .route("/{owner}", get(home::owner))
2292923×
        .route("/{owner}/{name}", get(repo::overview))
2302923×
        .route("/{owner}/{name}/tree/{r}", get(repo::tree_root))
2312923×
        .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree))
2322923×
        .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file))
2332923×
        .route("/{owner}/{name}/function/{r}/{*path}", get(history::function))
2342923×
        .route("/{owner}/{name}/lanes/{r}", get(history::lanes))
2352923×
        .route("/{owner}/{name}/lanes/{r}/plan", post(history::plan))
2362923×
        .route("/{owner}/{name}/raw/{r}/{*path}", get(repo::raw_file))
2372923×
        .route("/{owner}/{name}/last/{r}", get(repo::last_changes))
2382923×
        .route("/{owner}/{name}/changes/{r}", get(history::history))
2392923×
        .route("/{owner}/{name}/change/{hash}", get(history::change))
2402923×
        .route("/apt", get(crate::apt::home))
2412923×
        .route("/apt/{file}", get(crate::apt::key))
2422923×
        .route("/apt/dists/{suite}/{*rest}", get(crate::apt::dists))
2432923×
        .route("/apt/pool/{*path}", get(crate::apt::pool))
2442923×
        .route("/help", get(help::help))
2452923×
        .route("/projects/{owner}", get(projects::list).post(projects::create))
2462923×
        .route("/projects/{owner}/{number}", get(projects::show).post(projects::act))
2472923×
        .route("/projects/{owner}/{number}/charts", get(board_charts::show))
2482923×
        .route("/notifications/thread", post(inbox::thread))
2492923×
        .route("/notifications/open/{id}", get(inbox::open))
2502923×
        .route("/login/reset", get(recovery::request_form).post(recovery::request))
2512923×
        .route("/login/reset/{secret}", get(recovery::new_password_form).post(recovery::set_new_password))
2522923×
        .route("/verify/{secret}", get(recovery::verify))
2532923×
        .route("/settings/email/verify", post(settings::resend_verification))
2542923×
        .route("/{owner}/{name}/compare", get(history::compare_index))
2552923×
        .route("/{owner}/{name}/compare/{spec}", get(history::compare))
2562923×
        .route("/{owner}/{name}/bookmarks", get(refs::bookmarks))
2572923×
        .route("/{owner}/{name}/bookmarks/delete", post(refs::delete_bookmark))
2582923×
        .route("/{owner}/{name}/bookmarks/create", post(refs::create_bookmark))
2592923×
        .route("/{owner}/{name}/tags", get(refs::tags))
2602923×
        .route("/{owner}/{name}/tags/create", post(refs::create_tag))
2612923×
        .route("/{owner}/{name}/tags/withdraw", post(refs::withdraw_tag))
2622923×
        .route("/{owner}/{name}/artifacts", get(artifacts::artifacts))
2632923×
        .route("/{owner}/{name}/images", get(artifacts::images))
2642923×
        .route("/{owner}/{name}/terraform", get(artifacts::terraform))
2652923×
        .route("/{owner}/{name}/insights", get(insights::repo))
2662923×
        .route("/{owner}/{name}/terraform/{state}/download", get(artifacts::download))
2672923×
        .route("/{owner}/{name}/terraform/{state}/restore", post(artifacts::restore))
2682923×
        .route("/{owner}/{name}/conflicts", get(refs::conflicts))
2692923×
        .route("/{owner}/{name}/trust", get(refs::trust))
2702923×
        .route("/{owner}/{name}/pushes", get(refs::pushes))
2712923×
        .route("/{owner}/{name}/fork", get(forks::form).post(forks::create))
2722923×
        .route("/{owner}/{name}/forks", get(forks::list))
2732923×
        .route("/{owner}/{name}/settings", get(repo_settings::settings).post(repo_settings::update))
274
        // One page per setting (#278); some share their form's path.
2752923×
        .route("/{owner}/{name}/settings/{page}", get(repo_settings::page))
2762923×
        .route("/{owner}/{name}/settings/collaborators", get(repo_settings::page).post(repo_settings::collaborator))
2772923×
        .route("/{owner}/{name}/settings/delete", post(repo_settings::delete))
2782923×
        .route("/{owner}/{name}/settings/transfer", post(repo_settings::transfer))
2792923×
        .route("/{owner}/{name}/settings/archive", post(repo_settings::archive))
2802923×
        .route("/{owner}/{name}/settings/wiki/delete", post(repo_settings::wiki_delete))
2812923×
        .route("/{owner}/{name}/wiki", get(wiki::home))
2822923×
        .route("/{owner}/{name}/wiki/_pages", get(wiki::pages))
2832923×
        .route("/{owner}/{name}/wiki/_new", get(wiki::new_form))
2842923×
        .route("/{owner}/{name}/wiki/_raw/{*path}", get(wiki::raw))
2852923×
        .route("/{owner}/{name}/wiki/{slug}", get(wiki::show))
2862923×
        .route("/{owner}/{name}/wiki/{slug}/edit", get(wiki::edit_form).post(wiki::save))
2872923×
        .route("/{owner}/{name}/wiki/{slug}/history", get(wiki::history))
2882923×
        .route("/{owner}/{name}/wiki/{slug}/delete", post(wiki::delete))
2892923×
        .route("/{owner}/{name}/settings/requirements", post(repo_settings::requirements))
2902923×
        .route("/{owner}/{name}/proposals", get(proposals::list))
2912923×
        .route("/{owner}/{name}/proposals/new", get(proposals::new_form).post(proposals::create))
2922923×
        .route("/{owner}/{name}/proposals/new/draft", post(proposals::new_draft))
2932923×
        .route("/{owner}/{name}/proposals/new/draft/stream", post(proposals::new_draft_stream))
2942923×
        .route("/{owner}/{name}/proposal/{number}", get(proposals::show))
2952923×
        .route("/{owner}/{name}/proposal/{number}/comment", post(proposals::comment))
2962923×
        .route("/{owner}/{name}/proposal/{number}/comment/{id}/resolve", post(proposals::resolve_comment))
2972923×
        .route("/{owner}/{name}/proposal/{number}/resolve", post(proposals::resolve_on_web))
2982923×
        .route("/{owner}/{name}/proposal/{number}/review", post(proposals::review))
2992923×
        .route("/{owner}/{name}/proposal/{number}/reviewers", post(proposals::reviewers))
3002923×
        .route("/{owner}/{name}/proposal/{number}/assistant", post(proposals::assistant))
3012923×
        .route("/{owner}/{name}/proposal/{number}/draft", post(proposals::draft))
3022923×
        .route("/{owner}/{name}/proposal/{number}/draft/stream", post(proposals::draft_stream))
3032923×
        .route("/{owner}/{name}/proposal/{number}/edit", post(proposals::edit))
3042923×
        .route("/{owner}/{name}/proposal/{number}/state", post(proposals::state))
3052923×
        .route("/{owner}/{name}/proposal/{number}/land", post(proposals::land))
3062923×
        .route("/{owner}/{name}/proposal/{number}/auto-land", post(proposals::auto_land))
3072923×
        .route("/{owner}/{name}/proposal/{number}/labels", post(proposals::set_labels))
3082923×
        .route("/{owner}/{name}/proposal/{number}/project", post(projects::place_proposal))
3092923×
        .route("/{owner}/{name}/issue/{number}/project", post(projects::place_issue))
3102923×
        .route("/{owner}/{name}/proposal/{number}/events", get(proposals::events))
3112923×
        .route("/{owner}/{name}/settings/hooks", post(repo_settings::hooks))
3122923×
        .route("/{owner}/{name}/settings/assistants", get(repo_settings::page).post(repo_settings::assistants))
3132923×
        .route("/{owner}/{name}/settings/assistants/models", post(repo_settings::assistant_models))
3142923×
        .route("/{owner}/{name}/settings/variables", get(repo_settings::page).post(repo_settings::variables))
3152923×
        .route("/{owner}/{name}/settings/secrets", get(repo_settings::page).post(repo_settings::secrets))
3162923×
        .route("/{owner}/{name}/settings/hooks/{id}/deliveries", get(repo_settings::deliveries))
3172923×
        .route("/{owner}/{name}/settings/hooks/{id}/redeliver/{delivery}", post(repo_settings::redeliver))
3182923×
        .route("/{owner}/{name}/settings/checks", get(repo_settings::page).post(repo_settings::required_checks))
3192923×
        .route("/{owner}/{name}/watch", post(issues::watch))
3202923×
        .route("/{owner}/{name}/star", post(issues::star))
3212923×
        .route("/{owner}/{name}/edit/{r}", post(edit::save))
3222923×
        .route("/{owner}/{name}/edit/{r}/{*path}", get(edit::edit_form))
3232923×
        .route("/{owner}/{name}/resolve/{bookmark}/{*path}", get(resolve::form).post(resolve::save))
3242923×
        .route("/{owner}/{name}/resolve-live/{bookmark}/{*path}", get(resolve::live_events).post(resolve::live_choose))
3252923×
        .route("/{owner}/{name}/newfile/{r}", get(edit::new_form))
3262923×
        .route("/{owner}/{name}/flow", get(flow::runs))
3272923×
        .route("/{owner}/{name}/flow/badge.svg", get(flow::badge))
3282923×
        .route("/{owner}/{name}/flow/tab", get(flow::tab))
3292923×
        .route("/{owner}/{name}/tests", get(test_reports::overview))
3302923×
        .route("/{owner}/{name}/tests/case", get(test_reports::case))
3312923×
        .route("/{owner}/{name}/reports", get(reports::overview))
3322923×
        .route("/{owner}/{name}/reports/files/{id}/{mac}/{*path}", get(reports::file))
3332923×
        .route("/{owner}/{name}/reports/{report}", get(reports::show))
3342923×
        .route("/{owner}/{name}/coverage", get(coverage::overview))
3352923×
        .route("/{owner}/{name}/coverage/badge.svg", get(coverage::badge))
3362923×
        .route("/{owner}/{name}/coverage/{id}/file/{*path}", get(coverage::file))
3372923×
        .route("/{owner}/{name}/deployments", get(flow::deployments))
3382923×
        .route("/{owner}/{name}/flow/{id}", get(flow::run))
3392923×
        .route("/{owner}/{name}/flow/{id}/live", get(flow::live))
3402923×
        .route("/{owner}/{name}/flow/start", post(flow::start))
3412923×
        .route("/{owner}/{name}/flow/{id}/rerun", post(flow::rerun))
3422923×
        .route("/{owner}/{name}/flow/{id}/jobs/{job}/rerun", post(flow::rerun_job))
3432923×
        .route("/{owner}/{name}/flow/{id}/jobs/{job}/decide", post(flow::decide))
3442923×
        .route("/{owner}/{name}/flow/{id}/cancel", post(flow::cancel))
3452923×
        .route("/{owner}/{name}/flow/{id}/expedite", post(flow::expedite))
3462923×
        .route("/{owner}/{name}/flow/stamp/{r}", get(flow::stamp))
3472923×
        .route("/{owner}/{name}/flow/at/{r}", get(flow::at))
3482923×
        .route("/{owner}/{name}/receipts/{attest}", get(flow::receipt_file))
3492923×
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}", get(flow::artifact_file))
3502923×
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/attach", post(flow::attach))
3512923×
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/provenance", get(flow::provenance))
3522923×
        .route("/{owner}/{name}/releases", get(releases::list))
3532923×
        .route("/{owner}/{name}/releases/new", get(releases::new_form).post(releases::create))
3542923×
        .route("/{owner}/{name}/releases/tag/{*tag}", get(releases::show))
3552923×
        .route("/{owner}/{name}/releases/download/{tag}/{file}", get(releases::download_by_tag))
3562923×
        .route("/{owner}/{name}/releases/trust/{*tag}", get(release_trust::page))
3572923×
        .route("/{owner}/{name}/releases/edit/{id}", post(releases::edit))
3582923×
        .route(
3592923×
            "/{owner}/{name}/releases/upload/{id}",
3602923×
            post(releases::upload).layer(DefaultBodyLimit::max(app.config.limits.asset_limit.0 as usize + (1 << 20))),
361
        )
3622923×
        .route("/{owner}/{name}/asset/{id}/{file}", get(releases::download))
3632923×
        .route("/{owner}/{name}/attachments/{id}/{file}", get(releases::attachment))
3642923×
        .route("/{owner}/{name}/archive", get(releases::source_archive))
3652923×
        .route("/{owner}/{name}/search", get(repo::code_search))
3662923×
        .route("/{owner}/{name}/info/{*rest}", any(git_info))
3672923×
        .route("/{owner}/{name}/HEAD", get(git_head))
3682923×
        .route("/{owner}/{name}/objects/{*rest}", get(git_objects))
3692923×
        .route("/{owner}/{name}/git-upload-pack", post(git_upload_pack))
3702923×
        .route("/{owner}/{name}/git-receive-pack", post(git_receive_pack))
3712923×
        .route("/{owner}/{name}/settings/mirror", post(repo_settings::mirror))
3722923×
        .route("/{owner}/{name}/settings/flow", get(repo_settings::page).post(repo_settings::flow))
3732923×
        .route("/{owner}/{name}/settings/flow-priority", post(repo_settings::flow_priority))
3742923×
        .route("/{owner}/{name}/settings/agent-gates", post(repo_settings::agent_gates))
3752923×
        .route("/{owner}/{name}/settings/push-protection", get(repo_settings::page).post(repo_settings::push_protection))
3762923×
        .route("/{owner}/{name}/settings/secret-bypass", post(repo_settings::secret_bypass))
3772923×
        .route("/{owner}/{name}/settings/secret-bypass/remove", post(repo_settings::secret_bypass_remove))
3782923×
        .route("/{owner}/{name}/settings/secret-resolve", post(repo_settings::secret_resolve))
3792923×
        .route("/{owner}/{name}/settings/secret-scan", post(repo_settings::secret_scan))
3802923×
        .route("/{owner}/{name}/settings/flow-supersede", post(repo_settings::flow_supersede))
3812923×
        .route("/{owner}/{name}/settings/flow-skip", post(repo_settings::flow_skip))
3822923×
        .route("/{owner}/{name}/settings/flow-reuse", post(repo_settings::flow_reuse))
3832923×
        .route("/{owner}/{name}/settings/diffusion", get(repo_settings::page).post(repo_settings::diffusion))
3842923×
        .route("/{owner}/{name}/settings/backup", get(repo_settings::page).post(repo_settings::backup))
3852923×
        .route("/{owner}/{name}/settings/storage", get(repo_settings::page).post(repo_settings::storage))
3862923×
        .route("/{owner}/{name}/settings/coverage", get(repo_settings::page).post(repo_settings::coverage))
3872923×
        .route("/{owner}/{name}/settings/runners/token", post(repo_settings::runner_token))
3882923×
        .route("/{owner}/{name}/settings/runners/{id}/remove", post(repo_settings::runner_remove))
3892923×
        .route("/{owner}/{name}/issues", get(issues::list))
3902923×
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
3912923×
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
3922923×
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
3932923×
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
3942923×
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
3952923×
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
3962923×
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
3972923×
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
3982923×
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
3992923×
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
4002923×
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
4012923×
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
4022923×
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
4032923×
        .fallback(not_found)
4042923×
        .layer(axum::middleware::from_fn_with_state(app.clone(), sudo::gate))
4052923×
        .layer(axum::middleware::from_fn_with_state(app.clone(), rejections_as_pages))
4062923×
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
4072923×
        .layer(CompressionLayer::new())
4082923×
        .layer(TraceLayer::new_for_http())
4092923×
        .with_state(app)
4102923×
}
411
412
// Git's smart HTTP paths under `/{owner}/{name}.git/`, forwarded to the
413
// mirror (hub spec §14).
4145×
async fn git_info(
4155×
    st: axum::extract::State<Shared>,
4165×
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
4175×
    m: axum::http::Method,
4185×
    q: axum::extract::RawQuery,
4195×
    h: axum::http::HeaderMap,
4205×
    b: axum::body::Bytes,
4215×
) -> Response {
4225×
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await
4235×
}
424
4250×
async fn git_head(
4260×
    st: axum::extract::State<Shared>,
4270×
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
4280×
    m: axum::http::Method,
4290×
    q: axum::extract::RawQuery,
4300×
    h: axum::http::HeaderMap,
4310×
    b: axum::body::Bytes,
4320×
) -> Response {
4330×
    crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await
4340×
}
435
4360×
async fn git_objects(
4370×
    st: axum::extract::State<Shared>,
4380×
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
4390×
    m: axum::http::Method,
4400×
    q: axum::extract::RawQuery,
4410×
    h: axum::http::HeaderMap,
4420×
    b: axum::body::Bytes,
4430×
) -> Response {
4440×
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await
4450×
}
446
4475×
async fn git_upload_pack(
4485×
    st: axum::extract::State<Shared>,
4495×
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
4505×
    m: axum::http::Method,
4515×
    q: axum::extract::RawQuery,
4525×
    h: axum::http::HeaderMap,
4535×
    b: axum::body::Bytes,
4545×
) -> Response {
4555×
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await
4565×
}
457
4580×
async fn git_receive_pack(
4590×
    st: axum::extract::State<Shared>,
4600×
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
4610×
    m: axum::http::Method,
4620×
    q: axum::extract::RawQuery,
4630×
    h: axum::http::HeaderMap,
4640×
    b: axum::body::Bytes,
4650×
) -> Response {
4660×
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await
4670×
}
468
469
/// Cross-site form posts are refused (hub spec §15.2): a browser that
470
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
471
/// API clients send neither.
4723949×
async fn same_origin(
4733949×
    axum::extract::State(app): axum::extract::State<Shared>,
4743949×
    req: axum::extract::Request,
4753949×
    next: axum::middleware::Next,
4763949×
) -> Response {
4773949×
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
4781891×
        let headers = req.headers();
4791891×
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
4800×
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
4811891×
        }
4821891×
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
4830×
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
4840×
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
4850×
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
4860×
            if !ok && origin != "null" {
4870×
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
4880×
            }
4891891×
        }
4902058×
    }
4913949×
    next.run(req).await
4923949×
}
493
494
/// What every page's chrome needs.
495
#[derive(Clone, Debug)]
496
pub struct Shell {
497
    pub site: String,
498
    pub base_url: String,
499
    pub path: String,
500
    pub version: &'static str,
501
    /// What was built: `oxy describe` at deploy, a Flow build's heads, or "local build".
502
    pub build: &'static str,
503
    /// The signed-in username, if any.
504
    pub user: Option<String>,
505
    pub is_admin: bool,
506
    pub csrf: String,
507
    pub unread: i64,
508
    /// The signed-in viewer's live topic, `user:<id>` (docs/live.md L4),
509
    /// or empty.
510
    pub live_user: String,
511
}
512
513
impl Shell {
514
    /// The version in the stylesheet and script URLs (`statics::assets_version`).
5155188×
    pub fn assets(&self) -> &'static str {
5165188×
        statics::assets_version()
5175188×
    }
518
5191692×
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
520
        Shell {
5211692×
            site: app.config.site.name.clone(),
5221692×
            base_url: app.config.base_url().to_string(),
5231692×
            path: path.to_string(),
524
            version: env!("CARGO_PKG_VERSION"),
525
            build: env!("OXY_BUILD_ID"),
5261692×
            user: viewer.account().map(|a| a.username.clone()),
5271692×
            is_admin: viewer.is_admin(),
5281692×
            csrf: viewer.csrf().to_string(),
5291692×
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
5301692×
            live_user: viewer.account().map(|a| format!("user:{}", a.id)).unwrap_or_default(),
531
        }
5321692×
    }
533
5340×
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
5350×
        Shell::new(app, path, &Viewer(None))
5360×
    }
537
}
538
539
/// The repository chrome: tabs and counts.
540
#[derive(Clone, Debug)]
541
pub struct RepoShell {
542
    /// The repository's row id: its live topics name it (docs/live.md).
543
    pub id: i64,
544
    pub owner: String,
545
    pub name: String,
546
    pub url: String,
547
    pub description: String,
548
    pub default_bookmark: String,
549
    pub visibility: String,
550
    pub tab: &'static str,
551
    pub clone_url: String,
552
    /// The Git mirror's address, when the mirror is on (oxygenhub#215).
553
    pub git_url: Option<String>,
554
    /// The viewer's role, for showing settings and write actions.
555
    pub role: Option<Role>,
556
    /// Open issues and proposals, shown on their tabs.
557
    pub open_issues: i64,
558
    pub open_proposals: i64,
559
    /// Read-only (#108).
560
    pub archived: bool,
561
    /// Whether the repository has a wiki (§6.11).
562
    pub wiki: bool,
563
    /// The bucket its data lives in, when not this hub's disk (#96), as
564
    /// the header's provider icon shows it (#123).
565
    pub stored_in: Option<crate::storage::StoreBadge>,
566
    /// Whether it has coverage reports, for the Coverage tab (#113).
567
    pub coverage: bool,
568
    /// Whether it has test reports, for the Tests tab (#114).
569
    pub tests: bool,
570
    /// Whether it has reports of its own (#127); with coverage or tests,
571
    /// the Reports tab.
572
    pub reports: bool,
573
    /// Whether it pins, or is pinned by, another repository here: the
574
    /// Diffusion tab (#150).
575
    pub diffusion: bool,
576
    /// The backdrop's data, a sky of this repository alone; empty for none
577
    /// (docs/backgrounds.md, oxygenhub#196).
578
    pub backdrop: String,
579
    /// A drop (#279): its pages show the drop's own bar, not the
580
    /// repository's tabs. Its title, for that bar.
581
    pub is_drop: bool,
582
    pub drop_title: String,
583
}
584
585
impl RepoShell {
586540×
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
587
        RepoShell {
588540×
            id: row.id,
589540×
            owner: row.owner.clone(),
590540×
            name: row.name.clone(),
591540×
            url: format!("/{}/{}", row.owner, row.name),
592540×
            description: row.description.clone(),
593540×
            default_bookmark: row.default_bookmark.clone(),
594540×
            visibility: row.visibility.clone(),
595540×
            tab,
596540×
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
597540×
            git_url: row.git_mirror.then(|| format!("{}/{}/{}.git", app.config.base_url(), row.owner, row.name)),
598540×
            role: None,
599540×
            open_issues: row.open_issues,
600540×
            open_proposals: row.open_proposals,
601540×
            archived: row.archived,
602540×
            wiki: crate::repos::RepoName::new(&row.owner, &row.name).is_some_and(|n| app.wikis.exists(&n)),
603540×
            stored_in: crate::storage::location(app, &row.owner, &row.name).and_then(|u| crate::storage::StoreBadge::of(&u)),
604540×
            coverage: crate::coverage::has_reports(app, row.id),
605540×
            tests: crate::junit::has_reports(app, row.id),
606540×
            reports: crate::reports::has_reports(app, row.id),
607540×
            diffusion: crate::diffusion::involved(app, row.id),
608540×
            backdrop: String::new(),
609540×
            is_drop: row.is_drop(),
610540×
            drop_title: row.title.clone(),
611
        }
612540×
    }
613
614
    /// Give the page a backdrop: this repository's sky, its activity of the
615
    /// last 30 days from the database (#196).
616148×
    pub async fn with_sky(mut self, app: &Shared, row: &db::repos::RepoRow) -> RepoShell {
617148×
        self.backdrop = home::repo_sky(app, row).await;
618148×
        self
619148×
    }
620
621
    /// The repository's live topic (docs/live.md).
622116×
    pub fn live_topic(&self) -> String {
623116×
        crate::events::topic::repo(self.id)
624116×
    }
625
626
    /// Its Diffusion topic: bumps and pills.
6275×
    pub fn diffusion_topic(&self) -> String {
6285×
        crate::events::topic::diffusion(self.id)
6295×
    }
630
631540×
    pub fn with_role(mut self, role: Role) -> RepoShell {
632540×
        self.role = Some(role);
633540×
        self
634540×
    }
635
6361138×
    pub fn can(&self, access: Access) -> bool {
6371138×
        auth::roles::allows(self.role, access)
6381138×
    }
639
640517×
    pub fn can_maintain(&self) -> bool {
641517×
        self.can(Access::Maintain)
642517×
    }
643
}
644
645
/// Render a template as an HTML response.
646
/// One page of a long list: which page, how many, and links that keep
647
/// the rest of the query.
648
#[derive(Clone, Debug)]
649
pub struct Pager {
650
    pub page: usize,
651
    pub pages: usize,
652
    pub total: usize,
653
    /// The query without `page`, each pair encoded, joined with `&`.
654
    query: String,
655
}
656
657
impl Pager {
658
    pub const PER_PAGE: usize = 25;
659
660
    /// `page` counts from 1; out-of-range pages clamp to the last.
66112×
    pub fn new(total: usize, page: Option<usize>, query: &[(&str, &str)]) -> Pager {
66212×
        let pages = total.div_ceil(Self::PER_PAGE).max(1);
66312×
        let page = page.unwrap_or(1).clamp(1, pages);
66412×
        let query = query
66512×
            .iter()
66636×
            .filter(|(_, v)| !v.is_empty())
66730×
            .map(|(k, v)| format!("{k}={}", settings::urlencode(v).replace('/', "%2F")))
66812×
            .collect::<Vec<_>>()
66912×
            .join("&");
67012×
        Pager { page, pages, total, query }
67112×
    }
672
673
    /// This page's items.
67412×
    pub fn slice<T>(&self, all: Vec<T>) -> Vec<T> {
67512×
        all.into_iter().skip((self.page - 1) * Self::PER_PAGE).take(Self::PER_PAGE).collect()
67612×
    }
677
6783×
    pub fn url(&self, page: usize) -> String {
6793×
        if self.query.is_empty() {
6800×
            format!("?page={page}")
681
        } else {
6823×
            format!("?{}&page={page}", self.query)
683
        }
6843×
    }
685
686
    /// The same query with another sort, back on page one.
68743×
    pub fn sorted(&self, sort: &str) -> String {
688107×
        let rest: Vec<&str> = self.query.split('&').filter(|p| !p.is_empty() && !p.starts_with("sort=")).collect();
68943×
        let mut q = rest.join("&");
69043×
        if !q.is_empty() {
69143×
            q.push('&');
69243×
        }
69343×
        format!("?{q}sort={sort}")
69443×
    }
695
}
696
697
pub struct Page<T: Template>(pub T);
698
699
impl<T: Template> IntoResponse for Page<T> {
7001105×
    fn into_response(self) -> Response {
7011105×
        match self.0.render() {
7021105×
            Ok(s) => Html(s).into_response(),
7030×
            Err(e) => {
7040×
                tracing::error!("template: {e}");
7050×
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
706
            }
707
        }
7081105×
    }
709
}
710
711
#[derive(Template)]
712
#[template(path = "error.html")]
713
struct ErrorPage {
714
    shell: Shell,
715
    status: u16,
716
    title: String,
717
    detail: String,
718
}
719
720
/// A page-level failure, rendered inside the shell, or a redirect.
721
#[derive(Debug)]
722
pub struct Error {
723
    pub status: StatusCode,
724
    pub detail: String,
725
    shell: Option<Box<Shell>>,
726
    redirect: Option<String>,
727
}
728
729
impl Error {
73014×
    pub fn redirect(to: String) -> Error {
73114×
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
73214×
    }
733
73475×
    pub fn not_found(shell: Shell) -> Error {
73575×
        Error {
73675×
            status: StatusCode::NOT_FOUND,
73775×
            detail: "There is nothing at this address.".into(),
73875×
            shell: Some(Box::new(shell)),
73975×
            redirect: None,
74075×
        }
74175×
    }
742
74315×
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
74415×
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
74515×
    }
746
7473×
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
7481×
        match e {
7492×
            RepoError::NotFound => Error::not_found(shell),
7501×
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
7511×
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
752
            }
7530×
            other => {
7540×
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
755
            }
756
        }
7573×
    }
758
7590×
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
7600×
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
7610×
    }
762
}
763
764
impl IntoResponse for Error {
765105×
    fn into_response(self) -> Response {
766105×
        if let Some(to) = self.redirect {
76714×
            return Redirect::to(&to).into_response();
76891×
        }
76991×
        let title = match self.status {
77091×
            StatusCode::NOT_FOUND => "Not found",
77115×
            StatusCode::BAD_REQUEST => "Bad request",
7720×
            _ => "Something went wrong",
773
        };
77491×
        if self.status.is_server_error() {
7750×
            tracing::error!("{}", self.detail);
77691×
        }
77791×
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
77891×
            site: "OxygenHub".into(),
77991×
            base_url: String::new(),
78091×
            path: String::new(),
78191×
            version: "",
78291×
            build: "",
78391×
            user: None,
78491×
            is_admin: false,
78591×
            csrf: String::new(),
78691×
            unread: 0,
78791×
            live_user: String::new(),
78891×
        });
78991×
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
79091×
        match page.render() {
79191×
            Ok(s) => (self.status, Html(s)).into_response(),
7920×
            Err(_) => (self.status, title).into_response(),
793
        }
794105×
    }
795
}
796
797
/// A page address the router matched but could not read (a number that is
798
/// not one, a malformed query): axum answers that in plain text before any
799
/// handler runs. For pages, that is the site's not-found page instead
800
/// (#294); the oxy protocol and anything not asked for with GET or HEAD keep
801
/// the plain answer.
8023949×
async fn rejections_as_pages(
8033949×
    axum::extract::State(app): axum::extract::State<Shared>,
8043949×
    req: axum::extract::Request,
8053949×
    next: axum::middleware::Next,
8063949×
) -> Response {
8073949×
    let page = matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) && !req.uri().path().contains("/oxy/v1/");
8083949×
    if !page {
8092620×
        return next.run(req).await;
8101329×
    }
8111329×
    let (uri, headers) = (req.uri().clone(), req.headers().clone());
8121329×
    let res = next.run(req).await;
8131329×
    let plain = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/plain"));
8141329×
    if !(plain && matches!(res.status(), StatusCode::BAD_REQUEST | StatusCode::UNPROCESSABLE_ENTITY)) {
8151324×
        return res;
8165×
    }
817
    // Only axum's own rejections: a handler's plain 400 (the live stream's
818
    // "unknown topic") is the handler's answer and stays.
8195×
    let (head, body) = res.into_parts();
8205×
    let Ok(bytes) = axum::body::to_bytes(body, 4096).await else { return StatusCode::BAD_REQUEST.into_response() };
8215×
    let rejected = [&b"Invalid URL"[..], b"Failed to deserialize query string", b"Failed to deserialize the query string"]
8225×
        .iter()
8239×
        .any(|p| bytes.starts_with(p));
8245×
    if !rejected {
8252×
        return Response::from_parts(head, axum::body::Body::from(bytes));
8263×
    }
8273×
    let mut probe = axum::http::Request::builder().uri(uri.clone()).body(()).expect("a request");
8283×
    *probe.headers_mut() = headers;
8293×
    let (mut parts, ()) = probe.into_parts();
8303×
    let viewer = match <Viewer as axum::extract::FromRequestParts<Shared>>::from_request_parts(&mut parts, &app).await {
8313×
        Ok(v) => v,
832
        Err(never) => match never {},
833
    };
8343×
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
8353949×
}
836
8372×
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
8382×
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
8392×
}
840
841
/// A raw file response with a safe content type (hub spec §15.2).
84219×
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
84319×
    let mime = mime_of(name);
84419×
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
84519×
    (
84619×
        [
84719×
            (header::CONTENT_TYPE, mime.to_string()),
84819×
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
84919×
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
85019×
        ],
85119×
        bytes,
85219×
    )
85319×
        .into_response()
85419×
}
855
85626×
pub fn mime_of(name: &str) -> &'static str {
85726×
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
85826×
        Some("png") => "image/png",
85925×
        Some("jpg" | "jpeg") => "image/jpeg",
86025×
        Some("gif") => "image/gif",
86125×
        Some("webp") => "image/webp",
86225×
        Some("svg") => "image/svg+xml",
86325×
        Some("pdf") => "application/pdf",
864
        Some(
86525×
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
86624×
        ) => "text/plain; charset=utf-8",
8671×
        _ => "application/octet-stream",
868
    }
86926×
}
870
871
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
872
/// a repository the viewer may not see does not exist for them (hub spec
873
/// §4.4). Returns the viewer's role too.
874808×
pub async fn lookup_role(
875808×
    app: &Shared,
876808×
    shell: &Shell,
877808×
    viewer: &Viewer,
878808×
    owner: &str,
879808×
    name: &str,
880808×
    access: Access,
881808×
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
882808×
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
883808×
    let row = match db::repos::get(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))? {
884807×
        Some(row) => row,
885
        None => {
886
            // A transferred repository: the old URL goes to the new one (#108),
887
            // the rest of the path kept, when the viewer may see it.
8881×
            let moved = db::repos::moved_to(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))?;
8891×
            let Some(moved) = moved else { return Err(Error::not_found(shell.clone())) };
8901×
            let role = auth::roles::role_for(&app.db, viewer.account(), &moved).await.map_err(|e| Error::from_db(shell.clone(), e))?;
8911×
            if !auth::roles::allows(role, Access::Read) {
8920×
                return Err(Error::not_found(shell.clone()));
8931×
            }
8941×
            let old = format!("/{owner}/{name}");
8951×
            let rest = shell.path.strip_prefix(&old).unwrap_or("");
8961×
            return Err(Error::redirect(format!("/{}/{}{rest}", moved.owner, moved.name)));
897
        }
898
    };
899807×
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
900807×
    if !auth::roles::allows(role, access) {
90111×
        return Err(Error::not_found(shell.clone()));
902796×
    }
903
    // A drop's repository pages are read-only (its history, changes and
904
    // raw files, #279): it is changed from the drop's own page.
905796×
    if row.is_drop() && access != Access::Read {
9060×
        return Err(Error::not_found(shell.clone()));
907796×
    }
908796×
    if row.archived && matches!(access, Access::Write | Access::Maintain) {
9090×
        return Err(archived(shell));
910796×
    }
911796×
    Ok((repo, row, role.unwrap_or(Role::Read)))
912808×
}
913
914
/// The error for a write to an archived repository (#108).
9151×
pub fn archived(shell: &Shell) -> Error {
9161×
    Error::bad(shell.clone(), "This repository is archived and read-only. Its admins can bring it back under Settings › Advanced.")
9171×
}
918
919
/// Refuse a change to an archived repository, for handlers that open it
920
/// for reading and then write.
92135×
pub fn writable(row: &db::repos::RepoRow, shell: &Shell) -> Result<(), Error> {
92235×
    if row.archived {
9231×
        Err(archived(shell))
924
    } else {
92534×
        Ok(())
926
    }
92735×
}
928
929
/// `lookup_role` for reading.
930482×
pub async fn lookup(
931482×
    app: &Shared,
932482×
    shell: &Shell,
933482×
    viewer: &Viewer,
934482×
    owner: &str,
935482×
    name: &str,
936482×
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
937482×
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
938482×
}
939
940
/// Fill `account` on change authors whose key is linked to an account.
941117×
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
942117×
    if changes.is_empty() {
9433×
        return;
944114×
    }
945114×
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
946114×
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
947159×
    for c in changes.iter_mut() {
948159×
        if let Some(u) = map.get(&c.author.key) {
94973×
            c.author.account = Some(u.clone());
95086×
        }
951
    }
952117×
}
953
954
/// The part of a rendered page between `<!--frag:NAME-->` and
955
/// `<!--/frag:NAME-->` (live pages, docs/live.md): what a page fetches again
956
/// when its topic changes. `None` when the page has no such part.
9577×
pub fn fragment(html: &str, name: &str) -> Option<String> {
95831×
    if !name.bytes().all(|b| b.is_ascii_lowercase() || b == b'-') || name.is_empty() {
9591×
        return None;
9606×
    }
9616×
    let open = format!("<!--frag:{name}-->");
9626×
    let close = format!("<!--/frag:{name}-->");
9636×
    let start = html.find(&open)? + open.len();
9644×
    let end = start + html[start..].find(&close)?;
9654×
    Some(html[start..end].to_string())
9667×
}
967
968
#[cfg(test)]
969
mod fragment_tests {
970
    #[test]
9711×
    fn a_fragment_is_cut_from_the_page_by_its_markers() {
9721×
        let page = "<p>a</p><div data-fragment=\"x\"><!--frag:x--><b>inside</b><!--/frag:x--></div>";
9731×
        assert_eq!(super::fragment(page, "x").as_deref(), Some("<b>inside</b>"));
9741×
        assert_eq!(super::fragment(page, "y"), None);
9751×
        assert_eq!(super::fragment(page, "x--><b"), None, "names are plain");
9761×
    }
977
}