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