OXYGENHUB
# 07b1a5bbf481 oxygenhub / crates / hub / src / web / mod.rs
20.5 KiB · Rust · last changed Forks 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 avatar;
8
pub mod edit;
9
pub mod filters;
10
mod forks;
11
pub mod history;
12
mod home;
13
mod inbox;
14
pub mod issues;
15
mod orgs;
16
pub mod proposals;
17
mod refs;
18
pub mod releases;
19
mod repo;
20
mod repo_settings;
21
mod session;
22
mod settings;
23
mod statics;
24
25
use crate::auth::{self, Access, Role, Viewer};
26
use crate::repos::RepoError;
27
use crate::{db, Shared};
28
use askama::Template;
29
use axum::extract::DefaultBodyLimit;
30
use axum::http::{header, StatusCode};
31
use axum::response::{Html, IntoResponse, Redirect, Response};
32
use axum::routing::{any, get, post};
33
use axum::Router;
34
use tower_http::compression::CompressionLayer;
35
use tower_http::trace::TraceLayer;
36
37
pub fn router(app: Shared) -> Router {
38
    let push_limit = app.config.limits.push_body_limit.0 as usize;
39
    Router::new()
40
        .route("/", get(home::index))
41
        .route("/explore", get(home::explore))
42
        .route("/avatar/{name}", get(avatar::avatar))
43
        .route("/health", get(home::health))
44
        .route("/.well-known/oxyhub-key", get(home::hub_key))
45
        .route("/style.css", get(statics::style))
46
        .route("/favicon.svg", get(statics::favicon))
47
        .route("/favicon.ico", get(statics::favicon))
48
        .route("/static/{*path}", get(statics::asset))
49
        .route("/login", get(session::login_form).post(session::login))
50
        .route("/logout", post(session::logout))
51
        .route("/register", get(session::register_form).post(session::register))
52
        .route("/settings", get(settings::profile).post(settings::update_profile))
53
        .route("/settings/password", post(settings::change_password))
54
        .route("/settings/appearance", post(settings::appearance))
55
        .route("/settings/security", get(settings::security))
56
        .route("/settings/security/totp/begin", post(settings::totp_begin))
57
        .route("/settings/security/totp/enable", post(settings::totp_enable))
58
        .route("/settings/security/totp/disable", post(settings::totp_disable))
59
        .route("/settings/security/sessions", post(settings::sessions_reset))
60
        .route("/settings/keys", get(settings::keys))
61
        .route("/settings/keys/upload", post(settings::keys_upload))
62
        .route("/settings/keys/verify", post(settings::keys_verify))
63
        .route("/settings/keys/unlink", post(settings::keys_unlink))
64
        .route("/settings/tokens", get(settings::tokens).post(settings::tokens_create))
65
        .route("/settings/tokens/{id}/delete", post(settings::tokens_delete))
66
        .route("/new", get(repo_settings::new_form).post(repo_settings::create))
67
        .route("/orgs/new", get(orgs::new_form).post(orgs::create))
68
        .route("/orgs/{name}/settings", get(orgs::settings).post(orgs::update))
69
        .route("/orgs/{name}/settings/members", post(orgs::member))
70
        .route("/orgs/{name}/settings/teams", post(orgs::team))
71
        .route("/notifications", get(inbox::inbox))
72
        .route("/notifications/read", post(inbox::mark_read))
73
        .route("/settings/notifications", get(inbox::unsubscribe).post(inbox::prefs))
74
        .route("/search", get(inbox::search))
75
        .route("/admin", get(admin::index))
76
        .route("/admin/registration", post(admin::set_mode))
77
        .route("/admin/invite", post(admin::invite))
78
        .route("/admin/account", post(admin::account))
79
        .nest("/api/v1", crate::api::router())
80
        .route("/{owner}", get(home::owner))
81
        .route("/{owner}/{name}", get(repo::overview))
82
        .route("/{owner}/{name}/tree/{r}", get(repo::tree_root))
83
        .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree))
84
        .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file))
85
        .route("/{owner}/{name}/last/{r}", get(repo::last_changes))
86
        .route("/{owner}/{name}/changes/{r}", get(history::history))
87
        .route("/{owner}/{name}/change/{hash}", get(history::change))
88
        .route("/{owner}/{name}/compare/{spec}", get(history::compare))
89
        .route("/{owner}/{name}/bookmarks", get(refs::bookmarks))
90
        .route("/{owner}/{name}/tags", get(refs::tags))
91
        .route("/{owner}/{name}/conflicts", get(refs::conflicts))
92
        .route("/{owner}/{name}/trust", get(refs::trust))
93
        .route("/{owner}/{name}/pushes", get(refs::pushes))
94
        .route("/{owner}/{name}/fork", get(forks::form).post(forks::create))
95
        .route("/{owner}/{name}/forks", get(forks::list))
96
        .route("/{owner}/{name}/settings", get(repo_settings::settings).post(repo_settings::update))
97
        .route("/{owner}/{name}/settings/collaborators", post(repo_settings::collaborator))
98
        .route("/{owner}/{name}/settings/delete", post(repo_settings::delete))
99
        .route("/{owner}/{name}/settings/requirements", post(repo_settings::requirements))
100
        .route("/{owner}/{name}/proposals", get(proposals::list))
101
        .route("/{owner}/{name}/proposals/new", get(proposals::new_form).post(proposals::create))
102
        .route("/{owner}/{name}/proposal/{number}", get(proposals::show))
103
        .route("/{owner}/{name}/proposal/{number}/comment", post(proposals::comment))
104
        .route("/{owner}/{name}/proposal/{number}/comment/{id}/resolve", post(proposals::resolve_comment))
105
        .route("/{owner}/{name}/proposal/{number}/review", post(proposals::review))
106
        .route("/{owner}/{name}/proposal/{number}/edit", post(proposals::edit))
107
        .route("/{owner}/{name}/proposal/{number}/state", post(proposals::state))
108
        .route("/{owner}/{name}/proposal/{number}/land", post(proposals::land))
109
        .route("/{owner}/{name}/proposal/{number}/labels", post(proposals::set_labels))
110
        .route("/{owner}/{name}/proposal/{number}/events", get(proposals::events))
111
        .route("/{owner}/{name}/settings/hooks", post(repo_settings::hooks))
112
        .route("/{owner}/{name}/settings/hooks/{id}/deliveries", get(repo_settings::deliveries))
113
        .route("/{owner}/{name}/settings/hooks/{id}/redeliver/{delivery}", post(repo_settings::redeliver))
114
        .route("/{owner}/{name}/settings/checks", post(repo_settings::required_checks))
115
        .route("/{owner}/{name}/watch", post(issues::watch))
116
        .route("/{owner}/{name}/edit/{r}", post(edit::save))
117
        .route("/{owner}/{name}/edit/{r}/{*path}", get(edit::edit_form))
118
        .route("/{owner}/{name}/newfile/{r}", get(edit::new_form))
119
        .route("/{owner}/{name}/releases", get(releases::list))
120
        .route("/{owner}/{name}/releases/new", get(releases::new_form).post(releases::create))
121
        .route("/{owner}/{name}/releases/tag/{*tag}", get(releases::show))
122
        .route("/{owner}/{name}/releases/edit/{id}", post(releases::edit))
123
        .route(
124
            "/{owner}/{name}/releases/upload/{id}",
125
            post(releases::upload).layer(DefaultBodyLimit::max(app.config.limits.asset_limit.0 as usize + (1 << 20))),
126
        )
127
        .route("/{owner}/{name}/asset/{id}/{file}", get(releases::download))
128
        .route("/{owner}/{name}/archive", get(releases::source_archive))
129
        .route("/{owner}/{name}/search", get(repo::code_search))
130
        .route("/{owner}/{name}/info/{*rest}", any(git_info))
131
        .route("/{owner}/{name}/HEAD", get(git_head))
132
        .route("/{owner}/{name}/objects/{*rest}", get(git_objects))
133
        .route("/{owner}/{name}/git-upload-pack", post(git_upload_pack))
134
        .route("/{owner}/{name}/git-receive-pack", post(git_receive_pack))
135
        .route("/{owner}/{name}/settings/mirror", post(repo_settings::mirror))
136
        .route("/{owner}/{name}/issues", get(issues::list))
137
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
138
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
139
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
140
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
141
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
142
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
143
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
144
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
145
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
146
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
147
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
148
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
149
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
150
        .fallback(not_found)
151
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
152
        .layer(CompressionLayer::new())
153
        .layer(TraceLayer::new_for_http())
154
        .with_state(app)
155
}
156
157
// Git's smart HTTP paths under `/{owner}/{name}.git/`, forwarded to the
158
// mirror (hub spec §14).
159
async fn git_info(
160
    st: axum::extract::State<Shared>,
161
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
162
    m: axum::http::Method,
163
    q: axum::extract::RawQuery,
164
    h: axum::http::HeaderMap,
165
    b: axum::body::Bytes,
166
) -> Response {
167
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await
168
}
169
170
async fn git_head(
171
    st: axum::extract::State<Shared>,
172
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
173
    m: axum::http::Method,
174
    q: axum::extract::RawQuery,
175
    h: axum::http::HeaderMap,
176
    b: axum::body::Bytes,
177
) -> Response {
178
    crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await
179
}
180
181
async fn git_objects(
182
    st: axum::extract::State<Shared>,
183
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
184
    m: axum::http::Method,
185
    q: axum::extract::RawQuery,
186
    h: axum::http::HeaderMap,
187
    b: axum::body::Bytes,
188
) -> Response {
189
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await
190
}
191
192
async fn git_upload_pack(
193
    st: axum::extract::State<Shared>,
194
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
195
    m: axum::http::Method,
196
    q: axum::extract::RawQuery,
197
    h: axum::http::HeaderMap,
198
    b: axum::body::Bytes,
199
) -> Response {
200
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await
201
}
202
203
async fn git_receive_pack(
204
    st: axum::extract::State<Shared>,
205
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
206
    m: axum::http::Method,
207
    q: axum::extract::RawQuery,
208
    h: axum::http::HeaderMap,
209
    b: axum::body::Bytes,
210
) -> Response {
211
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await
212
}
213
214
/// Cross-site form posts are refused (hub spec §15.2): a browser that
215
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
216
/// API clients send neither.
217
async fn same_origin(
218
    axum::extract::State(app): axum::extract::State<Shared>,
219
    req: axum::extract::Request,
220
    next: axum::middleware::Next,
221
) -> Response {
222
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
223
        let headers = req.headers();
224
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
225
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
226
        }
227
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
228
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
229
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
230
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
231
            if !ok && origin != "null" {
232
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
233
            }
234
        }
235
    }
236
    next.run(req).await
237
}
238
239
/// What every page's chrome needs.
240
#[derive(Clone, Debug)]
241
pub struct Shell {
242
    pub site: String,
243
    pub base_url: String,
244
    pub path: String,
245
    pub version: &'static str,
246
    /// The signed-in username, if any.
247
    pub user: Option<String>,
248
    pub is_admin: bool,
249
    pub csrf: String,
250
    pub unread: i64,
251
}
252
253
impl Shell {
254
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
255
        Shell {
256
            site: app.config.site.name.clone(),
257
            base_url: app.config.base_url().to_string(),
258
            path: path.to_string(),
259
            version: env!("CARGO_PKG_VERSION"),
260
            user: viewer.account().map(|a| a.username.clone()),
261
            is_admin: viewer.is_admin(),
262
            csrf: viewer.csrf().to_string(),
263
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
264
        }
265
    }
266
267
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
268
        Shell::new(app, path, &Viewer(None))
269
    }
270
}
271
272
/// The repository chrome: tabs and counts.
273
#[derive(Clone, Debug)]
274
pub struct RepoShell {
275
    pub owner: String,
276
    pub name: String,
277
    pub url: String,
278
    pub description: String,
279
    pub default_bookmark: String,
280
    pub visibility: String,
281
    pub tab: &'static str,
282
    pub clone_url: String,
283
    /// The viewer's role, for showing settings and write actions.
284
    pub role: Option<Role>,
285
}
286
287
impl RepoShell {
288
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
289
        RepoShell {
290
            owner: row.owner.clone(),
291
            name: row.name.clone(),
292
            url: format!("/{}/{}", row.owner, row.name),
293
            description: row.description.clone(),
294
            default_bookmark: row.default_bookmark.clone(),
295
            visibility: row.visibility.clone(),
296
            tab,
297
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
298
            role: None,
299
        }
300
    }
301
302
    pub fn with_role(mut self, role: Role) -> RepoShell {
303
        self.role = Some(role);
304
        self
305
    }
306
307
    pub fn can(&self, access: Access) -> bool {
308
        auth::roles::allows(self.role, access)
309
    }
310
311
    pub fn can_maintain(&self) -> bool {
312
        self.can(Access::Maintain)
313
    }
314
}
315
316
/// Render a template as an HTML response.
317
pub struct Page<T: Template>(pub T);
318
319
impl<T: Template> IntoResponse for Page<T> {
320
    fn into_response(self) -> Response {
321
        match self.0.render() {
322
            Ok(s) => Html(s).into_response(),
323
            Err(e) => {
324
                tracing::error!("template: {e}");
325
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
326
            }
327
        }
328
    }
329
}
330
331
#[derive(Template)]
332
#[template(path = "error.html")]
333
struct ErrorPage {
334
    shell: Shell,
335
    status: u16,
336
    title: String,
337
    detail: String,
338
}
339
340
/// A page-level failure, rendered inside the shell, or a redirect.
341
#[derive(Debug)]
342
pub struct Error {
343
    pub status: StatusCode,
344
    pub detail: String,
345
    shell: Option<Box<Shell>>,
346
    redirect: Option<String>,
347
}
348
349
impl Error {
350
    pub fn redirect(to: String) -> Error {
351
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
352
    }
353
354
    pub fn not_found(shell: Shell) -> Error {
355
        Error {
356
            status: StatusCode::NOT_FOUND,
357
            detail: "There is nothing at this address.".into(),
358
            shell: Some(Box::new(shell)),
359
            redirect: None,
360
        }
361
    }
362
363
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
364
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
365
    }
366
367
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
368
        match e {
369
            RepoError::NotFound => Error::not_found(shell),
370
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
371
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
372
            }
373
            other => {
374
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
375
            }
376
        }
377
    }
378
379
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
380
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
381
    }
382
}
383
384
impl IntoResponse for Error {
385
    fn into_response(self) -> Response {
386
        if let Some(to) = self.redirect {
387
            return Redirect::to(&to).into_response();
388
        }
389
        let title = match self.status {
390
            StatusCode::NOT_FOUND => "Not found",
391
            StatusCode::BAD_REQUEST => "Bad request",
392
            _ => "Something went wrong",
393
        };
394
        if self.status.is_server_error() {
395
            tracing::error!("{}", self.detail);
396
        }
397
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
398
            site: "Oxygenhub".into(),
399
            base_url: String::new(),
400
            path: String::new(),
401
            version: "",
402
            user: None,
403
            is_admin: false,
404
            csrf: String::new(),
405
            unread: 0,
406
        });
407
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
408
        match page.render() {
409
            Ok(s) => (self.status, Html(s)).into_response(),
410
            Err(_) => (self.status, title).into_response(),
411
        }
412
    }
413
}
414
415
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
416
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
417
}
418
419
/// A raw file response with a safe content type (hub spec §15.2).
420
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
421
    let mime = mime_of(name);
422
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
423
    (
424
        [
425
            (header::CONTENT_TYPE, mime.to_string()),
426
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
427
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
428
        ],
429
        bytes,
430
    )
431
        .into_response()
432
}
433
434
pub fn mime_of(name: &str) -> &'static str {
435
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
436
        Some("png") => "image/png",
437
        Some("jpg" | "jpeg") => "image/jpeg",
438
        Some("gif") => "image/gif",
439
        Some("webp") => "image/webp",
440
        Some("svg") => "image/svg+xml",
441
        Some("pdf") => "application/pdf",
442
        Some(
443
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
444
        ) => "text/plain; charset=utf-8",
445
        _ => "application/octet-stream",
446
    }
447
}
448
449
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
450
/// a repository the viewer may not see does not exist for them (hub spec
451
/// §4.4). Returns the viewer's role too.
452
pub async fn lookup_role(
453
    app: &Shared,
454
    shell: &Shell,
455
    viewer: &Viewer,
456
    owner: &str,
457
    name: &str,
458
    access: Access,
459
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
460
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
461
    let row = db::repos::get(&app.db, owner, name)
462
        .await
463
        .map_err(|e| Error::from_db(shell.clone(), e))?
464
        .ok_or_else(|| Error::not_found(shell.clone()))?;
465
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
466
    if !auth::roles::allows(role, access) {
467
        return Err(Error::not_found(shell.clone()));
468
    }
469
    Ok((repo, row, role.unwrap_or(Role::Read)))
470
}
471
472
/// `lookup_role` for reading.
473
pub async fn lookup(
474
    app: &Shared,
475
    shell: &Shell,
476
    viewer: &Viewer,
477
    owner: &str,
478
    name: &str,
479
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
480
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
481
}
482
483
/// Fill `account` on change authors whose key is linked to an account.
484
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
485
    if changes.is_empty() {
486
        return;
487
    }
488
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
489
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
490
    for c in changes.iter_mut() {
491
        if let Some(u) = map.get(&c.author.key) {
492
            c.author.account = Some(u.clone());
493
        }
494
    }
495
}