Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions app/src/forge/calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ pub const SIGN_IN_SYNC_BUDGET: u32 = 1 + super::github::SIGN_IN_REPOSITORY_PAGES

/// Linking a repository checks it live (`link::link_repository`): the installation that reaches it, the person's
/// permission (a token, their login, collaborator and permission), its ID, then its visibility and licence
/// (`open_source::refresh`: a token, its path by ID, the repository, and its licence file when GitHub can't name the
/// licence). Eleven at most, when the installation token isn't cached between the two.
pub const LINK_BUDGET: u32 = 11;
/// (`open_source::refresh`: a token, the repository by its ID, and its licence file when GitHub can't name the
/// licence).
pub const LINK_BUDGET: u32 = 10;

/// Requests allowed more (or fewer) than [`DEFAULT_BUDGET`]: method, path (`*` is one segment), the most calls, and
/// why. Each is still a fixed number, whatever the size of the organization.
Expand Down
118 changes: 98 additions & 20 deletions app/src/forge/github_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,44 @@ async fn get(token: &str, path: &str) -> laravel::Result<Option<Value>> {
if response.status() == 401 {
token_refused(token).await;
}
if rate_limit_answer(&response) {
return Err(rate_limit_error(&format!("GET {path}"), &response));
}
if !response.successful() {
return Err(err(format!("GET {path}: HTTP {}", response.status())));
}
Ok(Some(response.json()?))
}

/// What [`rate_limited`] looks for in an error made from a rate-limit answer.
const RATE_LIMIT_ANSWER: &str = "GitHub's rate limit answered";

/// Whether GitHub's answer is its rate limit, primary or secondary: a 429, or a 403 with no calls left, a
/// `retry-after`, or a message naming a rate limit. Such an answer says nothing about access.
fn rate_limit_answer(response: &client::Response) -> bool {
response.status() == 429
|| (response.status() == 403
&& (response.header("x-ratelimit-remaining") == Some("0")
|| response.header("retry-after").is_some()
|| response.text().to_ascii_lowercase().contains("rate limit")))
}

/// The error for a rate-limit answer, which [`rate_limited`] recognises so the sync defers instead of failing.
fn rate_limit_error(what: &str, response: &client::Response) -> laravel::Error {
err(format!("{what}: HTTP {}, {RATE_LIMIT_ANSWER}", response.status()))
}

/// Whether a 403 says the installation can't read the resource ("Resource not accessible by integration"), and isn't
/// a rate limit. Any other 403 (no message, or another reason) isn't taken as "can't see it".
fn not_accessible(response: &client::Response) -> bool {
response.status() == 403
&& !rate_limit_answer(response)
&& response
.json::<Value>()
.ok()
.is_some_and(|body| body["message"].as_str() == Some("Resource not accessible by integration"))
}

/// How long before GitHub's expiry a cached installation token stops being used.
const TOKEN_MARGIN_SECONDS: i64 = 300;

Expand Down Expand Up @@ -95,6 +127,9 @@ pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel:
.header("accept", "application/vnd.github+json")
.header("user-agent", "visualci")
.await?;
if rate_limit_answer(&response) {
return Err(rate_limit_error("installation token", &response));
}
if !response.successful() {
return Err(err(format!("installation token: HTTP {}", response.status())));
}
Expand Down Expand Up @@ -271,17 +306,49 @@ pub fn configured(app: &GithubApp) -> bool {
/// Below this many API calls left in the hour, a recheck stops instead of using up what webhooks and checks need.
pub const RATE_LIMIT_RESERVE: i64 = 500;

/// Every collaborator on a repository (`owner/name`) with their permission, keyed by GitHub user ID: direct
/// Where GitHub's API serves a repository: `/repositories/{id}` by its permanent ID when it's known, else
/// `/repos/{owner}/{name}`. A renamed or transferred repository, or one whose organization was renamed, keeps its ID,
/// and GitHub answers its old name with a 301. This module's client follows redirects (its reads would survive one),
/// but checks and PR comments go through the `outbound` client, which refuses them, so those writes to a stale name
/// fail. The ID never goes stale. (5 Dec 2026: the
/// `visualci-com` organization became `visualcihq`.)
#[must_use]
pub fn repo_api(id: Option<&str>, path: &str) -> String {
match numeric(id) {
Some(id) => format!("/repositories/{id}"),
None => format!("/repos/{path}"),
}
}

/// A linked project's repository at [`repo_api`], from its stored ID and URL (`None` with neither).
#[must_use]
pub fn linked_repo_api(id: Option<&str>, url: Option<&str>) -> Option<String> {
match numeric(id) {
Some(id) => Some(format!("/repositories/{id}")),
None => url.and_then(super::Repository::parse).map(|r| format!("/repos/{}", r.path)),
}
}

/// A GitHub ID: digits only.
fn numeric(id: Option<&str>) -> Option<&str> {
id.filter(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit()))
}

/// Every collaborator on a repository (at [`repo_api`]) with their permission, keyed by GitHub user ID: direct
/// collaborators, team members and organization members with access, as `affiliation=all` lists them. Public
/// visibility gives nobody a place on it. `Err` when it can't be read completely (a partial list would drop people);
/// also when GitHub's rate limit is down to [`RATE_LIMIT_RESERVE`].
/// visibility gives nobody a place on it. `None` when GitHub answers 404, or 403 "Resource not accessible by
/// integration": the installation can't read it (a public repository transferred to an account the installation
/// doesn't cover still answers `GET /repositories/{id}`, but not this), so the caller treats the repository as unseen.
/// `Err` when it can't be read completely (a partial list would drop people); also when GitHub's rate limit is down to
/// [`RATE_LIMIT_RESERVE`] or answers instead (a 429, or a primary or secondary limit's 403), which [`rate_limited`]
/// recognises, and on any other 403.
///
/// # Errors
/// Those.
pub async fn collaborators(token: &str, repo: &str) -> laravel::Result<Vec<(String, Permission)>> {
pub async fn collaborators(token: &str, repo: &str) -> laravel::Result<Option<Vec<(String, Permission)>>> {
let mut out = Vec::new();
for page in 1..=50 {
let response = client::get(format!("{}/repos/{repo}/collaborators", api()))
let response = client::get(format!("{}{repo}/collaborators", api()))
.token(token)
.header("accept", "application/vnd.github+json")
.header("user-agent", "visualci")
Expand All @@ -290,10 +357,18 @@ pub async fn collaborators(token: &str, repo: &str) -> laravel::Result<Vec<(Stri
if response.status() == 401 {
token_refused(token).await;
}
let remaining = response.header("x-ratelimit-remaining").and_then(|v| v.parse::<i64>().ok());
// Not readable by this installation: only a 404, or a 403 that says so. A rate limit (403 or 429, primary or
// secondary) or any other 403 is an error, so the sync defers or fails instead of unlinking anyone
if response.status() == 404 || not_accessible(&response) {
return Ok(None);
}
if rate_limit_answer(&response) {
return Err(rate_limit_error(&format!("GET {repo}/collaborators"), &response));
}
if !response.successful() {
return Err(err(format!("GET /repos/{repo}/collaborators: HTTP {}", response.status())));
return Err(err(format!("GET {repo}/collaborators: HTTP {}", response.status())));
}
let remaining = response.header("x-ratelimit-remaining").and_then(|v| v.parse::<i64>().ok());
let list: Vec<Value> = response.json()?;
let done = list.len() < 100;
for c in &list {
Expand All @@ -309,7 +384,7 @@ pub async fn collaborators(token: &str, repo: &str) -> laravel::Result<Vec<(Stri
return Err(err(format!("the rate limit is down to {} calls", remaining.unwrap_or(0))));
}
if done {
return Ok(out);
return Ok(Some(out));
}
}
Err(err(format!("{repo} has more than 5,000 collaborators")))
Expand Down Expand Up @@ -340,36 +415,37 @@ pub async fn repository_path(token: &str, id: &str) -> laravel::Result<Option<St
Ok(get(token, &format!("/repositories/{id}")).await?.and_then(|v| v["full_name"].as_str().map(str::to_string)))
}

/// A repository as GitHub describes it (`GET /repos/{path}`: visibility, licence, ID); `None` when the installation
/// can't see it.
/// A repository (at [`repo_api`]) as GitHub describes it: its name now, visibility, licence and ID; `None` when the
/// installation can't see it.
///
/// # Errors
/// When GitHub can't be reached or refuses.
pub async fn repository(token: &str, repo: &str) -> laravel::Result<Option<Value>> {
get(token, &format!("/repos/{repo}")).await
get(token, repo).await
}

/// A repository's licence file as GitHub finds it (`GET /repos/{repo}/license`): its path and text. `None` when it
/// has none GitHub found. GitHub returns the file even when it can't name the licence (`NOASSERTION`).
/// A repository's licence file as GitHub finds it (`GET {repo}/license`, the repository at [`repo_api`]): its path and
/// text. `None` when it has none GitHub found. GitHub returns the file even when it can't name the licence
/// (`NOASSERTION`).
///
/// # Errors
/// When GitHub can't be reached or refuses.
pub async fn licence_file(token: &str, repo: &str) -> laravel::Result<Option<(String, String)>> {
use base64::Engine;
let Some(answer) = get(token, &format!("/repos/{repo}/license")).await? else { return Ok(None) };
let Some(answer) = get(token, &format!("{repo}/license")).await? else { return Ok(None) };
let (Some(path), Some(content)) = (answer["path"].as_str(), answer["content"].as_str()) else { return Ok(None) };
let bytes = base64::engine::general_purpose::STANDARD
.decode(content.split_whitespace().collect::<String>())
.map_err(|e| err(format!("GET /repos/{repo}/license: {e}")))?;
.map_err(|e| err(format!("GET {repo}/license: {e}")))?;
Ok(Some((path.to_string(), String::from_utf8_lossy(&bytes).into_owned())))
}

/// Whether a branch exists in a repository (`None` when the installation can't see the repository).
/// Whether a branch exists in a repository (at [`repo_api`]; `None` when the installation can't see the repository).
///
/// # Errors
/// When GitHub can't be reached or refuses.
pub async fn branch_exists(token: &str, repo: &str, branch: &str) -> laravel::Result<Option<bool>> {
if get(token, &format!("/repos/{repo}")).await?.is_none() {
if get(token, repo).await?.is_none() {
return Ok(None);
}
let branch: String = branch
Expand All @@ -382,7 +458,7 @@ pub async fn branch_exists(token: &str, repo: &str, branch: &str) -> laravel::Re
}
})
.collect();
Ok(Some(get(token, &format!("/repos/{repo}/branches/{branch}")).await?.is_some()))
Ok(Some(get(token, &format!("{repo}/branches/{branch}")).await?.is_some()))
}

/// A repository's permanent ID, by its path (`None` when the installation can't see it).
Expand All @@ -393,10 +469,12 @@ pub async fn repository_id(token: &str, repo: &str) -> laravel::Result<Option<St
Ok(get(token, &format!("/repos/{repo}")).await?.and_then(|v| v["id"].as_i64().map(|i| i.to_string())))
}

/// Whether an error is GitHub's rate limit running low ([`collaborators`]): the work waits for the next run.
/// Whether an error is GitHub's rate limit running low ([`collaborators`]) or answering instead of the API (a 429, or
/// a primary or secondary limit's 403): the work waits for the next run.
#[must_use]
pub fn rate_limited(e: &laravel::Error) -> bool {
e.to_string().contains("the rate limit is down")
let e = e.to_string();
e.contains("the rate limit is down") || e.contains(RATE_LIMIT_ANSWER)
}

/// GitHub's role name for a collaborator (`admin`, `maintain`, `write`, `triage`, `read`).
Expand Down
8 changes: 6 additions & 2 deletions app/src/forge/installations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,8 @@ async fn role_in(organization_id: i64, user_id: i64) -> laravel::Result<Option<R
}

/// Act on the App's `installation` deliveries: record installations made, suspended or removed. Returns what it did,
/// for the delivery's log; `Value::Null` when the delivery isn't about installations.
/// for the delivery's log; `Value::Null` when the delivery isn't about installations. An account renamed
/// (`installation_target`) is `webhooks::account_renamed`'s, which checks the rename isn't stale first.
///
/// # Errors
/// On a database error.
Expand All @@ -282,7 +283,10 @@ pub async fn from_webhook(kind: &str, event: &Value) -> laravel::Result<Value> {
let Some(id) = event["installation"]["id"].as_i64().map(|i| i.to_string()) else { return Ok(Value::Null) };
match (kind, action) {
("installation", "created" | "unsuspend" | "new_permissions_accepted") => {
let Some(found) = super::github::installation_account(id.clone(), &event["installation"]["account"]) else {
// A login that isn't one (`read_event` checks a rename's the same way) isn't stored: it goes into URLs
let Some(found) = super::github::installation_account(id.clone(), &event["installation"]["account"])
.filter(|found| super::webhooks::login(&found.account_login))
else {
return Ok(Value::Null);
};
upsert(&found).await?;
Expand Down
7 changes: 7 additions & 0 deletions app/src/forge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,13 @@ impl Repository {
Some(Self { forge: ForgeKind::Gitlab, url: format!("{scheme}://{host}/{path}"), path, id: None })
}

/// Where GitHub's API serves it: by its permanent ID when known, so a renamed repository or organization doesn't
/// break the call (`github_app::repo_api`).
#[must_use]
pub fn github_api_path(&self) -> String {
github_app::repo_api(self.id.as_deref(), &self.path)
}

/// The base URL of the site the repository is on: `https://gitlab.example.com`.
#[must_use]
pub fn site_url(&self) -> &str {
Expand Down
11 changes: 4 additions & 7 deletions app/src/forge/open_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use laravel::db;
use laravel::event::{Event, listener};
use serde_json::Value;

use super::Repository;
use super::events::RepositoryVisibilityChanged;
use super::github_app;
use crate::config::GithubApp;
Expand Down Expand Up @@ -483,14 +482,12 @@ async fn check(app: &GithubApp, p: &Project) -> Option<Status> {
let answer = async {
let token = github_app::installation_token(app, installation).await?;
// By GitHub's ID when known, so a rename can't mislead it
let path = match p.repository_id.as_deref() {
Some(id) => github_app::repository_path(&token, id).await?,
None => Repository::parse(url).map(|r| r.path),
let Some(repo_api) = github_app::linked_repo_api(p.repository_id.as_deref(), Some(url)) else {
return Ok(None);
};
let Some(path) = path else { return Ok(None) };
let Some(repo) = github_app::repository(&token, &path).await? else { return Ok(None) };
let Some(repo) = github_app::repository(&token, &repo_api).await? else { return Ok(None) };
let file = if needs_file(&repo) {
github_app::licence_file(&token, &path).await?.map(|(path, text)| LicenceFile { path, text })
github_app::licence_file(&token, &repo_api).await?.map(|(path, text)| LicenceFile { path, text })
} else {
None
};
Expand Down
14 changes: 8 additions & 6 deletions app/src/forge/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ pub fn github_check_run(check: &Check) -> Value {
}

/// Create or update a check on a commit; returns its ID for the next update (GitLab keeps one status per name and
/// commit, so its "ID" is the status's name).
/// commit, so its "ID" is the status's name). GitHub's repository is addressed by its ID when known
/// ([`Repository::github_api_path`]), so a renamed repository or organization still gets its checks.
///
/// # Errors
/// When the forge refuses it.
Expand All @@ -187,9 +188,10 @@ pub async fn report_check(
match target {
Target::Github { app, installation } => {
let token = github_app::installation_token(app, installation).await?;
let repo = repository.github_api_path();
let request = match existing {
Some(id) => client::patch(format!("{}/repos/{path}/check-runs/{id}", github())),
None => client::post(format!("{}/repos/{path}/check-runs", github())),
Some(id) => client::patch(format!("{}{repo}/check-runs/{id}", github())),
None => client::post(format!("{}{repo}/check-runs", github())),
};
let request =
request.token(&token).header("accept", "application/vnd.github+json").header("user-agent", "visualci");
Expand Down Expand Up @@ -231,7 +233,7 @@ pub async fn report_check(
}

/// Create or edit VisualCI's comment on a pull request (`existing` is the one it made before; one someone deleted is
/// made again). Returns the comment's ID.
/// made again). Returns the comment's ID. On GitHub, by the repository's ID when known, as [`report_check`].
///
/// # Errors
/// When the forge refuses it.
Expand All @@ -246,8 +248,8 @@ pub async fn upsert_comment(
let (token, comments, one, what) = match target {
Target::Github { app, installation } => (
github_app::installation_token(app, installation).await?,
format!("{}/repos/{path}/issues/{pr_number}/comments", github()),
format!("{}/repos/{path}/issues/comments", github()),
format!("{}{}/issues/{pr_number}/comments", github(), repository.github_api_path()),
format!("{}{}/issues/comments", github(), repository.github_api_path()),
"GitHub PR comment",
),
Target::Gitlab { base, token } => {
Expand Down
Loading
Loading