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