OXYGENHUB
# 1553bfc9ae53 oxygenhub / crates / hub / src / web / mod.rs
20.5 KiB · Rust · last changed Stars, topics, and a sortable, filterable Explore 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}/star", post(issues::star))
117
        .route("/{owner}/{name}/edit/{r}", post(edit::save))
118
        .route("/{owner}/{name}/edit/{r}/{*path}", get(edit::edit_form))
119
        .route("/{owner}/{name}/newfile/{r}", get(edit::new_form))
120
        .route("/{owner}/{name}/releases", get(releases::list))
121
        .route("/{owner}/{name}/releases/new", get(releases::new_form).post(releases::create))
122
        .route("/{owner}/{name}/releases/tag/{*tag}", get(releases::show))
123
        .route("/{owner}/{name}/releases/edit/{id}", post(releases::edit))
124
        .route(
125
            "/{owner}/{name}/releases/upload/{id}",
126
            post(releases::upload).layer(DefaultBodyLimit::max(app.config.limits.asset_limit.0 as usize + (1 << 20))),
127
        )
128
        .route("/{owner}/{name}/asset/{id}/{file}", get(releases::download))
129
        .route("/{owner}/{name}/archive", get(releases::source_archive))
130
        .route("/{owner}/{name}/search", get(repo::code_search))
131
        .route("/{owner}/{name}/info/{*rest}", any(git_info))
132
        .route("/{owner}/{name}/HEAD", get(git_head))
133
        .route("/{owner}/{name}/objects/{*rest}", get(git_objects))
134
        .route("/{owner}/{name}/git-upload-pack", post(git_upload_pack))
135
        .route("/{owner}/{name}/git-receive-pack", post(git_receive_pack))
136
        .route("/{owner}/{name}/settings/mirror", post(repo_settings::mirror))
137
        .route("/{owner}/{name}/issues", get(issues::list))
138
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
139
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
140
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
141
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
142
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
143
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
144
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
145
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
146
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
147
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
148
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
149
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
150
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
151
        .fallback(not_found)
152
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
153
        .layer(CompressionLayer::new())
154
        .layer(TraceLayer::new_for_http())
155
        .with_state(app)
156
}
157
158
// Git's smart HTTP paths under `/{owner}/{name}.git/`, forwarded to the
159
// mirror (hub spec §14).
160
async fn git_info(
161
    st: axum::extract::State<Shared>,
162
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
163
    m: axum::http::Method,
164
    q: axum::extract::RawQuery,
165
    h: axum::http::HeaderMap,
166
    b: axum::body::Bytes,
167
) -> Response {
168
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await
169
}
170
171
async fn git_head(
172
    st: axum::extract::State<Shared>,
173
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
174
    m: axum::http::Method,
175
    q: axum::extract::RawQuery,
176
    h: axum::http::HeaderMap,
177
    b: axum::body::Bytes,
178
) -> Response {
179
    crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await
180
}
181
182
async fn git_objects(
183
    st: axum::extract::State<Shared>,
184
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
185
    m: axum::http::Method,
186
    q: axum::extract::RawQuery,
187
    h: axum::http::HeaderMap,
188
    b: axum::body::Bytes,
189
) -> Response {
190
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await
191
}
192
193
async fn git_upload_pack(
194
    st: axum::extract::State<Shared>,
195
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
196
    m: axum::http::Method,
197
    q: axum::extract::RawQuery,
198
    h: axum::http::HeaderMap,
199
    b: axum::body::Bytes,
200
) -> Response {
201
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await
202
}
203
204
async fn git_receive_pack(
205
    st: axum::extract::State<Shared>,
206
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
207
    m: axum::http::Method,
208
    q: axum::extract::RawQuery,
209
    h: axum::http::HeaderMap,
210
    b: axum::body::Bytes,
211
) -> Response {
212
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await
213
}
214
215
/// Cross-site form posts are refused (hub spec §15.2): a browser that
216
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
217
/// API clients send neither.
218
async fn same_origin(
219
    axum::extract::State(app): axum::extract::State<Shared>,
220
    req: axum::extract::Request,
221
    next: axum::middleware::Next,
222
) -> Response {
223
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
224
        let headers = req.headers();
225
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
226
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
227
        }
228
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
229
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
230
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
231
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
232
            if !ok && origin != "null" {
233
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
234
            }
235
        }
236
    }
237
    next.run(req).await
238
}
239
240
/// What every page's chrome needs.
241
#[derive(Clone, Debug)]
242
pub struct Shell {
243
    pub site: String,
244
    pub base_url: String,
245
    pub path: String,
246
    pub version: &'static str,
247
    /// The signed-in username, if any.
248
    pub user: Option<String>,
249
    pub is_admin: bool,
250
    pub csrf: String,
251
    pub unread: i64,
252
}
253
254
impl Shell {
255
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
256
        Shell {
257
            site: app.config.site.name.clone(),
258
            base_url: app.config.base_url().to_string(),
259
            path: path.to_string(),
260
            version: env!("CARGO_PKG_VERSION"),
261
            user: viewer.account().map(|a| a.username.clone()),
262
            is_admin: viewer.is_admin(),
263
            csrf: viewer.csrf().to_string(),
264
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
265
        }
266
    }
267
268
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
269
        Shell::new(app, path, &Viewer(None))
270
    }
271
}
272
273
/// The repository chrome: tabs and counts.
274
#[derive(Clone, Debug)]
275
pub struct RepoShell {
276
    pub owner: String,
277
    pub name: String,
278
    pub url: String,
279
    pub description: String,
280
    pub default_bookmark: String,
281
    pub visibility: String,
282
    pub tab: &'static str,
283
    pub clone_url: String,
284
    /// The viewer's role, for showing settings and write actions.
285
    pub role: Option<Role>,
286
}
287
288
impl RepoShell {
289
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
290
        RepoShell {
291
            owner: row.owner.clone(),
292
            name: row.name.clone(),
293
            url: format!("/{}/{}", row.owner, row.name),
294
            description: row.description.clone(),
295
            default_bookmark: row.default_bookmark.clone(),
296
            visibility: row.visibility.clone(),
297
            tab,
298
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
299
            role: None,
300
        }
301
    }
302
303
    pub fn with_role(mut self, role: Role) -> RepoShell {
304
        self.role = Some(role);
305
        self
306
    }
307
308
    pub fn can(&self, access: Access) -> bool {
309
        auth::roles::allows(self.role, access)
310
    }
311
312
    pub fn can_maintain(&self) -> bool {
313
        self.can(Access::Maintain)
314
    }
315
}
316
317
/// Render a template as an HTML response.
318
pub struct Page<T: Template>(pub T);
319
320
impl<T: Template> IntoResponse for Page<T> {
321
    fn into_response(self) -> Response {
322
        match self.0.render() {
323
            Ok(s) => Html(s).into_response(),
324
            Err(e) => {
325
                tracing::error!("template: {e}");
326
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
327
            }
328
        }
329
    }
330
}
331
332
#[derive(Template)]
333
#[template(path = "error.html")]
334
struct ErrorPage {
335
    shell: Shell,
336
    status: u16,
337
    title: String,
338
    detail: String,
339
}
340
341
/// A page-level failure, rendered inside the shell, or a redirect.
342
#[derive(Debug)]
343
pub struct Error {
344
    pub status: StatusCode,
345
    pub detail: String,
346
    shell: Option<Box<Shell>>,
347
    redirect: Option<String>,
348
}
349
350
impl Error {
351
    pub fn redirect(to: String) -> Error {
352
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
353
    }
354
355
    pub fn not_found(shell: Shell) -> Error {
356
        Error {
357
            status: StatusCode::NOT_FOUND,
358
            detail: "There is nothing at this address.".into(),
359
            shell: Some(Box::new(shell)),
360
            redirect: None,
361
        }
362
    }
363
364
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
365
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
366
    }
367
368
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
369
        match e {
370
            RepoError::NotFound => Error::not_found(shell),
371
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
372
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
373
            }
374
            other => {
375
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
376
            }
377
        }
378
    }
379
380
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
381
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
382
    }
383
}
384
385
impl IntoResponse for Error {
386
    fn into_response(self) -> Response {
387
        if let Some(to) = self.redirect {
388
            return Redirect::to(&to).into_response();
389
        }
390
        let title = match self.status {
391
            StatusCode::NOT_FOUND => "Not found",
392
            StatusCode::BAD_REQUEST => "Bad request",
393
            _ => "Something went wrong",
394
        };
395
        if self.status.is_server_error() {
396
            tracing::error!("{}", self.detail);
397
        }
398
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
399
            site: "Oxygenhub".into(),
400
            base_url: String::new(),
401
            path: String::new(),
402
            version: "",
403
            user: None,
404
            is_admin: false,
405
            csrf: String::new(),
406
            unread: 0,
407
        });
408
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
409
        match page.render() {
410
            Ok(s) => (self.status, Html(s)).into_response(),
411
            Err(_) => (self.status, title).into_response(),
412
        }
413
    }
414
}
415
416
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
417
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
418
}
419
420
/// A raw file response with a safe content type (hub spec §15.2).
421
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
422
    let mime = mime_of(name);
423
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
424
    (
425
        [
426
            (header::CONTENT_TYPE, mime.to_string()),
427
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
428
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
429
        ],
430
        bytes,
431
    )
432
        .into_response()
433
}
434
435
pub fn mime_of(name: &str) -> &'static str {
436
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
437
        Some("png") => "image/png",
438
        Some("jpg" | "jpeg") => "image/jpeg",
439
        Some("gif") => "image/gif",
440
        Some("webp") => "image/webp",
441
        Some("svg") => "image/svg+xml",
442
        Some("pdf") => "application/pdf",
443
        Some(
444
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
445
        ) => "text/plain; charset=utf-8",
446
        _ => "application/octet-stream",
447
    }
448
}
449
450
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
451
/// a repository the viewer may not see does not exist for them (hub spec
452
/// §4.4). Returns the viewer's role too.
453
pub async fn lookup_role(
454
    app: &Shared,
455
    shell: &Shell,
456
    viewer: &Viewer,
457
    owner: &str,
458
    name: &str,
459
    access: Access,
460
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
461
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
462
    let row = db::repos::get(&app.db, owner, name)
463
        .await
464
        .map_err(|e| Error::from_db(shell.clone(), e))?
465
        .ok_or_else(|| Error::not_found(shell.clone()))?;
466
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
467
    if !auth::roles::allows(role, access) {
468
        return Err(Error::not_found(shell.clone()));
469
    }
470
    Ok((repo, row, role.unwrap_or(Role::Read)))
471
}
472
473
/// `lookup_role` for reading.
474
pub async fn lookup(
475
    app: &Shared,
476
    shell: &Shell,
477
    viewer: &Viewer,
478
    owner: &str,
479
    name: &str,
480
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
481
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
482
}
483
484
/// Fill `account` on change authors whose key is linked to an account.
485
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
486
    if changes.is_empty() {
487
        return;
488
    }
489
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
490
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
491
    for c in changes.iter_mut() {
492
        if let Some(u) = map.get(&c.author.key) {
493
            c.author.account = Some(u.clone());
494
        }
495
    }
496
}