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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
use crate::auth::ClientCertificate;
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
use crate::cert::CertificateValidation;
use crate::{
auth::Credentials,
error::Error,
http::{
headers::{
HeaderMap, HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE,
DEFAULT_ACCEPT, DEFAULT_CONTENT_TYPE, DEFAULT_USER_AGENT, USER_AGENT,
},
request::Body,
response::Response,
Method,
},
};
use base64::write::EncoderWriter as Base64Encoder;
use bytes::BytesMut;
use lazy_static::lazy_static;
use serde::Serialize;
use std::{
error, fmt,
fmt::Debug,
io::{self, Write},
time::Duration,
};
use url::Url;
#[derive(Debug)]
pub enum BuildError {
Io(io::Error),
Cert(reqwest::Error),
}
impl From<io::Error> for BuildError {
fn from(err: io::Error) -> BuildError {
BuildError::Io(err)
}
}
impl From<reqwest::Error> for BuildError {
fn from(err: reqwest::Error) -> BuildError {
BuildError::Cert(err)
}
}
impl error::Error for BuildError {
#[allow(warnings)]
fn description(&self) -> &str {
match *self {
BuildError::Io(ref err) => err.description(),
BuildError::Cert(ref err) => err.description(),
}
}
fn cause(&self) -> Option<&dyn error::Error> {
match *self {
BuildError::Io(ref err) => Some(err as &dyn error::Error),
BuildError::Cert(ref err) => Some(err as &dyn error::Error),
}
}
}
impl fmt::Display for BuildError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
BuildError::Io(ref err) => fmt::Display::fmt(err, f),
BuildError::Cert(ref err) => fmt::Display::fmt(err, f),
}
}
}
pub static DEFAULT_ADDRESS: &str = "http://localhost:9200";
lazy_static! {
static ref CLIENT_META: String = build_meta();
}
fn build_meta() -> String {
let mut version_parts = env!("CARGO_PKG_VERSION").split(&['.', '-'][..]);
let mut version = String::new();
version.push_str(version_parts.next().unwrap());
version.push('.');
version.push_str(version_parts.next().unwrap());
version.push('.');
version.push_str(version_parts.next().unwrap());
if version_parts.next().is_some() {
version.push('p');
}
let rustc = env!("RUSTC_VERSION");
let mut meta = format!("es={},rs={},t={}", version, rustc, version);
if cfg!(feature = "native-tls") {
meta.push_str(",tls=n");
} else if cfg!(feature = "rustls-tls") {
meta.push_str(",tls=r");
}
meta
}
pub struct TransportBuilder {
client_builder: reqwest::ClientBuilder,
conn_pool: Box<dyn ConnectionPool>,
credentials: Option<Credentials>,
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
cert_validation: Option<CertificateValidation>,
proxy: Option<Url>,
proxy_credentials: Option<Credentials>,
disable_proxy: bool,
headers: HeaderMap,
meta_header: bool,
timeout: Option<Duration>,
}
impl TransportBuilder {
pub fn new<P>(conn_pool: P) -> Self
where
P: ConnectionPool + Debug + Clone + Send + 'static,
{
Self {
client_builder: reqwest::ClientBuilder::new(),
conn_pool: Box::new(conn_pool),
credentials: None,
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
cert_validation: None,
proxy: None,
proxy_credentials: None,
disable_proxy: false,
headers: HeaderMap::new(),
meta_header: true,
timeout: None,
}
}
pub fn proxy(mut self, url: Url, username: Option<&str>, password: Option<&str>) -> Self {
self.proxy = Some(url);
if let Some(u) = username {
let p = password.unwrap_or("");
self.proxy_credentials = Some(Credentials::Basic(u.into(), p.into()));
}
self
}
pub fn disable_proxy(mut self) -> Self {
self.disable_proxy = true;
self
}
pub fn auth(mut self, credentials: Credentials) -> Self {
self.credentials = Some(credentials);
self
}
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
pub fn cert_validation(mut self, validation: CertificateValidation) -> Self {
self.cert_validation = Some(validation);
self
}
pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
self.headers.insert(key, value);
self
}
pub fn headers(mut self, headers: HeaderMap) -> Self {
for (key, value) in headers.iter() {
self.headers.insert(key, value.clone());
}
self
}
pub fn enable_meta_header(mut self, enable: bool) -> Self {
self.meta_header = enable;
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn build(self) -> Result<Transport, BuildError> {
let mut client_builder = self.client_builder;
if !self.headers.is_empty() {
client_builder = client_builder.default_headers(self.headers);
}
if let Some(t) = self.timeout {
client_builder = client_builder.timeout(t);
}
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
{
if let Some(creds) = &self.credentials {
if let Credentials::Certificate(cert) = creds {
client_builder = match cert {
#[cfg(feature = "native-tls")]
ClientCertificate::Pkcs12(b, p) => {
let password = match p {
Some(pass) => pass.as_str(),
None => "",
};
let pkcs12 = reqwest::Identity::from_pkcs12_der(b, password)?;
client_builder.identity(pkcs12)
}
#[cfg(feature = "rustls-tls")]
ClientCertificate::Pem(b) => {
let pem = reqwest::Identity::from_pem(b)?;
client_builder.identity(pem)
}
}
}
};
}
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
if let Some(v) = self.cert_validation {
client_builder = match v {
CertificateValidation::Default => client_builder,
CertificateValidation::Full(chain) => {
chain.into_iter().fold(client_builder, |client_builder, c| {
client_builder.add_root_certificate(c)
})
}
#[cfg(feature = "native-tls")]
CertificateValidation::Certificate(chain) => chain
.into_iter()
.fold(client_builder, |client_builder, c| {
client_builder.add_root_certificate(c)
})
.danger_accept_invalid_hostnames(true),
CertificateValidation::None => client_builder.danger_accept_invalid_certs(true),
}
}
if self.disable_proxy {
client_builder = client_builder.no_proxy();
} else if let Some(url) = self.proxy {
let mut proxy = reqwest::Proxy::all(url)?;
if let Some(c) = self.proxy_credentials {
proxy = match c {
Credentials::Basic(u, p) => proxy.basic_auth(&u, &p),
_ => proxy,
};
}
client_builder = client_builder.proxy(proxy);
}
let client = client_builder.build()?;
Ok(Transport {
client,
conn_pool: self.conn_pool,
credentials: self.credentials,
send_meta: self.meta_header,
})
}
}
impl Default for TransportBuilder {
fn default() -> Self {
Self::new(SingleNodeConnectionPool::default())
}
}
#[derive(Debug, Clone)]
pub struct Connection {
url: Url,
}
impl Connection {
pub fn new(url: Url) -> Self {
let mut url = url;
if !url.path().ends_with('/') {
url.set_path(&format!("{}/", url.path()));
}
Self { url }
}
}
#[derive(Debug, Clone)]
pub struct Transport {
client: reqwest::Client,
credentials: Option<Credentials>,
conn_pool: Box<dyn ConnectionPool>,
send_meta: bool,
}
impl Transport {
fn method(&self, method: Method) -> reqwest::Method {
match method {
Method::Get => reqwest::Method::GET,
Method::Put => reqwest::Method::PUT,
Method::Post => reqwest::Method::POST,
Method::Delete => reqwest::Method::DELETE,
Method::Head => reqwest::Method::HEAD,
}
}
fn bytes_mut(&self) -> BytesMut {
BytesMut::with_capacity(1024)
}
pub fn single_node(url: &str) -> Result<Transport, Error> {
let u = Url::parse(url)?;
let conn_pool = SingleNodeConnectionPool::new(u);
let transport = TransportBuilder::new(conn_pool).build()?;
Ok(transport)
}
pub fn cloud(cloud_id: &str, credentials: Credentials) -> Result<Transport, Error> {
let conn_pool = CloudConnectionPool::new(cloud_id)?;
let transport = TransportBuilder::new(conn_pool).auth(credentials).build()?;
Ok(transport)
}
pub async fn send<B, Q>(
&self,
method: Method,
path: &str,
headers: HeaderMap,
query_string: Option<&Q>,
body: Option<B>,
timeout: Option<Duration>,
) -> Result<Response, Error>
where
B: Body,
Q: Serialize + ?Sized,
{
let connection = self.conn_pool.next();
let url = connection.url.join(path.trim_start_matches('/'))?;
let reqwest_method = self.method(method);
let mut request_builder = self.client.request(reqwest_method, url);
if let Some(t) = timeout {
request_builder = request_builder.timeout(t);
}
if let Some(c) = &self.credentials {
request_builder = match c {
Credentials::Basic(u, p) => request_builder.basic_auth(u, Some(p)),
Credentials::Bearer(t) => request_builder.bearer_auth(t),
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
Credentials::Certificate(_) => request_builder,
Credentials::ApiKey(i, k) => {
let mut header_value = b"ApiKey ".to_vec();
{
let mut encoder = Base64Encoder::new(&mut header_value, base64::STANDARD);
write!(encoder, "{}:", i).unwrap();
write!(encoder, "{}", k).unwrap();
}
request_builder.header(
AUTHORIZATION,
HeaderValue::from_bytes(&header_value).unwrap(),
)
}
}
}
let mut request_headers = HeaderMap::with_capacity(4 + headers.len());
request_headers.insert(CONTENT_TYPE, HeaderValue::from_static(DEFAULT_CONTENT_TYPE));
request_headers.insert(ACCEPT, HeaderValue::from_static(DEFAULT_ACCEPT));
request_headers.insert(USER_AGENT, HeaderValue::from_static(DEFAULT_USER_AGENT));
for (name, value) in headers {
request_headers.insert(name.unwrap(), value);
}
if self.send_meta {
request_headers.insert(
"x-elastic-client-meta",
HeaderValue::from_static(CLIENT_META.as_str()),
);
}
request_builder = request_builder.headers(request_headers);
if let Some(b) = body {
let bytes = if let Some(bytes) = b.bytes() {
bytes
} else {
let mut bytes_mut = self.bytes_mut();
b.write(&mut bytes_mut)?;
bytes_mut.split().freeze()
};
request_builder = request_builder.body(bytes);
};
if let Some(q) = query_string {
request_builder = request_builder.query(q);
}
let response = request_builder.send().await;
match response {
Ok(r) => Ok(Response::new(r, method)),
Err(e) => Err(e.into()),
}
}
}
impl Default for Transport {
fn default() -> Self {
TransportBuilder::default().build().unwrap()
}
}
pub trait ConnectionPool: Debug + dyn_clone::DynClone + Sync + Send {
fn next(&self) -> &Connection;
}
clone_trait_object!(ConnectionPool);
#[derive(Debug, Clone)]
pub struct SingleNodeConnectionPool {
connection: Connection,
}
impl SingleNodeConnectionPool {
pub fn new(url: Url) -> Self {
Self {
connection: Connection::new(url),
}
}
}
impl Default for SingleNodeConnectionPool {
fn default() -> Self {
Self::new(Url::parse(DEFAULT_ADDRESS).unwrap())
}
}
impl ConnectionPool for SingleNodeConnectionPool {
fn next(&self) -> &Connection {
&self.connection
}
}
#[derive(Debug, Clone)]
pub struct CloudId {
pub name: String,
pub url: Url,
}
impl CloudId {
pub fn parse(cloud_id: &str) -> Result<CloudId, Error> {
if cloud_id.is_empty() || !cloud_id.contains(':') {
return Err(crate::error::lib(
"cloud_id should be of the form '<cluster name>:<base64 data>'",
));
}
let parts: Vec<&str> = cloud_id.splitn(2, ':').collect();
let name: String = parts[0].into();
if name.is_empty() {
return Err(crate::error::lib("cloud_id cluster name cannot be empty"));
}
let data = parts[1];
let decoded_result = base64::decode(data);
if decoded_result.is_err() {
return Err(crate::error::lib(format!(
"cannot base 64 decode '{}'",
data
)));
}
let decoded = decoded_result.unwrap();
let mut decoded_parts = decoded.split(|&b| b == b'$');
let domain_name;
let uuid;
match decoded_parts.next() {
Some(p) => {
match std::str::from_utf8(p) {
Ok(s) => {
domain_name = s.trim();
if domain_name.is_empty() {
return Err(crate::error::lib("decoded '<base64 data>' must contain a domain name as the first part"));
}
}
Err(_) => {
return Err(crate::error::lib(
"decoded '<base64 data>' must contain a domain name as the first part",
))
}
}
}
None => {
return Err(crate::error::lib(
"decoded '<base64 data>' must contain a domain name as the first part",
));
}
}
match decoded_parts.next() {
Some(p) => match std::str::from_utf8(p) {
Ok(s) => {
uuid = s.trim();
if uuid.is_empty() {
return Err(crate::error::lib(
"decoded '<base64 data>' must contain a uuid as the second part",
));
}
}
Err(_) => {
return Err(crate::error::lib(
"decoded '<base64 data>' must contain a uuid as the second part",
))
}
},
None => {
return Err(crate::error::lib(
"decoded '<base64 data>' must contain at least two parts",
));
}
}
let url = Url::parse(format!("https://{}.{}", uuid, domain_name).as_ref())?;
Ok(CloudId { name, url })
}
}
#[derive(Debug, Clone)]
pub struct CloudConnectionPool {
cloud_id: CloudId,
connection: Connection,
}
impl CloudConnectionPool {
pub fn new(cloud_id: &str) -> Result<Self, Error> {
let cloud = CloudId::parse(cloud_id)?;
let connection = Connection::new(cloud.url.clone());
Ok(Self {
cloud_id: cloud,
connection,
})
}
}
impl ConnectionPool for CloudConnectionPool {
fn next(&self) -> &Connection {
&self.connection
}
}
#[cfg(test)]
pub mod tests {
use super::*;
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
use crate::auth::ClientCertificate;
use regex::Regex;
use url::Url;
#[test]
#[cfg(feature = "native-tls")]
fn invalid_pkcs12_cert_credentials() {
let conn_pool = SingleNodeConnectionPool::default();
let builder = TransportBuilder::new(conn_pool)
.auth(ClientCertificate::Pkcs12(b"Nonsense".to_vec(), None).into());
let res = builder.build();
assert!(res.is_err());
}
#[test]
#[cfg(feature = "rustls-tls")]
fn invalid_pem_cert_credentials() {
let conn_pool = SingleNodeConnectionPool::default();
let builder = TransportBuilder::new(conn_pool)
.auth(ClientCertificate::Pem(b"Nonsense".to_vec()).into());
let res = builder.build();
assert!(res.is_err());
}
#[test]
fn can_parse_cloud_id_with_kibana_uuid() {
let base64 = base64::encode("cloud-endpoint.example$3dadf823f05388497ea684236d918a1a$3f26e1609cf54a0f80137a80de560da4");
let cloud_id = format!("my_cluster:{}", base64);
let result = CloudId::parse(&cloud_id);
assert!(result.is_ok());
let cloud = result.unwrap();
assert_eq!("my_cluster", cloud.name);
assert_eq!(
Url::parse("https://3dadf823f05388497ea684236d918a1a.cloud-endpoint.example").unwrap(),
cloud.url
);
}
#[test]
fn can_parse_cloud_id_without_kibana_uuid() {
let base64 = base64::encode("cloud-endpoint.example$3dadf823f05388497ea684236d918a1a$");
let cloud_id = format!("my_cluster:{}", base64);
let result = CloudId::parse(&cloud_id);
assert!(result.is_ok());
let cloud = result.unwrap();
assert_eq!("my_cluster", cloud.name);
assert_eq!(
Url::parse("https://3dadf823f05388497ea684236d918a1a.cloud-endpoint.example").unwrap(),
cloud.url
);
}
#[test]
fn can_parse_cloud_id_with_different_port() {
let base64 = base64::encode("cloud-endpoint.example:4463$3dadf823f05388497ea684236d918a1a$3f26e1609cf54a0f80137a80de560da4");
let cloud_id = format!("my_cluster:{}", base64);
let result = CloudId::parse(&cloud_id);
assert!(result.is_ok());
let cloud = result.unwrap();
assert_eq!("my_cluster", cloud.name);
assert_eq!(
Url::parse("https://3dadf823f05388497ea684236d918a1a.cloud-endpoint.example:4463")
.unwrap(),
cloud.url
);
}
#[test]
fn cloud_id_must_contain_colon() {
let base64 = base64::encode("cloud-endpoint.example$3dadf823f05388497ea684236d918a1a$3f26e1609cf54a0f80137a80de560da4");
let cloud_id = format!("my_cluster{}", base64);
let cloud = CloudId::parse(&cloud_id);
assert!(cloud.is_err());
}
#[test]
fn cloud_id_second_part_must_be_base64() {
let cloud_id = "my_cluster:not_base_64";
let cloud = CloudId::parse(cloud_id);
assert!(cloud.is_err());
}
#[test]
fn cloud_id_first_part_cannot_be_empty() {
let base64 = base64::encode("cloud-endpoint.example$3dadf823f05388497ea684236d918a1a$3f26e1609cf54a0f80137a80de560da4");
let cloud_id = format!(":{}", base64);
let cloud = CloudId::parse(&cloud_id);
assert!(cloud.is_err());
}
#[test]
fn cloud_id_second_part_cannot_be_empty() {
let cloud_id = "cluster_name:";
let cloud = CloudId::parse(&cloud_id);
assert!(cloud.is_err());
}
#[test]
fn cloud_id_second_part_must_have_at_least_two_parts() {
let base64 = base64::encode("cloud-endpoint.example");
let cloud_id = format!("my_cluster:{}", base64);
let result = CloudId::parse(&cloud_id);
assert!(result.is_err());
}
#[test]
fn connection_url_with_no_trailing_slash() {
let url = Url::parse("http://10.1.2.3/path_with_no_trailing_slash").unwrap();
let conn = Connection::new(url);
assert_eq!(
conn.url.as_str(),
"http://10.1.2.3/path_with_no_trailing_slash/"
);
}
#[test]
fn connection_url_with_trailing_slash() {
let url = Url::parse("http://10.1.2.3/path_with_trailing_slash/").unwrap();
let conn = Connection::new(url);
assert_eq!(
conn.url.as_str(),
"http://10.1.2.3/path_with_trailing_slash/"
);
}
#[test]
fn connection_url_with_no_path_and_no_trailing_slash() {
let url = Url::parse("http://10.1.2.3").unwrap();
let conn = Connection::new(url);
assert_eq!(conn.url.as_str(), "http://10.1.2.3/");
}
#[test]
fn connection_url_with_no_path_and_trailing_slash() {
let url = Url::parse("http://10.1.2.3/").unwrap();
let conn = Connection::new(url);
assert_eq!(conn.url.as_str(), "http://10.1.2.3/");
}
#[test]
pub fn test_meta_header() {
let re = Regex::new(r"^es=[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}p?,rs=[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}p?,t=[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}p?(,tls=[rn])?$").unwrap();
let x: &str = CLIENT_META.as_str();
println!("{}", x);
assert!(re.is_match(x));
}
}