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