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
|
use crate::error::{AppError, AppResult};
use crate::ip_service::IpServiceProvider::{IdentMe, Noop};
use http::StatusCode;
use reqwest::{Client, Url};
use serde::{Deserialize, Serialize};
use serde_with::DisplayFromStr;
use serde_with::serde_as;
use std::net::{IpAddr, Ipv4Addr};
use std::str::FromStr;
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type")]
pub enum IpServiceProvider {
#[serde(rename = "IDENTME")]
IdentMe(IdentMeConfig),
#[serde(rename = "NOOP")]
Noop,
}
impl IpService for IpServiceProvider {
async fn resolve(&self, client: &Client) -> AppResult<IpAddr> {
match self {
IdentMe(ident_me) => ident_me.resolve(client).await,
Noop => Ok(IpAddr::V4(Ipv4Addr::UNSPECIFIED)),
}
}
}
impl Default for IpServiceProvider {
fn default() -> Self {
IdentMe(IdentMeConfig::default())
}
}
pub trait IpService {
async fn resolve(&self, client: &Client) -> AppResult<IpAddr>;
}
#[serde_as]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct IdentMeConfig {
#[serde_as(as = "DisplayFromStr")]
url: Url,
}
impl IdentMeConfig {
fn convert_string_to_ip_address(input: String, url: &Url) -> AppResult<IpAddr> {
IpAddr::from_str(&input).map_err(|e| AppError::InvalidResponse {
url: url.clone(),
reason: format!(
"Failed to parse service response [{}] into valid ip address: {}",
input, e
),
})
}
fn request_failed(&self, e: reqwest::Error) -> AppError {
AppError::RequestFailed {
url: self.url.clone(),
source: e,
}
}
fn invalid_status_code(&self, status: StatusCode) -> AppError {
AppError::InvalidResponse {
url: self.url.clone(),
reason: format!("Status code: {}", status),
}
}
fn missing_text_response(&self, e: reqwest::Error) -> AppError {
AppError::InvalidResponse {
url: self.url.clone(),
reason: format!("Unable to get text from service response: {}", e),
}
}
}
impl Default for IdentMeConfig {
fn default() -> Self {
Self {
url: Url::parse("https://v4.ident.me/").unwrap(),
}
}
}
impl IpService for IdentMeConfig {
async fn resolve(&self, client: &Client) -> AppResult<IpAddr> {
let response = client
.get(self.url.clone())
.send()
.await
.map_err(|e| self.request_failed(e))?;
if !response.status().is_success() {
return Err(self.invalid_status_code(response.status()));
};
let response_text = response.text().await;
match response_text {
Ok(text) => Self::convert_string_to_ip_address(text, &self.url),
Err(e) => Err(self.missing_text_response(e)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{assert_error, assert_invalid_response, assert_request_failed};
use reqwest::ClientBuilder;
use std::error::Error;
use std::time::Duration;
use wiremock::matchers::method;
use wiremock::{Mock, MockServer, Respond, ResponseTemplate};
trait HasUrl {
fn url(&self) -> Url;
}
impl HasUrl for MockServer {
fn url(&self) -> Url {
Url::from_str(self.uri().as_str()).unwrap()
}
}
async fn setup_ipv4_service(response: impl Respond + 'static) -> MockServer {
let service = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(response)
.mount(&service)
.await;
service
}
fn plaintext_response(result: String) -> impl Respond + 'static {
ResponseTemplate::new(200)
.insert_header("Content-Type", "text/plain; charset=utf-8")
.set_body_string(result)
}
fn empty_response() -> impl Respond + 'static {
ResponseTemplate::new(204)
}
fn delayed_response(delay: u64) -> impl Respond + 'static {
ResponseTemplate::new(204).set_delay(Duration::from_millis(delay))
}
fn server_error() -> impl Respond + 'static {
ResponseTemplate::new(500)
}
#[tokio::test]
async fn successful_ipv4_address_resolution() -> Result<(), Box<dyn Error>> {
let expected = IpAddr::from_str("17.5.7.8")?;
let input = plaintext_response(expected.to_string());
let (ip_service, actual) = run_identme(input).await?;
assert_eq!(1, ip_service.received_requests().await.unwrap().len());
assert_eq!(actual?, expected);
Ok(())
}
#[tokio::test]
async fn failed_no_reachable_server() -> Result<(), Box<dyn Error>> {
let client = ClientBuilder::new().build()?;
let url = Url::from_str("http://localhost:8765/path")?;
let service = IdentMeConfig { url: url.clone() };
let actual = IdentMe(service).resolve(&client).await;
assert_request_failed!(actual, url);
Ok(())
}
#[tokio::test]
async fn failed_status_code() -> Result<(), Box<dyn Error>> {
let input = server_error();
let (ip_service, actual) = run_identme(input).await?;
assert_eq!(1, ip_service.received_requests().await.unwrap().len());
assert_invalid_response!(
actual,
ip_service.url(),
"Status code: 500 Internal Server Error"
);
Ok(())
}
#[tokio::test]
async fn failed_empty_response() -> Result<(), Box<dyn Error>> {
let input = empty_response();
let (ip_service, actual) = run_identme(input).await?;
assert_eq!(1, ip_service.received_requests().await.unwrap().len());
assert_invalid_response!(
actual,
ip_service.url(),
"Failed to parse service response [] into valid ip address"
);
Ok(())
}
#[tokio::test]
async fn failed_not_an_ip_address() -> Result<(), Box<dyn Error>> {
let input = plaintext_response("not-an-ip-address".to_string());
let (ip_service, actual) = run_identme(input).await?;
assert_eq!(1, ip_service.received_requests().await.unwrap().len());
assert_invalid_response!(
actual,
ip_service.url(),
"Failed to parse service response [not-an-ip-address] into valid ip address"
);
Ok(())
}
#[tokio::test]
async fn failed_timeout() -> Result<(), Box<dyn Error>> {
let input = delayed_response(200);
let (ip_service, actual) = run_identme(input).await?;
assert_eq!(1, ip_service.received_requests().await.unwrap().len());
assert_request_failed!(actual, ip_service.url());
Ok(())
}
async fn run_identme(
payload: impl Respond + 'static,
) -> Result<(MockServer, AppResult<IpAddr>), Box<dyn Error>> {
let ip_service = setup_ipv4_service(payload).await;
let client = ClientBuilder::new()
.timeout(Duration::from_millis(100))
.build()?;
let service = IdentMeConfig {
url: ip_service.uri().parse()?,
};
let actual = IdentMe(service).resolve(&client).await;
Ok((ip_service, actual))
}
}
|