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