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