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/// One org the authenticated credential belongs to. `org_name` is the org
98/// slug (`orgs.name` server-side) used in URL paths; `display_name` is the
99/// human label. Wire shape of `GET /api/v1/me/orgs`.
100// Full GET /api/v1/me/orgs wire shape; only org_name (the slug) is consumed.
101// Unused fields kept for the contract, allowed like MeResponse::user_id.
102#[derive(Debug, Deserialize)]
103pub struct OrgMembership {
104    #[allow(dead_code)]
105    pub org_id: uuid::Uuid,
106    pub org_name: String,
107    #[allow(dead_code)]
108    pub display_name: Option<String>,
109    #[allow(dead_code)]
110    pub role: String,
111}
112
113#[derive(Debug)]
114pub enum GetMeError {
115    /// 401 — token is missing or invalid.
116    Unauthorized,
117    /// Transport-level failure (DNS, TCP, TLS, timeout).
118    Network(String),
119    /// HTTP ≥ 400 other than 401, or malformed JSON.
120    Server(String),
121}
122
123impl std::fmt::Display for GetMeError {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        match self {
126            Self::Unauthorized => write!(f, "unauthorized (token invalid or expired)"),
127            Self::Network(m) => write!(f, "network error: {m}"),
128            Self::Server(m) => write!(f, "server error: {m}"),
129        }
130    }
131}
132
133impl std::error::Error for GetMeError {}
134
135#[derive(Debug, Serialize)]
136pub struct CiVerifyRequest {
137    pub commits: Vec<String>,
138}
139
140#[derive(Debug, Deserialize)]
141pub struct CiVerifyResponse {
142    pub status: String,
143    pub total_commits: usize,
144    pub registered_commits: usize,
145    pub sealed_commits: usize,
146    pub policy_passed_commits: usize,
147    pub results: Vec<CommitVerifyResult>,
148}
149
150#[derive(Debug, Deserialize)]
151pub struct CommitVerifyResult {
152    pub commit_sha: String,
153    pub status: String,
154    pub registered: bool,
155    pub sealed: bool,
156    pub signature_valid: bool,
157    pub chain_valid: bool,
158    pub policy_results: Vec<CiPolicyResult>,
159}
160
161#[derive(Debug, Deserialize)]
162pub struct CiPolicyResult {
163    pub rule_name: String,
164    pub result: String,
165    pub action: String,
166    pub severity: String,
167    pub details: String,
168}
169
170impl ApiClient {
171    pub fn new(base_url: &str, api_key: Option<&str>) -> Self {
172        Self {
173            base_url: base_url.trim_end_matches('/').to_string(),
174            api_key: api_key.map(String::from),
175            client: reqwest::Client::builder()
176                .timeout(std::time::Duration::from_secs(60))
177                .build()
178                .unwrap_or_default(),
179        }
180    }
181
182    pub async fn register_repo(
183        &self,
184        org_slug: &str,
185        req: RegisterRepoRequest,
186    ) -> Result<RegisterRepoResponse, Box<dyn Error>> {
187        let mut builder = self
188            .client
189            .post(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
190
191        if let Some(key) = &self.api_key {
192            builder = builder.header("Authorization", format!("Bearer {key}"));
193        }
194
195        let resp = builder.json(&req).send().await?;
196
197        if !resp.status().is_success() {
198            let status = resp.status();
199            let body = resp.text().await.unwrap_or_default();
200            return Err(format!("Server returned {status}: {body}").into());
201        }
202
203        Ok(resp.json().await?)
204    }
205
206    pub async fn device_start(&self) -> Result<DeviceAuthResponse, Box<dyn Error>> {
207        let resp = self
208            .client
209            // Send an explicit `Content-Length: 0`. reqwest/hyper omit the header
210            // entirely for a bodyless POST, and strict frontends (e.g. Google
211            // Front End) reject such requests with `411 Length Required`.
212            .post(format!("{}/api/v1/auth/device", self.base_url))
213            .header(reqwest::header::CONTENT_LENGTH, "0")
214            .send()
215            .await?;
216
217        if !resp.status().is_success() {
218            let status = resp.status();
219            let body = resp.text().await.unwrap_or_default();
220            return Err(format!("Server returned {status}: {body}").into());
221        }
222
223        Ok(resp.json().await?)
224    }
225
226    pub async fn device_status(&self, token: &str) -> Result<DeviceStatusResponse, Box<dyn Error>> {
227        let resp = self
228            .client
229            .get(format!(
230                "{}/api/v1/auth/device/{token}/status",
231                self.base_url
232            ))
233            .send()
234            .await?;
235
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
242        Ok(resp.json().await?)
243    }
244
245    pub async fn logout(&self) -> Result<(), Box<dyn Error>> {
246        let mut builder = self
247            .client
248            .post(format!("{}/api/v1/auth/logout", self.base_url));
249        if let Some(key) = &self.api_key {
250            builder = builder.header("Authorization", format!("Bearer {key}"));
251        }
252        // Explicit `Content-Length: 0` (see `device_start`): reqwest/hyper omit it
253        // for a bodyless POST, which strict frontends reject with 411.
254        let resp = builder
255            .header(reqwest::header::CONTENT_LENGTH, "0")
256            .send()
257            .await?;
258        if !resp.status().is_success() {
259            let status = resp.status();
260            let body = resp.text().await.unwrap_or_default();
261            return Err(format!("Server returned {status}: {body}").into());
262        }
263        Ok(())
264    }
265
266    /// GET `{base}{path}` with the bearer token, mapping failures into
267    /// `GetMeError` (401 → `Unauthorized`, transport → `Network`, other
268    /// non-2xx or bad JSON → `Server`). Shared by the credential-scoped GETs
269    /// so auth/error handling lives in one place.
270    async fn authed_get_json<T: serde::de::DeserializeOwned>(
271        &self,
272        path: &str,
273    ) -> Result<T, GetMeError> {
274        let mut builder = self.client.get(format!("{}{}", self.base_url, path));
275        if let Some(key) = &self.api_key {
276            builder = builder.header("Authorization", format!("Bearer {key}"));
277        }
278
279        let resp = builder
280            .send()
281            .await
282            .map_err(|e| GetMeError::Network(e.to_string()))?;
283
284        let status = resp.status();
285        if status == reqwest::StatusCode::UNAUTHORIZED {
286            return Err(GetMeError::Unauthorized);
287        }
288        if !status.is_success() {
289            let body = resp.text().await.unwrap_or_default();
290            return Err(GetMeError::Server(format!("{status}: {body}")));
291        }
292
293        resp.json::<T>()
294            .await
295            .map_err(|e| GetMeError::Server(e.to_string()))
296    }
297
298    /// GET /api/v1/auth/me — validates the bearer token and returns user
299    /// identity. Used by `tracevault status` to distinguish "logged out",
300    /// "expired token", and "server unreachable".
301    pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
302        self.authed_get_json("/api/v1/auth/me").await
303    }
304
305    /// List the orgs the authenticated credential belongs to.
306    /// `GET /api/v1/me/orgs`. For a service-account key this is the service
307    /// user's memberships; for a user session, the user's orgs; for an
308    /// org-scoped key, an empty list.
309    pub async fn list_my_orgs(&self) -> Result<Vec<OrgMembership>, GetMeError> {
310        self.authed_get_json("/api/v1/me/orgs").await
311    }
312
313    pub async fn list_repos(&self, org_slug: &str) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
314        let mut builder = self
315            .client
316            .get(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
317        if let Some(key) = &self.api_key {
318            builder = builder.header("Authorization", format!("Bearer {key}"));
319        }
320
321        let resp = builder.send().await?;
322
323        if !resp.status().is_success() {
324            let status = resp.status();
325            let body = resp.text().await.unwrap_or_default();
326            return Err(format!("Failed to list repos ({status}): {body}").into());
327        }
328
329        let repos: Vec<RepoListItem> = resp.json().await?;
330        Ok(repos)
331    }
332
333    pub async fn get_agent_instructions(
334        &self,
335        org_slug: &str,
336        repo_id: &uuid::Uuid,
337    ) -> Result<AgentInstructionsResponse, Box<dyn Error>> {
338        let mut builder = self.client.get(format!(
339            "{}/api/v1/orgs/{}/repos/{}/policies/agent-instructions",
340            self.base_url, org_slug, repo_id
341        ));
342        if let Some(key) = &self.api_key {
343            builder = builder.header("Authorization", format!("Bearer {key}"));
344        }
345
346        let resp = builder.send().await?;
347        if !resp.status().is_success() {
348            let status = resp.status();
349            let body = resp.text().await.unwrap_or_default();
350            return Err(format!("Failed to fetch agent instructions ({status}): {body}").into());
351        }
352        Ok(resp.json().await?)
353    }
354
355    pub async fn verify_commits(
356        &self,
357        org_slug: &str,
358        repo_id: &uuid::Uuid,
359        req: CiVerifyRequest,
360    ) -> Result<CiVerifyResponse, Box<dyn Error>> {
361        let mut builder = self.client.post(format!(
362            "{}/api/v1/orgs/{}/repos/{}/ci/verify",
363            self.base_url, org_slug, repo_id
364        ));
365        if let Some(key) = &self.api_key {
366            builder = builder.header("Authorization", format!("Bearer {key}"));
367        }
368
369        let resp = builder.json(&req).send().await?;
370
371        if !resp.status().is_success() {
372            let status = resp.status();
373            let body = resp.text().await.unwrap_or_default();
374            return Err(format!("CI verify failed ({status}): {body}").into());
375        }
376
377        Ok(resp.json().await?)
378    }
379
380    pub async fn push_commit(
381        &self,
382        org_slug: &str,
383        repo_id: &str,
384        req: &tracevault_protocol::streaming::CommitPushRequest,
385    ) -> Result<tracevault_protocol::streaming::CommitPushResponse, Box<dyn Error>> {
386        let mut builder = self.client.post(format!(
387            "{}/api/v1/orgs/{}/repos/{}/commits",
388            self.base_url, org_slug, repo_id
389        ));
390        if let Some(key) = &self.api_key {
391            builder = builder.header("Authorization", format!("Bearer {key}"));
392        }
393        let resp = builder.json(req).send().await?;
394        if !resp.status().is_success() {
395            let status = resp.status();
396            let body = resp.text().await.unwrap_or_default();
397            return Err(format!("Commit push failed ({status}): {body}").into());
398        }
399        Ok(resp.json().await?)
400    }
401
402    pub async fn stream_event(
403        &self,
404        org_slug: &str,
405        repo_id: &str,
406        req: &tracevault_protocol::streaming::StreamEventRequest,
407    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
408        let mut builder = self.client.post(format!(
409            "{}/api/v1/orgs/{}/repos/{}/stream",
410            self.base_url, org_slug, repo_id
411        ));
412        if let Some(key) = &self.api_key {
413            builder = builder.header("Authorization", format!("Bearer {key}"));
414        }
415        let resp = builder.json(req).send().await?;
416        if !resp.status().is_success() {
417            let status = resp.status();
418            let body = resp.text().await.unwrap_or_default();
419            return Err(format!("Stream failed ({status}): {body}").into());
420        }
421        Ok(resp.json().await?)
422    }
423
424    pub async fn check_policies(
425        &self,
426        org_slug: &str,
427        repo_id: &uuid::Uuid,
428        req: CheckPoliciesRequest,
429    ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
430        let mut builder = self.client.post(format!(
431            "{}/api/v1/orgs/{}/repos/{}/policies/check",
432            self.base_url, org_slug, repo_id
433        ));
434        if let Some(key) = &self.api_key {
435            builder = builder.header("Authorization", format!("Bearer {key}"));
436        }
437
438        let resp = builder.json(&req).send().await?;
439
440        if !resp.status().is_success() {
441            let status = resp.status();
442            let body = resp.text().await.unwrap_or_default();
443            return Err(format!("Policy check failed ({status}): {body}").into());
444        }
445
446        let result: CheckPoliciesResponse = resp.json().await?;
447        Ok(result)
448    }
449
450    /// Resolve a git remote URL to a registered repo id within `org_slug`.
451    /// `Ok(None)` when the server has no matching repo (404). Used by
452    /// workspace/detached mode, which has no pinned repo_id in config.
453    pub async fn resolve_repo(
454        &self,
455        org_slug: &str,
456        git_url: &str,
457    ) -> Result<Option<uuid::Uuid>, Box<dyn std::error::Error>> {
458        let mut url = Url::parse(&format!(
459            "{}/api/v1/orgs/{}/repos/resolve",
460            self.base_url, org_slug
461        ))?;
462        url.query_pairs_mut().append_pair("git_url", git_url);
463
464        let mut builder = self.client.get(url);
465        if let Some(key) = &self.api_key {
466            builder = builder.header("Authorization", format!("Bearer {key}"));
467        }
468        let resp = builder.send().await?;
469        if resp.status() == reqwest::StatusCode::NOT_FOUND {
470            return Ok(None);
471        }
472        if !resp.status().is_success() {
473            let status = resp.status();
474            let body = resp.text().await.unwrap_or_default();
475            return Err(format!("resolve_repo failed ({status}): {body}").into());
476        }
477        let parsed: ResolveRepoResponse = resp.json().await?;
478        Ok(Some(parsed.repo_id))
479    }
480}
481
482/// Resolve server URL and auth token from multiple sources.
483/// Priority: env var > credentials file > project config.toml
484/// Returns (server_url, auth_token).
485pub fn resolve_credentials(project_root: &Path) -> (Option<String>, Option<String>) {
486    use crate::credentials::Credentials;
487
488    // 1. Env var API key
489    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
490
491    // 2. Credentials file
492    let creds = Credentials::load();
493
494    // 3. Project config
495    let config_path = crate::config::TracevaultConfig::config_path(project_root);
496    let config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
497
498    let config_server_url = config_content
499        .lines()
500        .find(|l| l.starts_with("server_url"))
501        .and_then(|l| l.split('=').nth(1))
502        .map(|s| s.trim().trim_matches('"').to_string());
503
504    let config_api_key = config_content
505        .lines()
506        .find(|l| l.starts_with("api_key"))
507        .and_then(|l| l.split('=').nth(1))
508        .map(|s| s.trim().trim_matches('"').to_string());
509
510    // Resolve server URL: env > creds > config
511    let server_url = std::env::var("TRACEVAULT_SERVER_URL")
512        .ok()
513        .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
514        .or(config_server_url);
515
516    // Resolve token: env api key > creds token > config api key
517    let token = env_key
518        .or_else(|| creds.map(|c| c.token))
519        .or(config_api_key);
520
521    (server_url, token)
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527
528    #[test]
529    fn org_membership_deserializes_and_exposes_slug() {
530        let body = r#"[
531            {"org_id":"00000000-0000-0000-0000-000000000001","org_name":"acme","display_name":"Acme Inc","role":"admin"},
532            {"org_id":"00000000-0000-0000-0000-000000000002","org_name":"globex","display_name":null,"role":"member"}
533        ]"#;
534        let orgs: Vec<OrgMembership> = serde_json::from_str(body).unwrap();
535        assert_eq!(orgs.len(), 2);
536        // org_name is the slug used in URL paths.
537        assert_eq!(orgs[0].org_name, "acme");
538        assert_eq!(orgs[1].org_name, "globex");
539        assert_eq!(orgs[1].display_name, None);
540    }
541}