fix(providers): pagination, owner listing fallback, URL and name validation

- pages stop on total/Link/empty page, not on a short page
- GitHub/Gitea owner listing falls back to /user/repos (collaborator repos) and says so
- url module: plain repo names, https/ssh/scp URLs on the provider host, canonical https

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 18:53:10 +01:00
1 parent b875a41b4d
commit f1509c3d65
6 files changed
+303 -29

No files matched your search

+8 -4
View File
@@ -84,10 +84,14 @@ impl Provider for Gitea {
};
let items = match self.http.pages(&path, 50, "limit") {
Ok(v) => v,
// Not an organisation: another user's public repos.
Err(Error::Api { status: 404, .. }) if !owner.eq_ignore_ascii_case(login) => self
.http
.pages(&format!("/users/{owner}/repos"), 50, "limit")?,
// Not an organisation (a user, or an org the token cannot see): say so, and take
// what the token can see under that name, private repos it collaborates on included.
Err(Error::Api { status: 404, .. }) if !owner.eq_ignore_ascii_case(login) => {
eprintln!(
"grove: /orgs/{owner} not found; listing the repositories you can see owned by {owner}"
);
self.http.pages("/user/repos", 50, "limit")?
}
Err(e) => return Err(e),
};
Ok(items
+12 -4
View File
@@ -91,10 +91,18 @@ impl Provider for GitHub {
};
let items = match self.http.pages(&path, 100, "per_page") {
Ok(v) => v,
// Not an organisation: another user's public repos.
Err(Error::Api { status: 404, .. }) if !owner.eq_ignore_ascii_case(login) => self
.http
.pages(&format!("/users/{owner}/repos"), 100, "per_page")?,
// Not an organisation (a user, or an org the token cannot see): say so, and take
// what the token can see under that name, private repos it collaborates on included.
Err(Error::Api { status: 404, .. }) if !owner.eq_ignore_ascii_case(login) => {
eprintln!(
"grove: /orgs/{owner} not found; listing the repositories you can see owned by {owner}"
);
self.http.pages(
"/user/repos?affiliation=owner,collaborator,organization_member",
100,
"per_page",
)?
}
Err(e) => return Err(e),
};
Ok(items
+52 -11
View File
@@ -24,6 +24,17 @@ impl Http {
/// Returns the status and the parsed JSON body (`Null` when empty or not JSON).
pub fn send(&self, method: &str, path: &str, body: Option<&Value>) -> Result<(u16, Value)> {
self.send_h(method, path, body)
.map(|(status, json, _)| (status, json))
}
/// Like [`send`], also returning the pagination hints of the response headers.
fn send_h(
&self,
method: &str,
path: &str,
body: Option<&Value>,
) -> Result<(u16, Value, PageHints)> {
let url = format!("{}{}", self.base, path);
let net = |e: ureq::Error| Error::Network(e.to_string());
let mut resp = match (method, body) {
@@ -43,9 +54,19 @@ impl Http {
}
.map_err(net)?;
let status = resp.status().as_u16();
let header = |n: &str| {
resp.headers()
.get(n)
.and_then(|v| v.to_str().ok())
.map(str::to_string)
};
let hints = PageHints {
total: header("x-total-count").and_then(|v| v.trim().parse().ok()),
link: header("link"),
};
let text = resp.body_mut().read_to_string().map_err(net)?;
let json = serde_json::from_str(&text).unwrap_or(Value::Null);
Ok((status, json))
Ok((status, json, hints))
}
/// Like [`send`], but maps non-2xx statuses to [`Error::Api`].
@@ -62,22 +83,42 @@ impl Http {
}
/// Every item of a paginated list endpoint (`path` may already carry a query string).
///
/// A short page is not the end (a server may cap the page size below what was asked). It
/// ends on `X-Total-Count` being reached, on a `Link` header without `rel="next"`, or on an
/// empty or repeated page.
pub fn pages(&self, path: &str, per_page: usize, size_param: &str) -> Result<Vec<Value>> {
let sep = if path.contains('?') { '&' } else { '?' };
let mut out = Vec::new();
for page in 1..=200 {
let v = self.ok(
"GET",
&format!("{path}{sep}{size_param}={per_page}&page={page}"),
None,
)?;
let mut out: Vec<Value> = Vec::new();
let mut prev: Option<Vec<Value>> = None;
for page in 1..=500 {
let url = format!("{path}{sep}{size_param}={per_page}&page={page}");
let (status, v, hints) = self.send_h("GET", &url, None)?;
if !(200..300).contains(&status) {
let message = v["message"].as_str().unwrap_or("(no message)").to_string();
return Err(Error::Api { status, message });
}
let items = v.as_array().cloned().unwrap_or_default();
let n = items.len();
out.extend(items);
if n < per_page {
if items.is_empty() || prev.as_ref() == Some(&items) {
break;
}
out.extend(items.iter().cloned());
if hints.total.is_some_and(|t| out.len() >= t)
|| hints
.link
.as_deref()
.is_some_and(|l| !l.contains("rel=\"next\""))
{
break;
}
prev = Some(items);
}
Ok(out)
}
}
/// What the response headers say about the rest of a paginated list.
struct PageHints {
total: Option<usize>,
link: Option<String>,
}
+1
View File
@@ -6,6 +6,7 @@ mod gitea;
mod github;
mod http;
pub mod token;
pub mod url;
pub use gitea::Gitea;
pub use github::GitHub;
+191
View File
@@ -0,0 +1,191 @@
//! Validation and normalisation of what a forge (or a registry entry) tells us to clone: repo
//! names become directory names, URLs go to `git clone` together with credentials.
use crate::{Error, Result};
use grove_core::config::{Provider as ProviderCfg, ProviderKind};
/// A repo name is used as a directory name under the group: a plain, harmless one.
pub fn valid_repo_name(name: &str) -> bool {
!name.is_empty()
&& name != ".."
&& !name.starts_with(['.', '-'])
&& !name.contains(['/', '\\'])
&& !name.chars().any(char::is_control)
}
pub fn check_repo_name(name: &str) -> Result<()> {
if valid_repo_name(name) {
Ok(())
} else {
Err(Error::Other(format!(
"refusing repository name {name:?}: not a plain directory name"
)))
}
}
/// Host (lowercase, no user info, no port) of an `https://`, `ssh://` or scp-like
/// (`user@host:path`) URL. `None` for anything else (`file://`, local paths, `ext::`...).
pub fn url_host(url: &str) -> Option<String> {
if url.starts_with('-') || url.chars().any(char::is_control) {
return None;
}
let authority = if let Some((scheme, rest)) = url.split_once("://") {
if !["https", "ssh"].contains(&scheme) {
return None;
}
rest.split(['/', '?', '#']).next()?
} else {
// scp-like: user@host:path
let (head, _) = url.split_once(':')?;
if !head.contains('@') || head.contains('/') {
return None;
}
head
};
let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
let host = if host.starts_with('[') {
host
} else {
host.split(':').next()?
};
(!host.is_empty()).then(|| host.to_lowercase())
}
/// Ok when `url` is a clonable https/ssh URL on the provider's own host.
pub fn check_git_url(url: &str, expected_host: &str) -> Result<()> {
match url_host(url) {
Some(h) if h.eq_ignore_ascii_case(expected_host) => Ok(()),
Some(h) => Err(Error::Other(format!(
"refusing URL {url:?}: host {h} is not the provider's host {expected_host}"
))),
None => Err(Error::Other(format!(
"refusing URL {url:?}: only https://, ssh:// and user@host:path URLs are accepted"
))),
}
}
/// Host (no port) the provider's forge answers on; `github.com` for GitHub without a URL.
pub fn provider_host(cfg: &ProviderCfg) -> String {
let base = provider_base(cfg);
url_host(&base).unwrap_or_default()
}
/// `https://host[:port]` of the provider's web/git endpoint (no trailing slash).
pub fn provider_base(cfg: &ProviderCfg) -> String {
let url = cfg.url.as_deref().map(str::trim).unwrap_or_default();
let (scheme, rest) = url.split_once("://").unwrap_or(("https", url));
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
match cfg.kind {
ProviderKind::Github => {
let h = authority.strip_prefix("api.").unwrap_or(authority);
format!("https://{}", if h.is_empty() { "github.com" } else { h })
}
_ if authority.is_empty() => String::new(),
_ => format!("{scheme}://{authority}"),
}
}
/// `(owner, name)` of the path of a git URL (any accepted form), without a trailing `.git`.
pub fn owner_and_name(url: &str) -> Option<(String, String)> {
url_host(url)?;
let path = match url.split_once("://") {
Some((_, rest)) => rest.split_once('/')?.1,
None => url.split_once(':')?.1,
};
let path = path.trim_matches('/');
let path = path.strip_suffix(".git").unwrap_or(path);
let (owner, name) = path.rsplit_once('/')?;
// Only the last two segments matter (a forge may live under a sub-path).
let owner = owner.rsplit('/').next()?;
(!owner.is_empty() && !name.is_empty()).then(|| (owner.to_string(), name.to_string()))
}
/// The canonical https clone URL of the repo a git URL points to, on the provider `cfg`.
/// `None` when the URL's host is not the provider's.
pub fn canonical_https(cfg: &ProviderCfg, url: &str) -> Option<String> {
if !url_host(url)?.eq_ignore_ascii_case(&provider_host(cfg)) {
return None;
}
let (owner, name) = owner_and_name(url)?;
if !valid_repo_name(&name) || !valid_repo_name(&owner) {
return None;
}
Some(format!("{}/{owner}/{name}.git", provider_base(cfg)))
}
#[cfg(test)]
mod tests {
use super::*;
use grove_core::config::Protocol;
fn cfg(kind: ProviderKind, url: Option<&str>) -> ProviderCfg {
ProviderCfg {
kind,
protocol: Protocol::Https,
url: url.map(Into::into),
}
}
#[test]
fn repo_names_must_be_plain() {
for ok in ["a", "my-repo", "x.y", "Synapse_2"] {
assert!(valid_repo_name(ok), "{ok}");
}
for bad in [
"", "..", ".", ".hidden", "-rf", "a/b", "a\\b", "a\nb", "a\u{7}",
] {
assert!(!valid_repo_name(bad), "{bad:?}");
}
}
#[test]
fn only_https_ssh_and_scp_urls_on_the_right_host() {
let g = "git.example.es";
for ok in [
"https://git.example.es/o/r.git",
"https://tok@git.example.es:3000/o/r.git",
"ssh://gitea@git.example.es:2222/o/r.git",
"git@git.example.es:o/r.git",
] {
assert!(check_git_url(ok, g).is_ok(), "{ok}");
}
for bad in [
"https://evil.example/o/r.git",
"git@evil.example:o/r.git",
"file:///etc/passwd",
"/local/path",
"ext::sh -c id",
"--upload-pack=x",
"http://git.example.es/o/r.git",
"git://git.example.es/o/r.git",
] {
assert!(check_git_url(bad, g).is_err(), "{bad}");
}
}
#[test]
fn canonical_urls_follow_the_provider() {
let gitea = cfg(ProviderKind::Gitea, Some("https://git.example.es/"));
let want = Some("https://git.example.es/dasemu/x.git".to_string());
assert_eq!(
canonical_https(&gitea, "ssh://gitea@git.example.es:2222/dasemu/x.git"),
want
);
assert_eq!(
canonical_https(&gitea, "https://git.example.es/dasemu/x"),
want
);
assert_eq!(
canonical_https(&gitea, "https://evil.example/dasemu/x.git"),
None
);
let gh = cfg(ProviderKind::Github, None);
assert_eq!(
canonical_https(&gh, "git@github.com:Dasemu/Synapse.git").as_deref(),
Some("https://github.com/Dasemu/Synapse.git")
);
let ghe = cfg(ProviderKind::Github, Some("https://api.ghe.example.com"));
assert_eq!(provider_host(&ghe), "ghe.example.com");
}
}
+39 -10
View File
@@ -87,6 +87,7 @@ fn gitea_connection_list_create_and_mirror() {
200,
r#"[{"name":"a","private":true,"clone_url":"u/a.git","default_branch":"main","owner":{"login":"dasemu"}}]"#,
),
(200, "[]"),
(
201,
r#"{"name":"n","private":true,"clone_url":"u/n.git","default_branch":"main","owner":{"login":"dasemu"}}"#,
@@ -115,6 +116,7 @@ fn gitea_connection_list_create_and_mirror() {
.unwrap();
assert_eq!(r.clone_url, "u/n.git");
rx.recv().unwrap();
rx.recv().unwrap(); // the empty second page
let create = rx.recv().unwrap();
assert!(create.starts_with("POST /api/v1/user/repos "), "{create}");
assert_eq!(body(&create)["private"], true);
@@ -385,13 +387,16 @@ fn gitea_owner_listing_uses_the_org_endpoint_or_the_users_own() {
let user = format!("[{REPO_B},{REPO_C}]");
let (url, rx) = mock(vec![
(200, Box::leak(org.into_boxed_str())),
(200, "[]"),
(200, Box::leak(user.into_boxed_str())),
(200, "[]"),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
let r = g.list_owner_repos("Org", "me").unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].ssh_url, "git@h:o/a.git");
assert!(lines(&rx.recv().unwrap()).starts_with("GET /api/v1/orgs/Org/repos?limit=50&page=1 "));
assert!(lines(&rx.recv().unwrap()).contains("page=2 "));
// The login itself: `/user/repos`, then only its own repos (org repos it can see are dropped).
let r = g.list_owner_repos("ME", "me").unwrap();
assert_eq!(r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), ["b"]);
@@ -399,13 +404,17 @@ fn gitea_owner_listing_uses_the_org_endpoint_or_the_users_own() {
}
#[test]
fn github_owner_listing_scopes_the_query_and_falls_back_for_users() {
fn github_owner_listing_scopes_the_query_and_sees_collaborator_repos_of_users() {
let org = format!("[{REPO_A}]");
let mine = format!("[{REPO_B}]");
let collab = format!("[{REPO_C},{REPO_B}]");
let (url, rx) = mock(vec![
(200, Box::leak(org.into_boxed_str())),
(200, "[]"),
(200, Box::leak(mine.into_boxed_str())),
(200, "[]"),
(404, r#"{"message":"Not Found"}"#),
(200, Box::leak(collab.into_boxed_str())),
(200, "[]"),
]);
let g = GitHub::new(&url, "t".into());
@@ -413,26 +422,46 @@ fn github_owner_listing_scopes_the_query_and_falls_back_for_users() {
assert!(
lines(&rx.recv().unwrap()).starts_with("GET /orgs/Org/repos?type=all&per_page=100&page=1 ")
);
rx.recv().unwrap();
assert_eq!(g.list_owner_repos("me", "me").unwrap().len(), 1);
assert!(
lines(&rx.recv().unwrap())
.starts_with("GET /user/repos?affiliation=owner&per_page=100&page=1 ")
);
// Not an organisation (404): the other user's public repos.
assert!(g.list_owner_repos("someone", "me").unwrap().is_empty());
rx.recv().unwrap();
assert!(
lines(&rx.recv().unwrap()).starts_with("GET /users/someone/repos?per_page=100&page=1 ")
);
// Not an organisation (404): what the token sees under that name, private ones included.
let r = g.list_owner_repos("x", "me").unwrap();
assert_eq!(r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), ["c"]);
rx.recv().unwrap();
assert!(lines(&rx.recv().unwrap()).starts_with(
"GET /user/repos?affiliation=owner,collaborator,organization_member&per_page=100&page=1 "
));
}
#[test]
fn a_short_page_is_not_the_end_of_a_listing() {
// A server that caps the page size below the request: page 1 has 2 items, page 2 has 1.
let p1 = format!("[{REPO_A},{REPO_B}]");
let p2 = format!("[{REPO_C}]");
let (url, _rx) = mock(vec![
(200, Box::leak(p1.into_boxed_str())),
(200, Box::leak(p2.into_boxed_str())),
(200, "[]"),
]);
let g = GitHub::new(&url, "t".into());
assert_eq!(g.list_repos().unwrap().len(), 3);
}
#[test]
fn git_url_follows_the_protocol_and_needs_an_ssh_url_for_ssh() {
use grove_core::config::Protocol;
let (url, _rx) = mock(vec![(
200,
Box::leak(format!("[{REPO_B},{REPO_C}]").into_boxed_str()),
)]);
let (url, _rx) = mock(vec![
(
200,
Box::leak(format!("[{REPO_B},{REPO_C}]").into_boxed_str()),
),
(200, "[]"),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
let r = g.list_repos().unwrap();
assert_eq!(r[0].git_url(Protocol::Https).unwrap(), "https://h/me/b.git");