Skip to main content

tracevault_cli/
api_client.rs

1use serde::{Deserialize, Serialize};
2use std::error::Error;
3use std::path::Path;
4
5pub struct ApiClient {
6    base_url: String,
7    api_key: Option<String>,
8    client: reqwest::Client,
9}
10
11#[derive(Serialize)]
12pub struct RegisterRepoRequest {
13    pub repo_name: String,
14    pub github_url: Option<String>,
15}
16
17#[derive(Deserialize)]
18pub struct RegisterRepoResponse {
19    pub repo_id: uuid::Uuid,
20}
21
22#[derive(Deserialize)]
23pub struct DeviceAuthResponse {
24    pub token: String,
25}
26
27#[derive(Deserialize)]
28pub struct DeviceStatusResponse {
29    pub status: String,
30    pub token: Option<String>,
31    pub email: Option<String>,
32}
33
34#[derive(Debug, Serialize)]
35pub struct CheckPoliciesRequest {
36    pub sessions: Vec<SessionCheckData>,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub commit_sha: Option<String>,
39}
40
41#[derive(Debug, Serialize)]
42pub struct SessionCheckData {
43    pub session_id: String,
44    pub tool_calls: Option<serde_json::Value>,
45    pub files_modified: Option<Vec<String>>,
46    pub total_tool_calls: Option<i32>,
47}
48
49#[derive(Debug, Deserialize)]
50pub struct CheckPoliciesResponse {
51    pub passed: bool,
52    pub results: Vec<CheckResultItem>,
53    pub blocked: bool,
54}
55
56#[derive(Debug, Deserialize)]
57pub struct CheckResultItem {
58    pub rule_name: String,
59    pub result: String,
60    pub action: String,
61    pub severity: String,
62    pub details: String,
63}
64
65#[derive(Debug, Deserialize)]
66pub struct RepoListItem {
67    pub id: uuid::Uuid,
68    pub name: String,
69    #[serde(default)]
70    pub github_url: Option<String>,
71    #[serde(default)]
72    pub clone_status: Option<String>,
73}
74
75/// Response shape for the `policies/agent-instructions` endpoint.
76#[derive(Debug, Clone, Deserialize)]
77pub struct AgentInstructionsResponse {
78    #[allow(dead_code)]
79    pub format: String,
80    pub content: String,
81}
82
83#[derive(Debug, Deserialize)]
84pub struct MeResponse {
85    #[allow(dead_code)]
86    pub user_id: uuid::Uuid,
87    pub email: String,
88    pub name: Option<String>,
89}
90
91#[derive(Debug)]
92pub enum GetMeError {
93    /// 401 — token is missing or invalid.
94    Unauthorized,
95    /// Transport-level failure (DNS, TCP, TLS, timeout).
96    Network(String),
97    /// HTTP ≥ 400 other than 401, or malformed JSON.
98    Server(String),
99}
100
101impl std::fmt::Display for GetMeError {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        match self {
104            Self::Unauthorized => write!(f, "unauthorized (token invalid or expired)"),
105            Self::Network(m) => write!(f, "network error: {m}"),
106            Self::Server(m) => write!(f, "server error: {m}"),
107        }
108    }
109}
110
111impl std::error::Error for GetMeError {}
112
113#[derive(Debug, Serialize)]
114pub struct CiVerifyRequest {
115    pub commits: Vec<String>,
116}
117
118#[derive(Debug, Deserialize)]
119pub struct CiVerifyResponse {
120    pub status: String,
121    pub total_commits: usize,
122    pub registered_commits: usize,
123    pub sealed_commits: usize,
124    pub policy_passed_commits: usize,
125    pub results: Vec<CommitVerifyResult>,
126}
127
128#[derive(Debug, Deserialize)]
129pub struct CommitVerifyResult {
130    pub commit_sha: String,
131    pub status: String,
132    pub registered: bool,
133    pub sealed: bool,
134    pub signature_valid: bool,
135    pub chain_valid: bool,
136    pub policy_results: Vec<CiPolicyResult>,
137}
138
139#[derive(Debug, Deserialize)]
140pub struct CiPolicyResult {
141    pub rule_name: String,
142    pub result: String,
143    pub action: String,
144    pub severity: String,
145    pub details: String,
146}
147
148impl ApiClient {
149    pub fn new(base_url: &str, api_key: Option<&str>) -> Self {
150        Self {
151            base_url: base_url.trim_end_matches('/').to_string(),
152            api_key: api_key.map(String::from),
153            client: reqwest::Client::builder()
154                .timeout(std::time::Duration::from_secs(60))
155                .build()
156                .unwrap_or_default(),
157        }
158    }
159
160    pub async fn register_repo(
161        &self,
162        org_slug: &str,
163        req: RegisterRepoRequest,
164    ) -> Result<RegisterRepoResponse, Box<dyn Error>> {
165        let mut builder = self
166            .client
167            .post(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
168
169        if let Some(key) = &self.api_key {
170            builder = builder.header("Authorization", format!("Bearer {key}"));
171        }
172
173        let resp = builder.json(&req).send().await?;
174
175        if !resp.status().is_success() {
176            let status = resp.status();
177            let body = resp.text().await.unwrap_or_default();
178            return Err(format!("Server returned {status}: {body}").into());
179        }
180
181        Ok(resp.json().await?)
182    }
183
184    pub async fn device_start(&self) -> Result<DeviceAuthResponse, Box<dyn Error>> {
185        let resp = self
186            .client
187            // Send an explicit `Content-Length: 0`. reqwest/hyper omit the header
188            // entirely for a bodyless POST, and strict frontends (e.g. Google
189            // Front End) reject such requests with `411 Length Required`.
190            .post(format!("{}/api/v1/auth/device", self.base_url))
191            .header(reqwest::header::CONTENT_LENGTH, "0")
192            .send()
193            .await?;
194
195        if !resp.status().is_success() {
196            let status = resp.status();
197            let body = resp.text().await.unwrap_or_default();
198            return Err(format!("Server returned {status}: {body}").into());
199        }
200
201        Ok(resp.json().await?)
202    }
203
204    pub async fn device_status(&self, token: &str) -> Result<DeviceStatusResponse, Box<dyn Error>> {
205        let resp = self
206            .client
207            .get(format!(
208                "{}/api/v1/auth/device/{token}/status",
209                self.base_url
210            ))
211            .send()
212            .await?;
213
214        if !resp.status().is_success() {
215            let status = resp.status();
216            let body = resp.text().await.unwrap_or_default();
217            return Err(format!("Server returned {status}: {body}").into());
218        }
219
220        Ok(resp.json().await?)
221    }
222
223    pub async fn logout(&self) -> Result<(), Box<dyn Error>> {
224        let mut builder = self
225            .client
226            .post(format!("{}/api/v1/auth/logout", self.base_url));
227        if let Some(key) = &self.api_key {
228            builder = builder.header("Authorization", format!("Bearer {key}"));
229        }
230        // Explicit `Content-Length: 0` (see `device_start`): reqwest/hyper omit it
231        // for a bodyless POST, which strict frontends reject with 411.
232        let resp = builder
233            .header(reqwest::header::CONTENT_LENGTH, "0")
234            .send()
235            .await?;
236        if !resp.status().is_success() {
237            let status = resp.status();
238            let body = resp.text().await.unwrap_or_default();
239            return Err(format!("Server returned {status}: {body}").into());
240        }
241        Ok(())
242    }
243
244    /// GET /api/v1/auth/me — validates the bearer token and returns user
245    /// identity. Used by `tracevault status` to distinguish "logged out",
246    /// "expired token", and "server unreachable".
247    pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
248        let mut builder = self.client.get(format!("{}/api/v1/auth/me", self.base_url));
249        if let Some(key) = &self.api_key {
250            builder = builder.header("Authorization", format!("Bearer {key}"));
251        }
252
253        let resp = builder
254            .send()
255            .await
256            .map_err(|e| GetMeError::Network(e.to_string()))?;
257
258        let status = resp.status();
259        if status == reqwest::StatusCode::UNAUTHORIZED {
260            return Err(GetMeError::Unauthorized);
261        }
262        if !status.is_success() {
263            let body = resp.text().await.unwrap_or_default();
264            return Err(GetMeError::Server(format!("{status}: {body}")));
265        }
266
267        resp.json::<MeResponse>()
268            .await
269            .map_err(|e| GetMeError::Server(e.to_string()))
270    }
271
272    pub async fn list_repos(&self, org_slug: &str) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
273        let mut builder = self
274            .client
275            .get(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
276        if let Some(key) = &self.api_key {
277            builder = builder.header("Authorization", format!("Bearer {key}"));
278        }
279
280        let resp = builder.send().await?;
281
282        if !resp.status().is_success() {
283            let status = resp.status();
284            let body = resp.text().await.unwrap_or_default();
285            return Err(format!("Failed to list repos ({status}): {body}").into());
286        }
287
288        let repos: Vec<RepoListItem> = resp.json().await?;
289        Ok(repos)
290    }
291
292    pub async fn get_agent_instructions(
293        &self,
294        org_slug: &str,
295        repo_id: &uuid::Uuid,
296    ) -> Result<AgentInstructionsResponse, Box<dyn Error>> {
297        let mut builder = self.client.get(format!(
298            "{}/api/v1/orgs/{}/repos/{}/policies/agent-instructions",
299            self.base_url, org_slug, repo_id
300        ));
301        if let Some(key) = &self.api_key {
302            builder = builder.header("Authorization", format!("Bearer {key}"));
303        }
304
305        let resp = builder.send().await?;
306        if !resp.status().is_success() {
307            let status = resp.status();
308            let body = resp.text().await.unwrap_or_default();
309            return Err(format!("Failed to fetch agent instructions ({status}): {body}").into());
310        }
311        Ok(resp.json().await?)
312    }
313
314    pub async fn verify_commits(
315        &self,
316        org_slug: &str,
317        repo_id: &uuid::Uuid,
318        req: CiVerifyRequest,
319    ) -> Result<CiVerifyResponse, Box<dyn Error>> {
320        let mut builder = self.client.post(format!(
321            "{}/api/v1/orgs/{}/repos/{}/ci/verify",
322            self.base_url, org_slug, repo_id
323        ));
324        if let Some(key) = &self.api_key {
325            builder = builder.header("Authorization", format!("Bearer {key}"));
326        }
327
328        let resp = builder.json(&req).send().await?;
329
330        if !resp.status().is_success() {
331            let status = resp.status();
332            let body = resp.text().await.unwrap_or_default();
333            return Err(format!("CI verify failed ({status}): {body}").into());
334        }
335
336        Ok(resp.json().await?)
337    }
338
339    pub async fn push_commit(
340        &self,
341        org_slug: &str,
342        repo_id: &str,
343        req: &tracevault_protocol::streaming::CommitPushRequest,
344    ) -> Result<tracevault_protocol::streaming::CommitPushResponse, Box<dyn Error>> {
345        let mut builder = self.client.post(format!(
346            "{}/api/v1/orgs/{}/repos/{}/commits",
347            self.base_url, org_slug, repo_id
348        ));
349        if let Some(key) = &self.api_key {
350            builder = builder.header("Authorization", format!("Bearer {key}"));
351        }
352        let resp = builder.json(req).send().await?;
353        if !resp.status().is_success() {
354            let status = resp.status();
355            let body = resp.text().await.unwrap_or_default();
356            return Err(format!("Commit push failed ({status}): {body}").into());
357        }
358        Ok(resp.json().await?)
359    }
360
361    pub async fn stream_event(
362        &self,
363        org_slug: &str,
364        repo_id: &str,
365        req: &tracevault_protocol::streaming::StreamEventRequest,
366    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
367        let mut builder = self.client.post(format!(
368            "{}/api/v1/orgs/{}/repos/{}/stream",
369            self.base_url, org_slug, repo_id
370        ));
371        if let Some(key) = &self.api_key {
372            builder = builder.header("Authorization", format!("Bearer {key}"));
373        }
374        let resp = builder.json(req).send().await?;
375        if !resp.status().is_success() {
376            let status = resp.status();
377            let body = resp.text().await.unwrap_or_default();
378            return Err(format!("Stream failed ({status}): {body}").into());
379        }
380        Ok(resp.json().await?)
381    }
382
383    pub async fn check_policies(
384        &self,
385        org_slug: &str,
386        repo_id: &uuid::Uuid,
387        req: CheckPoliciesRequest,
388    ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
389        let mut builder = self.client.post(format!(
390            "{}/api/v1/orgs/{}/repos/{}/policies/check",
391            self.base_url, org_slug, repo_id
392        ));
393        if let Some(key) = &self.api_key {
394            builder = builder.header("Authorization", format!("Bearer {key}"));
395        }
396
397        let resp = builder.json(&req).send().await?;
398
399        if !resp.status().is_success() {
400            let status = resp.status();
401            let body = resp.text().await.unwrap_or_default();
402            return Err(format!("Policy check failed ({status}): {body}").into());
403        }
404
405        let result: CheckPoliciesResponse = resp.json().await?;
406        Ok(result)
407    }
408}
409
410/// Resolve server URL and auth token from multiple sources.
411/// Priority: env var > credentials file > project config.toml
412/// Returns (server_url, auth_token).
413pub fn resolve_credentials(project_root: &Path) -> (Option<String>, Option<String>) {
414    use crate::credentials::Credentials;
415
416    // 1. Env var API key
417    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
418
419    // 2. Credentials file
420    let creds = Credentials::load();
421
422    // 3. Project config
423    let config_path = crate::config::TracevaultConfig::config_path(project_root);
424    let config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
425
426    let config_server_url = config_content
427        .lines()
428        .find(|l| l.starts_with("server_url"))
429        .and_then(|l| l.split('=').nth(1))
430        .map(|s| s.trim().trim_matches('"').to_string());
431
432    let config_api_key = config_content
433        .lines()
434        .find(|l| l.starts_with("api_key"))
435        .and_then(|l| l.split('=').nth(1))
436        .map(|s| s.trim().trim_matches('"').to_string());
437
438    // Resolve server URL: env > creds > config
439    let server_url = std::env::var("TRACEVAULT_SERVER_URL")
440        .ok()
441        .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
442        .or(config_server_url);
443
444    // Resolve token: env api key > creds token > config api key
445    let token = env_key
446        .or_else(|| creds.map(|c| c.token))
447        .or(config_api_key);
448
449    (server_url, token)
450}