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