Skip to main content

tracevault_cli/
api_client.rs

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