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