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#[derive(Debug, Deserialize)]
76pub struct MeResponse {
77    #[allow(dead_code)]
78    pub user_id: uuid::Uuid,
79    pub email: String,
80    pub name: Option<String>,
81}
82
83#[derive(Debug)]
84pub enum GetMeError {
85    /// 401 — token is missing or invalid.
86    Unauthorized,
87    /// Transport-level failure (DNS, TCP, TLS, timeout).
88    Network(String),
89    /// HTTP ≥ 400 other than 401, or malformed JSON.
90    Server(String),
91}
92
93impl std::fmt::Display for GetMeError {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        match self {
96            Self::Unauthorized => write!(f, "unauthorized (token invalid or expired)"),
97            Self::Network(m) => write!(f, "network error: {m}"),
98            Self::Server(m) => write!(f, "server error: {m}"),
99        }
100    }
101}
102
103impl std::error::Error for GetMeError {}
104
105#[derive(Debug, Serialize)]
106pub struct CiVerifyRequest {
107    pub commits: Vec<String>,
108}
109
110#[derive(Debug, Deserialize)]
111pub struct CiVerifyResponse {
112    pub status: String,
113    pub total_commits: usize,
114    pub registered_commits: usize,
115    pub sealed_commits: usize,
116    pub policy_passed_commits: usize,
117    pub results: Vec<CommitVerifyResult>,
118}
119
120#[derive(Debug, Deserialize)]
121pub struct CommitVerifyResult {
122    pub commit_sha: String,
123    pub status: String,
124    pub registered: bool,
125    pub sealed: bool,
126    pub signature_valid: bool,
127    pub chain_valid: bool,
128    pub policy_results: Vec<CiPolicyResult>,
129}
130
131#[derive(Debug, Deserialize)]
132pub struct CiPolicyResult {
133    pub rule_name: String,
134    pub result: String,
135    pub action: String,
136    pub severity: String,
137    pub details: String,
138}
139
140impl ApiClient {
141    pub fn new(base_url: &str, api_key: Option<&str>) -> Self {
142        Self {
143            base_url: base_url.trim_end_matches('/').to_string(),
144            api_key: api_key.map(String::from),
145            client: reqwest::Client::new(),
146        }
147    }
148
149    pub async fn register_repo(
150        &self,
151        org_slug: &str,
152        req: RegisterRepoRequest,
153    ) -> Result<RegisterRepoResponse, Box<dyn Error>> {
154        let mut builder = self
155            .client
156            .post(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
157
158        if let Some(key) = &self.api_key {
159            builder = builder.header("Authorization", format!("Bearer {key}"));
160        }
161
162        let resp = builder.json(&req).send().await?;
163
164        if !resp.status().is_success() {
165            let status = resp.status();
166            let body = resp.text().await.unwrap_or_default();
167            return Err(format!("Server returned {status}: {body}").into());
168        }
169
170        Ok(resp.json().await?)
171    }
172
173    pub async fn device_start(&self) -> Result<DeviceAuthResponse, Box<dyn Error>> {
174        let resp = self
175            .client
176            .post(format!("{}/api/v1/auth/device", self.base_url))
177            .send()
178            .await?;
179
180        if !resp.status().is_success() {
181            let status = resp.status();
182            let body = resp.text().await.unwrap_or_default();
183            return Err(format!("Server returned {status}: {body}").into());
184        }
185
186        Ok(resp.json().await?)
187    }
188
189    pub async fn device_status(&self, token: &str) -> Result<DeviceStatusResponse, Box<dyn Error>> {
190        let resp = self
191            .client
192            .get(format!(
193                "{}/api/v1/auth/device/{token}/status",
194                self.base_url
195            ))
196            .send()
197            .await?;
198
199        if !resp.status().is_success() {
200            let status = resp.status();
201            let body = resp.text().await.unwrap_or_default();
202            return Err(format!("Server returned {status}: {body}").into());
203        }
204
205        Ok(resp.json().await?)
206    }
207
208    pub async fn logout(&self) -> Result<(), Box<dyn Error>> {
209        let mut builder = self
210            .client
211            .post(format!("{}/api/v1/auth/logout", self.base_url));
212        if let Some(key) = &self.api_key {
213            builder = builder.header("Authorization", format!("Bearer {key}"));
214        }
215        let resp = builder.send().await?;
216        if !resp.status().is_success() {
217            let status = resp.status();
218            let body = resp.text().await.unwrap_or_default();
219            return Err(format!("Server returned {status}: {body}").into());
220        }
221        Ok(())
222    }
223
224    /// GET /api/v1/auth/me — validates the bearer token and returns user
225    /// identity. Used by `tracevault status` to distinguish "logged out",
226    /// "expired token", and "server unreachable".
227    pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
228        let mut builder = self.client.get(format!("{}/api/v1/auth/me", self.base_url));
229        if let Some(key) = &self.api_key {
230            builder = builder.header("Authorization", format!("Bearer {key}"));
231        }
232
233        let resp = builder
234            .send()
235            .await
236            .map_err(|e| GetMeError::Network(e.to_string()))?;
237
238        let status = resp.status();
239        if status == reqwest::StatusCode::UNAUTHORIZED {
240            return Err(GetMeError::Unauthorized);
241        }
242        if !status.is_success() {
243            let body = resp.text().await.unwrap_or_default();
244            return Err(GetMeError::Server(format!("{status}: {body}")));
245        }
246
247        resp.json::<MeResponse>()
248            .await
249            .map_err(|e| GetMeError::Server(e.to_string()))
250    }
251
252    pub async fn list_repos(&self, org_slug: &str) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
253        let mut builder = self
254            .client
255            .get(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
256        if let Some(key) = &self.api_key {
257            builder = builder.header("Authorization", format!("Bearer {key}"));
258        }
259
260        let resp = builder.send().await?;
261
262        if !resp.status().is_success() {
263            let status = resp.status();
264            let body = resp.text().await.unwrap_or_default();
265            return Err(format!("Failed to list repos ({status}): {body}").into());
266        }
267
268        let repos: Vec<RepoListItem> = resp.json().await?;
269        Ok(repos)
270    }
271
272    pub async fn verify_commits(
273        &self,
274        org_slug: &str,
275        repo_id: &uuid::Uuid,
276        req: CiVerifyRequest,
277    ) -> Result<CiVerifyResponse, Box<dyn Error>> {
278        let mut builder = self.client.post(format!(
279            "{}/api/v1/orgs/{}/repos/{}/ci/verify",
280            self.base_url, org_slug, repo_id
281        ));
282        if let Some(key) = &self.api_key {
283            builder = builder.header("Authorization", format!("Bearer {key}"));
284        }
285
286        let resp = builder.json(&req).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!("CI verify failed ({status}): {body}").into());
292        }
293
294        Ok(resp.json().await?)
295    }
296
297    pub async fn push_commit(
298        &self,
299        org_slug: &str,
300        repo_id: &str,
301        req: &tracevault_core::streaming::CommitPushRequest,
302    ) -> Result<tracevault_core::streaming::CommitPushResponse, Box<dyn Error>> {
303        let mut builder = self.client.post(format!(
304            "{}/api/v1/orgs/{}/repos/{}/commits",
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        let resp = builder.json(req).send().await?;
311        if !resp.status().is_success() {
312            let status = resp.status();
313            let body = resp.text().await.unwrap_or_default();
314            return Err(format!("Commit push failed ({status}): {body}").into());
315        }
316        Ok(resp.json().await?)
317    }
318
319    pub async fn stream_event(
320        &self,
321        org_slug: &str,
322        repo_id: &str,
323        req: &tracevault_core::streaming::StreamEventRequest,
324    ) -> Result<tracevault_core::streaming::StreamEventResponse, Box<dyn Error>> {
325        let mut builder = self.client.post(format!(
326            "{}/api/v1/orgs/{}/repos/{}/stream",
327            self.base_url, org_slug, repo_id
328        ));
329        if let Some(key) = &self.api_key {
330            builder = builder.header("Authorization", format!("Bearer {key}"));
331        }
332        let resp = builder.json(req).send().await?;
333        if !resp.status().is_success() {
334            let status = resp.status();
335            let body = resp.text().await.unwrap_or_default();
336            return Err(format!("Stream failed ({status}): {body}").into());
337        }
338        Ok(resp.json().await?)
339    }
340
341    pub async fn check_policies(
342        &self,
343        org_slug: &str,
344        repo_id: &uuid::Uuid,
345        req: CheckPoliciesRequest,
346    ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
347        let mut builder = self.client.post(format!(
348            "{}/api/v1/orgs/{}/repos/{}/policies/check",
349            self.base_url, org_slug, repo_id
350        ));
351        if let Some(key) = &self.api_key {
352            builder = builder.header("Authorization", format!("Bearer {key}"));
353        }
354
355        let resp = builder.json(&req).send().await?;
356
357        if !resp.status().is_success() {
358            let status = resp.status();
359            let body = resp.text().await.unwrap_or_default();
360            return Err(format!("Policy check failed ({status}): {body}").into());
361        }
362
363        let result: CheckPoliciesResponse = resp.json().await?;
364        Ok(result)
365    }
366}
367
368/// Resolve server URL and auth token from multiple sources.
369/// Priority: env var > credentials file > project config.toml
370/// Returns (server_url, auth_token).
371pub fn resolve_credentials(project_root: &Path) -> (Option<String>, Option<String>) {
372    use crate::credentials::Credentials;
373
374    // 1. Env var API key
375    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
376
377    // 2. Credentials file
378    let creds = Credentials::load();
379
380    // 3. Project config
381    let config_path = crate::config::TracevaultConfig::config_path(project_root);
382    let config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
383
384    let config_server_url = config_content
385        .lines()
386        .find(|l| l.starts_with("server_url"))
387        .and_then(|l| l.split('=').nth(1))
388        .map(|s| s.trim().trim_matches('"').to_string());
389
390    let config_api_key = config_content
391        .lines()
392        .find(|l| l.starts_with("api_key"))
393        .and_then(|l| l.split('=').nth(1))
394        .map(|s| s.trim().trim_matches('"').to_string());
395
396    // Resolve server URL: env > creds > config
397    let server_url = std::env::var("TRACEVAULT_SERVER_URL")
398        .ok()
399        .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
400        .or(config_server_url);
401
402    // Resolve token: env api key > creds token > config api key
403    let token = env_key
404        .or_else(|| creds.map(|c| c.token))
405        .or(config_api_key);
406
407    (server_url, token)
408}