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