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