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

feat(http): expose proxy configuration #824

Merged
merged 8 commits into from
Dec 20, 2023
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
6 changes: 6 additions & 0 deletions .changes/http-proxy-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"http": minor
"http-js": minor
---

Add `proxy` field to `fetch` options to configure proxy.
60 changes: 54 additions & 6 deletions plugins/http/guest-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,45 @@

import { invoke } from "@tauri-apps/api/core";

/**
* Configuration of a proxy that a Client should pass requests to.
*
* @since 2.0.0
*/
export type Proxy = {
/**
* Proxy all traffic to the passed URL.
*/
all?: string | ProxyConfig;
/**
* Proxy all HTTP traffic to the passed URL.
*/
http?: string | ProxyConfig;
/**
* Proxy all HTTPS traffic to the passed URL.
*/
https?: string | ProxyConfig;
};

export interface ProxyConfig {
/**
* The URL of the proxy server.
*/
url: string;
/**
* Set the `Proxy-Authorization` header using Basic auth.
*/
basicAuth?: {
username: string;
password: string;
};
/**
* A configuration for filtering out requests that shouldn’t be proxied.
* Entries are expected to be comma-separated (whitespace between entries is ignored)
*/
noProxy?: string;
}

/**
* Options to configure the Rust client used to make fetch requests
*
Expand All @@ -39,6 +78,10 @@ export interface ClientOptions {
maxRedirections?: number;
/** Timeout in milliseconds */
connectTimeout?: number;
/**
* Configuration of a proxy that a Client should pass requests to.
*/
proxy?: Proxy;
}

/**
Expand All @@ -61,24 +104,29 @@ export async function fetch(
): Promise<Response> {
const maxRedirections = init?.maxRedirections;
const connectTimeout = init?.maxRedirections;
const proxy = init?.proxy;

// Remove these fields before creating the request
if (init) {
delete init.maxRedirections;
delete init.connectTimeout;
delete init.proxy;
}

const req = new Request(input, init);
const buffer = await req.arrayBuffer();
const reqData = buffer.byteLength ? Array.from(new Uint8Array(buffer)) : null;

const rid = await invoke<number>("plugin:http|fetch", {
method: req.method,
url: req.url,
headers: Array.from(req.headers.entries()),
data: reqData,
maxRedirections,
connectTimeout,
clientConfig: {
method: req.method,
url: req.url,
headers: Array.from(req.headers.entries()),
data: reqData,
maxRedirections,
connectTimeout,
proxy,
},
});

req.signal.addEventListener("abort", () => {
Expand Down
2 changes: 1 addition & 1 deletion plugins/http/src/api-iife.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

109 changes: 104 additions & 5 deletions plugins/http/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
use std::{collections::HashMap, time::Duration};

use http::{header, HeaderName, HeaderValue, Method, StatusCode};
use reqwest::redirect::Policy;
use serde::Serialize;
use reqwest::{redirect::Policy, NoProxy};
use serde::{Deserialize, Serialize};
use tauri::{command, AppHandle, Runtime};

use crate::{Error, FetchRequest, HttpExt, RequestId};
Expand All @@ -20,16 +20,111 @@ pub struct FetchResponse {
url: String,
}

#[command]
pub async fn fetch<R: Runtime>(
app: AppHandle<R>,
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientConfig {
method: String,
url: url::Url,
headers: Vec<(String, String)>,
data: Option<Vec<u8>>,
connect_timeout: Option<u64>,
max_redirections: Option<usize>,
proxy: Option<Proxy>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Proxy {
all: Option<UrlOrConfig>,
http: Option<UrlOrConfig>,
https: Option<UrlOrConfig>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum UrlOrConfig {
Url(String),
Config(ProxyConfig),
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProxyConfig {
url: String,
basic_auth: Option<BasicAuth>,
no_proxy: Option<String>,
}

#[derive(Deserialize)]
pub struct BasicAuth {
username: String,
password: String,
}

#[inline]
fn proxy_creator(
url_or_config: UrlOrConfig,
proxy_fn: fn(String) -> reqwest::Result<reqwest::Proxy>,
) -> reqwest::Result<reqwest::Proxy> {
match url_or_config {
UrlOrConfig::Url(url) => Ok(proxy_fn(url)?),
UrlOrConfig::Config(ProxyConfig {
url,
basic_auth,
no_proxy,
}) => {
let mut proxy = proxy_fn(url)?;
if let Some(basic_auth) = basic_auth {
proxy = proxy.basic_auth(&basic_auth.username, &basic_auth.password);
}
if let Some(no_proxy) = no_proxy {
proxy = proxy.no_proxy(NoProxy::from_string(&no_proxy));
}
Ok(proxy)
}
}
}

fn attach_proxy(
proxy: Proxy,
mut builder: reqwest::ClientBuilder,
) -> crate::Result<reqwest::ClientBuilder> {
let Proxy { all, http, https } = proxy;

if let Some(all) = all {
let proxy = proxy_creator(all, reqwest::Proxy::all)?;
builder = builder.proxy(proxy);
}

if let Some(http) = http {
let proxy = proxy_creator(http, reqwest::Proxy::http)?;
builder = builder.proxy(proxy);
}

if let Some(https) = https {
let proxy = proxy_creator(https, reqwest::Proxy::https)?;
builder = builder.proxy(proxy);
}

Ok(builder)
}

#[command]
pub async fn fetch<R: Runtime>(
app: AppHandle<R>,
client_config: ClientConfig,
) -> crate::Result<RequestId> {
let ClientConfig {
method,
url,
headers,
data,
connect_timeout,
max_redirections,
proxy,
} = client_config;

let scheme = url.scheme();
let method = Method::from_bytes(method.as_bytes())?;
let headers: HashMap<String, String> = HashMap::from_iter(headers);
Expand All @@ -51,6 +146,10 @@ pub async fn fetch<R: Runtime>(
});
}

if let Some(proxy_config) = proxy {
builder = attach_proxy(proxy_config, builder)?;
}

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

for (key, value) in &headers {
Expand Down
Loading