OXYGENHUB
# 36e5a9c15a84 oxygenhub / crates / hub / src / web / mod.rs
32.3 KiB · Rust · last changed Tests tab: a bookmark's test results over its runs (part 2) 29 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
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/runners/token", post(repo_settings::runner_token))
254
        .route("/{owner}/{name}/settings/runners/{id}/remove", post(repo_settings::runner_remove))
255
        .route("/{owner}/{name}/issues", get(issues::list))
256
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
257
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
258
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
259
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
260
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
261
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
262
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
263
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
264
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
265
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
266
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
267
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
268
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
269
        .fallback(not_found)
270
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
271
        .layer(CompressionLayer::new())
272
        .layer(TraceLayer::new_for_http())
273
        .with_state(app)
274
}
275
276
// Git's smart HTTP paths under `/{owner}/{name}.git/`, forwarded to the
277
// mirror (hub spec §14).
278
async fn git_info(
279
    st: axum::extract::State<Shared>,
280
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
281
    m: axum::http::Method,
282
    q: axum::extract::RawQuery,
283
    h: axum::http::HeaderMap,
284
    b: axum::body::Bytes,
285
) -> Response {
286
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await
287
}
288
289
async fn git_head(
290
    st: axum::extract::State<Shared>,
291
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
292
    m: axum::http::Method,
293
    q: axum::extract::RawQuery,
294
    h: axum::http::HeaderMap,
295
    b: axum::body::Bytes,
296
) -> Response {
297
    crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await
298
}
299
300
async fn git_objects(
301
    st: axum::extract::State<Shared>,
302
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
303
    m: axum::http::Method,
304
    q: axum::extract::RawQuery,
305
    h: axum::http::HeaderMap,
306
    b: axum::body::Bytes,
307
) -> Response {
308
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await
309
}
310
311
async fn git_upload_pack(
312
    st: axum::extract::State<Shared>,
313
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
314
    m: axum::http::Method,
315
    q: axum::extract::RawQuery,
316
    h: axum::http::HeaderMap,
317
    b: axum::body::Bytes,
318
) -> Response {
319
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await
320
}
321
322
async fn git_receive_pack(
323
    st: axum::extract::State<Shared>,
324
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
325
    m: axum::http::Method,
326
    q: axum::extract::RawQuery,
327
    h: axum::http::HeaderMap,
328
    b: axum::body::Bytes,
329
) -> Response {
330
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await
331
}
332
333
/// Cross-site form posts are refused (hub spec §15.2): a browser that
334
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
335
/// API clients send neither.
336
async fn same_origin(
337
    axum::extract::State(app): axum::extract::State<Shared>,
338
    req: axum::extract::Request,
339
    next: axum::middleware::Next,
340
) -> Response {
341
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
342
        let headers = req.headers();
343
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
344
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
345
        }
346
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
347
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
348
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
349
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
350
            if !ok && origin != "null" {
351
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
352
            }
353
        }
354
    }
355
    next.run(req).await
356
}
357
358
/// What every page's chrome needs.
359
#[derive(Clone, Debug)]
360
pub struct Shell {
361
    pub site: String,
362
    pub base_url: String,
363
    pub path: String,
364
    pub version: &'static str,
365
    /// What was built: `oxy describe` at deploy, a Flow build's heads, or "local build".
366
    pub build: &'static str,
367
    /// The signed-in username, if any.
368
    pub user: Option<String>,
369
    pub is_admin: bool,
370
    pub csrf: String,
371
    pub unread: i64,
372
}
373
374
impl Shell {
375
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
376
        Shell {
377
            site: app.config.site.name.clone(),
378
            base_url: app.config.base_url().to_string(),
379
            path: path.to_string(),
380
            version: env!("CARGO_PKG_VERSION"),
381
            build: env!("OXY_BUILD_ID"),
382
            user: viewer.account().map(|a| a.username.clone()),
383
            is_admin: viewer.is_admin(),
384
            csrf: viewer.csrf().to_string(),
385
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
386
        }
387
    }
388
389
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
390
        Shell::new(app, path, &Viewer(None))
391
    }
392
}
393
394
/// The repository chrome: tabs and counts.
395
#[derive(Clone, Debug)]
396
pub struct RepoShell {
397
    pub owner: String,
398
    pub name: String,
399
    pub url: String,
400
    pub description: String,
401
    pub default_bookmark: String,
402
    pub visibility: String,
403
    pub tab: &'static str,
404
    pub clone_url: String,
405
    /// The viewer's role, for showing settings and write actions.
406
    pub role: Option<Role>,
407
    /// Open issues and proposals, shown on their tabs.
408
    pub open_issues: i64,
409
    pub open_proposals: i64,
410
    /// Read-only (#108).
411
    pub archived: bool,
412
    /// Whether the repository has a wiki (§6.11).
413
    pub wiki: bool,
414
    /// The bucket its data lives in, when not this hub's disk (#96).
415
    pub stored_in: Option<String>,
416
    /// Whether it has coverage reports, for the Coverage tab (#113).
417
    pub coverage: bool,
418
    /// Whether it has test reports, for the Tests tab (#114).
419
    pub tests: bool,
420
}
421
422
impl RepoShell {
423
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
424
        RepoShell {
425
            owner: row.owner.clone(),
426
            name: row.name.clone(),
427
            url: format!("/{}/{}", row.owner, row.name),
428
            description: row.description.clone(),
429
            default_bookmark: row.default_bookmark.clone(),
430
            visibility: row.visibility.clone(),
431
            tab,
432
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
433
            role: None,
434
            open_issues: row.open_issues,
435
            open_proposals: row.open_proposals,
436
            archived: row.archived,
437
            wiki: crate::repos::RepoName::new(&row.owner, &row.name).is_some_and(|n| app.wikis.exists(&n)),
438
            stored_in: crate::storage::location(app, &row.owner, &row.name),
439
            coverage: crate::coverage::has_reports(app, row.id),
440
            tests: crate::junit::has_reports(app, row.id),
441
        }
442
    }
443
444
    pub fn with_role(mut self, role: Role) -> RepoShell {
445
        self.role = Some(role);
446
        self
447
    }
448
449
    pub fn can(&self, access: Access) -> bool {
450
        auth::roles::allows(self.role, access)
451
    }
452
453
    pub fn can_maintain(&self) -> bool {
454
        self.can(Access::Maintain)
455
    }
456
}
457
458
/// Render a template as an HTML response.
459
/// One page of a long list: which page, how many, and links that keep
460
/// the rest of the query.
461
#[derive(Clone, Debug)]
462
pub struct Pager {
463
    pub page: usize,
464
    pub pages: usize,
465
    pub total: usize,
466
    /// The query without `page`, each pair encoded, joined with `&`.
467
    query: String,
468
}
469
470
impl Pager {
471
    pub const PER_PAGE: usize = 25;
472
473
    /// `page` counts from 1; out-of-range pages clamp to the last.
474
    pub fn new(total: usize, page: Option<usize>, query: &[(&str, &str)]) -> Pager {
475
        let pages = total.div_ceil(Self::PER_PAGE).max(1);
476
        let page = page.unwrap_or(1).clamp(1, pages);
477
        let query = query
478
            .iter()
479
            .filter(|(_, v)| !v.is_empty())
480
            .map(|(k, v)| format!("{k}={}", settings::urlencode(v).replace('/', "%2F")))
481
            .collect::<Vec<_>>()
482
            .join("&");
483
        Pager { page, pages, total, query }
484
    }
485
486
    /// This page's items.
487
    pub fn slice<T>(&self, all: Vec<T>) -> Vec<T> {
488
        all.into_iter().skip((self.page - 1) * Self::PER_PAGE).take(Self::PER_PAGE).collect()
489
    }
490
491
    pub fn url(&self, page: usize) -> String {
492
        if self.query.is_empty() {
493
            format!("?page={page}")
494
        } else {
495
            format!("?{}&page={page}", self.query)
496
        }
497
    }
498
499
    /// The same query with another sort, back on page one.
500
    pub fn sorted(&self, sort: &str) -> String {
501
        let rest: Vec<&str> = self.query.split('&').filter(|p| !p.is_empty() && !p.starts_with("sort=")).collect();
502
        let mut q = rest.join("&");
503
        if !q.is_empty() {
504
            q.push('&');
505
        }
506
        format!("?{q}sort={sort}")
507
    }
508
}
509
510
pub struct Page<T: Template>(pub T);
511
512
impl<T: Template> IntoResponse for Page<T> {
513
    fn into_response(self) -> Response {
514
        match self.0.render() {
515
            Ok(s) => Html(s).into_response(),
516
            Err(e) => {
517
                tracing::error!("template: {e}");
518
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
519
            }
520
        }
521
    }
522
}
523
524
#[derive(Template)]
525
#[template(path = "error.html")]
526
struct ErrorPage {
527
    shell: Shell,
528
    status: u16,
529
    title: String,
530
    detail: String,
531
}
532
533
/// A page-level failure, rendered inside the shell, or a redirect.
534
#[derive(Debug)]
535
pub struct Error {
536
    pub status: StatusCode,
537
    pub detail: String,
538
    shell: Option<Box<Shell>>,
539
    redirect: Option<String>,
540
}
541
542
impl Error {
543
    pub fn redirect(to: String) -> Error {
544
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
545
    }
546
547
    pub fn not_found(shell: Shell) -> Error {
548
        Error {
549
            status: StatusCode::NOT_FOUND,
550
            detail: "There is nothing at this address.".into(),
551
            shell: Some(Box::new(shell)),
552
            redirect: None,
553
        }
554
    }
555
556
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
557
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
558
    }
559
560
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
561
        match e {
562
            RepoError::NotFound => Error::not_found(shell),
563
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
564
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
565
            }
566
            other => {
567
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
568
            }
569
        }
570
    }
571
572
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
573
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
574
    }
575
}
576
577
impl IntoResponse for Error {
578
    fn into_response(self) -> Response {
579
        if let Some(to) = self.redirect {
580
            return Redirect::to(&to).into_response();
581
        }
582
        let title = match self.status {
583
            StatusCode::NOT_FOUND => "Not found",
584
            StatusCode::BAD_REQUEST => "Bad request",
585
            _ => "Something went wrong",
586
        };
587
        if self.status.is_server_error() {
588
            tracing::error!("{}", self.detail);
589
        }
590
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
591
            site: "OxygenHub".into(),
592
            base_url: String::new(),
593
            path: String::new(),
594
            version: "",
595
            build: "",
596
            user: None,
597
            is_admin: false,
598
            csrf: String::new(),
599
            unread: 0,
600
        });
601
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
602
        match page.render() {
603
            Ok(s) => (self.status, Html(s)).into_response(),
604
            Err(_) => (self.status, title).into_response(),
605
        }
606
    }
607
}
608
609
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
610
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
611
}
612
613
/// A raw file response with a safe content type (hub spec §15.2).
614
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
615
    let mime = mime_of(name);
616
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
617
    (
618
        [
619
            (header::CONTENT_TYPE, mime.to_string()),
620
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
621
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
622
        ],
623
        bytes,
624
    )
625
        .into_response()
626
}
627
628
pub fn mime_of(name: &str) -> &'static str {
629
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
630
        Some("png") => "image/png",
631
        Some("jpg" | "jpeg") => "image/jpeg",
632
        Some("gif") => "image/gif",
633
        Some("webp") => "image/webp",
634
        Some("svg") => "image/svg+xml",
635
        Some("pdf") => "application/pdf",
636
        Some(
637
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
638
        ) => "text/plain; charset=utf-8",
639
        _ => "application/octet-stream",
640
    }
641
}
642
643
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
644
/// a repository the viewer may not see does not exist for them (hub spec
645
/// §4.4). Returns the viewer's role too.
646
pub async fn lookup_role(
647
    app: &Shared,
648
    shell: &Shell,
649
    viewer: &Viewer,
650
    owner: &str,
651
    name: &str,
652
    access: Access,
653
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
654
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
655
    let row = match db::repos::get(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))? {
656
        Some(row) => row,
657
        None => {
658
            // A transferred repository: the old URL goes to the new one (#108),
659
            // the rest of the path kept, when the viewer may see it.
660
            let moved = db::repos::moved_to(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))?;
661
            let Some(moved) = moved else { return Err(Error::not_found(shell.clone())) };
662
            let role = auth::roles::role_for(&app.db, viewer.account(), &moved).await.map_err(|e| Error::from_db(shell.clone(), e))?;
663
            if !auth::roles::allows(role, Access::Read) {
664
                return Err(Error::not_found(shell.clone()));
665
            }
666
            let old = format!("/{owner}/{name}");
667
            let rest = shell.path.strip_prefix(&old).unwrap_or("");
668
            return Err(Error::redirect(format!("/{}/{}{rest}", moved.owner, moved.name)));
669
        }
670
    };
671
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
672
    if !auth::roles::allows(role, access) {
673
        return Err(Error::not_found(shell.clone()));
674
    }
675
    if row.archived && matches!(access, Access::Write | Access::Maintain) {
676
        return Err(archived(shell));
677
    }
678
    Ok((repo, row, role.unwrap_or(Role::Read)))
679
}
680
681
/// The error for a write to an archived repository (#108).
682
pub fn archived(shell: &Shell) -> Error {
683
    Error::bad(shell.clone(), "This repository is archived and read-only. Its admins can bring it back under Settings › Advanced.")
684
}
685
686
/// Refuse a change to an archived repository, for handlers that open it
687
/// for reading and then write.
688
pub fn writable(row: &db::repos::RepoRow, shell: &Shell) -> Result<(), Error> {
689
    if row.archived {
690
        Err(archived(shell))
691
    } else {
692
        Ok(())
693
    }
694
}
695
696
/// `lookup_role` for reading.
697
pub async fn lookup(
698
    app: &Shared,
699
    shell: &Shell,
700
    viewer: &Viewer,
701
    owner: &str,
702
    name: &str,
703
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
704
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
705
}
706
707
/// Fill `account` on change authors whose key is linked to an account.
708
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
709
    if changes.is_empty() {
710
        return;
711
    }
712
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
713
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
714
    for c in changes.iter_mut() {
715
        if let Some(u) = map.get(&c.author.key) {
716
            c.author.account = Some(u.clone());
717
        }
718
    }
719
}