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