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