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            .post(format!("{}/api/v1/auth/device", self.base_url))
188            .send()
189            .await?;
190
191        if !resp.status().is_success() {
192            let status = resp.status();
193            let body = resp.text().await.unwrap_or_default();
194            return Err(format!("Server returned {status}: {body}").into());
195        }
196
197        Ok(resp.json().await?)
198    }
199
200    pub async fn device_status(&self, token: &str) -> Result<DeviceStatusResponse, Box<dyn Error>> {
201        let resp = self
202            .client
203            .get(format!(
204                "{}/api/v1/auth/device/{token}/status",
205                self.base_url
206            ))
207            .send()
208            .await?;
209
210        if !resp.status().is_success() {
211            let status = resp.status();
212            let body = resp.text().await.unwrap_or_default();
213            return Err(format!("Server returned {status}: {body}").into());
214        }
215
216        Ok(resp.json().await?)
217    }
218
219    pub async fn logout(&self) -> Result<(), Box<dyn Error>> {
220        let mut builder = self
221            .client
222            .post(format!("{}/api/v1/auth/logout", self.base_url));
223        if let Some(key) = &self.api_key {
224            builder = builder.header("Authorization", format!("Bearer {key}"));
225        }
226        let resp = builder.send().await?;
227        if !resp.status().is_success() {
228            let status = resp.status();
229            let body = resp.text().await.unwrap_or_default();
230            return Err(format!("Server returned {status}: {body}").into());
231        }
232        Ok(())
233    }
234
235    /// GET /api/v1/auth/me — validates the bearer token and returns user
236    /// identity. Used by `tracevault status` to distinguish "logged out",
237    /// "expired token", and "server unreachable".
238    pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
239        let mut builder = self.client.get(format!("{}/api/v1/auth/me", self.base_url));
240        if let Some(key) = &self.api_key {
241            builder = builder.header("Authorization", format!("Bearer {key}"));
242        }
243
244        let resp = builder
245            .send()
246            .await
247            .map_err(|e| GetMeError::Network(e.to_string()))?;
248
249        let status = resp.status();
250        if status == reqwest::StatusCode::UNAUTHORIZED {
251            return Err(GetMeError::Unauthorized);
252        }
253        if !status.is_success() {
254            let body = resp.text().await.unwrap_or_default();
255            return Err(GetMeError::Server(format!("{status}: {body}")));
256        }
257
258        resp.json::<MeResponse>()
259            .await
260            .map_err(|e| GetMeError::Server(e.to_string()))
261    }
262
263    pub async fn list_repos(&self, org_slug: &str) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
264        let mut builder = self
265            .client
266            .get(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
267        if let Some(key) = &self.api_key {
268            builder = builder.header("Authorization", format!("Bearer {key}"));
269        }
270
271        let resp = builder.send().await?;
272
273        if !resp.status().is_success() {
274            let status = resp.status();
275            let body = resp.text().await.unwrap_or_default();
276            return Err(format!("Failed to list repos ({status}): {body}").into());
277        }
278
279        let repos: Vec<RepoListItem> = resp.json().await?;
280        Ok(repos)
281    }
282
283    pub async fn get_agent_instructions(
284        &self,
285        org_slug: &str,
286        repo_id: &uuid::Uuid,
287    ) -> Result<AgentInstructionsResponse, Box<dyn Error>> {
288        let mut builder = self.client.get(format!(
289            "{}/api/v1/orgs/{}/repos/{}/policies/agent-instructions",
290            self.base_url, org_slug, repo_id
291        ));
292        if let Some(key) = &self.api_key {
293            builder = builder.header("Authorization", format!("Bearer {key}"));
294        }
295
296        let resp = builder.send().await?;
297        if !resp.status().is_success() {
298            let status = resp.status();
299            let body = resp.text().await.unwrap_or_default();
300            return Err(format!("Failed to fetch agent instructions ({status}): {body}").into());
301        }
302        Ok(resp.json().await?)
303    }
304
305    pub async fn verify_commits(
306        &self,
307        org_slug: &str,
308        repo_id: &uuid::Uuid,
309        req: CiVerifyRequest,
310    ) -> Result<CiVerifyResponse, Box<dyn Error>> {
311        let mut builder = self.client.post(format!(
312            "{}/api/v1/orgs/{}/repos/{}/ci/verify",
313            self.base_url, org_slug, repo_id
314        ));
315        if let Some(key) = &self.api_key {
316            builder = builder.header("Authorization", format!("Bearer {key}"));
317        }
318
319        let resp = builder.json(&req).send().await?;
320
321        if !resp.status().is_success() {
322            let status = resp.status();
323            let body = resp.text().await.unwrap_or_default();
324            return Err(format!("CI verify failed ({status}): {body}").into());
325        }
326
327        Ok(resp.json().await?)
328    }
329
330    pub async fn push_commit(
331        &self,
332        org_slug: &str,
333        repo_id: &str,
334        req: &tracevault_core::streaming::CommitPushRequest,
335    ) -> Result<tracevault_core::streaming::CommitPushResponse, Box<dyn Error>> {
336        let mut builder = self.client.post(format!(
337            "{}/api/v1/orgs/{}/repos/{}/commits",
338            self.base_url, org_slug, repo_id
339        ));
340        if let Some(key) = &self.api_key {
341            builder = builder.header("Authorization", format!("Bearer {key}"));
342        }
343        let resp = builder.json(req).send().await?;
344        if !resp.status().is_success() {
345            let status = resp.status();
346            let body = resp.text().await.unwrap_or_default();
347            return Err(format!("Commit push failed ({status}): {body}").into());
348        }
349        Ok(resp.json().await?)
350    }
351
352    pub async fn stream_event(
353        &self,
354        org_slug: &str,
355        repo_id: &str,
356        req: &tracevault_core::streaming::StreamEventRequest,
357    ) -> Result<tracevault_core::streaming::StreamEventResponse, Box<dyn Error>> {
358        let mut builder = self.client.post(format!(
359            "{}/api/v1/orgs/{}/repos/{}/stream",
360            self.base_url, org_slug, repo_id
361        ));
362        if let Some(key) = &self.api_key {
363            builder = builder.header("Authorization", format!("Bearer {key}"));
364        }
365        let resp = builder.json(req).send().await?;
366        if !resp.status().is_success() {
367            let status = resp.status();
368            let body = resp.text().await.unwrap_or_default();
369            return Err(format!("Stream failed ({status}): {body}").into());
370        }
371        Ok(resp.json().await?)
372    }
373
374    pub async fn check_policies(
375        &self,
376        org_slug: &str,
377        repo_id: &uuid::Uuid,
378        req: CheckPoliciesRequest,
379    ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
380        let mut builder = self.client.post(format!(
381            "{}/api/v1/orgs/{}/repos/{}/policies/check",
382            self.base_url, org_slug, repo_id
383        ));
384        if let Some(key) = &self.api_key {
385            builder = builder.header("Authorization", format!("Bearer {key}"));
386        }
387
388        let resp = builder.json(&req).send().await?;
389
390        if !resp.status().is_success() {
391            let status = resp.status();
392            let body = resp.text().await.unwrap_or_default();
393            return Err(format!("Policy check failed ({status}): {body}").into());
394        }
395
396        let result: CheckPoliciesResponse = resp.json().await?;
397        Ok(result)
398    }
399}
400
401/// Resolve server URL and auth token from multiple sources.
402/// Priority: env var > credentials file > project config.toml
403/// Returns (server_url, auth_token).
404pub fn resolve_credentials(project_root: &Path) -> (Option<String>, Option<String>) {
405    use crate::credentials::Credentials;
406
407    // 1. Env var API key
408    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
409
410    // 2. Credentials file
411    let creds = Credentials::load();
412
413    // 3. Project config
414    let config_path = crate::config::TracevaultConfig::config_path(project_root);
415    let config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
416
417    let config_server_url = config_content
418        .lines()
419        .find(|l| l.starts_with("server_url"))
420        .and_then(|l| l.split('=').nth(1))
421        .map(|s| s.trim().trim_matches('"').to_string());
422
423    let config_api_key = config_content
424        .lines()
425        .find(|l| l.starts_with("api_key"))
426        .and_then(|l| l.split('=').nth(1))
427        .map(|s| s.trim().trim_matches('"').to_string());
428
429    // Resolve server URL: env > creds > config
430    let server_url = std::env::var("TRACEVAULT_SERVER_URL")
431        .ok()
432        .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
433        .or(config_server_url);
434
435    // Resolve token: env api key > creds token > config api key
436    let token = env_key
437        .or_else(|| creds.map(|c| c.token))
438        .or(config_api_key);
439
440    (server_url, token)
441}