-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathcloudflare.rs
More file actions
235 lines (205 loc) · 6.87 KB
/
Copy pathcloudflare.rs
File metadata and controls
235 lines (205 loc) · 6.87 KB
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
// SPDX-FileCopyrightText: © 2024-2025 Phala Network <dstack@phala.network>
//
// SPDX-License-Identifier: Apache-2.0
use anyhow::{Context, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::dns01_client::Record;
use super::Dns01Api;
const CLOUDFLARE_API_URL: &str = "https://api.cloudflare.com/client/v4";
#[derive(Debug, Serialize, Deserialize)]
pub struct CloudflareClient {
zone_id: String,
api_token: String,
}
#[derive(Deserialize)]
struct Response {
result: ApiResult,
}
#[derive(Deserialize)]
struct ApiResult {
id: String,
}
impl CloudflareClient {
pub fn new(zone_id: String, api_token: String) -> Self {
Self { zone_id, api_token }
}
async fn add_record(&self, record: &impl Serialize) -> Result<Response> {
let client = Client::new();
let url = format!("{}/zones/{}/dns_records", CLOUDFLARE_API_URL, self.zone_id);
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", self.api_token))
.header("Content-Type", "application/json")
.json(&record)
.send()
.await
.context("failed to send add_record request")?;
if !response.status().is_success() {
anyhow::bail!("failed to add record: {}", response.text().await?);
}
let response = response.json().await.context("failed to parse response")?;
Ok(response)
}
}
impl Dns01Api for CloudflareClient {
async fn remove_record(&self, record_id: &str) -> Result<()> {
let client = Client::new();
let url = format!(
"{}/zones/{}/dns_records/{}",
CLOUDFLARE_API_URL, self.zone_id, record_id
);
let response = client
.delete(&url)
.header("Authorization", format!("Bearer {}", self.api_token))
.send()
.await?;
if !response.status().is_success() {
anyhow::bail!(
"failed to remove acme challenge: {}",
response.text().await?
);
}
Ok(())
}
async fn add_txt_record(&self, domain: &str, content: &str) -> Result<String> {
let response = self
.add_record(&json!({
"type": "TXT",
"name": domain,
"content": content,
}))
.await?;
Ok(response.result.id)
}
async fn add_caa_record(
&self,
domain: &str,
flags: u8,
tag: &str,
value: &str,
) -> Result<String> {
let response = self
.add_record(&json!({
"type": "CAA",
"name": domain,
"data": {
"flags": flags,
"tag": tag,
"value": value
}
}))
.await?;
Ok(response.result.id)
}
async fn get_records(&self, domain: &str) -> Result<Vec<Record>> {
let client = Client::new();
let url = format!("{}/zones/{}/dns_records", CLOUDFLARE_API_URL, self.zone_id);
let response = client
.get(&url)
.header("Authorization", format!("Bearer {}", self.api_token))
.send()
.await?;
if !response.status().is_success() {
anyhow::bail!("failed to get dns records: {}", response.text().await?);
}
#[derive(Deserialize, Debug)]
struct CloudflareResponse {
result: Vec<Record>,
}
let response: CloudflareResponse =
response.json().await.context("failed to parse response")?;
let records = response
.result
.into_iter()
.filter(|record| record.name == domain)
.collect();
Ok(records)
}
}
#[cfg(test)]
mod tests {
#![cfg(not(test))]
use super::*;
impl CloudflareClient {
#[cfg(test)]
async fn get_txt_records(&self, domain: &str) -> Result<Vec<Record>> {
Ok(self
.get_records(domain)
.await?
.into_iter()
.filter(|r| r.r#type == "TXT")
.collect())
}
#[cfg(test)]
async fn get_caa_records(&self, domain: &str) -> Result<Vec<Record>> {
Ok(self
.get_records(domain)
.await?
.into_iter()
.filter(|r| r.r#type == "CAA")
.collect())
}
}
fn create_client() -> CloudflareClient {
CloudflareClient::new(
std::env::var("CLOUDFLARE_ZONE_ID").expect("CLOUDFLARE_ZONE_ID not set"),
std::env::var("CLOUDFLARE_API_TOKEN").expect("CLOUDFLARE_API_TOKEN not set"),
)
}
fn random_subdomain() -> String {
format!(
"_acme-challenge.{}.{}",
rand::random::<u64>(),
std::env::var("TEST_DOMAIN").expect("TEST_DOMAIN not set"),
)
}
#[tokio::test]
async fn can_add_txt_record() {
let client = create_client();
let subdomain = random_subdomain();
println!("subdomain: {}", subdomain);
let record_id = client
.add_txt_record(&subdomain, "1234567890")
.await
.unwrap();
let record = client.get_txt_records(&subdomain).await.unwrap();
assert_eq!(record[0].id, record_id);
assert_eq!(record[0].content, "1234567890");
client.remove_record(&record_id).await.unwrap();
let record = client.get_txt_records(&subdomain).await.unwrap();
assert!(record.is_empty());
}
#[tokio::test]
async fn can_remove_txt_record() {
let client = create_client();
let subdomain = random_subdomain();
println!("subdomain: {}", subdomain);
let record_id = client
.add_txt_record(&subdomain, "1234567890")
.await
.unwrap();
let record = client.get_txt_records(&subdomain).await.unwrap();
assert_eq!(record[0].id, record_id);
assert_eq!(record[0].content, "1234567890");
client.remove_txt_records(&subdomain).await.unwrap();
let record = client.get_txt_records(&subdomain).await.unwrap();
assert!(record.is_empty());
}
#[tokio::test]
async fn can_add_caa_record() {
let client = create_client();
let subdomain = random_subdomain();
let record_id = client
.add_caa_record(&subdomain, 0, "issue", "letsencrypt.org;")
.await
.unwrap();
let record = client.get_caa_records(&subdomain).await.unwrap();
assert_eq!(record[0].id, record_id);
assert_eq!(record[0].content, "0 issue \"letsencrypt.org;\"");
client.remove_record(&record_id).await.unwrap();
let record = client.get_caa_records(&subdomain).await.unwrap();
assert!(record.is_empty());
}
}