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

Serve gzipped version of console asset if it exists #1345

Merged
merged 5 commits into from
Jul 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
83 changes: 48 additions & 35 deletions nexus/src/external_api/console_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,17 @@ pub async fn console_settings_page(
console_index_or_login_redirect(rqctx).await
}

fn with_gz_ext(path: Vec<String>) -> Vec<String> {
if path.len() == 0 {
return path;
}

let mut new_path = path.clone();
let last = new_path.pop().unwrap(); // we know there's one there
new_path.push(format!("{last}.gz"));
new_path
}

This comment was marked as resolved.


/// Fetch a static asset from `<static_dir>/assets`. 404 on virtually all
/// errors. No auth. NO SENSITIVE FILES.
#[endpoint {
Expand All @@ -633,11 +644,32 @@ pub async fn asset(
let apictx = rqctx.context();
let path = path_params.into_inner().path;

let file = match &apictx.console_config.static_dir {
// important: we only serve assets from assets/ within static_dir
Some(static_dir) => find_file(path, &static_dir.join("assets")),
_ => Err(not_found("static_dir undefined")),
}?;
// bail unless the extension is allowed
let filename = path.last().ok_or(not_found("no path"))?;
let ext = PathBuf::from(filename)
.extension()
.map(|ext| ext.to_os_string())
.unwrap_or_else(|| OsString::from("disallowed"));
if !ALLOWED_EXTENSIONS.contains(&ext) {
return Err(not_found("file extension not allowed"));
}

// important: we only serve assets from assets/ within static_dir
let assets_dir = &apictx
.console_config
.static_dir
.as_ref()
.ok_or(not_found("static_dir undefined"))?
.join("assets");

let path_gz = with_gz_ext(path.clone());

// try to find the gzipped version, fall back to non-gz
let (file, gzipped) = match find_file(path_gz, &assets_dir) {
Ok(file) => (file, true),
_ => (find_file(path, &assets_dir)?, false),
};
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is either the best or worst 3 lines I've ever written

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

best


let file_contents = tokio::fs::read(&file)
.await
.map_err(|e| not_found(&format!("accessing {:?}: {:#}", file, e)))?;
Expand All @@ -647,11 +679,19 @@ pub async fn asset(
.first()
.map_or_else(|| "text/plain".to_string(), |m| m.to_string());

Ok(Response::builder()
let mut resp = Response::builder()
.status(StatusCode::OK)
.header(http::header::CONTENT_TYPE, &content_type)
.header(http::header::CACHE_CONTROL, cache_control_header_value(apictx))
.body(file_contents.into())?)
.header(
http::header::CACHE_CONTROL,
cache_control_header_value(apictx),
);

if gzipped {
resp = resp.header(http::header::CONTENT_ENCODING, "gzip");
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the way to conditionally add a header?


Ok(resp.body(file_contents.into())?)
}

fn cache_control_header_value(apictx: &Arc<ServerContext>) -> String {
Expand Down Expand Up @@ -694,14 +734,6 @@ lazy_static! {
);
}

fn file_ext_allowed(path: &PathBuf) -> bool {
let ext = path
.extension()
.map(|ext| ext.to_os_string())
.unwrap_or_else(|| OsString::from("disallowed"));
ALLOWED_EXTENSIONS.contains(&ext)
}

/// Starting from `root_dir`, follow the segments of `path` down the file tree
/// until we find a file (or not). Do not follow symlinks.
fn find_file(
Expand Down Expand Up @@ -734,10 +766,6 @@ fn find_file(
return Err(not_found("expected a non-directory"));
}

if !file_ext_allowed(&current) {
return Err(not_found("file extension not allowed"));
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved this check out of find_file because it seemed silly to have to pop off .gz to do it. I also tried adding things like js.gz to the list of allowed extensions, but extension() only gives us the .gz. We could make it work by looping through the list and using some kind ends_with thing.

Ok(current)
}

Expand Down Expand Up @@ -821,19 +849,4 @@ mod test {
assert_eq!(error.status_code, StatusCode::NOT_FOUND);
assert_eq!(error.internal_message, "attempted to follow a symlink");
}

#[test]
fn test_find_file_404_on_disallowed_ext() {
let root = current_dir().unwrap();
let error =
find_file(get_path("tests/static/assets/blocked.ext"), &root)
.unwrap_err();
assert_eq!(error.status_code, StatusCode::NOT_FOUND);
assert_eq!(error.internal_message, "file extension not allowed",);

let error = find_file(get_path("tests/static/assets/no_ext"), &root)
.unwrap_err();
assert_eq!(error.status_code, StatusCode::NOT_FOUND);
assert_eq!(error.internal_message, "file extension not allowed");
}
Copy link
Contributor Author

@david-crespo david-crespo Jul 1, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This behavior has been moved out of find_file and there's already an integration test for it at the endpoint level.

}
1 change: 1 addition & 0 deletions nexus/test-utils/src/http_testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ impl<'a> RequestBuilder<'a> {
expected_status: None,
allowed_headers: Some(vec![
http::header::CACHE_CONTROL,
http::header::CONTENT_ENCODING,
http::header::CONTENT_LENGTH,
http::header::CONTENT_TYPE,
http::header::DATE,
Expand Down
12 changes: 12 additions & 0 deletions nexus/tests/integration_tests/console_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,23 @@ async fn test_assets(cptestctx: &ControlPlaneTestContext) {

// existing file is returned
let resp = RequestBuilder::new(&testctx, Method::GET, "/assets/hello.txt")
.expect_status(Some(StatusCode::OK))
.execute()
.await
.expect("failed to get existing file");

assert_eq!(resp.body, "hello there".as_bytes());

// file with existing gzipped version is returned
let resp =
RequestBuilder::new(&testctx, Method::GET, "/assets/gzipped.txt")
.expect_status(Some(StatusCode::OK))
.expect_response_header(http::header::CONTENT_ENCODING, "gzip")
.execute()
.await
.expect("failed to get existing file");

assert_eq!(resp.body, "pretend this is gzipped beep boop".as_bytes());
}

#[tokio::test]
Expand Down
1 change: 1 addition & 0 deletions nexus/tests/static/assets/gzipped.txt.gz
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pretend this is gzipped beep boop