Skip to content
This repository was archived by the owner on Oct 18, 2023. It is now read-only.

Commit

Permalink
handle host header error
Browse files Browse the repository at this point in the history
  • Loading branch information
MarinPostma committed Aug 8, 2023
1 parent b35fabf commit 19b640f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
2 changes: 2 additions & 0 deletions sqld/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ pub enum Error {
// Catch-all error since we use anyhow in certain places
#[error("Internal Error: `{0}`")]
Anyhow(#[from] anyhow::Error),
#[error("Invalid host header: `{0}`")]
InvalidHost(String),
}

impl Error {
Expand Down
17 changes: 13 additions & 4 deletions sqld/src/http/db_factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use bytes::Bytes;
use hyper::http::request::Parts;

use crate::database::factory::DbFactory;
use crate::error::Error;
use crate::namespace::NamespaceFactory;

use super::AppState;
Expand All @@ -16,14 +17,20 @@ impl<F> FromRequestParts<AppState<F>> for DbFactoryExtractor<F::Database>
where
F: NamespaceFactory,
{
type Rejection = crate::error::Error;
type Rejection = Error;

async fn from_request_parts(
parts: &mut Parts,
state: &AppState<F>,
) -> Result<Self, Self::Rejection> {
let host = parts.headers.get("host").unwrap().as_bytes();
let ns = split_namespace(std::str::from_utf8(host).unwrap())?;
let host = parts
.headers
.get("host")
.ok_or_else(|| Error::InvalidHost("missing host header".into()))?
.as_bytes();
let host_str = std::str::from_utf8(host)
.map_err(|_| Error::InvalidHost("host header is not valid UTF-8".into()))?;
let ns = split_namespace(host_str)?;
Ok(Self(
state
.namespaces
Expand All @@ -34,7 +41,9 @@ where
}

pub fn split_namespace(host: &str) -> crate::Result<Bytes> {
let (ns, _) = host.split_once('.').unwrap();
let (ns, _) = host.split_once('.').ok_or_else(|| {
Error::InvalidHost("host header should be in the format <namespace>.<...>".into())
})?;
let ns = Bytes::copy_from_slice(ns.as_bytes());
Ok(ns)
}

0 comments on commit 19b640f

Please sign in to comment.