ic-bn-lib 0.8.0

Internet Computer Boundary Nodes shared modules
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use std::time::Duration;

use anyhow::{Context, Error, anyhow, bail};
use async_trait::async_trait;
use http::StatusCode;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use url::Url;

use crate::tls::acme::{Record, dns::DnsManager};

pub struct IcDnsLb {
    client: Client,
    base_urls: Vec<Url>,
    token: String,
}

impl IcDnsLb {
    /// Create a new IC-DNS-LB API client with a default HTTP client
    pub fn new(base_urls: Vec<Url>, token: String) -> Result<Self, Error> {
        let client = Client::builder()
            .build()
            .context("failed to initialize HTTP client")?;

        Self::new_with_http_client(base_urls, client, token)
    }

    /// Create a new IC-DNS-LB API client with a provided HTTP client
    pub fn new_with_http_client(
        base_urls: Vec<Url>,
        client: Client,
        token: String,
    ) -> Result<Self, Error> {
        if base_urls.is_empty() {
            bail!("At least one URL must be specified");
        }

        for url in &base_urls {
            if url.cannot_be_a_base() {
                bail!("Invalid URL (cannot be a base)");
            }
        }

        Ok(Self {
            client,
            base_urls,
            token,
        })
    }

    /// Sends a POST request
    async fn post(&self, url: Url, req: AcmeChallengeRequest) -> Result<(), Error> {
        let call = async || -> Result<StatusCode, Error> {
            Ok(self
                .client
                .post(url.clone())
                .bearer_auth(&self.token)
                .json(&req)
                .send()
                .await
                .context("unable to send request")?
                .status())
        };

        // The calls are idempotent - do a few retries
        let mut last_error = None;
        for i in 0..5 {
            match call().await {
                Ok(v) => {
                    if !v.is_success() {
                        last_error = Some(anyhow!("bad HTTP status code: {v}"));

                        // Do not retry when it's not a server error
                        if !v.is_server_error() {
                            return Err(last_error.unwrap());
                        }
                    } else {
                        return Ok(());
                    }
                }

                Err(e) => {
                    last_error = Some(e);
                }
            }

            // Back off exponentially
            tokio::time::sleep(Duration::from_millis(250) * i).await;
        }

        Err(last_error.unwrap())
    }
}

/// Request that IC-DNS-LB expects
#[derive(Clone, Serialize, Deserialize)]
struct AcmeChallengeRequest {
    challenge: String,
}

#[async_trait]
impl DnsManager for IcDnsLb {
    async fn create(
        &self,
        zone: &str,
        _name: &str,
        record: Record,
        _ttl: u32,
    ) -> Result<(), Error> {
        let Record::Txt(challenge) = record;

        for url in &self.base_urls {
            let mut url = url.clone();

            // Strip trailing slash if exists & add path
            // SAFETY: cannot-be-a-base is checked in new()
            url.path_segments_mut()
                .unwrap()
                .pop_if_empty()
                .extend(["acme-challenge", "set", zone]);

            self.post(
                url,
                AcmeChallengeRequest {
                    challenge: challenge.clone(),
                },
            )
            .await?;
        }

        Ok(())
    }

    async fn delete(&self, zone: &str, _name: &str, record: &Record) -> Result<(), Error> {
        let Record::Txt(challenge) = record;

        // Try to remove records from all nodes even if some fail
        let mut errors = vec![];
        for url in &self.base_urls {
            let mut url = url.clone();

            // Strip trailing slash if exists & add path
            // SAFETY: cannot-be-a-base is checked in new()
            url.path_segments_mut().unwrap().pop_if_empty().extend([
                "acme-challenge",
                "unset",
                zone,
            ]);

            if let Err(e) = self
                .post(
                    url,
                    AcmeChallengeRequest {
                        challenge: challenge.clone(),
                    },
                )
                .await
            {
                errors.push(e.to_string());
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(Error::msg(errors.join(", ")))
        }
    }
}

/// Mocks the IC DNS LB HTTP API (`/acme-challenge/set/{zone}` and `/acme-challenge/unset/{zone}`)
#[cfg(test)]
mod test {
    use std::sync::{Arc, Mutex};

    use axum::{
        Json, Router,
        extract::{Path, State},
        http::{HeaderMap, StatusCode},
        response::{IntoResponse, Response},
        routing::post,
    };

    use super::*;
    use crate::tls::acme::dns::test::support::{
        check_bearer_auth, insecure_http_client, install_crypto_provider, spawn_https_mock_server,
    };

    const TOKEN: &str = "test-lb-token";

    /// In-memory state backing one mock IC DNS LB node.
    #[derive(Default)]
    struct MockState {
        // Incremented on every request regardless of outcome, so tests can tell a node
        // apart that was never contacted (e.g. because an earlier node in the list failed)
        // from one that was contacted but rejected the request.
        requests_received: u32,
        set_calls: Vec<(String, String)>,
        unset_calls: Vec<(String, String)>,
        fail_set: bool,
        fail_unset: bool,
    }

    type SharedState = Arc<Mutex<MockState>>;

    async fn set_challenge(
        State(state): State<SharedState>,
        Path(zone): Path<String>,
        headers: HeaderMap,
        Json(body): Json<AcmeChallengeRequest>,
    ) -> Response {
        let mut state = state.lock().unwrap();
        state.requests_received += 1;

        if !check_bearer_auth(&headers, TOKEN) {
            return StatusCode::UNAUTHORIZED.into_response();
        }
        if state.fail_set {
            return StatusCode::INTERNAL_SERVER_ERROR.into_response();
        }

        state.set_calls.push((zone, body.challenge));
        drop(state);
        StatusCode::OK.into_response()
    }

    async fn unset_challenge(
        State(state): State<SharedState>,
        Path(zone): Path<String>,
        headers: HeaderMap,
        Json(body): Json<AcmeChallengeRequest>,
    ) -> Response {
        let mut state = state.lock().unwrap();
        state.requests_received += 1;

        if !check_bearer_auth(&headers, TOKEN) {
            return StatusCode::UNAUTHORIZED.into_response();
        }
        if state.fail_unset {
            return StatusCode::INTERNAL_SERVER_ERROR.into_response();
        }

        state.unset_calls.push((zone, body.challenge));
        drop(state);
        StatusCode::OK.into_response()
    }

    fn mock_router(state: SharedState) -> Router {
        Router::new()
            .route("/acme-challenge/set/{zone}", post(set_challenge))
            .route("/acme-challenge/unset/{zone}", post(unset_challenge))
            .with_state(state)
    }

    /// One mock LB node: its in-memory state plus the base URL `IcDnsLb` should be given.
    struct TestNode {
        state: SharedState,
        base_url: Url,
    }

    fn client_with_token(base_urls: Vec<Url>, token: &str) -> IcDnsLb {
        IcDnsLb::new_with_http_client(base_urls, insecure_http_client(), token.to_string()).unwrap()
    }

    /// Boots `n` independent mock IC DNS LB nodes and a matching `IcDnsLb` client pointed at
    /// all of them, mirroring a real deployment where the same challenge is pushed to every
    /// node.
    async fn setup(n: usize) -> (IcDnsLb, Vec<TestNode>) {
        install_crypto_provider();

        let mut nodes = Vec::with_capacity(n);
        for _ in 0..n {
            let state: SharedState = Arc::new(Mutex::new(MockState::default()));
            let base_url = spawn_https_mock_server(mock_router(state.clone())).await;
            nodes.push(TestNode { state, base_url });
        }

        let base_urls = nodes.iter().map(|n| n.base_url.clone()).collect();
        let client = client_with_token(base_urls, TOKEN);

        (client, nodes)
    }

    #[tokio::test]
    async fn create_sends_challenge_to_every_node() {
        let (client, nodes) = setup(3).await;

        client
            .create(
                "example.com",
                "_acme-challenge",
                Record::Txt("the-token".into()),
                60,
            )
            .await
            .unwrap();

        for node in &nodes {
            assert_eq!(
                node.state.lock().unwrap().set_calls,
                vec![("example.com".to_string(), "the-token".to_string())]
            );
        }
    }

    #[tokio::test]
    async fn delete_sends_challenge_to_every_node() {
        let (client, nodes) = setup(3).await;

        client
            .delete(
                "example.com",
                "_acme-challenge",
                &Record::Txt("the-token".into()),
            )
            .await
            .unwrap();

        for node in &nodes {
            assert_eq!(
                node.state.lock().unwrap().unset_calls,
                vec![("example.com".to_string(), "the-token".to_string())]
            );
        }
    }

    #[tokio::test(start_paused = true)]
    async fn create_errors_when_a_node_returns_bad_status() {
        let (client, nodes) = setup(1).await;
        nodes[0].state.lock().unwrap().fail_set = true;

        let err = client
            .create(
                "example.com",
                "_acme-challenge",
                Record::Txt("the-token".into()),
                60,
            )
            .await
            .unwrap_err();
        assert!(err.to_string().contains("bad HTTP status code"), "{err}");
    }

    #[tokio::test(start_paused = true)]
    async fn delete_errors_when_a_node_returns_bad_status() {
        let (client, nodes) = setup(1).await;
        nodes[0].state.lock().unwrap().fail_unset = true;

        let err = client
            .delete(
                "example.com",
                "_acme-challenge",
                &Record::Txt("the-token".into()),
            )
            .await
            .unwrap_err();
        assert!(err.to_string().contains("bad HTTP status code"), "{err}");
    }

    #[tokio::test(start_paused = true)]
    async fn create_stops_at_first_failing_node_and_does_not_contact_the_rest() {
        let (client, nodes) = setup(2).await;
        nodes[0].state.lock().unwrap().fail_set = true;

        client
            .create(
                "example.com",
                "_acme-challenge",
                Record::Txt("the-token".into()),
                60,
            )
            .await
            .unwrap_err();

        assert_eq!(nodes[0].state.lock().unwrap().requests_received, 5);
        assert_eq!(
            nodes[1].state.lock().unwrap().requests_received,
            0,
            "later nodes must not be contacted once an earlier one fails"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn delete_contacts_all_nodes_even_if_one_fails() {
        let (client, nodes) = setup(2).await;
        nodes[0].state.lock().unwrap().fail_unset = true;

        client
            .delete(
                "example.com",
                "_acme-challenge",
                &Record::Txt("the-token".into()),
            )
            .await
            .unwrap_err();

        assert_eq!(nodes[0].state.lock().unwrap().requests_received, 5);
        assert_eq!(nodes[1].state.lock().unwrap().requests_received, 1);
    }

    #[tokio::test(start_paused = true)]
    async fn create_errors_when_a_node_is_unreachable() {
        install_crypto_provider();

        // Bind and immediately drop the listener: the port is guaranteed free, but nothing
        // is listening on it, so a connection attempt is refused at the TCP level rather than
        // answered with an HTTP error status.
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        drop(listener);

        let base_url: Url = format!("https://{addr}/").parse().unwrap();
        let client = client_with_token(vec![base_url], TOKEN);

        let err = client
            .create(
                "example.com",
                "_acme-challenge",
                Record::Txt("the-token".into()),
                60,
            )
            .await
            .unwrap_err();
        assert!(err.to_string().contains("unable to send request"), "{err}");
    }

    #[tokio::test]
    async fn create_errors_on_wrong_token() {
        let (_client, nodes) = setup(1).await;
        let base_urls = nodes.iter().map(|n| n.base_url.clone()).collect();
        let client = client_with_token(base_urls, "wrong-token");

        let err = client
            .create(
                "example.com",
                "_acme-challenge",
                Record::Txt("the-token".into()),
                60,
            )
            .await
            .unwrap_err();
        assert!(err.to_string().contains("bad HTTP status code"), "{err}");
        assert!(nodes[0].state.lock().unwrap().set_calls.is_empty());
    }

    /// Boots a single mock node whose API is mounted under a path prefix (e.g. as if the LB
    /// were reachable at `https://host/lb-api/...` rather than at the server root), so tests
    /// can check that `IcDnsLb` preserves an existing path prefix in `base_urls` instead of
    /// routing every request at the server root.
    async fn setup_with_path_prefix(prefix: &str) -> (Url, SharedState) {
        install_crypto_provider();

        let state: SharedState = Arc::new(Mutex::new(MockState::default()));
        let router = Router::new().nest(&format!("/{prefix}"), mock_router(state.clone()));
        let root_url = spawn_https_mock_server(router).await;

        (root_url, state)
    }

    #[tokio::test]
    async fn create_preserves_base_url_path_prefix_without_trailing_slash() {
        let (root_url, state) = setup_with_path_prefix("lb-api").await;
        let base_url: Url = format!("{root_url}lb-api").parse().unwrap();
        let client = client_with_token(vec![base_url], TOKEN);

        client
            .create(
                "example.com",
                "_acme-challenge",
                Record::Txt("the-token".into()),
                60,
            )
            .await
            .unwrap();

        assert_eq!(
            state.lock().unwrap().set_calls,
            vec![("example.com".to_string(), "the-token".to_string())]
        );
    }

    #[tokio::test]
    async fn create_preserves_base_url_path_prefix_with_trailing_slash() {
        let (root_url, state) = setup_with_path_prefix("lb-api").await;
        let base_url: Url = format!("{root_url}lb-api/").parse().unwrap();
        let client = client_with_token(vec![base_url], TOKEN);

        client
            .create(
                "example.com",
                "_acme-challenge",
                Record::Txt("the-token".into()),
                60,
            )
            .await
            .unwrap();

        assert_eq!(
            state.lock().unwrap().set_calls,
            vec![("example.com".to_string(), "the-token".to_string())]
        );
    }

    /// End-to-end lifecycle through the public `DnsManager` trait, fanned out across multiple
    /// nodes: create the challenge everywhere, then remove it everywhere.
    #[tokio::test]
    async fn create_then_delete_round_trip_across_nodes() {
        let (client, nodes) = setup(3).await;
        let manager: &dyn DnsManager = &client;

        manager
            .create(
                "example.com",
                "_acme-challenge",
                Record::Txt("round-trip-token".into()),
                60,
            )
            .await
            .unwrap();

        for node in &nodes {
            assert_eq!(
                node.state.lock().unwrap().set_calls,
                vec![("example.com".to_string(), "round-trip-token".to_string())]
            );
        }

        manager
            .delete(
                "example.com",
                "_acme-challenge",
                &Record::Txt("round-trip-token".into()),
            )
            .await
            .unwrap();

        for node in &nodes {
            assert_eq!(
                node.state.lock().unwrap().unset_calls,
                vec![("example.com".to_string(), "round-trip-token".to_string())]
            );
        }
    }
}