OXYGENHUB
# 3f02e5ea4f2d oxygenhub / crates / hub / src / web / mod.rs
16.9 KiB · Rust · last changed Milestone 0.5: API, webhooks, checks 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 mod filters;
8
pub mod history;
9
mod home;
10
mod inbox;
11
pub mod issues;
12
mod orgs;
13
pub mod proposals;
14
mod refs;
15
mod repo;
16
mod repo_settings;
17
mod session;
18
mod settings;
19
mod statics;
20
21
use crate::auth::{self, Access, Role, Viewer};
22
use crate::repos::RepoError;
23
use crate::{db, Shared};
24
use askama::Template;
25
use axum::extract::DefaultBodyLimit;
26
use axum::http::{header, StatusCode};
27
use axum::response::{Html, IntoResponse, Redirect, Response};
28
use axum::routing::{any, get, post};
29
use axum::Router;
30
use tower_http::compression::CompressionLayer;
31
use tower_http::trace::TraceLayer;
32
33
pub fn router(app: Shared) -> Router {
34
    let push_limit = app.config.limits.push_body_limit.0 as usize;
35
    Router::new()
36
        .route("/", get(home::index))
37
        .route("/explore", get(home::explore))
38
        .route("/health", get(home::health))
39
        .route("/.well-known/oxyhub-key", get(home::hub_key))
40
        .route("/style.css", get(statics::style))
41
        .route("/favicon.svg", get(statics::favicon))
42
        .route("/favicon.ico", get(statics::favicon))
43
        .route("/static/{*path}", get(statics::asset))
44
        .route("/login", get(session::login_form).post(session::login))
45
        .route("/logout", post(session::logout))
46
        .route("/register", get(session::register_form).post(session::register))
47
        .route("/settings", get(settings::profile).post(settings::update_profile))
48
        .route("/settings/password", post(settings::change_password))
49
        .route("/settings/security", get(settings::security))
50
        .route("/settings/security/totp/begin", post(settings::totp_begin))
51
        .route("/settings/security/totp/enable", post(settings::totp_enable))
52
        .route("/settings/security/totp/disable", post(settings::totp_disable))
53
        .route("/settings/security/sessions", post(settings::sessions_reset))
54
        .route("/settings/keys", get(settings::keys))
55
        .route("/settings/keys/upload", post(settings::keys_upload))
56
        .route("/settings/keys/verify", post(settings::keys_verify))
57
        .route("/settings/keys/unlink", post(settings::keys_unlink))
58
        .route("/settings/tokens", get(settings::tokens).post(settings::tokens_create))
59
        .route("/settings/tokens/{id}/delete", post(settings::tokens_delete))
60
        .route("/new", get(repo_settings::new_form).post(repo_settings::create))
61
        .route("/orgs/new", get(orgs::new_form).post(orgs::create))
62
        .route("/orgs/{name}/settings", get(orgs::settings).post(orgs::update))
63
        .route("/orgs/{name}/settings/members", post(orgs::member))
64
        .route("/orgs/{name}/settings/teams", post(orgs::team))
65
        .route("/notifications", get(inbox::inbox))
66
        .route("/notifications/read", post(inbox::mark_read))
67
        .route("/settings/notifications", get(inbox::unsubscribe).post(inbox::prefs))
68
        .route("/search", get(inbox::search))
69
        .route("/admin", get(admin::index))
70
        .route("/admin/registration", post(admin::set_mode))
71
        .route("/admin/invite", post(admin::invite))
72
        .route("/admin/account", post(admin::account))
73
        .nest("/api/v1", crate::api::router())
74
        .route("/{owner}", get(home::owner))
75
        .route("/{owner}/{name}", get(repo::overview))
76
        .route("/{owner}/{name}/tree/{r}", get(repo::tree_root))
77
        .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree))
78
        .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file))
79
        .route("/{owner}/{name}/last/{r}", get(repo::last_changes))
80
        .route("/{owner}/{name}/changes/{r}", get(history::history))
81
        .route("/{owner}/{name}/change/{hash}", get(history::change))
82
        .route("/{owner}/{name}/compare/{spec}", get(history::compare))
83
        .route("/{owner}/{name}/bookmarks", get(refs::bookmarks))
84
        .route("/{owner}/{name}/tags", get(refs::tags))
85
        .route("/{owner}/{name}/conflicts", get(refs::conflicts))
86
        .route("/{owner}/{name}/trust", get(refs::trust))
87
        .route("/{owner}/{name}/pushes", get(refs::pushes))
88
        .route("/{owner}/{name}/settings", get(repo_settings::settings).post(repo_settings::update))
89
        .route("/{owner}/{name}/settings/collaborators", post(repo_settings::collaborator))
90
        .route("/{owner}/{name}/settings/delete", post(repo_settings::delete))
91
        .route("/{owner}/{name}/settings/requirements", post(repo_settings::requirements))
92
        .route("/{owner}/{name}/proposals", get(proposals::list))
93
        .route("/{owner}/{name}/proposals/new", get(proposals::new_form).post(proposals::create))
94
        .route("/{owner}/{name}/proposal/{number}", get(proposals::show))
95
        .route("/{owner}/{name}/proposal/{number}/comment", post(proposals::comment))
96
        .route("/{owner}/{name}/proposal/{number}/comment/{id}/resolve", post(proposals::resolve_comment))
97
        .route("/{owner}/{name}/proposal/{number}/review", post(proposals::review))
98
        .route("/{owner}/{name}/proposal/{number}/edit", post(proposals::edit))
99
        .route("/{owner}/{name}/proposal/{number}/state", post(proposals::state))
100
        .route("/{owner}/{name}/proposal/{number}/land", post(proposals::land))
101
        .route("/{owner}/{name}/proposal/{number}/labels", post(proposals::set_labels))
102
        .route("/{owner}/{name}/proposal/{number}/events", get(proposals::events))
103
        .route("/{owner}/{name}/settings/hooks", post(repo_settings::hooks))
104
        .route("/{owner}/{name}/settings/hooks/{id}/deliveries", get(repo_settings::deliveries))
105
        .route("/{owner}/{name}/settings/hooks/{id}/redeliver/{delivery}", post(repo_settings::redeliver))
106
        .route("/{owner}/{name}/settings/checks", post(repo_settings::required_checks))
107
        .route("/{owner}/{name}/watch", post(issues::watch))
108
        .route("/{owner}/{name}/issues", get(issues::list))
109
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
110
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
111
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
112
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
113
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
114
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
115
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
116
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
117
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
118
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
119
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
120
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
121
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
122
        .fallback(not_found)
123
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
124
        .layer(CompressionLayer::new())
125
        .layer(TraceLayer::new_for_http())
126
        .with_state(app)
127
}
128
129
/// Cross-site form posts are refused (hub spec §15.2): a browser that
130
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
131
/// API clients send neither.
132
async fn same_origin(
133
    axum::extract::State(app): axum::extract::State<Shared>,
134
    req: axum::extract::Request,
135
    next: axum::middleware::Next,
136
) -> Response {
137
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
138
        let headers = req.headers();
139
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
140
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
141
        }
142
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
143
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
144
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
145
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
146
            if !ok && origin != "null" {
147
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
148
            }
149
        }
150
    }
151
    next.run(req).await
152
}
153
154
/// What every page's chrome needs.
155
#[derive(Clone, Debug)]
156
pub struct Shell {
157
    pub site: String,
158
    pub base_url: String,
159
    pub path: String,
160
    pub version: &'static str,
161
    /// The signed-in username, if any.
162
    pub user: Option<String>,
163
    pub is_admin: bool,
164
    pub csrf: String,
165
    pub unread: i64,
166
}
167
168
impl Shell {
169
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
170
        Shell {
171
            site: app.config.site.name.clone(),
172
            base_url: app.config.base_url().to_string(),
173
            path: path.to_string(),
174
            version: env!("CARGO_PKG_VERSION"),
175
            user: viewer.account().map(|a| a.username.clone()),
176
            is_admin: viewer.is_admin(),
177
            csrf: viewer.csrf().to_string(),
178
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
179
        }
180
    }
181
182
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
183
        Shell::new(app, path, &Viewer(None))
184
    }
185
}
186
187
/// The repository chrome: tabs and counts.
188
#[derive(Clone, Debug)]
189
pub struct RepoShell {
190
    pub owner: String,
191
    pub name: String,
192
    pub url: String,
193
    pub description: String,
194
    pub default_bookmark: String,
195
    pub visibility: String,
196
    pub tab: &'static str,
197
    pub clone_url: String,
198
    /// The viewer's role, for showing settings and write actions.
199
    pub role: Option<Role>,
200
}
201
202
impl RepoShell {
203
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
204
        RepoShell {
205
            owner: row.owner.clone(),
206
            name: row.name.clone(),
207
            url: format!("/{}/{}", row.owner, row.name),
208
            description: row.description.clone(),
209
            default_bookmark: row.default_bookmark.clone(),
210
            visibility: row.visibility.clone(),
211
            tab,
212
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
213
            role: None,
214
        }
215
    }
216
217
    pub fn with_role(mut self, role: Role) -> RepoShell {
218
        self.role = Some(role);
219
        self
220
    }
221
222
    pub fn can(&self, access: Access) -> bool {
223
        auth::roles::allows(self.role, access)
224
    }
225
226
    pub fn can_maintain(&self) -> bool {
227
        self.can(Access::Maintain)
228
    }
229
}
230
231
/// Render a template as an HTML response.
232
pub struct Page<T: Template>(pub T);
233
234
impl<T: Template> IntoResponse for Page<T> {
235
    fn into_response(self) -> Response {
236
        match self.0.render() {
237
            Ok(s) => Html(s).into_response(),
238
            Err(e) => {
239
                tracing::error!("template: {e}");
240
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
241
            }
242
        }
243
    }
244
}
245
246
#[derive(Template)]
247
#[template(path = "error.html")]
248
struct ErrorPage {
249
    shell: Shell,
250
    status: u16,
251
    title: String,
252
    detail: String,
253
}
254
255
/// A page-level failure, rendered inside the shell, or a redirect.
256
#[derive(Debug)]
257
pub struct Error {
258
    pub status: StatusCode,
259
    pub detail: String,
260
    shell: Option<Box<Shell>>,
261
    redirect: Option<String>,
262
}
263
264
impl Error {
265
    pub fn redirect(to: String) -> Error {
266
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
267
    }
268
269
    pub fn not_found(shell: Shell) -> Error {
270
        Error {
271
            status: StatusCode::NOT_FOUND,
272
            detail: "There is nothing at this address.".into(),
273
            shell: Some(Box::new(shell)),
274
            redirect: None,
275
        }
276
    }
277
278
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
279
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
280
    }
281
282
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
283
        match e {
284
            RepoError::NotFound => Error::not_found(shell),
285
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
286
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
287
            }
288
            other => {
289
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
290
            }
291
        }
292
    }
293
294
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
295
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
296
    }
297
}
298
299
impl IntoResponse for Error {
300
    fn into_response(self) -> Response {
301
        if let Some(to) = self.redirect {
302
            return Redirect::to(&to).into_response();
303
        }
304
        let title = match self.status {
305
            StatusCode::NOT_FOUND => "Not found",
306
            StatusCode::BAD_REQUEST => "Bad request",
307
            _ => "Something went wrong",
308
        };
309
        if self.status.is_server_error() {
310
            tracing::error!("{}", self.detail);
311
        }
312
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
313
            site: "Oxygenhub".into(),
314
            base_url: String::new(),
315
            path: String::new(),
316
            version: "",
317
            user: None,
318
            is_admin: false,
319
            csrf: String::new(),
320
            unread: 0,
321
        });
322
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
323
        match page.render() {
324
            Ok(s) => (self.status, Html(s)).into_response(),
325
            Err(_) => (self.status, title).into_response(),
326
        }
327
    }
328
}
329
330
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
331
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
332
}
333
334
/// A raw file response with a safe content type (hub spec §15.2).
335
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
336
    let mime = mime_of(name);
337
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
338
    (
339
        [
340
            (header::CONTENT_TYPE, mime.to_string()),
341
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
342
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
343
        ],
344
        bytes,
345
    )
346
        .into_response()
347
}
348
349
pub fn mime_of(name: &str) -> &'static str {
350
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
351
        Some("png") => "image/png",
352
        Some("jpg" | "jpeg") => "image/jpeg",
353
        Some("gif") => "image/gif",
354
        Some("webp") => "image/webp",
355
        Some("svg") => "image/svg+xml",
356
        Some("pdf") => "application/pdf",
357
        Some(
358
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
359
        ) => "text/plain; charset=utf-8",
360
        _ => "application/octet-stream",
361
    }
362
}
363
364
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
365
/// a repository the viewer may not see does not exist for them (hub spec
366
/// §4.4). Returns the viewer's role too.
367
pub async fn lookup_role(
368
    app: &Shared,
369
    shell: &Shell,
370
    viewer: &Viewer,
371
    owner: &str,
372
    name: &str,
373
    access: Access,
374
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
375
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
376
    let row = db::repos::get(&app.db, owner, name)
377
        .await
378
        .map_err(|e| Error::from_db(shell.clone(), e))?
379
        .ok_or_else(|| Error::not_found(shell.clone()))?;
380
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
381
    if !auth::roles::allows(role, access) {
382
        return Err(Error::not_found(shell.clone()));
383
    }
384
    Ok((repo, row, role.unwrap_or(Role::Read)))
385
}
386
387
/// `lookup_role` for reading.
388
pub async fn lookup(
389
    app: &Shared,
390
    shell: &Shell,
391
    viewer: &Viewer,
392
    owner: &str,
393
    name: &str,
394
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
395
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
396
}
397
398
/// Fill `account` on change authors whose key is linked to an account.
399
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
400
    if changes.is_empty() {
401
        return;
402
    }
403
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
404
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
405
    for c in changes.iter_mut() {
406
        if let Some(u) = map.get(&c.author.key) {
407
            c.author.account = Some(u.clone());
408
        }
409
    }
410
}