Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rawtree-cli"
version = "0.8.5"
version = "0.8.6"
edition = "2021"
repository = "https://github.com/rawtreedb/rawtree-cli"

Expand Down
35 changes: 26 additions & 9 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,17 +284,34 @@ fn check_status(resp: Response) -> Result<()> {
Err(format_server_error(&text, status.as_u16()))
}

// RawTree API errors carry both a machine-readable code and a message.
// A private deployment's proxy may also respond with HTTP 403.
#[derive(Debug)]
struct ApiResponseError(String);

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

fn format_server_error(body: &str, status: u16) -> anyhow::Error {
if let Ok(json) = serde_json::from_str::<Value>(body) {
let message = json["message"].as_str().unwrap_or("Unknown error");
let hint = json["hint"].as_str().unwrap_or("");
if hint.is_empty() {
anyhow::anyhow!("Server error ({}): {}", status, message)
} else {
anyhow::anyhow!("Server error ({}): {}\nHint: {}", status, message, hint)
}
let Ok(json) = serde_json::from_str::<Value>(body) else {
return anyhow::anyhow!("Server error ({status}): {body}");
};
let code = json["error"].as_str().filter(|s| !s.is_empty());
let detail = json["message"].as_str().filter(|s| !s.is_empty());
let mut message = format!(
"Server error ({status}): {}",
detail.or(code).unwrap_or("Unknown error")
);
if let Some(hint) = json["hint"].as_str().filter(|hint| !hint.is_empty()) {
message.push_str(&format!("\nHint: {hint}"));
}
if code.is_some() && detail.is_some() {
anyhow::Error::msg(ApiResponseError(message))
} else {
anyhow::anyhow!("Server error ({}): {}", status, body)
anyhow::Error::msg(message)
}
}

Expand Down
20 changes: 10 additions & 10 deletions src/client/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{
handle_response,
regions::Region,
routing::{before_deadline, valid_routing},
ApiClient,
ApiClient, ApiResponseError,
};
use anyhow::{Context, Result};
use reqwest::{blocking::RequestBuilder, Method, StatusCode};
Expand Down Expand Up @@ -59,16 +59,16 @@ fn load_catalogs(requests: Vec<RequestBuilder>, deadline: Instant) -> Result<Vec
let result = match response {
Ok(response) => {
let status = response.status();
let result = handle_response(response);
if matches!(
status,
StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN
) {
return Err(result.err().unwrap_or_else(|| {
anyhow::anyhow!("Access denied ({status})")
}));
match handle_response(response) {
Err(error)
if status == StatusCode::UNAUTHORIZED
|| (status == StatusCode::FORBIDDEN
&& error.is::<ApiResponseError>()) =>
{
return Err(error);
}
result => result,
}
result
}
Err(error) => Err(error),
};
Expand Down
33 changes: 29 additions & 4 deletions tests/regional_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::time::{Duration, Instant};
#[derive(Clone, Copy)]
enum Failure {
Http(u16),
Proxy(u16, &'static str),
Disconnect,
Stall,
SlowBody,
Expand Down Expand Up @@ -73,7 +74,10 @@ fn run(args: &[&str], failure: Failure, all_fail: bool) -> (Output, Vec<String>,
}]}));
} else {
match failure {
Failure::Http(status) => reply(&mut socket, status, json!({"message":"Regional failure"})),
Failure::Http(status) => reply(&mut socket, status, json!({"error":"forbidden","message":"Regional failure","hint":"Check access."})),
Failure::Proxy(status, body) => {
write!(socket, "HTTP/1.1 {status} Test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
}
Failure::Disconnect => (),
Failure::Stall => thread::sleep(Duration::from_secs(6)),
Failure::SlowBody => {
Expand Down Expand Up @@ -121,7 +125,13 @@ fn run(args: &[&str], failure: Failure, all_fail: bool) -> (Output, Vec<String>,

#[test]
fn table_list_survives_http_and_connection_failures_in_other_regions() {
for failure in [Failure::Http(503), Failure::Disconnect] {
for failure in [
Failure::Http(503),
Failure::Proxy(403, "<html>Forbidden</html>"),
Failure::Proxy(403, r#"{"message":"Forbidden"}"#),
Failure::Proxy(403, r#"{"error":"Forbidden"}"#),
Failure::Disconnect,
] {
let (output, requests, _) = run(&["--json", "table", "list"], failure, false);
assert!(
output.status.success(),
Expand Down Expand Up @@ -169,7 +179,7 @@ fn cluster_list_exposes_partial_catalog_in_json_and_warns_in_text() {
} else {
vec!["cluster", "list"]
};
let (output, _, _) = run(&args, Failure::Http(503), false);
let (output, _, _) = run(&args, Failure::Proxy(403, "{}"), false);
assert!(
output.status.success(),
"{}",
Expand Down Expand Up @@ -208,6 +218,21 @@ fn authorization_and_total_outages_fail_without_executing_table_request() {
}
}

#[test]
fn raw_http_denials_remain_errors_for_expired_credentials_or_a_total_outage() {
for (status, all_fail) in [(401, false), (403, true)] {
let (output, _, _) = run(
&["--json", "cluster", "list"],
Failure::Proxy(status, ""),
all_fail,
);
assert!(!output.status.success());
assert!(
String::from_utf8_lossy(&output.stderr).contains(&format!("Server error ({status})"))
);
}
}

#[test]
fn missing_cluster_in_partial_catalog_never_falls_back_to_gateway() {
let (output, requests, _) = run(
Expand All @@ -234,7 +259,7 @@ fn management_commands_report_outages_for_missing_targets_in_partial_catalogs()
if command == "update" {
args.extend(["--idle-timeout-minutes", "60"]);
}
let (output, requests, _) = run(&args, Failure::Http(503), false);
let (output, requests, _) = run(&args, Failure::Proxy(403, "{}"), false);
assert!(!output.status.success(), "{command} {target}");
assert!(output.stdout.is_empty());
let error: Value = serde_json::from_slice(&output.stderr).unwrap();
Expand Down