Skip to content
Open
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
6 changes: 6 additions & 0 deletions .changes/http-transport-extensions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"http": minor
"http-js": minor
---

Add native transport extension hooks for request validation, final `reqwest::ClientBuilder` configuration, setup, and structured transport error mapping.
39 changes: 39 additions & 0 deletions plugins/http/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,45 @@ const response = await fetch('http://localhost:3003/users/2', {
})
```

## Native transport extensions

Trusted native code can extend the request transport while preserving the
existing JavaScript API. Extensions can validate request metadata, configure
the final `reqwest::ClientBuilder`, and map transport failures to structured
errors:

```rust
use tauri_plugin_http::{
ExtensionError, HttpTransportExtension, RequestContext,
};

struct CustomTransport;

impl<R: tauri::Runtime> HttpTransportExtension<R> for CustomTransport {
fn configure(
&self,
builder: reqwest::ClientBuilder,
_request: &RequestContext,
) -> Result<reqwest::ClientBuilder, ExtensionError> {
Ok(builder.https_only(true))
}
}

fn main() {
tauri::Builder::default()
.plugin(
tauri_plugin_http::Builder::new()
.extension(CustomTransport)
.build(),
)
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```

Extensions run in registration order and are trusted to replace transport
settings. Request bodies are not exposed through `RequestContext`.

## Contributing

PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
Expand Down
49 changes: 45 additions & 4 deletions plugins/http/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use tokio::sync::oneshot::{channel, Receiver, Sender};

use crate::{
scope::{Entry, Scope},
Error, Http, Result,
Error, Http, RequestContext, Result,
};

const HTTP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
Expand Down Expand Up @@ -177,7 +177,7 @@ fn attach_proxy(
#[command]
pub async fn fetch<R: Runtime>(
webview: Webview<R>,
state: State<'_, Http>,
state: State<'_, Http<R>>,
client_config: ClientConfig,
command_scope: CommandScope<Entry>,
global_scope: GlobalScope<Entry>,
Expand Down Expand Up @@ -228,6 +228,33 @@ pub async fn fetch<R: Runtime>(
)
.is_allowed(&url)
{
let extensions = state.extensions.clone();
let connect_timeout = connect_timeout.map(Duration::from_millis);
let (danger_accept_invalid_certs, danger_accept_invalid_hostnames) = danger
.as_ref()
.map(|settings| {
(
settings.accept_invalid_certs,
settings.accept_invalid_hostnames,
)
})
.unwrap_or_default();
let request_context = RequestContext::new(
method.clone(),
url.clone(),
headers.clone(),
data.is_some(),
connect_timeout,
max_redirections,
proxy.is_some(),
danger_accept_invalid_certs,
danger_accept_invalid_hostnames,
);

for extension in extensions.iter() {
extension.validate(&request_context)?;
}

let mut builder = reqwest::ClientBuilder::new();

if let Some(danger_config) = danger {
Expand All @@ -249,7 +276,7 @@ pub async fn fetch<R: Runtime>(
}

if let Some(timeout) = connect_timeout {
builder = builder.connect_timeout(Duration::from_millis(timeout));
builder = builder.connect_timeout(timeout);
}

if let Some(max_redirections) = max_redirections {
Expand All @@ -269,6 +296,10 @@ pub async fn fetch<R: Runtime>(
builder = builder.cookie_provider(state.cookies_jar.clone());
}

for extension in extensions.iter() {
builder = extension.configure(builder, &request_context)?;
}

let mut request = builder.build()?.request(method.clone(), url);

// POST and PUT requests should always have a 0 length content-length,
Expand Down Expand Up @@ -317,7 +348,17 @@ pub async fn fetch<R: Runtime>(
#[cfg(feature = "tracing")]
tracing::trace!("{:?}", request);

let fut = async move { request.send().await.map_err(Into::into) };
let fut = async move {
request.send().await.map_err(|error| {
extensions
.iter()
.find_map(|extension| {
extension.map_transport_error(&error, &request_context)
})
.map(Error::from)
.unwrap_or_else(|| Error::from(error))
})
};

let mut resources_table = webview.resources_table();
let rid = resources_table.add_request(Box::pin(fut));
Expand Down
37 changes: 36 additions & 1 deletion plugins/http/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub enum Error {
#[error(transparent)]
Network(#[from] reqwest::Error),
#[error(transparent)]
Extension(#[from] crate::ExtensionError),
#[error(transparent)]
Http(#[from] http::Error),
#[error(transparent)]
HttpInvalidHeaderName(#[from] http::header::InvalidHeaderName),
Expand Down Expand Up @@ -50,8 +52,41 @@ impl Serialize for Error {
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
match self {
Self::Extension(error) => error.value().serialize(serializer),
_ => serializer.serialize_str(self.to_string().as_ref()),
}
}
}

pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn extension_errors_keep_their_json_shape() {
let error = Error::Extension(crate::ExtensionError::from_value(serde_json::json!({
"code": "POLICY_REJECTED",
"host": "example.test"
})));

assert_eq!(
serde_json::to_value(error).unwrap(),
serde_json::json!({
"code": "POLICY_REJECTED",
"host": "example.test"
})
);
}

#[test]
fn existing_errors_remain_strings() {
let error = Error::RequestCanceled;
assert_eq!(
serde_json::to_value(error).unwrap(),
serde_json::Value::String("Request canceled".into())
);
}
}
Loading