OXYGENHUB
# 18e381ea88c2 oxygenhub / crates / hub / src / web / mod.rs
16.5 KiB · Rust · last changed Milestone 0.4: issues and notifications 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
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}/watch", post(issues::watch))
103
        .route("/{owner}/{name}/issues", get(issues::list))
104
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
105
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
106
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
107
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
108
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
109
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
110
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
111
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
112
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
113
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
114
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
115
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
116
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
117
        .fallback(not_found)
118
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
119
        .layer(CompressionLayer::new())
120
        .layer(TraceLayer::new_for_http())
121
        .with_state(app)
122
}
123
124
/// Cross-site form posts are refused (hub spec §15.2): a browser that
125
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
126
/// API clients send neither.
127
async fn same_origin(
128
    axum::extract::State(app): axum::extract::State<Shared>,
129
    req: axum::extract::Request,
130
    next: axum::middleware::Next,
131
) -> Response {
132
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
133
        let headers = req.headers();
134
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
135
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
136
        }
137
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
138
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
139
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
140
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
141
            if !ok && origin != "null" {
142
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
143
            }
144
        }
145
    }
146
    next.run(req).await
147
}
148
149
/// What every page's chrome needs.
150
#[derive(Clone, Debug)]
151
pub struct Shell {
152
    pub site: String,
153
    pub base_url: String,
154
    pub path: String,
155
    pub version: &'static str,
156
    /// The signed-in username, if any.
157
    pub user: Option<String>,
158
    pub is_admin: bool,
159
    pub csrf: String,
160
    pub unread: i64,
161
}
162
163
impl Shell {
164
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
165
        Shell {
166
            site: app.config.site.name.clone(),
167
            base_url: app.config.base_url().to_string(),
168
            path: path.to_string(),
169
            version: env!("CARGO_PKG_VERSION"),
170
            user: viewer.account().map(|a| a.username.clone()),
171
            is_admin: viewer.is_admin(),
172
            csrf: viewer.csrf().to_string(),
173
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
174
        }
175
    }
176
177
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
178
        Shell::new(app, path, &Viewer(None))
179
    }
180
}
181
182
/// The repository chrome: tabs and counts.
183
#[derive(Clone, Debug)]
184
pub struct RepoShell {
185
    pub owner: String,
186
    pub name: String,
187
    pub url: String,
188
    pub description: String,
189
    pub default_bookmark: String,
190
    pub visibility: String,
191
    pub tab: &'static str,
192
    pub clone_url: String,
193
    /// The viewer's role, for showing settings and write actions.
194
    pub role: Option<Role>,
195
}
196
197
impl RepoShell {
198
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
199
        RepoShell {
200
            owner: row.owner.clone(),
201
            name: row.name.clone(),
202
            url: format!("/{}/{}", row.owner, row.name),
203
            description: row.description.clone(),
204
            default_bookmark: row.default_bookmark.clone(),
205
            visibility: row.visibility.clone(),
206
            tab,
207
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
208
            role: None,
209
        }
210
    }
211
212
    pub fn with_role(mut self, role: Role) -> RepoShell {
213
        self.role = Some(role);
214
        self
215
    }
216
217
    pub fn can(&self, access: Access) -> bool {
218
        auth::roles::allows(self.role, access)
219
    }
220
221
    pub fn can_maintain(&self) -> bool {
222
        self.can(Access::Maintain)
223
    }
224
}
225
226
/// Render a template as an HTML response.
227
pub struct Page<T: Template>(pub T);
228
229
impl<T: Template> IntoResponse for Page<T> {
230
    fn into_response(self) -> Response {
231
        match self.0.render() {
232
            Ok(s) => Html(s).into_response(),
233
            Err(e) => {
234
                tracing::error!("template: {e}");
235
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
236
            }
237
        }
238
    }
239
}
240
241
#[derive(Template)]
242
#[template(path = "error.html")]
243
struct ErrorPage {
244
    shell: Shell,
245
    status: u16,
246
    title: String,
247
    detail: String,
248
}
249
250
/// A page-level failure, rendered inside the shell, or a redirect.
251
#[derive(Debug)]
252
pub struct Error {
253
    pub status: StatusCode,
254
    pub detail: String,
255
    shell: Option<Box<Shell>>,
256
    redirect: Option<String>,
257
}
258
259
impl Error {
260
    pub fn redirect(to: String) -> Error {
261
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
262
    }
263
264
    pub fn not_found(shell: Shell) -> Error {
265
        Error {
266
            status: StatusCode::NOT_FOUND,
267
            detail: "There is nothing at this address.".into(),
268
            shell: Some(Box::new(shell)),
269
            redirect: None,
270
        }
271
    }
272
273
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
274
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
275
    }
276
277
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
278
        match e {
279
            RepoError::NotFound => Error::not_found(shell),
280
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
281
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
282
            }
283
            other => {
284
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
285
            }
286
        }
287
    }
288
289
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
290
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
291
    }
292
}
293
294
impl IntoResponse for Error {
295
    fn into_response(self) -> Response {
296
        if let Some(to) = self.redirect {
297
            return Redirect::to(&to).into_response();
298
        }
299
        let title = match self.status {
300
            StatusCode::NOT_FOUND => "Not found",
301
            StatusCode::BAD_REQUEST => "Bad request",
302
            _ => "Something went wrong",
303
        };
304
        if self.status.is_server_error() {
305
            tracing::error!("{}", self.detail);
306
        }
307
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
308
            site: "Oxygenhub".into(),
309
            base_url: String::new(),
310
            path: String::new(),
311
            version: "",
312
            user: None,
313
            is_admin: false,
314
            csrf: String::new(),
315
            unread: 0,
316
        });
317
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
318
        match page.render() {
319
            Ok(s) => (self.status, Html(s)).into_response(),
320
            Err(_) => (self.status, title).into_response(),
321
        }
322
    }
323
}
324
325
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
326
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
327
}
328
329
/// A raw file response with a safe content type (hub spec §15.2).
330
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
331
    let mime = mime_of(name);
332
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
333
    (
334
        [
335
            (header::CONTENT_TYPE, mime.to_string()),
336
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
337
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
338
        ],
339
        bytes,
340
    )
341
        .into_response()
342
}
343
344
pub fn mime_of(name: &str) -> &'static str {
345
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
346
        Some("png") => "image/png",
347
        Some("jpg" | "jpeg") => "image/jpeg",
348
        Some("gif") => "image/gif",
349
        Some("webp") => "image/webp",
350
        Some("svg") => "image/svg+xml",
351
        Some("pdf") => "application/pdf",
352
        Some(
353
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
354
        ) => "text/plain; charset=utf-8",
355
        _ => "application/octet-stream",
356
    }
357
}
358
359
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
360
/// a repository the viewer may not see does not exist for them (hub spec
361
/// §4.4). Returns the viewer's role too.
362
pub async fn lookup_role(
363
    app: &Shared,
364
    shell: &Shell,
365
    viewer: &Viewer,
366
    owner: &str,
367
    name: &str,
368
    access: Access,
369
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
370
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
371
    let row = db::repos::get(&app.db, owner, name)
372
        .await
373
        .map_err(|e| Error::from_db(shell.clone(), e))?
374
        .ok_or_else(|| Error::not_found(shell.clone()))?;
375
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
376
    if !auth::roles::allows(role, access) {
377
        return Err(Error::not_found(shell.clone()));
378
    }
379
    Ok((repo, row, role.unwrap_or(Role::Read)))
380
}
381
382
/// `lookup_role` for reading.
383
pub async fn lookup(
384
    app: &Shared,
385
    shell: &Shell,
386
    viewer: &Viewer,
387
    owner: &str,
388
    name: &str,
389
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
390
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
391
}
392
393
/// Fill `account` on change authors whose key is linked to an account.
394
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
395
    if changes.is_empty() {
396
        return;
397
    }
398
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
399
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
400
    for c in changes.iter_mut() {
401
        if let Some(u) = map.get(&c.author.key) {
402
            c.author.account = Some(u.clone());
403
        }
404
    }
405
}