Skip to content
This repository has been archived by the owner on Aug 3, 2023. It is now read-only.

Commit

Permalink
Sends custom user agent with cloudflare-rs
Browse files Browse the repository at this point in the history
  • Loading branch information
EverlastingBugstopper committed Feb 14, 2020
1 parent 4d0168e commit b6a404e
Show file tree
Hide file tree
Showing 11 changed files with 175 additions and 145 deletions.
2 changes: 1 addition & 1 deletion src/commands/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub fn global_config(user: &GlobalUser, verify: bool) -> Result<(), failure::Err
// validate_credentials() checks the /user/tokens/verify endpoint (for API token)
// or /user endpoint (for global API key) to ensure provided credentials actually work.
pub fn validate_credentials(user: &GlobalUser) -> Result<(), failure::Error> {
let client = http::cf_v4_api_client(user, HttpApiClientConfig::default())?;
let client = http::cf_v4_api_client(user, None)?;

match user {
GlobalUser::TokenAuth { .. } => {
Expand Down
11 changes: 2 additions & 9 deletions src/commands/kv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::settings::global_user::GlobalUser;
use crate::settings::toml::Target;

use crate::http;
use crate::http::Feature;

pub mod bucket;
pub mod bulk;
Expand All @@ -19,15 +20,7 @@ pub mod namespace;
// Create a special API client that has a longer timeout than usual, given that KV operations
// can be lengthy if payloads are large.
fn api_client(user: &GlobalUser) -> Result<HttpApiClient, failure::Error> {
http::cf_v4_api_client(
user,
HttpApiClientConfig {
default_headers: http::headers(None),
// Use 5 minute timeout instead of default 30-second one.
// This is useful for bulk upload operations.
http_timeout: Duration::from_secs(5 * 60),
},
)
http::cf_v4_api_client(user, Some(Feature::KV))
}

fn format_error(e: ApiFailure) -> String {
Expand Down
3 changes: 2 additions & 1 deletion src/commands/publish/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::commands::kv;
use crate::commands::kv::bucket::AssetManifest;
use crate::commands::subdomain::Subdomain;
use crate::http;
use crate::http::Feature;
use crate::settings::global_user::GlobalUser;
use crate::settings::toml::{DeployConfig, KvNamespace, Site, Target, Zoneless};
use crate::terminal::{emoji, message};
Expand Down Expand Up @@ -99,7 +100,7 @@ fn upload_script(
);

let client = if target.site.is_some() {
http::auth_client(Some("site"), user)
http::auth_client(Some(Feature::Sites), user)
} else {
http::auth_client(None, user)
};
Expand Down
5 changes: 2 additions & 3 deletions src/commands/publish/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use serde::Serialize;

use cloudflare::endpoints::workers::{CreateRoute, CreateRouteParams, ListRoutes};
use cloudflare::framework::apiclient::ApiClient;
use cloudflare::framework::HttpApiClientConfig;

use crate::http::{cf_v4_api_client, format_error};
use crate::settings::global_user::GlobalUser;
Expand All @@ -29,7 +28,7 @@ pub fn publish_routes(
}

fn fetch_all(user: &GlobalUser, zone_identifier: &str) -> Result<Vec<Route>, failure::Error> {
let client = cf_v4_api_client(user, HttpApiClientConfig::default())?;
let client = cf_v4_api_client(user, None)?;

let routes: Vec<Route> = match client.request(&ListRoutes { zone_identifier }) {
Ok(success) => success.result.iter().map(Route::from).collect(),
Expand All @@ -44,7 +43,7 @@ fn create(
zone_identifier: &str,
route: &Route,
) -> Result<Route, failure::Error> {
let client = cf_v4_api_client(user, HttpApiClientConfig::default())?;
let client = cf_v4_api_client(user, None)?;

log::info!("Creating your route {:#?}", &route.pattern,);
match client.request(&CreateRoute {
Expand Down
4 changes: 2 additions & 2 deletions src/commands/route/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::settings::global_user::GlobalUser;
use crate::terminal::message;

pub fn list(zone_identifier: String, user: &GlobalUser) -> Result<(), failure::Error> {
let client = http::cf_v4_api_client(user, HttpApiClientConfig::default())?;
let client = http::cf_v4_api_client(user, None)?;

let result = client.request(&ListRoutes {
zone_identifier: &zone_identifier,
Expand All @@ -31,7 +31,7 @@ pub fn delete(
user: &GlobalUser,
route_id: &str,
) -> Result<(), failure::Error> {
let client = http::cf_v4_api_client(user, HttpApiClientConfig::default())?;
let client = http::cf_v4_api_client(user, None)?;

let result = client.request(&DeleteRoute {
zone_identifier: &zone_identifier,
Expand Down
6 changes: 3 additions & 3 deletions src/commands/secret/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub fn create_secret(name: &str, user: &GlobalUser, target: &Target) -> Result<(
target.name
));

let client = http::cf_v4_api_client(user, HttpApiClientConfig::default())?;
let client = http::cf_v4_api_client(user, None)?;

let params = CreateSecretParams {
name: name.to_string(),
Expand Down Expand Up @@ -103,7 +103,7 @@ pub fn delete_secret(name: &str, user: &GlobalUser, target: &Target) -> Result<(
name, target.name
));

let client = http::cf_v4_api_client(user, HttpApiClientConfig::default())?;
let client = http::cf_v4_api_client(user, None)?;

let response = client.request(&DeleteSecret {
account_identifier: &target.account_id,
Expand All @@ -121,7 +121,7 @@ pub fn delete_secret(name: &str, user: &GlobalUser, target: &Target) -> Result<(

pub fn list_secrets(user: &GlobalUser, target: &Target) -> Result<(), failure::Error> {
validate_target(target)?;
let client = http::cf_v4_api_client(user, HttpApiClientConfig::default())?;
let client = http::cf_v4_api_client(user, None)?;

let response = client.request(&ListSecrets {
account_identifier: &target.account_id,
Expand Down
126 changes: 0 additions & 126 deletions src/http.rs

This file was deleted.

36 changes: 36 additions & 0 deletions src/http/feature.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};

use crate::install;

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Feature {
Sites,
KV,
}

pub(super) fn headers(feature: Option<Feature>) -> HeaderMap {
let mut headers = HeaderMap::default();
headers.insert(
USER_AGENT,
HeaderValue::from_str(&get_user_agent(feature)).unwrap(),
);
headers
}

fn get_user_agent(feature: Option<Feature>) -> String {
let version = if install::target::DEBUG {
"dev"
} else {
env!("CARGO_PKG_VERSION")
};

let mut agent = format!("wrangler/{}", version);
if let Some(feature) = feature {
agent.push_str("/");
match feature {
Feature::Sites => agent.push_str("sites"),
Feature::KV => agent.push_str("kv"),
}
}
agent
}
48 changes: 48 additions & 0 deletions src/http/legacy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use reqwest::blocking::{Client, ClientBuilder};
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::redirect::Policy;
use std::time::Duration;

use crate::http::{feature::headers, Feature};
use crate::settings::global_user::GlobalUser;

// TODO: remove this and replace it entirely with cloudflare-rs
pub fn client(feature: Option<Feature>) -> Client {
builder()
.default_headers(headers(feature))
.build()
.expect("could not create http client")
}

pub fn auth_client(feature: Option<Feature>, user: &GlobalUser) -> Client {
let mut headers = headers(feature);
add_auth_headers(&mut headers, user);

builder()
.default_headers(headers)
.redirect(Policy::none())
.build()
.expect("could not create authenticated http client")
}

fn builder() -> ClientBuilder {
let builder = reqwest::blocking::Client::builder();
builder
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
}

fn add_auth_headers<'a>(headers: &'a mut HeaderMap, user: &GlobalUser) {
match user {
GlobalUser::TokenAuth { api_token } => {
headers.insert(
"Authorization",
HeaderValue::from_str(&format!("Bearer {}", &api_token)).unwrap(),
);
}
GlobalUser::GlobalKeyAuth { email, api_key } => {
headers.insert("X-Auth-Email", HeaderValue::from_str(&email).unwrap());
headers.insert("X-Auth-Key", HeaderValue::from_str(&api_key).unwrap());
}
}
}
7 changes: 7 additions & 0 deletions src/http/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
pub(self) mod feature;
pub(self) mod legacy;
pub(self) mod v4;

pub use feature::Feature;
pub use legacy::{auth_client, client};
pub use v4::{cf_v4_api_client, format_error};
Loading

0 comments on commit b6a404e

Please sign in to comment.