//! Pages (hub spec §6): the router, the shell every template extends, the //! error page, viewer-aware lookups and askama filters. Handlers are thin: //! they resolve names, call the view layer under the repository lock, and //! render. mod admin; mod artifacts; pub(crate) mod assistants; mod avatar; pub(crate) mod backups; pub mod board_charts; pub mod chain; pub mod charts; pub mod coverage; mod device; mod diffusion; mod drops; pub mod edit; pub mod filters; pub mod flow; mod forks; pub mod help; pub mod history; pub mod home; pub mod icons; mod insights; mod live_stream; mod security_txt; mod transparency; /// A state as people read it (oxygenhub#170): `02a6c9d4746a+… (14 heads)` /// for heads joined by `+`, which can run to hundreds of characters; a /// single head, or text that is not heads, unchanged. pub fn state_label(text: &str) -> String { let parts: Vec<&str> = text.split('+').collect(); let heads = parts.len() > 1 && parts.iter().all(|p| p.len() >= 7 && p.chars().all(|c| c.is_ascii_hexdigit())); if !heads { return text.to_string(); } format!("{}+… ({} heads)", &parts[0][..12.min(parts[0].len())], parts.len()) } mod inbox; pub mod issues; mod orgs; pub mod projects; pub mod proposals; mod recovery; mod refs; pub mod release_trust; pub mod releases; mod repo; mod repo_settings; pub mod reports; mod resolve; pub mod runner_updates; pub mod runners; mod secrets; mod session; pub(crate) mod settings; mod signin; mod statics; mod sudo; pub mod test_reports; mod variables; mod webhooks; mod wiki; use crate::auth::{self, Access, Role, Viewer}; use crate::repos::RepoError; use crate::{db, Shared}; use askama::Template; use axum::extract::DefaultBodyLimit; use axum::http::{header, StatusCode}; use axum::response::{Html, IntoResponse, Redirect, Response}; use axum::routing::{any, get, post}; use axum::Router; use tower_http::compression::CompressionLayer; use tower_http::trace::TraceLayer; pub fn router(app: Shared) -> Router { let push_limit = app.config.limits.push_body_limit.0 as usize; Router::new() .route("/", get(home::index)) .route("/explore", get(home::explore)) .route("/avatar/agent/{name}", get(avatar::agent)) .route("/avatar/{name}", get(avatar::avatar)) .route("/health", get(home::health)) .route("/about", get(home::about)) .route("/.well-known/oxyhub-key", get(home::hub_key)) .route("/.well-known/assetlinks.json", get(home::assetlinks)) .route("/metrics", get(crate::metrics::metrics)) .route("/log", get(transparency::page)) .route("/log/checkpoint", get(crate::tlog::checkpoint)) .route("/log/witnesses", get(crate::tlog::witnesses)) .route("/log/tile/{*path}", get(crate::tlog::tile)) .route("/log/witness/add-checkpoint", axum::routing::post(crate::tlog::add_checkpoint)) .route("/.well-known/oxyhub-ca.pem", get(home::hub_ca)) .route("/.well-known/oxyhub-signing.pem", get(flow::signing_key)) .route("/.well-known/openid-configuration", get(crate::oidc::discovery)) .route("/.well-known/jwks.json", get(crate::oidc::jwks)) .route("/live", get(live_stream::stream)) .route("/.well-known/security.txt", get(security_txt::serve)) .route("/security.txt", get(security_txt::serve)) .route("/security-contact", get(security_txt::contact_page)) .route("/style.css", get(statics::style)) .route("/favicon.svg", get(statics::favicon)) .route("/favicon.ico", get(statics::favicon)) .route("/static/{*path}", get(statics::asset)) .route("/login", get(session::login_form).post(session::login)) .route("/login/approval", post(session::approval_state)) .route("/sudo", get(sudo::show).post(sudo::confirm)) .route("/sudo/phone", post(sudo::ask_phone)) .route("/sudo/approval/{id}", get(sudo::approval_state)) .route("/device", get(device::form).post(device::answer)) .route(crate::headers::REPORT_PATH, post(crate::headers::csp_report).layer(DefaultBodyLimit::max(16 * 1024))) .route("/logout", post(session::logout)) .route("/register", get(session::register_form).post(session::register)) .route("/settings", get(settings::profile).post(settings::update_profile)) .route("/settings/password", post(settings::change_password)) .route("/settings/appearance", post(settings::appearance)) .route("/settings/security", get(settings::security)) .route("/settings/security/totp/begin", post(settings::totp_begin)) .route("/settings/security/totp/enable", post(settings::totp_enable)) .route("/settings/security/totp/disable", post(settings::totp_disable)) .route("/settings/security/sessions", post(settings::sessions_reset)) .route("/settings/security/sessions/{id}/end", post(settings::session_end)) .route("/settings/security/phones/{id}/remove", post(settings::phone_remove)) .route("/settings/keys", get(settings::keys)) .route("/settings/keys/upload", post(settings::keys_upload)) .route("/settings/keys/verify", post(settings::keys_verify)) .route("/settings/keys/unlink", post(settings::keys_unlink)) .route("/settings/tokens", get(settings::tokens).post(settings::tokens_create)) .route("/sky/arrivals", get(home::arrivals)) .route("/settings/backups", get(backups::user).post(backups::user_save)) .route("/settings/backups/run", post(backups::user_run)) .route("/settings/backups/test", post(backups::user_test)) .route("/orgs/{name}/settings/backups", get(backups::org).post(backups::org_save)) .route("/orgs/{name}/settings/backups/run", post(backups::org_run)) .route("/orgs/{name}/settings/backups/test", post(backups::org_test)) .route("/settings/tokens/{id}/delete", post(settings::tokens_delete)) .route("/settings/tokens/{id}/agent", post(settings::tokens_agent)) .route("/new", get(repo_settings::new_form).post(repo_settings::create)) .route("/new/check", get(repo_settings::check_name)) .route("/orgs/new", get(orgs::new_form).post(orgs::create)) .route("/orgs/{name}/settings", get(orgs::settings).post(orgs::update)) .route("/orgs/{name}/settings/members", post(orgs::member)) .route("/orgs/{name}/settings/teams", post(orgs::team)) .route("/orgs/{name}/settings/hooks", post(orgs::hooks)) .route("/orgs/{name}/settings/assistants", post(orgs::assistants)) .route("/orgs/{name}/settings/assistants/models", post(orgs::assistant_models)) .route("/orgs/{name}/settings/variables", post(orgs::variables)) .route("/orgs/{name}/settings/secrets", post(orgs::secrets)) .route("/orgs/{name}/settings/storage", post(orgs::storage)) .route("/orgs/{name}/settings/flow-priority", post(orgs::flow_priority)) .route("/orgs/{name}/settings/runners/token", post(orgs::runner_token)) .route("/orgs/{name}/settings/runners/{id}/remove", post(orgs::runner_remove)) .route("/orgs/{name}/settings/runners/updates/policy", post(orgs::runner_updates_policy)) .route("/orgs/{name}/settings/runners/updates/groups", post(orgs::runner_updates_group_new)) .route("/orgs/{name}/settings/runners/updates/groups/{id}", post(orgs::runner_updates_group)) .route("/orgs/{name}/settings/runners/updates/groups/{id}/delete", post(orgs::runner_updates_group_delete)) .route("/orgs/{name}/settings/hooks/{id}/deliveries", get(orgs::deliveries)) .route("/orgs/{name}/settings/hooks/{id}/redeliver/{delivery}", post(orgs::redeliver)) .route("/orgs/{name}/settings/avatar", post(orgs::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10)))) .route("/settings/avatar", post(settings::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10)))) .route("/notifications", get(inbox::inbox)) .route("/notifications/read", post(inbox::mark_read)) .route("/settings/notifications", get(inbox::unsubscribe).post(inbox::prefs)) .route("/search", get(inbox::search)) .route("/admin", get(admin::index)) .route("/admin/accounts", get(admin::section)) .route("/admin/organisations", get(admin::section)) .route("/admin/audit", get(admin::section)) .route("/admin/registration", get(admin::section).post(admin::set_mode)) .route("/admin/invite", post(admin::invite)) .route("/admin/account", post(admin::account)) .route("/admin/storage", get(admin::storage).post(admin::maintain)) .route("/admin/runners", get(runners::list)) .route("/admin/runners/settings", get(runners::settings).post(runners::save_settings)) .route("/admin/runners/priority", post(runners::save_priority)) .route("/admin/runners/images", get(runners::images)) .route("/admin/runners/updates", get(runner_updates::show)) .route("/admin/runners/updates/source", post(runner_updates::save_source)) .route("/admin/runners/updates/policy", post(runner_updates::save_policy)) .route("/admin/runners/updates/groups", post(runner_updates::create_group)) .route("/admin/runners/updates/holds/lift", post(runner_updates::lift_hold)) .route("/admin/runners/updates/groups/{id}", post(runner_updates::save_group)) .route("/admin/runners/updates/groups/{id}/delete", post(runner_updates::delete_group)) .route("/admin/insights", get(insights::site)) .route("/insights/{owner}", get(insights::owner)) .route("/admin/diffusion", get(diffusion::admin)) .route("/admin/backups", get(backups::admin)) .route("/{owner}/{name}/diffusion", get(diffusion::page)) .route("/admin/runners/token", post(runners::new_token)) .route("/admin/runners/{id}", get(runners::show)) .route("/admin/runners/{id}/state", post(runners::set_state)) .route("/admin/runners/{id}/scope", post(runners::set_scope)) .route("/admin/runners/{id}/limits", post(runners::set_limits)) .route("/admin/mail", get(admin::section).post(admin::set_mail)) .route("/admin/mail/test", post(admin::test_mail)) .route("/admin/assistants", get(admin::section).post(admin::assistants)) .route("/admin/assistants/models", post(admin::assistant_models)) .route("/admin/signin", get(admin::section).post(admin::signin)) .route("/admin/security", get(admin::section).post(security_txt::save)) .route("/login/{provider}", get(signin::start)) .route("/login/{provider}/callback", get(signin::callback)) .route("/settings/security/connect/{provider}", get(signin::connect)) .route("/settings/security/disconnect/{provider}", post(signin::disconnect)) .route("/admin/variables", get(admin::section).post(admin::variables)) .route("/admin/secrets", get(admin::section).post(admin::secrets)) .route("/admin/runners/{id}/remove", post(runners::remove)) .nest("/api/v1", crate::api::router(app.config.limits.asset_limit.0 as usize)) // Drops (#279): `drops` is reserved, as an owner and as a repository name. .route("/drops", get(drops::mine)) .route("/drops/new", get(drops::new_form).post(drops::create)) .route("/{owner}/drops", get(drops::list)) .route("/{owner}/drops/{id}", get(drops::show)) .route("/{owner}/drops/{id}/tree/{r}", get(drops::show_at)) .route("/{owner}/drops/{id}/edit", get(drops::edit_form).post(drops::save)) .route("/{owner}/drops/{id}/delete", post(drops::delete)) .route("/{owner}/drops/{id}/fork", post(drops::fork)) .route("/{owner}/drops/{id}/star", post(drops::star)) .route("/{owner}/drops/{id}/embed", get(drops::embed)) .route("/{owner}/drops/{id}/comment", post(drops::comment)) .route("/{owner}/drops/{id}/comment/{n}/delete", post(drops::delete_comment)) .route("/{owner}/drops/{id}/changes/{r}", get(drops::changes)) .route("/{owner}/drops/{id}/change/{hash}", get(drops::change)) .route("/{owner}/drops/{id}/raw/{r}/{*path}", get(drops::raw)) .route("/{owner}/drops/{id}/file/{r}/{*path}", get(drops::file)) .route("/{owner}/drops/{id}/oxy/v1/{endpoint}", any(crate::protocol::dispatch_drop).layer(DefaultBodyLimit::max(push_limit))) .route("/{owner}", get(home::owner)) .route("/{owner}/{name}", get(repo::overview)) .route("/{owner}/{name}/tree/{r}", get(repo::tree_root)) .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree)) .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file)) .route("/{owner}/{name}/function/{r}/{*path}", get(history::function)) .route("/{owner}/{name}/lanes/{r}", get(history::lanes)) .route("/{owner}/{name}/lanes/{r}/plan", post(history::plan)) .route("/{owner}/{name}/raw/{r}/{*path}", get(repo::raw_file)) .route("/{owner}/{name}/last/{r}", get(repo::last_changes)) .route("/{owner}/{name}/changes/{r}", get(history::history)) .route("/{owner}/{name}/change/{hash}", get(history::change)) .route("/apt", get(crate::apt::home)) .route("/apt/{file}", get(crate::apt::key)) .route("/apt/dists/{suite}/{*rest}", get(crate::apt::dists)) .route("/apt/pool/{*path}", get(crate::apt::pool)) .route("/help", get(help::help)) .route("/projects/{owner}", get(projects::list).post(projects::create)) .route("/projects/{owner}/{number}", get(projects::show).post(projects::act)) .route("/projects/{owner}/{number}/charts", get(board_charts::show)) .route("/notifications/thread", post(inbox::thread)) .route("/notifications/open/{id}", get(inbox::open)) .route("/login/reset", get(recovery::request_form).post(recovery::request)) .route("/login/reset/{secret}", get(recovery::new_password_form).post(recovery::set_new_password)) .route("/verify/{secret}", get(recovery::verify)) .route("/settings/email/verify", post(settings::resend_verification)) .route("/{owner}/{name}/compare", get(history::compare_index)) .route("/{owner}/{name}/compare/{spec}", get(history::compare)) .route("/{owner}/{name}/bookmarks", get(refs::bookmarks)) .route("/{owner}/{name}/bookmarks/delete", post(refs::delete_bookmark)) .route("/{owner}/{name}/bookmarks/create", post(refs::create_bookmark)) .route("/{owner}/{name}/tags", get(refs::tags)) .route("/{owner}/{name}/tags/create", post(refs::create_tag)) .route("/{owner}/{name}/tags/withdraw", post(refs::withdraw_tag)) .route("/{owner}/{name}/artifacts", get(artifacts::artifacts)) .route("/{owner}/{name}/images", get(artifacts::images)) .route("/{owner}/{name}/terraform", get(artifacts::terraform)) .route("/{owner}/{name}/insights", get(insights::repo)) .route("/{owner}/{name}/terraform/{state}/download", get(artifacts::download)) .route("/{owner}/{name}/terraform/{state}/restore", post(artifacts::restore)) .route("/{owner}/{name}/conflicts", get(refs::conflicts)) .route("/{owner}/{name}/trust", get(refs::trust)) .route("/{owner}/{name}/pushes", get(refs::pushes)) .route("/{owner}/{name}/fork", get(forks::form).post(forks::create)) .route("/{owner}/{name}/forks", get(forks::list)) .route("/{owner}/{name}/settings", get(repo_settings::settings).post(repo_settings::update)) // One page per setting (#278); some share their form's path. .route("/{owner}/{name}/settings/{page}", get(repo_settings::page)) .route("/{owner}/{name}/settings/collaborators", get(repo_settings::page).post(repo_settings::collaborator)) .route("/{owner}/{name}/settings/delete", post(repo_settings::delete)) .route("/{owner}/{name}/settings/transfer", post(repo_settings::transfer)) .route("/{owner}/{name}/settings/archive", post(repo_settings::archive)) .route("/{owner}/{name}/settings/wiki/delete", post(repo_settings::wiki_delete)) .route("/{owner}/{name}/wiki", get(wiki::home)) .route("/{owner}/{name}/wiki/_pages", get(wiki::pages)) .route("/{owner}/{name}/wiki/_new", get(wiki::new_form)) .route("/{owner}/{name}/wiki/_raw/{*path}", get(wiki::raw)) .route("/{owner}/{name}/wiki/{slug}", get(wiki::show)) .route("/{owner}/{name}/wiki/{slug}/edit", get(wiki::edit_form).post(wiki::save)) .route("/{owner}/{name}/wiki/{slug}/history", get(wiki::history)) .route("/{owner}/{name}/wiki/{slug}/delete", post(wiki::delete)) .route("/{owner}/{name}/settings/requirements", post(repo_settings::requirements)) .route("/{owner}/{name}/proposals", get(proposals::list)) .route("/{owner}/{name}/proposals/new", get(proposals::new_form).post(proposals::create)) .route("/{owner}/{name}/proposals/new/draft", post(proposals::new_draft)) .route("/{owner}/{name}/proposals/new/draft/stream", post(proposals::new_draft_stream)) .route("/{owner}/{name}/proposal/{number}", get(proposals::show)) .route("/{owner}/{name}/proposal/{number}/comment", post(proposals::comment)) .route("/{owner}/{name}/proposal/{number}/comment/{id}/resolve", post(proposals::resolve_comment)) .route("/{owner}/{name}/proposal/{number}/resolve", post(proposals::resolve_on_web)) .route("/{owner}/{name}/proposal/{number}/review", post(proposals::review)) .route("/{owner}/{name}/proposal/{number}/reviewers", post(proposals::reviewers)) .route("/{owner}/{name}/proposal/{number}/assistant", post(proposals::assistant)) .route("/{owner}/{name}/proposal/{number}/draft", post(proposals::draft)) .route("/{owner}/{name}/proposal/{number}/draft/stream", post(proposals::draft_stream)) .route("/{owner}/{name}/proposal/{number}/edit", post(proposals::edit)) .route("/{owner}/{name}/proposal/{number}/state", post(proposals::state)) .route("/{owner}/{name}/proposal/{number}/land", post(proposals::land)) .route("/{owner}/{name}/proposal/{number}/auto-land", post(proposals::auto_land)) .route("/{owner}/{name}/proposal/{number}/labels", post(proposals::set_labels)) .route("/{owner}/{name}/proposal/{number}/project", post(projects::place_proposal)) .route("/{owner}/{name}/issue/{number}/project", post(projects::place_issue)) .route("/{owner}/{name}/proposal/{number}/events", get(proposals::events)) .route("/{owner}/{name}/settings/hooks", post(repo_settings::hooks)) .route("/{owner}/{name}/settings/assistants", get(repo_settings::page).post(repo_settings::assistants)) .route("/{owner}/{name}/settings/assistants/models", post(repo_settings::assistant_models)) .route("/{owner}/{name}/settings/variables", get(repo_settings::page).post(repo_settings::variables)) .route("/{owner}/{name}/settings/secrets", get(repo_settings::page).post(repo_settings::secrets)) .route("/{owner}/{name}/settings/hooks/{id}/deliveries", get(repo_settings::deliveries)) .route("/{owner}/{name}/settings/hooks/{id}/redeliver/{delivery}", post(repo_settings::redeliver)) .route("/{owner}/{name}/settings/checks", get(repo_settings::page).post(repo_settings::required_checks)) .route("/{owner}/{name}/watch", post(issues::watch)) .route("/{owner}/{name}/star", post(issues::star)) .route("/{owner}/{name}/edit/{r}", post(edit::save)) .route("/{owner}/{name}/edit/{r}/{*path}", get(edit::edit_form)) .route("/{owner}/{name}/resolve/{bookmark}/{*path}", get(resolve::form).post(resolve::save)) .route("/{owner}/{name}/resolve-live/{bookmark}/{*path}", get(resolve::live_events).post(resolve::live_choose)) .route("/{owner}/{name}/newfile/{r}", get(edit::new_form)) .route("/{owner}/{name}/flow", get(flow::runs)) .route("/{owner}/{name}/flow/badge.svg", get(flow::badge)) .route("/{owner}/{name}/flow/tab", get(flow::tab)) .route("/{owner}/{name}/tests", get(test_reports::overview)) .route("/{owner}/{name}/tests/case", get(test_reports::case)) .route("/{owner}/{name}/reports", get(reports::overview)) .route("/{owner}/{name}/reports/files/{id}/{mac}/{*path}", get(reports::file)) .route("/{owner}/{name}/reports/{report}", get(reports::show)) .route("/{owner}/{name}/coverage", get(coverage::overview)) .route("/{owner}/{name}/coverage/badge.svg", get(coverage::badge)) .route("/{owner}/{name}/coverage/{id}/file/{*path}", get(coverage::file)) .route("/{owner}/{name}/deployments", get(flow::deployments)) .route("/{owner}/{name}/flow/{id}", get(flow::run)) .route("/{owner}/{name}/flow/{id}/live", get(flow::live)) .route("/{owner}/{name}/flow/start", post(flow::start)) .route("/{owner}/{name}/flow/{id}/rerun", post(flow::rerun)) .route("/{owner}/{name}/flow/{id}/jobs/{job}/rerun", post(flow::rerun_job)) .route("/{owner}/{name}/flow/{id}/jobs/{job}/decide", post(flow::decide)) .route("/{owner}/{name}/flow/{id}/cancel", post(flow::cancel)) .route("/{owner}/{name}/flow/{id}/expedite", post(flow::expedite)) .route("/{owner}/{name}/flow/stamp/{r}", get(flow::stamp)) .route("/{owner}/{name}/flow/at/{r}", get(flow::at)) .route("/{owner}/{name}/receipts/{attest}", get(flow::receipt_file)) .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}", get(flow::artifact_file)) .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/attach", post(flow::attach)) .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/provenance", get(flow::provenance)) .route("/{owner}/{name}/releases", get(releases::list)) .route("/{owner}/{name}/releases/new", get(releases::new_form).post(releases::create)) .route("/{owner}/{name}/releases/tag/{*tag}", get(releases::show)) .route("/{owner}/{name}/releases/download/{tag}/{file}", get(releases::download_by_tag)) .route("/{owner}/{name}/releases/trust/{*tag}", get(release_trust::page)) .route("/{owner}/{name}/releases/edit/{id}", post(releases::edit)) .route( "/{owner}/{name}/releases/upload/{id}", post(releases::upload).layer(DefaultBodyLimit::max(app.config.limits.asset_limit.0 as usize + (1 << 20))), ) .route("/{owner}/{name}/asset/{id}/{file}", get(releases::download)) .route("/{owner}/{name}/attachments/{id}/{file}", get(releases::attachment)) .route("/{owner}/{name}/archive", get(releases::source_archive)) .route("/{owner}/{name}/search", get(repo::code_search)) .route("/{owner}/{name}/info/{*rest}", any(git_info)) .route("/{owner}/{name}/HEAD", get(git_head)) .route("/{owner}/{name}/objects/{*rest}", get(git_objects)) .route("/{owner}/{name}/git-upload-pack", post(git_upload_pack)) .route("/{owner}/{name}/git-receive-pack", post(git_receive_pack)) .route("/{owner}/{name}/settings/mirror", post(repo_settings::mirror)) .route("/{owner}/{name}/settings/flow", get(repo_settings::page).post(repo_settings::flow)) .route("/{owner}/{name}/settings/flow-priority", post(repo_settings::flow_priority)) .route("/{owner}/{name}/settings/agent-gates", post(repo_settings::agent_gates)) .route("/{owner}/{name}/settings/push-protection", get(repo_settings::page).post(repo_settings::push_protection)) .route("/{owner}/{name}/settings/secret-bypass", post(repo_settings::secret_bypass)) .route("/{owner}/{name}/settings/secret-bypass/remove", post(repo_settings::secret_bypass_remove)) .route("/{owner}/{name}/settings/secret-resolve", post(repo_settings::secret_resolve)) .route("/{owner}/{name}/settings/secret-scan", post(repo_settings::secret_scan)) .route("/{owner}/{name}/settings/flow-supersede", post(repo_settings::flow_supersede)) .route("/{owner}/{name}/settings/flow-skip", post(repo_settings::flow_skip)) .route("/{owner}/{name}/settings/flow-reuse", post(repo_settings::flow_reuse)) .route("/{owner}/{name}/settings/diffusion", get(repo_settings::page).post(repo_settings::diffusion)) .route("/{owner}/{name}/settings/backup", get(repo_settings::page).post(repo_settings::backup)) .route("/{owner}/{name}/settings/storage", get(repo_settings::page).post(repo_settings::storage)) .route("/{owner}/{name}/settings/coverage", get(repo_settings::page).post(repo_settings::coverage)) .route("/{owner}/{name}/settings/runners/token", post(repo_settings::runner_token)) .route("/{owner}/{name}/settings/runners/{id}/remove", post(repo_settings::runner_remove)) .route("/{owner}/{name}/issues", get(issues::list)) .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create)) .route("/{owner}/{name}/issue/{number}", get(issues::show)) .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment)) .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment)) .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit)) .route("/{owner}/{name}/issue/{number}/state", post(issues::state)) .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels)) .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign)) .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone)) .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe)) .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label)) .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone)) .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit))) .fallback(not_found) .layer(axum::middleware::from_fn_with_state(app.clone(), sudo::gate)) .layer(axum::middleware::from_fn_with_state(app.clone(), rejections_as_pages)) .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin)) .layer(CompressionLayer::new()) .layer(TraceLayer::new_for_http()) .with_state(app) } // Git's smart HTTP paths under `/{owner}/{name}.git/`, forwarded to the // mirror (hub spec §14). async fn git_info( st: axum::extract::State, axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>, m: axum::http::Method, q: axum::extract::RawQuery, h: axum::http::HeaderMap, b: axum::body::Bytes, ) -> Response { crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await } async fn git_head( st: axum::extract::State, axum::extract::Path((o, n)): axum::extract::Path<(String, String)>, m: axum::http::Method, q: axum::extract::RawQuery, h: axum::http::HeaderMap, b: axum::body::Bytes, ) -> Response { crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await } async fn git_objects( st: axum::extract::State, axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>, m: axum::http::Method, q: axum::extract::RawQuery, h: axum::http::HeaderMap, b: axum::body::Bytes, ) -> Response { crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await } async fn git_upload_pack( st: axum::extract::State, axum::extract::Path((o, n)): axum::extract::Path<(String, String)>, m: axum::http::Method, q: axum::extract::RawQuery, h: axum::http::HeaderMap, b: axum::body::Bytes, ) -> Response { crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await } async fn git_receive_pack( st: axum::extract::State, axum::extract::Path((o, n)): axum::extract::Path<(String, String)>, m: axum::http::Method, q: axum::extract::RawQuery, h: axum::http::HeaderMap, b: axum::body::Bytes, ) -> Response { crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await } /// Cross-site form posts are refused (hub spec §15.2): a browser that /// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and /// API clients send neither. async fn same_origin( axum::extract::State(app): axum::extract::State, req: axum::extract::Request, next: axum::middleware::Next, ) -> Response { if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD { let headers = req.headers(); if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") { return (StatusCode::FORBIDDEN, "cross-site request refused").into_response(); } if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) { let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase(); let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase()); let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str()); if !ok && origin != "null" { return (StatusCode::FORBIDDEN, "cross-site request refused").into_response(); } } } next.run(req).await } /// What every page's chrome needs. #[derive(Clone, Debug)] pub struct Shell { pub site: String, pub base_url: String, pub path: String, pub version: &'static str, /// What was built: `oxy describe` at deploy, a Flow build's heads, or "local build". pub build: &'static str, /// The signed-in username, if any. pub user: Option, pub is_admin: bool, pub csrf: String, pub unread: i64, /// The signed-in viewer's live topic, `user:` (docs/live.md L4), /// or empty. pub live_user: String, } impl Shell { /// The version in the stylesheet and script URLs (`statics::assets_version`). pub fn assets(&self) -> &'static str { statics::assets_version() } pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell { Shell { site: app.config.site.name.clone(), base_url: app.config.base_url().to_string(), path: path.to_string(), version: env!("CARGO_PKG_VERSION"), build: env!("OXY_BUILD_ID"), user: viewer.account().map(|a| a.username.clone()), is_admin: viewer.is_admin(), csrf: viewer.csrf().to_string(), unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0), live_user: viewer.account().map(|a| format!("user:{}", a.id)).unwrap_or_default(), } } pub fn anonymous(app: &Shared, path: &str) -> Shell { Shell::new(app, path, &Viewer(None)) } } /// The repository chrome: tabs and counts. #[derive(Clone, Debug)] pub struct RepoShell { /// The repository's row id: its live topics name it (docs/live.md). pub id: i64, pub owner: String, pub name: String, pub url: String, pub description: String, pub default_bookmark: String, pub visibility: String, pub tab: &'static str, pub clone_url: String, /// The Git mirror's address, when the mirror is on (oxygenhub#215). pub git_url: Option, /// The viewer's role, for showing settings and write actions. pub role: Option, /// Open issues and proposals, shown on their tabs. pub open_issues: i64, pub open_proposals: i64, /// Read-only (#108). pub archived: bool, /// Whether the repository has a wiki (§6.11). pub wiki: bool, /// The bucket its data lives in, when not this hub's disk (#96), as /// the header's provider icon shows it (#123). pub stored_in: Option, /// Whether it has coverage reports, for the Coverage tab (#113). pub coverage: bool, /// Whether it has test reports, for the Tests tab (#114). pub tests: bool, /// Whether it has reports of its own (#127); with coverage or tests, /// the Reports tab. pub reports: bool, /// Whether it pins, or is pinned by, another repository here: the /// Diffusion tab (#150). pub diffusion: bool, /// The backdrop's data, a sky of this repository alone; empty for none /// (docs/backgrounds.md, oxygenhub#196). pub backdrop: String, /// A drop (#279): its pages show the drop's own bar, not the /// repository's tabs. Its title, for that bar. pub is_drop: bool, pub drop_title: String, } impl RepoShell { pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell { RepoShell { id: row.id, owner: row.owner.clone(), name: row.name.clone(), url: format!("/{}/{}", row.owner, row.name), description: row.description.clone(), default_bookmark: row.default_bookmark.clone(), visibility: row.visibility.clone(), tab, clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name), git_url: row.git_mirror.then(|| format!("{}/{}/{}.git", app.config.base_url(), row.owner, row.name)), role: None, open_issues: row.open_issues, open_proposals: row.open_proposals, archived: row.archived, wiki: crate::repos::RepoName::new(&row.owner, &row.name).is_some_and(|n| app.wikis.exists(&n)), stored_in: crate::storage::location(app, &row.owner, &row.name).and_then(|u| crate::storage::StoreBadge::of(&u)), coverage: crate::coverage::has_reports(app, row.id), tests: crate::junit::has_reports(app, row.id), reports: crate::reports::has_reports(app, row.id), diffusion: crate::diffusion::involved(app, row.id), backdrop: String::new(), is_drop: row.is_drop(), drop_title: row.title.clone(), } } /// Give the page a backdrop: this repository's sky, its activity of the /// last 30 days from the database (#196). pub async fn with_sky(mut self, app: &Shared, row: &db::repos::RepoRow) -> RepoShell { self.backdrop = home::repo_sky(app, row).await; self } /// The repository's live topic (docs/live.md). pub fn live_topic(&self) -> String { crate::events::topic::repo(self.id) } /// Its Diffusion topic: bumps and pills. pub fn diffusion_topic(&self) -> String { crate::events::topic::diffusion(self.id) } pub fn with_role(mut self, role: Role) -> RepoShell { self.role = Some(role); self } pub fn can(&self, access: Access) -> bool { auth::roles::allows(self.role, access) } pub fn can_maintain(&self) -> bool { self.can(Access::Maintain) } } /// Render a template as an HTML response. /// One page of a long list: which page, how many, and links that keep /// the rest of the query. #[derive(Clone, Debug)] pub struct Pager { pub page: usize, pub pages: usize, pub total: usize, /// The query without `page`, each pair encoded, joined with `&`. query: String, } impl Pager { pub const PER_PAGE: usize = 25; /// `page` counts from 1; out-of-range pages clamp to the last. pub fn new(total: usize, page: Option, query: &[(&str, &str)]) -> Pager { let pages = total.div_ceil(Self::PER_PAGE).max(1); let page = page.unwrap_or(1).clamp(1, pages); let query = query .iter() .filter(|(_, v)| !v.is_empty()) .map(|(k, v)| format!("{k}={}", settings::urlencode(v).replace('/', "%2F"))) .collect::>() .join("&"); Pager { page, pages, total, query } } /// This page's items. pub fn slice(&self, all: Vec) -> Vec { all.into_iter().skip((self.page - 1) * Self::PER_PAGE).take(Self::PER_PAGE).collect() } pub fn url(&self, page: usize) -> String { if self.query.is_empty() { format!("?page={page}") } else { format!("?{}&page={page}", self.query) } } /// The same query with another sort, back on page one. pub fn sorted(&self, sort: &str) -> String { let rest: Vec<&str> = self.query.split('&').filter(|p| !p.is_empty() && !p.starts_with("sort=")).collect(); let mut q = rest.join("&"); if !q.is_empty() { q.push('&'); } format!("?{q}sort={sort}") } } pub struct Page(pub T); impl IntoResponse for Page { fn into_response(self) -> Response { match self.0.render() { Ok(s) => Html(s).into_response(), Err(e) => { tracing::error!("template: {e}"); (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response() } } } } #[derive(Template)] #[template(path = "error.html")] struct ErrorPage { shell: Shell, status: u16, title: String, detail: String, } /// A page-level failure, rendered inside the shell, or a redirect. #[derive(Debug)] pub struct Error { pub status: StatusCode, pub detail: String, shell: Option>, redirect: Option, } impl Error { pub fn redirect(to: String) -> Error { Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) } } pub fn not_found(shell: Shell) -> Error { Error { status: StatusCode::NOT_FOUND, detail: "There is nothing at this address.".into(), shell: Some(Box::new(shell)), redirect: None, } } pub fn bad(shell: Shell, detail: impl Into) -> Error { Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None } } pub fn from_repo(shell: Shell, e: RepoError) -> Error { match e { RepoError::NotFound => Error::not_found(shell), RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => { Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None } } other => { Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None } } } } pub fn from_db(shell: Shell, e: sqlx::Error) -> Error { Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None } } } impl IntoResponse for Error { fn into_response(self) -> Response { if let Some(to) = self.redirect { return Redirect::to(&to).into_response(); } let title = match self.status { StatusCode::NOT_FOUND => "Not found", StatusCode::BAD_REQUEST => "Bad request", _ => "Something went wrong", }; if self.status.is_server_error() { tracing::error!("{}", self.detail); } let shell = self.shell.map(|b| *b).unwrap_or(Shell { site: "OxygenHub".into(), base_url: String::new(), path: String::new(), version: "", build: "", user: None, is_admin: false, csrf: String::new(), unread: 0, live_user: String::new(), }); let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail }; match page.render() { Ok(s) => (self.status, Html(s)).into_response(), Err(_) => (self.status, title).into_response(), } } } /// A page address the router matched but could not read (a number that is /// not one, a malformed query): axum answers that in plain text before any /// handler runs. For pages, that is the site's not-found page instead /// (#294); the oxy protocol and anything not asked for with GET or HEAD keep /// the plain answer. async fn rejections_as_pages( axum::extract::State(app): axum::extract::State, req: axum::extract::Request, next: axum::middleware::Next, ) -> Response { let page = matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) && !req.uri().path().contains("/oxy/v1/"); if !page { return next.run(req).await; } let (uri, headers) = (req.uri().clone(), req.headers().clone()); let res = next.run(req).await; let plain = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/plain")); if !(plain && matches!(res.status(), StatusCode::BAD_REQUEST | StatusCode::UNPROCESSABLE_ENTITY)) { return res; } // Only axum's own rejections: a handler's plain 400 (the live stream's // "unknown topic") is the handler's answer and stays. let (head, body) = res.into_parts(); let Ok(bytes) = axum::body::to_bytes(body, 4096).await else { return StatusCode::BAD_REQUEST.into_response() }; let rejected = [&b"Invalid URL"[..], b"Failed to deserialize query string", b"Failed to deserialize the query string"] .iter() .any(|p| bytes.starts_with(p)); if !rejected { return Response::from_parts(head, axum::body::Body::from(bytes)); } let mut probe = axum::http::Request::builder().uri(uri.clone()).body(()).expect("a request"); *probe.headers_mut() = headers; let (mut parts, ()) = probe.into_parts(); let viewer = match >::from_request_parts(&mut parts, &app).await { Ok(v) => v, Err(never) => match never {}, }; Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response() } async fn not_found(axum::extract::State(app): axum::extract::State, viewer: Viewer, uri: axum::http::Uri) -> Response { Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response() } /// A raw file response with a safe content type (hub spec §15.2). pub fn raw(bytes: Vec, name: &str, inline_image: bool) -> Response { let mime = mime_of(name); let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" }; ( [ (header::CONTENT_TYPE, mime.to_string()), (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))), (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()), ], bytes, ) .into_response() } pub fn mime_of(name: &str) -> &'static str { match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() { Some("png") => "image/png", Some("jpg" | "jpeg") => "image/jpeg", Some("gif") => "image/gif", Some("webp") => "image/webp", Some("svg") => "image/svg+xml", Some("pdf") => "application/pdf", Some( "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh", ) => "text/plain; charset=utf-8", _ => "application/octet-stream", } } /// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404: /// a repository the viewer may not see does not exist for them (hub spec /// §4.4). Returns the viewer's role too. pub async fn lookup_role( app: &Shared, shell: &Shell, viewer: &Viewer, owner: &str, name: &str, access: Access, ) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> { let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?; let row = match db::repos::get(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))? { Some(row) => row, None => { // A transferred repository: the old URL goes to the new one (#108), // the rest of the path kept, when the viewer may see it. let moved = db::repos::moved_to(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))?; let Some(moved) = moved else { return Err(Error::not_found(shell.clone())) }; let role = auth::roles::role_for(&app.db, viewer.account(), &moved).await.map_err(|e| Error::from_db(shell.clone(), e))?; if !auth::roles::allows(role, Access::Read) { return Err(Error::not_found(shell.clone())); } let old = format!("/{owner}/{name}"); let rest = shell.path.strip_prefix(&old).unwrap_or(""); return Err(Error::redirect(format!("/{}/{}{rest}", moved.owner, moved.name))); } }; let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?; if !auth::roles::allows(role, access) { return Err(Error::not_found(shell.clone())); } // A drop's repository pages are read-only (its history, changes and // raw files, #279): it is changed from the drop's own page. if row.is_drop() && access != Access::Read { return Err(Error::not_found(shell.clone())); } if row.archived && matches!(access, Access::Write | Access::Maintain) { return Err(archived(shell)); } Ok((repo, row, role.unwrap_or(Role::Read))) } /// The error for a write to an archived repository (#108). pub fn archived(shell: &Shell) -> Error { Error::bad(shell.clone(), "This repository is archived and read-only. Its admins can bring it back under Settings › Advanced.") } /// Refuse a change to an archived repository, for handlers that open it /// for reading and then write. pub fn writable(row: &db::repos::RepoRow, shell: &Shell) -> Result<(), Error> { if row.archived { Err(archived(shell)) } else { Ok(()) } } /// `lookup_role` for reading. pub async fn lookup( app: &Shared, shell: &Shell, viewer: &Viewer, owner: &str, name: &str, ) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> { lookup_role(app, shell, viewer, owner, name, Access::Read).await } /// Fill `account` on change authors whose key is linked to an account. pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) { if changes.is_empty() { return; } let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return }; let map: std::collections::HashMap = links.into_iter().collect(); for c in changes.iter_mut() { if let Some(u) = map.get(&c.author.key) { c.author.account = Some(u.clone()); } } } /// The part of a rendered page between `` and /// `` (live pages, docs/live.md): what a page fetches again /// when its topic changes. `None` when the page has no such part. pub fn fragment(html: &str, name: &str) -> Option { if !name.bytes().all(|b| b.is_ascii_lowercase() || b == b'-') || name.is_empty() { return None; } let open = format!(""); let close = format!(""); let start = html.find(&open)? + open.len(); let end = start + html[start..].find(&close)?; Some(html[start..end].to_string()) } #[cfg(test)] mod fragment_tests { #[test] fn a_fragment_is_cut_from_the_page_by_its_markers() { let page = "

a

inside
"; assert_eq!(super::fragment(page, "x").as_deref(), Some("inside")); assert_eq!(super::fragment(page, "y"), None); assert_eq!(super::fragment(page, "x-->