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