mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 23:36:11 +00:00
fix(daemon): gate snapshots on every push URL and mirror target, shorter private TTL, purge on withhold, offline uses last verdict
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
30c84aef2f
commit
9d1a743073
3 files changed
+621
-179
No files matched your search
@@ -5,7 +5,7 @@
|
|||||||
use crate::activity::{Activity, now_secs};
|
use crate::activity::{Activity, now_secs};
|
||||||
use crate::discover::{discover, group_of};
|
use crate::discover::{discover, group_of};
|
||||||
use crate::ipc;
|
use crate::ipc;
|
||||||
use crate::visibility::{Visibility, forge_fetch, snapshot_gate};
|
use crate::visibility::{RealForge, Visibility, snapshot_gate};
|
||||||
use grove_core::config::Config;
|
use grove_core::config::Config;
|
||||||
use grove_core::receive::Received;
|
use grove_core::receive::Received;
|
||||||
use grove_core::sync::{Options, sync_repo};
|
use grove_core::sync::{Options, sync_repo};
|
||||||
@@ -59,6 +59,8 @@ pub struct RepoStatus {
|
|||||||
pub failures: u32,
|
pub failures: u32,
|
||||||
/// Why WIP snapshots are not pushed for this repo (`None` = they are).
|
/// Why WIP snapshots are not pushed for this repo (`None` = they are).
|
||||||
pub snapshots_withheld: Option<String>,
|
pub snapshots_withheld: Option<String>,
|
||||||
|
/// Last verdict of the snapshot gate (`None` = not evaluated yet).
|
||||||
|
pub gate_allowed: Option<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for RepoStatus {
|
impl Default for RepoStatus {
|
||||||
@@ -70,6 +72,7 @@ impl Default for RepoStatus {
|
|||||||
worktrees: Vec::new(),
|
worktrees: Vec::new(),
|
||||||
failures: 0,
|
failures: 0,
|
||||||
snapshots_withheld: None,
|
snapshots_withheld: None,
|
||||||
|
gate_allowed: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -379,16 +382,23 @@ fn pass(
|
|||||||
.iter()
|
.iter()
|
||||||
.find(|g| g.name == group)
|
.find(|g| g.name == group)
|
||||||
.is_none_or(|g| g.auto_materialize);
|
.is_none_or(|g| g.auto_materialize);
|
||||||
// No lookup needed offline: nothing is pushed in such a pass anyway.
|
// Offline there is no lookup: use the last verdict, and take no snapshot if there is none.
|
||||||
let gate = if offline {
|
let push_snapshots = if offline {
|
||||||
Ok(())
|
ctx.shared
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.repos
|
||||||
|
.get(repo)
|
||||||
|
.is_some_and(|s| s.gate_allowed == Some(true))
|
||||||
} else {
|
} else {
|
||||||
snapshot_gate(cfg, repo, &st.remote, visibility, now_secs(), &forge_fetch)
|
let gate = snapshot_gate(cfg, repo, &st.remote, visibility, now_secs(), &RealForge);
|
||||||
};
|
let allowed = gate.is_ok();
|
||||||
let push_snapshots = gate.is_ok();
|
|
||||||
if !offline {
|
|
||||||
note_snapshot_gate(ctx, repo, &name, gate.err());
|
note_snapshot_gate(ctx, repo, &name, gate.err());
|
||||||
|
if !allowed {
|
||||||
|
purge_snapshots(ctx, repo, &name, cfg, st);
|
||||||
}
|
}
|
||||||
|
allowed
|
||||||
|
};
|
||||||
let opts = Options {
|
let opts = Options {
|
||||||
machine: cfg.machine.name.clone(),
|
machine: cfg.machine.name.clone(),
|
||||||
stamp: stamp(),
|
stamp: stamp(),
|
||||||
@@ -485,6 +495,7 @@ fn pass(
|
|||||||
fn note_snapshot_gate(ctx: &Ctx, repo: &Path, name: &str, withheld: Option<String>) {
|
fn note_snapshot_gate(ctx: &Ctx, repo: &Path, name: &str, withheld: Option<String>) {
|
||||||
let mut shared = ctx.shared.lock().unwrap();
|
let mut shared = ctx.shared.lock().unwrap();
|
||||||
let status = shared.repos.entry(repo.to_path_buf()).or_default();
|
let status = shared.repos.entry(repo.to_path_buf()).or_default();
|
||||||
|
status.gate_allowed = Some(withheld.is_none());
|
||||||
if status.snapshots_withheld == withheld {
|
if status.snapshots_withheld == withheld {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -501,6 +512,31 @@ fn note_snapshot_gate(ctx: &Ctx, repo: &Path, name: &str, withheld: Option<Strin
|
|||||||
status.snapshots_withheld = withheld;
|
status.snapshots_withheld = withheld;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Snapshots are withheld: remove this machine's snapshot refs from the remote (they may have
|
||||||
|
/// been pushed while the repo was still private) and locally. Only `refs/sync/<machine>/*`;
|
||||||
|
/// never other machines' refs or branches. Does nothing when there are no local refs, and a
|
||||||
|
/// failed deletion keeps them so the next pass retries.
|
||||||
|
fn purge_snapshots(ctx: &Ctx, repo: &Path, name: &str, cfg: &Config, st: &Settings) {
|
||||||
|
let gitdir = grove_core::sync::git_dir_for(repo);
|
||||||
|
match grove_core::receive::purge_own_snapshots(&gitdir, &cfg.machine.name, &st.remote) {
|
||||||
|
Ok(done) if done.is_empty() => {}
|
||||||
|
Ok(done) => ctx.activity.log(
|
||||||
|
"snapshots_purged",
|
||||||
|
Some(name),
|
||||||
|
format!(
|
||||||
|
"WARNING: snapshots are no longer allowed; deleted {} snapshot ref(s) of this machine from the remote: {}",
|
||||||
|
done.len(),
|
||||||
|
done.join(", ")
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Err(e) => ctx.activity.log(
|
||||||
|
"error",
|
||||||
|
Some(name),
|
||||||
|
format!("could not delete this machine's snapshot refs from the remote: {e}"),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn set_phase(ctx: &Ctx, repo: &Path, phase: &'static str) {
|
fn set_phase(ctx: &Ctx, repo: &Path, phase: &'static str) {
|
||||||
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(repo) {
|
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(repo) {
|
||||||
s.phase = phase;
|
s.phase = phase;
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
//! Snapshot privacy: WIP snapshots hold uncommitted work, so under the default `private-only`
|
//! Snapshot privacy: WIP snapshots hold uncommitted work, so under the default `private-only`
|
||||||
//! policy they are pushed only to repos the forge reports as private. Anything unknown (no
|
//! policy they are pushed only when EVERY place the push can reach is known to be private: all
|
||||||
//! matching provider, no token, network error, odd answer) is treated as public.
|
//! push URLs of `origin` (pushurl, several urls, pushInsteadOf) and the repo's mirror targets
|
||||||
|
//! configured for its group (forge-side push/pull mirrors copy `refs/sync/*` too). Anything
|
||||||
|
//! unknown (no or several matching providers, no token, network error, odd answer) counts as
|
||||||
|
//! public.
|
||||||
//!
|
//!
|
||||||
//! Answers are cached in `<state dir>/visibility.json` and refreshed every [`TTL`] seconds;
|
//! Answers are cached in `<state dir>/visibility.json` (mode 0600). A "private" answer is trusted
|
||||||
//! failed lookups are retried at most every [`RETRY`] seconds.
|
//! for [`PRIVATE_TTL`] only; failed lookups are retried at most every [`RETRY`] seconds.
|
||||||
|
//! Residual risk: mirrors made by hand outside grove's config are not known to the daemon.
|
||||||
|
|
||||||
use grove_core::config::{Config, Provider as ProviderCfg, ProviderKind, SnapshotPolicy};
|
use grove_core::config::{Config, Provider as ProviderCfg, ProviderKind, SnapshotPolicy};
|
||||||
use grove_core::git::Git;
|
use grove_core::git::Git;
|
||||||
@@ -12,15 +16,23 @@ use serde::{Deserialize, Serialize};
|
|||||||
use std::collections::{BTreeMap, HashMap};
|
use std::collections::{BTreeMap, HashMap};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
/// How long a successful answer is trusted.
|
/// How long a "private" answer is trusted (a repo can be made public at any time).
|
||||||
pub const TTL: u64 = 6 * 3600;
|
pub const PRIVATE_TTL: u64 = 3600;
|
||||||
|
/// How long a "not private" or "absent" answer is trusted.
|
||||||
|
pub const OTHER_TTL: u64 = 6 * 3600;
|
||||||
/// Minimum wait before asking the forge again after a failed lookup.
|
/// Minimum wait before asking the forge again after a failed lookup.
|
||||||
pub const RETRY: u64 = 300;
|
pub const RETRY: u64 = 300;
|
||||||
|
|
||||||
/// Host (lowercase, no port) and `owner/name` of a remote URL.
|
/// A parsed remote URL.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct RepoId {
|
pub struct RepoId {
|
||||||
pub host: String,
|
pub host: String,
|
||||||
|
/// Explicit port, if any.
|
||||||
|
pub port: Option<u16>,
|
||||||
|
/// `http`, `https` or `ssh` (scp-like URLs are `ssh`).
|
||||||
|
pub scheme: String,
|
||||||
|
/// Path segments before `owner` (a forge installed under a sub-path).
|
||||||
|
pub prefix: Vec<String>,
|
||||||
pub owner: String,
|
pub owner: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
}
|
}
|
||||||
@@ -29,17 +41,32 @@ pub struct RepoId {
|
|||||||
/// scp-like `git@host:owner/repo.git`. The last two path segments are owner and name.
|
/// scp-like `git@host:owner/repo.git`. The last two path segments are owner and name.
|
||||||
pub fn parse_remote(url: &str) -> Option<RepoId> {
|
pub fn parse_remote(url: &str) -> Option<RepoId> {
|
||||||
let url = url.trim();
|
let url = url.trim();
|
||||||
let (authority, path) = match url.split_once("://") {
|
let (scheme, authority, path) = match url.split_once("://") {
|
||||||
Some((_, rest)) => rest.split_once('/')?,
|
Some((s, rest)) => {
|
||||||
None => url.split_once(':')?,
|
let (a, p) = rest.split_once('/')?;
|
||||||
|
(s.to_ascii_lowercase(), a, p)
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let (a, p) = url.split_once(':')?;
|
||||||
|
("ssh".to_string(), a, p)
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
|
let hostport = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
|
||||||
let host = match host.strip_prefix('[') {
|
let (host, port) = match hostport.strip_prefix('[') {
|
||||||
Some(v6) => v6.split(']').next()?, // [::1]:22
|
Some(v6) => {
|
||||||
None => host.split(':').next()?,
|
let (h, rest) = v6.split_once(']')?;
|
||||||
|
(h, rest.strip_prefix(':').and_then(|p| p.parse().ok()))
|
||||||
|
}
|
||||||
|
None => match hostport.split_once(':') {
|
||||||
|
Some((h, p)) if scheme != "ssh" || url.contains("://") => (h, p.parse().ok()),
|
||||||
|
Some((h, _)) => (h, None),
|
||||||
|
None => (hostport, None),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
let mut segs: Vec<&str> = path
|
let mut segs: Vec<&str> = path
|
||||||
.split(['/', '?', '#'])
|
.split(['?', '#'])
|
||||||
|
.next()?
|
||||||
|
.split('/')
|
||||||
.filter(|s| !s.is_empty())
|
.filter(|s| !s.is_empty())
|
||||||
.collect();
|
.collect();
|
||||||
let last = segs.pop()?;
|
let last = segs.pop()?;
|
||||||
@@ -50,35 +77,80 @@ pub fn parse_remote(url: &str) -> Option<RepoId> {
|
|||||||
}
|
}
|
||||||
Some(RepoId {
|
Some(RepoId {
|
||||||
host: host.to_ascii_lowercase(),
|
host: host.to_ascii_lowercase(),
|
||||||
|
port,
|
||||||
|
scheme,
|
||||||
|
prefix: segs.iter().map(|s| s.to_string()).collect(),
|
||||||
owner: owner.to_string(),
|
owner: owner.to_string(),
|
||||||
name: name.to_string(),
|
name: name.to_string(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Host (lowercase, no port) a provider answers for. GitHub without a URL is `github.com`; a
|
fn default_port(scheme: &str) -> Option<u16> {
|
||||||
/// leading `api.` is dropped so API URLs map to the clone host.
|
match scheme {
|
||||||
fn provider_host(cfg: &ProviderCfg) -> Option<String> {
|
"http" => Some(80),
|
||||||
let url = cfg.url.as_deref().map(str::trim).filter(|u| !u.is_empty());
|
"https" => Some(443),
|
||||||
let Some(url) = url else {
|
_ => None,
|
||||||
return (cfg.kind == ProviderKind::Github).then(|| "github.com".to_string());
|
}
|
||||||
};
|
|
||||||
let rest = url.split_once("://").map_or(url, |(_, r)| r);
|
|
||||||
let auth = rest.split(['/', '?', '#']).next()?;
|
|
||||||
let auth = auth.rsplit_once('@').map_or(auth, |(_, h)| h);
|
|
||||||
let host = auth.split(':').next()?.to_ascii_lowercase();
|
|
||||||
let host = match cfg.kind {
|
|
||||||
ProviderKind::Github => host.strip_prefix("api.").unwrap_or(&host).to_string(),
|
|
||||||
_ => host,
|
|
||||||
};
|
|
||||||
(!host.is_empty()).then_some(host)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The configured provider (id and config) that serves `host`.
|
/// Whether the provider `cfg` serves the repo behind `id`: same host, same port (http/https
|
||||||
pub fn provider_for<'a>(cfg: &'a Config, host: &str) -> Option<(&'a str, &'a ProviderCfg)> {
|
/// only: an ssh port says nothing about the web port), and the provider's URL path is a prefix
|
||||||
cfg.providers
|
/// of the repo path (not checked for GitHub, whose API URL differs from its clone URL).
|
||||||
.iter()
|
fn serves(cfg: &ProviderCfg, id: &RepoId) -> bool {
|
||||||
.find(|(_, p)| provider_host(p).as_deref() == Some(host))
|
let url = cfg.url.as_deref().map(str::trim).filter(|u| !u.is_empty());
|
||||||
.map(|(id, p)| (id.as_str(), p))
|
let (scheme, authority, path) = match url {
|
||||||
|
None => {
|
||||||
|
return cfg.kind == ProviderKind::Github
|
||||||
|
&& id.host == "github.com"
|
||||||
|
&& (id.scheme == "ssh"
|
||||||
|
|| id.port.is_none_or(|p| Some(p) == default_port(&id.scheme)));
|
||||||
|
}
|
||||||
|
Some(u) => match u.split_once("://") {
|
||||||
|
Some((s, r)) => {
|
||||||
|
let (a, p) = r.split_once('/').unwrap_or((r, ""));
|
||||||
|
(s.to_ascii_lowercase(), a, p)
|
||||||
|
}
|
||||||
|
None => ("https".to_string(), u, ""),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let hostport = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
|
||||||
|
let (host, port) = match hostport.split_once(':') {
|
||||||
|
Some((h, p)) => (h, p.parse::<u16>().ok()),
|
||||||
|
None => (hostport, None),
|
||||||
|
};
|
||||||
|
let mut host = host.to_ascii_lowercase();
|
||||||
|
if cfg.kind == ProviderKind::Github {
|
||||||
|
host = host.strip_prefix("api.").unwrap_or(&host).to_string();
|
||||||
|
}
|
||||||
|
if host != id.host {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if id.scheme != "ssh" {
|
||||||
|
let mine = port.or(default_port(&scheme));
|
||||||
|
let theirs = id.port.or(default_port(&id.scheme));
|
||||||
|
if mine != theirs {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cfg.kind == ProviderKind::Github || id.scheme == "ssh" {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let want: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
||||||
|
id.prefix.len() >= want.len() && id.prefix.iter().zip(&want).all(|(a, b)| a == b)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one configured provider (id and config) that serves `id`. Zero or several matches are an
|
||||||
|
/// error: with several candidates the repo's visibility cannot be told.
|
||||||
|
pub fn provider_for<'a>(
|
||||||
|
cfg: &'a Config,
|
||||||
|
id: &RepoId,
|
||||||
|
) -> Result<(&'a str, &'a ProviderCfg), String> {
|
||||||
|
let mut hits = cfg.providers.iter().filter(|(_, p)| serves(p, id));
|
||||||
|
match (hits.next(), hits.next()) {
|
||||||
|
(Some((i, p)), None) => Ok((i.as_str(), p)),
|
||||||
|
(None, _) => Err(format!("no configured provider for host {}", id.host)),
|
||||||
|
_ => Err(format!("several providers match host {}", id.host)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
@@ -89,23 +161,65 @@ pub enum Verdict {
|
|||||||
Unknown(String),
|
Unknown(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What a forge says about one repo.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Seen {
|
||||||
|
Private,
|
||||||
|
NotPrivate,
|
||||||
|
/// 404: no such repo (or not visible to the token, so not public either).
|
||||||
|
Absent,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The forge lookups the daemon needs; faked in tests.
|
||||||
|
pub trait Forge {
|
||||||
|
fn seen(&self, id: &str, pc: &ProviderCfg, owner: &str, name: &str) -> Result<Seen, String>;
|
||||||
|
/// The login the token belongs to (owner of repos without an `owners` entry).
|
||||||
|
fn login(&self, id: &str, pc: &ProviderCfg) -> Result<String, String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The real forges: token via `token::resolve` (grove login, Secret Service, tea/gh).
|
||||||
|
pub struct RealForge;
|
||||||
|
|
||||||
|
impl RealForge {
|
||||||
|
fn provider(id: &str, pc: &ProviderCfg) -> Result<Box<dyn grove_providers::Provider>, String> {
|
||||||
|
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
|
||||||
|
Ok(grove_providers::build(pc, token))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Forge for RealForge {
|
||||||
|
fn seen(&self, id: &str, pc: &ProviderCfg, owner: &str, name: &str) -> Result<Seen, String> {
|
||||||
|
match Self::provider(id, pc)?.get_repo(owner, name) {
|
||||||
|
Ok(r) if r.private => Ok(Seen::Private),
|
||||||
|
Ok(_) => Ok(Seen::NotPrivate),
|
||||||
|
Err(grove_providers::Error::Api { status: 404, .. }) => Ok(Seen::Absent),
|
||||||
|
Err(e) => Err(e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn login(&self, id: &str, pc: &ProviderCfg) -> Result<String, String> {
|
||||||
|
Self::provider(id, pc)?
|
||||||
|
.test_connection()
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
struct Entry {
|
struct Entry {
|
||||||
private: bool,
|
seen: Seen,
|
||||||
checked: u64,
|
checked: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Asks the forge whether `owner/name` is private: `(provider id, provider config, owner, name)`.
|
impl Entry {
|
||||||
pub type Fetch<'a> = &'a dyn Fn(&str, &ProviderCfg, &str, &str) -> Result<bool, String>;
|
/// A timestamp in the future (clock change, hand-edited file) counts as expired.
|
||||||
|
fn fresh(&self, now: u64) -> bool {
|
||||||
/// The real lookup: token via `token::resolve` (grove login, Secret Service, tea/gh), then
|
let ttl = match self.seen {
|
||||||
/// `GET /repos/{owner}/{repo}`.
|
Seen::Private => PRIVATE_TTL,
|
||||||
pub fn forge_fetch(id: &str, pc: &ProviderCfg, owner: &str, name: &str) -> Result<bool, String> {
|
_ => OTHER_TTL,
|
||||||
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
|
};
|
||||||
let p = grove_providers::build(pc, token);
|
self.checked <= now && now - self.checked < ttl
|
||||||
p.get_repo(owner, name)
|
}
|
||||||
.map(|r| r.private)
|
|
||||||
.map_err(|e| e.to_string())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Visibility cache. Owned by the daemon's single worker thread.
|
/// Visibility cache. Owned by the daemon's single worker thread.
|
||||||
@@ -114,6 +228,7 @@ pub struct Visibility {
|
|||||||
path: Option<PathBuf>,
|
path: Option<PathBuf>,
|
||||||
entries: BTreeMap<String, Entry>,
|
entries: BTreeMap<String, Entry>,
|
||||||
failed: HashMap<String, (u64, String)>,
|
failed: HashMap<String, (u64, String)>,
|
||||||
|
logins: HashMap<String, String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Visibility {
|
impl Visibility {
|
||||||
@@ -127,69 +242,125 @@ impl Visibility {
|
|||||||
Visibility {
|
Visibility {
|
||||||
path,
|
path,
|
||||||
entries,
|
entries,
|
||||||
failed: HashMap::new(),
|
..Visibility::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save(&self) {
|
fn save(&self) {
|
||||||
|
use std::io::Write;
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
let Some(path) = &self.path else { return };
|
let Some(path) = &self.path else { return };
|
||||||
if let Some(dir) = path.parent() {
|
if let Some(dir) = path.parent() {
|
||||||
let _ = std::fs::create_dir_all(dir);
|
let _ = std::fs::create_dir_all(dir);
|
||||||
}
|
}
|
||||||
let tmp = path.with_extension("json.tmp");
|
let tmp = path.with_extension("json.tmp");
|
||||||
if let Ok(text) = serde_json::to_string_pretty(&self.entries)
|
let _ = std::fs::remove_file(&tmp);
|
||||||
&& std::fs::write(&tmp, text).is_ok()
|
let Ok(text) = serde_json::to_string_pretty(&self.entries) else {
|
||||||
{
|
return;
|
||||||
|
};
|
||||||
|
let written = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.mode(0o600)
|
||||||
|
.open(&tmp)
|
||||||
|
.and_then(|mut f| f.write_all(text.as_bytes()));
|
||||||
|
if written.is_ok() {
|
||||||
let _ = std::fs::rename(&tmp, path);
|
let _ = std::fs::rename(&tmp, path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Visibility of the repo behind `origin_url`, from the cache or the forge.
|
/// What the forge says about `owner/name` on provider `pid`, from the cache or the forge.
|
||||||
pub fn check(&mut self, cfg: &Config, origin_url: &str, now: u64, fetch: Fetch) -> Verdict {
|
fn seen(
|
||||||
let Some(id) = parse_remote(origin_url) else {
|
&mut self,
|
||||||
return Verdict::Unknown("origin URL not understood".into());
|
pid: &str,
|
||||||
};
|
pc: &ProviderCfg,
|
||||||
let Some((pid, pc)) = provider_for(cfg, &id.host) else {
|
owner: &str,
|
||||||
return Verdict::Unknown(format!("no configured provider for host {}", id.host));
|
name: &str,
|
||||||
};
|
now: u64,
|
||||||
let key = format!("{}/{}/{}", id.host, id.owner, id.name).to_ascii_lowercase();
|
forge: &dyn Forge,
|
||||||
let verdict = |private| {
|
) -> Result<Seen, String> {
|
||||||
if private {
|
let key = format!("{pid}/{owner}/{name}").to_ascii_lowercase();
|
||||||
Verdict::Private
|
|
||||||
} else {
|
|
||||||
Verdict::Public
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Some(e) = self.entries.get(&key)
|
if let Some(e) = self.entries.get(&key)
|
||||||
&& now.saturating_sub(e.checked) < TTL
|
&& e.fresh(now)
|
||||||
{
|
{
|
||||||
return verdict(e.private);
|
return Ok(e.seen);
|
||||||
}
|
}
|
||||||
if let Some((at, why)) = self.failed.get(&key)
|
if let Some((at, why)) = self.failed.get(&key)
|
||||||
&& now.saturating_sub(*at) < RETRY
|
&& at.saturating_sub(0) <= now
|
||||||
|
&& now - at < RETRY
|
||||||
{
|
{
|
||||||
return Verdict::Unknown(why.clone());
|
return Err(why.clone());
|
||||||
}
|
}
|
||||||
match fetch(pid, pc, &id.owner, &id.name) {
|
match forge.seen(pid, pc, owner, name) {
|
||||||
Ok(private) => {
|
Ok(seen) => {
|
||||||
self.failed.remove(&key);
|
self.failed.remove(&key);
|
||||||
self.entries.insert(
|
self.entries.insert(key, Entry { seen, checked: now });
|
||||||
key,
|
|
||||||
Entry {
|
|
||||||
private,
|
|
||||||
checked: now,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
self.save();
|
self.save();
|
||||||
verdict(private)
|
Ok(seen)
|
||||||
}
|
}
|
||||||
Err(why) => {
|
Err(why) => {
|
||||||
let why = format!("lookup on {pid:?} failed: {why}");
|
let why = format!("lookup on {pid:?} failed: {why}");
|
||||||
self.failed.insert(key, (now, why.clone()));
|
self.failed.insert(key, (now, why.clone()));
|
||||||
Verdict::Unknown(why)
|
Err(why)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Visibility of the repo behind one push URL.
|
||||||
|
pub fn check_url(&mut self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
|
||||||
|
let Some(id) = parse_remote(url) else {
|
||||||
|
return Verdict::Unknown("push URL not understood".into());
|
||||||
|
};
|
||||||
|
let (pid, pc) = match provider_for(cfg, &id) {
|
||||||
|
Ok(x) => x,
|
||||||
|
Err(e) => return Verdict::Unknown(e),
|
||||||
|
};
|
||||||
|
match self.seen(pid, pc, &id.owner, &id.name, now, forge) {
|
||||||
|
Ok(Seen::Private) => Verdict::Private,
|
||||||
|
Ok(Seen::NotPrivate) => Verdict::Public,
|
||||||
|
Ok(Seen::Absent) => Verdict::Unknown(format!("repo not found on {pid:?}")),
|
||||||
|
Err(why) => Verdict::Unknown(why),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mirror target `name` on provider `pid`: `Ok` when it is private or does not exist.
|
||||||
|
fn check_mirror(
|
||||||
|
&mut self,
|
||||||
|
cfg: &Config,
|
||||||
|
group: &str,
|
||||||
|
pid: &str,
|
||||||
|
name: &str,
|
||||||
|
now: u64,
|
||||||
|
forge: &dyn Forge,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let pc = cfg
|
||||||
|
.providers
|
||||||
|
.get(pid)
|
||||||
|
.ok_or_else(|| format!("unknown mirror provider {pid:?}"))?;
|
||||||
|
let owner = match cfg
|
||||||
|
.groups
|
||||||
|
.iter()
|
||||||
|
.find(|g| g.name == group)
|
||||||
|
.and_then(|g| g.owner(pid))
|
||||||
|
{
|
||||||
|
Some(o) => o.to_string(),
|
||||||
|
None => match self.logins.get(pid) {
|
||||||
|
Some(l) => l.clone(),
|
||||||
|
None => {
|
||||||
|
let l = forge
|
||||||
|
.login(pid, pc)
|
||||||
|
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
|
||||||
|
self.logins.insert(pid.to_string(), l.clone());
|
||||||
|
l
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
match self.seen(pid, pc, &owner, name, now, forge) {
|
||||||
|
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(why) => Err(format!("mirror {pid}:{owner}/{name}: {why}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Policy decision: `Ok(())` to push snapshots, `Err(reason)` to withhold them. Unknown
|
/// Policy decision: `Ok(())` to push snapshots, `Err(reason)` to withhold them. Unknown
|
||||||
@@ -208,6 +379,15 @@ pub fn decide(policy: SnapshotPolicy, verdict: impl FnOnce() -> Verdict) -> Resu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where `git push <remote>` goes: `git remote get-url --push --all` honours `pushurl`, several
|
||||||
|
/// urls and `pushInsteadOf`.
|
||||||
|
fn push_urls(repo: &Path, remote: &str) -> Vec<String> {
|
||||||
|
Git::new(git_dir_for(repo))
|
||||||
|
.run(&["remote", "get-url", "--push", "--all", remote])
|
||||||
|
.map(|o| o.lines().map(|l| l.trim().to_string()).collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether the daemon may push WIP snapshots of `repo` (a bare-layout repo in a group).
|
/// Whether the daemon may push WIP snapshots of `repo` (a bare-layout repo in a group).
|
||||||
pub fn snapshot_gate(
|
pub fn snapshot_gate(
|
||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
@@ -215,25 +395,81 @@ pub fn snapshot_gate(
|
|||||||
remote: &str,
|
remote: &str,
|
||||||
vis: &mut Visibility,
|
vis: &mut Visibility,
|
||||||
now: u64,
|
now: u64,
|
||||||
fetch: Fetch,
|
forge: &dyn Forge,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let group = crate::discover::group_of(repo).unwrap_or_default();
|
let group = crate::discover::group_of(repo).unwrap_or_default();
|
||||||
|
let mut name = None;
|
||||||
decide(cfg.snapshot_policy(&group), || {
|
decide(cfg.snapshot_policy(&group), || {
|
||||||
let url = Git::new(git_dir_for(repo))
|
let urls = push_urls(repo, remote);
|
||||||
.probe(&["config", "--get", &format!("remote.{remote}.url")])
|
if urls.is_empty() {
|
||||||
.ok()
|
return Verdict::Unknown(format!("no push URL for {remote}"));
|
||||||
.flatten();
|
|
||||||
match url {
|
|
||||||
Some(u) => vis.check(cfg, &u, now, fetch),
|
|
||||||
None => Verdict::Unknown(format!("no {remote} remote")),
|
|
||||||
}
|
}
|
||||||
})
|
for u in &urls {
|
||||||
|
match vis.check_url(cfg, u, now, forge) {
|
||||||
|
Verdict::Private => {}
|
||||||
|
other => return other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name = parse_remote(&urls[0]).map(|i| i.name);
|
||||||
|
Verdict::Private
|
||||||
|
})?;
|
||||||
|
if cfg.snapshot_policy(&group) != SnapshotPolicy::PrivateOnly {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// Forge-side mirrors copy refs/sync/* to their targets, which must be private too.
|
||||||
|
let Some(name) = name else {
|
||||||
|
return Err("repo name unknown".into());
|
||||||
|
};
|
||||||
|
let Some(g) = cfg.groups.iter().find(|g| g.name == group) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let mut targets: Vec<String> = [g.route(true), g.route(false)]
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|r| r.mirror_to)
|
||||||
|
.collect();
|
||||||
|
targets.sort();
|
||||||
|
targets.dedup();
|
||||||
|
for pid in targets {
|
||||||
|
vis.check_mirror(cfg, &group, &pid, &name, now, forge)
|
||||||
|
.map_err(|e| format!("{e} (snapshots = \"private-only\")"))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::cell::Cell;
|
use std::cell::{Cell, RefCell};
|
||||||
|
|
||||||
|
/// Scripted forge: answers by `owner/name` (lowercase); anything else is an error.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Fake {
|
||||||
|
repos: HashMap<String, Result<Seen, String>>,
|
||||||
|
calls: Cell<u32>,
|
||||||
|
asked: RefCell<Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fake {
|
||||||
|
fn with(mut self, key: &str, v: Result<Seen, &str>) -> Fake {
|
||||||
|
self.repos.insert(key.into(), v.map_err(str::to_string));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Forge for Fake {
|
||||||
|
fn seen(&self, id: &str, _: &ProviderCfg, owner: &str, name: &str) -> Result<Seen, String> {
|
||||||
|
self.calls.set(self.calls.get() + 1);
|
||||||
|
let key = format!("{owner}/{name}").to_ascii_lowercase();
|
||||||
|
self.asked.borrow_mut().push(format!("{id}:{key}"));
|
||||||
|
self.repos
|
||||||
|
.get(&key)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or(Err("no such fake".into()))
|
||||||
|
}
|
||||||
|
fn login(&self, _: &str, _: &ProviderCfg) -> Result<String, String> {
|
||||||
|
Ok("me".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn cfg() -> Config {
|
fn cfg() -> Config {
|
||||||
Config::parse(
|
Config::parse(
|
||||||
@@ -258,6 +494,11 @@ snapshots = "all"
|
|||||||
name = "off"
|
name = "off"
|
||||||
primary = "gitea"
|
primary = "gitea"
|
||||||
snapshots = "none"
|
snapshots = "none"
|
||||||
|
[[groups]]
|
||||||
|
name = "mir"
|
||||||
|
primary = "gitea"
|
||||||
|
mirror_to = ["github"]
|
||||||
|
owners = { github = "gh-org" }
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -265,65 +506,94 @@ snapshots = "none"
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_remote_url_forms() {
|
fn parses_remote_url_forms() {
|
||||||
let id = |h: &str, o: &str, n: &str| {
|
let r = |s: &str| parse_remote(s).unwrap();
|
||||||
Some(RepoId {
|
let a = r("https://github.com/Org/repo.git");
|
||||||
host: h.into(),
|
|
||||||
owner: o.into(),
|
|
||||||
name: n.into(),
|
|
||||||
})
|
|
||||||
};
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parse_remote("https://github.com/Org/repo.git"),
|
(a.host.as_str(), a.owner.as_str(), a.name.as_str()),
|
||||||
id("github.com", "Org", "repo")
|
("github.com", "Org", "repo")
|
||||||
);
|
);
|
||||||
|
assert_eq!(a.port, None);
|
||||||
|
let b = r("git@GitHub.com:Org/repo.git");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parse_remote("git@GitHub.com:Org/repo.git"),
|
(b.host.as_str(), b.scheme.as_str(), b.port),
|
||||||
id("github.com", "Org", "repo")
|
("github.com", "ssh", None)
|
||||||
);
|
);
|
||||||
|
let c = r("ssh://git@git.example.com:2222/o/r");
|
||||||
|
assert_eq!((c.host.as_str(), c.port), ("git.example.com", Some(2222)));
|
||||||
|
let d = r("https://u:p@h.io:3000/sub/o/r.git/");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parse_remote("ssh://git@git.example.com:2222/o/r"),
|
(d.port, d.prefix.clone(), d.owner.as_str()),
|
||||||
id("git.example.com", "o", "r")
|
(Some(3000), vec!["sub".to_string()], "o")
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert!(parse_remote("/local/path/repo.git").is_none());
|
||||||
parse_remote("https://u:p@h.io:3000/sub/o/r.git/"),
|
assert!(parse_remote("https://host/onlyone").is_none());
|
||||||
id("h.io", "o", "r")
|
|
||||||
);
|
|
||||||
assert_eq!(parse_remote("/local/path/repo.git"), None);
|
|
||||||
assert_eq!(parse_remote("https://host/onlyone"), None);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn matches_providers_by_host() {
|
fn matches_providers_by_host_port_and_path_prefix() {
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
assert_eq!(provider_for(&c, "git.example.com").unwrap().0, "gitea");
|
let m = |u: &str| provider_for(&c, &parse_remote(u).unwrap()).map(|(i, _)| i.to_string());
|
||||||
assert_eq!(provider_for(&c, "github.com").unwrap().0, "github");
|
assert_eq!(m("https://git.example.com:3000/o/r").unwrap(), "gitea");
|
||||||
assert!(provider_for(&c, "gitlab.com").is_none());
|
assert_eq!(m("ssh://git@git.example.com:22/o/r").unwrap(), "gitea");
|
||||||
|
assert_eq!(m("git@git.example.com:o/r.git").unwrap(), "gitea");
|
||||||
|
assert!(m("https://git.example.com/o/r").is_err(), "other web port");
|
||||||
|
assert_eq!(m("https://github.com/o/r").unwrap(), "github");
|
||||||
|
assert_eq!(m("git@github.com:o/r.git").unwrap(), "github");
|
||||||
|
assert!(m("https://gitlab.com/o/r").is_err());
|
||||||
|
|
||||||
|
let sub = Config::parse(
|
||||||
|
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n[providers.a]\nkind=\"gitea\"\nurl=\"https://h.io/a\"\n[providers.b]\nkind=\"gitea\"\nurl=\"https://h.io/b\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let m = |u: &str| provider_for(&sub, &parse_remote(u).unwrap()).map(|(i, _)| i.to_string());
|
||||||
|
assert_eq!(m("https://h.io/a/o/r").unwrap(), "a");
|
||||||
|
assert_eq!(m("https://h.io/b/o/r").unwrap(), "b");
|
||||||
|
assert!(m("https://h.io/o/r").is_err());
|
||||||
|
|
||||||
|
// Two providers for the same host: ambiguous, so unknown.
|
||||||
|
let dup = Config::parse(
|
||||||
|
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n[providers.a]\nkind=\"gitea\"\nurl=\"https://h.io\"\n[providers.b]\nkind=\"forgejo\"\nurl=\"https://h.io\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
|
||||||
|
assert!(e.contains("several"));
|
||||||
|
let mut v = Visibility::default();
|
||||||
|
let fake = Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
|
assert!(matches!(
|
||||||
|
v.check_url(&dup, "https://h.io/o/r", 0, &fake),
|
||||||
|
Verdict::Unknown(_)
|
||||||
|
));
|
||||||
|
assert_eq!(fake.calls.get(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn unknown_visibility_is_public_and_withholds_snapshots() {
|
fn unknown_visibility_is_public_and_withholds_snapshots() {
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let mut v = Visibility::default();
|
let mut v = Visibility::default();
|
||||||
let boom = |_: &str, _: &ProviderCfg, _: &str, _: &str| Err("no token".to_string());
|
let boom = Fake::default();
|
||||||
// Unmatched host, unparsable URL and a failing lookup are all "unknown".
|
|
||||||
for url in [
|
for url in [
|
||||||
"https://gitlab.com/o/r.git",
|
"https://gitlab.com/o/r.git",
|
||||||
"/some/path",
|
"/some/path",
|
||||||
"https://github.com/o/r",
|
"https://github.com/o/r",
|
||||||
] {
|
] {
|
||||||
let verdict = v.check(&c, url, 1000, &boom);
|
let verdict = v.check_url(&c, url, 1000, &boom);
|
||||||
assert!(matches!(verdict, Verdict::Unknown(_)), "{url}: {verdict:?}");
|
assert!(matches!(verdict, Verdict::Unknown(_)), "{url}: {verdict:?}");
|
||||||
assert!(decide(SnapshotPolicy::PrivateOnly, || verdict).is_err());
|
assert!(decide(SnapshotPolicy::PrivateOnly, || verdict).is_err());
|
||||||
}
|
}
|
||||||
// Public and private answers.
|
let f = Fake::default()
|
||||||
let public = |_: &str, _: &ProviderCfg, _: &str, _: &str| Ok(false);
|
.with("o/pub", Ok(Seen::NotPrivate))
|
||||||
let private = |_: &str, _: &ProviderCfg, _: &str, _: &str| Ok(true);
|
.with("o/priv", Ok(Seen::Private))
|
||||||
let p = v.check(&c, "https://github.com/o/pub", 1000, &public);
|
.with("o/gone", Ok(Seen::Absent));
|
||||||
|
let p = v.check_url(&c, "https://github.com/o/pub", 1000, &f);
|
||||||
assert_eq!(p, Verdict::Public);
|
assert_eq!(p, Verdict::Public);
|
||||||
assert!(decide(SnapshotPolicy::PrivateOnly, || p).is_err());
|
assert!(decide(SnapshotPolicy::PrivateOnly, || p).is_err());
|
||||||
let q = v.check(&c, "https://github.com/o/priv", 1000, &private);
|
let q = v.check_url(&c, "https://github.com/o/priv", 1000, &f);
|
||||||
assert_eq!(q, Verdict::Private);
|
assert_eq!(q, Verdict::Private);
|
||||||
assert!(decide(SnapshotPolicy::PrivateOnly, || q).is_ok());
|
assert!(decide(SnapshotPolicy::PrivateOnly, || q).is_ok());
|
||||||
|
assert!(matches!(
|
||||||
|
v.check_url(&c, "https://github.com/o/gone", 1000, &f),
|
||||||
|
Verdict::Unknown(_)
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -334,90 +604,193 @@ snapshots = "none"
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn answers_are_cached_until_the_ttl_and_failures_are_throttled() {
|
fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let mut v = Visibility::default();
|
let mut v = Visibility::default();
|
||||||
let calls = Cell::new(0);
|
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
let ok = |_: &str, _: &ProviderCfg, _: &str, _: &str| {
|
|
||||||
calls.set(calls.get() + 1);
|
|
||||||
Ok(true)
|
|
||||||
};
|
|
||||||
let url = "https://github.com/o/r";
|
let url = "https://github.com/o/r";
|
||||||
assert_eq!(v.check(&c, url, 0, &ok), Verdict::Private);
|
assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private);
|
||||||
assert_eq!(v.check(&c, url, TTL - 1, &ok), Verdict::Private);
|
assert_eq!(
|
||||||
assert_eq!(calls.get(), 1);
|
v.check_url(&c, url, 100 + PRIVATE_TTL - 1, &f),
|
||||||
assert_eq!(v.check(&c, url, TTL, &ok), Verdict::Private);
|
Verdict::Private
|
||||||
assert_eq!(calls.get(), 2);
|
);
|
||||||
|
assert_eq!(f.calls.get(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
v.check_url(&c, url, 100 + PRIVATE_TTL, &f),
|
||||||
|
Verdict::Private
|
||||||
|
);
|
||||||
|
assert_eq!(f.calls.get(), 2);
|
||||||
|
// A timestamp from the future is expired.
|
||||||
|
assert_eq!(v.check_url(&c, url, 50, &f), Verdict::Private);
|
||||||
|
assert_eq!(f.calls.get(), 3);
|
||||||
|
// A "not private" answer is kept longer.
|
||||||
|
let f2 = Fake::default().with("o/p", Ok(Seen::NotPrivate));
|
||||||
|
v.check_url(&c, "https://github.com/o/p", 0, &f2);
|
||||||
|
v.check_url(&c, "https://github.com/o/p", OTHER_TTL - 1, &f2);
|
||||||
|
assert_eq!(f2.calls.get(), 1);
|
||||||
// After the TTL a failing refresh does not fall back to the stale answer.
|
// After the TTL a failing refresh does not fall back to the stale answer.
|
||||||
let fails = Cell::new(0);
|
let bad = Fake::default().with("o/r", Err("down"));
|
||||||
let bad = |_: &str, _: &ProviderCfg, _: &str, _: &str| {
|
let t = 100 + 10 * PRIVATE_TTL;
|
||||||
fails.set(fails.get() + 1);
|
assert!(matches!(v.check_url(&c, url, t, &bad), Verdict::Unknown(_)));
|
||||||
Err("down".to_string())
|
|
||||||
};
|
|
||||||
let t = 2 * TTL;
|
|
||||||
assert!(matches!(v.check(&c, url, t, &bad), Verdict::Unknown(_)));
|
|
||||||
assert!(matches!(v.check(&c, url, t + 1, &bad), Verdict::Unknown(_)));
|
|
||||||
assert_eq!(fails.get(), 1, "retry is throttled");
|
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
v.check(&c, url, t + RETRY, &bad),
|
v.check_url(&c, url, t + 1, &bad),
|
||||||
Verdict::Unknown(_)
|
Verdict::Unknown(_)
|
||||||
));
|
));
|
||||||
assert_eq!(fails.get(), 2);
|
assert_eq!(bad.calls.get(), 1, "retry is throttled");
|
||||||
|
assert!(matches!(
|
||||||
|
v.check_url(&c, url, t + RETRY, &bad),
|
||||||
|
Verdict::Unknown(_)
|
||||||
|
));
|
||||||
|
assert_eq!(bad.calls.get(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn cache_persists_in_the_state_dir() {
|
fn cache_keys_include_provider_and_are_case_normalised() {
|
||||||
|
let c = cfg();
|
||||||
|
let mut v = Visibility::default();
|
||||||
|
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
|
v.check_url(&c, "https://github.com/O/R.git", 0, &f);
|
||||||
|
v.check_url(&c, "git@github.com:o/r", 0, &f);
|
||||||
|
assert_eq!(f.calls.get(), 1);
|
||||||
|
v.check_url(&c, "https://git.example.com:3000/o/r", 0, &f);
|
||||||
|
assert_eq!(
|
||||||
|
f.calls.get(),
|
||||||
|
2,
|
||||||
|
"same owner/name on another provider is another entry"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cache_persists_in_the_state_dir_with_mode_0600() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
let dir = std::env::temp_dir().join(format!("grove-vis-{}", std::process::id()));
|
let dir = std::env::temp_dir().join(format!("grove-vis-{}", std::process::id()));
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
let file = dir.join("visibility.json");
|
let file = dir.join("visibility.json");
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let public = |_: &str, _: &ProviderCfg, _: &str, _: &str| Ok(false);
|
let f = Fake::default().with("o/r", Ok(Seen::NotPrivate));
|
||||||
let mut v = Visibility::load(Some(file.clone()));
|
let mut v = Visibility::load(Some(file.clone()));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
v.check(&c, "https://github.com/o/r", 50, &public),
|
v.check_url(&c, "https://github.com/o/r", 50, &f),
|
||||||
Verdict::Public
|
Verdict::Public
|
||||||
);
|
);
|
||||||
let never = |_: &str, _: &ProviderCfg, _: &str, _: &str| Err("unused".to_string());
|
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
|
||||||
|
assert_eq!(mode, 0o600);
|
||||||
|
let never = Fake::default();
|
||||||
let mut again = Visibility::load(Some(file));
|
let mut again = Visibility::load(Some(file));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
again.check(&c, "https://github.com/o/r", 60, &never),
|
again.check_url(&c, "https://github.com/o/r", 60, &never),
|
||||||
Verdict::Public
|
Verdict::Public
|
||||||
);
|
);
|
||||||
std::fs::remove_dir_all(&dir).unwrap();
|
std::fs::remove_dir_all(&dir).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
fn mk(base: &Path, group: &str, urls: &[&str], push: &[&str]) -> PathBuf {
|
||||||
fn gate_uses_the_group_policy_and_the_origin_url() {
|
|
||||||
let c = cfg();
|
|
||||||
let base = std::env::temp_dir().join(format!("grove-gate-{}", std::process::id()));
|
|
||||||
let _ = std::fs::remove_dir_all(&base);
|
|
||||||
let mk = |group: &str, url: Option<&str>| {
|
|
||||||
let repo = base.join(group).join("r");
|
let repo = base.join(group).join("r");
|
||||||
let bare = repo.join(".bare");
|
let bare = repo.join(".bare");
|
||||||
std::fs::create_dir_all(&bare).unwrap();
|
std::fs::create_dir_all(&bare).unwrap();
|
||||||
let g = Git::new(&bare);
|
let g = Git::new(&bare);
|
||||||
g.run(&["init", "-q", "--bare"]).unwrap();
|
g.run(&["init", "-q", "--bare"]).unwrap();
|
||||||
if let Some(u) = url {
|
for (i, u) in urls.iter().enumerate() {
|
||||||
|
if i == 0 {
|
||||||
g.run(&["remote", "add", "origin", u]).unwrap();
|
g.run(&["remote", "add", "origin", u]).unwrap();
|
||||||
|
} else {
|
||||||
|
g.run(&["remote", "set-url", "--add", "origin", u]).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for u in push {
|
||||||
|
g.run(&["remote", "set-url", "--push", "--add", "origin", u])
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
repo
|
repo
|
||||||
};
|
}
|
||||||
let private = |_: &str, _: &ProviderCfg, _: &str, _: &str| Ok(true);
|
|
||||||
|
#[test]
|
||||||
|
fn gate_uses_group_policy_and_every_push_url() {
|
||||||
|
let c = cfg();
|
||||||
|
let base = std::env::temp_dir().join(format!("grove-gate-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&base);
|
||||||
|
let f = Fake::default()
|
||||||
|
.with("o/r", Ok(Seen::Private))
|
||||||
|
.with("o/open", Ok(Seen::NotPrivate));
|
||||||
let mut v = Visibility::default();
|
let mut v = Visibility::default();
|
||||||
let url = Some("https://git.example.com:3000/o/r.git");
|
let gate = |repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
|
||||||
let gate =
|
let ok = "https://git.example.com:3000/o/r.git";
|
||||||
|repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &private);
|
assert!(gate(&mk(&base, "priv", &[ok], &[]), &mut v).is_ok());
|
||||||
assert!(gate(&mk("priv", url), &mut v).is_ok());
|
assert!(gate(&mk(&base, "off", &[ok], &[]), &mut v).is_err());
|
||||||
assert!(gate(&mk("off", url), &mut v).is_err());
|
|
||||||
assert!(gate(&mk("all", Some("https://unknown.example/o/r")), &mut v).is_ok());
|
|
||||||
// Private-only without an origin remote: unknown, withheld.
|
|
||||||
std::fs::remove_dir_all(base.join("priv")).unwrap();
|
|
||||||
mk("priv", None);
|
|
||||||
assert!(
|
assert!(
|
||||||
gate(&base.join("priv/r"), &mut v)
|
gate(
|
||||||
|
&mk(&base, "all", &["https://unknown.example/o/r"], &[]),
|
||||||
|
&mut v
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
// Fetch URL private, but the push goes to a public repo (pushurl).
|
||||||
|
let e = gate(
|
||||||
|
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
|
||||||
|
&mut v,
|
||||||
|
);
|
||||||
|
assert!(e.is_err());
|
||||||
|
// Private-only without any remote: unknown, withheld.
|
||||||
|
let bare = base.join("priv/none/.bare");
|
||||||
|
std::fs::create_dir_all(&bare).unwrap();
|
||||||
|
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
|
||||||
|
assert!(
|
||||||
|
gate(&base.join("priv/none"), &mut v)
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.contains("unknown")
|
.contains("unknown")
|
||||||
);
|
);
|
||||||
std::fs::remove_dir_all(&base).unwrap();
|
std::fs::remove_dir_all(&base).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gate_checks_all_push_urls_and_push_instead_of() {
|
||||||
|
let c = cfg();
|
||||||
|
let base = std::env::temp_dir().join(format!("grove-gate2-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&base);
|
||||||
|
let f = Fake::default()
|
||||||
|
.with("o/r", Ok(Seen::Private))
|
||||||
|
.with("o/open", Ok(Seen::NotPrivate));
|
||||||
|
let mut v = Visibility::default();
|
||||||
|
let ok = "https://git.example.com:3000/o/r.git";
|
||||||
|
let open = "https://github.com/o/open";
|
||||||
|
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
|
||||||
|
let both = mk(&base, "priv", &[ok], &[ok, "https://github.com/o/r"]);
|
||||||
|
assert!(snapshot_gate(&c, &both, "origin", &mut v, 0, &f).is_ok());
|
||||||
|
std::fs::remove_dir_all(base.join("priv")).unwrap();
|
||||||
|
let leaky = mk(&base, "priv", &[ok, open], &[]);
|
||||||
|
let e = snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).unwrap_err();
|
||||||
|
assert!(e.contains("public"), "{e}");
|
||||||
|
// pushInsteadOf rewrites the push URL to a public repo.
|
||||||
|
let g = Git::new(leaky.join(".bare"));
|
||||||
|
g.run(&["remote", "set-url", "--delete", "origin", open])
|
||||||
|
.unwrap();
|
||||||
|
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_ok());
|
||||||
|
g.run(&["config", &format!("url.{open}.pushInsteadOf"), ok])
|
||||||
|
.unwrap();
|
||||||
|
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_err());
|
||||||
|
std::fs::remove_dir_all(&base).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gate_requires_mirror_targets_to_be_private_or_absent() {
|
||||||
|
let c = cfg();
|
||||||
|
let base = std::env::temp_dir().join(format!("grove-gate3-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&base);
|
||||||
|
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
|
||||||
|
let gate = |f: &Fake| {
|
||||||
|
let mut v = Visibility::default();
|
||||||
|
snapshot_gate(&c, &repo, "origin", &mut v, 0, f)
|
||||||
|
};
|
||||||
|
let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
|
// No mirror (404): fine. Mirror owner comes from `owners`.
|
||||||
|
let f = base_f().with("gh-org/r", Ok(Seen::Absent));
|
||||||
|
assert!(gate(&f).is_ok());
|
||||||
|
assert!(f.asked.borrow().iter().any(|a| a == "github:gh-org/r"));
|
||||||
|
assert!(gate(&base_f().with("gh-org/r", Ok(Seen::Private))).is_ok());
|
||||||
|
let e = gate(&base_f().with("gh-org/r", Ok(Seen::NotPrivate))).unwrap_err();
|
||||||
|
assert!(e.contains("mirror") && e.contains("public"), "{e}");
|
||||||
|
let e = gate(&base_f().with("gh-org/r", Err("down"))).unwrap_err();
|
||||||
|
assert!(e.contains("mirror"), "{e}");
|
||||||
|
std::fs::remove_dir_all(&base).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -494,3 +494,36 @@ fn auto_materialize_is_decided_per_group() {
|
|||||||
});
|
});
|
||||||
d.shutdown();
|
d.shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn snapshots_already_pushed_are_deleted_when_they_become_withheld() {
|
||||||
|
let w = world("purge", &["pca"]);
|
||||||
|
let repo = w.base.join("pca/g/repo/main");
|
||||||
|
// This machine pushed a snapshot earlier; another machine has one too.
|
||||||
|
git(&repo, &["update-ref", "refs/sync/pca/main", "HEAD"]);
|
||||||
|
git(
|
||||||
|
&repo,
|
||||||
|
&[
|
||||||
|
"push",
|
||||||
|
"-q",
|
||||||
|
"origin",
|
||||||
|
"refs/sync/pca/main:refs/sync/pca/main",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
git(&repo, &["push", "-q", "origin", "HEAD:refs/sync/pcb/main"]);
|
||||||
|
let text = format!(
|
||||||
|
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n{GROUP}[sync]\nfetch_interval_s = 1\n",
|
||||||
|
w.base.join("pca").display()
|
||||||
|
);
|
||||||
|
let d = Daemon::start(Config::parse(&text).unwrap(), settings(&w, "pca")).unwrap();
|
||||||
|
wait_until("own snapshot deleted remotely", 15, || {
|
||||||
|
!git(&w.remote, &["for-each-ref", "refs/sync/pca/"]).contains("refs/sync/pca/main")
|
||||||
|
});
|
||||||
|
d.shutdown();
|
||||||
|
let refs = git(&w.remote, &["for-each-ref", "--format=%(refname)"]);
|
||||||
|
assert!(refs.contains("refs/sync/pcb/main"), "{refs}");
|
||||||
|
assert!(refs.contains("refs/heads/main"), "{refs}");
|
||||||
|
assert!(git(&repo, &["for-each-ref", "refs/sync/pca/"]).is_empty());
|
||||||
|
let log = fs::read_to_string(w.base.join("pca.jsonl")).unwrap();
|
||||||
|
assert!(log.contains("snapshots_purged"), "{log}");
|
||||||
|
}
|
||||||
Reference in new issue
Block a user