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