OXYGENHUB
# 8f3d2ccfe6fc oxygenhub / crates / hub / src / web / mod.rs
8.0 KiB · Rust · last changed Serve the self-signed certificate at /.well-known/oxyhub-ca.pem; connecting notes on the trust page 1 month ago source blame history raw
1
//! Pages (hub spec §6): the router, the shell every template extends, the
2
//! error page, and askama filters. Handlers are thin: they resolve names,
3
//! call the view layer under the repository lock, and render.
4
5
pub mod filters;
6
mod history;
7
mod home;
8
mod refs;
9
mod repo;
10
mod statics;
11
12
use crate::repos::RepoError;
13
use crate::{db, Shared};
14
use askama::Template;
15
use axum::extract::DefaultBodyLimit;
16
use axum::http::{header, StatusCode};
17
use axum::response::{Html, IntoResponse, Response};
18
use axum::routing::{any, get};
19
use axum::Router;
20
use tower_http::compression::CompressionLayer;
21
use tower_http::trace::TraceLayer;
22
23
pub fn router(app: Shared) -> Router {
24
    let push_limit = app.config.limits.push_body_limit.0 as usize;
25
    Router::new()
26
        .route("/", get(home::index))
27
        .route("/explore", get(home::explore))
28
        .route("/health", get(home::health))
29
        .route("/.well-known/oxyhub-key", get(home::hub_key))
30
        .route("/.well-known/oxyhub-ca.pem", get(home::hub_ca))
31
        .route("/style.css", get(statics::style))
32
        .route("/favicon.svg", get(statics::favicon))
33
        .route("/favicon.ico", get(statics::favicon))
34
        .route("/static/{*path}", get(statics::asset))
35
        .nest("/api/v1", crate::api::router())
36
        .route("/{owner}", get(home::owner))
37
        .route("/{owner}/{name}", get(repo::overview))
38
        .route("/{owner}/{name}/tree/{r}", get(repo::tree_root))
39
        .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree))
40
        .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file))
41
        .route("/{owner}/{name}/last/{r}", get(repo::last_changes))
42
        .route("/{owner}/{name}/changes/{r}", get(history::history))
43
        .route("/{owner}/{name}/change/{hash}", get(history::change))
44
        .route("/{owner}/{name}/compare/{spec}", get(history::compare))
45
        .route("/{owner}/{name}/bookmarks", get(refs::bookmarks))
46
        .route("/{owner}/{name}/tags", get(refs::tags))
47
        .route("/{owner}/{name}/conflicts", get(refs::conflicts))
48
        .route("/{owner}/{name}/trust", get(refs::trust))
49
        .route("/{owner}/{name}/pushes", get(refs::pushes))
50
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
51
        .fallback(not_found)
52
        .layer(CompressionLayer::new())
53
        .layer(TraceLayer::new_for_http())
54
        .with_state(app)
55
}
56
57
/// What every page's chrome needs.
58
#[derive(Clone, Debug)]
59
pub struct Shell {
60
    pub site: String,
61
    pub base_url: String,
62
    pub path: String,
63
    pub version: &'static str,
64
}
65
66
impl Shell {
67
    pub fn new(app: &Shared, path: &str) -> Shell {
68
        Shell {
69
            site: app.config.site.name.clone(),
70
            base_url: app.config.base_url().to_string(),
71
            path: path.to_string(),
72
            version: env!("CARGO_PKG_VERSION"),
73
        }
74
    }
75
}
76
77
/// The repository chrome: tabs and counts.
78
#[derive(Clone, Debug)]
79
pub struct RepoShell {
80
    pub owner: String,
81
    pub name: String,
82
    pub url: String,
83
    pub description: String,
84
    pub default_bookmark: String,
85
    pub visibility: String,
86
    pub tab: &'static str,
87
    pub clone_url: String,
88
}
89
90
impl RepoShell {
91
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
92
        RepoShell {
93
            owner: row.owner.clone(),
94
            name: row.name.clone(),
95
            url: format!("/{}/{}", row.owner, row.name),
96
            description: row.description.clone(),
97
            default_bookmark: row.default_bookmark.clone(),
98
            visibility: row.visibility.clone(),
99
            tab,
100
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
101
        }
102
    }
103
}
104
105
/// Render a template as an HTML response.
106
pub struct Page<T: Template>(pub T);
107
108
impl<T: Template> IntoResponse for Page<T> {
109
    fn into_response(self) -> Response {
110
        match self.0.render() {
111
            Ok(s) => Html(s).into_response(),
112
            Err(e) => {
113
                tracing::error!("template: {e}");
114
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
115
            }
116
        }
117
    }
118
}
119
120
#[derive(Template)]
121
#[template(path = "error.html")]
122
struct ErrorPage {
123
    shell: Shell,
124
    status: u16,
125
    title: String,
126
    detail: String,
127
}
128
129
/// A page-level failure, rendered inside the shell.
130
#[derive(Debug)]
131
pub struct Error {
132
    pub status: StatusCode,
133
    pub detail: String,
134
    shell: Option<Shell>,
135
}
136
137
impl Error {
138
    pub fn not_found(shell: Shell) -> Error {
139
        Error { status: StatusCode::NOT_FOUND, detail: "There is nothing at this address.".into(), shell: Some(shell) }
140
    }
141
142
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
143
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(shell) }
144
    }
145
146
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
147
        match e {
148
            RepoError::NotFound => Error::not_found(shell),
149
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(shell) },
150
            other => Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(shell) },
151
        }
152
    }
153
154
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
155
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(shell) }
156
    }
157
}
158
159
impl IntoResponse for Error {
160
    fn into_response(self) -> Response {
161
        let title = match self.status {
162
            StatusCode::NOT_FOUND => "Not found",
163
            StatusCode::BAD_REQUEST => "Bad request",
164
            _ => "Something went wrong",
165
        };
166
        if self.status.is_server_error() {
167
            tracing::error!("{}", self.detail);
168
        }
169
        let shell = self.shell.unwrap_or(Shell { site: "Oxygenhub".into(), base_url: String::new(), path: String::new(), version: "" });
170
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
171
        match page.render() {
172
            Ok(s) => (self.status, Html(s)).into_response(),
173
            Err(_) => (self.status, title).into_response(),
174
        }
175
    }
176
}
177
178
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, uri: axum::http::Uri) -> Response {
179
    Error::not_found(Shell::new(&app, uri.path())).into_response()
180
}
181
182
/// A raw file response with a safe content type (hub spec §15.2).
183
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
184
    let mime = mime_of(name);
185
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
186
    (
187
        [
188
            (header::CONTENT_TYPE, mime.to_string()),
189
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
190
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
191
        ],
192
        bytes,
193
    )
194
        .into_response()
195
}
196
197
pub fn mime_of(name: &str) -> &'static str {
198
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
199
        Some("png") => "image/png",
200
        Some("jpg" | "jpeg") => "image/jpeg",
201
        Some("gif") => "image/gif",
202
        Some("webp") => "image/webp",
203
        Some("svg") => "image/svg+xml",
204
        Some("pdf") => "application/pdf",
205
        Some(
206
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
207
        ) => "text/plain; charset=utf-8",
208
        _ => "application/octet-stream",
209
    }
210
}
211
212
/// Resolve `{owner}/{name}` to its row, or 404. Private repositories are
213
/// invisible until accounts exist (hub 0.2).
214
pub async fn lookup(app: &Shared, shell: &Shell, owner: &str, name: &str) -> Result<(crate::repos::RepoName, db::repos::RepoRow), Error> {
215
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
216
    let row = db::repos::get(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))?;
217
    match row {
218
        Some(r) if r.visibility() == hub_api::Visibility::Public => Ok((repo, r)),
219
        _ => Err(Error::not_found(shell.clone())),
220
    }
221
}