Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 46 additions & 9 deletions hindsight-cli/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,26 @@ use serde::{Deserialize, Serialize};
use serde_json;
use std::collections::HashMap;

const DEFAULT_CLI_USER_AGENT: &str = concat!("hindsight-cli/", env!("CARGO_PKG_VERSION"));

fn default_headers(api_key: Option<&str>) -> Result<reqwest::header::HeaderMap> {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::USER_AGENT,
reqwest::header::HeaderValue::from_static(DEFAULT_CLI_USER_AGENT),
);

if let Some(key) = api_key {
let auth_value = format!("Bearer {}", key);
headers.insert(
reqwest::header::AUTHORIZATION,
reqwest::header::HeaderValue::from_str(&auth_value)?,
);
}

Ok(headers)
}

/// Convert a progenitor client error into an anyhow error that includes the
/// HTTP response body. Without this, errors render as
/// "Unexpected Response: Response { ... }" with no body, hiding validation
Expand Down Expand Up @@ -112,15 +132,7 @@ impl ApiClient {
let mut client_builder =
reqwest::Client::builder().timeout(std::time::Duration::from_secs(120));

if let Some(key) = api_key {
let mut headers = reqwest::header::HeaderMap::new();
let auth_value = format!("Bearer {}", key);
headers.insert(
reqwest::header::AUTHORIZATION,
reqwest::header::HeaderValue::from_str(&auth_value)?,
);
client_builder = client_builder.default_headers(headers);
}
client_builder = client_builder.default_headers(default_headers(api_key.as_deref())?);

let http_client = client_builder.build()?;

Expand Down Expand Up @@ -1309,6 +1321,31 @@ pub use types::{
mod tests {
use super::*;

#[test]
fn default_headers_set_cli_user_agent_without_api_key() {
let headers = default_headers(None).unwrap();

assert_eq!(
headers.get(reqwest::header::USER_AGENT).unwrap(),
DEFAULT_CLI_USER_AGENT,
);
assert!(!headers.contains_key(reqwest::header::AUTHORIZATION));
}

#[test]
fn default_headers_keep_authorization_with_cli_user_agent() {
let headers = default_headers(Some("hsk_test")).unwrap();

assert_eq!(
headers.get(reqwest::header::USER_AGENT).unwrap(),
DEFAULT_CLI_USER_AGENT,
);
assert_eq!(
headers.get(reqwest::header::AUTHORIZATION).unwrap(),
"Bearer hsk_test",
);
}

#[test]
fn test_operation_deserialize() {
let json = r#"{
Expand Down