Skip to content

Commit

Permalink
feat(core): set CORS headers on protocol errors (#8419)
Browse files Browse the repository at this point in the history
* feat(core): set CORS headers on protocol errors

This ensures the frontend can read the error message instead of just showing a CORS error

* fix statuscode
  • Loading branch information
lucasfernog committed Dec 18, 2023
1 parent ea03ade commit 11a1529
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changes/fix-protocol-response.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tauri": patch:enhance
---

Include CORS header on custom protocol response errors to ensure frontend can read the error message.
15 changes: 5 additions & 10 deletions core/tauri/src/protocol/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub fn get(scope: scope::fs::Scope, window_origin: String) -> UriSchemeProtocolH
http::Response::builder()
.status(http::StatusCode::BAD_REQUEST)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.header("Access-Control-Allow-Origin", &window_origin)
.body(e.to_string().as_bytes().to_vec())
.unwrap(),
),
Expand All @@ -36,24 +37,18 @@ fn get_response(
.decode_utf8_lossy()
.to_string();

let mut resp = Response::builder().header("Access-Control-Allow-Origin", window_origin);

if let Err(e) = SafePathBuf::new(path.clone().into()) {
debug_eprintln!("asset protocol path \"{}\" is not valid: {}", path, e);
return Response::builder()
.status(403)
.body(Vec::new().into())
.map_err(Into::into);
return resp.status(403).body(Vec::new().into()).map_err(Into::into);
}

if !scope.is_allowed(&path) {
debug_eprintln!("asset protocol not configured to allow the path: {}", path);
return Response::builder()
.status(403)
.body(Vec::new().into())
.map_err(Into::into);
return resp.status(403).body(Vec::new().into()).map_err(Into::into);
}

let mut resp = Response::builder().header("Access-Control-Allow-Origin", window_origin);

let (mut file, len, mime_type, read_bytes) = crate::async_runtime::safe_block_on(async move {
let mut file = File::open(&path).await?;

Expand Down
1 change: 1 addition & 0 deletions core/tauri/src/protocol/tauri.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub fn get<R: Runtime>(
HttpResponse::builder()
.status(StatusCode::BAD_REQUEST)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.header("Access-Control-Allow-Origin", &window_origin)
.body(e.to_string().as_bytes().to_vec())
.unwrap(),
),
Expand Down

0 comments on commit 11a1529

Please sign in to comment.