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