securegit 0.8.5

Zero-trust git replacement with 12 built-in security scanners, LLM redteam bridge, universal undo, durable backups, and a 50-tool MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use super::types::*;
use super::{Platform, PlatformHost};
use crate::auth::SecureString;
use anyhow::{bail, Context, Result};
use async_trait::async_trait;

pub struct GitLabClient {
    token: SecureString,
    owner: String,
    repo: String,
    client: reqwest::Client,
    api_base: String,
}

impl GitLabClient {
    pub fn new(token: SecureString, owner: String, repo: String) -> Self {
        Self::new_with_base(token, owner, repo, "https://gitlab.com/api/v4".to_string())
    }

    pub fn new_with_base(
        token: SecureString,
        owner: String,
        repo: String,
        api_base: String,
    ) -> Self {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .user_agent("securegit")
            .build()
            .expect("Failed to create HTTP client");

        Self {
            token,
            owner,
            repo,
            client,
            api_base,
        }
    }

    fn auth_headers(&self) -> reqwest::header::HeaderMap {
        let mut headers = reqwest::header::HeaderMap::new();
        if let Ok(val) = reqwest::header::HeaderValue::from_str(self.token.as_str()) {
            headers.insert("PRIVATE-TOKEN", val);
        }
        headers
    }

    fn project_id(&self) -> String {
        format!("{}%2F{}", urlencoding(&self.owner), urlencoding(&self.repo))
    }

    fn project_url(&self) -> String {
        format!("{}/projects/{}", self.api_base, self.project_id())
    }
}

#[async_trait]
impl Platform for GitLabClient {
    fn host(&self) -> PlatformHost {
        PlatformHost::GitLab
    }

    async fn create_pull_request(&self, pr: &CreatePR) -> Result<PullRequest> {
        let url = format!("{}/merge_requests", self.project_url());
        let body = serde_json::json!({
            "title": pr.title,
            "description": pr.body,
            "source_branch": pr.head,
            "target_branch": pr.base,
        });

        let resp = self
            .client
            .post(&url)
            .headers(self.auth_headers())
            .json(&body)
            .send()
            .await
            .context("Failed to create merge request")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            bail!("GitLab API error ({}): {}", status, text);
        }

        let d: serde_json::Value = resp.json().await?;
        Ok(PullRequest {
            number: d["iid"].as_u64().unwrap_or(0),
            title: d["title"].as_str().unwrap_or("").to_string(),
            state: d["state"].as_str().unwrap_or("opened").to_string(),
            html_url: d["web_url"].as_str().unwrap_or("").to_string(),
            head_ref: d["source_branch"].as_str().unwrap_or("").to_string(),
            base_ref: d["target_branch"].as_str().unwrap_or("").to_string(),
            draft: d["draft"].as_bool().unwrap_or(false),
            user: d["author"]["username"].as_str().unwrap_or("").to_string(),
            created_at: d["created_at"].as_str().unwrap_or("").to_string(),
        })
    }

    async fn list_pull_requests(&self, state: &str) -> Result<Vec<PullRequest>> {
        let gl_state = match state {
            "open" => "opened",
            "closed" => "closed",
            "all" => "all",
            other => other,
        };
        let url = format!(
            "{}/merge_requests?state={}&per_page=30",
            self.project_url(),
            gl_state
        );
        let resp = self
            .client
            .get(&url)
            .headers(self.auth_headers())
            .send()
            .await
            .context("Failed to list merge requests")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            bail!("GitLab API error ({}): {}", status, text);
        }

        let data: Vec<serde_json::Value> = resp.json().await?;
        Ok(data
            .into_iter()
            .map(|d| PullRequest {
                number: d["iid"].as_u64().unwrap_or(0),
                title: d["title"].as_str().unwrap_or("").to_string(),
                state: d["state"].as_str().unwrap_or("").to_string(),
                html_url: d["web_url"].as_str().unwrap_or("").to_string(),
                head_ref: d["source_branch"].as_str().unwrap_or("").to_string(),
                base_ref: d["target_branch"].as_str().unwrap_or("").to_string(),
                draft: d["draft"].as_bool().unwrap_or(false),
                user: d["author"]["username"].as_str().unwrap_or("").to_string(),
                created_at: d["created_at"].as_str().unwrap_or("").to_string(),
            })
            .collect())
    }

    async fn get_pull_request(&self, number: u64) -> Result<PullRequest> {
        let url = format!("{}/merge_requests/{}", self.project_url(), number);
        let resp = self
            .client
            .get(&url)
            .headers(self.auth_headers())
            .send()
            .await
            .context("Failed to get merge request")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            bail!("GitLab API error ({}): {}", status, text);
        }

        let d: serde_json::Value = resp.json().await?;
        Ok(PullRequest {
            number: d["iid"].as_u64().unwrap_or(0),
            title: d["title"].as_str().unwrap_or("").to_string(),
            state: d["state"].as_str().unwrap_or("").to_string(),
            html_url: d["web_url"].as_str().unwrap_or("").to_string(),
            head_ref: d["source_branch"].as_str().unwrap_or("").to_string(),
            base_ref: d["target_branch"].as_str().unwrap_or("").to_string(),
            draft: d["draft"].as_bool().unwrap_or(false),
            user: d["author"]["username"].as_str().unwrap_or("").to_string(),
            created_at: d["created_at"].as_str().unwrap_or("").to_string(),
        })
    }

    async fn create_issue(&self, issue: &CreateIssue) -> Result<Issue> {
        let url = format!("{}/issues", self.project_url());
        let body = serde_json::json!({
            "title": issue.title,
            "description": issue.body,
            "labels": issue.labels.join(","),
        });

        let resp = self
            .client
            .post(&url)
            .headers(self.auth_headers())
            .json(&body)
            .send()
            .await
            .context("Failed to create issue")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            bail!("GitLab API error ({}): {}", status, text);
        }

        let d: serde_json::Value = resp.json().await?;
        Ok(Issue {
            number: d["iid"].as_u64().unwrap_or(0),
            title: d["title"].as_str().unwrap_or("").to_string(),
            state: d["state"].as_str().unwrap_or("opened").to_string(),
            html_url: d["web_url"].as_str().unwrap_or("").to_string(),
        })
    }

    async fn search_issues(&self, query: &str) -> Result<Vec<Issue>> {
        let url = format!(
            "{}/issues?search={}&per_page=20",
            self.project_url(),
            urlencoding(query)
        );
        let resp = self
            .client
            .get(&url)
            .headers(self.auth_headers())
            .send()
            .await
            .context("Failed to search issues")?;

        if !resp.status().is_success() {
            return Ok(vec![]);
        }

        let data: Vec<serde_json::Value> = resp.json().await?;
        Ok(data
            .into_iter()
            .map(|d| Issue {
                number: d["iid"].as_u64().unwrap_or(0),
                title: d["title"].as_str().unwrap_or("").to_string(),
                state: d["state"].as_str().unwrap_or("").to_string(),
                html_url: d["web_url"].as_str().unwrap_or("").to_string(),
            })
            .collect())
    }

    async fn add_labels(&self, number: u64, labels: &[String]) -> Result<()> {
        let url = format!("{}/merge_requests/{}", self.project_url(), number);
        let body = serde_json::json!({
            "add_labels": labels.join(","),
        });

        let resp = self
            .client
            .put(&url)
            .headers(self.auth_headers())
            .json(&body)
            .send()
            .await
            .context("Failed to add labels")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            bail!("GitLab API error adding labels ({}): {}", status, text);
        }
        Ok(())
    }

    async fn create_release(&self, release: &CreateRelease) -> Result<Release> {
        let url = format!("{}/releases", self.project_url());
        let body = serde_json::json!({
            "tag_name": release.tag_name,
            "name": release.name,
            "description": release.body,
        });

        let resp = self
            .client
            .post(&url)
            .headers(self.auth_headers())
            .json(&body)
            .send()
            .await
            .context("Failed to create release")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            bail!("GitLab API error ({}): {}", status, text);
        }

        let d: serde_json::Value = resp.json().await?;
        Ok(Release {
            id: 0, // GitLab doesn't return numeric ID for releases
            tag_name: d["tag_name"].as_str().unwrap_or("").to_string(),
            name: d["name"].as_str().unwrap_or("").to_string(),
            html_url: d["_links"]["self"].as_str().unwrap_or("").to_string(),
            upload_url: format!(
                "{}/releases/{}/assets/links",
                self.project_url(),
                urlencoding(&release.tag_name)
            ),
            draft: false,
            prerelease: false,
            created_at: d["created_at"].as_str().unwrap_or("").to_string(),
        })
    }

    async fn list_releases(&self, count: usize) -> Result<Vec<Release>> {
        let url = format!("{}/releases?per_page={}", self.project_url(), count);
        let resp = self
            .client
            .get(&url)
            .headers(self.auth_headers())
            .send()
            .await
            .context("Failed to list releases")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            bail!("GitLab API error ({}): {}", status, text);
        }

        let data: Vec<serde_json::Value> = resp.json().await?;
        Ok(data
            .into_iter()
            .map(|d| Release {
                id: 0,
                tag_name: d["tag_name"].as_str().unwrap_or("").to_string(),
                name: d["name"].as_str().unwrap_or("").to_string(),
                html_url: d["_links"]["self"].as_str().unwrap_or("").to_string(),
                upload_url: String::new(),
                draft: false,
                prerelease: false,
                created_at: d["created_at"].as_str().unwrap_or("").to_string(),
            })
            .collect())
    }

    async fn upload_release_asset(
        &self,
        _upload_url: &str,
        name: &str,
        _content_type: &str,
        _data: Vec<u8>,
    ) -> Result<()> {
        // GitLab uses a link-based asset system rather than direct uploads.
        // For now, log the limitation.
        tracing::warn!(
            "GitLab release asset upload not yet supported for '{}'. Use the GitLab UI to attach files.",
            name
        );
        Ok(())
    }

    async fn get_check_runs(&self, ref_name: &str) -> Result<CombinedStatus> {
        // GitLab uses pipelines instead of check runs
        let url = format!(
            "{}/pipelines?ref={}&per_page=5",
            self.project_url(),
            urlencoding(ref_name)
        );
        let resp = self
            .client
            .get(&url)
            .headers(self.auth_headers())
            .send()
            .await
            .context("Failed to get pipelines")?;

        if !resp.status().is_success() {
            return Ok(CombinedStatus {
                state: "unknown".to_string(),
                total_count: 0,
                check_runs: vec![],
            });
        }

        let pipelines: Vec<serde_json::Value> = resp.json().await?;
        let mut runs = Vec::new();

        for p in &pipelines {
            let pipeline_id = p["id"].as_u64().unwrap_or(0);
            // Get jobs for the most recent pipeline
            if pipeline_id > 0 {
                let jobs_url = format!("{}/pipelines/{}/jobs", self.project_url(), pipeline_id);
                if let Ok(jobs_resp) = self
                    .client
                    .get(&jobs_url)
                    .headers(self.auth_headers())
                    .send()
                    .await
                {
                    if let Ok(jobs) = jobs_resp.json::<Vec<serde_json::Value>>().await {
                        for j in jobs {
                            runs.push(CheckRun {
                                name: j["name"].as_str().unwrap_or("").to_string(),
                                status: j["status"].as_str().unwrap_or("").to_string(),
                                conclusion: j["status"].as_str().map(|s| {
                                    match s {
                                        "success" => "success",
                                        "failed" => "failure",
                                        "canceled" => "cancelled",
                                        _ => s,
                                    }
                                    .to_string()
                                }),
                                html_url: j["web_url"].as_str().map(|s| s.to_string()),
                                started_at: j["started_at"].as_str().map(|s| s.to_string()),
                                completed_at: j["finished_at"].as_str().map(|s| s.to_string()),
                            });
                        }
                    }
                }
                break; // Only fetch jobs for the most recent pipeline
            }
        }

        let overall_state = if let Some(p) = pipelines.first() {
            p["status"].as_str().unwrap_or("pending").to_string()
        } else {
            "no_pipelines".to_string()
        };

        Ok(CombinedStatus {
            state: overall_state,
            total_count: runs.len() as u64,
            check_runs: runs,
        })
    }

    async fn get_authenticated_user(&self) -> Result<String> {
        let url = format!("{}/user", self.api_base);
        let resp = self
            .client
            .get(&url)
            .headers(self.auth_headers())
            .send()
            .await
            .context("Failed to get authenticated user")?;

        if !resp.status().is_success() {
            bail!("Authentication failed — invalid or expired token");
        }

        let data: serde_json::Value = resp.json().await?;
        Ok(data["username"].as_str().unwrap_or("unknown").to_string())
    }

    async fn create_repo(&self, repo: &CreateRepo) -> Result<Repository> {
        let visibility = if repo.private { "private" } else { "public" };

        let mut body = serde_json::json!({
            "name": repo.name,
            "visibility": visibility,
        });

        if let Some(ref desc) = repo.description {
            body["description"] = serde_json::Value::String(desc.clone());
        }

        // Resolve namespace (group) to namespace_id if provided
        if let Some(ref namespace) = repo.namespace {
            let ns_url = format!(
                "{}/namespaces?search={}",
                self.api_base,
                urlencoding(namespace)
            );
            let ns_resp = self
                .client
                .get(&ns_url)
                .headers(self.auth_headers())
                .send()
                .await
                .context("Failed to search namespaces")?;

            if ns_resp.status().is_success() {
                let namespaces: Vec<serde_json::Value> = ns_resp.json().await?;
                // Find exact match by full_path
                let ns_id = namespaces
                    .iter()
                    .find(|ns| ns["full_path"].as_str() == Some(namespace))
                    .or_else(|| namespaces.first())
                    .and_then(|ns| ns["id"].as_u64());

                if let Some(id) = ns_id {
                    body["namespace_id"] = serde_json::Value::Number(id.into());
                } else {
                    bail!(
                        "Namespace '{}' not found. Check the group path and your permissions.",
                        namespace
                    );
                }
            }
        }

        let url = format!("{}/projects", self.api_base);
        let resp = self
            .client
            .post(&url)
            .headers(self.auth_headers())
            .json(&body)
            .send()
            .await
            .context("Failed to create project")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            bail!("GitLab API error ({}): {}", status, text);
        }

        let d: serde_json::Value = resp.json().await?;
        Ok(Repository {
            id: d["id"].as_u64().unwrap_or(0),
            name: d["name"].as_str().unwrap_or("").to_string(),
            full_name: d["path_with_namespace"]
                .as_str()
                .unwrap_or("")
                .to_string(),
            web_url: d["web_url"].as_str().unwrap_or("").to_string(),
            clone_url_http: d["http_url_to_repo"].as_str().unwrap_or("").to_string(),
            clone_url_ssh: d["ssh_url_to_repo"].as_str().map(|s| s.to_string()),
            private: d["visibility"].as_str() == Some("private"),
        })
    }
}

fn urlencoding(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => result.push(c),
            ' ' => result.push_str("%20"),
            '/' => result.push_str("%2F"),
            _ => {
                for b in c.to_string().as_bytes() {
                    result.push_str(&format!("%{:02X}", b));
                }
            }
        }
    }
    result
}