OXYGENHUB
# 1e8a6e8bb91b oxygenhub / crates / hub / src / web / mod.rs
34.2 KiB · Rust · last changed Admin › Backups: whether each owner's backup ran, and who has none 23 days ago source blame history raw
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
pub(crate) mod assistants;
8
mod avatar;
9
mod backups;
10
pub mod chain;
11
pub mod coverage;
12
mod device;
13
mod diffusion;
14
pub mod edit;
15
pub mod filters;
16
pub mod flow;
17
mod forks;
18
pub mod help;
19
pub mod history;
20
pub mod home;
21
pub mod icons;
22
mod inbox;
23
pub mod issues;
24
mod orgs;
25
pub mod projects;
26
pub mod proposals;
27
mod recovery;
28
mod refs;
29
pub mod release_trust;
30
pub mod releases;
31
mod repo;
32
mod repo_settings;
33
pub mod reports;
34
mod resolve;
35
pub mod runners;
36
mod secrets;
37
mod session;
38
pub(crate) mod settings;
39
mod signin;
40
mod statics;
41
pub mod test_reports;
42
mod variables;
43
mod webhooks;
44
mod wiki;
45
46
use crate::auth::{self, Access, Role, Viewer};
47
use crate::repos::RepoError;
48
use crate::{db, Shared};
49
use askama::Template;
50
use axum::extract::DefaultBodyLimit;
51
use axum::http::{header, StatusCode};
52
use axum::response::{Html, IntoResponse, Redirect, Response};
53
use axum::routing::{any, get, post};
54
use axum::Router;
55
use tower_http::compression::CompressionLayer;
56
use tower_http::trace::TraceLayer;
57
58
pub fn router(app: Shared) -> Router {
59
    let push_limit = app.config.limits.push_body_limit.0 as usize;
60
    Router::new()
61
        .route("/", get(home::index))
62
        .route("/explore", get(home::explore))
63
        .route("/avatar/agent/{name}", get(avatar::agent))
64
        .route("/avatar/{name}", get(avatar::avatar))
65
        .route("/health", get(home::health))
66
        .route("/about", get(home::about))
67
        .route("/.well-known/oxyhub-key", get(home::hub_key))
68
        .route("/.well-known/oxyhub-ca.pem", get(home::hub_ca))
69
        .route("/.well-known/openid-configuration", get(crate::oidc::discovery))
70
        .route("/.well-known/jwks.json", get(crate::oidc::jwks))
71
        .route("/style.css", get(statics::style))
72
        .route("/favicon.svg", get(statics::favicon))
73
        .route("/favicon.ico", get(statics::favicon))
74
        .route("/static/{*path}", get(statics::asset))
75
        .route("/login", get(session::login_form).post(session::login))
76
        .route("/device", get(device::form).post(device::answer))
77
        .route("/logout", post(session::logout))
78
        .route("/register", get(session::register_form).post(session::register))
79
        .route("/settings", get(settings::profile).post(settings::update_profile))
80
        .route("/settings/password", post(settings::change_password))
81
        .route("/settings/appearance", post(settings::appearance))
82
        .route("/settings/security", get(settings::security))
83
        .route("/settings/security/totp/begin", post(settings::totp_begin))
84
        .route("/settings/security/totp/enable", post(settings::totp_enable))
85
        .route("/settings/security/totp/disable", post(settings::totp_disable))
86
        .route("/settings/security/sessions", post(settings::sessions_reset))
87
        .route("/settings/keys", get(settings::keys))
88
        .route("/settings/keys/upload", post(settings::keys_upload))
89
        .route("/settings/keys/verify", post(settings::keys_verify))
90
        .route("/settings/keys/unlink", post(settings::keys_unlink))
91
        .route("/settings/tokens", get(settings::tokens).post(settings::tokens_create))
92
        .route("/settings/backups", get(backups::user).post(backups::user_save))
93
        .route("/settings/backups/run", post(backups::user_run))
94
        .route("/settings/backups/test", post(backups::user_test))
95
        .route("/orgs/{name}/settings/backups", get(backups::org).post(backups::org_save))
96
        .route("/orgs/{name}/settings/backups/run", post(backups::org_run))
97
        .route("/orgs/{name}/settings/backups/test", post(backups::org_test))
98
        .route("/settings/tokens/{id}/delete", post(settings::tokens_delete))
99
        .route("/new", get(repo_settings::new_form).post(repo_settings::create))
100
        .route("/orgs/new", get(orgs::new_form).post(orgs::create))
101
        .route("/orgs/{name}/settings", get(orgs::settings).post(orgs::update))
102
        .route("/orgs/{name}/settings/members", post(orgs::member))
103
        .route("/orgs/{name}/settings/teams", post(orgs::team))
104
        .route("/orgs/{name}/settings/hooks", post(orgs::hooks))
105
        .route("/orgs/{name}/settings/assistants", post(orgs::assistants))
106
        .route("/orgs/{name}/settings/assistants/models", post(orgs::assistant_models))
107
        .route("/orgs/{name}/settings/variables", post(orgs::variables))
108
        .route("/orgs/{name}/settings/secrets", post(orgs::secrets))
109
        .route("/orgs/{name}/settings/storage", post(orgs::storage))
110
        .route("/orgs/{name}/settings/runners/token", post(orgs::runner_token))
111
        .route("/orgs/{name}/settings/runners/{id}/remove", post(orgs::runner_remove))
112
        .route("/orgs/{name}/settings/hooks/{id}/deliveries", get(orgs::deliveries))
113
        .route("/orgs/{name}/settings/hooks/{id}/redeliver/{delivery}", post(orgs::redeliver))
114
        .route("/orgs/{name}/settings/avatar", post(orgs::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10))))
115
        .route("/settings/avatar", post(settings::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10))))
116
        .route("/notifications", get(inbox::inbox))
117
        .route("/notifications/read", post(inbox::mark_read))
118
        .route("/settings/notifications", get(inbox::unsubscribe).post(inbox::prefs))
119
        .route("/search", get(inbox::search))
120
        .route("/admin", get(admin::index))
121
        .route("/admin/registration", post(admin::set_mode))
122
        .route("/admin/invite", post(admin::invite))
123
        .route("/admin/account", post(admin::account))
124
        .route("/admin/storage", get(admin::storage).post(admin::maintain))
125
        .route("/admin/runners", get(runners::list))
126
        .route("/admin/runners/settings", get(runners::settings).post(runners::save_settings))
127
        .route("/admin/runners/images", get(runners::images))
128
        .route("/admin/diffusion", get(diffusion::admin))
129
        .route("/admin/backups", get(backups::admin))
130
        .route("/{owner}/{name}/diffusion", get(diffusion::page))
131
        .route("/admin/runners/token", post(runners::new_token))
132
        .route("/admin/runners/{id}", get(runners::show))
133
        .route("/admin/runners/{id}/state", post(runners::set_state))
134
        .route("/admin/runners/{id}/scope", post(runners::set_scope))
135
        .route("/admin/runners/{id}/limits", post(runners::set_limits))
136
        .route("/admin/mail", post(admin::set_mail))
137
        .route("/admin/mail/test", post(admin::test_mail))
138
        .route("/admin/assistants", post(admin::assistants))
139
        .route("/admin/assistants/models", post(admin::assistant_models))
140
        .route("/admin/signin", post(admin::signin))
141
        .route("/login/{provider}", get(signin::start))
142
        .route("/login/{provider}/callback", get(signin::callback))
143
        .route("/settings/security/connect/{provider}", get(signin::connect))
144
        .route("/settings/security/disconnect/{provider}", post(signin::disconnect))
145
        .route("/admin/variables", post(admin::variables))
146
        .route("/admin/secrets", post(admin::secrets))
147
        .route("/admin/runners/{id}/remove", post(runners::remove))
148
        .nest("/api/v1", crate::api::router(app.config.limits.asset_limit.0 as usize))
149
        .route("/{owner}", get(home::owner))
150
        .route("/{owner}/{name}", get(repo::overview))
151
        .route("/{owner}/{name}/tree/{r}", get(repo::tree_root))
152
        .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree))
153
        .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file))
154
        .route("/{owner}/{name}/function/{r}/{*path}", get(history::function))
155
        .route("/{owner}/{name}/lanes/{r}", get(history::lanes))
156
        .route("/{owner}/{name}/lanes/{r}/plan", post(history::plan))
157
        .route("/{owner}/{name}/raw/{r}/{*path}", get(repo::raw_file))
158
        .route("/{owner}/{name}/last/{r}", get(repo::last_changes))
159
        .route("/{owner}/{name}/changes/{r}", get(history::history))
160
        .route("/{owner}/{name}/change/{hash}", get(history::change))
161
        .route("/apt", get(crate::apt::home))
162
        .route("/apt/{file}", get(crate::apt::key))
163
        .route("/apt/dists/{suite}/{*rest}", get(crate::apt::dists))
164
        .route("/apt/pool/{*path}", get(crate::apt::pool))
165
        .route("/help", get(help::help))
166
        .route("/projects/{owner}", get(projects::list).post(projects::create))
167
        .route("/projects/{owner}/{number}", get(projects::show).post(projects::act))
168
        .route("/notifications/thread", post(inbox::thread))
169
        .route("/notifications/open/{id}", get(inbox::open))
170
        .route("/login/reset", get(recovery::request_form).post(recovery::request))
171
        .route("/login/reset/{secret}", get(recovery::new_password_form).post(recovery::set_new_password))
172
        .route("/verify/{secret}", get(recovery::verify))
173
        .route("/settings/email/verify", post(settings::resend_verification))
174
        .route("/{owner}/{name}/compare", get(history::compare_index))
175
        .route("/{owner}/{name}/compare/{spec}", get(history::compare))
176
        .route("/{owner}/{name}/bookmarks", get(refs::bookmarks))
177
        .route("/{owner}/{name}/bookmarks/delete", post(refs::delete_bookmark))
178
        .route("/{owner}/{name}/tags", get(refs::tags))
179
        .route("/{owner}/{name}/conflicts", get(refs::conflicts))
180
        .route("/{owner}/{name}/trust", get(refs::trust))
181
        .route("/{owner}/{name}/pushes", get(refs::pushes))
182
        .route("/{owner}/{name}/fork", get(forks::form).post(forks::create))
183
        .route("/{owner}/{name}/forks", get(forks::list))
184
        .route("/{owner}/{name}/settings", get(repo_settings::settings).post(repo_settings::update))
185
        .route("/{owner}/{name}/settings/collaborators", post(repo_settings::collaborator))
186
        .route("/{owner}/{name}/settings/delete", post(repo_settings::delete))
187
        .route("/{owner}/{name}/settings/transfer", post(repo_settings::transfer))
188
        .route("/{owner}/{name}/settings/archive", post(repo_settings::archive))
189
        .route("/{owner}/{name}/settings/wiki/delete", post(repo_settings::wiki_delete))
190
        .route("/{owner}/{name}/wiki", get(wiki::home))
191
        .route("/{owner}/{name}/wiki/_pages", get(wiki::pages))
192
        .route("/{owner}/{name}/wiki/_new", get(wiki::new_form))
193
        .route("/{owner}/{name}/wiki/_raw/{*path}", get(wiki::raw))
194
        .route("/{owner}/{name}/wiki/{slug}", get(wiki::show))
195
        .route("/{owner}/{name}/wiki/{slug}/edit", get(wiki::edit_form).post(wiki::save))
196
        .route("/{owner}/{name}/wiki/{slug}/history", get(wiki::history))
197
        .route("/{owner}/{name}/wiki/{slug}/delete", post(wiki::delete))
198
        .route("/{owner}/{name}/settings/requirements", post(repo_settings::requirements))
199
        .route("/{owner}/{name}/proposals", get(proposals::list))
200
        .route("/{owner}/{name}/proposals/new", get(proposals::new_form).post(proposals::create))
201
        .route("/{owner}/{name}/proposals/new/draft", post(proposals::new_draft))
202
        .route("/{owner}/{name}/proposal/{number}", get(proposals::show))
203
        .route("/{owner}/{name}/proposal/{number}/comment", post(proposals::comment))
204
        .route("/{owner}/{name}/proposal/{number}/comment/{id}/resolve", post(proposals::resolve_comment))
205
        .route("/{owner}/{name}/proposal/{number}/review", post(proposals::review))
206
        .route("/{owner}/{name}/proposal/{number}/reviewers", post(proposals::reviewers))
207
        .route("/{owner}/{name}/proposal/{number}/assistant", post(proposals::assistant))
208
        .route("/{owner}/{name}/proposal/{number}/draft", post(proposals::draft))
209
        .route("/{owner}/{name}/proposal/{number}/edit", post(proposals::edit))
210
        .route("/{owner}/{name}/proposal/{number}/state", post(proposals::state))
211
        .route("/{owner}/{name}/proposal/{number}/land", post(proposals::land))
212
        .route("/{owner}/{name}/proposal/{number}/labels", post(proposals::set_labels))
213
        .route("/{owner}/{name}/proposal/{number}/project", post(projects::place_proposal))
214
        .route("/{owner}/{name}/issue/{number}/project", post(projects::place_issue))
215
        .route("/{owner}/{name}/proposal/{number}/events", get(proposals::events))
216
        .route("/{owner}/{name}/settings/hooks", post(repo_settings::hooks))
217
        .route("/{owner}/{name}/settings/assistants", post(repo_settings::assistants))
218
        .route("/{owner}/{name}/settings/assistants/models", post(repo_settings::assistant_models))
219
        .route("/{owner}/{name}/settings/variables", post(repo_settings::variables))
220
        .route("/{owner}/{name}/settings/secrets", post(repo_settings::secrets))
221
        .route("/{owner}/{name}/settings/hooks/{id}/deliveries", get(repo_settings::deliveries))
222
        .route("/{owner}/{name}/settings/hooks/{id}/redeliver/{delivery}", post(repo_settings::redeliver))
223
        .route("/{owner}/{name}/settings/checks", post(repo_settings::required_checks))
224
        .route("/{owner}/{name}/watch", post(issues::watch))
225
        .route("/{owner}/{name}/star", post(issues::star))
226
        .route("/{owner}/{name}/edit/{r}", post(edit::save))
227
        .route("/{owner}/{name}/edit/{r}/{*path}", get(edit::edit_form))
228
        .route("/{owner}/{name}/resolve/{bookmark}/{*path}", get(resolve::form).post(resolve::save))
229
        .route("/{owner}/{name}/resolve-live/{bookmark}/{*path}", get(resolve::live_events).post(resolve::live_choose))
230
        .route("/{owner}/{name}/newfile/{r}", get(edit::new_form))
231
        .route("/{owner}/{name}/flow", get(flow::runs))
232
        .route("/{owner}/{name}/flow/badge.svg", get(flow::badge))
233
        .route("/{owner}/{name}/tests", get(test_reports::overview))
234
        .route("/{owner}/{name}/tests/case", get(test_reports::case))
235
        .route("/{owner}/{name}/reports", get(reports::overview))
236
        .route("/{owner}/{name}/reports/files/{id}/{mac}/{*path}", get(reports::file))
237
        .route("/{owner}/{name}/reports/{report}", get(reports::show))
238
        .route("/{owner}/{name}/coverage", get(coverage::overview))
239
        .route("/{owner}/{name}/coverage/badge.svg", get(coverage::badge))
240
        .route("/{owner}/{name}/coverage/{id}/file/{*path}", get(coverage::file))
241
        .route("/{owner}/{name}/flow/{id}", get(flow::run))
242
        .route("/{owner}/{name}/flow/{id}/live", get(flow::live))
243
        .route("/{owner}/{name}/flow/start", post(flow::start))
244
        .route("/{owner}/{name}/flow/{id}/rerun", post(flow::rerun))
245
        .route("/{owner}/{name}/flow/{id}/cancel", post(flow::cancel))
246
        .route("/{owner}/{name}/flow/stamp/{r}", get(flow::stamp))
247
        .route("/{owner}/{name}/flow/at/{r}", get(flow::at))
248
        .route("/{owner}/{name}/receipts/{attest}", get(flow::receipt_file))
249
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}", get(flow::artifact_file))
250
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/attach", post(flow::attach))
251
        .route("/{owner}/{name}/releases", get(releases::list))
252
        .route("/{owner}/{name}/releases/new", get(releases::new_form).post(releases::create))
253
        .route("/{owner}/{name}/releases/tag/{*tag}", get(releases::show))
254
        .route("/{owner}/{name}/releases/trust/{*tag}", get(release_trust::page))
255
        .route("/{owner}/{name}/releases/edit/{id}", post(releases::edit))
256
        .route(
257
            "/{owner}/{name}/releases/upload/{id}",
258
            post(releases::upload).layer(DefaultBodyLimit::max(app.config.limits.asset_limit.0 as usize + (1 << 20))),
259
        )
260
        .route("/{owner}/{name}/asset/{id}/{file}", get(releases::download))
261
        .route("/{owner}/{name}/archive", get(releases::source_archive))
262
        .route("/{owner}/{name}/search", get(repo::code_search))
263
        .route("/{owner}/{name}/info/{*rest}", any(git_info))
264
        .route("/{owner}/{name}/HEAD", get(git_head))
265
        .route("/{owner}/{name}/objects/{*rest}", get(git_objects))
266
        .route("/{owner}/{name}/git-upload-pack", post(git_upload_pack))
267
        .route("/{owner}/{name}/git-receive-pack", post(git_receive_pack))
268
        .route("/{owner}/{name}/settings/mirror", post(repo_settings::mirror))
269
        .route("/{owner}/{name}/settings/flow", post(repo_settings::flow))
270
        .route("/{owner}/{name}/settings/diffusion", post(repo_settings::diffusion))
271
        .route("/{owner}/{name}/settings/storage", post(repo_settings::storage))
272
        .route("/{owner}/{name}/settings/coverage", post(repo_settings::coverage))
273
        .route("/{owner}/{name}/settings/runners/token", post(repo_settings::runner_token))
274
        .route("/{owner}/{name}/settings/runners/{id}/remove", post(repo_settings::runner_remove))
275
        .route("/{owner}/{name}/issues", get(issues::list))
276
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
277
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
278
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
279
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
280
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
281
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
282
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
283
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
284
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
285
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
286
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
287
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
288
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
289
        .fallback(not_found)
290
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
291
        .layer(CompressionLayer::new())
292
        .layer(TraceLayer::new_for_http())
293
        .with_state(app)
294
}
295
296
// Git's smart HTTP paths under `/{owner}/{name}.git/`, forwarded to the
297
// mirror (hub spec §14).
298
async fn git_info(
299
    st: axum::extract::State<Shared>,
300
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
301
    m: axum::http::Method,
302
    q: axum::extract::RawQuery,
303
    h: axum::http::HeaderMap,
304
    b: axum::body::Bytes,
305
) -> Response {
306
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await
307
}
308
309
async fn git_head(
310
    st: axum::extract::State<Shared>,
311
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
312
    m: axum::http::Method,
313
    q: axum::extract::RawQuery,
314
    h: axum::http::HeaderMap,
315
    b: axum::body::Bytes,
316
) -> Response {
317
    crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await
318
}
319
320
async fn git_objects(
321
    st: axum::extract::State<Shared>,
322
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
323
    m: axum::http::Method,
324
    q: axum::extract::RawQuery,
325
    h: axum::http::HeaderMap,
326
    b: axum::body::Bytes,
327
) -> Response {
328
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await
329
}
330
331
async fn git_upload_pack(
332
    st: axum::extract::State<Shared>,
333
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
334
    m: axum::http::Method,
335
    q: axum::extract::RawQuery,
336
    h: axum::http::HeaderMap,
337
    b: axum::body::Bytes,
338
) -> Response {
339
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await
340
}
341
342
async fn git_receive_pack(
343
    st: axum::extract::State<Shared>,
344
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
345
    m: axum::http::Method,
346
    q: axum::extract::RawQuery,
347
    h: axum::http::HeaderMap,
348
    b: axum::body::Bytes,
349
) -> Response {
350
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await
351
}
352
353
/// Cross-site form posts are refused (hub spec §15.2): a browser that
354
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
355
/// API clients send neither.
356
async fn same_origin(
357
    axum::extract::State(app): axum::extract::State<Shared>,
358
    req: axum::extract::Request,
359
    next: axum::middleware::Next,
360
) -> Response {
361
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
362
        let headers = req.headers();
363
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
364
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
365
        }
366
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
367
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
368
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
369
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
370
            if !ok && origin != "null" {
371
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
372
            }
373
        }
374
    }
375
    next.run(req).await
376
}
377
378
/// What every page's chrome needs.
379
#[derive(Clone, Debug)]
380
pub struct Shell {
381
    pub site: String,
382
    pub base_url: String,
383
    pub path: String,
384
    pub version: &'static str,
385
    /// What was built: `oxy describe` at deploy, a Flow build's heads, or "local build".
386
    pub build: &'static str,
387
    /// The signed-in username, if any.
388
    pub user: Option<String>,
389
    pub is_admin: bool,
390
    pub csrf: String,
391
    pub unread: i64,
392
}
393
394
impl Shell {
395
    /// The version in the stylesheet and script URLs (`statics::assets_version`).
396
    pub fn assets(&self) -> &'static str {
397
        statics::assets_version()
398
    }
399
400
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
401
        Shell {
402
            site: app.config.site.name.clone(),
403
            base_url: app.config.base_url().to_string(),
404
            path: path.to_string(),
405
            version: env!("CARGO_PKG_VERSION"),
406
            build: env!("OXY_BUILD_ID"),
407
            user: viewer.account().map(|a| a.username.clone()),
408
            is_admin: viewer.is_admin(),
409
            csrf: viewer.csrf().to_string(),
410
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
411
        }
412
    }
413
414
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
415
        Shell::new(app, path, &Viewer(None))
416
    }
417
}
418
419
/// The repository chrome: tabs and counts.
420
#[derive(Clone, Debug)]
421
pub struct RepoShell {
422
    pub owner: String,
423
    pub name: String,
424
    pub url: String,
425
    pub description: String,
426
    pub default_bookmark: String,
427
    pub visibility: String,
428
    pub tab: &'static str,
429
    pub clone_url: String,
430
    /// The viewer's role, for showing settings and write actions.
431
    pub role: Option<Role>,
432
    /// Open issues and proposals, shown on their tabs.
433
    pub open_issues: i64,
434
    pub open_proposals: i64,
435
    /// Read-only (#108).
436
    pub archived: bool,
437
    /// Whether the repository has a wiki (§6.11).
438
    pub wiki: bool,
439
    /// The bucket its data lives in, when not this hub's disk (#96), as
440
    /// the header's provider icon shows it (#123).
441
    pub stored_in: Option<crate::storage::StoreBadge>,
442
    /// Whether it has coverage reports, for the Coverage tab (#113).
443
    pub coverage: bool,
444
    /// Whether it has test reports, for the Tests tab (#114).
445
    pub tests: bool,
446
    /// Whether it has reports of its own (#127); with coverage or tests,
447
    /// the Reports tab.
448
    pub reports: bool,
449
    /// Whether it pins, or is pinned by, another repository here: the
450
    /// Diffusion tab (#150).
451
    pub diffusion: bool,
452
}
453
454
impl RepoShell {
455
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
456
        RepoShell {
457
            owner: row.owner.clone(),
458
            name: row.name.clone(),
459
            url: format!("/{}/{}", row.owner, row.name),
460
            description: row.description.clone(),
461
            default_bookmark: row.default_bookmark.clone(),
462
            visibility: row.visibility.clone(),
463
            tab,
464
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
465
            role: None,
466
            open_issues: row.open_issues,
467
            open_proposals: row.open_proposals,
468
            archived: row.archived,
469
            wiki: crate::repos::RepoName::new(&row.owner, &row.name).is_some_and(|n| app.wikis.exists(&n)),
470
            stored_in: crate::storage::location(app, &row.owner, &row.name).and_then(|u| crate::storage::StoreBadge::of(&u)),
471
            coverage: crate::coverage::has_reports(app, row.id),
472
            tests: crate::junit::has_reports(app, row.id),
473
            reports: crate::reports::has_reports(app, row.id),
474
            diffusion: crate::diffusion::involved(app, row.id),
475
        }
476
    }
477
478
    pub fn with_role(mut self, role: Role) -> RepoShell {
479
        self.role = Some(role);
480
        self
481
    }
482
483
    pub fn can(&self, access: Access) -> bool {
484
        auth::roles::allows(self.role, access)
485
    }
486
487
    pub fn can_maintain(&self) -> bool {
488
        self.can(Access::Maintain)
489
    }
490
}
491
492
/// Render a template as an HTML response.
493
/// One page of a long list: which page, how many, and links that keep
494
/// the rest of the query.
495
#[derive(Clone, Debug)]
496
pub struct Pager {
497
    pub page: usize,
498
    pub pages: usize,
499
    pub total: usize,
500
    /// The query without `page`, each pair encoded, joined with `&`.
501
    query: String,
502
}
503
504
impl Pager {
505
    pub const PER_PAGE: usize = 25;
506
507
    /// `page` counts from 1; out-of-range pages clamp to the last.
508
    pub fn new(total: usize, page: Option<usize>, query: &[(&str, &str)]) -> Pager {
509
        let pages = total.div_ceil(Self::PER_PAGE).max(1);
510
        let page = page.unwrap_or(1).clamp(1, pages);
511
        let query = query
512
            .iter()
513
            .filter(|(_, v)| !v.is_empty())
514
            .map(|(k, v)| format!("{k}={}", settings::urlencode(v).replace('/', "%2F")))
515
            .collect::<Vec<_>>()
516
            .join("&");
517
        Pager { page, pages, total, query }
518
    }
519
520
    /// This page's items.
521
    pub fn slice<T>(&self, all: Vec<T>) -> Vec<T> {
522
        all.into_iter().skip((self.page - 1) * Self::PER_PAGE).take(Self::PER_PAGE).collect()
523
    }
524
525
    pub fn url(&self, page: usize) -> String {
526
        if self.query.is_empty() {
527
            format!("?page={page}")
528
        } else {
529
            format!("?{}&page={page}", self.query)
530
        }
531
    }
532
533
    /// The same query with another sort, back on page one.
534
    pub fn sorted(&self, sort: &str) -> String {
535
        let rest: Vec<&str> = self.query.split('&').filter(|p| !p.is_empty() && !p.starts_with("sort=")).collect();
536
        let mut q = rest.join("&");
537
        if !q.is_empty() {
538
            q.push('&');
539
        }
540
        format!("?{q}sort={sort}")
541
    }
542
}
543
544
pub struct Page<T: Template>(pub T);
545
546
impl<T: Template> IntoResponse for Page<T> {
547
    fn into_response(self) -> Response {
548
        match self.0.render() {
549
            Ok(s) => Html(s).into_response(),
550
            Err(e) => {
551
                tracing::error!("template: {e}");
552
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
553
            }
554
        }
555
    }
556
}
557
558
#[derive(Template)]
559
#[template(path = "error.html")]
560
struct ErrorPage {
561
    shell: Shell,
562
    status: u16,
563
    title: String,
564
    detail: String,
565
}
566
567
/// A page-level failure, rendered inside the shell, or a redirect.
568
#[derive(Debug)]
569
pub struct Error {
570
    pub status: StatusCode,
571
    pub detail: String,
572
    shell: Option<Box<Shell>>,
573
    redirect: Option<String>,
574
}
575
576
impl Error {
577
    pub fn redirect(to: String) -> Error {
578
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
579
    }
580
581
    pub fn not_found(shell: Shell) -> Error {
582
        Error {
583
            status: StatusCode::NOT_FOUND,
584
            detail: "There is nothing at this address.".into(),
585
            shell: Some(Box::new(shell)),
586
            redirect: None,
587
        }
588
    }
589
590
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
591
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
592
    }
593
594
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
595
        match e {
596
            RepoError::NotFound => Error::not_found(shell),
597
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
598
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
599
            }
600
            other => {
601
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
602
            }
603
        }
604
    }
605
606
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
607
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
608
    }
609
}
610
611
impl IntoResponse for Error {
612
    fn into_response(self) -> Response {
613
        if let Some(to) = self.redirect {
614
            return Redirect::to(&to).into_response();
615
        }
616
        let title = match self.status {
617
            StatusCode::NOT_FOUND => "Not found",
618
            StatusCode::BAD_REQUEST => "Bad request",
619
            _ => "Something went wrong",
620
        };
621
        if self.status.is_server_error() {
622
            tracing::error!("{}", self.detail);
623
        }
624
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
625
            site: "OxygenHub".into(),
626
            base_url: String::new(),
627
            path: String::new(),
628
            version: "",
629
            build: "",
630
            user: None,
631
            is_admin: false,
632
            csrf: String::new(),
633
            unread: 0,
634
        });
635
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
636
        match page.render() {
637
            Ok(s) => (self.status, Html(s)).into_response(),
638
            Err(_) => (self.status, title).into_response(),
639
        }
640
    }
641
}
642
643
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
644
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
645
}
646
647
/// A raw file response with a safe content type (hub spec §15.2).
648
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
649
    let mime = mime_of(name);
650
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
651
    (
652
        [
653
            (header::CONTENT_TYPE, mime.to_string()),
654
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
655
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
656
        ],
657
        bytes,
658
    )
659
        .into_response()
660
}
661
662
pub fn mime_of(name: &str) -> &'static str {
663
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
664
        Some("png") => "image/png",
665
        Some("jpg" | "jpeg") => "image/jpeg",
666
        Some("gif") => "image/gif",
667
        Some("webp") => "image/webp",
668
        Some("svg") => "image/svg+xml",
669
        Some("pdf") => "application/pdf",
670
        Some(
671
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
672
        ) => "text/plain; charset=utf-8",
673
        _ => "application/octet-stream",
674
    }
675
}
676
677
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
678
/// a repository the viewer may not see does not exist for them (hub spec
679
/// §4.4). Returns the viewer's role too.
680
pub async fn lookup_role(
681
    app: &Shared,
682
    shell: &Shell,
683
    viewer: &Viewer,
684
    owner: &str,
685
    name: &str,
686
    access: Access,
687
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
688
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
689
    let row = match db::repos::get(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))? {
690
        Some(row) => row,
691
        None => {
692
            // A transferred repository: the old URL goes to the new one (#108),
693
            // the rest of the path kept, when the viewer may see it.
694
            let moved = db::repos::moved_to(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))?;
695
            let Some(moved) = moved else { return Err(Error::not_found(shell.clone())) };
696
            let role = auth::roles::role_for(&app.db, viewer.account(), &moved).await.map_err(|e| Error::from_db(shell.clone(), e))?;
697
            if !auth::roles::allows(role, Access::Read) {
698
                return Err(Error::not_found(shell.clone()));
699
            }
700
            let old = format!("/{owner}/{name}");
701
            let rest = shell.path.strip_prefix(&old).unwrap_or("");
702
            return Err(Error::redirect(format!("/{}/{}{rest}", moved.owner, moved.name)));
703
        }
704
    };
705
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
706
    if !auth::roles::allows(role, access) {
707
        return Err(Error::not_found(shell.clone()));
708
    }
709
    if row.archived && matches!(access, Access::Write | Access::Maintain) {
710
        return Err(archived(shell));
711
    }
712
    Ok((repo, row, role.unwrap_or(Role::Read)))
713
}
714
715
/// The error for a write to an archived repository (#108).
716
pub fn archived(shell: &Shell) -> Error {
717
    Error::bad(shell.clone(), "This repository is archived and read-only. Its admins can bring it back under Settings › Advanced.")
718
}
719
720
/// Refuse a change to an archived repository, for handlers that open it
721
/// for reading and then write.
722
pub fn writable(row: &db::repos::RepoRow, shell: &Shell) -> Result<(), Error> {
723
    if row.archived {
724
        Err(archived(shell))
725
    } else {
726
        Ok(())
727
    }
728
}
729
730
/// `lookup_role` for reading.
731
pub async fn lookup(
732
    app: &Shared,
733
    shell: &Shell,
734
    viewer: &Viewer,
735
    owner: &str,
736
    name: &str,
737
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
738
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
739
}
740
741
/// Fill `account` on change authors whose key is linked to an account.
742
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
743
    if changes.is_empty() {
744
        return;
745
    }
746
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
747
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
748
    for c in changes.iter_mut() {
749
        if let Some(u) = map.get(&c.author.key) {
750
            c.author.account = Some(u.clone());
751
        }
752
    }
753
}