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