grove
at @9
1//! Talking to a grove server over HTTPS.
2//!
3//! The transport is the system's `curl`: TLS is cryptography grove shouldn't write itself, and
4//! curl is on every machine. Settings and the token go to curl on stdin (`--config -`), never
5//! on its command line, so they don't show up in process lists.
6
7use crate::json::{self, Value};
8use std::io::Write;
9use std::process::{Command, Stdio};
10
11pub struct Client {
12 base: String,
13 token: Option<String>,
14}
15
16fn quote(s: &str) -> String {
17 format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
18}
19
20impl Client {
21 pub fn new(base: &str, token: Option<String>) -> Client {
22 Client { base: base.trim_end_matches('/').to_string(), token }
23 }
24
25 /// One request. Returns the status and the response body.
26 pub fn call(&self, method: &str, path: &str, body: Option<(&[u8], &str)>) -> Result<(u16, Vec<u8>), String> {
27 let body_file = match body {
28 Some((bytes, _)) => {
29 let path = std::env::temp_dir().join(format!("grove-body-{}", crate::random::hex(8)));
30 std::fs::write(&path, bytes).map_err(|e| e.to_string())?;
31 Some(path)
32 }
33 None => None,
34 };
35 let mut config = String::new();
36 config += &format!("request = {}\n", quote(method));
37 config += &format!("url = {}\n", quote(&format!("{}{path}", self.base)));
38 config += "silent\nshow-error\n";
39 config += &format!("write-out = {}\n", quote("%{stderr}%{http_code}"));
40 if let Some(t) = &self.token {
41 config += &format!("header = {}\n", quote(&format!("Authorization: Bearer {t}")));
42 }
43 if let (Some(path), Some((_, ctype))) = (&body_file, body) {
44 config += &format!("header = {}\n", quote(&format!("Content-Type: {ctype}")));
45 config += &format!("data-binary = {}\n", quote(&format!("@{}", path.display())));
46 }
47 let mut child = Command::new("curl")
48 .args(["--config", "-"])
49 .stdin(Stdio::piped())
50 .stdout(Stdio::piped())
51 .stderr(Stdio::piped())
52 .spawn()
53 .map_err(|e| format!("couldn't run curl: {e}"))?;
54 child.stdin.take().unwrap().write_all(config.as_bytes()).map_err(|e| e.to_string())?;
55 let out = child.wait_with_output().map_err(|e| e.to_string())?;
56 if let Some(p) = body_file {
57 let _ = std::fs::remove_file(p);
58 }
59 let stderr = String::from_utf8_lossy(&out.stderr).to_string();
60 // The status code is the last thing curl writes to stderr.
61 let (msg, code) = stderr.split_at(stderr.len().saturating_sub(3));
62 match code.parse::<u16>() {
63 Ok(status) if status != 0 && out.status.success() => Ok((status, out.stdout)),
64 _ => Err(format!("couldn't reach {}: {}", self.base, msg.trim().trim_start_matches("curl: "))),
65 }
66 }
67
68 fn check(&self, status: u16, bytes: Vec<u8>) -> Result<Vec<u8>, String> {
69 if status == 200 {
70 return Ok(bytes);
71 }
72 let text = String::from_utf8_lossy(&bytes);
73 let msg = json::parse(&text).ok().and_then(|v| v.get("error").and_then(Value::as_str).map(str::to_string)).unwrap_or_else(|| text.to_string());
74 Err(msg)
75 }
76
77 pub fn get(&self, path: &str) -> Result<Value, String> {
78 let (status, bytes) = self.call("GET", path, None)?;
79 let bytes = self.check(status, bytes)?;
80 json::parse(&String::from_utf8_lossy(&bytes)).map_err(|e| e.to_string())
81 }
82
83 pub fn post(&self, path: &str, body: &Value) -> Result<Value, String> {
84 let (status, bytes) = self.call("POST", path, Some((body.encode().as_bytes(), "application/json")))?;
85 let bytes = self.check(status, bytes)?;
86 json::parse(&String::from_utf8_lossy(&bytes)).map_err(|e| e.to_string())
87 }
88
89 pub fn post_bytes(&self, path: &str, body: &[u8], ctype: &str) -> Result<Vec<u8>, String> {
90 let (status, bytes) = self.call("POST", path, Some((body, ctype)))?;
91 self.check(status, bytes)
92 }
93}