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
//! [![Crates.io](https://img.shields.io/crates/l/tenable?label=license)](https://crates.io/crates/tenable)
//! [![Crates.io](https://img.shields.io/crates/v/tenable?label=version)](https://crates.io/crates/tenable)
//! [![Crates.io](https://img.shields.io/badge/docs-latest-blue.svg)](https://docs.rs/tenable)
//!
//! This is an API Abstraction for the [Tenable API](https://developer.tenable.com/reference).
//!
//! The API itself is far too big for one person to develop. That is the reason why this crate does not provide methods for all endpoints, but instead focuses on modularity and extensability. Instead of providing methods for all endpoints, this crate makes it as easy as possible for users to add their own endpoints and hopefully contribute them afterwards.
//!
//! # Usage
//!
//! Add this crate as a dependency to your `Cargo.toml`. Afterwards you can use it like this to execute api calls like fetching all assets:
//!
//! ## Sync
//!
//! ```rust,no_run
//! use std::convert::Infallible;
//! use reqwest::blocking::Client;
//! use tenable::{requests::AssetReq, Error, Response, Tenable};
//! use http::Request;
//!
//! pub fn request(req: Request<Vec<u8>>) -> Result<Response, Error<reqwest::Error>> {
//!     let (req, body) = req.into_parts();
//!     let res = Client::new()
//!         .request(req.method, &req.uri.to_string())
//!         .headers(req.headers)
//!         .body(body)
//!         .send()
//!         .map_err(Error::Request)?;
//!     Ok(Response {
//!         status: res.status(),
//!         body: res.bytes().map_err(Error::Request)?,
//!     })
//! }
//!
//! let tenable = Tenable::new(
//!     "0000000000000000000000000000000000000000000000000000000000000000",
//!     "0000000000000000000000000000000000000000000000000000000000000000",
//! );
//! let req = tenable.assets();
//! let _assets = Tenable::request(req, request).expect("Unable to list all assets");
//! ```
//!
//! # Async
//!
//! ```rust,no_run
//! # use tokio::runtime::Runtime;
//! use std::convert::Infallible;
//! use reqwest::Client;
//! use tenable::{requests::AssetReq, types::Assets, Error, Response, Tenable};
//! use http::Request;
//!
//! pub async fn request_async(req: Request<Vec<u8>>) -> Result<Response, Error<reqwest::Error>> {
//!    let (req, body) = req.into_parts();
//!    let res = Client::new()
//!        .request(req.method, &req.uri.to_string())
//!        .headers(req.headers)
//!        .body(body)
//!        .send()
//!        .await
//!        .map_err(Error::Request)?;
//!    Ok(Response {
//!        status: res.status(),
//!        body: res.bytes().await.map_err(Error::Request)?,
//!    })
//! }
//!
//! # let mut rt = Runtime::new().expect("Unable to create runtime");
//! # rt.block_on(async {
//! let tenable = Tenable::new(
//!     "0000000000000000000000000000000000000000000000000000000000000000",
//!     "0000000000000000000000000000000000000000000000000000000000000000",
//! );
//! let req = tenable.assets();
//! let _assets: Assets = Tenable::request_async(req, request_async).await
//!     .expect("Unable to list all assets");
//! # })
//! ```
//!
//! # Extending
//!
//! Extending the functionality is possible by creating a type that implements `HttpRequest`, which defines how a request looks like and how to handle the server response. The following shows how to do that using the `AssetsReq` type which handles the `/assets` endpoint:
//!
//! ```rust
//! use http::{header::HeaderValue, status::StatusCode, Method, Request};
//! use tenable::{
//!    types::Assets,
//!    Error, HttpRequest, Response, Tenable,
//! };
//! use std::fmt;
//!
//! #[derive(Clone, Debug)]
//! pub struct AssetsReq<'a> {
//!     pub tenable: &'a Tenable<'a>,
//! }
//!
//! impl<RE: fmt::Debug> HttpRequest<RE> for AssetsReq<'_> {
//!     // The final concret type returned on a successful call
//!     type Output = Assets;
//!
//!     #[inline]
//!     fn to_request(&self) -> Result<Request<Vec<u8>>, Error<RE>> {
//!         // Create a request...
//!         let req = Request::builder()
//!             // ...by specificing the endpoint...
//!             .uri(format!("{}/assets", self.tenable.uri))
//!             // ...the method...
//!             .method(Method::GET)
//!             // ...authorization...
//!             .header(
//!                 "X-ApiKeys",
//!                 HeaderValue::from_str(self.tenable.auth.as_ref())?,
//!             )
//!             // ...and more like required headers, form parameters, body...
//!             .header("Accept", HeaderValue::from_static("application/json"))
//!             .body(Vec::new())?;
//!         Ok(req)
//!     }
//!
//!     #[inline]
//!     fn from_response(&self, res: Response) -> Result<Self::Output, Error<RE>> {
//!         // Handles the server response
//!         match res.status {
//!             // When the call was successfull, continue with deserializing
//!             StatusCode::OK => Ok(serde_json::from_slice(&res.body)?),
//!             // Otherwise, check whether the server returned one of the known errors
//!             StatusCode::FORBIDDEN => Err(Error::InsufficientPermission),
//!             StatusCode::TOO_MANY_REQUESTS => Err(Error::RateLimitReached),
//!             // Every other error may be collected in catch all type
//!             code => Err(Error::UnexpectedStatusCode(code)),
//!         }
//!     }
//! }
//! ```
//!
//! To be able to directly use the type with the tenable struct, we can add a new trait and implement it for tenable
//!
//! ```rust
//! use tenable::{Tenable, types::AssetsReq};
//!
//! pub trait AssetReq {
//!     fn assets(&self) -> AssetsReq<'_>;
//! }
//!
//! impl AssetReq for Tenable<'_> {
//!     fn assets(&self) -> AssetsReq<'_> {
//!         AssetsReq { tenable: self }
//!     }
//! }
//! ```
//!
//! # License
//!
//! Licensed under either of
//!
//!  * Apache License, Version 2.0
//!    ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
//!  * MIT license
//!    ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
//!
//! at your option.
//!
//! # Contribution
//!
//! Unless you explicitly state otherwise, any contribution intentionally submitted
//! for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
//! dual licensed as above, without any additional terms or conditions.

#![forbid(unsafe_code)]
#![warn(
    absolute_paths_not_starting_with_crate,
    anonymous_parameters,
    box_pointers,
    deprecated_in_future,
    elided_lifetimes_in_paths,
    explicit_outlives_requirements,
    indirect_structural_match,
    keyword_idents,
    macro_use_extern_crate,
    meta_variable_misuse,
    missing_copy_implementations,
    missing_debug_implementations,
    missing_docs,
    missing_doc_code_examples,
    non_ascii_idents,
    single_use_lifetimes,
    trivial_casts,
    trivial_numeric_casts,
    unreachable_pub,
    unstable_features,
    unused_extern_crates,
    unused_import_braces,
    unused_lifetimes,
    unused_qualifications,
    unused_results,
    variant_size_differences
)]
#![warn(
    clippy::correctness,
    clippy::restriction,
    clippy::style,
    clippy::pedantic,
    clippy::complexity,
    clippy::perf,
    clippy::cargo,
    clippy::nursery
)]
#![allow(
    clippy::implicit_return,
    clippy::missing_docs_in_private_items,
    clippy::shadow_reuse,
    clippy::similar_names,
    clippy::else_if_without_else,
    clippy::multiple_crate_versions,
    clippy::module_name_repetitions,
    clippy::print_stdout,
    clippy::used_underscore_binding
)]

mod error;
pub mod requests;
pub mod types;

pub use error::Error;

use bytes::Bytes;
use http::{status::StatusCode, Request};
use std::{borrow::Cow, fmt, future::Future, time::Duration};

/// Tenable Client which allows requests against the tenable API
#[derive(Clone, Debug)]
pub struct Tenable<'a> {
    /// Authentication string
    pub auth: String,
    /// Uri to send requests against
    pub uri: Cow<'a, str>,
}

impl Tenable<'_> {
    /// Creates a new `Tenable` client with the given credentials
    ///
    /// # Arguments
    ///
    /// * `access_key`: Tenable User Access Key
    /// * `secret_key`: Tenable User Access Key
    ///
    /// # Example
    ///
    /// ```
    /// use tenable::Tenable;
    /// let tenable = Tenable::new(
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    ///     "0000000000000000000000000000000000000000000000000000000000000000"
    /// );
    /// ```
    #[must_use]
    #[inline]
    pub fn new(access_key: &str, secret_key: &str) -> Self {
        Tenable {
            auth: format!("accessKey={};secretKey={}", access_key, secret_key),
            uri: Cow::Borrowed("https://cloud.tenable.com"),
        }
    }

    /// Executes a synchronous http request using the given function
    ///
    /// # Arguments
    ///
    /// * `request`: Request to send. Use one of the functions in the `requests` module to create a request
    /// * `fun`: Function which implements sending synchronous requests.
    ///
    /// # Errors
    ///
    /// Fails in the following cases:
    ///
    /// * Unable to create a valid Request
    /// * Server responded with error code
    /// * Unable to deserialize the server response
    /// * Custom Errors returned by the function given as `fun` parameter
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::convert::Infallible;
    /// use tenable::{requests::AssetReq, Error, Response, Tenable};
    /// let tenable = Tenable::new(
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    /// );
    /// let req = tenable.assets();
    /// let _assets = Tenable::request(req, |_| {
    ///     Result::<Response, Error<Infallible>>::Ok(todo!("Define a method to send http requests"))
    /// }).expect("Unable to list all assets");
    /// ```
    #[inline]
    #[allow(single_use_lifetimes)]
    pub fn request<'a, O, R, CR, RE, F>(request: CR, fun: F) -> Result<O, Error<RE>>
    where
        CR: Into<Cow<'a, R>>,
        R: 'a + HttpRequest<RE, Output = O>,
        RE: fmt::Debug,
        F: FnOnce(Request<Vec<u8>>) -> Result<Response, Error<RE>>,
    {
        let request = request.into();
        let req = request.to_request()?;
        let res = fun(req)?;
        request.from_response(res)
    }

    /// Executes a synchronous http request using the given function.
    /// Automatically backs off when a Rate Limit is hit
    ///
    /// # Arguments
    ///
    /// * `request`: Request to send. Use one of the functions in the `requests` module to create a request
    /// * `fun`: Function which implements sending synchronous requests.
    /// * `backoff_fun`: Function which waits for the given Duration
    ///
    /// # Errors
    ///
    /// Fails in the following cases:
    ///
    /// * Unable to create a valid Request
    /// * Server responded with error code
    /// * Unable to deserialize the server response
    /// * Custom Errors returned by the function given as `fun` parameter
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::{convert::Infallible, thread::sleep};
    /// use tenable::{requests::AssetReq, Error, Response, Tenable};
    /// let tenable = Tenable::new(
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    /// );
    /// let req = tenable.assets();
    /// let _assets = Tenable::request_with_backoff(req, |_| {
    ///     Result::<Response, Error<Infallible>>::Ok(todo!("Define a method to send http requests"))
    /// }, sleep).expect("Unable to list all assets");
    /// ```
    #[inline]
    #[allow(single_use_lifetimes)]
    pub fn request_with_backoff<'a, O, R, CR, RE, F, BF>(
        request: CR,
        fun: F,
        backoff_fun: BF,
    ) -> Result<O, Error<RE>>
    where
        CR: Into<Cow<'a, R>>,
        R: 'a + HttpRequest<RE, Output = O>,
        RE: fmt::Debug,
        F: Fn(Request<Vec<u8>>) -> Result<Response, Error<RE>>,
        BF: Fn(Duration) -> (),
    {
        let mut wait = Duration::from_millis(100);
        let request = request.into();
        loop {
            let req = request.to_request()?;
            let res = fun(req)?;
            #[allow(clippy::wildcard_enum_match_arm)]
            match request.from_response(res) {
                Err(Error::RateLimitReached) => {
                    backoff_fun(wait);
                    match wait.checked_add(Duration::from_millis(100)) {
                        Some(new_wait) => wait = new_wait,
                        None => return Err(Error::MaximumWaitTimeReached),
                    }
                }
                other => return other,
            }
        }
    }

    /// Executes an asynchronous http request using the given function
    ///
    /// # Arguments
    ///
    /// * `request`: Request to send. Use one of the functions in the `requests` module to create a request
    /// * `fun`: Function which implements sending asynchronous requests.
    ///
    /// # Errors
    ///
    /// Fails in the following cases:
    ///
    /// * Unable to create a valid Request
    /// * Server responded with error code
    /// * Unable to deserialize the server response
    /// * Custom Errors returned by the function given as `fun` parameter
    ///
    /// # Example
    ///
    /// ## `tokio`
    ///
    /// ```no_run
    /// # use tokio::runtime::Runtime;
    /// use http::Request;
    /// use std::convert::Infallible;
    /// use tenable::{requests::AssetReq, Error, Response, Tenable};
    /// async fn request(_req: Request<Vec<u8>>) -> Result::<Response, Error<Infallible>> { Ok(todo!("Define a method to send http requests")) }
    ///
    /// # let mut rt = Runtime::new().expect("Unable to create runtime");
    /// # rt.block_on(async {
    /// let tenable = Tenable::new(
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    /// );
    /// let req = tenable.assets();
    /// let _assets = Tenable::request_async(req, request).await
    ///     .expect("Unable to list all assets");
    /// # })
    /// ```
    ///
    /// ## `async_std`
    ///
    /// ```no_run
    /// # use async_std::task;
    /// use http::Request;
    /// use std::convert::Infallible;
    /// use tenable::{requests::AssetReq, Error, Response, Tenable};
    /// async fn request(_req: Request<Vec<u8>>) -> Result::<Response, Error<Infallible>> { Ok(todo!("Define a method to send http requests")) }
    ///
    /// # task::block_on(async {
    /// let tenable = Tenable::new(
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    /// );
    /// let req = tenable.assets();
    /// let _assets = Tenable::request_async(req, request).await
    ///     .expect("Unable to list all assets");
    /// # })
    /// ```
    #[inline]
    #[allow(single_use_lifetimes, unused_lifetimes)]
    pub async fn request_async<'a, O, R, CR, RE, F, Fut>(
        request: CR,
        fun: F,
    ) -> Result<O, Error<RE>>
    where
        CR: Into<Cow<'a, R>>,
        R: 'a + HttpRequest<RE, Output = O>,
        RE: fmt::Debug,
        F: FnOnce(Request<Vec<u8>>) -> Fut,
        Fut: Future<Output = Result<Response, Error<RE>>>,
    {
        let request = request.into();
        let req = request.to_request()?;
        let res = fun(req).await?;
        request.from_response(res)
    }

    /// Executes an asynchronous http request using the given function.
    /// Automatically backs off when a Rate Limit is hit
    ///
    /// # Arguments
    ///
    /// * `request`: Request to send. Use one of the functions in the `requests` module to create a request
    /// * `fun`: Function which implements sending asynchronous requests.
    /// * `backoff_fun`: Function which waits for the given Duration
    ///
    /// # Errors
    ///
    /// Fails in the following cases:
    ///
    /// * Unable to create a valid Request
    /// * Server responded with error code
    /// * Unable to deserialize the server response
    /// * Custom Errors returned by the function given as `fun` parameter
    ///
    /// # Example
    ///
    /// ## `tokio`
    ///
    /// ```no_run
    /// # use tokio::runtime::Runtime;
    /// use tokio::time::delay_for;
    /// use http::Request;
    /// use std::convert::Infallible;
    /// use tenable::{requests::AssetReq, Error, Response, Tenable};
    /// async fn request(_req: Request<Vec<u8>>) -> Result::<Response, Error<Infallible>> { Ok(todo!("Define a method to send http requests")) }
    ///
    /// # let mut rt = Runtime::new().expect("Unable to create runtime");
    /// # rt.block_on(async {
    /// let tenable = Tenable::new(
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    /// );
    /// let req = tenable.assets();
    /// let _assets = Tenable::request_with_backoff_async(req, request, delay_for).await
    ///     .expect("Unable to list all assets");
    /// # })
    /// ```
    ///
    /// ## `async_std`
    ///
    /// ```no_run
    /// use async_std::task;
    /// use http::Request;
    /// use std::convert::Infallible;
    /// use tenable::{requests::AssetReq, Error, Response, Tenable};
    /// async fn request(_req: Request<Vec<u8>>) -> Result::<Response, Error<Infallible>> { Ok(todo!("Define a method to send http requests")) }
    ///
    /// # task::block_on(async {
    /// let tenable = Tenable::new(
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    ///     "0000000000000000000000000000000000000000000000000000000000000000",
    /// );
    /// let req = tenable.assets();
    /// let _assets = Tenable::request_with_backoff_async(req, request, task::sleep).await
    ///     .expect("Unable to list all assets");
    /// # })
    /// ```
    #[inline]
    #[allow(single_use_lifetimes, unused_lifetimes)]
    pub async fn request_with_backoff_async<'a, O, R, CR, RE, F, Fut, BF, FutBF>(
        request: CR,
        fun: F,
        backoff_fun: BF,
    ) -> Result<O, Error<RE>>
    where
        CR: Into<Cow<'a, R>>,
        R: 'a + HttpRequest<RE, Output = O>,
        RE: fmt::Debug,
        F: Fn(Request<Vec<u8>>) -> Fut,
        Fut: Future<Output = Result<Response, Error<RE>>>,
        BF: Fn(Duration) -> FutBF,
        FutBF: Future<Output = ()>,
    {
        let mut wait = Duration::from_millis(100);
        let request = request.into();
        loop {
            let req = request.to_request()?;
            let res = fun(req).await?;
            #[allow(clippy::wildcard_enum_match_arm)]
            match request.from_response(res) {
                Err(Error::RateLimitReached) => {
                    backoff_fun(wait).await;
                    match wait.checked_add(Duration::from_millis(100)) {
                        Some(new_wait) => wait = new_wait,
                        None => return Err(Error::MaximumWaitTimeReached),
                    }
                }
                other => return other,
            }
        }
    }
}

/// Server Response allowing further processing
#[derive(Clone, Debug)]
pub struct Response {
    /// The `StatusCode` returned by the Server
    pub status: StatusCode,
    /// The Server Body in bytes
    pub body: Bytes,
}

/// Generic Requests which provides information for further processing using
/// the HTTP function given by the user
pub trait HttpRequest<RE: fmt::Debug>: Clone {
    /// Type which is returned by the HTTP Endpoint
    type Output;

    /// Creates an HTTP Request which can be send using an Http Client
    ///
    /// # Errors
    /// Fails if it is not possible to create a valid Request
    fn to_request(&self) -> Result<Request<Vec<u8>>, Error<RE>>;

    /// Parses the Http Client Response to its concret Type.
    ///
    /// # Errors
    ///
    /// Fails in the following cases:
    ///
    /// * Server responded with error code
    /// * Unable to deserialize the server response
    fn from_response(&self, res: Response) -> Result<Self::Output, Error<RE>>;
}