From e2631e7ab708ff976f69d67ad46dfb52d4bd464c Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 16:54:07 +0100 Subject: [PATCH 1/3] feat(providers): pull mirrors on Gitea and tea/gh token fallback Co-Authored-By: Claude Opus 5.5 --- .env.example | 1 + crates/grove-providers/src/gitea.rs | 29 +++++- crates/grove-providers/src/github.rs | 11 ++- crates/grove-providers/src/lib.rs | 20 +++- crates/grove-providers/src/token.rs | 142 ++++++++++++++++++++++++++- crates/grove-providers/tests/api.rs | 141 +++++++++++++++++++++++++- 6 files changed, 337 insertions(+), 7 deletions(-) diff --git a/.env.example b/.env.example index cb606ef..c032ddc 100644 --- a/.env.example +++ b/.env.example @@ -2,4 +2,5 @@ # Headless override (CI, servers without a Secret Service): GROVE_TOKEN_, where is the provider # id upper-cased with non-alphanumerics replaced by `_`. Example for a provider called "home": # GROVE_TOKEN_HOME= +# GROVE_NO_CLI_TOKENS=1 # do not fall back to the tokens of `tea` (Gitea/Forgejo) and `gh` (GitHub) # GROVE_BIN= # GUI shell only: path of the grove CLI (default: `grove` from PATH) diff --git a/crates/grove-providers/src/gitea.rs b/crates/grove-providers/src/gitea.rs index cf21c82..f143ae2 100644 --- a/crates/grove-providers/src/gitea.rs +++ b/crates/grove-providers/src/gitea.rs @@ -1,5 +1,7 @@ use crate::http::Http; -use crate::{Capabilities, Error, MirrorSpec, NewRepo, Provider, RemoteRepo, Result}; +use crate::{ + Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result, +}; use grove_core::config::ProviderKind; use serde_json::{Value, json}; @@ -40,6 +42,7 @@ impl Provider for Gitea { fn capabilities(&self) -> Capabilities { Capabilities { push_mirror: true, + pull_mirror: true, orgs: true, } } @@ -94,4 +97,28 @@ impl Provider for Gitea { ) .map(|_| ()) } + + fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result { + let mut body = json!({ + "clone_addr": spec.source_url, + "repo_name": spec.name, + "mirror": true, + "mirror_interval": spec.interval, + "private": spec.private, + "service": "git", + "description": "Mirror managed by grove", + }); + if let Some(o) = &spec.owner { + body["repo_owner"] = json!(o); + } + if let Some((user, token)) = &spec.source_auth { + body["auth_username"] = json!(user); + body["auth_password"] = json!(token); + } + Ok(repo(&self.http.ok( + "POST", + "/repos/migrate", + Some(&body), + )?)) + } } diff --git a/crates/grove-providers/src/github.rs b/crates/grove-providers/src/github.rs index 1077b11..a1ac8c2 100644 --- a/crates/grove-providers/src/github.rs +++ b/crates/grove-providers/src/github.rs @@ -1,5 +1,7 @@ use crate::http::Http; -use crate::{Capabilities, Error, MirrorSpec, NewRepo, Provider, RemoteRepo, Result}; +use crate::{ + Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result, +}; use grove_core::config::ProviderKind; use serde_json::{Value, json}; @@ -39,6 +41,7 @@ impl Provider for GitHub { fn capabilities(&self) -> Capabilities { Capabilities { push_mirror: false, + pull_mirror: false, orgs: true, } } @@ -84,4 +87,10 @@ impl Provider for GitHub { "GitHub has no push mirrors; use a Gitea pull mirror or the daemon's branch push", )) } + + fn create_pull_mirror(&self, _: &PullMirrorSpec) -> Result { + Err(Error::Unsupported( + "GitHub cannot pull-mirror another forge", + )) + } } diff --git a/crates/grove-providers/src/lib.rs b/crates/grove-providers/src/lib.rs index 0536e89..822a029 100644 --- a/crates/grove-providers/src/lib.rs +++ b/crates/grove-providers/src/lib.rs @@ -37,7 +37,7 @@ impl fmt::Display for Error { Error::Unsupported(m) => write!(f, "not supported by this forge: {m}"), Error::NoToken(id) => write!( f, - "no token for provider {id:?} (run `grove login {id}` or set GROVE_TOKEN_*)" + "no token for provider {id:?} (log in with `tea`/`gh`, run `grove login {id}` or set GROVE_TOKEN_*)" ), Error::Other(m) => f.write_str(m), } @@ -80,9 +80,25 @@ pub struct MirrorSpec { pub struct Capabilities { /// The forge can push-mirror a repo to another forge by itself. pub push_mirror: bool, + /// The forge can create a repo that pulls (mirrors) another forge's repo on a schedule. + pub pull_mirror: bool, pub orgs: bool, } +/// A repo on this forge that mirrors `source_url` (another forge) by pulling it. +#[derive(Debug, Clone)] +pub struct PullMirrorSpec { + pub name: String, + /// Create under this organisation instead of the authenticated user. + pub owner: Option, + pub private: bool, + pub source_url: String, + /// Credentials for a private source; `None` for a public one (nothing is stored). + pub source_auth: Option<(String, String)>, + /// Go-style duration (`8h0m0s`). + pub interval: String, +} + pub trait Provider { fn kind(&self) -> ProviderKind; fn capabilities(&self) -> Capabilities; @@ -91,6 +107,8 @@ pub trait Provider { fn list_repos(&self) -> Result>; fn create_repo(&self, new: &NewRepo) -> Result; fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>; + /// Creates a pull mirror (see [`Capabilities::pull_mirror`]). + fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result; } /// Builds the provider described by `cfg`, using `token`. diff --git a/crates/grove-providers/src/token.rs b/crates/grove-providers/src/token.rs index d60e04a..de7ccc2 100644 --- a/crates/grove-providers/src/token.rs +++ b/crates/grove-providers/src/token.rs @@ -1,7 +1,12 @@ //! Token storage: `GROVE_TOKEN_` env var first (headless machines, tests), then the -//! desktop Secret Service. Tokens are never written to the config file. +//! desktop Secret Service, then the login of the forge's own CLI (`tea`, `gh`) if present. +//! Tokens are never written to the config file. use crate::{Error, Result}; +use grove_core::config::{Provider as ProviderCfg, ProviderKind}; +use std::io::{Read, Write}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; const SERVICE: &str = "grove"; @@ -33,6 +38,107 @@ pub fn get(provider_id: &str) -> Result { } } +/// Where a token came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + Grove, + Tea, + Gh, +} + +/// [`get`], falling back to the forge CLI's own login (`tea` for Gitea/Forgejo, `gh` for +/// GitHub) when grove has no token of its own. Set `GROVE_NO_CLI_TOKENS=1` to disable it. +pub fn resolve(provider_id: &str, cfg: &ProviderCfg) -> Result<(String, Source)> { + let own = match get(provider_id) { + Ok(t) => return Ok((t, Source::Grove)), + Err(e) => e, + }; + if std::env::var_os("GROVE_NO_CLI_TOKENS").is_some_and(|v| !v.is_empty() && v != "0") { + return Err(own); + } + let host = host(cfg); + let found = match cfg.kind { + ProviderKind::Gitea | ProviderKind::Forgejo => host + .as_deref() + .and_then(tea_token) + .map(|t| (t, Source::Tea)), + ProviderKind::Github => { + gh_token(host.as_deref().unwrap_or("github.com")).map(|t| (t, Source::Gh)) + } + }; + // Report grove's own error (no token / Secret Service down) when the CLIs have nothing. + found.ok_or(own) +} + +/// Host (with port) of the provider URL, without user info. For GitHub a leading `api.` is +/// dropped so Enterprise API URLs map to the host `gh` knows. `None` when no URL is configured. +fn host(cfg: &ProviderCfg) -> Option { + let url = cfg.url.as_deref()?.trim(); + let rest = url.split_once("://").map_or(url, |(_, r)| r); + let h = rest.split(['/', '?', '#']).next()?.trim(); + let h = h.rsplit_once('@').map_or(h, |(_, h)| h); + let h = match cfg.kind { + ProviderKind::Github => h.strip_prefix("api.").unwrap_or(h), + _ => h, + }; + (!h.is_empty()).then(|| h.to_string()) +} + +/// How long a forge CLI may take to answer (it may be waiting on a keyring unlock prompt). +const CLI_TIMEOUT: Duration = Duration::from_secs(10); + +fn run(cmd: &str, args: &[&str], stdin: Option<&str>) -> Option { + let mut child = Command::new(cmd) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let wrote = match (stdin, child.stdin.take()) { + (Some(input), Some(mut w)) => w.write_all(input.as_bytes()).is_ok(), + _ => true, // dropping the handle closes stdin + }; + // Outputs are a few bytes, so the pipe cannot fill up while we poll. + let deadline = Instant::now() + CLI_TIMEOUT; + let status = loop { + match child.try_wait() { + Ok(Some(s)) => break Some(s), + Ok(None) if wrote && Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(20)) + } + _ => { + let _ = child.kill(); + let _ = child.wait(); + break None; + } + } + }?; + let mut out = String::new(); + child.stdout.take()?.read_to_string(&mut out).ok()?; + status.success().then_some(out) +} + +/// Asks tea's git credential helper, which matches the host against tea's logins. +fn tea_token(host: &str) -> Option { + let out = run( + "tea", + &["login", "helper", "get"], + Some(&format!("protocol=https\nhost={host}\n\n")), + )?; + out.lines() + .find_map(|l| l.strip_prefix("password=")) + .map(str::trim) + .filter(|t| !t.is_empty()) + .map(str::to_string) +} + +fn gh_token(host: &str) -> Option { + let t = run("gh", &["auth", "token", "--hostname", host], None)?; + let t = t.trim(); + (!t.is_empty()).then(|| t.to_string()) +} + pub fn set(provider_id: &str, token: &str) -> Result<()> { keyring::Entry::new(SERVICE, provider_id) .and_then(|e| e.set_password(token)) @@ -45,3 +151,37 @@ pub fn delete(provider_id: &str) -> Result<()> { Err(e) => Err(Error::Other(format!("secret service: {e}"))), } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn host_strips_scheme_path_userinfo_and_github_api_prefix() { + let h = |kind, url: &str| { + host(&ProviderCfg { + kind, + url: Some(url.into()), + }) + }; + let g = ProviderKind::Gitea; + assert_eq!( + h(g, "https://git.example.com/").as_deref(), + Some("git.example.com") + ); + assert_eq!( + h(g, "https://u@git.example.com:3000/x").as_deref(), + Some("git.example.com:3000") + ); + assert_eq!( + h(g, "https://api.example.com").as_deref(), + Some("api.example.com") + ); + let gh = ProviderKind::Github; + assert_eq!( + h(gh, "https://api.ghe.corp/api/v3").as_deref(), + Some("ghe.corp") + ); + assert_eq!(h(gh, "").as_deref(), None); + } +} diff --git a/crates/grove-providers/tests/api.rs b/crates/grove-providers/tests/api.rs index 675eaf6..80e9b1a 100644 --- a/crates/grove-providers/tests/api.rs +++ b/crates/grove-providers/tests/api.rs @@ -1,5 +1,5 @@ use grove_core::config::ProviderKind; -use grove_providers::{Error, GitHub, Gitea, MirrorSpec, NewRepo, Provider, token}; +use grove_providers::{Error, GitHub, Gitea, MirrorSpec, NewRepo, Provider, PullMirrorSpec, token}; use std::io::{Read, Write}; use std::net::TcpListener; use std::sync::mpsc; @@ -48,6 +48,33 @@ fn mock(replies: Vec<(u16, &'static str)>) -> (String, mpsc::Receiver) { (url, rx) } +/// Serialises the tests that change process-wide env vars. +static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Restores an env var on drop, also when an assertion panics. +struct EnvGuard(&'static str, Option); + +impl EnvGuard { + fn set(k: &'static str, v: impl AsRef) -> Self { + let g = EnvGuard(k, std::env::var_os(k)); + // SAFETY: callers hold ENV_LOCK; no other test reads these variables. + unsafe { std::env::set_var(k, v) }; + g + } +} + +impl Drop for EnvGuard { + fn drop(&mut self) { + // SAFETY: as in `set`. + unsafe { + match &self.1 { + Some(v) => std::env::set_var(self.0, v), + None => std::env::remove_var(self.0), + } + } + } +} + fn body(req: &str) -> serde_json::Value { serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap() } @@ -179,7 +206,115 @@ fn unreachable_forge_is_a_network_error() { #[test] fn env_var_overrides_the_keyring() { assert_eq!(token::env_name("gitea-main"), "GROVE_TOKEN_GITEA_MAIN"); - // SAFETY: tests in this binary that touch this variable run in this single test. - unsafe { std::env::set_var("GROVE_TOKEN_ENV_TEST", " abc ") }; + let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _g = EnvGuard::set("GROVE_TOKEN_ENV_TEST", " abc "); assert_eq!(token::get("env-test").unwrap(), "abc"); } + +#[test] +fn gitea_pull_mirror_sends_credentials_only_for_private_sources() { + let reply = r#"{"name":"m","private":false,"clone_url":"u/m.git","owner":{"login":"Org"}}"#; + let (url, rx) = mock(vec![(201, reply), (201, reply)]); + let g = Gitea::new(ProviderKind::Gitea, &url, "secret".into()); + let mut spec = PullMirrorSpec { + name: "m".into(), + owner: Some("Org".into()), + private: false, + source_url: "https://github.com/o/m.git".into(), + source_auth: None, + interval: "8h0m0s".into(), + }; + assert_eq!(g.create_pull_mirror(&spec).unwrap().owner, "Org"); + let req = rx.recv().unwrap(); + assert!(req.starts_with("POST /api/v1/repos/migrate "), "{req}"); + let b = body(&req); + assert_eq!(b["clone_addr"], "https://github.com/o/m.git"); + assert_eq!( + (b["mirror"].as_bool(), b["repo_owner"].as_str()), + (Some(true), Some("Org")) + ); + assert!(b.get("auth_password").is_none(), "{b}"); + + spec.private = true; + spec.owner = None; + spec.source_auth = Some(("me".into(), "ghtok".into())); + g.create_pull_mirror(&spec).unwrap(); + let b = body(&rx.recv().unwrap()); + assert_eq!( + (b["auth_username"].as_str(), b["auth_password"].as_str()), + (Some("me"), Some("ghtok")) + ); + assert!(b.get("repo_owner").is_none(), "{b}"); + assert_eq!(b["private"], true); +} + +#[test] +fn github_cannot_pull_mirror() { + let g = GitHub::new("http://127.0.0.1:9", "t".into()); + assert!(!g.capabilities().pull_mirror); + let spec = PullMirrorSpec { + name: "m".into(), + owner: None, + private: false, + source_url: "x".into(), + source_auth: None, + interval: "8h0m0s".into(), + }; + assert!(matches!( + g.create_pull_mirror(&spec), + Err(Error::Unsupported(_)) + )); +} + +/// Changes PATH and GROVE_NO_CLI_TOKENS under ENV_LOCK; both are restored on drop. +#[test] +fn falls_back_to_tea_and_gh_logins() { + use grove_core::config::Provider as ProviderCfg; + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!( + "grove-clitok-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + // tea's credential helper answers only for its host; gh echoes the host it was asked for. + let scripts = [ + ( + "tea", + "#!/bin/sh\nin=\"\"; while IFS= read -r l; do in=\"$in $l\"; done\ncase \"$in\" in *host=git.example.com*) printf 'protocol=https\\nhost=git.example.com\\nusername=u\\npassword=teatok\\n';; *) exit 1;; esac\n", + ), + ( + "gh", + "#!/bin/sh\n[ \"$4\" = github.com ] && echo ' ghtok ' || exit 1\n", + ), + ]; + for (name, body) in scripts { + let p = dir.join(name); + std::fs::write(&p, body).unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _path = EnvGuard::set("PATH", &dir); + let off = EnvGuard::set("GROVE_NO_CLI_TOKENS", "0"); + let gitea = |url: &str| ProviderCfg { + kind: ProviderKind::Gitea, + url: Some(url.into()), + }; + let github = ProviderCfg { + kind: ProviderKind::Github, + url: None, + }; + let id = format!("clitok-{}", std::process::id()); + let got = token::resolve(&id, &gitea("https://git.example.com/")).unwrap(); + assert_eq!(got, ("teatok".to_string(), token::Source::Tea)); + assert!(token::resolve(&id, &gitea("https://other.example.com")).is_err()); + let got = token::resolve(&id, &github).unwrap(); + assert_eq!(got, ("ghtok".to_string(), token::Source::Gh)); + drop(off); + let _off = EnvGuard::set("GROVE_NO_CLI_TOKENS", "1"); + assert!(token::resolve(&id, &github).is_err()); + std::fs::remove_dir_all(&dir).unwrap(); +} From ed07c0a081dd604c1c4822a9e5264967bf8d33d0 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 16:54:07 +0100 Subject: [PATCH 2/3] feat: per-group routing by visibility and repo owners Co-Authored-By: Claude Opus 5.5 --- crates/grove-core/src/config.rs | 147 ++++++++++++++++++--- crates/grove/src/main.rs | 11 +- crates/grove/src/workflow.rs | 226 ++++++++++++++++++++++++++------ gui/ui/app.js | 4 +- 4 files changed, 326 insertions(+), 62 deletions(-) diff --git a/crates/grove-core/src/config.rs b/crates/grove-core/src/config.rs index 7e1c9e7..05a0664 100644 --- a/crates/grove-core/src/config.rs +++ b/crates/grove-core/src/config.rs @@ -62,6 +62,40 @@ pub struct Group { pub layout: Layout, #[serde(default = "yes")] pub auto_materialize: bool, + /// Account or organisation that owns the group's repos, per provider id. A provider not + /// listed here uses the authenticated user. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub owners: BTreeMap, + /// Where public repos go when that differs from `primary`/`mirror_to` (which then apply to + /// private repos only). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub public: Option, +} + +/// A primary forge plus the forges it is mirrored to. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Route { + pub primary: String, + #[serde(default)] + pub mirror_to: Vec, +} + +impl Group { + /// The route a repo of this visibility takes. + pub fn route(&self, private: bool) -> Route { + match (&self.public, private) { + (Some(r), false) => r.clone(), + _ => Route { + primary: self.primary.clone(), + mirror_to: self.mirror_to.clone(), + }, + } + } + + /// The owner configured for `provider`, if any (otherwise: the authenticated user). + pub fn owner(&self, provider: &str) -> Option<&str> { + self.owners.get(provider).map(String::as_str) + } } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] @@ -186,24 +220,44 @@ impl Config { )); } for g in &self.groups { - if !self.providers.contains_key(&g.primary) { - return bad(format!( - "group {:?}: unknown primary provider {:?}", - g.name, g.primary - )); + let mut routes = vec![("", g.route(true))]; + if let Some(p) = &g.public { + routes.push(("public.", p.clone())); } - if let Some(m) = g - .mirror_to - .iter() - .find(|m| !self.providers.contains_key(*m)) - { - return bad(format!("group {:?}: unknown mirror provider {m:?}", g.name)); + for (pfx, r) in routes { + if !self.providers.contains_key(&r.primary) { + return bad(format!( + "group {:?}: unknown {pfx}primary provider {:?}", + g.name, r.primary + )); + } + if let Some(m) = r + .mirror_to + .iter() + .find(|m| !self.providers.contains_key(*m)) + { + return bad(format!( + "group {:?}: unknown {pfx}mirror provider {m:?}", + g.name + )); + } + if r.mirror_to.contains(&r.primary) { + return bad(format!( + "group {:?}: {pfx}primary cannot also be a mirror target", + g.name + )); + } } - if g.mirror_to.contains(&g.primary) { - return bad(format!( - "group {:?}: primary cannot also be a mirror target", - g.name - )); + for (p, o) in &g.owners { + if !self.providers.contains_key(p) { + return bad(format!( + "group {:?}: owner for unknown provider {p:?}", + g.name + )); + } + if o.trim().is_empty() { + return bad(format!("group {:?}: empty owner for {p:?}", g.name)); + } } } if let Some(c) = &self.config_repo @@ -292,6 +346,67 @@ name = "grove-config" )); } + const ROUTED: &str = r#" +[machine] +name = "a" +[root] +path = "/x" +[providers.gitea] +kind = "gitea" +[providers.github] +kind = "github" +[[groups]] +name = "g" +primary = "gitea" +owners = { gitea = "Org", github = "org-gh" } +[groups.public] +primary = "github" +mirror_to = ["gitea"] +"#; + + #[test] + fn routes_by_visibility_and_resolves_owners() { + let c = Config::parse(ROUTED).unwrap(); + let g = &c.groups[0]; + let private = g.route(true); + assert_eq!( + (private.primary.as_str(), private.mirror_to.len()), + ("gitea", 0) + ); + let public = g.route(false); + assert_eq!(public.primary, "github"); + assert_eq!(public.mirror_to, vec!["gitea".to_string()]); + assert_eq!(g.owner("gitea"), Some("Org")); + assert_eq!(g.owner("nope"), None); + // Without a public route both visibilities use the base route. + let plain = Config::parse(FULL).unwrap(); + assert_eq!(plain.groups[0].route(false), plain.groups[0].route(true)); + // Round-trips through save's serializer. + let text = toml::to_string_pretty(&c).unwrap(); + assert_eq!(Config::parse(&text).unwrap(), c); + } + + #[test] + fn rejects_bad_public_routes_and_owners() { + for (from, to) in [ + ( + "primary = \"github\"\nmirror_to", + "primary = \"nope\"\nmirror_to", + ), + ("mirror_to = [\"gitea\"]", "mirror_to = [\"github\"]"), + ("mirror_to = [\"gitea\"]", "mirror_to = [\"nope\"]"), + ("github = \"org-gh\"", "nope = \"x\""), + ("github = \"org-gh\"", "github = \" \""), + ] { + let t = ROUTED.replace(from, to); + assert_ne!(t, ROUTED, "{from:?} not found"); + assert!( + matches!(Config::parse(&t), Err(ConfigError::Invalid(_))), + "{to:?}" + ); + } + } + #[test] fn rejects_bad_syntax_and_unknown_kind() { assert!(matches!(Config::parse("["), Err(ConfigError::Parse(_)))); diff --git a/crates/grove/src/main.rs b/crates/grove/src/main.rs index 8e38405..271ffd7 100644 --- a/crates/grove/src/main.rs +++ b/crates/grove/src/main.rs @@ -367,7 +367,9 @@ fn main() -> Result<()> { *force, )?; println!("wrote {}", path.display()); - println!("next: `grove login {provider}` to store the API token"); + println!( + "next: `grove doctor` (tokens from `tea`/`gh` are used if present; else `grove login {provider}`)" + ); Ok(()) } Cmd::Login { provider } => { @@ -524,6 +526,13 @@ fn doctor(cfg_arg: &Option) -> Result<()> { if let Some(c) = &cfg { let root = c.root_path(); line(Some(root.is_dir()), format!("root {}", root.display())); + // Local lookup only (env, Secret Service, tea/gh): no request reaches the forge. + for (id, pc) in &c.providers { + match grove_providers::token::resolve(id, pc) { + Ok((_, src)) => line(Some(true), format!("provider {id:?}: token from {src:?}")), + Err(e) => line(None, format!("provider {id:?}: {e}")), + } + } for g in &c.groups { let gdir = root.join(&g.name); let Ok(rd) = std::fs::read_dir(&gdir) else { diff --git a/crates/grove/src/workflow.rs b/crates/grove/src/workflow.rs index 9497dc0..177e35e 100644 --- a/crates/grove/src/workflow.rs +++ b/crates/grove/src/workflow.rs @@ -6,13 +6,15 @@ use grove_core::config::{ }; use grove_core::git::Git; use grove_core::registry::{Entry, Registry, clone_bare_layout, init_bare_layout, push_initial}; -use grove_providers::{MirrorSpec, NewRepo, Provider, build, token}; +use grove_providers::{MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, build, token}; use std::fs; use std::path::{Path, PathBuf}; pub struct Forge { pub api: Box, pub login: String, + /// API token (also used to authorise mirrors that read from this forge). + pub token: String, /// Git environment that authenticates HTTPS operations with the stored token. pub git_env: Vec<(String, String)>, } @@ -22,7 +24,7 @@ pub fn connect(cfg: &Config, id: &str) -> Result { .providers .get(id) .with_context(|| format!("provider {id:?} is not in the config"))?; - let tok = token::get(id)?; + let (tok, _) = token::resolve(id, pc)?; let api = build(pc, tok.clone()); let login = api.test_connection()?; let git_env = match pc.kind { @@ -35,16 +37,55 @@ pub fn connect(cfg: &Config, id: &str) -> Result { ), ("GIT_TERMINAL_PROMPT".into(), "0".into()), ], - // GitHub git-over-HTTPS needs Basic auth; leave it to the user's credential helper. - ProviderKind::Github => vec![("GIT_TERMINAL_PROMPT".into(), "0".into())], + // GitHub git-over-HTTPS takes the token as Basic auth (any user name works). + ProviderKind::Github => vec![ + ("GIT_CONFIG_COUNT".into(), "1".into()), + ("GIT_CONFIG_KEY_0".into(), "http.extraHeader".into()), + ( + "GIT_CONFIG_VALUE_0".into(), + format!( + "Authorization: Basic {}", + base64(&format!("x-access-token:{tok}")) + ), + ), + ("GIT_TERMINAL_PROMPT".into(), "0".into()), + ], }; Ok(Forge { api, login, + token: tok, git_env, }) } +/// The group's owner on `provider`, or `None` when that is the authenticated user itself +/// (personal repos use `/user/repos`, not the org endpoint). +fn org_owner(grp: &Group, provider: &str, login: &str) -> Option { + grp.owner(provider) + .filter(|o| !o.eq_ignore_ascii_case(login)) + .map(str::to_string) +} + +/// Standard base64 with padding (enough for an auth header; avoids a dependency). +fn base64(s: &str) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + for c in s.as_bytes().chunks(3) { + let n = (c[0] as u32) << 16 + | (*c.get(1).unwrap_or(&0) as u32) << 8 + | *c.get(2).unwrap_or(&0) as u32; + for i in 0..4 { + if i <= c.len() { + out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + fn group<'a>(cfg: &'a Config, name: &str) -> Result<&'a Group> { cfg.groups .iter() @@ -91,6 +132,8 @@ pub fn init(path: &Path, a: InitArgs, force: bool) -> Result { mirror_to: vec![], layout: Layout::BareWorktrees, auto_materialize: true, + owners: Default::default(), + public: None, }], sync: Default::default(), config_repo: a.config_repo.map(|name| grove_core::config::ConfigRepo { @@ -123,24 +166,25 @@ pub fn new_repo(cfg: &Config, group_name: &str, name: &str, private: bool) -> Re if dir.exists() { bail!("{} already exists", dir.display()); } - let primary = connect(cfg, &grp.primary)?; + let route = grp.route(private); + let primary = connect(cfg, &route.primary)?; let remote = primary.api.create_repo(&NewRepo { name: name.into(), - owner: None, + owner: org_owner(grp, &route.primary, &primary.login), private, description: String::new(), })?; println!( "created {}/{} on {}", - remote.owner, remote.name, grp.primary + remote.owner, remote.name, route.primary ); let wt = init_bare_layout(&dir, &remote.clone_url)?; push_initial(&dir, &primary.git_env)?; println!("pushed initial commit; worktree {}", wt.display()); - for mid in &grp.mirror_to { - match configure_mirror(cfg, &primary, mid, &remote.owner, name, private) { - Ok(()) => println!("push mirror to {mid} configured"), + for mid in &route.mirror_to { + match configure_mirror(cfg, grp, &primary, &remote, mid) { + Ok(()) => println!("mirror to {mid} configured"), Err(e) => println!("warning: mirror to {mid} not configured: {e}"), } } @@ -155,53 +199,95 @@ pub fn new_repo(cfg: &Config, group_name: &str, name: &str, private: bool) -> Re Ok(wt) } +/// Mirrors `remote` (on `primary`) to `mirror_id`: a push mirror from the primary when it can +/// do that (Gitea/Forgejo), otherwise a pull mirror created on the target (e.g. GitHub -> Gitea). fn configure_mirror( cfg: &Config, + grp: &Group, primary: &Forge, + remote: &RemoteRepo, mirror_id: &str, - owner: &str, - name: &str, - private: bool, ) -> Result<()> { let m = connect(cfg, mirror_id)?; - let target = m.api.create_repo(&NewRepo { - name: name.into(), - owner: None, - private, - description: "Mirror managed by grove".into(), - })?; - primary.api.configure_mirror( - owner, - name, - &MirrorSpec { - remote_url: target.clone_url, - remote_username: m.login, - remote_token: token::get(mirror_id)?, + let owner = org_owner(grp, mirror_id, &m.login); + if primary.api.capabilities().push_mirror { + let target = m.api.create_repo(&NewRepo { + name: remote.name.clone(), + owner, + private: remote.private, + description: "Mirror managed by grove".into(), + })?; + primary.api.configure_mirror( + &remote.owner, + &remote.name, + &MirrorSpec { + remote_url: target.clone_url, + remote_username: m.login.clone(), + remote_token: m.token.clone(), + interval: "8h0m0s".into(), + sync_on_commit: true, + }, + )?; + } else { + // Credentials are only handed to the mirror when the source is private. + let source_auth = remote + .private + .then(|| (primary.login.clone(), primary.token.clone())); + m.api.create_pull_mirror(&PullMirrorSpec { + name: remote.name.clone(), + owner, + private: remote.private, + source_url: remote.clone_url.clone(), + source_auth, interval: "8h0m0s".into(), - sync_on_commit: true, - }, - )?; + })?; + } Ok(()) } -/// Lists remote repos of the group's primary that are not on disk; clones the named ones. +/// Remote repos of one route that belong to the group: owned by `owner` (case-insensitive, as +/// forge logins are) and, when the group splits routes by visibility, of that visibility. +fn select(repos: Vec, owner: &str, private: Option) -> Vec { + repos + .into_iter() + .filter(|r| r.owner.eq_ignore_ascii_case(owner)) + .filter(|r| private.is_none_or(|p| r.private == p)) + .collect() +} + +/// Lists the group's remote repos that are not on disk; clones the named ones. pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> { let grp = group(cfg, group_name)?; - let primary = connect(cfg, &grp.primary)?; + // (provider id, visibility filter): one side per route. + let sides = match &grp.public { + Some(p) => vec![ + (grp.primary.clone(), Some(true)), + (p.primary.clone(), Some(false)), + ], + None => vec![(grp.primary.clone(), None)], + }; let gdir = cfg.root_path().join(&grp.name); - let missing: Vec<_> = primary - .api - .list_repos()? - .into_iter() - .filter(|r| !gdir.join(&r.name).join(".bare").exists()) - .collect(); + let mut forges = Vec::new(); + let mut missing: Vec<(RemoteRepo, usize)> = Vec::new(); + for (pid, vis) in sides { + let f = connect(cfg, &pid)?; + let owner = grp.owner(&pid).unwrap_or(&f.login).to_string(); + for r in select(f.api.list_repos()?, &owner, vis) { + let here = gdir.join(&r.name).join(".bare").exists(); + if !here && !missing.iter().any(|(m, _)| m.name == r.name) { + missing.push((r, forges.len())); + } + } + forges.push((pid, f)); + } if wanted.is_empty() { - println!("repos on {} not yet in {}:", grp.primary, gdir.display()); - for r in &missing { + println!("repos of group {} not yet in {}:", grp.name, gdir.display()); + for (r, i) in &missing { println!( - " {}/{}{}", + " {}/{} on {}{}", r.owner, r.name, + forges[*i].0, if r.private { " (private)" } else { "" } ); } @@ -209,12 +295,12 @@ pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> { return Ok(()); } for w in wanted { - let r = missing + let (r, i) = missing .iter() - .find(|r| &r.name == w) + .find(|(r, _)| &r.name == w) .with_context(|| format!("{w:?} is not a remote repo missing locally"))?; let dir = gdir.join(&r.name); - clone_bare_layout(&r.clone_url, &dir, &primary.git_env)?; + clone_bare_layout(&r.clone_url, &dir, &forges[*i].1.git_env)?; println!("imported {} -> {}", r.name, dir.display()); register( cfg, @@ -387,3 +473,57 @@ pub fn bootstrap(cfg: &Config) -> Result<(usize, usize)> { commit_and_push(cfg, &dir, &forge, "machine heartbeat")?; Ok((done, skipped)) } + +#[cfg(test)] +mod tests { + use super::*; + + fn r(owner: &str, name: &str, private: bool) -> RemoteRepo { + RemoteRepo { + owner: owner.into(), + name: name.into(), + private, + clone_url: format!("u/{name}.git"), + default_branch: "main".into(), + } + } + + #[test] + fn base64_matches_rfc4648_vectors() { + for (i, o) in [ + ("", ""), + ("f", "Zg=="), + ("fo", "Zm8="), + ("foo", "Zm9v"), + ("foobar", "Zm9vYmFy"), + ] { + assert_eq!(base64(i), o); + } + } + + #[test] + fn own_login_is_not_an_org_owner() { + let mut g: Group = toml::from_str("name='g'\nprimary='p'").unwrap(); + assert_eq!(org_owner(&g, "p", "me"), None); + g.owners.insert("p".into(), "Me".into()); + assert_eq!(org_owner(&g, "p", "me"), None); + g.owners.insert("p".into(), "Org".into()); + assert_eq!(org_owner(&g, "p", "me").as_deref(), Some("Org")); + } + + #[test] + fn select_filters_by_owner_and_visibility() { + let all = || { + vec![ + r("dasemu", "priv", true), + r("Dasemu", "pub", false), + r("Zenvairo", "org", true), + ] + }; + let names = |v: Vec| v.into_iter().map(|r| r.name).collect::>(); + assert_eq!(names(select(all(), "dasemu", None)), ["priv", "pub"]); + assert_eq!(names(select(all(), "dasemu", Some(true))), ["priv"]); + assert_eq!(names(select(all(), "DASEMU", Some(false))), ["pub"]); + assert_eq!(names(select(all(), "zenvairo", None)), ["org"]); + } +} diff --git a/gui/ui/app.js b/gui/ui/app.js index 3a71a4f..c305147 100644 --- a/gui/ui/app.js +++ b/gui/ui/app.js @@ -225,7 +225,7 @@ views.import = () => { list.replaceChildren(h('p', { class: 'muted' }, 'Scanning…')); out.replaceChildren(); const r = await cli(['import', sel.value]); - const names = (r.output.match(/^\s+\S+\/(\S+?)(?: \(private\))?$/gm) || []).map((l) => l.trim().split(/\s+/)[0].split('/')[1]); + const names = (r.output.match(/^\s+\S+\/(\S+?)(?: on \S+)?(?: \(private\))?$/gm) || []).map((l) => l.trim().split(/\s+/)[0].split('/')[1]); if (!r.ok) return list.replaceChildren(h('div', { class: 'term fail' }, r.output)); if (!names.length) return list.replaceChildren(h('p', { class: 'muted' }, 'Nothing to import: every remote repository is already on this machine.')); const boxes = names.map((n) => h('label', { class: 'check' }, h('input', { type: 'checkbox', value: n }), n)); @@ -260,7 +260,7 @@ views.settings = () => { h('h2', {}, 'Providers'), kv(provs.map(([id, p]) => [id, p.kind + (p.url ? ' · ' + p.url : '')])), h('h2', {}, 'Groups'), - kv((cfg.groups || []).map((g) => [g.name, 'primary ' + g.primary + (g.mirror_to && g.mirror_to.length ? ' · mirrors: ' + g.mirror_to.join(', ') : '') + ' · ' + (g.layout || 'bare-worktrees')])), + kv((cfg.groups || []).map((g) => [g.name, 'primary ' + g.primary + (g.mirror_to && g.mirror_to.length ? ' · mirrors: ' + g.mirror_to.join(', ') : '') + (g.public ? ' · public: ' + g.public.primary + ((g.public.mirror_to || []).length ? ' → ' + g.public.mirror_to.join(', ') : '') : '') + ' · ' + (g.layout || 'bare-worktrees')])), h('h2', {}, 'Config repository'), kv([['Repository', cfg.config_repo ? cfg.config_repo.name + ' on ' + cfg.config_repo.provider : 'not configured']]), h('div', { class: 'actions' }, From b4bc604c8ead0603f9f92abd5d905de2bb55b511 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 16:54:07 +0100 Subject: [PATCH 3/3] docs: phase 6 (routing, owners, CLI tokens) Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/phase4.md | 4 +++- docs/phase6.md | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 docs/phase6.md diff --git a/CLAUDE.md b/CLAUDE.md index f2545f0..806b95d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,7 +18,7 @@ Do not start new work before the previous results are written to `docs/`. - Throwaway e2e on a local Forgejo: `spikes/phase4-e2e.sh` ## Architecture -See `docs/` (`phase0-spike.md` ... `phase5.md`, `DECISIONS.md`). Git is the storage layer; shell out to +See `docs/` (`phase0-spike.md` ... `phase6.md`, `DECISIONS.md`). Git is the storage layer; shell out to system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touching the user's branch or index. diff --git a/docs/phase4.md b/docs/phase4.md index 114c123..5939e94 100644 --- a/docs/phase4.md +++ b/docs/phase4.md @@ -10,6 +10,7 @@ Service via `keyring` (service `grove`, user = provider id). Tokens are never wr file. `grove login ` reads the token from stdin (never argv), checks it against the forge and stores it. HTTPS git operations of the wizards authenticate through `http.extraHeader` set in the process environment only (Gitea/Forgejo); for GitHub they use the user's credential helper. +Since phase 6 the `tea`/`gh` logins are used when grove has no token of its own (`phase6.md`). ## Commands @@ -33,7 +34,8 @@ clone lives in `/config-repo`. It is created on the first registratio Gitea/Forgejo: the primary creates a push mirror via `POST /repos/{o}/{r}/push_mirrors` (`sync_on_commit`, 8 h interval) to a repo created on the mirror provider. GitHub has no push mirrors: `configure_mirror` reports `Unsupported` and `new` warns. The daemon-side fallback (push -branches and tags only, never `refs/sync/*`) is **not implemented**. +branches and tags only, never `refs/sync/*`) is **not implemented**. Phase 6 adds a pull mirror on +the Gitea side for GitHub primaries (`phase6.md`). ## Validation diff --git a/docs/phase6.md b/docs/phase6.md new file mode 100644 index 0000000..ed18939 --- /dev/null +++ b/docs/phase6.md @@ -0,0 +1,64 @@ +# Phase 6: routing by visibility, owners, CLI tokens + +## Config + +Two optional keys per group, both backward compatible. Nothing is hard-coded: each user decides per +group which forge is primary, where it is mirrored and whether public repos route differently. +Without these keys a group behaves as before (one route for every repo, owned by the token's user). +Example (one person's setup, not a default): + +```toml +[[groups]] +name = "Zenvairo" +primary = "gitea" # private repos (and all repos without [groups.public]) +mirror_to = [] +owners = { gitea = "Zenvairo" } # account/org per provider; unset = authenticated user +[groups.public] # public repos take this route instead +primary = "github" +mirror_to = ["gitea"] +``` + +- `Group::route(private)` picks the route; `Group::owner(provider)` the owner. +- Validation: the public route follows the same rules as the base one (known providers, primary + not in its own `mirror_to`); `owners` keys must be known providers, values non-empty. + +## Flows + +- `grove new [--public]` creates the repo on the route's primary, under the + configured owner (`POST /orgs/{owner}/repos`), then sets up each mirror of that route: + - primary can push-mirror (Gitea/Forgejo): target repo created under the mirror's owner, then a + push mirror on the primary (as before); + - otherwise (GitHub primary): a **pull mirror** on the target via Gitea's `POST /repos/migrate` + (`mirror: true`, 8 h interval). Credentials of the source are sent only for private sources. +- `grove import ` lists, per route, the primary's repos owned by the configured owner (or + the authenticated user), and with a public route only those of the route's visibility. Repos of + other owners (orgs you belong to) no longer show up in every group: give an org group its + `owners` entry. If one route's provider is unreachable, the whole group's import fails. +- An owner equal to the authenticated login means "my account" (`/user/repos`), not an org. +- Wizard git over HTTPS authenticates with the resolved token on both forge kinds + (`http.extraHeader`, process env only; GitHub as Basic `x-access-token`). + +## Tokens + +`token::resolve`: `GROVE_TOKEN_`, then the Secret Service, then the forge CLI's login: +`tea login helper get` for Gitea/Forgejo (matched by the provider URL's host) and +`gh auth token --hostname ` for GitHub (`github.com` without a URL). `GROVE_NO_CLI_TOKENS=1` +disables the fallback. Each CLI call is killed after 10 s (e.g. a pending keyring unlock). +`grove doctor` reports the source per provider without contacting the forge. + +Mirrors store a token on the forge: the mirror provider's token in the primary's push-mirror +config, and the source's token in a pull mirror of a **private** source. With the CLI fallback that +is the broad-scope `tea`/`gh` token; use `grove login` with a narrower token to avoid that. + +## Validation + +- `grove-core` config tests: routing, owners, round trip, invalid public routes/owners. +- `grove-providers/tests/api.rs`: migrate request shape (owner, credentials only when private), + GitHub `Unsupported`, tea/gh fallback with fake binaries on `PATH`, opt-out variable. +- `grove` unit test: import filtering by owner (case-insensitive) and visibility. +- Real machine: `grove doctor` found the tea (git.zenvairo.es) and gh (github.com) tokens. + +## Not verified + +- Pull mirror creation on the real Gitea and push to a real GitHub org (mock-tested only). +- The daemon still syncs every repo under `root.path`, whether or not its directory is a group.