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