Skip to content

Commit

Permalink
fix format
Browse files Browse the repository at this point in the history
  • Loading branch information
cn-kali-team committed Nov 26, 2023
1 parent b6d6c14 commit 8a9e8c2
Show file tree
Hide file tree
Showing 10 changed files with 318 additions and 281 deletions.
2 changes: 1 addition & 1 deletion helper/src/bin/cve_to_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ pub fn create_product(

fn main() {
let connection_pool = init_db_pool();
for y in 2023..2024 {
for y in 2004..2024 {
let p = format!("helper/examples/nvdcve/nvdcve-1.1-{y}.json.gz");
println!("{p}");
let gz_open_file = File::open(p).unwrap();
Expand Down
84 changes: 0 additions & 84 deletions helper/src/bin/query.rs

This file was deleted.

20 changes: 10 additions & 10 deletions helper/tests/test_cve_api.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
#[cfg(test)]
mod tests {
use nvd_api::pagination::ListResponse;
use nvd_api::pagination::ListResponse;

#[test]
fn cve() {
let j = include_str!("test/CVE-2001-0328.json");
let i: ListResponse = serde_json::from_str(j).unwrap();
println!("{:?}", i);
let j = include_str!("test/hasCertAlerts_2.0_fmt.json");
let i: ListResponse = serde_json::from_str(j).unwrap();
println!("{:?}", i);
}
#[test]
fn cve() {
let j = include_str!("test/CVE-2001-0328.json");
let i: ListResponse = serde_json::from_str(j).unwrap();
println!("{:?}", i);
let j = include_str!("test/hasCertAlerts_2.0_fmt.json");
let i: ListResponse = serde_json::from_str(j).unwrap();
println!("{:?}", i);
}
}
104 changes: 52 additions & 52 deletions nvd-api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,81 +5,81 @@ use std::num::NonZeroU16;

#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Invalid NVD API Token: {}", source)]
InvalidApiToken {
source: reqwest::header::InvalidHeaderValue,
},
#[error("Invalid NVD API Token: {}", source)]
InvalidApiToken {
source: reqwest::header::InvalidHeaderValue,
},

#[error("Unable to build reqwest HTTP client: {}", source)]
BuildingClient { source: reqwest::Error },
#[error("Unable to build reqwest HTTP client: {}", source)]
BuildingClient { source: reqwest::Error },

#[error("Error sending HTTP request: {}", source)]
RequestFailed {
#[from]
source: reqwest::Error,
},
#[error("Error sending HTTP request: {}", source)]
RequestFailed {
#[from]
source: reqwest::Error,
},

#[error("Error reading response: {}", source)]
ResponseIo { source: reqwest::Error },
#[error("Error reading response: {}", source)]
ResponseIo { source: reqwest::Error },

#[error("Error parsing json response: {}", source)]
JsonParse { source: serde_json::Error },
#[error("Error parsing json response: {}", source)]
JsonParse { source: serde_json::Error },

#[error("Unexpected API Response")]
UnexpectedResponse { response: Object },
#[error("Unexpected API Response")]
UnexpectedResponse { response: Object },

#[error("API Error {}({}): {}", .error.code, .error.status, .error.message)]
Api { error: ErrorResponse },
#[error("API Error {}({}): {}", .error.code, .error.status, .error.message)]
Api { error: ErrorResponse },
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct StatusCode(NonZeroU16);

impl Display for StatusCode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
pub struct ErrorResponse {
pub status: StatusCode,
pub code: ErrorCode,
pub message: String,
pub status: StatusCode,
pub code: ErrorCode,
pub message: String,
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
/// The request body could not be decoded as JSON.
InvalidJson,
/// The request URL is not valid.
InvalidRequestUrl,
/// This request is not supported.
InvalidRequest,
/// The request body does not match the schema for the expected parameters. Check the "message" property for more details.
MissionVersion,
/// The bearer token is not valid.
Unauthorized,
/// Given the bearer token used, the client doesn't have permission to perform this operation.
RestrictedResource,
/// Given the bearer token used, the resource does not exist. This error can also indicate that the resource has not been shared with owner of the bearer token.
ObjectNotFound,
/// The transaction could not be completed, potentially due to a data collision. Make sure the parameters are up to date and try again.
ConflictError,
/// This request exceeds the number of requests allowed. Slow down and try again. More details on rate limits.
RateLimited,
/// An unexpected error occurred. Reach out to NVD support.
InternalServerError,
/// NVD is unavailable. Try again later. This can occur when the time to respond to a request takes longer than 60 seconds, the maximum request timeout.
ServiceUnavailable,
#[serde(other)] // serde issue #912
Unknown,
/// The request body could not be decoded as JSON.
InvalidJson,
/// The request URL is not valid.
InvalidRequestUrl,
/// This request is not supported.
InvalidRequest,
/// The request body does not match the schema for the expected parameters. Check the "message" property for more details.
MissionVersion,
/// The bearer token is not valid.
Unauthorized,
/// Given the bearer token used, the client doesn't have permission to perform this operation.
RestrictedResource,
/// Given the bearer token used, the resource does not exist. This error can also indicate that the resource has not been shared with owner of the bearer token.
ObjectNotFound,
/// The transaction could not be completed, potentially due to a data collision. Make sure the parameters are up to date and try again.
ConflictError,
/// This request exceeds the number of requests allowed. Slow down and try again. More details on rate limits.
RateLimited,
/// An unexpected error occurred. Reach out to NVD support.
InternalServerError,
/// NVD is unavailable. Try again later. This can occur when the time to respond to a request takes longer than 60 seconds, the maximum request timeout.
ServiceUnavailable,
#[serde(other)] // serde issue #912
Unknown,
}

impl Display for ErrorCode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
46 changes: 25 additions & 21 deletions nvd-api/src/pagination.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::error::ErrorResponse;
use crate::v2::Vulnerabilities;
use crate::v2::products::{MatchStrings, Products};
use crate::v2::vulnerabilities::{Change, Vulnerabilities};
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};

Expand All @@ -9,35 +10,38 @@ pub struct PagingCursor(String);

#[derive(Serialize, Debug, Eq, PartialEq, Default, Clone)]
pub struct Paging {
#[serde(skip_serializing_if = "Option::is_none")]
pub start_cursor: Option<PagingCursor>,
#[serde(skip_serializing_if = "Option::is_none")]
pub page_size: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
pub start_cursor: Option<PagingCursor>,
#[serde(skip_serializing_if = "Option::is_none")]
pub page_size: Option<u8>,
}

pub trait Pageable {
fn start_from(self, starting_point: Option<PagingCursor>) -> Self;
fn start_from(self, starting_point: Option<PagingCursor>) -> Self;
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(rename_all(deserialize = "camelCase"))]
pub struct ListResponse {
#[serde(flatten)]
pub results: Object,
pub results_per_page: u32,
pub start_index: u32,
pub total_results: u32,
pub format: String,
pub version: String,
pub timestamp: NaiveDateTime,
#[serde(flatten)]
pub results: Object,
pub results_per_page: u32,
pub start_index: u32,
pub total_results: u32,
pub format: String,
pub version: String,
pub timestamp: NaiveDateTime,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
#[serde(rename_all = "camelCase")]
pub enum Object {
Vulnerabilities(Vec<Vulnerabilities>),
Error {
#[serde(flatten)]
error: ErrorResponse,
},
}
Vulnerabilities(Vec<Vulnerabilities>),
CveChanges(Vec<Change>),
Products(Vec<Products>),
MatchStrings(Vec<MatchStrings>),
Error {
#[serde(flatten)]
error: ErrorResponse,
},
}
48 changes: 0 additions & 48 deletions nvd-api/src/v2/cve_history.rs

This file was deleted.

Loading

0 comments on commit 8a9e8c2

Please sign in to comment.