dns-update 0.4.1

Dynamic DNS update (RFC 2136 and cloud) library for Rust
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
/*
 * Copyright Stalwart Labs LLC See the COPYING
 * file at the top-level directory of this distribution.
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */

use crate::{
    DnsRecord, DnsRecordType, Error, IntoFqdn, crypto::hmac_sha1, http::HttpClientBuilder,
};
use base64::{Engine, engine::general_purpose::STANDARD as BASE64_STANDARD};
use chrono::Utc;
use quick_xml::se::to_string as xml_to_string;
use serde::{Deserialize, Serialize};
use std::time::Duration;

const DEFAULT_ENDPOINT: &str = "https://dns.api.nifcloud.com";
const API_VERSION: &str = "2012-12-12N2013-12-16";
const XMLNS: &str = "https://route53.amazonaws.com/doc/2012-12-12/";

#[derive(Clone)]
pub struct NifcloudProvider {
    client: HttpClientBuilder,
    access_key: String,
    secret_key: String,
    endpoint: String,
}

#[derive(Serialize, Debug)]
#[serde(rename = "ChangeResourceRecordSetsRequest")]
struct ChangeRequest {
    #[serde(rename = "@xmlns")]
    xmlns: &'static str,
    #[serde(rename = "ChangeBatch")]
    change_batch: ChangeBatch,
}

#[derive(Serialize, Debug)]
struct ChangeBatch {
    #[serde(rename = "Comment")]
    comment: String,
    #[serde(rename = "Changes")]
    changes: Changes,
}

#[derive(Serialize, Debug)]
struct Changes {
    #[serde(rename = "Change")]
    change: Vec<Change>,
}

#[derive(Serialize, Debug)]
struct Change {
    #[serde(rename = "Action")]
    action: &'static str,
    #[serde(rename = "ResourceRecordSet")]
    resource_record_set: ResourceRecordSet,
}

#[derive(Serialize, Debug)]
struct ResourceRecordSet {
    #[serde(rename = "Name")]
    name: String,
    #[serde(rename = "Type")]
    record_type: &'static str,
    #[serde(rename = "TTL")]
    ttl: u32,
    #[serde(rename = "ResourceRecords")]
    resource_records: ResourceRecords,
}

#[derive(Serialize, Debug)]
struct ResourceRecords {
    #[serde(rename = "ResourceRecord")]
    resource_record: Vec<ResourceRecord>,
}

#[derive(Serialize, Debug)]
struct ResourceRecord {
    #[serde(rename = "Value")]
    value: String,
}

#[derive(Deserialize, Debug)]
struct ChangeResponse {
    #[serde(rename = "ChangeInfo")]
    #[allow(dead_code)]
    change_info: ChangeInfo,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct ChangeInfo {
    #[serde(rename = "Id")]
    id: String,
}

#[derive(Deserialize, Debug)]
struct ErrorResponse {
    #[serde(rename = "Error", default)]
    error: NifcloudError,
}

#[derive(Deserialize, Debug, Default)]
struct NifcloudError {
    #[serde(rename = "Code", default)]
    code: String,
    #[serde(rename = "Message", default)]
    message: String,
}

impl NifcloudProvider {
    pub(crate) fn new(
        access_key: impl AsRef<str>,
        secret_key: impl AsRef<str>,
        timeout: Option<Duration>,
    ) -> crate::Result<Self> {
        let access_key = access_key.as_ref();
        let secret_key = secret_key.as_ref();
        if access_key.is_empty() || secret_key.is_empty() {
            return Err(Error::Api("Nifcloud credentials missing".into()));
        }
        let client = HttpClientBuilder::default()
            .with_header("Accept", "application/xml")
            .with_timeout(timeout);
        Ok(Self {
            client,
            access_key: access_key.to_string(),
            secret_key: secret_key.to_string(),
            endpoint: DEFAULT_ENDPOINT.to_string(),
        })
    }

    #[cfg(test)]
    pub(crate) fn with_endpoint(self, endpoint: impl AsRef<str>) -> Self {
        Self {
            endpoint: endpoint.as_ref().to_string(),
            ..self
        }
    }

    fn signed(&self, request: crate::http::HttpClient) -> crate::http::HttpClient {
        let date = Utc::now().format("%a, %d %b %Y %H:%M:%S GMT").to_string();
        let mac = hmac_sha1(self.secret_key.as_bytes(), date.as_bytes());
        let signature = BASE64_STANDARD.encode(&mac);
        let auth = format!(
            "NIFTY3-HTTPS NiftyAccessKeyId={},Algorithm=HmacSHA1,Signature={}",
            self.access_key, signature
        );
        request
            .with_header("Date", date)
            .with_header("X-Nifty-Authorization", auth)
            .with_header("Content-Type", "text/xml; charset=utf-8")
    }

    pub(crate) async fn create(
        &self,
        name: impl IntoFqdn<'_>,
        record: DnsRecord,
        ttl: u32,
        origin: impl IntoFqdn<'_>,
    ) -> crate::Result<()> {
        self.change_record("CREATE", name, record, ttl, origin).await
    }

    pub(crate) async fn update(
        &self,
        name: impl IntoFqdn<'_>,
        record: DnsRecord,
        ttl: u32,
        origin: impl IntoFqdn<'_>,
    ) -> crate::Result<()> {
        let original_value = build_value(&record)?;
        let original_type = dns_type(&record)?;
        let original_ttl = ttl;
        let name_fqdn = name.into_fqdn().to_string();
        let domain = origin.into_name();
        let subdomain_name =
            normalized_record_name(name_fqdn.trim_end_matches('.'), &domain);

        let delete_set = ResourceRecordSet {
            name: subdomain_name.clone(),
            record_type: original_type,
            ttl: original_ttl,
            resource_records: ResourceRecords {
                resource_record: vec![ResourceRecord {
                    value: original_value.clone(),
                }],
            },
        };

        let create_set = ResourceRecordSet {
            name: subdomain_name,
            record_type: original_type,
            ttl: original_ttl,
            resource_records: ResourceRecords {
                resource_record: vec![ResourceRecord {
                    value: original_value,
                }],
            },
        };

        let _ = self
            .send_change(
                &domain,
                ChangeRequest {
                    xmlns: XMLNS,
                    change_batch: ChangeBatch {
                        comment: "Managed by dns-update".into(),
                        changes: Changes {
                            change: vec![Change {
                                action: "DELETE",
                                resource_record_set: delete_set,
                            }],
                        },
                    },
                },
            )
            .await;

        self.send_change(
            &domain,
            ChangeRequest {
                xmlns: XMLNS,
                change_batch: ChangeBatch {
                    comment: "Managed by dns-update".into(),
                    changes: Changes {
                        change: vec![Change {
                            action: "CREATE",
                            resource_record_set: create_set,
                        }],
                    },
                },
            },
        )
        .await
        .map(|_| ())
    }

    pub(crate) async fn delete(
        &self,
        name: impl IntoFqdn<'_>,
        origin: impl IntoFqdn<'_>,
        record_type: DnsRecordType,
    ) -> crate::Result<()> {
        let name_str = name.into_name().to_string();
        let domain = origin.into_name();
        let subdomain_name = normalized_record_name(&name_str, &domain);
        let type_str = match record_type {
            DnsRecordType::A => "A",
            DnsRecordType::AAAA => "AAAA",
            DnsRecordType::CNAME => "CNAME",
            DnsRecordType::NS => "NS",
            DnsRecordType::MX => "MX",
            DnsRecordType::TXT => "TXT",
            DnsRecordType::SRV => "SRV",
            DnsRecordType::CAA => {
                return Err(Error::Api("CAA records are not supported by Nifcloud".into()));
            }
            DnsRecordType::TLSA => {
                return Err(Error::Api("TLSA records are not supported by Nifcloud".into()));
            }
        };
        let delete_set = ResourceRecordSet {
            name: subdomain_name,
            record_type: type_str,
            ttl: 0,
            resource_records: ResourceRecords {
                resource_record: vec![ResourceRecord {
                    value: String::new(),
                }],
            },
        };
        self.send_change(
            &domain,
            ChangeRequest {
                xmlns: XMLNS,
                change_batch: ChangeBatch {
                    comment: "Managed by dns-update".into(),
                    changes: Changes {
                        change: vec![Change {
                            action: "DELETE",
                            resource_record_set: delete_set,
                        }],
                    },
                },
            },
        )
        .await
        .map(|_| ())
    }

    async fn change_record(
        &self,
        action: &'static str,
        name: impl IntoFqdn<'_>,
        record: DnsRecord,
        ttl: u32,
        origin: impl IntoFqdn<'_>,
    ) -> crate::Result<()> {
        let name_str = name.into_name().to_string();
        let domain = origin.into_name();
        let subdomain_name = normalized_record_name(&name_str, &domain);
        let value = build_value(&record)?;
        let record_type = dns_type(&record)?;

        let body = ChangeRequest {
            xmlns: XMLNS,
            change_batch: ChangeBatch {
                comment: "Managed by dns-update".into(),
                changes: Changes {
                    change: vec![Change {
                        action,
                        resource_record_set: ResourceRecordSet {
                            name: subdomain_name,
                            record_type,
                            ttl,
                            resource_records: ResourceRecords {
                                resource_record: vec![ResourceRecord { value }],
                            },
                        },
                    }],
                },
            },
        };
        self.send_change(&domain, body).await.map(|_| ())
    }

    async fn send_change(&self, domain: &str, body: ChangeRequest) -> crate::Result<String> {
        let xml_body = xml_to_string(&body)
            .map_err(|e| Error::Serialize(format!("XML serialization failed: {e}")))?;
        let payload = format!("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n{}", xml_body);
        let url = format!(
            "{}/{}/hostedzone/{}/rrset",
            self.endpoint, API_VERSION, domain
        );
        let response = self
            .signed(self.client.post(url).with_raw_body(payload))
            .send_raw()
            .await?;
        if response.contains("<Error>") {
            let parsed: Result<ErrorResponse, _> = quick_xml::de::from_str(&response);
            if let Ok(err) = parsed {
                return Err(Error::Api(format!(
                    "Nifcloud error {}: {}",
                    err.error.code, err.error.message
                )));
            }
            return Err(Error::Api(format!("Nifcloud error response: {response}")));
        }
        let _info: ChangeResponse = quick_xml::de::from_str(&response)
            .map_err(|e| Error::Serialize(format!("XML deserialization failed: {e}")))?;
        Ok(response)
    }
}

fn normalized_record_name(name: &str, domain: &str) -> String {
    let unfqdn = name.trim_end_matches('.');
    let domain = domain.trim_end_matches('.');
    if unfqdn == domain {
        "@".to_string()
    } else {
        unfqdn.to_string()
    }
}

fn dns_type(record: &DnsRecord) -> crate::Result<&'static str> {
    match record {
        DnsRecord::A(_) => Ok("A"),
        DnsRecord::AAAA(_) => Ok("AAAA"),
        DnsRecord::CNAME(_) => Ok("CNAME"),
        DnsRecord::NS(_) => Ok("NS"),
        DnsRecord::MX(_) => Ok("MX"),
        DnsRecord::TXT(_) => Ok("TXT"),
        DnsRecord::SRV(_) => Ok("SRV"),
        DnsRecord::CAA(_) => Err(Error::Api("CAA records are not supported by Nifcloud".into())),
        DnsRecord::TLSA(_) => Err(Error::Api(
            "TLSA records are not supported by Nifcloud".into(),
        )),
    }
}

fn build_value(record: &DnsRecord) -> crate::Result<String> {
    Ok(match record {
        DnsRecord::A(addr) => addr.to_string(),
        DnsRecord::AAAA(addr) => addr.to_string(),
        DnsRecord::CNAME(target) => target.clone(),
        DnsRecord::NS(target) => target.clone(),
        DnsRecord::MX(mx) => format!("{} {}", mx.priority, mx.exchange),
        DnsRecord::TXT(text) => format!("\"{}\"", text.replace('\"', "\\\"")),
        DnsRecord::SRV(srv) => format!(
            "{} {} {} {}",
            srv.priority, srv.weight, srv.port, srv.target
        ),
        DnsRecord::CAA(_) => {
            return Err(Error::Api("CAA records are not supported by Nifcloud".into()));
        }
        DnsRecord::TLSA(_) => {
            return Err(Error::Api(
                "TLSA records are not supported by Nifcloud".into(),
            ));
        }
    })
}