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
622
623
624
#![deny(missing_docs)]
use serde::Deserialize;
use serde_json::json;
pub mod strongbox;
pub mod volga;
#[cfg(feature = "utilities")]
pub mod utilities;
#[cfg(feature = "login-helper")]
pub mod login_helper;
#[derive(Debug, Deserialize)]
pub struct RESTError {
#[serde(rename = "error-message")]
pub error_message: String,
#[serde(rename = "error-info")]
pub error_info: serde_json::Value,
}
#[derive(Debug, Deserialize)]
pub struct RESTErrorList {
pub errors: Vec<RESTError>,
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Login failed: {0}")]
LoginFailure(String),
#[error("Login failure, missing environment variable '{0}'")]
LoginFailureMissingEnv(String),
#[error("HTTP failed {0}, {1}")]
WebServer(u16, String),
#[error("Websocket error: {0}")]
WebSocket(#[from] tokio_tungstenite::tungstenite::Error),
#[error("Serde JSON error: {0}")]
Serde(#[from] serde_json::Error),
#[error("URL: {0}")]
URL(#[from] url::ParseError),
#[error("Reqwest: {0}")]
HTTPClient(#[from] reqwest::Error),
#[error("Error from Volga {0:?}")]
Volga(Option<String>),
#[error("API Error {0:?}")]
API(String),
#[error("REST error {0:?}")]
REST(RESTErrorList),
#[error("TLS error {0}")]
TLS(#[from] tokio_native_tls::native_tls::Error),
#[error("IO error {0}")]
IO(#[from] std::io::Error),
#[error("Error {0}")]
General(String),
}
impl Error {
pub fn general(err: &str) -> Self {
Self::General(err.to_string())
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Deserialize)]
pub(crate) struct LoginToken {
pub token: String,
expires_in: Option<i64>,
pub creation_time: Option<chrono::DateTime<chrono::offset::FixedOffset>>,
}
impl std::fmt::Debug for LoginToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LoginToken")
.field("expires_in", &self.expires_in)
.field("creation_time", &self.creation_time)
.finish()
}
}
#[derive(Debug)]
struct ClientState {
login_token: LoginToken,
}
#[derive(Clone)]
pub struct ClientBuilder {
reqwest_ca: Vec<reqwest::Certificate>,
tls_ca: Vec<tokio_native_tls::native_tls::Certificate>,
disable_hostname_check: bool,
disable_cert_verification: bool,
}
impl ClientBuilder {
pub fn new() -> Self {
Self {
reqwest_ca: Vec::new(),
tls_ca: Vec::new(),
disable_cert_verification: false,
disable_hostname_check: false,
}
}
pub fn add_root_certificate(mut self, cert: &[u8]) -> Result<Self> {
let r_ca = reqwest::Certificate::from_pem(cert)?;
let t_ca = tokio_native_tls::native_tls::Certificate::from_pem(cert)?;
self.reqwest_ca.push(r_ca);
self.tls_ca.push(t_ca);
Ok(self)
}
pub fn danger_accept_invalid_certs(self) -> Self {
Self {
disable_cert_verification: true,
..self
}
}
pub fn danger_accept_invalid_hostnames(self) -> Self {
Self {
disable_hostname_check: true,
..self
}
}
pub async fn application_login(&self, host: &str, approle_id: Option<&str>) -> Result<Client> {
let secret_id = std::env::var("APPROLE_SECRET_ID")
.map_err(|_| Error::LoginFailureMissingEnv(String::from("APPROLE_SECRET_ID")))?;
let role_id = approle_id.unwrap_or(&secret_id);
let base_url = url::Url::parse(host)?;
let url = base_url.join("v1/approle-login")?;
let data = json!({
"role-id": role_id,
"secret-id": secret_id,
});
Client::do_login(self, base_url, url, data).await
}
pub async fn login(&self, host: &str, username: &str, password: &str) -> Result<Client> {
let base_url = url::Url::parse(host)?;
let url = base_url.join("v1/login")?;
let data = json!({
"username":username,
"password":password
});
Client::do_login(self, base_url, url, data).await
}
}
impl Default for ClientBuilder {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone)]
pub struct Client {
base_url: url::Url,
websocket_url: url::Url,
state: std::sync::Arc<tokio::sync::Mutex<ClientState>>,
client: reqwest::Client,
tls_ca: Vec<tokio_native_tls::native_tls::Certificate>,
disable_hostname_check: bool,
disable_cert_verification: bool,
}
impl std::fmt::Debug for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client")
.field("base_url", &self.base_url)
.field("websocket_url", &self.websocket_url)
.field("state", &self.state)
.field("client", &self.client)
.field("disable_hostname_check", &self.disable_hostname_check)
.field("disable_cert_verification", &self.disable_cert_verification)
.finish()
}
}
impl Client {
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
async fn do_login(
builder: &ClientBuilder,
base_url: url::Url,
url: url::Url,
payload: serde_json::Value,
) -> Result<Self> {
let json = serde_json::to_string(&payload)?;
let client = reqwest::Client::builder();
let client = builder
.reqwest_ca
.iter()
.fold(client, |client, ca| client.add_root_certificate(ca.clone()));
let client = client.danger_accept_invalid_certs(builder.disable_cert_verification);
let client = client.build()?;
let result = client
.post(url)
.header("content-type", "application/json")
.body(json)
.send()
.await?;
if result.status().is_success() {
let text = result.text().await?;
let login_token = serde_json::from_str::<LoginToken>(&text)?;
Self::new(builder, client, base_url, login_token)
} else {
let text = result.text().await?;
tracing::debug!("login returned {}", text);
Err(Error::LoginFailure(text))
}
}
fn new(
builder: &ClientBuilder,
client: reqwest::Client,
base_url: url::Url,
login_token: LoginToken,
) -> Result<Self> {
let websocket_url = url::Url::parse(&format!("wss://{}/v1/ws/", base_url.host_port()?))?;
let state = ClientState { login_token };
Ok(Self {
client,
tls_ca: builder.tls_ca.clone(),
disable_cert_verification: builder.disable_cert_verification,
disable_hostname_check: builder.disable_hostname_check,
base_url,
websocket_url,
state: std::sync::Arc::new(tokio::sync::Mutex::new(state)),
})
}
pub async fn bearer_token(&self) -> String {
let state = self.state.lock().await;
state.login_token.token.clone()
}
pub async fn get_json<T: serde::de::DeserializeOwned>(
&self,
path: &str,
query_params: Option<&[(&str, &str)]>,
) -> Result<T> {
let url = self.base_url.join(path)?;
let token = self.state.lock().await.login_token.token.clone();
let mut builder = self
.client
.get(url)
.bearer_auth(&token)
.header("Accept", "application/json");
if let Some(qp) = query_params {
builder = builder.query(qp);
}
let result = builder.send().await?;
if result.status().is_success() {
let res = result.json().await?;
Ok(res)
} else {
Err(Error::WebServer(
result.status().as_u16(),
result.status().to_string(),
))
}
}
pub async fn post_json(
&self,
path: &str,
data: &serde_json::Value,
) -> Result<serde_json::Value> {
let url = self.base_url.join(path)?;
let token = self.state.lock().await.login_token.token.clone();
tracing::debug!("POST {} {:?}", url, data);
let result = self
.client
.post(url)
.json(&data)
.bearer_auth(&token)
.send()
.await?;
if result.status().is_success() {
let resp = result.bytes().await?;
let mut responses: Vec<serde_json::Value> = Vec::new();
let decoder = serde_json::Deserializer::from_slice(&resp);
for v in decoder.into_iter() {
responses.push(v?);
}
match responses.len() {
0 => Ok(serde_json::Value::Object(Default::default())),
1 => Ok(responses.into_iter().next().unwrap()),
_ => {
Ok(serde_json::Value::Array(responses))
}
}
} else {
tracing::error!("POST call failed");
let status = result.status();
let resp = result.json().await;
match resp {
Ok(resp) => Err(Error::REST(resp)),
Err(_) => Err(Error::WebServer(status.as_u16(), status.to_string())),
}
}
}
pub async fn put_json(
&self,
path: &str,
data: &serde_json::Value,
) -> Result<serde_json::Value> {
let url = self.base_url.join(path)?;
let token = self.state.lock().await.login_token.token.clone();
tracing::debug!("PUT {} {:?}", url, data);
let result = self
.client
.put(url)
.json(&data)
.bearer_auth(&token)
.send()
.await?;
if result.status().is_success() {
use std::error::Error;
let resp = result.json().await.or_else(|e| match e {
e if e.is_decode() => {
match e
.source()
.map(|e| e.downcast_ref::<serde_json::Error>())
.flatten()
{
Some(e) if e.is_eof() => {
Ok(serde_json::Value::Object(serde_json::Map::new()))
}
_ => Err(e),
}
}
e => Err(e),
})?;
Ok(resp)
} else {
tracing::error!("PUT call failed");
let status = result.status();
let resp = result.json().await;
match resp {
Ok(resp) => Err(Error::REST(resp)),
Err(_) => Err(Error::WebServer(status.as_u16(), status.to_string())),
}
}
}
pub fn get_client(&self) -> reqwest::Client {
self.client.clone()
}
pub async fn volga_open_producer(
&self,
producer_name: &str,
topic: &str,
options: volga::Options,
) -> Result<volga::Producer> {
crate::volga::ProducerBuilder::new(self, producer_name, topic, options)?
.set_options(options)
.connect()
.await
}
pub async fn volga_open_nat_producer(
&self,
producer_name: &str,
topic: &str,
site: &str,
options: volga::Options,
) -> Result<volga::Producer> {
crate::volga::ProducerBuilder::new_nat(self, producer_name, topic, site, options)?
.set_options(options)
.connect()
.await
}
pub async fn volga_open_consumer(
&self,
consumer_name: &str,
topic: &str,
options: crate::volga::ConsumerOptions,
) -> Result<volga::Consumer> {
crate::volga::ConsumerBuilder::new(self, consumer_name, topic)?
.set_options(options)
.connect()
.await
}
pub async fn volga_open_nat_consumer(
&self,
consumer_name: &str,
topic: &str,
site: &str,
options: crate::volga::ConsumerOptions,
) -> Result<volga::Consumer> {
crate::volga::ConsumerBuilder::new_nat(self, consumer_name, topic, site)?
.set_options(options)
.connect()
.await
}
pub(crate) async fn open_tls_stream(
&self,
) -> Result<tokio_native_tls::TlsStream<tokio::net::TcpStream>> {
let mut connector = tokio_native_tls::native_tls::TlsConnector::builder();
self.tls_ca.iter().for_each(|ca| {
connector.add_root_certificate(ca.clone());
});
connector
.danger_accept_invalid_hostnames(self.disable_hostname_check)
.danger_accept_invalid_certs(self.disable_cert_verification);
let connector = connector.build()?;
let connector: tokio_native_tls::TlsConnector = connector.into();
let addrs = self.websocket_url.socket_addrs(|| None)?;
let stream = tokio::net::TcpStream::connect(&*addrs).await?;
let stream = connector.connect("192.168.8.11:4646", stream).await?;
Ok(stream)
}
pub async fn volga_open_log_query(&self, query: &volga::Query) -> Result<volga::QueryStream> {
volga::QueryStream::new(self, query).await
}
pub async fn open_strongbox_vault(&self, vault: &str) -> Result<strongbox::Vault> {
strongbox::Vault::open(self, vault).await
}
}
pub(crate) trait URLExt {
fn host_port(&self) -> std::result::Result<String, url::ParseError>;
}
impl URLExt for url::Url {
fn host_port(&self) -> std::result::Result<String, url::ParseError> {
let host = self.host_str().ok_or(url::ParseError::EmptyHost)?;
Ok(match (host, self.port()) {
(host, Some(port)) => format!("{}:{}", host, port),
(host, _) => host.to_string(),
})
}
}
#[cfg(test)]
mod test {
#[test]
fn url_ext() {
use super::URLExt;
let url = url::Url::parse("https://1.2.3.4:5000/a/b/c").unwrap();
let host_port = url.host_port().unwrap();
assert_eq!(&host_port, "1.2.3.4:5000");
let url = url::Url::parse("https://1.2.3.4/a/b/c").unwrap();
let host_port = url.host_port().unwrap();
assert_eq!(&host_port, "1.2.3.4");
let url = url::Url::parse("https://www.avassa.com/a/b/c").unwrap();
let host_port = url.host_port().unwrap();
assert_eq!(&host_port, "www.avassa.com");
let url = url::Url::parse("https://www.avassa.com:1234/a/b/c").unwrap();
let host_port = url.host_port().unwrap();
assert_eq!(&host_port, "www.avassa.com:1234");
}
}