nym-http-api-client 1.20.5

Nym's HTTP API client, examples, and tests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0

//! Utilities for and implementation of request tunneling

use std::sync::{
    Arc, LazyLock, RwLock,
    atomic::{AtomicBool, Ordering},
};
use tracing::warn;

use crate::{Client, ClientBuilder};

static SHARED_FRONTING_POLICY: LazyLock<Arc<RwLock<FrontPolicy>>> =
    LazyLock::new(|| Arc::new(RwLock::new(FrontPolicy::Off)));

// #[cfg(feature = "tunneling")]
#[derive(Debug)]
pub(crate) struct Front {
    pub(crate) policy: Arc<RwLock<FrontPolicy>>,
    enabled: AtomicBool,
}

impl Clone for Front {
    fn clone(&self) -> Self {
        Self {
            policy: self.policy.clone(),
            enabled: AtomicBool::new(false),
        }
    }
}

impl Front {
    pub(crate) fn new(policy: FrontPolicy) -> Self {
        Self {
            enabled: AtomicBool::new(false),
            policy: Arc::new(RwLock::new(policy)),
        }
    }

    pub(crate) fn off() -> Self {
        Self::new(FrontPolicy::Off)
    }

    pub(crate) fn shared() -> Self {
        let policy = SHARED_FRONTING_POLICY.clone();
        Self {
            enabled: AtomicBool::new(false),
            policy,
        }
    }

    pub(crate) fn set_policy(&self, policy: FrontPolicy) {
        *self.policy.write().unwrap() = policy;
        self.enabled.store(false, Ordering::Relaxed);
    }

    pub(crate) fn is_enabled(&self) -> bool {
        match *self.policy.read().unwrap() {
            FrontPolicy::Off => false,
            FrontPolicy::OnRetry => self.enabled.load(Ordering::Relaxed),
            FrontPolicy::Always => true,
        }
    }

    // Used to indicate that the client hit an error that should trigger the retry policy
    // to enable fronting.
    pub(crate) fn retry_enable(&self) {
        if self.is_enabled() {
            return;
        }
        if matches!(*self.policy.read().unwrap(), FrontPolicy::OnRetry) {
            self.enabled.store(true, Ordering::Relaxed);
        }
    }
}

#[derive(Debug, Default, PartialEq, Clone)]
/// Policy for when to use domain fronting for HTTP requests.
pub enum FrontPolicy {
    /// Always use domain fronting for all requests.
    Always,
    /// Only use domain fronting when retrying failed requests.
    OnRetry,
    #[default]
    /// Never use domain fronting.
    Off,
}

impl ClientBuilder {
    /// Enable and configure request tunneling for API requests. If no front policy is
    /// provided the shared fronting policy will be used.
    pub fn with_fronting(mut self, policy: Option<FrontPolicy>) -> Self {
        let front = if let Some(p) = policy {
            Front::new(p)
        } else {
            Front::shared()
        };

        // Check if any of the supplied urls even support fronting
        if !self.urls.iter().any(|url| url.has_front()) {
            warn!(
                "fronting is enabled, but none of the supplied urls have configured fronting domains: {:?}",
                self.urls
            );
        }

        self.front = front;

        self
    }
}

impl Client {
    /// Set the policy for enabling fronting. If fronting was previously unset this will set it, and
    /// make it possible to enable (i.e [`FrontPolicy::Off`] will not enable it).
    ///
    /// Calling this function sets a custom policy for this client, disconnecting it from the shared
    /// fronting policy -- i.e. changes applied through [`Client::set_shared_front_policy`] will not
    /// be impact this client.
    pub fn set_front_policy(&mut self, policy: FrontPolicy) {
        self.front.set_policy(policy)
    }

    /// Set the fronting policy for this client to follow the shared policy.
    pub fn use_shared_front_policy(&mut self) {
        self.front = Front::shared();
    }

    /// Set the fronting policy for all clients using the shared policy.
    //
    // NOTE: this does not reset the per-instance enabled flag like it will when using
    // [`Front::set_front_policy`]. So if a client is using shared policy with the `OnRetry` policy
    // and this function is used to swap that policy away from and then back to `OnRetry` the
    // fronting will still be enabled. Noting this here just in case this triggers any corner cases
    // down the road.
    pub fn set_shared_front_policy(policy: FrontPolicy) {
        *SHARED_FRONTING_POLICY.write().unwrap() = policy;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ApiClientCore, NO_PARAMS, Url};

    impl Front {
        pub(crate) fn policy(&self) -> FrontPolicy {
            self.policy.read().unwrap().clone()
        }
    }

    /// Policy can be set for an independent client and the update is applied properly
    #[test]
    fn set_policy_independent_client() {
        let url1 = Url::new(
            "https://validator.global.ssl.fastly.net",
            Some(vec!["https://yelp.global.ssl.fastly.net"]),
        )
        .unwrap();

        let mut client1 = ClientBuilder::new(url1.clone())
            .unwrap()
            .with_fronting(Some(FrontPolicy::Off))
            .build()
            .unwrap();
        assert!(client1.front.policy() == FrontPolicy::Off);

        let client2 = ClientBuilder::new(url1.clone())
            .unwrap()
            .with_fronting(Some(FrontPolicy::OnRetry))
            .build()
            .unwrap();

        // Ensure that setting the policy for a client it gets properly applied.
        client1.set_front_policy(FrontPolicy::Always);
        assert!(client1.front.policy() == FrontPolicy::Always);

        // ensure that setting the policy in a client NOT using the shared policy does NOT update
        // the policy used by another client.
        assert!(client2.front.policy() == FrontPolicy::OnRetry);

        // Ensure that the policy takes effect and is applied when setting host headers on outgoing
        // requests
        let req = client1
            .create_request(reqwest::Method::GET, &["/"], NO_PARAMS, None::<&()>)
            .unwrap()
            .build()
            .unwrap();

        let expected_host = url1.host_str().unwrap();
        assert!(
            req.headers()
                .get(reqwest::header::HOST)
                .is_some_and(|h| h.to_str().unwrap() == expected_host),
            "{:?} != {:?}",
            expected_host,
            req,
        );

        let expected_front = url1.front_str().unwrap();
        assert!(
            req.url()
                .host()
                .is_some_and(|url| url.to_string() == expected_front),
            "{:?} != {:?}",
            expected_front,
            req,
        );
    }

    /// Policy can be set for the shared client and the update is applied properly
    // NOTE THIS TEST IS DISABLED BECAUSE IT INTERACTS WITH THE SHARED POLICY AND AS SUCH CAN HAVE
    // AN IMPACT ON OTHER TESTS
    #[test]
    #[cfg(any())] // #[ignore] we run --ignore in CI/CD assuming it just means slow -_-
    fn set_policy_shared_client() {
        let url1 = Url::new(
            "https://validator.global.ssl.fastly.net",
            Some(vec!["https://yelp.global.ssl.fastly.net"]),
        )
        .unwrap();

        Client::set_shared_front_policy(FrontPolicy::Off);
        assert!(*SHARED_FRONTING_POLICY.read().unwrap() == FrontPolicy::Off);

        let client1 = ClientBuilder::new(url1.clone())
            .unwrap()
            .with_fronting(None)
            .build()
            .unwrap();
        assert!(client1.front.policy() == FrontPolicy::Off);

        let mut client2 = ClientBuilder::new(url1.clone())
            .unwrap()
            .with_fronting(Some(FrontPolicy::Off))
            .build()
            .unwrap();

        // Ensure that setting the shared policy gets properly applied
        Client::set_shared_front_policy(FrontPolicy::Always);
        assert!(client1.front.policy() == FrontPolicy::Always);

        // Setting the shared policy should NOT update clients NOT using the shared policy.
        assert!(client2.front.policy() == FrontPolicy::Off);

        // Ensure that the policy takes effect and is applied when setting host headers on outgoing
        // requests
        let req = client1
            .create_request(reqwest::Method::GET, &["/"], NO_PARAMS, None::<&()>)
            .unwrap()
            .build()
            .unwrap();

        let expected_host = url1.host_str().unwrap();
        assert!(
            req.headers()
                .get(reqwest::header::HOST)
                .is_some_and(|h| h.to_str().unwrap() == expected_host),
            "{:?} != {:?}",
            expected_host,
            req,
        );

        let expected_front = url1.front_str().unwrap();
        assert!(
            req.url()
                .host()
                .is_some_and(|url| url.to_string() == expected_front),
            "{:?} != {:?}",
            expected_front,
            req,
        );

        // ensure that setting to the shared policy works
        client2.use_shared_front_policy();
        assert!(client2.front.policy() == FrontPolicy::Always);

        // ensure that if the policy is OnRetry then the `enabled` fields are still independent,
        // despite the policy being shared.
        Client::set_shared_front_policy(FrontPolicy::OnRetry);
        assert!(client1.front.policy() == FrontPolicy::OnRetry);
        assert!(client2.front.policy() == FrontPolicy::OnRetry);

        assert!(!client1.front.is_enabled());
        assert!(!client2.front.is_enabled());

        client1.front.retry_enable();
        assert!(client1.front.is_enabled());
        assert!(!client2.front.is_enabled());
    }

    #[tokio::test]
    async fn nym_api_works() {
        let url1 = Url::new(
            "https://validator.global.ssl.fastly.net",
            Some(vec!["https://yelp.global.ssl.fastly.net"]),
        )
        .unwrap(); // fastly

        // let url2 = Url::new(
        //     "https://validator.nymtech.net",
        //     Some(vec!["https://cdn77.com"]),
        // ).unwrap(); // cdn77

        let client = ClientBuilder::new(url1)
            .expect("bad url")
            .with_fronting(Some(FrontPolicy::Always))
            .build()
            .expect("failed to build client");

        let response = client
            .send_request::<_, (), &str, &str>(
                reqwest::Method::GET,
                &["api", "v1", "network", "details"],
                NO_PARAMS,
                None,
            )
            .await
            .expect("failed get request");

        // println!("{response:?}");
        assert_eq!(response.status(), 200);
    }

    #[tokio::test]
    async fn fallback_on_failure() {
        let url1 = Url::new(
            "https://fake-domain.nymtech.net",
            Some(vec![
                "https://fake-front-1.nymtech.net",
                "https://fake-front-2.nymtech.net",
            ]),
        )
        .unwrap();
        let url2 = Url::new(
            "https://validator.global.ssl.fastly.net",
            Some(vec!["https://yelp.global.ssl.fastly.net"]),
        )
        .unwrap(); // fastly

        let client = ClientBuilder::new_with_urls(vec![url1, url2])
            .expect("bad url")
            .with_fronting(Some(FrontPolicy::Always))
            .build()
            .expect("failed to build client");

        // Check that the initial configuration has the broken domain and front.
        assert_eq!(
            client.current_url().as_str(),
            "https://fake-domain.nymtech.net/",
        );
        assert_eq!(
            client.current_url().front_str(),
            Some("fake-front-1.nymtech.net"),
        );

        let result = client
            .send_request::<_, (), &str, &str>(
                reqwest::Method::GET,
                &["api", "v1", "network", "details"],
                NO_PARAMS,
                None,
            )
            .await;
        assert!(result.is_err());

        // Check that the host configuration updated the front on error.
        assert_eq!(
            client.current_url().as_str(),
            "https://fake-domain.nymtech.net/",
        );
        assert_eq!(
            client.current_url().front_str(),
            Some("fake-front-2.nymtech.net"),
        );

        let result = client
            .send_request::<_, (), &str, &str>(
                reqwest::Method::GET,
                &["api", "v1", "network", "details"],
                NO_PARAMS,
                None,
            )
            .await;
        assert!(result.is_err());

        // Check that the host configuration updated the domain and front on error.
        assert_eq!(
            client.current_url().as_str(),
            "https://validator.global.ssl.fastly.net/",
        );
        assert_eq!(
            client.current_url().front_str(),
            Some("yelp.global.ssl.fastly.net"),
        );

        let response = client
            .send_request::<_, (), &str, &str>(
                reqwest::Method::GET,
                &["api", "v1", "network", "details"],
                NO_PARAMS,
                None,
            )
            .await
            .expect("failed get request");

        assert_eq!(response.status(), 200);
    }
}