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
use crate::auth::{oauth, store, SecureString};
use crate::cli::args::AuthCommands;
use crate::cli::UI;
use crate::platform;
use crate::platform::server_registry::ServerRegistry;
use anyhow::Result;
use std::collections::HashSet;

pub async fn execute(action: AuthCommands, ui: &UI) -> Result<()> {
    match action {
        AuthCommands::Login {
            provider,
            token,
            host,
        } => login(provider, token, host, ui).await,
        AuthCommands::Logout { provider } => logout(provider, ui),
        AuthCommands::Status => status(ui).await,
    }
}

async fn login(
    provider: Option<String>,
    token: Option<String>,
    custom_host: Option<String>,
    ui: &UI,
) -> Result<()> {
    let provider_name = provider.as_deref().unwrap_or("github");

    // If a custom host is provided, use it directly for self-hosted instances
    if let Some(ref host_url) = custom_host {
        return login_custom_host(provider_name, host_url, token, ui).await;
    }

    let host = match provider_name {
        "github" | "gh" => "github.com",
        "gitlab" | "gl" => "gitlab.com",
        other => {
            anyhow::bail!("Unknown provider: {}. Use 'github' or 'gitlab'.", other);
        }
    };

    ui.header("SecureGit Authentication");
    ui.blank();
    ui.field("Provider", provider_name);

    if let Some(token_str) = token {
        // Direct token input
        ui.field("Method", "Token");
        ui.blank();

        let secure_token = SecureString::from_string(token_str);

        // Validate the token
        let spinner = ui.spinner("Validating token...");
        let user = validate_token(host, &secure_token).await?;
        ui.finish_progress(&spinner, "Token validated");

        store::store_token(host, &secure_token)?;

        ui.blank();
        ui.success(format!("Authenticated as {}", user));
        ui.blank();
        ui.field("User", &user);
        ui.field("Stored", "~/.config/securegit/credentials.json");
        ui.blank();
    } else {
        // Device flow OAuth
        ui.field("Method", "Device Flow");
        ui.blank();

        let result = match host {
            "github.com" => {
                oauth::github_device_flow(
                    |code, uri| {
                        ui.blank();
                        ui.info(format!("Open {}", uri));
                        ui.info(format!("Enter code: {}", code));
                        ui.blank();
                    },
                    || {},
                )
                .await?
            }
            "gitlab.com" => {
                oauth::gitlab_device_flow(
                    |code, uri| {
                        ui.blank();
                        ui.info(format!("Open {}", uri));
                        ui.info(format!("Enter code: {}", code));
                        ui.blank();
                    },
                    || {},
                )
                .await?
            }
            _ => unreachable!(),
        };

        store::store_token(host, &result.token)?;

        ui.blank();
        ui.success(format!("Authenticated as {}", result.user));
        ui.blank();
        ui.field("User", &result.user);
        ui.field("Scope", &result.scope);
        ui.field("Stored", "~/.config/securegit/credentials.json");
        ui.blank();
    }

    Ok(())
}

async fn login_custom_host(
    provider_name: &str,
    host_url: &str,
    token: Option<String>,
    ui: &UI,
) -> Result<()> {
    ui.header("SecureGit Authentication (Self-Hosted)");
    ui.blank();
    ui.field("Provider", provider_name);
    ui.field("Host", host_url);

    let token_str = token.ok_or_else(|| {
        anyhow::anyhow!("--token is required for self-hosted instances (no device flow support)")
    })?;

    ui.field("Method", "Token");
    ui.blank();

    let secure_token = SecureString::from_string(token_str);

    let spinner = ui.spinner("Validating token...");
    let user = validate_token_generic(host_url, provider_name, &secure_token).await?;
    ui.finish_progress(&spinner, "Token validated");

    // Store using the host URL as the key
    store::store_token(host_url, &secure_token)?;

    ui.blank();
    ui.success(format!("Authenticated as {}", user));
    ui.blank();
    ui.field("User", &user);
    ui.field("Stored", "~/.config/securegit/credentials.json");
    ui.blank();

    Ok(())
}

fn logout(provider: Option<String>, ui: &UI) -> Result<()> {
    ui.header("SecureGit Logout");
    ui.blank();

    if let Some(provider_name) = provider {
        let host = match provider_name.as_str() {
            "github" | "gh" => "github.com",
            "gitlab" | "gl" => "gitlab.com",
            other => {
                anyhow::bail!("Unknown provider: {}", other);
            }
        };
        store::delete_token(host)?;
        ui.status_item(true, format!("Removed credentials for {}", host));
    } else {
        store::delete_all_tokens()?;
        ui.status_item(true, "Removed all stored credentials");
    }

    ui.blank();
    Ok(())
}

async fn status(ui: &UI) -> Result<()> {
    ui.header("Authentication Status");
    ui.blank();

    // Build a dynamic set of hosts: defaults + stored credentials + registered servers
    let mut hosts: Vec<String> = vec!["github.com".to_string(), "gitlab.com".to_string()];
    let mut seen: HashSet<String> = hosts.iter().cloned().collect();

    // Add hosts from stored credentials
    for h in store::list_stored_hosts() {
        if seen.insert(h.clone()) {
            hosts.push(h);
        }
    }

    // Load registered servers for display below and to add their API URL hosts
    let registry = ServerRegistry::load().ok();
    if let Some(ref reg) = registry {
        for server in &reg.servers {
            if let Ok(url) = url::Url::parse(&server.api_url) {
                if let Some(h) = url.host_str() {
                    let h = h.to_string();
                    if seen.insert(h.clone()) {
                        hosts.push(h);
                    }
                }
            }
        }
    }

    let mut any_authenticated = false;

    for host in &hosts {
        let provider = match host.as_str() {
            "github.com" => "GitHub".to_string(),
            "gitlab.com" => "GitLab".to_string(),
            other => {
                // Check if this host belongs to a registered server
                if let Some(ref reg) = registry {
                    reg.servers
                        .iter()
                        .find(|s| {
                            url::Url::parse(&s.api_url)
                                .ok()
                                .and_then(|u| u.host_str().map(|h| h == other))
                                .unwrap_or(false)
                        })
                        .map(|s| s.name.clone())
                        .unwrap_or_else(|| other.to_string())
                } else {
                    other.to_string()
                }
            }
        };

        // Check env vars first
        if let Some(token) = crate::auth::token_for_host(host) {
            let source = if store::get_token(host).is_some() {
                "stored credentials"
            } else {
                "environment variable"
            };

            // Try to get the username — use generic validation for non-standard hosts
            let user = match host.as_str() {
                "github.com" | "gitlab.com" => validate_token(host, &token)
                    .await
                    .unwrap_or_else(|_| "unknown".to_string()),
                other => {
                    // Determine platform heuristically or from registry
                    let platform_str = if let Some(ref reg) = registry {
                        reg.servers
                            .iter()
                            .find(|s| {
                                url::Url::parse(&s.api_url)
                                    .ok()
                                    .and_then(|u| u.host_str().map(|h| h == other))
                                    .unwrap_or(false)
                            })
                            .map(|s| s.platform.to_string())
                            .unwrap_or_else(|| {
                                if other.contains("github") {
                                    "github".to_string()
                                } else {
                                    "gitlab".to_string()
                                }
                            })
                    } else if other.contains("github") {
                        "github".to_string()
                    } else {
                        "gitlab".to_string()
                    };
                    // Find the API URL for this host from the registry
                    let api_url = if let Some(ref reg) = registry {
                        reg.servers
                            .iter()
                            .find(|s| {
                                url::Url::parse(&s.api_url)
                                    .ok()
                                    .and_then(|u| u.host_str().map(|h| h == other))
                                    .unwrap_or(false)
                            })
                            .map(|s| s.api_url.clone())
                    } else {
                        None
                    };
                    if let Some(api_url) = api_url {
                        validate_token_generic(&api_url, &platform_str, &token)
                            .await
                            .unwrap_or_else(|_| "unknown".to_string())
                    } else {
                        "authenticated".to_string()
                    }
                }
            };

            ui.field(&provider, format!("{} (via {})", user, source));
            any_authenticated = true;
        } else {
            ui.field(&provider, "not authenticated");
        }
    }

    // Show registered servers
    if let Some(ref reg) = registry {
        if !reg.servers.is_empty() {
            ui.blank();
            ui.field("Servers", "");
            for server in &reg.servers {
                let auth_status = if crate::auth::token_for_server(server).is_some() {
                    "authenticated"
                } else {
                    "not authenticated"
                };
                ui.field(
                    &format!("  {}", server.name),
                    format!("{} ({})", auth_status, server.api_url),
                );
            }
        }
    }

    // Also check for current repo remote
    if let Ok(remote) = platform::detect_remote(&std::path::PathBuf::from(".")) {
        ui.blank();
        ui.field(
            "Current repo",
            format!("{} ({}/{})", remote.host, remote.owner, remote.repo),
        );
    }

    if !any_authenticated {
        ui.blank();
        ui.info("Run 'securegit auth login' to authenticate");
    }

    ui.blank();
    Ok(())
}

async fn validate_token(host: &str, token: &SecureString) -> Result<String> {
    match host {
        "github.com" => {
            let client = reqwest::Client::new();
            let resp = client
                .get("https://api.github.com/user")
                .header("Authorization", format!("Bearer {}", token.as_str()))
                .header("User-Agent", "securegit")
                .send()
                .await?;

            if !resp.status().is_success() {
                anyhow::bail!("Invalid or expired GitHub token");
            }
            let data: serde_json::Value = resp.json().await?;
            Ok(data["login"].as_str().unwrap_or("unknown").to_string())
        }
        "gitlab.com" => {
            let client = reqwest::Client::new();
            let resp = client
                .get("https://gitlab.com/api/v4/user")
                .header("PRIVATE-TOKEN", token.as_str())
                .send()
                .await?;

            if !resp.status().is_success() {
                anyhow::bail!("Invalid or expired GitLab token");
            }
            let data: serde_json::Value = resp.json().await?;
            Ok(data["username"].as_str().unwrap_or("unknown").to_string())
        }
        _ => anyhow::bail!("Unknown host: {}", host),
    }
}

/// Validate a token against a self-hosted instance.
/// Determines the auth style from the provider name.
async fn validate_token_generic(
    api_url: &str,
    provider: &str,
    token: &SecureString,
) -> Result<String> {
    let client = reqwest::Client::builder()
        .user_agent("securegit")
        .timeout(std::time::Duration::from_secs(15))
        .build()?;

    // Strip trailing /api/v4 or /api/v3 to build user endpoint
    let base = api_url.trim_end_matches('/');

    match provider.to_lowercase().as_str() {
        "github" | "gh" => {
            let url = format!("{}/user", base);
            let resp = client
                .get(&url)
                .header("Authorization", format!("Bearer {}", token.as_str()))
                .send()
                .await?;

            if !resp.status().is_success() {
                anyhow::bail!("Invalid or expired token for {}", api_url);
            }
            let data: serde_json::Value = resp.json().await?;
            Ok(data["login"].as_str().unwrap_or("unknown").to_string())
        }
        "gitlab" | "gl" => {
            let url = format!("{}/user", base);
            let resp = client
                .get(&url)
                .header("PRIVATE-TOKEN", token.as_str())
                .send()
                .await?;

            if !resp.status().is_success() {
                anyhow::bail!("Invalid or expired token for {}", api_url);
            }
            let data: serde_json::Value = resp.json().await?;
            Ok(data["username"].as_str().unwrap_or("unknown").to_string())
        }
        other => anyhow::bail!("Unknown provider '{}' for custom host", other),
    }
}