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