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