technitium 0.4.0

Typed async Rust client for the Technitium DNS Server API
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
use std::sync::Arc;
use std::time::Duration;

use reqwest::multipart;
use serde::de::DeserializeOwned;
use tokio::sync::RwLock;
use tokio::time::Instant;
use tracing::instrument;
use url::Url;

use crate::error::{ApiResponse, Error, RequestParams};
use crate::rate_limiter::RateLimiter;
use crate::retry::RetryPolicy;
use crate::types::auth::Credentials;
use crate::zone_client::ZoneClient;

/// Params to exclude from error context (sensitive data).
const SENSITIVE_PARAMS: &[&str] = &["token", "pass", "totp"];

/// Filter out sensitive parameters before attaching to errors.
fn filter_sensitive_params(params: &[(&str, &str)]) -> RequestParams {
    RequestParams(
        params
            .iter()
            .filter(|(k, _)| !SENSITIVE_PARAMS.contains(k))
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect(),
    )
}

/// An async client for the Technitium DNS Server API.
///
/// Construct via [`Client::builder`] or [`Client::connect`].
///
/// # Examples
///
/// ```no_run
/// # async fn example() -> Result<(), technitium::Error> {
/// // Quick connect with auto-reauth
/// let client = technitium::Client::connect(
///     "http://localhost:5380", "admin", "admin"
/// ).await?;
///
/// let zones = client.list_zones().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Client {
    pub(crate) base_url: Url,
    pub(crate) http: reqwest::Client,
    pub(crate) token: Arc<RwLock<Option<String>>>,
    pub(crate) credentials: Option<Credentials>,
    pub(crate) auto_reauth: bool,
    pub(crate) retry_policy: Option<RetryPolicy>,
    pub(crate) rate_limiter: Option<Arc<RateLimiter>>,
}

impl Client {
    /// Create a new [`ClientBuilder`].
    #[must_use]
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Connect, authenticate, and enable auto-reauth in one call.
    ///
    /// This is a convenience for the common pattern of building a client,
    /// logging in, and enabling automatic re-authentication.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Authentication`] if login fails, or
    /// [`Error::Config`] if the URL is invalid.
    pub async fn connect(
        url: impl Into<String>,
        username: &str,
        password: &str,
    ) -> Result<Self, Error> {
        let client = Self::builder()
            .base_url(url)
            .credentials(username, password)
            .auto_reauth(true)
            .build()?;
        client.login(username, password).await?;
        Ok(client)
    }

    /// Create a zone-scoped handle that binds the zone name for all operations.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), technitium::Error> {
    /// let client = technitium::Client::connect(
    ///     "http://localhost:5380", "admin", "admin",
    /// ).await?;
    ///
    /// let zone = client.zone("example.com");
    /// let records = zone.list_records(None).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn zone(&self, zone: impl Into<String>) -> ZoneClient<'_> {
        ZoneClient::new(self, zone.into())
    }

    /// Resolve which zone contains a domain by walking parent labels.
    ///
    /// Queries [`Client::list_zones`] and matches the domain against known
    /// zone names by progressively stripping leading labels.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if no matching zone is found.
    pub async fn resolve_zone(&self, domain: &str) -> Result<String, Error> {
        let zones = self.list_zones().await?;

        let mut candidate = domain;
        loop {
            if zones.iter().any(|z| z.name == candidate) {
                return Ok(candidate.to_string());
            }
            match candidate.find('.') {
                Some(idx) => candidate = &candidate[idx + 1..],
                None => break,
            }
        }

        Err(Error::Config {
            reason: format!("no zone found for domain '{domain}'"),
        })
    }

    /// Resolve the zone for a domain, then return a zone-scoped handle.
    ///
    /// Combines [`Client::resolve_zone`] and [`Client::zone`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), technitium::Error> {
    /// let client = technitium::Client::connect(
    ///     "http://localhost:5380", "admin", "admin",
    /// ).await?;
    ///
    /// let zone = client.zone_for_domain("www.example.com").await?;
    /// assert_eq!(zone.name(), "example.com");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if no matching zone is found.
    pub async fn zone_for_domain(&self, domain: &str) -> Result<ZoneClient<'_>, Error> {
        let zone_name = self.resolve_zone(domain).await?;
        Ok(self.zone(zone_name))
    }

    // ── Internal dispatch helpers (single copy of each pattern) ──

    /// Read the current token from the lock.
    async fn current_token(&self) -> Option<String> {
        self.token.read().await.clone()
    }

    /// Send a form-encoded POST and return the raw response.
    pub(crate) async fn do_send_form(
        &self,
        path: &str,
        params: &[(&str, &str)],
    ) -> Result<reqwest::Response, Error> {
        // Check authentication
        let token = self.current_token().await;
        if token.is_none() {
            // Allow unauthenticated calls to login/createToken endpoints
            let is_auth_path = path.contains("/user/login") || path.contains("/user/createToken");
            if !is_auth_path {
                return Err(Error::NotAuthenticated);
            }
        }

        let url = self.base_url.join(path).map_err(|e| Error::Config {
            reason: format!("invalid API path '{path}': {e}"),
        })?;

        let mut form_params: Vec<(String, String)> = params
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();

        if let Some(t) = &token {
            form_params.push(("token".to_string(), t.clone()));
        }

        tracing::debug!(%url, "sending API request");

        self.http
            .post(url)
            .form(&form_params)
            .send()
            .await?
            .error_for_status()
            .map_err(Error::Http)
    }

    /// Send a multipart POST and return the raw response.
    async fn do_send_multipart(
        &self,
        path: &str,
        form: multipart::Form,
    ) -> Result<reqwest::Response, Error> {
        let token = self.current_token().await;
        if token.is_none() {
            return Err(Error::NotAuthenticated);
        }

        let url = self.base_url.join(path).map_err(|e| Error::Config {
            reason: format!("invalid API path '{path}': {e}"),
        })?;

        let form = if let Some(t) = &token {
            form.text("token", t.clone())
        } else {
            form
        };

        tracing::debug!(%url, "sending multipart API request");

        self.http
            .post(url)
            .multipart(form)
            .send()
            .await?
            .error_for_status()
            .map_err(Error::Http)
    }

    /// Acquire a rate limiter permit if rate limiting is enabled.
    async fn acquire_rate_limit(&self) {
        if let Some(rl) = &self.rate_limiter {
            rl.acquire().await;
        }
    }

    // ── Public dispatch methods (reauth + retry wrappers) ───────

    /// Send a POST request with rate limiting, reauth, and retry.
    #[instrument(skip(self, params), fields(path))]
    pub(crate) async fn request<T: DeserializeOwned>(
        &self,
        path: &str,
        params: &[(&str, &str)],
    ) -> Result<T, Error> {
        self.with_reauth_retry(|| self.do_request::<T>(path, params))
            .await
    }

    /// Send a POST request that returns no meaningful data.
    #[instrument(skip(self, params), fields(path))]
    pub(crate) async fn request_unit(
        &self,
        path: &str,
        params: &[(&str, &str)],
    ) -> Result<(), Error> {
        self.with_reauth_retry(|| self.do_request_unit(path, params))
            .await
    }

    /// Execute a request with rate limiting, automatic re-authentication,
    /// and retry on transient errors.
    async fn with_reauth_retry<T, Fut>(&self, execute: impl Fn() -> Fut) -> Result<T, Error>
    where
        Fut: Future<Output = Result<T, Error>>,
    {
        self.acquire_rate_limit().await;

        let mut result = execute().await;

        // Reauth on invalid token (once, before retries)
        if matches!(&result, Err(Error::InvalidToken)) && self.auto_reauth {
            if let Some(creds) = &self.credentials {
                tracing::info!("token expired, attempting re-authentication");
                self.do_login(&creds.username, &creds.password, creds.totp.as_deref())
                    .await?;
                result = execute().await;
            }
        }

        // Retry transient errors
        if let Some(ref policy) = self.retry_policy {
            if let Err(ref e) = result {
                if e.is_retryable() && policy.max_attempts > 0 {
                    let started = Instant::now();
                    for attempt in 1..=policy.max_attempts {
                        let delay = policy.compute_delay(attempt - 1);
                        if started.elapsed() + delay > Duration::from_secs(30) {
                            break;
                        }
                        tracing::warn!(
                            attempt,
                            delay_ms = u64::try_from(delay.as_millis()).unwrap_or(u64::MAX),
                            "retrying after transient error"
                        );
                        tokio::time::sleep(delay).await;
                        result = execute().await;
                        if result.is_ok() || !result.as_ref().err().is_some_and(Error::is_retryable)
                        {
                            break;
                        }
                    }
                }
            }
        }

        result
    }

    // ── Inner dispatch (no retry/reauth, just send + parse) ─────

    /// Send form POST and parse typed response.
    async fn do_request<T: DeserializeOwned>(
        &self,
        path: &str,
        params: &[(&str, &str)],
    ) -> Result<T, Error> {
        let response = self.do_send_form(path, params).await?;
        let http_status = response.status().as_u16();
        let mut api_response: ApiResponse<T> = response.json().await?;
        api_response.http_status = Some(http_status);
        api_response.path = path.to_string();
        api_response.params = filter_sensitive_params(params);
        api_response.into_result()
    }

    /// Send form POST and check status only.
    async fn do_request_unit(&self, path: &str, params: &[(&str, &str)]) -> Result<(), Error> {
        let response = self.do_send_form(path, params).await?;
        let http_status = response.status().as_u16();
        let mut api_response: ApiResponse<serde_json::Value> = response.json().await?;
        api_response.http_status = Some(http_status);
        api_response.path = path.to_string();
        api_response.params = filter_sensitive_params(params);
        api_response.check_status()
    }

    /// Send a multipart POST request that returns no meaningful data.
    #[instrument(skip(self, form), fields(path))]
    pub(crate) async fn request_multipart_unit(
        &self,
        path: &str,
        form: multipart::Form,
    ) -> Result<(), Error> {
        self.acquire_rate_limit().await;
        let response = self.do_send_multipart(path, form).await?;
        let http_status = response.status().as_u16();
        let mut api_response: ApiResponse<serde_json::Value> = response.json().await?;
        api_response.http_status = Some(http_status);
        api_response.path = path.to_string();
        // Multipart forms don't have structured params to capture
        api_response.check_status()
    }

    /// Download raw bytes from an API endpoint.
    #[instrument(skip(self, params), fields(path))]
    pub(crate) async fn request_bytes(
        &self,
        path: &str,
        params: &[(&str, &str)],
    ) -> Result<Vec<u8>, Error> {
        self.acquire_rate_limit().await;
        let response = self.do_send_form(path, params).await?;
        let bytes = response.bytes().await?;
        Ok(bytes.to_vec())
    }

    /// Internal login implementation.
    pub(crate) async fn do_login(
        &self,
        username: &str,
        password: &str,
        totp: Option<&str>,
    ) -> Result<(), Error> {
        let url = self
            .base_url
            .join("/api/user/login")
            .map_err(|e| Error::Config {
                reason: format!("invalid base URL: {e}"),
            })?;

        let mut form: Vec<(&str, &str)> = vec![("user", username), ("pass", password)];
        if let Some(code) = totp {
            form.push(("totp", code));
        }

        tracing::info!("authenticating as {}", username);

        let response = self
            .http
            .post(url)
            .form(&form)
            .send()
            .await?
            .error_for_status()
            .map_err(Error::Http)?;

        let body: serde_json::Value = response.json().await?;

        let login_params = RequestParams(vec![("user".to_string(), username.to_string())]);

        match body.get("status").and_then(|s| s.as_str()) {
            Some("ok") => {
                let token =
                    body.get("token")
                        .and_then(|t| t.as_str())
                        .ok_or_else(|| Error::Server {
                            message: "login response missing token".to_string(),
                            status_code: None,
                            path: "/api/user/login".to_string(),
                            params: login_params.clone(),
                        })?;
                let mut guard = self.token.write().await;
                *guard = Some(token.to_owned());
                Ok(())
            }
            Some("error") => Err(Error::Authentication {
                message: body
                    .get("errorMessage")
                    .and_then(|m| m.as_str())
                    .unwrap_or("unknown error")
                    .to_string(),
            }),
            Some("invalid-token") => Err(Error::InvalidToken),
            Some("2fa-required") => Err(Error::TwoFactorRequired),
            _ => Err(Error::Server {
                message: "unexpected login response".to_string(),
                status_code: None,
                path: "/api/user/login".to_string(),
                params: login_params,
            }),
        }
    }
}

const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// Builder for constructing a [`Client`].
///
/// # Examples
///
/// ```no_run
/// use std::time::Duration;
/// use technitium::{Client, RetryPolicy};
///
/// # fn example() -> Result<(), technitium::Error> {
/// let client = Client::builder()
///     .base_url("http://localhost:5380")
///     .request_timeout(Duration::from_secs(15))
///     .retry_policy(RetryPolicy::default())
///     .rate_limit(10.0)
///     .build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Default)]
pub struct ClientBuilder {
    base_url: Option<String>,
    token: Option<String>,
    username: Option<String>,
    password: Option<String>,
    auto_reauth: bool,
    request_timeout: Option<Duration>,
    connect_timeout: Option<Duration>,
    retry_policy: Option<RetryPolicy>,
    rate_limit: Option<f64>,
    pool_max_idle: Option<usize>,
    pool_idle_timeout: Option<Duration>,
}

impl ClientBuilder {
    /// Set the Technitium server base URL.
    #[must_use]
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Set a pre-existing session or API token.
    #[must_use]
    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// Store credentials for automatic re-authentication.
    #[must_use]
    pub fn credentials(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
        self.username = Some(username.into());
        self.password = Some(password.into());
        self
    }

    /// Enable automatic re-authentication on token expiry.
    ///
    /// Requires credentials to be set via [`ClientBuilder::credentials`].
    #[must_use]
    pub fn auto_reauth(mut self, enabled: bool) -> Self {
        self.auto_reauth = enabled;
        self
    }

    /// Set the total request timeout (default: 30s).
    #[must_use]
    pub fn request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = Some(timeout);
        self
    }

    /// Set the connection timeout (default: 10s).
    #[must_use]
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = Some(timeout);
        self
    }

    /// Enable automatic retry with the given policy.
    #[must_use]
    pub fn retry_policy(mut self, policy: RetryPolicy) -> Self {
        self.retry_policy = Some(policy);
        self
    }

    /// Set the maximum requests per second (default: unlimited).
    #[must_use]
    pub fn rate_limit(mut self, requests_per_second: f64) -> Self {
        self.rate_limit = Some(requests_per_second);
        self
    }

    /// Set the maximum idle connections per host.
    #[must_use]
    pub fn pool_max_idle(mut self, max_idle: usize) -> Self {
        self.pool_max_idle = Some(max_idle);
        self
    }

    /// Set the idle connection timeout.
    #[must_use]
    pub fn pool_idle_timeout(mut self, timeout: Duration) -> Self {
        self.pool_idle_timeout = Some(timeout);
        self
    }

    /// Build the [`Client`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if:
    /// - `base_url` is missing or invalid
    /// - `auto_reauth` is enabled without credentials
    pub fn build(self) -> Result<Client, Error> {
        let base_url_str = self.base_url.ok_or_else(|| Error::Config {
            reason: "base_url is required".to_string(),
        })?;
        let base_url = Url::parse(&base_url_str).map_err(|e| Error::Config {
            reason: format!("invalid base_url '{base_url_str}': {e}"),
        })?;

        // Validate auto_reauth requires credentials
        let credentials = match (self.username, self.password) {
            (Some(u), Some(p)) => Some(Credentials {
                username: u,
                password: p,
                totp: None,
            }),
            _ => None,
        };

        if self.auto_reauth && credentials.is_none() {
            return Err(Error::Config {
                reason: "auto_reauth requires credentials — call .credentials() before .auto_reauth(true)"
                    .to_string(),
            });
        }

        let token = self.token.map_or_else(
            || Arc::new(RwLock::new(None)),
            |t| Arc::new(RwLock::new(Some(t))),
        );

        let mut http_builder = reqwest::Client::builder()
            .timeout(self.request_timeout.unwrap_or(DEFAULT_REQUEST_TIMEOUT))
            .connect_timeout(self.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT));

        if let Some(max_idle) = self.pool_max_idle {
            http_builder = http_builder.pool_max_idle_per_host(max_idle);
        }
        if let Some(idle_timeout) = self.pool_idle_timeout {
            http_builder = http_builder.pool_idle_timeout(idle_timeout);
        }

        let http = http_builder.build().map_err(|e| Error::Config {
            reason: format!("failed to build HTTP client: {e}"),
        })?;

        let rate_limiter = self.rate_limit.map(|rps| Arc::new(RateLimiter::new(rps)));

        Ok(Client {
            base_url,
            http,
            token,
            credentials,
            auto_reauth: self.auto_reauth,
            retry_policy: self.retry_policy,
            rate_limiter,
        })
    }
}