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