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