Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle serving from a sub-path #48

Merged
merged 5 commits into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ jobs:
components: clippy
- run: cargo clippy -- -W clippy::pedantic
- run: cargo test
- run: WASTEBIN_BASE_URL="http://127.0.0.1:8080/wastebin" cargo test # port is not relevant
53 changes: 53 additions & 0 deletions src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,25 @@ pub enum Error {
HttpTimeout(ParseIntError),
}

pub struct BasePath(String);

impl BasePath {
pub fn path(&self) -> &str {
&self.0
}

pub fn join(&self, s: &str) -> String {
let b = &self.0;
format!("{b}{s}")
}
}

impl Default for BasePath {
fn default() -> Self {
BasePath("/".to_string())
}
}

/// Retrieve reference to initialized metadata.
pub fn metadata() -> &'static Metadata<'static> {
static DATA: OnceLock<Metadata> = OnceLock::new();
Expand Down Expand Up @@ -119,6 +138,40 @@ pub fn base_url() -> Result<Option<url::Url>, Error> {
Ok(result)
}

pub fn base_path() -> &'static BasePath {
// NOTE: This relies on `VAR_BASE_URL` but repeates parsing to handle errors.
static BASE_PATH: OnceLock<BasePath> = OnceLock::new();

BASE_PATH.get_or_init(|| {
std::env::var(VAR_BASE_URL).map_or_else(
|err| {
match err {
VarError::NotPresent => (),
VarError::NotUnicode(_) => {
tracing::warn!("`VAR_BASE_URL` not Unicode, defaulting to '/'")
}
};
BasePath::default()
},
|var| match url::Url::parse(&var) {
Ok(url) => {
let path = url.path();

if path.ends_with('/') {
BasePath(path.to_string())
} else {
BasePath(format!("{path}/"))
}
}
Err(err) => {
tracing::error!("error parsing `VAR_BASE_URL`, defaulting to '/': {err}");
BasePath::default()
}
},
)
})
}

pub fn password_hash_salt() -> String {
std::env::var(VAR_PASSWORD_SALT).unwrap_or_else(|_| "somesalt".to_string())
}
Expand Down
2 changes: 1 addition & 1 deletion src/highlight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ pub struct Data<'a> {
impl<'a> Css<'a> {
fn new(name: &str, content: &'a str) -> Self {
let name = format!(
"/{name}.{}.css",
"{name}.{}.css",
hex::encode(Sha256::digest(content.as_bytes()))
.get(0..16)
.expect("at least 16 characters")
Expand Down
2 changes: 1 addition & 1 deletion src/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl Id {
entry
.extension
.as_ref()
.map_or_else(|| format!("/{self}"), |ext| format!("/{self}.{ext}"))
.map_or_else(|| format!("{self}"), |ext| format!("{self}.{ext}"))
}
}

Expand Down
21 changes: 13 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;
use url::Url;

use self::env::base_path;

mod cache;
mod crypto;
mod db;
Expand Down Expand Up @@ -42,14 +44,17 @@ impl FromRef<AppState> for Key {
}

pub(crate) fn make_app(max_body_size: usize, timeout: Duration) -> Router<AppState> {
Router::new().merge(routes::routes()).layer(
ServiceBuilder::new()
.layer(DefaultBodyLimit::max(max_body_size))
.layer(DefaultBodyLimit::disable())
.layer(CompressionLayer::new())
.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::new(timeout)),
)
let base_path = base_path();
Router::new()
.nest(base_path.path(), routes::routes())
.layer(
ServiceBuilder::new()
.layer(DefaultBodyLimit::max(max_body_size))
.layer(DefaultBodyLimit::disable())
.layer(CompressionLayer::new())
.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::new(timeout)),
)
}

async fn shutdown_signal() {
Expand Down
12 changes: 12 additions & 0 deletions src/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::default::Default;
#[template(path = "error.html")]
pub struct Error<'a> {
meta: &'a env::Metadata<'a>,
base_path: &'static env::BasePath,
error: String,
}

Expand All @@ -21,6 +22,7 @@ impl From<crate::Error> for ErrorResponse<'_> {
fn from(err: crate::Error) -> Self {
let html = Error {
meta: env::metadata(),
base_path: env::base_path(),
error: err.to_string(),
};

Expand All @@ -33,12 +35,14 @@ impl From<crate::Error> for ErrorResponse<'_> {
#[template(path = "index.html")]
pub struct Index<'a> {
meta: &'a env::Metadata<'a>,
base_path: &'static env::BasePath,
}

impl<'a> Default for Index<'a> {
fn default() -> Self {
Self {
meta: env::metadata(),
base_path: env::base_path(),
}
}
}
Expand All @@ -48,6 +52,7 @@ impl<'a> Default for Index<'a> {
#[template(path = "formatted.html")]
pub struct Paste<'a> {
meta: &'a env::Metadata<'a>,
base_path: &'static env::BasePath,
id: String,
ext: String,
can_delete: bool,
Expand All @@ -61,6 +66,7 @@ impl<'a> Paste<'a> {

Self {
meta: env::metadata(),
base_path: env::base_path(),
id: key.id(),
ext: key.ext,
can_delete,
Expand All @@ -74,6 +80,7 @@ impl<'a> Paste<'a> {
#[template(path = "encrypted.html")]
pub struct Encrypted<'a> {
meta: &'a env::Metadata<'a>,
base_path: &'static env::BasePath,
id: String,
ext: String,
query: String,
Expand All @@ -91,6 +98,7 @@ impl<'a> Encrypted<'a> {

Self {
meta: env::metadata(),
base_path: env::base_path(),
id: key.id(),
ext: key.ext,
query,
Expand All @@ -103,6 +111,7 @@ impl<'a> Encrypted<'a> {
#[template(path = "qr.html", escape = "none")]
pub struct Qr<'a> {
meta: &'a env::Metadata<'a>,
base_path: &'static env::BasePath,
id: String,
ext: String,
can_delete: bool,
Expand All @@ -114,6 +123,7 @@ impl<'a> Qr<'a> {
pub fn new(code: qrcodegen::QrCode, key: CacheKey) -> Self {
Self {
meta: env::metadata(),
base_path: env::base_path(),
id: key.id(),
ext: key.ext,
code,
Expand All @@ -136,6 +146,7 @@ impl<'a> Qr<'a> {
#[template(path = "burn.html")]
pub struct Burn<'a> {
meta: &'a env::Metadata<'a>,
base_path: &'static env::BasePath,
id: String,
}

Expand All @@ -144,6 +155,7 @@ impl<'a> Burn<'a> {
pub fn new(id: String) -> Self {
Self {
meta: env::metadata(),
base_path: env::base_path(),
id,
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/routes/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ fn favicon() -> impl IntoResponse {
}

pub fn routes() -> Router<AppState> {
let style_name = &data().style.name;
Router::new()
.route("/favicon.png", get(|| async { favicon() }))
.route(&data().style.name, get(|| async { style_css() }))
.route(&format!("/{style_name}"), get(|| async { style_css() }))
.route("/dark.css", get(|| async { dark_css() }))
.route("/light.css", get(|| async { light_css() }))
}
16 changes: 9 additions & 7 deletions src/routes/form.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::db::write;
use crate::env::base_path;
use crate::id::Id;
use crate::{pages, AppState, Error};
use axum::extract::{Form, State};
Expand Down Expand Up @@ -62,16 +63,17 @@ pub async fn insert(
let mut entry: write::Entry = entry.into();
entry.uid = Some(uid);

let url = id.to_url_path(&entry);
let mut url = id.to_url_path(&entry);

let burn_after_reading = entry.burn_after_reading.unwrap_or(false);
if burn_after_reading {
url = format!("burn/{url}");
}

let url_with_base = base_path().join(&url);

state.db.insert(id, entry).await?;

let jar = jar.add(Cookie::new("uid", uid.to_string()));

if burn_after_reading {
Ok((jar, Redirect::to(&format!("/burn{url}"))))
} else {
Ok((jar, Redirect::to(&url)))
}
Ok((jar, Redirect::to(&url_with_base)))
}
4 changes: 3 additions & 1 deletion src/routes/json.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::db::write;
use crate::env::base_path;
use crate::errors::{Error, JsonErrorResponse};
use crate::id::Id;
use crate::AppState;
Expand Down Expand Up @@ -47,8 +48,9 @@ pub async fn insert(
.into();

let entry: write::Entry = entry.into();
let path = id.to_url_path(&entry);

let url = id.to_url_path(&entry);
let path = base_path().join(&url);
state.db.insert(id, entry).await?;

Ok(Json::from(RedirectResponse { path }))
Expand Down
Loading
Loading