mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 15:26:09 +00:00
Merge pull request 'feat: per-group routing by visibility, repo owners and tea/gh tokens' (#4) from feat/routing-owners-cli-tokens into development
Reviewed-on: #4
This commit is contained in:
commit
0884d556ce
13 files changed
+731
-71
No files matched your search
@@ -2,4 +2,5 @@
|
|||||||
# Headless override (CI, servers without a Secret Service): GROVE_TOKEN_<ID>, where <ID> is the provider
|
# Headless override (CI, servers without a Secret Service): GROVE_TOKEN_<ID>, where <ID> is the provider
|
||||||
# id upper-cased with non-alphanumerics replaced by `_`. Example for a provider called "home":
|
# id upper-cased with non-alphanumerics replaced by `_`. Example for a provider called "home":
|
||||||
# GROVE_TOKEN_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)
|
# GROVE_BIN= # GUI shell only: path of the grove CLI (default: `grove` from PATH)
|
||||||
@@ -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`
|
- Throwaway e2e on a local Forgejo: `spikes/phase4-e2e.sh`
|
||||||
|
|
||||||
## Architecture
|
## 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
|
system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touching the
|
||||||
user's branch or index.
|
user's branch or index.
|
||||||
|
|
||||||
|
|||||||
+131
-16
@@ -62,6 +62,40 @@ pub struct Group {
|
|||||||
pub layout: Layout,
|
pub layout: Layout,
|
||||||
#[serde(default = "yes")]
|
#[serde(default = "yes")]
|
||||||
pub auto_materialize: bool,
|
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<String, String>,
|
||||||
|
/// 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<Route>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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)]
|
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||||
@@ -186,24 +220,44 @@ impl Config {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
for g in &self.groups {
|
for g in &self.groups {
|
||||||
if !self.providers.contains_key(&g.primary) {
|
let mut routes = vec![("", g.route(true))];
|
||||||
return bad(format!(
|
if let Some(p) = &g.public {
|
||||||
"group {:?}: unknown primary provider {:?}",
|
routes.push(("public.", p.clone()));
|
||||||
g.name, g.primary
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
if let Some(m) = g
|
for (pfx, r) in routes {
|
||||||
.mirror_to
|
if !self.providers.contains_key(&r.primary) {
|
||||||
.iter()
|
return bad(format!(
|
||||||
.find(|m| !self.providers.contains_key(*m))
|
"group {:?}: unknown {pfx}primary provider {:?}",
|
||||||
{
|
g.name, r.primary
|
||||||
return bad(format!("group {:?}: unknown mirror provider {m:?}", g.name));
|
));
|
||||||
|
}
|
||||||
|
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) {
|
for (p, o) in &g.owners {
|
||||||
return bad(format!(
|
if !self.providers.contains_key(p) {
|
||||||
"group {:?}: primary cannot also be a mirror target",
|
return bad(format!(
|
||||||
g.name
|
"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
|
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]
|
#[test]
|
||||||
fn rejects_bad_syntax_and_unknown_kind() {
|
fn rejects_bad_syntax_and_unknown_kind() {
|
||||||
assert!(matches!(Config::parse("["), Err(ConfigError::Parse(_))));
|
assert!(matches!(Config::parse("["), Err(ConfigError::Parse(_))));
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use crate::http::Http;
|
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 grove_core::config::ProviderKind;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
@@ -40,6 +42,7 @@ impl Provider for Gitea {
|
|||||||
fn capabilities(&self) -> Capabilities {
|
fn capabilities(&self) -> Capabilities {
|
||||||
Capabilities {
|
Capabilities {
|
||||||
push_mirror: true,
|
push_mirror: true,
|
||||||
|
pull_mirror: true,
|
||||||
orgs: true,
|
orgs: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,4 +97,28 @@ impl Provider for Gitea {
|
|||||||
)
|
)
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result<RemoteRepo> {
|
||||||
|
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),
|
||||||
|
)?))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
use crate::http::Http;
|
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 grove_core::config::ProviderKind;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
@@ -39,6 +41,7 @@ impl Provider for GitHub {
|
|||||||
fn capabilities(&self) -> Capabilities {
|
fn capabilities(&self) -> Capabilities {
|
||||||
Capabilities {
|
Capabilities {
|
||||||
push_mirror: false,
|
push_mirror: false,
|
||||||
|
pull_mirror: false,
|
||||||
orgs: true,
|
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",
|
"GitHub has no push mirrors; use a Gitea pull mirror or the daemon's branch push",
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn create_pull_mirror(&self, _: &PullMirrorSpec) -> Result<RemoteRepo> {
|
||||||
|
Err(Error::Unsupported(
|
||||||
|
"GitHub cannot pull-mirror another forge",
|
||||||
|
))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -37,7 +37,7 @@ impl fmt::Display for Error {
|
|||||||
Error::Unsupported(m) => write!(f, "not supported by this forge: {m}"),
|
Error::Unsupported(m) => write!(f, "not supported by this forge: {m}"),
|
||||||
Error::NoToken(id) => write!(
|
Error::NoToken(id) => write!(
|
||||||
f,
|
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),
|
Error::Other(m) => f.write_str(m),
|
||||||
}
|
}
|
||||||
@@ -80,9 +80,25 @@ pub struct MirrorSpec {
|
|||||||
pub struct Capabilities {
|
pub struct Capabilities {
|
||||||
/// The forge can push-mirror a repo to another forge by itself.
|
/// The forge can push-mirror a repo to another forge by itself.
|
||||||
pub push_mirror: bool,
|
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,
|
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<String>,
|
||||||
|
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 {
|
pub trait Provider {
|
||||||
fn kind(&self) -> ProviderKind;
|
fn kind(&self) -> ProviderKind;
|
||||||
fn capabilities(&self) -> Capabilities;
|
fn capabilities(&self) -> Capabilities;
|
||||||
@@ -91,6 +107,8 @@ pub trait Provider {
|
|||||||
fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
|
fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
|
||||||
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo>;
|
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo>;
|
||||||
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> 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<RemoteRepo>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds the provider described by `cfg`, using `token`.
|
/// Builds the provider described by `cfg`, using `token`.
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
//! Token storage: `GROVE_TOKEN_<ID>` env var first (headless machines, tests), then the
|
//! Token storage: `GROVE_TOKEN_<ID>` 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 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";
|
const SERVICE: &str = "grove";
|
||||||
|
|
||||||
@@ -33,6 +38,107 @@ pub fn get(provider_id: &str) -> Result<String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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<String> {
|
||||||
|
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<String> {
|
||||||
|
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<String> {
|
||||||
|
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<String> {
|
||||||
|
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<()> {
|
pub fn set(provider_id: &str, token: &str) -> Result<()> {
|
||||||
keyring::Entry::new(SERVICE, provider_id)
|
keyring::Entry::new(SERVICE, provider_id)
|
||||||
.and_then(|e| e.set_password(token))
|
.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}"))),
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use grove_core::config::ProviderKind;
|
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::io::{Read, Write};
|
||||||
use std::net::TcpListener;
|
use std::net::TcpListener;
|
||||||
use std::sync::mpsc;
|
use std::sync::mpsc;
|
||||||
@@ -48,6 +48,33 @@ fn mock(replies: Vec<(u16, &'static str)>) -> (String, mpsc::Receiver<String>) {
|
|||||||
(url, rx)
|
(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<std::ffi::OsString>);
|
||||||
|
|
||||||
|
impl EnvGuard {
|
||||||
|
fn set(k: &'static str, v: impl AsRef<std::ffi::OsStr>) -> 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 {
|
fn body(req: &str) -> serde_json::Value {
|
||||||
serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap()
|
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]
|
#[test]
|
||||||
fn env_var_overrides_the_keyring() {
|
fn env_var_overrides_the_keyring() {
|
||||||
assert_eq!(token::env_name("gitea-main"), "GROVE_TOKEN_GITEA_MAIN");
|
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.
|
let _l = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
unsafe { std::env::set_var("GROVE_TOKEN_ENV_TEST", " abc ") };
|
let _g = EnvGuard::set("GROVE_TOKEN_ENV_TEST", " abc ");
|
||||||
assert_eq!(token::get("env-test").unwrap(), "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();
|
||||||
|
}
|
||||||
@@ -367,7 +367,9 @@ fn main() -> Result<()> {
|
|||||||
*force,
|
*force,
|
||||||
)?;
|
)?;
|
||||||
println!("wrote {}", path.display());
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Cmd::Login { provider } => {
|
Cmd::Login { provider } => {
|
||||||
@@ -524,6 +526,13 @@ fn doctor(cfg_arg: &Option<PathBuf>) -> Result<()> {
|
|||||||
if let Some(c) = &cfg {
|
if let Some(c) = &cfg {
|
||||||
let root = c.root_path();
|
let root = c.root_path();
|
||||||
line(Some(root.is_dir()), format!("root {}", root.display()));
|
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 {
|
for g in &c.groups {
|
||||||
let gdir = root.join(&g.name);
|
let gdir = root.join(&g.name);
|
||||||
let Ok(rd) = std::fs::read_dir(&gdir) else {
|
let Ok(rd) = std::fs::read_dir(&gdir) else {
|
||||||
|
|||||||
+183
-43
@@ -6,13 +6,15 @@ use grove_core::config::{
|
|||||||
};
|
};
|
||||||
use grove_core::git::Git;
|
use grove_core::git::Git;
|
||||||
use grove_core::registry::{Entry, Registry, clone_bare_layout, init_bare_layout, push_initial};
|
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::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
pub struct Forge {
|
pub struct Forge {
|
||||||
pub api: Box<dyn Provider>,
|
pub api: Box<dyn Provider>,
|
||||||
pub login: String,
|
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.
|
/// Git environment that authenticates HTTPS operations with the stored token.
|
||||||
pub git_env: Vec<(String, String)>,
|
pub git_env: Vec<(String, String)>,
|
||||||
}
|
}
|
||||||
@@ -22,7 +24,7 @@ pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
|
|||||||
.providers
|
.providers
|
||||||
.get(id)
|
.get(id)
|
||||||
.with_context(|| format!("provider {id:?} is not in the config"))?;
|
.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 api = build(pc, tok.clone());
|
||||||
let login = api.test_connection()?;
|
let login = api.test_connection()?;
|
||||||
let git_env = match pc.kind {
|
let git_env = match pc.kind {
|
||||||
@@ -35,16 +37,55 @@ pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
|
|||||||
),
|
),
|
||||||
("GIT_TERMINAL_PROMPT".into(), "0".into()),
|
("GIT_TERMINAL_PROMPT".into(), "0".into()),
|
||||||
],
|
],
|
||||||
// GitHub git-over-HTTPS needs Basic auth; leave it to the user's credential helper.
|
// GitHub git-over-HTTPS takes the token as Basic auth (any user name works).
|
||||||
ProviderKind::Github => vec![("GIT_TERMINAL_PROMPT".into(), "0".into())],
|
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 {
|
Ok(Forge {
|
||||||
api,
|
api,
|
||||||
login,
|
login,
|
||||||
|
token: tok,
|
||||||
git_env,
|
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<String> {
|
||||||
|
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> {
|
fn group<'a>(cfg: &'a Config, name: &str) -> Result<&'a Group> {
|
||||||
cfg.groups
|
cfg.groups
|
||||||
.iter()
|
.iter()
|
||||||
@@ -91,6 +132,8 @@ pub fn init(path: &Path, a: InitArgs, force: bool) -> Result<Config> {
|
|||||||
mirror_to: vec![],
|
mirror_to: vec![],
|
||||||
layout: Layout::BareWorktrees,
|
layout: Layout::BareWorktrees,
|
||||||
auto_materialize: true,
|
auto_materialize: true,
|
||||||
|
owners: Default::default(),
|
||||||
|
public: None,
|
||||||
}],
|
}],
|
||||||
sync: Default::default(),
|
sync: Default::default(),
|
||||||
config_repo: a.config_repo.map(|name| grove_core::config::ConfigRepo {
|
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() {
|
if dir.exists() {
|
||||||
bail!("{} already exists", dir.display());
|
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 {
|
let remote = primary.api.create_repo(&NewRepo {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
owner: None,
|
owner: org_owner(grp, &route.primary, &primary.login),
|
||||||
private,
|
private,
|
||||||
description: String::new(),
|
description: String::new(),
|
||||||
})?;
|
})?;
|
||||||
println!(
|
println!(
|
||||||
"created {}/{} on {}",
|
"created {}/{} on {}",
|
||||||
remote.owner, remote.name, grp.primary
|
remote.owner, remote.name, route.primary
|
||||||
);
|
);
|
||||||
let wt = init_bare_layout(&dir, &remote.clone_url)?;
|
let wt = init_bare_layout(&dir, &remote.clone_url)?;
|
||||||
push_initial(&dir, &primary.git_env)?;
|
push_initial(&dir, &primary.git_env)?;
|
||||||
println!("pushed initial commit; worktree {}", wt.display());
|
println!("pushed initial commit; worktree {}", wt.display());
|
||||||
|
|
||||||
for mid in &grp.mirror_to {
|
for mid in &route.mirror_to {
|
||||||
match configure_mirror(cfg, &primary, mid, &remote.owner, name, private) {
|
match configure_mirror(cfg, grp, &primary, &remote, mid) {
|
||||||
Ok(()) => println!("push mirror to {mid} configured"),
|
Ok(()) => println!("mirror to {mid} configured"),
|
||||||
Err(e) => println!("warning: mirror to {mid} not configured: {e}"),
|
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)
|
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(
|
fn configure_mirror(
|
||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
|
grp: &Group,
|
||||||
primary: &Forge,
|
primary: &Forge,
|
||||||
|
remote: &RemoteRepo,
|
||||||
mirror_id: &str,
|
mirror_id: &str,
|
||||||
owner: &str,
|
|
||||||
name: &str,
|
|
||||||
private: bool,
|
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let m = connect(cfg, mirror_id)?;
|
let m = connect(cfg, mirror_id)?;
|
||||||
let target = m.api.create_repo(&NewRepo {
|
let owner = org_owner(grp, mirror_id, &m.login);
|
||||||
name: name.into(),
|
if primary.api.capabilities().push_mirror {
|
||||||
owner: None,
|
let target = m.api.create_repo(&NewRepo {
|
||||||
private,
|
name: remote.name.clone(),
|
||||||
description: "Mirror managed by grove".into(),
|
owner,
|
||||||
})?;
|
private: remote.private,
|
||||||
primary.api.configure_mirror(
|
description: "Mirror managed by grove".into(),
|
||||||
owner,
|
})?;
|
||||||
name,
|
primary.api.configure_mirror(
|
||||||
&MirrorSpec {
|
&remote.owner,
|
||||||
remote_url: target.clone_url,
|
&remote.name,
|
||||||
remote_username: m.login,
|
&MirrorSpec {
|
||||||
remote_token: token::get(mirror_id)?,
|
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(),
|
interval: "8h0m0s".into(),
|
||||||
sync_on_commit: true,
|
})?;
|
||||||
},
|
}
|
||||||
)?;
|
|
||||||
Ok(())
|
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<RemoteRepo>, owner: &str, private: Option<bool>) -> Vec<RemoteRepo> {
|
||||||
|
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<()> {
|
pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> {
|
||||||
let grp = group(cfg, group_name)?;
|
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 gdir = cfg.root_path().join(&grp.name);
|
||||||
let missing: Vec<_> = primary
|
let mut forges = Vec::new();
|
||||||
.api
|
let mut missing: Vec<(RemoteRepo, usize)> = Vec::new();
|
||||||
.list_repos()?
|
for (pid, vis) in sides {
|
||||||
.into_iter()
|
let f = connect(cfg, &pid)?;
|
||||||
.filter(|r| !gdir.join(&r.name).join(".bare").exists())
|
let owner = grp.owner(&pid).unwrap_or(&f.login).to_string();
|
||||||
.collect();
|
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() {
|
if wanted.is_empty() {
|
||||||
println!("repos on {} not yet in {}:", grp.primary, gdir.display());
|
println!("repos of group {} not yet in {}:", grp.name, gdir.display());
|
||||||
for r in &missing {
|
for (r, i) in &missing {
|
||||||
println!(
|
println!(
|
||||||
" {}/{}{}",
|
" {}/{} on {}{}",
|
||||||
r.owner,
|
r.owner,
|
||||||
r.name,
|
r.name,
|
||||||
|
forges[*i].0,
|
||||||
if r.private { " (private)" } else { "" }
|
if r.private { " (private)" } else { "" }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -209,12 +295,12 @@ pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
for w in wanted {
|
for w in wanted {
|
||||||
let r = missing
|
let (r, i) = missing
|
||||||
.iter()
|
.iter()
|
||||||
.find(|r| &r.name == w)
|
.find(|(r, _)| &r.name == w)
|
||||||
.with_context(|| format!("{w:?} is not a remote repo missing locally"))?;
|
.with_context(|| format!("{w:?} is not a remote repo missing locally"))?;
|
||||||
let dir = gdir.join(&r.name);
|
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());
|
println!("imported {} -> {}", r.name, dir.display());
|
||||||
register(
|
register(
|
||||||
cfg,
|
cfg,
|
||||||
@@ -387,3 +473,57 @@ pub fn bootstrap(cfg: &Config) -> Result<(usize, usize)> {
|
|||||||
commit_and_push(cfg, &dir, &forge, "machine heartbeat")?;
|
commit_and_push(cfg, &dir, &forge, "machine heartbeat")?;
|
||||||
Ok((done, skipped))
|
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<RemoteRepo>| v.into_iter().map(|r| r.name).collect::<Vec<_>>();
|
||||||
|
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"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-1
@@ -10,6 +10,7 @@ Service via `keyring` (service `grove`, user = provider id). Tokens are never wr
|
|||||||
file. `grove login <id>` reads the token from stdin (never argv), checks it against the forge and
|
file. `grove login <id>` 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
|
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.
|
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
|
## Commands
|
||||||
|
|
||||||
@@ -33,7 +34,8 @@ clone lives in `<state dir>/config-repo`. It is created on the first registratio
|
|||||||
Gitea/Forgejo: the primary creates a push mirror via `POST /repos/{o}/{r}/push_mirrors`
|
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
|
(`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
|
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
|
## Validation
|
||||||
|
|
||||||
|
|||||||
@@ -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 <group> <name> [--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 <group>` 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_<ID>`, 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 <host>` 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.
|
||||||
+2
-2
@@ -225,7 +225,7 @@ views.import = () => {
|
|||||||
list.replaceChildren(h('p', { class: 'muted' }, 'Scanning…'));
|
list.replaceChildren(h('p', { class: 'muted' }, 'Scanning…'));
|
||||||
out.replaceChildren();
|
out.replaceChildren();
|
||||||
const r = await cli(['import', sel.value]);
|
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 (!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.'));
|
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));
|
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'),
|
h('h2', {}, 'Providers'),
|
||||||
kv(provs.map(([id, p]) => [id, p.kind + (p.url ? ' · ' + p.url : '')])),
|
kv(provs.map(([id, p]) => [id, p.kind + (p.url ? ' · ' + p.url : '')])),
|
||||||
h('h2', {}, 'Groups'),
|
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'),
|
h('h2', {}, 'Config repository'),
|
||||||
kv([['Repository', cfg.config_repo ? cfg.config_repo.name + ' on ' + cfg.config_repo.provider : 'not configured']]),
|
kv([['Repository', cfg.config_repo ? cfg.config_repo.name + ' on ' + cfg.config_repo.provider : 'not configured']]),
|
||||||
h('div', { class: 'actions' },
|
h('div', { class: 'actions' },
|
||||||
|
|||||||
Reference in new issue
Block a user