Commit 1934ca1f41

1934ca1f418d4b1038e61466ab94284e9c9505ff

parent: f2f65f98be

Unregistered key

Ulyssa <git@ulyssa.dev> · 2026-08-15 22:33 UTC
committer: <noreply@github.com>

Add support for SOCKS and HTTPS proxying (#640)

Co-authored-by: vaw <git@nlih.de>
Co-authored-by: Kara Zajac <kara@soulstone.org>

Layout: unified · split

Cargo.lock +11
@@ -2269,6 +2269,16 @@ dependencies = [
2269 "pin-project-lite", 2269 "pin-project-lite",
2270] 2270]
2271 2271
2272[[package]]
2273name = "http-serde"
2274version = "2.1.1"
2275source = "registry+https://github.com/rust-lang/crates.io-index"
2276checksum = "0f056c8559e3757392c8d091e796416e4649d8e49e88b8d76df6c002f05027fd"
2277dependencies = [
2278 "http",
2279 "serde",
2280]
2281
2272[[package]] 2282[[package]]
2273name = "httparse" 2283name = "httparse"
2274version = "1.10.1" 2284version = "1.10.1"
@@ -2368,6 +2378,7 @@ dependencies = [
2368 "futures", 2378 "futures",
2369 "gethostname", 2379 "gethostname",
2370 "html5ever", 2380 "html5ever",
2381 "http-serde",
2371 "humansize", 2382 "humansize",
2372 "image", 2383 "image",
2373 "lazy_static 1.5.0", 2384 "lazy_static 1.5.0",
Cargo.toml +2 −1
@@ -38,6 +38,7 @@ feruca = "0.11"
38futures = "0.3" 38futures = "0.3"
39gethostname = "1.1" 39gethostname = "1.1"
40html5ever = "0.39.0" 40html5ever = "0.39.0"
41http-serde = "2.1.1"
41humansize = "2.0.0" 42humansize = "2.0.0"
42image = "0.25.6" 43image = "0.25.6"
43libc = "0.2" 44libc = "0.2"
@@ -89,7 +90,7 @@ version = "0.0.25"
89[dependencies.matrix-sdk] 90[dependencies.matrix-sdk]
90version = "0.18.0" 91version = "0.18.0"
91default-features = false 92default-features = false
92features = ["e2e-encryption", "sqlite", "sso-login"] 93features = ["e2e-encryption", "socks", "sqlite", "sso-login"]
93 94
94[dependencies.matrix-sdk-crypto] 95[dependencies.matrix-sdk-crypto]
95version = "0.18.0" 96version = "0.18.0"
config.example.toml +5
@@ -30,6 +30,11 @@ indicator_location = "title|prompt"
30protocol.type = "sixel" 30protocol.type = "sixel"
31size = { "width" = 66, "height" = 10 } 31size = { "width" = 66, "height" = 10 }
32 32
33[settings.proxy]
34url = "" # An empty string disables any proxying
35auth = "Bearer abcd1234"
36headers.X-Proxy-Config = "foobar"
37
33[settings.sort] 38[settings.sort]
34rooms = ["favorite", "lowpriority", "unread", "name"] 39rooms = ["favorite", "lowpriority", "unread", "name"]
35members = ["power", "id"] 40members = ["power", "id"]
docs/iamb.1 +6 −1
@@ -309,12 +309,17 @@ The behaviour of
309.Nm 309.Nm
310is affected by the following environment variables. 310is affected by the following environment variables.
311.Bl -tag -width Ds 311.Bl -tag -width Ds
312.It Sy "ALL_PROXY, HTTP_PROXY, HTTPS_PROXY"
313Sets the proxy server to use.
314These names also work in lowercase.
315Example:
316.Dq export ALL_PROXY=socks5://localhost:9050 .
312.It Sy "RUST_LOG" 317.It Sy "RUST_LOG"
313Overwrites the value set by the 318Overwrites the value set by the
314.Sy log_level 319.Sy log_level
315config value. 320config value.
316The syntax is defined at 321The syntax is defined at
317.Lk https://docs.rs/tracing-subscriber/0.3.16/tracing_subscriber/filter/struct.EnvFilter.html 322.Lk https://docs.rs/tracing_subscriber/0.3.16/tracing_subscriber/filter/struct.EnvFilter.html
318 323
319.Sh EXAMPLES 324.Sh EXAMPLES
320.Ss Example 1: Starting with a specific profile 325.Ss Example 1: Starting with a specific profile
docs/iamb.5 +33
@@ -218,6 +218,11 @@ for more details.
218Defines a custom command and its arguments to run when opening downloads instead of the default. 218Defines a custom command and its arguments to run when opening downloads instead of the default.
219(For example, 219(For example,
220.Sy ["my-open",\ "--file"] . ) 220.Sy ["my-open",\ "--file"] . )
221.Sy proxy
222When this subsection is present, you can configure how requests are proxied to the homeserver.
223See
224.Sx PROXYING
225for more details.
221.It Sy reaction_display 226.It Sy reaction_display
222Defines whether or not reactions should be shown. 227Defines whether or not reactions should be shown.
223.It Sy reaction_shortcode_display 228.It Sy reaction_shortcode_display
@@ -376,6 +381,34 @@ enabled = true
376sound_hint = "message-new-instant" # Linux 381sound_hint = "message-new-instant" # Linux
377sound_hint = "IM" # Windows 382sound_hint = "IM" # Windows
378.Ed 383.Ed
384.Sh "PROXYING"
385The
386.Sy settings.proxy
387subsection allows configuring proxying for requests to the homeserver.
388.Pp
389Fields available within this subsection are:
390.Bl -tag -width Ds
391.It Sy url
392Either a
393.Sy socks5://IP:PORT
394URL for a SOCKS server to proxy request through,
395or a
396.Sy http[s]://[USER:PASS@]HOST[:PORT]/
397URL to do HTTP(S) proxying through.
398Setting this to the empty string will explicitly disable proxying, and any environment variables will be ignored.
399.It Sy auth
400A value to send in a
401.Sy Proxy-Authorization
402header if your HTTP(S) proxy requires it,
403such as for doing Bearer authentication with a token.
404.It Sy headers
405A subsection for specifying additional headers and values to include in requests sent to the proxy.
406For example, custom HTTPS proxy server software may require specifying a
407.Sy User-Agent
408or a custom header like
409.Sy X-Proxy-Token
410in order to be allowed to send request through it.
411.El
379.Sh "SORTING LISTS" 412.Sh "SORTING LISTS"
380The 413The
381.Sy settings.sort 414.Sy settings.sort
src/config.rs +192 −50
@@ -9,9 +9,11 @@ use std::hash::{Hash, Hasher};
9use std::io::{BufReader, BufWriter, Write}; 9use std::io::{BufReader, BufWriter, Write};
10use std::path::{Path, PathBuf}; 10use std::path::{Path, PathBuf};
11use std::process; 11use std::process;
12use std::str::FromStr;
12 13
13use clap::Parser; 14use clap::Parser;
14use matrix_sdk::authentication::matrix::MatrixSession; 15use matrix_sdk::authentication::matrix::MatrixSession;
16use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
15use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId}; 17use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
16use matrix_sdk::EncryptionState; 18use matrix_sdk::EncryptionState;
17use ratatui::style::{Color, Modifier as StyleModifier, Style}; 19use ratatui::style::{Color, Modifier as StyleModifier, Style};
@@ -123,6 +125,20 @@ fn validate_profile_names(names: &BTreeMap<String, ProfileConfig>) {
123 } 125 }
124} 126}
125 127
128fn deserialize_from_str_opt<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
129where
130 D: serde::de::Deserializer<'de>,
131 T: FromStr,
132 <T as FromStr>::Err: fmt::Display,
133{
134 <Option<&'de str>>::deserialize(deserializer)?
135 .map(|s| {
136 let t = T::from_str(s);
137 t.map_err(|e| D::Error::custom(format!("failed to parse string: {e}")))
138 })
139 .transpose()
140}
141
126const VERSION: &str = match option_env!("VERGEN_GIT_SHA") { 142const VERSION: &str = match option_env!("VERGEN_GIT_SHA") {
127 None => env!("CARGO_PKG_VERSION"), 143 None => env!("CARGO_PKG_VERSION"),
128 Some(_) => concat!(env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), ")"), 144 Some(_) => concat!(env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), ")"),
@@ -154,6 +170,26 @@ pub enum ConfigError {
154 InvalidJSON(#[from] serde_json::Error), 170 InvalidJSON(#[from] serde_json::Error),
155} 171}
156 172
173macro_rules! deserialize_str_with_visitor {
174 ($t: ident, $v: ident) => {
175 impl<'de> Deserialize<'de> for $t {
176 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
177 where
178 D: Deserializer<'de>,
179 {
180 deserializer.deserialize_str($v)
181 }
182 }
183 };
184}
185
186deserialize_str_with_visitor!(Keys, KeysVisitor);
187deserialize_str_with_visitor!(VimModes, VimModesVisitor);
188deserialize_str_with_visitor!(UserColor, UserColorVisitor);
189deserialize_str_with_visitor!(EncryptionIndicatorLocation, EncryptionIndicatorLocationVisitor);
190deserialize_str_with_visitor!(NotifyVia, NotifyViaVisitor);
191deserialize_str_with_visitor!(ProxyUrl, ProxyUrlVisitor);
192
157#[derive(Clone, Debug, Eq, Hash, PartialEq)] 193#[derive(Clone, Debug, Eq, Hash, PartialEq)]
158pub struct Keys(pub Vec<TerminalKey>, pub String); 194pub struct Keys(pub Vec<TerminalKey>, pub String);
159pub struct KeysVisitor; 195pub struct KeysVisitor;
@@ -176,15 +212,6 @@ impl Visitor<'_> for KeysVisitor {
176 } 212 }
177} 213}
178 214
179impl<'de> Deserialize<'de> for Keys {
180 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
181 where
182 D: Deserializer<'de>,
183 {
184 deserializer.deserialize_str(KeysVisitor)
185 }
186}
187
188#[derive(Clone, Debug, Eq, Hash, PartialEq)] 215#[derive(Clone, Debug, Eq, Hash, PartialEq)]
189pub struct VimModes(pub Vec<VimMode>); 216pub struct VimModes(pub Vec<VimMode>);
190pub struct VimModesVisitor; 217pub struct VimModesVisitor;
@@ -220,15 +247,6 @@ impl Visitor<'_> for VimModesVisitor {
220 } 247 }
221} 248}
222 249
223impl<'de> Deserialize<'de> for VimModes {
224 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
225 where
226 D: Deserializer<'de>,
227 {
228 deserializer.deserialize_str(VimModesVisitor)
229 }
230}
231
232#[derive(Clone, Debug, Eq, PartialEq)] 250#[derive(Clone, Debug, Eq, PartialEq)]
233pub struct UserColor(pub Color); 251pub struct UserColor(pub Color);
234pub struct UserColorVisitor; 252pub struct UserColorVisitor;
@@ -267,15 +285,6 @@ impl Visitor<'_> for UserColorVisitor {
267 } 285 }
268} 286}
269 287
270impl<'de> Deserialize<'de> for UserColor {
271 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
272 where
273 D: Deserializer<'de>,
274 {
275 deserializer.deserialize_str(UserColorVisitor)
276 }
277}
278
279#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] 288#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
280pub struct Session { 289pub struct Session {
281 access_token: String, 290 access_token: String,
@@ -392,15 +401,6 @@ impl Visitor<'_> for EncryptionIndicatorLocationVisitor {
392 } 401 }
393} 402}
394 403
395impl<'de> Deserialize<'de> for EncryptionIndicatorLocation {
396 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
397 where
398 D: Deserializer<'de>,
399 {
400 deserializer.deserialize_str(EncryptionIndicatorLocationVisitor)
401 }
402}
403
404#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)] 404#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
405#[serde(rename_all = "lowercase")] 405#[serde(rename_all = "lowercase")]
406pub enum UserDisplayStyle { 406pub enum UserDisplayStyle {
@@ -485,15 +485,6 @@ impl Visitor<'_> for NotifyViaVisitor {
485 } 485 }
486} 486}
487 487
488impl<'de> Deserialize<'de> for NotifyVia {
489 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
490 where
491 D: Deserializer<'de>,
492 {
493 deserializer.deserialize_str(NotifyViaVisitor)
494 }
495}
496
497#[derive(Clone, Debug, Default, Deserialize)] 488#[derive(Clone, Debug, Default, Deserialize)]
498pub struct Encryption { 489pub struct Encryption {
499 indicator: Option<EncryptionIndicator>, 490 indicator: Option<EncryptionIndicator>,
@@ -564,6 +555,69 @@ impl EncryptionValues {
564 } 555 }
565} 556}
566 557
558#[derive(Clone, Debug, Default, Eq, PartialEq)]
559pub enum ProxyUrl {
560 Disabled,
561 Endpoint(Url),
562 #[default]
563 System,
564}
565
566pub struct ProxyUrlVisitor;
567
568impl Visitor<'_> for ProxyUrlVisitor {
569 type Value = ProxyUrl;
570
571 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
572 formatter.write_str("a valid proxy URL (e.g. \"socks5://localhost:9050\")")
573 }
574
575 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
576 where
577 E: SerdeError,
578 {
579 if value.is_empty() {
580 return Ok(ProxyUrl::Disabled);
581 }
582
583 match Url::from_str(value) {
584 Ok(uri) => Ok(ProxyUrl::Endpoint(uri)),
585 Err(e) => Err(E::custom(format!("could not parse {value:?}: {e}"))),
586 }
587 }
588}
589
590#[derive(Clone, Debug, Default, Deserialize)]
591pub struct Proxy {
592 /// How and where to proxy the client's requests to the homeserver.
593 url: Option<ProxyUrl>,
594
595 /// An optional value to include in the `Proxy-Authorization` header.
596 #[serde(default, deserialize_with = "deserialize_from_str_opt")]
597 auth: Option<HeaderValue>,
598
599 /// Optional headers to include in requests sent to the proxy.
600 #[serde(default, with = "http_serde::header_map")]
601 headers: HeaderMap,
602}
603
604impl Proxy {
605 pub fn values(self) -> ProxyValues {
606 ProxyValues {
607 url: self.url.unwrap_or_default(),
608 auth: self.auth,
609 headers: self.headers,
610 }
611 }
612}
613
614#[derive(Clone, Debug, Default)]
615pub struct ProxyValues {
616 pub url: ProxyUrl,
617 pub auth: Option<HeaderValue>,
618 pub headers: HeaderMap,
619}
620
567#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)] 621#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
568pub struct Mouse { 622pub struct Mouse {
569 #[serde(default)] 623 #[serde(default)]
@@ -589,7 +643,7 @@ pub struct ImagePreviewValues {
589 pub protocol: Option<ImagePreviewProtocolValues>, 643 pub protocol: Option<ImagePreviewProtocolValues>,
590} 644}
591 645
592#[derive(Clone, Default, Deserialize)] 646#[derive(Clone, Debug, Default, Deserialize)]
593pub struct ImagePreview { 647pub struct ImagePreview {
594 pub lazy_load: Option<bool>, 648 pub lazy_load: Option<bool>,
595 pub size: Option<ImagePreviewSize>, 649 pub size: Option<ImagePreviewSize>,
@@ -618,7 +672,7 @@ impl Default for ImagePreviewSize {
618 } 672 }
619} 673}
620 674
621#[derive(Clone, Deserialize)] 675#[derive(Clone, Debug, Deserialize)]
622pub struct ImagePreviewProtocolValues { 676pub struct ImagePreviewProtocolValues {
623 pub r#type: Option<ProtocolType>, 677 pub r#type: Option<ProtocolType>,
624 pub font_size: Option<(u16, u16)>, 678 pub font_size: Option<(u16, u16)>,
@@ -633,7 +687,7 @@ pub struct SortValues {
633 pub members: Vec<SortColumn<SortFieldUser>>, 687 pub members: Vec<SortColumn<SortFieldUser>>,
634} 688}
635 689
636#[derive(Clone, Default, Deserialize)] 690#[derive(Clone, Debug, Default, Deserialize)]
637pub struct SortOverrides { 691pub struct SortOverrides {
638 pub chats: Option<Vec<SortColumn<SortFieldRoom>>>, 692 pub chats: Option<Vec<SortColumn<SortFieldRoom>>>,
639 pub dms: Option<Vec<SortColumn<SortFieldRoom>>>, 693 pub dms: Option<Vec<SortColumn<SortFieldRoom>>>,
@@ -696,6 +750,8 @@ pub struct TerminalValues {
696 pub enable_title: bool, 750 pub enable_title: bool,
697} 751}
698 752
753/// The configuration settings to run with, after merging the
754/// per-profile overrides on top of the global settings.
699#[derive(Clone)] 755#[derive(Clone)]
700pub struct TunableValues { 756pub struct TunableValues {
701 pub encryption: EncryptionValues, 757 pub encryption: EncryptionValues,
@@ -703,6 +759,7 @@ pub struct TunableValues {
703 pub max_log_files: usize, 759 pub max_log_files: usize,
704 pub message_shortcode_display: bool, 760 pub message_shortcode_display: bool,
705 pub normal_after_send: bool, 761 pub normal_after_send: bool,
762 pub proxy: ProxyValues,
706 pub reaction_display: bool, 763 pub reaction_display: bool,
707 pub reaction_shortcode_display: bool, 764 pub reaction_shortcode_display: bool,
708 pub read_receipt_send: bool, 765 pub read_receipt_send: bool,
@@ -728,12 +785,15 @@ pub struct TunableValues {
728 pub ssl_verify: bool, 785 pub ssl_verify: bool,
729} 786}
730 787
731#[derive(Clone, Default, Deserialize)] 788#[derive(Clone, Debug, Default, Deserialize)]
732pub struct Tunables { 789pub struct Tunables {
733 /// Subsection for overriding encryption-related settings. 790 /// Subsection for overriding encryption-related settings.
734 #[serde(default)] 791 #[serde(default)]
735 pub encryption: Encryption, 792 pub encryption: Encryption,
736 793
794 /// Subsection for configuring an HTTP(S) proxy.
795 pub proxy: Option<Proxy>,
796
737 /// Subsection for overriding sort orders in UI lists. 797 /// Subsection for overriding sort orders in UI lists.
738 #[serde(default)] 798 #[serde(default)]
739 pub sort: SortOverrides, 799 pub sort: SortOverrides,
@@ -779,6 +839,11 @@ impl Tunables {
779 terminal: Terminal::merge(self.terminal, other.terminal), 839 terminal: Terminal::merge(self.terminal, other.terminal),
780 users: merge_maps(self.users, other.users), 840 users: merge_maps(self.users, other.users),
781 841
842 // Proxy configuration sub-field do *not* get merged, so that a
843 // per-profile override won't inherit auth or headers from the
844 // global settings.
845 proxy: self.proxy.or(other.proxy),
846
782 log_level: self.log_level.or(other.log_level), 847 log_level: self.log_level.or(other.log_level),
783 max_log_files: self.max_log_files.or(other.max_log_files), 848 max_log_files: self.max_log_files.or(other.max_log_files),
784 message_shortcode_display: self 849 message_shortcode_display: self
@@ -815,8 +880,10 @@ impl Tunables {
815 fn values(self) -> TunableValues { 880 fn values(self) -> TunableValues {
816 TunableValues { 881 TunableValues {
817 encryption: self.encryption.values(), 882 encryption: self.encryption.values(),
883 proxy: self.proxy.unwrap_or_default().values(),
818 sort: self.sort.values(), 884 sort: self.sort.values(),
819 terminal: self.terminal.values(), 885 terminal: self.terminal.values(),
886 users: self.users.unwrap_or_default(),
820 887
821 log_level: self.log_level.unwrap_or_else(|| "warn".to_string()), 888 log_level: self.log_level.unwrap_or_else(|| "warn".to_string()),
822 max_log_files: self.max_log_files.unwrap_or(7), 889 max_log_files: self.max_log_files.unwrap_or(7),
@@ -830,7 +897,6 @@ impl Tunables {
830 state_event_display: self.state_event_display.unwrap_or(true), 897 state_event_display: self.state_event_display.unwrap_or(true),
831 typing_notice_send: self.typing_notice_send.unwrap_or(true), 898 typing_notice_send: self.typing_notice_send.unwrap_or(true),
832 typing_notice_display: self.typing_notice_display.unwrap_or(true), 899 typing_notice_display: self.typing_notice_display.unwrap_or(true),
833 users: self.users.unwrap_or_default(),
834 username_display: self.username_display.unwrap_or_default(), 900 username_display: self.username_display.unwrap_or_default(),
835 message_user_color: self.message_user_color.unwrap_or(false), 901 message_user_color: self.message_user_color.unwrap_or(false),
836 default_room: self.default_room, 902 default_room: self.default_room,
@@ -1424,6 +1490,82 @@ mod tests {
1424 assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT)); 1490 assert_eq!(res.sort.dms, Vec::from(DEFAULT_ROOM_SORT));
1425 } 1491 }
1426 1492
1493 #[test]
1494 fn test_parse_tunables_proxy_invalid() {
1495 let res =
1496 serde_json::from_str::<Tunables>(r#"{"proxy": {"url": "localhost"}}"#).unwrap_err();
1497
1498 // Should result in a validation error:
1499 assert_eq!(res.classify(), serde_json::error::Category::Data);
1500 }
1501
1502 #[test]
1503 fn test_parse_tunables_proxy_empty() {
1504 let res: Tunables = serde_json::from_str(r#"{"proxy": {"url": ""}}"#).unwrap();
1505 let proxy = res.proxy.unwrap();
1506 assert_eq!(proxy.url.unwrap(), ProxyUrl::Disabled);
1507 }
1508
1509 #[test]
1510 fn test_parse_tunables_proxy_socks5() {
1511 let res: Tunables =
1512 serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1513 let proxy = res.proxy.unwrap();
1514 let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1515 panic!("should parse ProxyUrl::Endpoint")
1516 };
1517
1518 assert_eq!(url.scheme(), "socks5");
1519 assert_eq!(url.host_str().unwrap(), "localhost");
1520 assert_eq!(url.port().unwrap(), 1080);
1521 assert_eq!(url.authority(), "localhost:1080");
1522 }
1523
1524 #[test]
1525 fn test_parse_tunables_proxy_https() {
1526 let res: Tunables = serde_json::from_str(
1527 r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1528 ).unwrap();
1529 let proxy = res.proxy.unwrap();
1530 let ProxyUrl::Endpoint(url) = proxy.url.unwrap() else {
1531 panic!("should parse ProxyUrl::Endpoint")
1532 };
1533
1534 // Verify URL fields:
1535 assert_eq!(url.scheme(), "https");
1536 assert_eq!(url.host_str().unwrap(), "localhost");
1537 assert_eq!(url.port().unwrap(), 8080);
1538 assert_eq!(url.authority(), "localhost:8080");
1539
1540 // Verify our `Proxy-Authorization` value:
1541 assert_eq!(proxy.auth.unwrap(), "Bearer abcd1234");
1542
1543 // Verify our custom header is present:
1544 assert_eq!(proxy.headers.len(), 1);
1545 assert_eq!(proxy.headers.get("user-agent").unwrap(), "iamb");
1546 }
1547
1548 #[test]
1549 fn test_parse_tunables_proxy_merge() {
1550 let global: Tunables = serde_json::from_str(
1551 r#"{"proxy": {"url": "https://localhost:8080","auth": "Bearer abcd1234","headers":{"User-Agent": "iamb"}}}"#
1552 ).unwrap();
1553 let profile: Tunables =
1554 serde_json::from_str(r#"{"proxy": {"url": "socks5://localhost:1080"}}"#).unwrap();
1555
1556 // The configuration merge should select the entirety of the profile proxy config,
1557 // and not merge subfields, to ensure that things like `auth` and `headers` are
1558 // not ever sent to a `url` they were meant for.
1559 let merged = profile.merge(global).values();
1560 let ProxyUrl::Endpoint(url) = merged.proxy.url else {
1561 panic!("should parse ProxyUrl::Endpoint")
1562 };
1563 assert_eq!(url.scheme(), "socks5");
1564 assert_eq!(url.authority(), "localhost:1080");
1565 assert_eq!(merged.proxy.auth, None);
1566 assert_eq!(merged.proxy.headers.is_empty(), true);
1567 }
1568
1427 #[test] 1569 #[test]
1428 fn test_parse_layout() { 1570 fn test_parse_layout() {
1429 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned()); 1571 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
src/tests.rs +2 −16
@@ -23,22 +23,7 @@ use tokio::sync::mpsc::unbounded_channel;
23use crate::message::MessageTimeStamp; 23use crate::message::MessageTimeStamp;
24use crate::{ 24use crate::{
25 base::{ChatStore, EventLocation, ProgramStore, RoomInfo}, 25 base::{ChatStore, EventLocation, ProgramStore, RoomInfo},
26 config::{ 26 config::*,
27 user_color,
28 user_style_from_color,
29 ApplicationSettings,
30 DirectoryValues,
31 Encryption,
32 Notifications,
33 NotifyVia,
34 ProfileConfig,
35 SortOverrides,
36 Terminal,
37 TunableValues,
38 UserColor,
39 UserDisplayStyle,
40 UserDisplayTunables,
41 },
42 message::{Message, MessageEvent, MessageKey, Messages}, 27 message::{Message, MessageEvent, MessageKey, Messages},
43 worker::Requester, 28 worker::Requester,
44}; 29};
@@ -187,6 +172,7 @@ pub fn mock_tunables() -> TunableValues {
187 max_log_files: 7, 172 max_log_files: 7,
188 message_shortcode_display: false, 173 message_shortcode_display: false,
189 normal_after_send: true, 174 normal_after_send: true,
175 proxy: Proxy::default().values(),
190 reaction_display: true, 176 reaction_display: true,
191 reaction_shortcode_display: false, 177 reaction_shortcode_display: false,
192 read_receipt_send: true, 178 read_receipt_send: true,
src/worker.rs +31 −5
@@ -95,7 +95,7 @@ use modalkit::errors::UIError;
95use modalkit::prelude::{EditInfo, InfoMessage}; 95use modalkit::prelude::{EditInfo, InfoMessage};
96 96
97use crate::base::{EchoLocation, MessageNeed}; 97use crate::base::{EchoLocation, MessageNeed};
98use crate::config::ImagePreviewSize; 98use crate::config::{ImagePreviewSize, ProxyUrl};
99use crate::message::{Message, MessageEvent, MessageId, MessageKey}; 99use crate::message::{Message, MessageEvent, MessageId, MessageKey};
100use crate::notifications::register_notifications; 100use crate::notifications::register_notifications;
101use crate::preview::load_image; 101use crate::preview::load_image;
@@ -808,15 +808,41 @@ async fn create_client_inner(
808 let req_timeout = Duration::from_secs(settings.tunables.request_timeout); 808 let req_timeout = Duration::from_secs(settings.tunables.request_timeout);
809 809
810 // Set up the HTTP client. 810 // Set up the HTTP client.
811 let http = reqwest::Client::builder() 811 let mut builder = reqwest::Client::builder()
812 .user_agent(IAMB_USER_AGENT) 812 .user_agent(IAMB_USER_AGENT)
813 .timeout(req_timeout) 813 .timeout(req_timeout)
814 .pool_idle_timeout(Duration::from_secs(60)) 814 .pool_idle_timeout(Duration::from_secs(60))
815 .pool_max_idle_per_host(10) 815 .pool_max_idle_per_host(10)
816 .tcp_keepalive(Duration::from_secs(10)) 816 .tcp_keepalive(Duration::from_secs(10))
817 .danger_accept_invalid_certs(!settings.tunables.ssl_verify) 817 .danger_accept_invalid_certs(!settings.tunables.ssl_verify);
818 .build() 818
819 .unwrap(); 819 // Configure the HTTP client to use any provided proxy settings:
820 let proxy_config = &settings.tunables.proxy;
821
822 match &proxy_config.url {
823 ProxyUrl::Disabled => builder = builder.no_proxy(),
824 ProxyUrl::Endpoint(url) => {
825 let mut proxy =
826 reqwest::Proxy::all(url.clone()).map_err(matrix_sdk::HttpError::Reqwest)?;
827
828 if !proxy_config.headers.is_empty() {
829 proxy = proxy.headers(proxy_config.headers.clone());
830 }
831
832 if let Some(auth) = proxy_config.auth.clone() {
833 proxy = proxy.custom_http_auth(auth);
834 }
835
836 builder = builder.proxy(proxy)
837 },
838 ProxyUrl::System => {
839 // `reqwest` will use the *_PROXY environment variables from the
840 // system by default (through `hyper_util::client::proxy`), so do
841 // nothing and let it just figure things out for us.
842 },
843 }
844
845 let http = builder.build().map_err(matrix_sdk::HttpError::Reqwest)?;
820 846
821 let req_config = RequestConfig::new().timeout(req_timeout).max_retry_time(req_timeout); 847 let req_config = RequestConfig::new().timeout(req_timeout).max_retry_time(req_timeout);
822 848