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