gitorii 0.7.2

A human-first Git client with simplified commands, snapshots, multi-platform mirrors and built-in secret scanning
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
537
538
539
540
541
//! Credential storage for torii — both the gitorii.com cloud API key
//! and the per-platform tokens (GitHub, GitLab, Gitea, Forgejo,
//! Codeberg, crates.io) that the HTTPS transport and platform APIs use.
//!
//! Storage layout (`~/.config/torii/auth.toml`, chmod 600 on Unix):
//!
//! ```toml
//! [cloud]
//! key = "gitorii_sk_…"
//! endpoint = "https://api.gitorii.com"
//!
//! [tokens]
//! github = "ghp_…"
//! gitlab = "glpat-…"
//! gitea = "…"
//! forgejo = "…"
//! codeberg = "…"
//! cargo = "cio_…"
//! ```
//!
//! For backwards compatibility we also read the legacy formats:
//!
//! - `auth.toml` with `key = …` / `endpoint = …` at the top level (the
//!   pre-0.7.1 cloud-only format) — auto-rewrites to the new sectioned
//!   format on the next save.
//! - `config.toml`'s `[auth]` block (where platform tokens used to live)
//!   — also auto-migrated to `auth.toml [tokens]` on the next mutating
//!   call.
//!
//! Token precedence (resolved by [`resolve_token`]):
//!
//! 1. Provider-specific env var (`GITHUB_TOKEN`/`GH_TOKEN`,
//!    `GITLAB_TOKEN`, `CARGO_REGISTRY_TOKEN`, …)
//! 2. Generic env var `TORII_HTTPS_TOKEN`
//! 3. Local repo config (`<repo>/.torii/auth.toml`, same schema as
//!    global)
//! 4. Global config (`~/.config/torii/auth.toml`)
//!
//! Env var `TORII_API_KEY` overrides the cloud key the same way.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::error::{Result, ToriiError};

const CLOUD_ENV_VAR: &str = "TORII_API_KEY";
const FILE_NAME: &str = "auth.toml";

// -- Public types -----------------------------------------------------------

#[derive(Debug, Clone, Default)]
pub struct ApiKey {
    pub key: String,
    pub endpoint: String,
}

/// Every credential torii knows about, in one struct. `tokens` is a
/// map rather than fixed fields so `auth.toml` can keep older or
/// newer entries without parser breakage when we add providers.
#[derive(Debug, Clone, Default)]
pub struct AuthStore {
    pub cloud: Option<ApiKey>,
    pub tokens: BTreeMap<String, String>,
}

/// Recognised provider names. The CLI accepts these; readers ask by
/// the same string. Add new entries here only — every other module
/// looks them up by name.
pub const PROVIDERS: &[&str] = &[
    "github",
    "gitlab",
    "gitea",
    "forgejo",
    "codeberg",
    "bitbucket",
    "sourcehut",
    "cargo",
];

// -- Default endpoint for cloud --------------------------------------------

pub fn default_endpoint() -> String {
    std::env::var("TORII_API_ENDPOINT")
        .unwrap_or_else(|_| "https://api.gitorii.com".to_string())
}

// -- Paths -----------------------------------------------------------------

fn global_path() -> Option<PathBuf> {
    dirs::config_dir().map(|d| d.join("torii").join(FILE_NAME))
}

fn local_path<P: AsRef<Path>>(repo_path: P) -> PathBuf {
    repo_path.as_ref().join(".torii").join(FILE_NAME)
}

// -- Load -------------------------------------------------------------------

/// Read the cloud API key (env wins).
pub fn load() -> Option<ApiKey> {
    if let Ok(env_key) = std::env::var(CLOUD_ENV_VAR) {
        if !env_key.is_empty() {
            return Some(ApiKey {
                key: env_key,
                endpoint: default_endpoint(),
            });
        }
    }
    load_global().cloud
}

/// Read the whole global store from disk (no env override applied —
/// that's [`load`] / [`resolve_token`]'s job).
pub fn load_global() -> AuthStore {
    let Some(path) = global_path() else {
        return AuthStore::default();
    };
    if !path.exists() {
        // Fallback: try migrating the legacy `[auth]` block from
        // `config.toml` so the user doesn't lose tokens after upgrade.
        return migrate_from_config_toml().unwrap_or_default();
    }
    let text = match fs::read_to_string(&path) {
        Ok(t) => t,
        Err(_) => return AuthStore::default(),
    };
    parse(&text)
}

/// Read a local (per-repo) store. Returns empty if the repo has no
/// `.torii/auth.toml`. **Never** falls back to global — that's the
/// merge step's job ([`resolve_token`]).
pub fn load_local_raw<P: AsRef<Path>>(repo_path: P) -> AuthStore {
    let path = local_path(repo_path);
    if !path.exists() {
        return AuthStore::default();
    }
    let text = match fs::read_to_string(&path) {
        Ok(t) => t,
        Err(_) => return AuthStore::default(),
    };
    parse(&text)
}

// -- Save -------------------------------------------------------------------

/// Persist a store to disk with chmod 600 on Unix.
fn save_to(path: &Path, store: &AuthStore) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|e| ToriiError::InvalidConfig(format!("create dir: {}", e)))?;
    }
    let mut out = String::new();
    out.push_str("# torii credentials — managed by 'torii auth …'. Do not share.\n\n");
    if let Some(cloud) = &store.cloud {
        out.push_str("[cloud]\n");
        out.push_str(&format!("key = \"{}\"\n", cloud.key));
        out.push_str(&format!("endpoint = \"{}\"\n\n", cloud.endpoint));
    }
    if !store.tokens.is_empty() {
        out.push_str("[tokens]\n");
        for (k, v) in &store.tokens {
            out.push_str(&format!("{} = \"{}\"\n", k, v));
        }
    }
    fs::write(path, out)
        .map_err(|e| ToriiError::InvalidConfig(format!("write {}: {}", path.display(), e)))?;
    restrict_permissions(path);
    Ok(())
}

pub fn save_global(store: &AuthStore) -> Result<()> {
    let path = global_path()
        .ok_or_else(|| ToriiError::InvalidConfig("could not resolve config dir".to_string()))?;
    save_to(&path, store)
}

pub fn save_local<P: AsRef<Path>>(repo_path: P, store: &AuthStore) -> Result<()> {
    let path = local_path(repo_path);
    save_to(&path, store)
}

/// Persist a cloud key — kept as a back-compat shim for `torii auth login`
/// callers that don't know about the wider store yet.
pub fn save_cloud(key: &str, endpoint: &str) -> Result<()> {
    let mut store = load_global();
    store.cloud = Some(ApiKey {
        key: key.to_string(),
        endpoint: endpoint.to_string(),
    });
    save_global(&store)
}

/// Delete just the cloud entry (preserves platform tokens).
pub fn delete() -> Result<()> {
    let mut store = load_global();
    store.cloud = None;
    if store.tokens.is_empty() {
        // Whole file was just the cloud key — remove it entirely.
        if let Some(path) = global_path() {
            if path.exists() {
                fs::remove_file(&path).map_err(|e| {
                    ToriiError::InvalidConfig(format!("remove {}: {}", path.display(), e))
                })?;
            }
        }
        return Ok(());
    }
    save_global(&store)
}

// -- Token mutation ---------------------------------------------------------

/// Validate the provider name against the known list. Case-insensitive
/// match; returns the canonical lowercase form.
pub fn normalise_provider(name: &str) -> Result<String> {
    let lc = name.to_lowercase();
    if PROVIDERS.iter().any(|p| **p == lc) {
        Ok(lc)
    } else {
        Err(ToriiError::InvalidConfig(format!(
            "unknown provider '{}'. Known: {}",
            name,
            PROVIDERS.join(", ")
        )))
    }
}

pub fn set_token(provider: &str, token: &str, local: Option<&Path>) -> Result<()> {
    let provider = normalise_provider(provider)?;
    if let Some(repo) = local {
        let mut store = load_local_raw(repo);
        store.tokens.insert(provider, token.to_string());
        save_local(repo, &store)
    } else {
        let mut store = load_global();
        store.tokens.insert(provider, token.to_string());
        save_global(&store)
    }
}

pub fn remove_token(provider: &str, local: Option<&Path>) -> Result<bool> {
    let provider = normalise_provider(provider)?;
    if let Some(repo) = local {
        let mut store = load_local_raw(repo);
        let removed = store.tokens.remove(&provider).is_some();
        save_local(repo, &store)?;
        Ok(removed)
    } else {
        let mut store = load_global();
        let removed = store.tokens.remove(&provider).is_some();
        save_global(&store)?;
        Ok(removed)
    }
}

// -- The big one: token resolution -----------------------------------------

/// Where a token came from, surfaced by `torii auth doctor`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenSource {
    EnvVar(&'static str),
    EnvGeneric,
    Local,
    Global,
    Missing,
}

#[derive(Debug, Clone)]
pub struct ResolvedToken {
    pub provider: String,
    pub value: Option<String>,
    pub source: TokenSource,
}

/// Look up a token using the documented precedence:
/// env-per-host > env generic > local config > global config > none.
///
/// `repo_path` is the path to the repo (`.` is usually fine); pass it
/// even when you don't expect a local override, the local lookup is
/// cheap when the file doesn't exist.
pub fn resolve_token<P: AsRef<Path>>(provider: &str, repo_path: P) -> ResolvedToken {
    let provider_lc = provider.to_lowercase();

    // 1. Per-provider env vars.
    for env_name in env_vars_for(&provider_lc) {
        if let Ok(v) = std::env::var(env_name) {
            if !v.is_empty() {
                return ResolvedToken {
                    provider: provider_lc,
                    value: Some(v),
                    source: TokenSource::EnvVar(env_name),
                };
            }
        }
    }

    // 2. Generic env var (TORII_HTTPS_TOKEN) — matches existing transport.
    if let Ok(v) = std::env::var("TORII_HTTPS_TOKEN") {
        if !v.is_empty() {
            return ResolvedToken {
                provider: provider_lc,
                value: Some(v),
                source: TokenSource::EnvGeneric,
            };
        }
    }

    // 3. Local (per-repo) store.
    let local = load_local_raw(repo_path);
    if let Some(v) = local.tokens.get(&provider_lc) {
        if !v.is_empty() {
            return ResolvedToken {
                provider: provider_lc,
                value: Some(v.clone()),
                source: TokenSource::Local,
            };
        }
    }

    // 4. Global store.
    let global = load_global();
    if let Some(v) = global.tokens.get(&provider_lc) {
        if !v.is_empty() {
            return ResolvedToken {
                provider: provider_lc,
                value: Some(v.clone()),
                source: TokenSource::Global,
            };
        }
    }

    ResolvedToken {
        provider: provider_lc,
        value: None,
        source: TokenSource::Missing,
    }
}

/// Env var names checked for each provider, in order. Order matters
/// because `gh` and GitHub's own CI use `GH_TOKEN` interchangeably with
/// `GITHUB_TOKEN`; we accept both.
fn env_vars_for(provider: &str) -> &'static [&'static str] {
    match provider {
        "github" => &["GITHUB_TOKEN", "GH_TOKEN"],
        "gitlab" => &["GITLAB_TOKEN", "GL_TOKEN"],
        "gitea" => &["GITEA_TOKEN"],
        "forgejo" => &["FORGEJO_TOKEN"],
        "codeberg" => &["CODEBERG_TOKEN"],
        "bitbucket" => &["BITBUCKET_TOKEN"],
        "sourcehut" => &["SOURCEHUT_TOKEN", "SRHT_TOKEN"],
        "cargo" => &["CARGO_REGISTRY_TOKEN"],
        _ => &[],
    }
}

// -- Parser -----------------------------------------------------------------

/// Parse the on-disk format. Accepts both the new sectioned form and
/// the pre-0.7.1 cloud-only form (bare `key = …`/`endpoint = …`).
fn parse(text: &str) -> AuthStore {
    enum Section {
        TopLevel,
        Cloud,
        Tokens,
    }
    let mut section = Section::TopLevel;
    let mut cloud_key = String::new();
    let mut cloud_endpoint = default_endpoint();
    let mut have_cloud = false;
    let mut tokens = BTreeMap::new();

    for raw in text.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if line.starts_with('[') && line.ends_with(']') {
            let name = &line[1..line.len() - 1];
            section = match name.trim() {
                "cloud" => Section::Cloud,
                "tokens" => Section::Tokens,
                _ => Section::TopLevel, // unknown section: tolerate, ignore lines
            };
            continue;
        }
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        let k = k.trim();
        let v = v.trim().trim_matches('"').to_string();
        match section {
            Section::Cloud | Section::TopLevel => match k {
                "key" => {
                    cloud_key = v;
                    have_cloud = true;
                }
                "endpoint" => {
                    cloud_endpoint = v;
                }
                _ => {}
            },
            Section::Tokens => {
                if !v.is_empty() {
                    tokens.insert(k.to_string(), v);
                }
            }
        }
    }

    AuthStore {
        cloud: if have_cloud && !cloud_key.is_empty() {
            Some(ApiKey {
                key: cloud_key,
                endpoint: cloud_endpoint,
            })
        } else {
            None
        },
        tokens,
    }
}

// -- Migration --------------------------------------------------------------

/// Back-compat: read `~/.config/torii/config.toml`, pull `[auth]` out of
/// it into an `AuthStore`, and on success write it into `auth.toml` (so
/// next time we use the canonical location). Idempotent — silently
/// returns None when there's nothing to migrate.
fn migrate_from_config_toml() -> Option<AuthStore> {
    let config_path = dirs::config_dir()?.join("torii").join("config.toml");
    if !config_path.exists() {
        return None;
    }
    let text = fs::read_to_string(&config_path).ok()?;

    let mut tokens = BTreeMap::new();
    let mut in_auth = false;
    for raw in text.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if line.starts_with('[') && line.ends_with(']') {
            in_auth = line.trim_start_matches('[').trim_end_matches(']').trim() == "auth";
            continue;
        }
        if !in_auth {
            continue;
        }
        let Some((k, v)) = line.split_once('=') else {
            continue;
        };
        let key = k.trim();
        let value = v.trim().trim_matches('"').to_string();
        if value.is_empty() {
            continue;
        }
        // Field name in config.toml was `<provider>_token`; in auth.toml
        // we drop the `_token` suffix to match the CLI argument.
        if let Some(provider) = key.strip_suffix("_token") {
            tokens.insert(provider.to_string(), value);
        }
    }
    if tokens.is_empty() {
        return None;
    }
    let store = AuthStore {
        cloud: None,
        tokens,
    };
    let _ = save_global(&store);
    Some(store)
}

// -- Unix permissions -------------------------------------------------------

#[cfg(unix)]
fn restrict_permissions(path: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
}

#[cfg(not(unix))]
fn restrict_permissions(_: &std::path::Path) {}

// -- Tests ------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_legacy_top_level_cloud() {
        let s = parse("key = \"gitorii_sk_abc\"");
        assert_eq!(s.cloud.as_ref().unwrap().key, "gitorii_sk_abc");
        assert!(s.tokens.is_empty());
    }

    #[test]
    fn parse_new_sectioned_cloud_only() {
        let s = parse("[cloud]\nkey = \"x\"\nendpoint = \"http://h\"\n");
        let c = s.cloud.unwrap();
        assert_eq!(c.key, "x");
        assert_eq!(c.endpoint, "http://h");
    }

    #[test]
    fn parse_tokens_only() {
        let s = parse("[tokens]\ngithub = \"ghp_x\"\ngitlab = \"glp_y\"\n");
        assert_eq!(s.tokens["github"], "ghp_x");
        assert_eq!(s.tokens["gitlab"], "glp_y");
        assert!(s.cloud.is_none());
    }

    #[test]
    fn parse_both_sections() {
        let s = parse("[cloud]\nkey = \"k\"\n[tokens]\ncargo = \"cio\"\n");
        assert_eq!(s.cloud.unwrap().key, "k");
        assert_eq!(s.tokens["cargo"], "cio");
    }

    #[test]
    fn parse_empty_tokens_are_dropped() {
        let s = parse("[tokens]\ngithub = \"\"\ngitlab = \"x\"\n");
        assert!(!s.tokens.contains_key("github"));
        assert!(s.tokens.contains_key("gitlab"));
    }

    #[test]
    fn normalise_provider_accepts_known() {
        assert_eq!(normalise_provider("GitHub").unwrap(), "github");
        assert_eq!(normalise_provider("cargo").unwrap(), "cargo");
    }

    #[test]
    fn normalise_provider_rejects_unknown() {
        assert!(normalise_provider("hackernews").is_err());
    }
}