Watch
0
0
Fork
You've already forked hyperhive
0

swarm-controller: move the forge concern into its own module

Refs #6897
This commit is contained in:
atlas 2026-11-27 15:47:00 +01:00 • committed by mara
commit a9df331469
31 changed files with 44 additions and 37 deletions

View file

@ -0,0 +1,469 @@
//! Swarm-level config-PR status, kept current by both a webhook nudge and a
//! periodic poll.
//!
//! swarm-ui's config-PR panel needs a *swarm*-level answer to "does agent X
//! have an open config PR" that does not depend on which hive currently
//! hosts X being reachable.
//!
//! Both paths write the same [`ConfigPrCache`]:
//!
//! - [`spawn`] — a periodic full rescan. The backstop: catches anything a
//! missed delivery loses, and is what populates the cache before the first
//! delivery ever arrives.
//! - [`ConfigPrCache::apply_webhook_delivery`] — called from
//! `crate::webhook::post_webhook_forge` on a verified `ConfigPr` delivery.
//! The low-latency path: a PR opening or closing shows up immediately
//! instead of waiting up to `POLL_INTERVAL`.
//!
//! [`merged`] reads the same delivery for a merge, which the webhook handler
//! turns into a deploy, and [`changed_head`] reads it for a PR's new head,
//! which the handler turns into a build check (`crate::builder`). The cache
//! poll has no counterpart to either, and a PR head whose delivery is lost is
//! not built. A merge whose delivery is lost is deployed by
//! [`crate::config_drift`], which [`spawn`] runs after each scan.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use serde::Deserialize;
use crate::forge::{Client, ConfigPrStatus};
/// The handful of fields this cache needs out of a Forgejo `pull_request`
/// webhook payload — not a full typed mirror of the event (Forgejo's own
/// schema has dozens more), just enough to know which agent, which PR, and
/// whether it's still open.
#[derive(Deserialize)]
pub struct ConfigPrWebhookPayload {
/// `"closed"` on both a merge and a close without merging; `merged`
/// tells them apart.
#[serde(default)]
action: String,
pull_request: WebhookPullRequest,
repository: WebhookRepository,
}
#[derive(Deserialize)]
struct WebhookPullRequest {
number: u64,
/// Forgejo sends `"open"` or `"closed"` here — merged and
/// closed-without-merging are indistinguishable at this field, but this
/// cache only ever answers "is there an open PR," so the distinction
/// doesn't matter to it.
state: String,
html_url: Option<String>,
#[serde(default)]
merged: bool,
/// The commit the merge left on the base branch.
#[serde(default)]
merge_commit_sha: Option<String>,
/// The branch the PR targets. Only a merge into `main` is deployed: the
/// hive builds its config repo's `main`.
#[serde(default)]
base: Option<WebhookBranch>,
/// The PR's branch, whose `sha` is the commit a build check builds.
#[serde(default)]
head: Option<WebhookBranch>,
}
#[derive(Deserialize)]
struct WebhookBranch {
#[serde(rename = "ref")]
name: String,
#[serde(default)]
sha: Option<String>,
}
/// A config PR that was just merged: whose config, the commit to deploy, and
/// the PR.
#[derive(Debug, PartialEq, Eq)]
pub struct MergedConfigPr {
pub agent: String,
pub rev: String,
pub pr: u64,
}
/// The merge a verified `ConfigPr` delivery reports, if it reports one.
///
/// Only the `closed` action counts: Forgejo also sends `merged: true` on
/// later events about an already-merged PR (a label or an edit), and those
/// must not deploy it again. So does only a merge into `main`. A body that
/// does not parse is `None`; [`ConfigPrCache::apply_webhook_delivery`]
/// already logs it.
pub fn merged(body: &[u8]) -> Option<MergedConfigPr> {
let payload: ConfigPrWebhookPayload = serde_json::from_slice(body).ok()?;
let into_main = payload
.pull_request
.base
.as_ref()
.is_some_and(|base| base.name == "main");
if payload.action != "closed" || !payload.pull_request.merged || !into_main {
return None;
}
let Some(rev) = payload.pull_request.merge_commit_sha else {
tracing::warn!(
agent = %payload.repository.name,
pr = payload.pull_request.number,
"config-pr webhook: merged PR carries no merge_commit_sha; nothing deployed"
);
return None;
};
Some(MergedConfigPr {
agent: payload.repository.name,
rev,
pr: payload.pull_request.number,
})
}
/// A config PR whose head just changed: whose config, the head commit, and
/// the PR.
#[derive(Debug, PartialEq, Eq)]
pub struct ChangedConfigPr {
pub agent: String,
pub rev: String,
pub pr: u64,
}
/// The new head a verified `ConfigPr` delivery reports, if it reports one: a
/// PR opened, reopened, or pushed to (`synchronized`). Edits and labels leave
/// the head as it was and build nothing. A body that does not parse is
/// `None`; [`ConfigPrCache::apply_webhook_delivery`] already logs it.
pub fn changed_head(body: &[u8]) -> Option<ChangedConfigPr> {
let payload: ConfigPrWebhookPayload = serde_json::from_slice(body).ok()?;
if !matches!(
payload.action.as_str(),
"opened" | "reopened" | "synchronized"
) || payload.pull_request.state != "open"
{
return None;
}
let Some(rev) = payload.pull_request.head.and_then(|h| h.sha) else {
tracing::warn!(
agent = %payload.repository.name,
pr = payload.pull_request.number,
"config-pr webhook: PR carries no head sha; nothing built"
);
return None;
};
Some(ChangedConfigPr {
agent: payload.repository.name,
rev,
pr: payload.pull_request.number,
})
}
#[derive(Deserialize)]
struct WebhookRepository {
/// The config repo's name IS the agent's name — same convention
/// `Client::list_open_config_prs` relies on.
name: String,
}
/// How often to rescan `agent-configs/*`.
const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// The latest full scan, replaced atomically each cycle.
///
/// A full replace rather than an incremental merge: `Client::list_open_config_prs`
/// already returns the complete current set (an agent with no open PR is
/// simply absent), so merging would need its own stale-entry eviction to
/// avoid an agent's long-closed PR lingering forever. A full replace
/// sidesteps needing that logic: the map at any moment is nothing more
/// than "the last successful scan's answer."
pub struct ConfigPrCache(Mutex<HashMap<String, ConfigPrStatus>>);
impl ConfigPrCache {
fn new() -> Self {
Self(Mutex::new(HashMap::new()))
}
/// `agent`'s open PR, if the last successful scan found one.
///
/// Returns `None` both when the agent has no open PR and when no scan
/// has completed yet — the caller (`GET /api/agents/<name>/config-pr`)
/// treats both as "nothing to show," which is the honest answer for a
/// value that's a best-effort cache, not a live read.
pub fn get(&self, agent: &str) -> Option<ConfigPrStatus> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(agent)
.cloned()
}
/// Every agent with an open PR, per the last successful scan (plus any
/// webhook upserts since). The bulk counterpart to [`Self::get`] — for
/// `GET /api/config-prs` (swarm-ui's config-PR table), which needs every
/// agent's status in one round trip rather than one request per agent.
pub fn snapshot(&self) -> HashMap<String, ConfigPrStatus> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
/// ⚠️ Can race [`Self::apply_webhook_delivery`]: a scan started before a
/// PR opened may finish *after* the webhook already upserted it, and
/// this snapshot — taken before that PR existed — will overwrite the
/// fresh entry. Self-heals within one `POLL_INTERVAL` (the next scan
/// sees the PR), so not worth coordinating against; noted per argus's
/// review rather than left implicit.
fn replace(&self, scan: HashMap<String, ConfigPrStatus>) {
*self
.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = scan;
}
/// Apply one verified `ConfigPr` webhook delivery's raw body to the
/// cache — the low-latency counterpart to [`spawn`]'s periodic rescan.
///
/// A parse failure is logged and dropped, not propagated: the caller
/// (`crate::webhook::post_webhook_forge`) already returned 200 to
/// Forgejo (HMAC verification, not payload parsing, is what a retry
/// could fix), and the next poll tick reconciles whatever this delivery
/// would have changed — same "poll as backstop" property [`spawn`]'s
/// doc comment describes, just exercised on the failure path instead of
/// the steady-state one.
///
/// An `open` PR is upserted unconditionally. A `closed` one is removed
/// only if the cached entry's PR number still matches — guards against
/// an out-of-order delivery (a stale `closed` for PR #1 arriving after a
/// newer `opened` for PR #2 on the same repo) wiping out a genuinely
/// current entry.
pub fn apply_webhook_delivery(&self, body: &[u8]) {
let payload: ConfigPrWebhookPayload = match serde_json::from_slice(body) {
Ok(p) => p,
Err(e) => {
tracing::warn!(
error = %e,
"config-pr webhook: payload did not parse, cache unchanged (next poll reconciles)"
);
return;
}
};
let mut map = self
.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if payload.pull_request.state == "open" {
map.insert(
payload.repository.name,
ConfigPrStatus {
pr_number: payload.pull_request.number,
html_url: payload.pull_request.html_url,
},
);
} else if map
.get(&payload.repository.name)
.is_some_and(|cached| cached.pr_number == payload.pull_request.number)
{
map.remove(&payload.repository.name);
}
}
}
/// Build an empty cache and spawn the periodic scan that keeps it current.
///
/// The scan runs immediately on the first tick (`tokio::time::interval`'s
/// default), so the cache is populated on startup rather than staying empty
/// for a full `POLL_INTERVAL` after boot.
///
/// With `drift`, each tick also runs [`crate::config_drift::run`] after the scan.
pub(crate) fn spawn(
client: Arc<Client>,
drift: Option<crate::config_drift::Deps>,
) -> Arc<ConfigPrCache> {
let cache = Arc::new(ConfigPrCache::new());
let cache_for_task = Arc::clone(&cache);
tokio::spawn(async move {
let mut ticker = tokio::time::interval(POLL_INTERVAL);
loop {
ticker.tick().await;
match crate::forge::within_forge_deadline(
"config-pr poll",
client.list_open_config_prs(),
)
.await
{
Some(Ok(scan)) => cache_for_task.replace(scan),
Some(Err(e)) => {
tracing::warn!(
error = %format!("{e:#}"),
"config-pr poll: scan failed, cache keeps its last value"
);
}
None => {}
}
if let Some(drift) = &drift {
crate::forge::within_forge_deadline(
"config drift pass",
crate::config_drift::run(drift, &client),
)
.await;
}
}
});
cache
}
#[cfg(test)]
mod tests {
use super::ConfigPrCache;
fn payload(agent: &str, number: u64, state: &str) -> Vec<u8> {
serde_json::json!({
"pull_request": { "number": number, "state": state, "html_url": "https://forge.example/pr" },
"repository": { "name": agent },
})
.to_string()
.into_bytes()
}
#[test]
fn an_open_delivery_upserts_the_entry() {
let cache = ConfigPrCache::new();
cache.apply_webhook_delivery(&payload("damocles", 5, "open"));
let status = cache.get("damocles").expect("entry inserted");
assert_eq!(status.pr_number, 5);
}
#[test]
fn a_closed_delivery_removes_a_matching_entry() {
let cache = ConfigPrCache::new();
cache.apply_webhook_delivery(&payload("damocles", 5, "open"));
cache.apply_webhook_delivery(&payload("damocles", 5, "closed"));
assert!(cache.get("damocles").is_none());
}
#[test]
fn a_stale_closed_delivery_does_not_clobber_a_newer_open_pr() {
let cache = ConfigPrCache::new();
// PR #5 opened, then closed, then a genuinely new PR #6 opens.
cache.apply_webhook_delivery(&payload("damocles", 5, "open"));
cache.apply_webhook_delivery(&payload("damocles", 6, "open"));
// The #5 close event arrives late, after #6 already replaced it.
cache.apply_webhook_delivery(&payload("damocles", 5, "closed"));
let status = cache.get("damocles").expect("PR #6 must survive");
assert_eq!(status.pr_number, 6);
}
#[test]
fn snapshot_returns_every_agent_with_an_open_pr() {
let cache = ConfigPrCache::new();
assert!(
cache.snapshot().is_empty(),
"an unpopulated cache snapshots empty, not missing"
);
cache.apply_webhook_delivery(&payload("damocles", 5, "open"));
cache.apply_webhook_delivery(&payload("iris", 9, "open"));
let snapshot = cache.snapshot();
assert_eq!(snapshot.len(), 2);
assert_eq!(snapshot["damocles"].pr_number, 5);
assert_eq!(snapshot["iris"].pr_number, 9);
}
fn closed(merged: bool) -> Vec<u8> {
serde_json::json!({
"action": "closed",
"pull_request": {
"number": 5,
"state": "closed",
"html_url": "https://forge.example/pr",
"merged": merged,
"merge_commit_sha": merged.then_some("abc123"),
"base": { "ref": "main" },
},
"repository": { "name": "damocles" },
})
.to_string()
.into_bytes()
}
#[test]
fn a_merged_delivery_names_the_agent_and_the_merge_commit() {
assert_eq!(
super::merged(&closed(true)),
Some(super::MergedConfigPr {
agent: "damocles".to_owned(),
rev: "abc123".to_owned(),
pr: 5,
})
);
}
#[test]
fn a_closed_unmerged_delivery_is_not_a_merge() {
assert_eq!(super::merged(&closed(false)), None);
}
#[test]
fn a_merged_pr_on_a_non_close_action_is_not_a_merge() {
let mut body: serde_json::Value =
serde_json::from_slice(&closed(true)).expect("fixture is json");
body["action"] = "label_updated".into();
assert_eq!(super::merged(body.to_string().as_bytes()), None);
}
#[test]
fn a_merge_into_another_branch_is_not_deployed() {
let mut body: serde_json::Value =
serde_json::from_slice(&closed(true)).expect("fixture is json");
body["pull_request"]["base"]["ref"] = "staging".into();
assert_eq!(super::merged(body.to_string().as_bytes()), None);
}
#[test]
fn an_open_delivery_is_not_a_merge() {
assert_eq!(super::merged(&payload("damocles", 5, "open")), None);
}
#[test]
fn a_malformed_payload_leaves_the_cache_unchanged() {
let cache = ConfigPrCache::new();
cache.apply_webhook_delivery(&payload("damocles", 5, "open"));
cache.apply_webhook_delivery(b"not json");
let status = cache
.get("damocles")
.expect("prior entry must survive a bad delivery");
assert_eq!(status.pr_number, 5);
}
fn head_changed(action: &str) -> Vec<u8> {
serde_json::json!({
"action": action,
"pull_request": {
"number": 5,
"state": "open",
"head": { "ref": "fix", "sha": "def456" },
"base": { "ref": "main", "sha": "abc123" },
},
"repository": { "name": "damocles" },
})
.to_string()
.into_bytes()
}
#[test]
fn an_opened_reopened_or_pushed_pr_names_its_head() {
for action in ["opened", "reopened", "synchronized"] {
assert_eq!(
super::changed_head(&head_changed(action)),
Some(super::ChangedConfigPr {
agent: "damocles".to_owned(),
rev: "def456".to_owned(),
pr: 5,
}),
"{action}"
);
}
}
#[test]
fn an_edit_a_label_or_a_close_builds_nothing() {
for action in ["edited", "label_updated", "closed"] {
assert_eq!(super::changed_head(&head_changed(action)), None, "{action}");
}
assert_eq!(super::changed_head(&closed(true)), None);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,223 @@
//! Each existing agent's forge account at its own repository limit.
//!
//! The limit is the `max_repos` of the agent's record in `agent-permissions`
//! (`swarm_wire::agent_permissions`). A new account gets it from its
//! `CreateForgeUser` node. This pass reaches the others: at start, when a
//! change of an agent's `max_repos` wakes it
//! ([`crate::agent_permissions::MAX_REPOS_CHANGED`]), and every
//! [`RECONCILE_INTERVAL`] over every agent that holds a store identity.
//!
//! Forgejo never returns an account's `max_repo_creation`, so nothing can be
//! compared against the forge. The pass remembers what it applied to each agent
//! in this process and applies again only what differs, so a restart applies
//! every agent's limit once, and an agent whose edit failed is retried at the
//! next tick. The decision is pure ([`plan`]), so the tests pin it.
use std::collections::BTreeMap;
use std::sync::Arc;
use super::Client;
/// How often [`spawn`] re-checks every agent.
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// The agents of `desired` whose account is not known to be at their limit,
/// with that limit.
pub fn plan(
desired: &BTreeMap<String, u32>,
applied: &BTreeMap<String, u32>,
) -> Vec<(String, u32)> {
desired
.iter()
.filter(|(agent, limit)| applied.get(*agent) != Some(limit))
.map(|(agent, limit)| (agent.clone(), *limit))
.collect()
}
/// One pass: set each limit of `todo` on its agent's account, recording the
/// ones the forge took in `applied`. An agent the forge refuses is logged and
/// left out, so the next pass plans it again.
async fn apply(client: &Client, todo: &[(String, u32)], applied: &mut BTreeMap<String, u32>) {
for (agent, limit) in todo {
match client.limit_agent_account(agent, *limit).await {
Ok(()) => {
applied.insert(agent.clone(), *limit);
}
Err(e) => tracing::warn!(
%agent,
limit,
error = %format!("{e:#}"),
"agent max repos: the forge account was not updated; retrying next pass"
),
}
}
}
/// Every roster agent's limit. An agent whose record can't be read is left
/// out, so nothing is applied for it this pass.
async fn desired(queue: &async_nats::Client, roster: &[String]) -> BTreeMap<String, u32> {
let mut limits = BTreeMap::new();
for agent in roster {
match crate::agent_permissions::max_repos(queue, agent).await {
Ok(limit) => {
limits.insert(agent.clone(), limit);
}
Err(e) => tracing::warn!(
%agent,
error = %format!("{e:#}"),
"agent max repos: the agent's limit was not read; skipping it this pass"
),
}
}
limits
}
/// Apply every agent's limit now and again on each wake and tick. A pass that
/// fails is logged and retried on the next tick; it never stops the daemon.
pub fn spawn(client: Arc<Client>, queue: async_nats::Client) {
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
let mut applied = BTreeMap::new();
loop {
tokio::select! {
_ = ticker.tick() => {}
() = crate::agent_permissions::MAX_REPOS_CHANGED.notified() => {}
}
let roster = match super::docs_grant::read_roster().await {
Ok(roster) => roster,
Err(e) => {
tracing::warn!(error = %format!("{e:#}"), "agent max repos: no roster; retrying next tick");
continue;
}
};
applied.retain(|agent, _| roster.contains(agent));
let todo = plan(&desired(&queue, &roster).await, &applied);
if todo.is_empty() {
continue;
}
tracing::info!(agents = todo.len(), "agent max repos: applying the limits");
super::within_forge_deadline("agent max repos", apply(&client, &todo, &mut applied))
.await;
}
});
}
#[cfg(test)]
mod tests {
use super::*;
fn limits(of: &[(&str, u32)]) -> BTreeMap<String, u32> {
of.iter().map(|(a, n)| ((*a).to_owned(), *n)).collect()
}
/// An agent at another value, or not yet applied, is planned with its own
/// limit; one already at its limit is not.
#[test]
fn plan_names_the_agents_not_at_their_limit() {
let desired = limits(&[("atlas", 2), ("iris", 0), ("sock", 5)]);
let applied = limits(&[("atlas", 2), ("iris", 1)]);
assert_eq!(
plan(&desired, &applied),
[("iris".to_owned(), 0), ("sock".to_owned(), 5)]
);
// Control: everything applied at its limit leaves nothing to do.
assert!(plan(&desired, &desired).is_empty());
}
/// A stand-in forge on a loopback port that answers each agent's own
/// email and records every admin edit as (login, body).
async fn stub_agents() -> (
Client,
Arc<std::sync::Mutex<Vec<(String, serde_json::Value)>>>,
) {
use axum::http::{Method, StatusCode, Uri, header::CONTENT_TYPE};
let edits: Arc<std::sync::Mutex<Vec<(String, serde_json::Value)>>> = Arc::default();
let recorded = Arc::clone(&edits);
let app = axum::Router::new().fallback(
move |method: Method, uri: Uri, body: axum::body::Bytes| {
let recorded = Arc::clone(&recorded);
async move {
let login = uri.path().rsplit('/').next().unwrap_or_default().to_owned();
let body = match method {
Method::GET => format!(r#"{{"email":"{login}@hyperhive.local"}}"#),
Method::PATCH => {
let json = serde_json::from_slice(&body).unwrap_or_default();
recorded.lock().unwrap().push((login, json));
"{}".to_owned()
}
_ => "{}".to_owned(),
};
(StatusCode::OK, [(CONTENT_TYPE, "application/json")], body)
}
},
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
tokio::spawn(async move { axum::serve(listener, app).await });
let api = crate::forge::api::tests::fixed(url.clone(), "stub-token");
(Client { api, url }, edits)
}
/// Each agent gets its own limit, none is skipped and none takes another's;
/// each is recorded as applied, and a second plan has nothing left.
#[tokio::test]
async fn the_pass_sets_each_agent_its_own_limit() {
let (client, edits) = stub_agents().await;
let desired = limits(&[("atlas", 4), ("iris", 0), ("sock", 9)]);
let mut applied = BTreeMap::new();
apply(&client, &plan(&desired, &applied), &mut applied).await;
let mut seen: Vec<(String, i64, bool)> = edits
.lock()
.unwrap()
.iter()
.map(|(login, body)| {
(
login.clone(),
body["max_repo_creation"].as_i64().unwrap(),
body["allow_create_organization"] == false,
)
})
.collect();
seen.sort();
assert_eq!(
seen,
[
("atlas".to_owned(), 4, true),
("iris".to_owned(), 0, true),
("sock".to_owned(), 9, true)
]
);
assert_eq!(applied, desired);
assert!(plan(&desired, &applied).is_empty());
// One agent's changed limit plans that agent alone.
let changed = limits(&[("atlas", 4), ("iris", 1), ("sock", 9)]);
assert_eq!(plan(&changed, &applied), [("iris".to_owned(), 1)]);
}
/// An agent whose edit the forge refuses is not recorded, so the next pass
/// plans it again.
#[tokio::test]
async fn a_refused_agent_is_planned_again() {
let (client, edits) = stub_agents().await;
let mut applied = BTreeMap::new();
apply(&client, &[("atlas".to_owned(), 2)], &mut applied).await;
// Control: an account that is the agent's own is recorded.
assert_eq!(applied.get("atlas"), Some(&2));
assert_eq!(edits.lock().unwrap().len(), 1);
let (broken, _seen) = super::super::tests::stub_forge(
(200, "{}"),
(200, r#"{"email":"someone@example.com"}"#),
(200, "{}"),
)
.await;
let mut applied = BTreeMap::new();
apply(&broken, &[("atlas".to_owned(), 2)], &mut applied).await;
assert!(applied.is_empty(), "a refused agent must not be recorded");
let desired = limits(&[("atlas", 2)]);
assert_eq!(plan(&desired, &applied), [("atlas".to_owned(), 2)]);
}
}

View file

@ -0,0 +1,780 @@
//! Each agent's own forge access token: minted here with the admin API, stored
//! at `swarm/agents/<agent>/forge-token`, and pulled from there by the agent
//! container itself (`nix/agent-modules/forge-token.nix`).
//!
//! One token per agent, under the fixed name [`AGENT_TOKEN_NAME`]. Forgejo
//! refuses a second token with a name the user already has, so a rotation is a
//! delete then a create, and there is never more than one of these per agent.
//! The `hyperhive-<unix-seconds>` tokens `hive-c0re` used to mint are never
//! touched here: the name cannot match them. [`spawn`]'s pass deletes them
//! separately, via [`super::legacy_tokens`].
//!
//! Two callers insert the same `MintAgentForgeToken` job node: agent creation,
//! and [`spawn`]'s pass at start and every [`RECONCILE_INTERVAL`] over every
//! agent that holds a store identity. The decision is pure ([`classify`] and
//! [`plan`]), so the tests pin it; the IO on either side only reads or acts.
use std::collections::BTreeSet;
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use forge_client::async_client;
use forgejo_api::structs::{AccessToken, CreateAccessTokenOption};
use forgejo_api::{ApiErrorKind, ForgejoError};
use reqwest::StatusCode;
use swarm_secret_client::{client::DEFAULT_CERT_MOUNT, forge, policy};
use super::Client;
use crate::store::TokenStore;
/// The forge's name for every agent token this module mints.
///
/// Deliberately not `hyperhive-…`: that prefix is what `hive-c0re` named each
/// of its re-mints, and [`super::legacy_tokens`] deletes those.
pub const AGENT_TOKEN_NAME: &str = "swarm-agent";
/// The scopes an agent token carries. Byte-identical to the `TOKEN_SCOPES`
/// `hive-c0re` minted with, so the move from hive to swarm changes nothing an
/// agent can do. Narrowing it is a separate decision. A test here pins the
/// literal.
pub const AGENT_TOKEN_SCOPES: &str = "read:user,write:user,read:notification,write:notification,write:repository,write:issue,write:organization,write:misc";
/// How often [`spawn`] re-checks every agent's token.
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// Why a token has to be (re)minted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MintReason {
/// The store holds nothing for this agent.
NotStored,
/// The forge lists no [`AGENT_TOKEN_NAME`] token for this agent.
NotOnForge,
/// The forge's token is not the one the store holds.
LastEightMismatch,
/// The forge's token carries other scopes than [`AGENT_TOKEN_SCOPES`].
ScopeMismatch,
}
/// What to do about one agent's token.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
/// The stored token is the forge's token, with the right scopes.
Keep,
/// Delete any [`AGENT_TOKEN_NAME`] token, create a new one, store it.
Mint(MintReason),
/// The forge lists more than one [`AGENT_TOKEN_NAME`] token. Forgejo
/// refuses a duplicate name, so this is a forge in a state nothing here
/// can reason about; a delete by name would 422 on it anyway.
Conflict,
}
/// A scope list reduced to what Forgejo would store for it.
///
/// Forgejo normalises a new token's scopes before storing them
/// (`models/auth/access_token_scope.go`, `Normalize` → `toScope`): a `read:X`
/// beside `write:X` is dropped, because the write bit implies the read one.
/// The admin list then returns the stored form. Comparing
/// [`AGENT_TOKEN_SCOPES`] to that list as written would never match, and every
/// pass would rotate every agent's token.
fn normalized_scopes<'a>(scopes: impl IntoIterator<Item = &'a str>) -> BTreeSet<String> {
let all: BTreeSet<&str> = scopes.into_iter().map(str::trim).collect();
all.iter()
.filter(|s| {
s.strip_prefix("read:")
.is_none_or(|area| !all.contains(format!("write:{area}").as_str()))
})
.map(|s| (*s).to_owned())
.collect()
}
/// The last eight characters of `token`, as Forgejo reports them for a token
/// it holds (`token_last_eight`). `None` for a token shorter than that, which
/// no Forgejo token is.
fn last_eight(token: &str) -> Option<&str> {
token.len().checked_sub(8).and_then(|at| token.get(at..))
}
/// Decide what to do about an agent's token, from what the store holds and
/// what the forge lists for the agent.
///
/// Every token not named [`AGENT_TOKEN_NAME`] is ignored, so the
/// `hyperhive-*` tokens `hive-c0re` left behind never affect the decision.
pub fn classify(stored: Option<&forge::Credential>, listed: &[AccessToken]) -> Decision {
classify_named(AGENT_TOKEN_NAME, AGENT_TOKEN_SCOPES, stored, listed)
}
/// [`classify`] for the token named `name` that should carry `scopes`, so a
/// second kind of token this controller mints decides the same way.
pub(super) fn classify_named(
name: &str,
scopes: &str,
stored: Option<&forge::Credential>,
listed: &[AccessToken],
) -> Decision {
let ours: Vec<&AccessToken> = listed
.iter()
.filter(|t| t.name.as_deref() == Some(name))
.collect();
let token = match ours[..] {
[] => return Decision::Mint(MintReason::NotOnForge),
[token] => token,
_ => return Decision::Conflict,
};
let Some(stored) = stored else {
return Decision::Mint(MintReason::NotStored);
};
if token.token_last_eight.as_deref() != last_eight(&stored.value) {
return Decision::Mint(MintReason::LastEightMismatch);
}
let listed_scopes = normalized_scopes(token.scopes.iter().flatten().map(String::as_str));
if listed_scopes != normalized_scopes(scopes.split(',')) {
return Decision::Mint(MintReason::ScopeMismatch);
}
Decision::Keep
}
/// What one pass found for one agent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Observed {
/// Both reads worked, and this is what [`classify`] made of them.
Decided(Decision),
/// The forge has no user by this agent's name. Planned like a mint: the
/// queued job creates the user first (`CreateForgeUser`, idempotent), so
/// an agent that holds a store identity but was never given a forge
/// account still ends up with both.
NoForgeUser,
/// A read failed. Nothing is known, so nothing is done.
Unknown,
}
/// The agents a pass mints for: a [`Decision::Mint`], or an agent with no
/// forge user yet ([`Observed::NoForgeUser`]), whose job creates the user
/// before it mints.
///
/// [`Observed::Unknown`] in particular never mints: a forge or store outage
/// must not turn into a rotation of every agent's token.
pub fn plan(observed: &[(String, Observed)]) -> Vec<String> {
observed
.iter()
.filter(|(_, o)| {
matches!(
o,
Observed::Decided(Decision::Mint(_)) | Observed::NoForgeUser
)
})
.map(|(agent, _)| agent.clone())
.collect()
}
/// Whether a forge error is a 404, whichever of its two shapes it came in.
pub(super) fn is_not_found(e: &ForgejoError) -> bool {
match e {
ForgejoError::ApiError(api) => {
matches!(api.error_kind(), ApiErrorKind::NotFound { .. })
|| matches!(api.error_kind(), ApiErrorKind::Other(s) if *s == StatusCode::NOT_FOUND)
}
ForgejoError::UnexpectedStatusCode(s) => *s == StatusCode::NOT_FOUND,
_ => false,
}
}
impl Client {
/// Every access token the forge lists for `agent`, or `None` when the
/// forge has no such user.
pub(super) async fn list_agent_tokens(&self, agent: &str) -> Result<Option<Vec<AccessToken>>> {
match self
.api
.call(|api| Box::pin(api.admin_list_user_access_tokens(agent).all()))
.await
{
Ok(tokens) => Ok(Some(tokens)),
Err(e) if is_not_found(&e) => Ok(None),
Err(e) => Err(e).with_context(|| format!("listing {agent}'s forge tokens")),
}
}
/// Make sure `agent`'s stored token is a live [`AGENT_TOKEN_NAME`] token
/// with [`AGENT_TOKEN_SCOPES`], and mint one if it is not. The whole job
/// of the `MintAgentForgeToken` node.
///
/// A rotation deletes the old token first, then creates, stores, and uses
/// the new one: it logs in with it and asks the forge who it is, so the
/// node does not report success on a write nobody has read. A crash
/// between any two steps leaves a state the next run classifies as
/// [`Decision::Mint`] again.
///
/// # Errors
/// When the store or the forge refuses a step, when the agent has no forge
/// user, or when the new token authenticates as someone else.
pub async fn ensure_agent_forge_token(&self, agent: &str) -> Result<()> {
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
self.ensure_agent_forge_token_in(&store, agent).await
}
/// [`Client::ensure_agent_forge_token`] against any store.
///
/// # Errors
/// As [`Client::ensure_agent_forge_token`]. A store that can't be read is
/// one of them: nothing is minted on a token that might exist.
pub(super) async fn ensure_agent_forge_token_in(
&self,
store: &impl TokenStore,
agent: &str,
) -> Result<()> {
let path = forge::agent_token_path(agent)?;
let stored = store
.read_credential(&path)
.await
.with_context(|| format!("reading {path}"))?;
let Some(listed) = self.list_agent_tokens(agent).await? else {
bail!(
"the forge has no user {agent:?} even after this job's create_forge_user \
node, so there is nothing to mint a token for"
);
};
let reason = match classify(stored.as_ref(), &listed) {
Decision::Keep => {
tracing::debug!(agent, "agent forge token is current; left as it is");
return Ok(());
}
Decision::Conflict => bail!(
"the forge lists more than one {AGENT_TOKEN_NAME:?} token for {agent:?}; \
delete them by id and re-run"
),
Decision::Mint(reason) => reason,
};
let credential = self
.replace_token(
store,
agent,
AGENT_TOKEN_NAME,
AGENT_TOKEN_SCOPES,
&listed,
&path,
)
.await?;
let as_agent = async_client(self.url.clone(), &credential.value)
.context("building a forge client with the new token")?;
let me = as_agent
.user_get_current()
.await
.with_context(|| format!("using {agent}'s new forge token"))?;
if me.login.as_deref() != Some(agent) {
bail!("{agent}'s new forge token authenticates as someone else");
}
tracing::info!(agent, ?reason, %path, "agent forge token minted and stored");
Ok(())
}
/// Delete `user`'s token named `name` if `listed` has one, create a new
/// one carrying `scopes`, and store it at `path`. A crash between any two
/// steps leaves a state [`classify_named`] reads as a mint again.
///
/// # Errors
/// When the forge refuses the delete or the create, answers the create
/// with no value, or the store refuses the write.
pub(super) async fn replace_token(
&self,
store: &impl TokenStore,
user: &str,
name: &str,
scopes: &str,
listed: &[AccessToken],
path: &str,
) -> Result<forge::Credential> {
if listed.iter().any(|t| t.name.as_deref() == Some(name)) {
match self
.api
.call(|api| api.admin_delete_user_access_token(user, name).into_future())
.await
{
Ok(()) => {}
Err(e) if is_not_found(&e) => {}
Err(e) => {
return Err(e).with_context(|| format!("deleting {user}'s {name} token"));
}
}
}
let created = self
.api
.call(|api| {
api.admin_create_user_access_token(
user,
CreateAccessTokenOption {
name: name.to_owned(),
repositories: None,
scopes: Some(scopes.split(',').map(str::to_owned).collect()),
},
)
.into_future()
})
.await
.with_context(|| format!("creating {user}'s {name} token"))?;
let Some(value) = created.sha1.filter(|v| !v.is_empty()) else {
bail!("the forge created {user}'s token but returned no value for it");
};
let credential = forge::Credential {
value,
name: name.to_owned(),
};
store
.write_credential(path, &credential)
.await
.with_context(|| format!("storing {user}'s forge token at {path}"))?;
Ok(credential)
}
/// What the forge and the store say about `agent`'s token.
pub(super) async fn observe_agent(&self, store: &impl TokenStore, agent: &str) -> Observed {
let stored = match forge::agent_token_path(agent) {
Ok(path) => store.read_credential(&path).await,
Err(e) => Err(e),
};
let stored = match stored {
Ok(stored) => stored,
Err(e) => {
tracing::warn!(agent, error = %e, "agent forge token: store read failed");
return Observed::Unknown;
}
};
match self.list_agent_tokens(agent).await {
Ok(Some(listed)) => Observed::Decided(classify(stored.as_ref(), &listed)),
Ok(None) => Observed::NoForgeUser,
Err(e) => {
tracing::warn!(agent, error = %format!("{e:#}"), "agent forge token: forge read failed");
Observed::Unknown
}
}
}
/// One pass: every agent holding a store identity, observed.
async fn observe_all(&self) -> Result<Vec<(String, Observed)>> {
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let roles = store
.list_cert_roles(DEFAULT_CERT_MOUNT)
.await
.context("listing the store's cert-auth roles")?;
let mut observed = Vec::new();
for agent in policy::agents_from_role_names(&roles) {
let o = self.observe_agent(&store, &agent).await;
if o == Observed::NoForgeUser {
tracing::info!(
agent,
"agent forge token: no forge user; creating one first"
);
}
observed.push((agent, o));
}
Ok(observed)
}
}
/// Check every agent's token now and every [`RECONCILE_INTERVAL`] after, and
/// hand the agents that need one to `enqueue`, which inserts a
/// `MintAgentForgeToken` node for each. Also sweeps each `Keep`-decided
/// agent's legacy `hyperhive-<seconds>` tokens off the same observation
/// (`super::legacy_tokens::sweepable`), so a boot where the first tick's
/// store or forge read fails retries the sweep on the next tick instead of
/// leaving those tokens live until a restart.
///
/// The roster is the store's `hive-agent-*` cert-auth roles: exactly the
/// agents that can read what the node writes. The first tick fires
/// immediately (`tokio::time::interval`'s default). A pass that fails is
/// logged and retried on the next tick; it never stops the daemon.
pub fn spawn(client: Arc<Client>, enqueue: impl Fn(Vec<String>) + Send + 'static) {
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
loop {
ticker.tick().await;
let Some(outcome) = super::within_forge_deadline("agent forge tokens", async {
let observed = client.observe_all().await?;
let legacy = super::legacy_tokens::sweepable(&observed);
client.sweep_legacy_tokens(&legacy).await;
anyhow::Ok(observed)
})
.await
else {
continue;
};
match outcome {
Ok(observed) => {
let agents = plan(&observed);
if agents.is_empty() {
tracing::debug!(
checked = observed.len(),
"agent forge tokens: all current"
);
} else {
tracing::info!(
checked = observed.len(),
minting = agents.len(),
"agent forge tokens: queueing mints"
);
enqueue(agents);
}
}
Err(e) => tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"agent forge tokens: pass failed; retrying next tick"
),
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::fake::FakeTokens;
const VALUE: &str = "0123456789abcdef0123456789abcdef01234567";
fn stored() -> forge::Credential {
forge::Credential {
value: VALUE.to_owned(),
name: AGENT_TOKEN_NAME.to_owned(),
}
}
fn token(name: &str, last_eight: &str, scopes: &[&str]) -> AccessToken {
AccessToken {
created_at: None,
id: Some(1),
name: Some(name.to_owned()),
repositories: None,
scopes: Some(scopes.iter().map(|s| (*s).to_owned()).collect()),
sha1: None,
token_last_eight: Some(last_eight.to_owned()),
}
}
/// What Forgejo v16 stores and lists for [`AGENT_TOKEN_SCOPES`]: the
/// `toScope` order, with each `read:X` folded into its `write:X`.
const LISTED_SCOPES: [&str; 6] = [
"write:misc",
"write:notification",
"write:organization",
"write:issue",
"write:repository",
"write:user",
];
fn ours() -> AccessToken {
token(AGENT_TOKEN_NAME, "01234567", &LISTED_SCOPES)
}
#[test]
fn the_scopes_are_hive_c0res_byte_for_byte() {
assert_eq!(
AGENT_TOKEN_SCOPES,
"read:user,write:user,read:notification,write:notification,write:repository,write:issue,write:organization,write:misc"
);
}
#[test]
fn a_current_token_is_kept() {
assert_eq!(classify(Some(&stored()), &[ours()]), Decision::Keep);
}
#[test]
fn scopes_as_written_are_kept_too() {
// A forge that listed the scopes un-normalised must not rotate either.
let t = token(
AGENT_TOKEN_NAME,
"01234567",
&AGENT_TOKEN_SCOPES.split(',').collect::<Vec<_>>(),
);
assert_eq!(classify(Some(&stored()), &[t]), Decision::Keep);
}
#[test]
fn nothing_stored_mints() {
assert_eq!(
classify(None, &[ours()]),
Decision::Mint(MintReason::NotStored)
);
}
#[test]
fn nothing_on_the_forge_mints() {
assert_eq!(
classify(Some(&stored()), &[]),
Decision::Mint(MintReason::NotOnForge)
);
assert_eq!(classify(None, &[]), Decision::Mint(MintReason::NotOnForge));
}
#[test]
fn a_different_last_eight_mints() {
let t = token(AGENT_TOKEN_NAME, "ffffffff", &LISTED_SCOPES);
assert_eq!(
classify(Some(&stored()), &[t]),
Decision::Mint(MintReason::LastEightMismatch)
);
}
#[test]
fn a_missing_scope_mints() {
let t = token(AGENT_TOKEN_NAME, "01234567", &LISTED_SCOPES[1..]);
assert_eq!(
classify(Some(&stored()), &[t]),
Decision::Mint(MintReason::ScopeMismatch)
);
}
#[test]
fn an_extra_scope_mints() {
let mut scopes = LISTED_SCOPES.to_vec();
scopes.push("write:admin");
let t = token(AGENT_TOKEN_NAME, "01234567", &scopes);
assert_eq!(
classify(Some(&stored()), &[t]),
Decision::Mint(MintReason::ScopeMismatch)
);
}
#[test]
fn scope_order_does_not_matter() {
let mut scopes = LISTED_SCOPES.to_vec();
scopes.reverse();
let t = token(AGENT_TOKEN_NAME, "01234567", &scopes);
assert_eq!(classify(Some(&stored()), &[t]), Decision::Keep);
}
#[test]
fn legacy_tokens_are_ignored() {
// A pile of `hyperhive-*` tokens, one of them even matching the
// stored value's last eight, is still "no swarm token".
let legacy = [
token("hyperhive-1700000000", "01234567", &LISTED_SCOPES),
token("hyperhive-1700000001", "aaaaaaaa", &LISTED_SCOPES),
];
assert_eq!(
classify(Some(&stored()), &legacy),
Decision::Mint(MintReason::NotOnForge)
);
let mut with_ours = legacy.to_vec();
with_ours.push(ours());
assert_eq!(classify(Some(&stored()), &with_ours), Decision::Keep);
}
#[test]
fn two_swarm_tokens_are_a_conflict_not_a_mint() {
assert_eq!(
classify(Some(&stored()), &[ours(), ours()]),
Decision::Conflict
);
}
#[test]
fn last_eight_is_the_tail() {
assert_eq!(last_eight(VALUE), Some("01234567"));
assert_eq!(last_eight("short"), None);
}
#[test]
fn a_mint_or_a_missing_user_is_planned() {
let observed = [
("a".to_owned(), Observed::Decided(Decision::Keep)),
(
"b".to_owned(),
Observed::Decided(Decision::Mint(MintReason::NotStored)),
),
("c".to_owned(), Observed::Unknown),
("d".to_owned(), Observed::NoForgeUser),
("e".to_owned(), Observed::Decided(Decision::Conflict)),
(
"f".to_owned(),
Observed::Decided(Decision::Mint(MintReason::ScopeMismatch)),
),
];
assert_eq!(plan(&observed), ["b", "d", "f"]);
}
/// An agent with a store identity and no forge user used to be skipped
/// on every pass, forever. It is planned now; the job it gets creates
/// the user before it mints (see `queue_forge_token_mints`).
#[test]
fn a_missing_forge_user_is_planned() {
let observed = [("ruth".to_owned(), Observed::NoForgeUser)];
assert_eq!(plan(&observed), ["ruth"]);
}
#[test]
fn an_outage_plans_nothing() {
let observed = [
("a".to_owned(), Observed::Unknown),
("b".to_owned(), Observed::Unknown),
];
assert!(plan(&observed).is_empty());
}
#[test]
fn both_404_shapes_are_not_found() {
assert!(is_not_found(&ForgejoError::UnexpectedStatusCode(
StatusCode::NOT_FOUND
)));
assert!(is_not_found(&ForgejoError::ApiError(
ApiErrorKind::NotFound { errors: None }.into()
)));
assert!(!is_not_found(&ForgejoError::UnexpectedStatusCode(
StatusCode::FORBIDDEN
)));
}
/// A stand-in forge for the agent `atlas`: it lists `listed` as the
/// agent's tokens, answers a create with a token whose value is
/// `NEW_VALUE`, and takes every other request.
async fn token_forge(listed: serde_json::Value) -> (Client, super::super::tests::Seen) {
super::super::tests::routed_forge(move |method, path, _| match method {
"GET" if path.contains("tokens") => (200, listed.to_string()),
"POST" if path.contains("tokens") => {
(201, serde_json::json!({"sha1": NEW_VALUE}).to_string())
}
"GET" if path == "/api/v1/user" => {
(200, serde_json::json!({"login": "atlas"}).to_string())
}
"DELETE" => (204, String::new()),
"POST" => (201, "{}".to_owned()),
_ => (200, "{}".to_owned()),
})
.await
}
const NEW_VALUE: &str = "fedcba9876543210fedcba9876543210fedcba98";
fn listed_json(last_eight: &str) -> serde_json::Value {
serde_json::json!([{
"id": 1,
"name": AGENT_TOKEN_NAME,
"token_last_eight": last_eight,
"scopes": LISTED_SCOPES,
}])
}
/// The token requests the forge saw that change something.
fn token_writes(seen: &super::super::tests::Seen) -> Vec<String> {
super::super::tests::writes(seen)
.into_iter()
.filter(|w| w.contains("tokens"))
.collect()
}
fn agent_path() -> String {
forge::agent_token_path("atlas").expect("a valid agent name")
}
#[tokio::test]
async fn a_token_the_store_does_not_hold_is_replaced_and_stored() {
let (client, seen) = token_forge(listed_json("01234567")).await;
let store = FakeTokens::default();
client
.ensure_agent_forge_token_in(&store, "atlas")
.await
.expect("mints");
assert_eq!(store.value_at(&agent_path()).as_deref(), Some(NEW_VALUE));
let writes = token_writes(&seen);
assert!(writes.iter().any(|w| w.starts_with("DELETE")), "{writes:?}");
assert!(writes.iter().any(|w| w.starts_with("POST")), "{writes:?}");
}
#[tokio::test]
async fn a_token_the_forge_no_longer_lists_is_created_without_a_delete() {
// Revoked or expired on the forge: the store's copy is dead.
let (client, seen) = token_forge(serde_json::json!([])).await;
let store = FakeTokens::default().holding(&agent_path(), AGENT_TOKEN_NAME, VALUE);
client
.ensure_agent_forge_token_in(&store, "atlas")
.await
.expect("mints");
assert_eq!(store.value_at(&agent_path()).as_deref(), Some(NEW_VALUE));
let writes = token_writes(&seen);
assert!(
writes.iter().all(|w| !w.starts_with("DELETE")),
"{writes:?}"
);
assert_eq!(writes.len(), 1, "{writes:?}");
}
#[tokio::test]
async fn a_token_whose_forge_copy_differs_is_rotated() {
let (client, seen) = token_forge(listed_json("ffffffff")).await;
let store = FakeTokens::default().holding(&agent_path(), AGENT_TOKEN_NAME, VALUE);
client
.ensure_agent_forge_token_in(&store, "atlas")
.await
.expect("rotates");
assert_eq!(store.value_at(&agent_path()).as_deref(), Some(NEW_VALUE));
assert_eq!(token_writes(&seen).len(), 2, "a delete, then a create");
}
#[tokio::test]
async fn a_valid_token_is_kept_and_nothing_is_written() {
let (client, seen) = token_forge(listed_json("01234567")).await;
let store = FakeTokens::default().holding(&agent_path(), AGENT_TOKEN_NAME, VALUE);
client
.ensure_agent_forge_token_in(&store, "atlas")
.await
.expect("keeps");
assert!(token_writes(&seen).is_empty(), "{:?}", token_writes(&seen));
assert_eq!(store.calls(), [format!("read {}", agent_path())]);
assert_eq!(store.value_at(&agent_path()).as_deref(), Some(VALUE));
}
#[tokio::test]
async fn a_store_that_cannot_be_read_never_mints() {
// The token may well exist: a blind mint would rotate a live one.
let (client, seen) = token_forge(listed_json("ffffffff")).await;
let store = FakeTokens::default().unreadable();
client
.ensure_agent_forge_token_in(&store, "atlas")
.await
.expect_err("the read failed");
assert!(token_writes(&seen).is_empty(), "{:?}", token_writes(&seen));
assert!(store.calls().iter().all(|c| c.starts_with("read")));
}
#[tokio::test]
async fn a_token_the_store_will_not_take_is_an_error_not_a_success() {
let (client, _seen) = token_forge(serde_json::json!([])).await;
let store = FakeTokens::default().unwritable();
let err = client
.ensure_agent_forge_token_in(&store, "atlas")
.await
.expect_err("the write failed");
assert!(format!("{err:#}").contains("storing"), "{err:#}");
}
#[tokio::test]
async fn the_pass_reads_a_stored_token_and_a_failed_read_decides_nothing() {
let (client, seen) = token_forge(listed_json("01234567")).await;
let held = FakeTokens::default().holding(&agent_path(), AGENT_TOKEN_NAME, VALUE);
assert_eq!(
client.observe_agent(&held, "atlas").await,
Observed::Decided(Decision::Keep)
);
let empty = FakeTokens::default();
assert_eq!(
client.observe_agent(&empty, "atlas").await,
Observed::Decided(Decision::Mint(MintReason::NotStored))
);
// The failure: unknown, and the forge is not even asked.
seen.lock().unwrap().clear();
let broken = FakeTokens::default().unreadable();
assert_eq!(
client.observe_agent(&broken, "atlas").await,
Observed::Unknown
);
assert!(
seen.lock().unwrap().is_empty(),
"{:?}",
seen.lock().unwrap()
);
}
}

View file

@ -0,0 +1,294 @@
//! The forge API under the controller's token, re-read from the swarm secret
//! store when the forge refuses it.
//!
//! [`Api::call`] runs one request. When the forge answers 401, it asks the
//! [`StoredSecret`] for a token to try instead and runs the request once more
//! with it; a second 401 is returned as it came. The `StoredSecret` runs one
//! store read at a time and backs off after a read that brings no new token,
//! so a burst of refusals costs the store one read.
use std::sync::{Arc, Mutex};
use forge_client::async_client;
use forgejo_api::{ApiErrorKind, Forgejo, ForgejoError};
use futures_util::future::BoxFuture;
use reqwest::StatusCode;
use swarm_secret_client::stored_secret::StoredSecret;
/// One forge request, as [`Api::call`] runs it.
pub(crate) type Call<'a, R> = BoxFuture<'a, Result<R, ForgejoError>>;
pub(crate) struct Api {
url: url::Url,
token: StoredSecret,
/// A client sending the token it is paired with. Rebuilt when `token`
/// holds a different one.
built: Mutex<(String, Arc<Forgejo>)>,
}
impl Api {
/// A client for the forge at `url`, sending `token`'s current value.
///
/// # Errors
/// `url` is not http(s), or the token is not ASCII.
pub(crate) fn new(url: url::Url, token: StoredSecret) -> Result<Self, ForgejoError> {
let current = token.current();
let api = Arc::new(async_client(url.clone(), &current)?);
Ok(Self {
url,
token,
built: Mutex::new((current, api)),
})
}
/// The token in use and a client sending it.
fn current(&self) -> Result<(String, Arc<Forgejo>), ForgejoError> {
let token = self.token.current();
let mut built = self.built.lock().expect("unpoisoned");
if built.0 != token {
let api = Arc::new(async_client(self.url.clone(), &token)?);
*built = (token.clone(), api);
}
Ok((token, Arc::clone(&built.1)))
}
/// `request` against the forge, run a second time with a re-read token
/// when the forge refuses the first. The forge acts on nothing it answers
/// 401 to, so running a non-idempotent request again is safe.
///
/// Boxed, so a caller awaiting several of these does not carry each one's
/// `R` inline.
pub(crate) fn call<'s, R, F>(&'s self, request: F) -> Call<'s, R>
where
F: Fn(&Forgejo) -> Call<'_, R> + Send + 's,
R: Send + 's,
{
Box::pin(async move {
let (token, api) = self.current()?;
match request(&api).await {
Err(e) if refuses_the_token(&e) => {
if self.token.after_refusal(&token).await.is_none() {
return Err(e);
}
let (_, api) = self.current()?;
request(&api).await
}
done => done,
}
})
}
}
/// The HTTP status `e` reports, for the shapes a 401 can arrive in: endpoints
/// that declare a 401 parse its body into [`ApiErrorKind::Unauthorized`], the
/// rest report the bare status.
fn status(e: &ForgejoError) -> Option<StatusCode> {
match e {
ForgejoError::UnexpectedStatusCode(s) => Some(*s),
ForgejoError::ApiError(e) => match e.error_kind() {
ApiErrorKind::Unauthorized => Some(StatusCode::UNAUTHORIZED),
ApiErrorKind::Other(s) => Some(*s),
_ => None,
},
_ => None,
}
}
/// Whether the forge refused the token. Only a 401: to the forge a 400 is a
/// malformed request, and a re-read it started would find the same token and
/// put a real 401 right after it inside the re-read backoff.
fn refuses_the_token(e: &ForgejoError) -> bool {
status(e) == Some(StatusCode::UNAUTHORIZED)
}
#[cfg(test)]
pub(crate) mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
/// A forge answering 200 to `accepted` and 401 to any other token,
/// counting the requests it serves. The `held`-th request to arrive, from
/// 0, is answered only after one with `accepted` is.
async fn forge_accepting(
accepted: &'static str,
held: Option<usize>,
) -> (url::Url, Arc<AtomicUsize>) {
use axum::http::{HeaderMap, StatusCode, header::AUTHORIZATION, header::CONTENT_TYPE};
let served = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&served);
let (accepted_once, seen_accepted) = tokio::sync::watch::channel(false);
let app = axum::Router::new().fallback(move |headers: HeaderMap| {
let counted = Arc::clone(&counted);
let (accepted_once, mut seen_accepted) = (accepted_once.clone(), seen_accepted.clone());
async move {
let n = counted.fetch_add(1, Ordering::SeqCst);
if held == Some(n) {
seen_accepted.wait_for(|seen| *seen).await.unwrap();
}
let sent = headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok());
if sent == Some(&format!("token {accepted}")) {
accepted_once.send_replace(true);
(StatusCode::OK, [(CONTENT_TYPE, "application/json")], "{}")
} else {
let body = r#"{"message":"token is required"}"#;
(
StatusCode::UNAUTHORIZED,
[(CONTENT_TYPE, "application/json")],
body,
)
}
}
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
tokio::spawn(async move { axum::serve(listener, app).await });
(url, served)
}
/// A token starting at `initial` whose store holds `stored`, counting the
/// reads, each of which takes a second.
fn token(initial: &str, stored: &'static str) -> (StoredSecret, Arc<AtomicUsize>) {
let reads = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&reads);
let secret = StoredSecret::new("test", initial.to_owned(), move || {
let counted = Arc::clone(&counted);
async move {
counted.fetch_add(1, Ordering::SeqCst);
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(stored.to_owned())
}
});
(secret, reads)
}
/// A client for `url` holding `token`, whose store read always fails.
pub(crate) fn fixed(url: url::Url, token: &str) -> Api {
let token = StoredSecret::new("test", token.to_owned(), || async {
Err("no store in this test".into())
});
Api::new(url, token).unwrap()
}
async fn whoami(api: &Api) -> Result<forgejo_api::structs::User, ForgejoError> {
api.call(|api| api.user_get_current().into_future()).await
}
#[tokio::test(start_paused = true)]
async fn a_refused_token_is_re_read_and_the_request_sent_again_with_the_new_one() {
let (url, served) = forge_accepting("new", None).await;
let (token, reads) = token("old", "new");
let api = Api::new(url, token).unwrap();
whoami(&api).await.expect("accepted with the re-read token");
assert_eq!(reads.load(Ordering::SeqCst), 1);
assert_eq!(served.load(Ordering::SeqCst), 2);
whoami(&api).await.expect("the new token stays in use");
assert_eq!(reads.load(Ordering::SeqCst), 1);
assert_eq!(served.load(Ordering::SeqCst), 3);
}
#[tokio::test(start_paused = true)]
async fn a_re_read_token_the_forge_also_refuses_is_returned_as_the_error() {
let (url, served) = forge_accepting("neither", None).await;
let (token, reads) = token("old", "new");
let api = Api::new(url, token).unwrap();
let err = whoami(&api).await.expect_err("both tokens refused");
assert!(refuses_the_token(&err), "{err}");
assert_eq!(reads.load(Ordering::SeqCst), 1);
assert_eq!(served.load(Ordering::SeqCst), 2);
}
#[tokio::test(start_paused = true)]
async fn a_refused_token_still_in_the_store_is_not_sent_again() {
let (url, served) = forge_accepting("new", None).await;
let (token, reads) = token("old", "old");
let api = Api::new(url, token).unwrap();
let err = whoami(&api).await.expect_err("no other token to try");
assert!(refuses_the_token(&err), "{err}");
assert_eq!(reads.load(Ordering::SeqCst), 1);
assert_eq!(served.load(Ordering::SeqCst), 1);
}
#[tokio::test(start_paused = true)]
async fn concurrent_refusals_share_one_store_read() {
let (url, served) = forge_accepting("new", None).await;
let (token, reads) = token("old", "new");
let api = Api::new(url, token).unwrap();
let all = futures_util::future::join_all((0..5).map(|_| whoami(&api))).await;
assert!(all.iter().all(Result::is_ok), "{all:?}");
assert_eq!(reads.load(Ordering::SeqCst), 1);
assert_eq!(served.load(Ordering::SeqCst), 10);
}
// Real time: the held request waits on a socket, and paused time would
// jump the bound below while it does.
#[tokio::test]
async fn a_refusal_landing_after_the_re_read_is_sent_again_without_another_read() {
let (url, served) = forge_accepting("new", Some(1)).await;
let (token, reads) = token("old", "new");
let api = Api::new(url, token).unwrap();
let both = async { tokio::join!(whoami(&api), whoami(&api)) };
let (a, b) = tokio::time::timeout(std::time::Duration::from_secs(10), both)
.await
.expect("the held request is answered once the other is accepted");
a.expect("accepted with the re-read token");
b.expect("accepted with the re-read token");
assert_eq!(reads.load(Ordering::SeqCst), 1);
assert_eq!(served.load(Ordering::SeqCst), 4);
}
#[tokio::test(start_paused = true)]
async fn an_unchanged_token_keeps_the_client() {
let (url, served) = forge_accepting("old", None).await;
let (token, reads) = token("old", "new");
let api = Api::new(url, token).unwrap();
let (first_token, first) = api.current().unwrap();
let (second_token, second) = api.current().unwrap();
assert_eq!(
(first_token.as_str(), second_token.as_str()),
("old", "old")
);
assert!(Arc::ptr_eq(&first, &second));
first.user_get_current().await.expect("sends the old token");
assert_eq!(reads.load(Ordering::SeqCst), 0);
assert_eq!(served.load(Ordering::SeqCst), 1);
}
#[tokio::test(start_paused = true)]
async fn a_changed_token_builds_a_client_sending_the_new_one() {
let (url, _) = forge_accepting("new", None).await;
let (token, _) = token("old", "new");
let api = Api::new(url, token).unwrap();
let (_, before) = api.current().unwrap();
api.token.after_refusal("old").await.expect("a new token");
let (token, after) = api.current().unwrap();
assert_eq!(token, "new");
assert!(!Arc::ptr_eq(&before, &after));
after.user_get_current().await.expect("sends the new token");
let err = before.user_get_current().await.expect_err("still the old");
assert!(refuses_the_token(&err), "{err}");
}
#[test]
fn only_a_401_counts_as_refusing_the_token() {
let unauthorized = forgejo_api::ApiError {
message: None,
kind: ApiErrorKind::Unauthorized,
};
assert!(refuses_the_token(&ForgejoError::ApiError(unauthorized)));
assert!(refuses_the_token(&ForgejoError::UnexpectedStatusCode(
StatusCode::UNAUTHORIZED
)));
let other = forgejo_api::ApiError {
message: None,
kind: ApiErrorKind::Other(StatusCode::UNAUTHORIZED),
};
assert!(refuses_the_token(&ForgejoError::ApiError(other)));
for refused in [StatusCode::BAD_REQUEST, StatusCode::FORBIDDEN] {
assert!(!refuses_the_token(&ForgejoError::UnexpectedStatusCode(
refused
)));
}
}
}

View file

@ -0,0 +1,42 @@
//! The open pull requests that target one branch.
use anyhow::{Context, Result};
use forgejo_api::structs::{
PullRequest, RepoListPullRequestsQuery, RepoListPullRequestsQueryState,
};
use super::Client;
impl Client {
/// Every open pull request in `owner/repo` whose target branch is `base`,
/// as the forge lists them: one call per page of 50.
///
/// # Errors
///
/// The forge refused or did not answer.
pub async fn open_pulls_on(
&self,
owner: &str,
repo: &str,
base: &str,
) -> Result<Vec<PullRequest>> {
let query = RepoListPullRequestsQuery {
state: Some(RepoListPullRequestsQueryState::Open),
sort: None,
milestone: None,
labels: None,
poster: None,
base: Some(base.to_owned()),
head: None,
};
self.api
.call(|api| {
Box::pin(
api.repo_list_pull_requests(owner, repo, query.clone())
.all(),
)
})
.await
.with_context(|| format!("list open pull requests on {base} in {owner}/{repo}"))
}
}

View file

@ -0,0 +1,357 @@
//! The swarm builder's read-only forge account, [`LOGIN`]: created here with
//! the admin API, put in the `hives` team of `agent-configs` (read on every
//! config repo, including ones created later), and given one token, stored
//! at `swarm_secret_client::builder::forge_token_path`, where the builder
//! reads it under its own store identity to fetch the config it builds.
//!
//! The builder never writes to the forge: its build results become commit
//! statuses through this daemon's own client (`crate::builder`).
//!
//! The token decision is [`super::agent_token`]'s, under this module's name
//! and scopes, so a stored token the forge still lists with the same last
//! eight characters and scopes is kept, and a pass whose reads fail queues
//! nothing.
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use forge_client::async_client;
use forgejo_api::structs::RepoSearchQuery;
use swarm_secret_client::builder::forge_token_path;
use swarm_secret_client::forge;
use super::Client;
use super::agent_token::{Decision, Observed, classify_named, is_not_found};
use super::hive_token::TeamSeen;
/// The builder's forge login.
pub const LOGIN: &str = "builder";
/// The forge's name for the account's one token.
pub const TOKEN_NAME: &str = "swarm-builder";
/// What the token may do: read repositories. Which repositories is the
/// account's business, and the account is only in the `hives` team.
pub const TOKEN_SCOPES: &str = "read:repository";
/// How often [`spawn`] re-checks the account and its token.
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// The email this module creates the account with, and the one it requires
/// before acting on an account named [`LOGIN`]. Under its own domain, so it
/// equals no agent's or hive's account email.
const EMAIL: &str = "builder@services.hyperhive.local";
/// Whether a pass that found `seen`, and `member` for the account's place in
/// the `hives` team, queues a `MintBuilderForgeToken` job.
/// [`Observed::Unknown`] never does, so a forge or store outage can't rotate
/// the token, and neither does a [`Decision::Conflict`], which the job would
/// refuse. A kept token queues only when the account is known to be out of
/// the team; that job finds the token current and does not rotate it.
pub fn needs_job(seen: Observed, member: Option<bool>) -> bool {
match seen {
Observed::NoForgeUser | Observed::Decided(Decision::Mint(_)) => true,
Observed::Decided(Decision::Keep) => member == Some(false),
Observed::Unknown | Observed::Decided(Decision::Conflict) => false,
}
}
impl Client {
/// Make sure [`LOGIN`] exists, is in the `hives` team, and holds a live
/// [`TOKEN_NAME`] token in the store, minting one when it does not. The
/// whole job of the `MintBuilderForgeToken` node.
///
/// # Errors
/// When the store or the forge refuses a step, when an account named
/// [`LOGIN`] exists with another email, or when the read-back does not
/// show the new token.
pub async fn ensure_builder_forge_token(&self) -> Result<()> {
let path = forge_token_path()?;
self.ensure_builder_user().await?;
let team = self.ensure_hives_team().await?;
self.api
.call(|api| api.org_add_team_member(team, LOGIN).into_future())
.await
.with_context(|| format!("adding {LOGIN} to the hives team"))?;
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let (stored, listed) = self.read_builder_token(&store, &path).await?;
let reason = match classify_named(TOKEN_NAME, TOKEN_SCOPES, stored.as_ref(), &listed) {
Decision::Keep => {
tracing::debug!("builder forge token is current; left as it is");
return Ok(());
}
Decision::Conflict => bail!(
"the forge lists more than one {TOKEN_NAME:?} token for {LOGIN:?}; delete them \
by id and re-run"
),
Decision::Mint(reason) => reason,
};
let credential = self
.replace_token(&store, LOGIN, TOKEN_NAME, TOKEN_SCOPES, &listed, &path)
.await?;
async_client(self.url.clone(), &credential.value)
.context("building a forge client with the new token")?
.repo_search(RepoSearchQuery::default())
.await
.with_context(|| format!("using {LOGIN}'s new forge token"))?;
let (stored, listed) = self.read_builder_token(&store, &path).await?;
let now = classify_named(TOKEN_NAME, TOKEN_SCOPES, stored.as_ref(), &listed);
if now != Decision::Keep {
bail!("{LOGIN}'s new forge token does not read back as current: {now:?}");
}
tracing::info!(?reason, %path, "builder forge token minted and stored");
Ok(())
}
/// The stored token at `path` and every token the forge lists for
/// [`LOGIN`], which must exist.
async fn read_builder_token(
&self,
store: &swarm_secret_client::SecretStore,
path: &str,
) -> Result<(
Option<forge::Credential>,
Vec<forgejo_api::structs::AccessToken>,
)> {
let stored = store
.read_optional(path)
.await
.with_context(|| format!("reading {path}"))?;
let Some(listed) = self.list_agent_tokens(LOGIN).await? else {
bail!("the forge has no user {LOGIN:?} after this job created it");
};
Ok((stored, listed))
}
/// Create [`LOGIN`] if there is none, refuse one with another email, and
/// lock it out of creating repos.
async fn ensure_builder_user(&self) -> Result<()> {
self.create_user(LOGIN, EMAIL).await?;
let user = self
.api
.call(|api| api.user_get(LOGIN).into_future())
.await
.with_context(|| format!("read forge user {LOGIN}"))?;
if user.email.as_deref() != Some(EMAIL) {
bail!(
"forge account `{LOGIN}` exists but is not the swarm builder's (email {:?}, \
expected `{EMAIL}`); refusing to give it read on every config repo",
user.email
);
}
self.api
.call(|api| {
api.admin_edit_user(LOGIN, super::repo_creation_lockdown(LOGIN))
.into_future()
})
.await
.with_context(|| format!("disable repo creation for forge user {LOGIN}"))?;
Ok(())
}
/// What the store and the forge say about the account's token, and
/// whether it is in the `hives` team (`None` when that read failed).
async fn observe_builder(&self) -> Result<(Observed, Option<bool>)> {
let path = forge_token_path()?;
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let stored = match store.read_optional::<forge::Credential>(&path).await {
Ok(stored) => stored,
Err(e) => {
tracing::warn!(error = %e, "builder forge token: store read failed");
return Ok((Observed::Unknown, None));
}
};
let seen = match self.list_agent_tokens(LOGIN).await {
Ok(Some(listed)) => Observed::Decided(classify_named(
TOKEN_NAME,
TOKEN_SCOPES,
stored.as_ref(),
&listed,
)),
Ok(None) => Observed::NoForgeUser,
Err(e) => {
tracing::warn!(error = %format!("{e:#}"), "builder forge token: forge read failed");
Observed::Unknown
}
};
let member = match self.observe_hives_team().await {
TeamSeen::Matches(id) | TeamSeen::Drifted(id) => {
match self
.api
.call(|api| api.org_list_team_member(id, LOGIN).into_future())
.await
{
Ok(_) => Some(true),
Err(e) if is_not_found(&e) => Some(false),
Err(e) => {
tracing::warn!(error = %e, "builder forge token: team membership read failed");
None
}
}
}
TeamSeen::Absent => Some(false),
TeamSeen::Unknown => None,
};
Ok((seen, member))
}
}
/// Check the account now and every [`RECONCILE_INTERVAL`] after, and call
/// `enqueue`, which inserts a `MintBuilderForgeToken` node, when it needs a
/// job. A pass that fails is logged and retried on the next tick.
pub fn spawn(client: Arc<Client>, enqueue: impl Fn() + Send + 'static) {
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
loop {
ticker.tick().await;
let Some(outcome) =
super::within_forge_deadline("builder forge token", client.observe_builder()).await
else {
continue;
};
match outcome {
Ok((seen, member)) if needs_job(seen, member) => {
tracing::info!(?seen, ?member, "builder forge token: queueing a job");
enqueue();
}
Ok((seen, member)) => {
tracing::debug!(?seen, ?member, "builder forge token: no job");
}
Err(e) => tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"builder forge token: pass failed; retrying next tick"
),
}
}
});
}
#[cfg(test)]
mod tests {
use super::super::agent_token::MintReason;
use super::*;
#[test]
fn the_token_reads_repositories_and_nothing_else() {
assert_eq!(TOKEN_SCOPES, "read:repository");
assert_ne!(TOKEN_NAME, super::super::agent_token::AGENT_TOKEN_NAME);
assert_ne!(TOKEN_NAME, super::super::hive_token::HIVE_TOKEN_NAME);
assert_ne!(TOKEN_NAME, super::super::classifier_account::TOKEN_NAME);
}
#[test]
fn a_mint_a_missing_account_or_a_lost_membership_queues() {
let mint = Observed::Decided(Decision::Mint(MintReason::NotStored));
let keep = Observed::Decided(Decision::Keep);
assert!(needs_job(Observed::NoForgeUser, None));
assert!(needs_job(mint, Some(true)));
assert!(needs_job(keep, Some(false)));
assert!(!needs_job(keep, Some(true)));
assert!(!needs_job(keep, None));
assert!(!needs_job(
Observed::Decided(Decision::Conflict),
Some(false)
));
assert!(!needs_job(Observed::Unknown, Some(false)));
}
#[test]
fn the_accounts_email_is_no_agents_or_hives() {
assert_ne!(EMAIL, super::super::agent_email(LOGIN));
assert_ne!(EMAIL, super::super::legacy_agent_email(LOGIN));
assert!(!LOGIN.starts_with(hive_types::RESERVED_AGENT_PREFIX));
}
/// An existing account named like the builder with an agent's email is
/// refused before the lockdown, so it never joins the team.
#[tokio::test]
async fn the_job_refuses_an_account_that_is_not_the_builders() {
use super::super::tests::{lockdown_patch, stub_forge};
let (client, seen) = stub_forge(
(409, r#"{"message":"user already exists"}"#),
(200, r#"{"email":"builder@hyperhive.local"}"#),
(200, "{}"),
)
.await;
let err = client
.ensure_builder_user()
.await
.expect_err("an agent's account is not the builder's");
assert!(format!("{err:#}").contains("not the swarm builder's"));
assert!(lockdown_patch(&seen, LOGIN).is_none());
}
/// An existing account is locked out of repo creation and of
/// organizations on every pass.
#[tokio::test]
async fn the_job_locks_the_builder_out_of_repos_and_organizations() {
use super::super::tests::{lockdown_patch, stub_forge};
let (client, seen) = stub_forge(
(409, r#"{"message":"user already exists"}"#),
(200, r#"{"email":"builder@services.hyperhive.local"}"#),
(200, "{}"),
)
.await;
client
.ensure_builder_user()
.await
.expect("the builder's own account");
let body = lockdown_patch(&seen, LOGIN).expect("no lockdown PATCH sent");
assert_eq!(body["max_repo_creation"], 0);
assert_eq!(body["allow_create_organization"], false);
}
/// The account is created, its email checked, and it is locked out of
/// creating repos and organizations, in that order.
#[tokio::test]
async fn the_account_is_created_and_locked_out_of_creating_repos() {
use super::super::tests::{lockdown_patch, stub_forge, writes};
let (client, seen) = stub_forge(
(201, "{}"),
(200, r#"{"email":"builder@services.hyperhive.local"}"#),
(200, "{}"),
)
.await;
client.ensure_builder_user().await.unwrap();
let lock = lockdown_patch(&seen, LOGIN).expect("lockdown sent");
assert_eq!(lock["max_repo_creation"], 0);
assert_eq!(lock["allow_create_organization"], false);
assert_eq!(lock["login_name"], LOGIN);
assert_eq!(
writes(&seen),
[
"POST /api/v1/admin/users".to_owned(),
format!("PATCH /api/v1/admin/users/{LOGIN}")
]
);
}
#[tokio::test]
async fn a_refused_create_or_lockdown_fails_the_job() {
use super::super::tests::stub_forge;
let email = (200, r#"{"email":"builder@services.hyperhive.local"}"#);
let (client, seen) = stub_forge((500, r#"{"message":"x"}"#), email, (200, "{}")).await;
client
.ensure_builder_user()
.await
.expect_err("create refused");
assert_eq!(seen.lock().unwrap().len(), 1, "nothing is sent after it");
let (client, _) = stub_forge((201, "{}"), email, (500, r#"{"message":"x"}"#)).await;
client
.ensure_builder_user()
.await
.expect_err("a lockdown that failed is not a built account");
}
}

View file

@ -0,0 +1,766 @@
//! The CI metrics poller's read-only forge account, [`LOGIN`]: created here
//! with the admin API, put in a [`TEAM`] in every organisation that reads the
//! Actions unit of each of its repos (including ones created later), and
//! given one token, stored at
//! `swarm_secret_client::ci_metrics::forge_token_path`, where the poller reads
//! it under its own store identity to list CI runs.
//!
//! A public repo's runs need no grant. A private repo owned by a user gets
//! none: the forge grants a user's repo only to a collaborator, and a
//! collaborator reads every unit, code included.
//!
//! The token decision is [`super::agent_token`]'s, under this module's name
//! and scopes, so a stored token the forge still lists with the same last
//! eight characters and scopes is kept, and a pass whose reads fail queues
//! nothing.
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use forge_client::async_client;
use forgejo_api::structs::{
CreateTeamOption, CreateTeamOptionPermission, EditTeamOption, EditTeamOptionPermission,
RepoSearchQuery, Team, TeamPermission,
};
use swarm_secret_client::ci_metrics::forge_token_path;
use swarm_secret_client::forge;
use super::agent_token::{Decision, Observed, classify_named, is_not_found};
use super::hive_token::TeamSeen;
use super::{Client, folds_into_success};
/// The poller's forge login.
pub const LOGIN: &str = "ci-metrics";
/// The forge's name for the account's one token.
pub const TOKEN_NAME: &str = "swarm-ci-metrics";
/// What the token may do: read repositories, which the runs list is filed
/// under. Which repositories is the account's business: public ones, and
/// those its [`TEAM`]s reach.
pub const TOKEN_SCOPES: &str = "read:repository";
/// The team in each organisation the account is the one member of.
const TEAM: &str = "ci-metrics";
const TEAM_DESCRIPTION: &str = "hyperhive CI metrics — read on every repo's Actions runs";
/// The one unit the team reads.
const TEAM_UNITS: [&str; 1] = ["repo.actions"];
/// Organisations per page of the admin listing.
const ORG_PAGE: u32 = 50;
/// How often [`spawn`] re-checks the account, its teams and its token.
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// The email this module creates the account with, and the one it requires
/// before acting on an account named [`LOGIN`]. Under its own domain, so it
/// equals no agent's or hive's account email.
const EMAIL: &str = "ci-metrics@services.hyperhive.local";
/// Whether `t` has every setting [`Client::ensure_ci_metrics_team`] gives it.
fn team_matches(t: &Team) -> bool {
t.units
.as_deref()
.is_some_and(|units| units.iter().map(String::as_str).eq(TEAM_UNITS))
&& t.permission == Some(TeamPermission::Read)
&& t.includes_all_repositories == Some(true)
&& t.can_create_org_repo == Some(false)
&& t.description.as_deref() == Some(TEAM_DESCRIPTION)
}
/// Whether a pass that found `seen`, and `granted` for whether every
/// organisation's [`TEAM`] is as the job leaves it with the account in it,
/// queues a `MintCiMetricsForgeToken` job. [`Observed::Unknown`] never does,
/// so a forge or store outage can't rotate the token, and neither does a
/// [`Decision::Conflict`], which the job would refuse. A kept token queues
/// only when some grant is known to be missing; that job finds the token
/// current and does not rotate it.
pub fn needs_job(seen: Observed, granted: Option<bool>) -> bool {
match seen {
Observed::NoForgeUser | Observed::Decided(Decision::Mint(_)) => true,
Observed::Decided(Decision::Keep) => granted == Some(false),
Observed::Unknown | Observed::Decided(Decision::Conflict) => false,
}
}
impl Client {
/// Make sure [`LOGIN`] exists, is in [`TEAM`] in every organisation, and
/// holds a live [`TOKEN_NAME`] token in the store, minting one when it
/// does not. The whole job of the `MintCiMetricsForgeToken` node.
///
/// # Errors
/// When the store or the forge refuses a step, when an account named
/// [`LOGIN`] exists with another email, or when the read-back does not
/// show the new token.
pub async fn ensure_ci_metrics_forge_token(&self) -> Result<()> {
let path = forge_token_path()?;
self.ensure_ci_metrics_user().await?;
for org in self.all_orgs().await? {
let team = self.ensure_ci_metrics_team(&org).await?;
self.api
.call(|api| api.org_add_team_member(team, LOGIN).into_future())
.await
.with_context(|| format!("adding {LOGIN} to {org}/{TEAM}"))?;
}
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let (stored, listed) = self.read_ci_metrics_token(&store, &path).await?;
let reason = match classify_named(TOKEN_NAME, TOKEN_SCOPES, stored.as_ref(), &listed) {
Decision::Keep => {
tracing::debug!("ci metrics forge token is current; left as it is");
return Ok(());
}
Decision::Conflict => bail!(
"the forge lists more than one {TOKEN_NAME:?} token for {LOGIN:?}; delete them \
by id and re-run"
),
Decision::Mint(reason) => reason,
};
let credential = self
.replace_token(&store, LOGIN, TOKEN_NAME, TOKEN_SCOPES, &listed, &path)
.await?;
async_client(self.url.clone(), &credential.value)
.context("building a forge client with the new token")?
.repo_search(RepoSearchQuery::default())
.await
.with_context(|| format!("using {LOGIN}'s new forge token"))?;
let (stored, listed) = self.read_ci_metrics_token(&store, &path).await?;
let now = classify_named(TOKEN_NAME, TOKEN_SCOPES, stored.as_ref(), &listed);
if now != Decision::Keep {
bail!("{LOGIN}'s new forge token does not read back as current: {now:?}");
}
tracing::info!(?reason, %path, "ci metrics forge token minted and stored");
Ok(())
}
/// The stored token at `path` and every token the forge lists for
/// [`LOGIN`], which must exist.
async fn read_ci_metrics_token(
&self,
store: &swarm_secret_client::SecretStore,
path: &str,
) -> Result<(
Option<forge::Credential>,
Vec<forgejo_api::structs::AccessToken>,
)> {
let stored = store
.read_optional(path)
.await
.with_context(|| format!("reading {path}"))?;
let Some(listed) = self.list_agent_tokens(LOGIN).await? else {
bail!("the forge has no user {LOGIN:?} after this job created it");
};
Ok((stored, listed))
}
/// Create [`LOGIN`] if there is none, refuse one with another email, and
/// lock it out of creating repos.
async fn ensure_ci_metrics_user(&self) -> Result<()> {
self.create_user(LOGIN, EMAIL).await?;
let user = self
.api
.call(|api| api.user_get(LOGIN).into_future())
.await
.with_context(|| format!("read forge user {LOGIN}"))?;
if user.email.as_deref() != Some(EMAIL) {
bail!(
"forge account `{LOGIN}` exists but is not the CI metrics poller's (email {:?}, \
expected `{EMAIL}`); refusing to give it read on every organisation's runs",
user.email
);
}
self.api
.call(|api| {
api.admin_edit_user(LOGIN, super::repo_creation_lockdown(LOGIN))
.into_future()
})
.await
.with_context(|| format!("disable repo creation for forge user {LOGIN}"))?;
Ok(())
}
/// Every organisation on the forge, by name.
async fn all_orgs(&self) -> Result<Vec<String>> {
let mut names = Vec::new();
let mut page = 1;
loop {
let (_, orgs) = self
.api
.call(|api| {
api.admin_get_all_orgs()
.page(page)
.page_size(ORG_PAGE)
.into_future()
})
.await
.context("listing the forge's organisations")?;
let last = orgs.len() < ORG_PAGE as usize;
names.extend(orgs.into_iter().filter_map(|o| o.username.or(o.name)));
if last {
return Ok(names);
}
page += 1;
}
}
/// The id of `org`'s [`TEAM`], created or put back to its settings.
async fn ensure_ci_metrics_team(&self, org: &str) -> Result<i64> {
match self.observe_ci_metrics_team(org).await {
TeamSeen::Matches(id) => Ok(id),
TeamSeen::Drifted(id) => {
self.api
.call(|api| {
api.org_edit_team(
id,
EditTeamOption {
can_create_org_repo: Some(false),
description: Some(TEAM_DESCRIPTION.to_owned()),
includes_all_repositories: Some(true),
name: TEAM.to_owned(),
permission: Some(EditTeamOptionPermission::Read),
units: Some(TEAM_UNITS.map(str::to_owned).to_vec()),
units_map: None,
},
)
.into_future()
})
.await
.with_context(|| format!("reconcile {org}/{TEAM} team settings"))?;
tracing::info!("swarm forge: reconciled {org}/{TEAM} team settings");
Ok(id)
}
TeamSeen::Absent => self.create_ci_metrics_team(org).await,
TeamSeen::Unknown => bail!("could not read the teams of {org}"),
}
}
async fn create_ci_metrics_team(&self, org: &str) -> Result<i64> {
let team = CreateTeamOption {
can_create_org_repo: Some(false),
description: Some(TEAM_DESCRIPTION.to_owned()),
includes_all_repositories: Some(true),
name: TEAM.to_owned(),
permission: Some(CreateTeamOptionPermission::Read),
units: Some(TEAM_UNITS.map(str::to_owned).to_vec()),
units_map: None,
};
match self
.api
.call(|api| api.org_create_team(org, team.clone()).into_future())
.await
{
Ok(created) => {
tracing::info!("swarm forge: created {org}/{TEAM} team");
created
.id
.with_context(|| format!("the forge created {org}/{TEAM} but returned no id"))
}
// A duplicate is a 409 or a 422; either counts once a re-read
// finds the team, which also supplies its id.
Err(e) => match self.observe_ci_metrics_team(org).await {
TeamSeen::Matches(id) | TeamSeen::Drifted(id) if folds_into_success(&e, true) => {
Ok(id)
}
_ => Err(e).with_context(|| format!("create team {org}/{TEAM}")),
},
}
}
async fn observe_ci_metrics_team(&self, org: &str) -> TeamSeen {
match self
.api
.call(|api| api.org_list_teams(org).into_future())
.await
{
Ok((_, teams)) => teams
.into_iter()
.find(|t| t.name.as_deref() == Some(TEAM))
.map_or(TeamSeen::Absent, |t| match t.id {
Some(id) if team_matches(&t) => TeamSeen::Matches(id),
Some(id) => TeamSeen::Drifted(id),
None => TeamSeen::Unknown,
}),
Err(e) => {
tracing::warn!(error = %e, "ci metrics forge token: reading the teams of {org} failed");
TeamSeen::Unknown
}
}
}
/// Whether every organisation's [`TEAM`] is as the job leaves it, with
/// the account in it; `None` when a read failed.
async fn observe_ci_metrics_grants(&self) -> Option<bool> {
let orgs = match self.all_orgs().await {
Ok(orgs) => orgs,
Err(e) => {
tracing::warn!(error = %format!("{e:#}"), "ci metrics forge token: organisation read failed");
return None;
}
};
for org in orgs {
let id = match self.observe_ci_metrics_team(&org).await {
TeamSeen::Matches(id) => id,
TeamSeen::Drifted(_) | TeamSeen::Absent => return Some(false),
TeamSeen::Unknown => return None,
};
match self
.api
.call(|api| api.org_list_team_member(id, LOGIN).into_future())
.await
{
Ok(_) => {}
Err(e) if is_not_found(&e) => return Some(false),
Err(e) => {
tracing::warn!(error = %e, "ci metrics forge token: team membership read failed");
return None;
}
}
}
Some(true)
}
/// What the store and the forge say about the account's token, and
/// whether its grants are all in place.
async fn observe_ci_metrics(&self) -> Result<(Observed, Option<bool>)> {
let path = forge_token_path()?;
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let stored = match store.read_optional::<forge::Credential>(&path).await {
Ok(stored) => stored,
Err(e) => {
tracing::warn!(error = %e, "ci metrics forge token: store read failed");
return Ok((Observed::Unknown, None));
}
};
let seen = match self.list_agent_tokens(LOGIN).await {
Ok(Some(listed)) => Observed::Decided(classify_named(
TOKEN_NAME,
TOKEN_SCOPES,
stored.as_ref(),
&listed,
)),
Ok(None) => Observed::NoForgeUser,
Err(e) => {
tracing::warn!(error = %format!("{e:#}"), "ci metrics forge token: forge read failed");
Observed::Unknown
}
};
Ok((seen, self.observe_ci_metrics_grants().await))
}
}
/// Check the account now and every [`RECONCILE_INTERVAL`] after, and call
/// `enqueue`, which inserts a `MintCiMetricsForgeToken` node, when it needs a
/// job. A pass that fails is logged and retried on the next tick.
pub fn spawn(client: Arc<Client>, enqueue: impl Fn() + Send + 'static) {
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
loop {
ticker.tick().await;
let Some(outcome) =
super::within_forge_deadline("ci metrics forge token", client.observe_ci_metrics())
.await
else {
continue;
};
match outcome {
Ok((seen, granted)) if needs_job(seen, granted) => {
tracing::info!(?seen, ?granted, "ci metrics forge token: queueing a job");
enqueue();
}
Ok((seen, granted)) => {
tracing::debug!(?seen, ?granted, "ci metrics forge token: no job");
}
Err(e) => tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"ci metrics forge token: pass failed; retrying next tick"
),
}
}
});
}
#[cfg(test)]
mod tests {
use super::super::agent_token::MintReason;
use super::*;
#[test]
fn the_token_reads_repositories_and_nothing_else() {
assert_eq!(TOKEN_SCOPES, "read:repository");
assert_ne!(TOKEN_NAME, super::super::agent_token::AGENT_TOKEN_NAME);
assert_ne!(TOKEN_NAME, super::super::hive_token::HIVE_TOKEN_NAME);
assert_ne!(TOKEN_NAME, super::super::classifier_account::TOKEN_NAME);
assert_ne!(TOKEN_NAME, super::super::builder_account::TOKEN_NAME);
}
#[test]
fn a_mint_a_missing_account_or_a_missing_grant_queues() {
let mint = Observed::Decided(Decision::Mint(MintReason::NotStored));
let keep = Observed::Decided(Decision::Keep);
assert!(needs_job(Observed::NoForgeUser, None));
assert!(needs_job(mint, Some(true)));
assert!(needs_job(keep, Some(false)));
assert!(!needs_job(keep, Some(true)));
assert!(!needs_job(keep, None));
assert!(!needs_job(
Observed::Decided(Decision::Conflict),
Some(false)
));
assert!(!needs_job(Observed::Unknown, Some(false)));
}
fn team(units: &[&str], permission: TeamPermission) -> Team {
Team {
can_create_org_repo: Some(false),
description: Some(TEAM_DESCRIPTION.to_owned()),
id: Some(7),
includes_all_repositories: Some(true),
name: Some(TEAM.to_owned()),
organization: None,
permission: Some(permission),
units: Some(units.iter().map(|u| (*u).to_owned()).collect()),
units_map: None,
}
}
#[test]
fn the_team_reads_actions_and_nothing_else() {
assert!(team_matches(&team(&["repo.actions"], TeamPermission::Read)));
assert!(!team_matches(&team(
&["repo.actions", "repo.code"],
TeamPermission::Read
)));
assert!(!team_matches(&team(
&["repo.actions"],
TeamPermission::Write
)));
let mut some_repos = team(&["repo.actions"], TeamPermission::Read);
some_repos.includes_all_repositories = Some(false);
assert!(!team_matches(&some_repos));
}
#[test]
fn the_accounts_email_is_no_agents_or_hives() {
assert_ne!(EMAIL, super::super::agent_email(LOGIN));
assert_ne!(EMAIL, super::super::legacy_agent_email(LOGIN));
assert!(!LOGIN.starts_with(hive_types::RESERVED_AGENT_PREFIX));
}
/// An existing account named like the poller with an agent's email is
/// refused before the lockdown, so it never joins a team.
#[tokio::test]
async fn the_job_refuses_an_account_that_is_not_the_pollers() {
use super::super::tests::{lockdown_patch, stub_forge};
let (client, seen) = stub_forge(
(409, r#"{"message":"user already exists"}"#),
(200, r#"{"email":"ci-metrics@hyperhive.local"}"#),
(200, "{}"),
)
.await;
let err = client
.ensure_ci_metrics_user()
.await
.expect_err("an agent's account is not the poller's");
assert!(format!("{err:#}").contains("not the CI metrics poller's"));
assert!(lockdown_patch(&seen, LOGIN).is_none());
}
/// An existing account is locked out of repo creation and of
/// organizations on every pass.
#[tokio::test]
async fn the_job_locks_the_poller_out_of_repos_and_organizations() {
use super::super::tests::{lockdown_patch, stub_forge};
let (client, seen) = stub_forge(
(409, r#"{"message":"user already exists"}"#),
(200, r#"{"email":"ci-metrics@services.hyperhive.local"}"#),
(200, "{}"),
)
.await;
client
.ensure_ci_metrics_user()
.await
.expect("the poller's own account");
let body = lockdown_patch(&seen, LOGIN).expect("no lockdown PATCH sent");
assert_eq!(body["max_repo_creation"], 0);
assert_eq!(body["allow_create_organization"], false);
}
// The forge side, against a stand-in forge that answers by path.
use super::super::tests::{Seen as Requests, routed_forge, sent, writes};
use serde_json::{Value, json};
use std::sync::atomic::{AtomicUsize, Ordering};
fn team_json(id: i64, permission: &str, units: &[&str]) -> Value {
json!({
"id": id,
"name": TEAM,
"description": TEAM_DESCRIPTION,
"permission": permission,
"includes_all_repositories": true,
"can_create_org_repo": false,
"units": units,
})
}
/// A forge listing `orgs` and giving each the teams in `teams`, every
/// request not named by `rest` a 201 for a POST and 200 otherwise.
async fn forge_of(
orgs: &[&str],
teams: Vec<(&'static str, u16, Value)>,
rest: Vec<(String, u16, Value)>,
) -> (Client, Requests) {
let orgs: Vec<Value> = orgs.iter().map(|o| json!({"username": o})).collect();
let teams: Vec<(String, u16, Value)> = teams
.into_iter()
.map(|(k, s, b)| (k.to_owned(), s, b))
.collect();
routed_forge(move |method, path, _| {
let key = format!("{method} {path}");
if key == "GET /api/v1/admin/orgs" {
return (200, json!(orgs).to_string());
}
if let Some((_, s, b)) = teams.iter().chain(rest.iter()).find(|(k, _, _)| *k == key) {
return (*s, b.to_string());
}
match method {
"GET" => (404, r#"{"message":"no"}"#.to_owned()),
"POST" => (201, "{}".to_owned()),
_ => (200, "{}".to_owned()),
}
})
.await
}
#[tokio::test]
async fn the_account_is_created_and_locked_out_of_creating_repos() {
let (client, seen) = forge_of(
&[],
vec![],
vec![at(
"GET /api/v1/users/ci-metrics",
200,
json!({"email": EMAIL}),
)],
)
.await;
client.ensure_ci_metrics_user().await.unwrap();
assert_eq!(
writes(&seen),
[
"POST /api/v1/admin/users".to_owned(),
"PATCH /api/v1/admin/users/ci-metrics".to_owned()
]
);
let lock = sent(&seen, "PATCH", "/api/v1/admin/users/ci-metrics").unwrap();
assert_eq!(lock["max_repo_creation"], 0);
assert_eq!(lock["allow_create_organization"], false);
assert_eq!(lock["login_name"], LOGIN);
}
#[tokio::test]
async fn a_refused_create_stops_before_the_account_is_read_or_locked() {
let (client, seen) = forge_of(
&[],
vec![],
vec![
at("POST /api/v1/admin/users", 500, json!({"message": "x"})),
at("GET /api/v1/users/ci-metrics", 200, json!({"email": EMAIL})),
],
)
.await;
client.ensure_ci_metrics_user().await.expect_err("refused");
assert_eq!(writes(&seen), ["POST /api/v1/admin/users"]);
}
#[tokio::test]
async fn a_team_that_matches_is_left_and_one_with_the_wrong_grant_is_put_back() {
let path = "GET /api/v1/orgs/o/teams";
let (client, seen) = forge_of(
&[],
vec![(path, 200, json!([team_json(3, "read", &TEAM_UNITS)]))],
vec![],
)
.await;
assert_eq!(client.ensure_ci_metrics_team("o").await.unwrap(), 3);
assert!(writes(&seen).is_empty());
let wide = team_json(3, "write", &["repo.actions", "repo.code"]);
let (client, seen) = forge_of(&[], vec![(path, 200, json!([wide]))], vec![]).await;
assert_eq!(client.ensure_ci_metrics_team("o").await.unwrap(), 3);
assert_eq!(writes(&seen), ["PATCH /api/v1/teams/3"]);
let edit = sent(&seen, "PATCH", "/api/v1/teams/3").unwrap();
assert_eq!(edit["permission"], "read");
assert_eq!(edit["units"], json!(TEAM_UNITS));
assert_eq!(edit["includes_all_repositories"], true);
assert_eq!(edit["can_create_org_repo"], false);
}
#[tokio::test]
async fn a_missing_team_is_created_read_only_on_actions_and_a_missing_id_fails() {
let list = ("GET /api/v1/orgs/o/teams", 200, json!([]));
let (client, seen) = forge_of(
&[],
vec![list.clone()],
vec![at("POST /api/v1/orgs/o/teams", 201, json!({"id": 11}))],
)
.await;
assert_eq!(client.ensure_ci_metrics_team("o").await.unwrap(), 11);
let team = sent(&seen, "POST", "/api/v1/orgs/o/teams").unwrap();
assert_eq!(team["name"], TEAM);
assert_eq!(team["permission"], "read");
assert_eq!(team["units"], json!(TEAM_UNITS));
assert_eq!(team["includes_all_repositories"], true);
assert_eq!(team["can_create_org_repo"], false);
let (client, _) = forge_of(&[], vec![list], vec![]).await;
client
.ensure_ci_metrics_team("o")
.await
.expect_err("created, but no id came back");
}
#[tokio::test]
async fn an_unreadable_team_list_is_an_error_and_never_a_create() {
let (client, seen) = forge_of(
&[],
vec![("GET /api/v1/orgs/o/teams", 500, json!({"message": "x"}))],
vec![],
)
.await;
client
.ensure_ci_metrics_team("o")
.await
.expect_err("unknown");
assert!(writes(&seen).is_empty());
}
#[tokio::test]
async fn a_duplicate_create_is_found_by_a_re_read_and_a_refusal_with_no_team_fails() {
let reads = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&reads);
let (client, _) = routed_forge(move |method, path, _| match (method, path) {
("GET", "/api/v1/orgs/o/teams") if counted.fetch_add(1, Ordering::SeqCst) == 0 => {
(200, "[]".to_owned())
}
("GET", "/api/v1/orgs/o/teams") => {
(200, json!([team_json(4, "read", &TEAM_UNITS)]).to_string())
}
("POST", _) => (409, r#"{"message":"exists"}"#.to_owned()),
_ => (200, "{}".to_owned()),
})
.await;
assert_eq!(client.ensure_ci_metrics_team("o").await.unwrap(), 4);
let (client, _) = forge_of(
&[],
vec![("GET /api/v1/orgs/o/teams", 200, json!([]))],
vec![at(
"POST /api/v1/orgs/o/teams",
409,
json!({"message": "x"}),
)],
)
.await;
client
.ensure_ci_metrics_team("o")
.await
.expect_err("not found again");
}
#[tokio::test]
async fn every_page_of_organisations_is_read() {
let asked = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&asked);
let (client, _) = routed_forge(move |_, path, _| {
assert_eq!(path, "/api/v1/admin/orgs");
let page = counted.fetch_add(1, Ordering::SeqCst);
let n = if page == 0 { ORG_PAGE as usize } else { 1 };
let orgs: Vec<Value> = (0..n)
.map(|i| json!({"username": format!("org-{page}-{i}")}))
.collect();
(200, json!(orgs).to_string())
})
.await;
let names = client.all_orgs().await.unwrap();
assert_eq!(names.len(), ORG_PAGE as usize + 1);
assert_eq!(asked.load(Ordering::SeqCst), 2);
assert_eq!(names.last().unwrap(), "org-1-0");
}
fn at(key: &str, status: u16, body: Value) -> (String, u16, Value) {
(key.to_owned(), status, body)
}
fn member(id: i64) -> (String, u16, Value) {
at(
&format!("GET /api/v1/teams/{id}/members/ci-metrics"),
200,
json!({}),
)
}
#[tokio::test]
async fn the_grants_are_complete_only_when_every_org_has_the_team_with_the_account_in_it() {
let teams = |ok: bool| {
vec![
(
"GET /api/v1/orgs/a/teams",
200,
json!([team_json(1, "read", &TEAM_UNITS)]),
),
(
"GET /api/v1/orgs/b/teams",
200,
if ok {
json!([team_json(2, "read", &TEAM_UNITS)])
} else {
json!([])
},
),
]
};
let members = vec![member(1), member(2)];
let (client, _) = forge_of(&["a", "b"], teams(true), members.clone()).await;
assert_eq!(client.observe_ci_metrics_grants().await, Some(true));
// A team missing in one org.
let (client, _) = forge_of(&["a", "b"], teams(false), members.clone()).await;
assert_eq!(client.observe_ci_metrics_grants().await, Some(false));
// The account missing from a team (404), against a failed read (500).
let (client, _) = forge_of(&["a", "b"], teams(true), vec![member(1)]).await;
assert_eq!(client.observe_ci_metrics_grants().await, Some(false));
let (client, _) = forge_of(
&["a", "b"],
teams(true),
vec![
member(1),
at(
"GET /api/v1/teams/2/members/ci-metrics",
500,
json!({"message": "x"}),
),
],
)
.await;
assert_eq!(client.observe_ci_metrics_grants().await, None);
// An unreadable team list, and an unreadable org list.
let mut unreadable = teams(true);
unreadable[1] = ("GET /api/v1/orgs/b/teams", 500, json!({"message": "x"}));
let (client, _) = forge_of(&["a", "b"], unreadable, members).await;
assert_eq!(client.observe_ci_metrics_grants().await, None);
let (client, _) = routed_forge(|_, _, _| (500, r#"{"message":"x"}"#.to_owned())).await;
assert_eq!(client.observe_ci_metrics_grants().await, None);
}
}

View file

@ -0,0 +1,587 @@
//! The review classifier's forge account, [`LOGIN`]: created here with the
//! admin API and given one token, stored at
//! `swarm_secret_client::review_classifier::forge_token_path`. Requesting
//! this account as a reviewer starts a classifier run, and this daemon posts
//! the result as the account's review (`crate::review_classifier::review`).
//! This daemon also pushes the try-out page's branches as the account
//! (`crate::review_classifier::open_pr`). The classifier itself never holds
//! the token.
//!
//! The account gets no repo access here. A repo admin adds it to a repo by
//! hand: read to request it as a reviewer, write (or a place on the branch
//! protection's approvals whitelist) for its approval to count, and write to
//! push a branch.
//!
//! The token decision is [`super::agent_token`]'s, under this module's name
//! and scopes, so a stored token the forge still lists with the same last
//! eight characters and scopes is kept, and a pass whose reads fail queues
//! nothing.
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use forge_client::async_client;
use forgejo_api::Forgejo;
use forgejo_api::structs::{
ChangeFileOperation, ChangeFileOperationOperation, ChangeFilesOptions, CreatePullReviewOptions,
Identity, RepoSearchQuery,
};
use swarm_secret_client::forge;
use swarm_secret_client::review_classifier::forge_token_path;
use super::Client;
use super::agent_token::{Decision, Observed, classify_named, is_not_found};
/// The classifier's forge login: the reviewer someone requests.
pub const LOGIN: &str = "review-classifier";
/// The forge's name for the account's one token.
pub const TOKEN_NAME: &str = "swarm-review-classifier";
/// What the token may do: post reviews and push branches, both of which the
/// forge files under the repository scope. Which repos is the account's access, granted by hand.
pub const TOKEN_SCOPES: &str = "write:repository";
/// How often [`spawn`] re-checks the account and its token.
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// The email this module creates the account with, and the one it requires
/// before acting on an account named [`LOGIN`]. Under its own domain, so it
/// equals no agent's or hive's account email.
const EMAIL: &str = "review-classifier@services.hyperhive.local";
/// Whether a pass that found `seen` queues a `MintClassifierForgeToken` job.
/// [`Observed::Unknown`] never does, so a forge or store outage can't rotate
/// the token, and neither does a [`Decision::Conflict`], which the job would
/// refuse.
pub fn needs_job(seen: Observed) -> bool {
matches!(
seen,
Observed::NoForgeUser | Observed::Decided(Decision::Mint(_))
)
}
/// One review as the classifier's account posts it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Review {
/// `APPROVED`, `REQUEST_CHANGES` or `COMMENT`.
pub event: &'static str,
pub body: String,
}
/// Who a commit names as its author.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommitAuthor {
pub name: String,
pub email: String,
}
/// One file written as one commit on a new branch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BranchCommit {
/// The branch the new one starts from, at its head.
pub base: String,
/// Must not exist yet: the forge refuses the commit when it does.
pub branch: String,
pub path: String,
/// The blob sha of the file on `base` it replaces; `None` creates it.
/// The forge refuses the commit when `base` no longer holds that blob.
pub sha: Option<String>,
pub content: Vec<u8>,
pub message: String,
pub author: CommitAuthor,
}
impl Client {
/// Make sure [`LOGIN`] exists and holds a live [`TOKEN_NAME`] token in
/// the store, minting one when it does not. The whole job of the
/// `MintClassifierForgeToken` node.
///
/// # Errors
/// When the store or the forge refuses a step, when an account named
/// [`LOGIN`] exists with another email, or when the read-back does not
/// show the new token.
pub async fn ensure_classifier_forge_token(&self) -> Result<()> {
let path = forge_token_path()?;
self.ensure_classifier_user().await?;
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let (stored, listed) = self.read_classifier_token(&store, &path).await?;
let reason = match classify_named(TOKEN_NAME, TOKEN_SCOPES, stored.as_ref(), &listed) {
Decision::Keep => {
tracing::debug!("review classifier forge token is current; left as it is");
return Ok(());
}
Decision::Conflict => bail!(
"the forge lists more than one {TOKEN_NAME:?} token for {LOGIN:?}; delete them \
by id and re-run"
),
Decision::Mint(reason) => reason,
};
let credential = self
.replace_token(&store, LOGIN, TOKEN_NAME, TOKEN_SCOPES, &listed, &path)
.await?;
async_client(self.url.clone(), &credential.value)
.context("building a forge client with the new token")?
.repo_search(RepoSearchQuery::default())
.await
.with_context(|| format!("using {LOGIN}'s new forge token"))?;
let (stored, listed) = self.read_classifier_token(&store, &path).await?;
let now = classify_named(TOKEN_NAME, TOKEN_SCOPES, stored.as_ref(), &listed);
if now != Decision::Keep {
bail!("{LOGIN}'s new forge token does not read back as current: {now:?}");
}
tracing::info!(?reason, %path, "review classifier forge token minted and stored");
Ok(())
}
/// Post `review` on PR `number` of `owner/repo` as [`LOGIN`], on
/// `commit` when one is given. Reads the token from the store on every
/// call. The posted review's URL, when the forge names one.
///
/// # Errors
/// When the store holds no token yet, or the forge refuses the review.
pub async fn post_classifier_review(
&self,
owner: &str,
repo: &str,
number: i64,
commit: Option<&str>,
review: Review,
) -> Result<Option<String>> {
self.as_classifier()
.await?
.repo_create_pull_review(
owner,
repo,
number,
CreatePullReviewOptions {
body: Some(review.body),
comments: None,
commit_id: commit.map(str::to_owned),
event: Some(review.event.to_owned()),
},
)
.await
.with_context(|| format!("posting {LOGIN}'s review on PR {number} of {owner}/{repo}"))
.map(|posted| posted.html_url.map(String::from))
}
/// Make `commit` as [`LOGIN`]: one commit on a new branch, from the head
/// of its base. Reads the token from the store on every call.
///
/// # Errors
/// When the store holds no token yet, or the forge refuses the commit;
/// a [`forgejo_api::ForgejoError`] in the chain carries the forge's
/// status.
pub async fn push_classifier_branch(
&self,
owner: &str,
repo: &str,
commit: BranchCommit,
) -> Result<()> {
push_branch(&self.as_classifier().await?, owner, repo, commit).await
}
/// The forge account `login` as a commit author: its full name, or its
/// login when it has none, and its [`noreply_address`], so the commit
/// links to the account without showing its email. `None` when the
/// forge has no such account.
///
/// # Errors
/// When the forge refuses the read, or this daemon's forge URL has no
/// host.
pub async fn commit_author(&self, login: &str) -> Result<Option<CommitAuthor>> {
let user = match self.api.call(|api| api.user_get(login).into_future()).await {
Ok(user) => user,
Err(e) if is_not_found(&e) => return Ok(None),
Err(e) => return Err(e).with_context(|| format!("read forge user {login}")),
};
let login = user.login.as_deref().unwrap_or(login);
let email = noreply_address(&self.url, login)?;
let name = user
.full_name
.map(|n| n.trim().to_owned())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| login.to_owned());
Ok(Some(CommitAuthor { name, email }))
}
/// A forge client acting as [`LOGIN`], with the token the store holds.
async fn as_classifier(&self) -> Result<Forgejo> {
let path = forge_token_path()?;
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let Some(credential) = store
.read_optional::<forge::Credential>(&path)
.await
.with_context(|| format!("reading {path}"))?
else {
bail!("nothing at {path}: the classifier's forge token is not minted yet");
};
async_client(self.url.clone(), &credential.value)
.context("building a forge client with the classifier's token")
}
/// The stored token at `path` and every token the forge lists for
/// [`LOGIN`], which must exist.
async fn read_classifier_token(
&self,
store: &swarm_secret_client::SecretStore,
path: &str,
) -> Result<(
Option<forge::Credential>,
Vec<forgejo_api::structs::AccessToken>,
)> {
let stored = store
.read_optional(path)
.await
.with_context(|| format!("reading {path}"))?;
let Some(listed) = self.list_agent_tokens(LOGIN).await? else {
bail!("the forge has no user {LOGIN:?} after this job created it");
};
Ok((stored, listed))
}
/// Create [`LOGIN`] if there is none, refuse one with another email, and
/// lock it out of creating repos.
async fn ensure_classifier_user(&self) -> Result<()> {
self.create_user(LOGIN, EMAIL).await?;
let user = self
.api
.call(|api| api.user_get(LOGIN).into_future())
.await
.with_context(|| format!("read forge user {LOGIN}"))?;
if user.email.as_deref() != Some(EMAIL) {
bail!(
"forge account `{LOGIN}` exists but is not the review classifier's (email {:?}, \
expected `{EMAIL}`); refusing to mint a token for it",
user.email
);
}
self.api
.call(|api| {
api.admin_edit_user(LOGIN, super::repo_creation_lockdown(LOGIN))
.into_future()
})
.await
.with_context(|| format!("disable repo creation for forge user {LOGIN}"))?;
Ok(())
}
/// What the store and the forge say about the account's token.
async fn observe_classifier(&self) -> Result<Observed> {
let path = forge_token_path()?;
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let stored = match store.read_optional::<forge::Credential>(&path).await {
Ok(stored) => stored,
Err(e) => {
tracing::warn!(error = %e, "review classifier forge token: store read failed");
return Ok(Observed::Unknown);
}
};
Ok(match self.list_agent_tokens(LOGIN).await {
Ok(Some(listed)) => Observed::Decided(classify_named(
TOKEN_NAME,
TOKEN_SCOPES,
stored.as_ref(),
&listed,
)),
Ok(None) => Observed::NoForgeUser,
Err(e) => {
tracing::warn!(error = %format!("{e:#}"), "review classifier forge token: forge read failed");
Observed::Unknown
}
})
}
}
/// The address the forge itself puts on a web commit by `login` when the
/// account keeps its email private: the lowercased login at
/// `NO_REPLY_ADDRESS`. The forge module leaves that at its default,
/// `noreply.<DOMAIN>`, and sets `DOMAIN` from
/// `services.hyperhive.swarm.forge.domain`, the option this daemon's forge
/// URL `forge` is built from, so the domain is that URL's host.
fn noreply_address(forge: &url::Url, login: &str) -> Result<String> {
let domain = forge
.host_str()
.with_context(|| format!("the forge URL {forge} names no host"))?;
Ok(format!("{}@noreply.{domain}", login.to_lowercase()))
}
/// Make `commit` with `forge`'s identity as committer, through the contents
/// API.
async fn push_branch(forge: &Forgejo, owner: &str, repo: &str, commit: BranchCommit) -> Result<()> {
use base64::Engine as _;
let branch = commit.branch.clone();
forge
.repo_change_files(
owner,
repo,
ChangeFilesOptions {
author: Some(Identity {
name: Some(commit.author.name),
email: Some(commit.author.email),
}),
branch: Some(commit.base),
committer: None,
dates: None,
files: vec![ChangeFileOperation {
content: Some(
base64::engine::general_purpose::STANDARD.encode(&commit.content),
),
from_path: None,
operation: if commit.sha.is_some() {
ChangeFileOperationOperation::Update
} else {
ChangeFileOperationOperation::Create
},
path: commit.path,
sha: commit.sha,
}],
force_overwrite_new_branch: Some(false),
message: Some(commit.message),
new_branch: Some(commit.branch),
signoff: None,
},
)
.await
.with_context(|| format!("pushing {LOGIN}'s branch {branch} to {owner}/{repo}"))?;
Ok(())
}
/// Check the account now and every [`RECONCILE_INTERVAL`] after, and call
/// `enqueue`, which inserts a `MintClassifierForgeToken` node, when it needs
/// a job. A pass that fails is logged and retried on the next tick.
pub fn spawn(client: Arc<Client>, enqueue: impl Fn() + Send + 'static) {
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
loop {
ticker.tick().await;
let Some(outcome) = super::within_forge_deadline(
"review classifier forge token",
client.observe_classifier(),
)
.await
else {
continue;
};
match outcome {
Ok(seen) if needs_job(seen) => {
tracing::info!(?seen, "review classifier forge token: queueing a job");
enqueue();
}
Ok(seen) => tracing::debug!(?seen, "review classifier forge token: no job"),
Err(e) => tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"review classifier forge token: pass failed; retrying next tick"
),
}
}
});
}
#[cfg(test)]
mod tests {
use super::super::agent_token::MintReason;
use super::*;
#[test]
fn the_token_writes_repositories_and_nothing_else() {
assert_eq!(TOKEN_SCOPES, "write:repository");
assert_ne!(TOKEN_NAME, super::super::agent_token::AGENT_TOKEN_NAME);
assert_ne!(TOKEN_NAME, super::super::hive_token::HIVE_TOKEN_NAME);
}
#[test]
fn a_mint_or_a_missing_account_queues_and_nothing_else_does() {
assert!(needs_job(Observed::NoForgeUser));
assert!(needs_job(Observed::Decided(Decision::Mint(
MintReason::NotStored
))));
assert!(!needs_job(Observed::Decided(Decision::Keep)));
assert!(!needs_job(Observed::Decided(Decision::Conflict)));
assert!(!needs_job(Observed::Unknown));
}
#[test]
fn the_accounts_email_is_no_agents() {
assert_ne!(EMAIL, super::super::agent_email(LOGIN));
assert_ne!(EMAIL, super::super::legacy_agent_email(LOGIN));
}
/// An existing account named like the classifier with an agent's email
/// is refused before the lockdown, so no token is minted for it.
#[tokio::test]
async fn the_job_refuses_an_account_that_is_not_the_classifiers() {
use super::super::tests::{lockdown_patch, stub_forge};
let (client, seen) = stub_forge(
(409, r#"{"message":"user already exists"}"#),
(200, r#"{"email":"review-classifier@hyperhive.local"}"#),
(200, "{}"),
)
.await;
let err = client
.ensure_classifier_user()
.await
.expect_err("an agent's account is not the classifier's");
assert!(format!("{err:#}").contains("not the review classifier's"));
assert!(lockdown_patch(&seen, LOGIN).is_none());
}
/// The one request `push_branch` sends for `sha`, as a stand-in forge
/// saw it: method, path and JSON body.
async fn pushed(sha: Option<&str>) -> (String, String, serde_json::Value) {
use axum::http::{Method, StatusCode, Uri, header::CONTENT_TYPE};
let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
let recorded = Arc::clone(&seen);
let app = axum::Router::new().fallback(
move |method: Method, uri: Uri, body: axum::body::Bytes| {
let recorded = Arc::clone(&recorded);
async move {
recorded.lock().unwrap().push((
method.to_string(),
uri.path().to_owned(),
serde_json::from_slice(&body).unwrap_or_default(),
));
(
StatusCode::CREATED,
[(CONTENT_TYPE, "application/json")],
r#"{"commit":{"sha":"c1"}}"#,
)
}
},
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
tokio::spawn(async move { axum::serve(listener, app).await });
let forge = async_client(url, "stub-token").unwrap();
let commit = BranchCommit {
base: "main".to_owned(),
branch: "review-classifier/alice-0a1b2c3d".to_owned(),
path: ".hyperhive/review-classifier.yml".to_owned(),
sha: sha.map(str::to_owned),
content: b"classifications: []\n".to_vec(),
message: "review classifier: add no-ads".to_owned(),
author: CommitAuthor {
name: "Alice".to_owned(),
email: "alice@example.test".to_owned(),
},
};
push_branch(&forge, "o", "r", commit).await.expect("pushed");
let mut seen = seen.lock().unwrap();
assert_eq!(seen.len(), 1, "{seen:?}");
seen.remove(0)
}
#[tokio::test]
async fn a_push_is_one_commit_on_a_new_branch_authored_by_the_operator() {
let (method, path, body) = pushed(Some("b1")).await;
assert_eq!(method, "POST");
assert_eq!(path, "/api/v1/repos/o/r/contents");
assert_eq!(body["branch"], "main");
assert_eq!(body["new_branch"], "review-classifier/alice-0a1b2c3d");
assert_eq!(body["force_overwrite_new_branch"], false);
assert_eq!(body["message"], "review classifier: add no-ads");
assert_eq!(
body["author"],
serde_json::json!({ "name": "Alice", "email": "alice@example.test" })
);
assert_eq!(body["committer"], serde_json::Value::Null);
assert_eq!(
body["files"],
serde_json::json!([{
"operation": "update",
"path": ".hyperhive/review-classifier.yml",
"sha": "b1",
// base64 of "classifications: []\n"
"content": "Y2xhc3NpZmljYXRpb25zOiBbXQo=",
"from_path": null,
}])
);
}
#[tokio::test]
async fn a_push_without_a_blob_sha_creates_the_file() {
let (_, _, body) = pushed(None).await;
assert_eq!(body["files"][0]["operation"], "create");
assert_eq!(body["files"][0]["sha"], serde_json::Value::Null);
}
#[tokio::test]
async fn a_commit_author_is_the_accounts_name_at_its_noreply_address_or_none() {
use super::super::tests::stub_forge;
let (client, _) = stub_forge(
(404, "{}"),
(
200,
r#"{"login":"Alice","full_name":" Alice A ","email":"private@x.test"}"#,
),
(404, "{}"),
)
.await;
let domain = client.url.host_str().expect("a host").to_owned();
assert_eq!(
client.commit_author("alice").await.expect("read"),
Some(CommitAuthor {
name: "Alice A".to_owned(),
email: format!("alice@noreply.{domain}"),
})
);
let (client, _) = stub_forge(
(404, "{}"),
(200, r#"{"login":"bob","full_name":"","email":""}"#),
(404, "{}"),
)
.await;
let bob = client.commit_author("bob").await.expect("read");
assert_eq!(bob.map(|a| a.name).as_deref(), Some("bob"));
let (client, _) = stub_forge(
(404, "{}"),
(404, r#"{"message":"user does not exist"}"#),
(404, "{}"),
)
.await;
assert_eq!(client.commit_author("nobody").await.expect("read"), None);
}
#[test]
fn the_noreply_address_is_the_lowercased_login_at_noreply_dot_the_forge_host() {
let forge = url::Url::parse("https://Forge.Example:8443/").expect("a URL");
assert_eq!(
noreply_address(&forge, "Alice-B").expect("a host"),
"alice-b@noreply.forge.example"
);
}
#[tokio::test]
async fn the_job_locks_down_the_classifiers_own_account() {
use super::super::tests::{lockdown_patch, stub_forge};
let (client, seen) = stub_forge(
(409, r#"{"message":"user already exists"}"#),
(
200,
r#"{"email":"review-classifier@services.hyperhive.local"}"#,
),
(200, "{}"),
)
.await;
client
.ensure_classifier_user()
.await
.expect("the classifier's own account");
let body = lockdown_patch(&seen, LOGIN).expect("no lockdown PATCH sent");
assert_eq!(body["max_repo_creation"], 0);
assert_eq!(body["allow_create_organization"], false);
}
}

View file

@ -0,0 +1,484 @@
//! Each agent's read access to `internal/docs`: a collaborator grant at
//! **read**, made here with the admin API so it does not depend on which hive
//! the agent runs on or whether that hive has a forge container.
//!
//! Two callers insert the same `GrantDocsRead` job node: agent creation, and
//! [`spawn`]'s pass at start and every [`RECONCILE_INTERVAL`] over every
//! agent that holds a store identity. The pass reaches agents created before
//! this node existed and agents whose creation-time grant failed. It only ever
//! adds: nobody is removed, whatever the roster or the forge says. The
//! decision is pure ([`plan`]), so the tests pin it.
use std::sync::Arc;
use anyhow::{Context, Result};
use forgejo_api::structs::{AddCollaboratorOptionPermission, RepoCollaboratorPermission};
use swarm_secret_client::{client::DEFAULT_CERT_MOUNT, policy};
use super::Client;
use super::agent_token::is_not_found;
use super::objects::{SHARED_DOCS_REPO, SHARED_ORG};
/// How often [`spawn`] re-checks every agent.
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// What one pass found for one agent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Observed {
/// The agent is already a collaborator on `internal/docs`, at any level.
Granted,
/// The forge says the agent is not a collaborator, or has no such user —
/// the queued job creates the user before it grants.
Missing,
/// The read failed. Nothing is known, so nothing is done.
Unknown,
}
/// The agents a pass queues a grant for: those the forge says are not
/// collaborators. [`Observed::Unknown`] is never queued.
pub fn plan(observed: &[(String, Observed)]) -> Vec<String> {
observed
.iter()
.filter(|(_, o)| *o == Observed::Missing)
.map(|(agent, _)| agent.clone())
.collect()
}
/// Whether a permission read says the user already has read access or more.
fn holds_read(p: &RepoCollaboratorPermission) -> bool {
matches!(
p.permission.as_deref(),
Some("read" | "write" | "admin" | "owner")
)
}
impl Client {
/// Make `agent` a **read** collaborator on `internal/docs` — the whole job
/// of the `GrantDocsRead` node. Idempotent, and never lowers: see
/// [`Self::grant_read`]. Needs the forge user to exist.
pub async fn grant_docs_read(&self, agent: &str) -> Result<()> {
self.grant_read(SHARED_ORG, SHARED_DOCS_REPO, agent).await
}
/// Make `user` a **read** collaborator on `owner/repo` unless it already
/// holds read or more (write, admin, owner), which is left as it is: the
/// add endpoint would overwrite the permission, so adding at read would
/// lower a write grant an operator made.
pub(super) async fn grant_read(&self, owner: &str, repo: &str, user: &str) -> Result<()> {
match self
.api
.call(|api| {
api.repo_get_repo_permissions(owner, repo, user)
.into_future()
})
.await
{
Ok(p) if holds_read(&p) => return Ok(()),
Ok(_) => {}
Err(e) if is_not_found(&e) => {}
Err(e) => {
return Err(e)
.with_context(|| format!("read {user}'s permission on {owner}/{repo}"));
}
}
self.add_collaborator_to(owner, repo, user, AddCollaboratorOptionPermission::Read)
.await
}
/// Whether `agent` is a collaborator on `internal/docs` now.
async fn observe_grant(&self, agent: &str) -> Observed {
match self
.api
.call(|api| {
api.repo_check_collaborator(SHARED_ORG, SHARED_DOCS_REPO, agent)
.into_future()
})
.await
{
Ok(()) => Observed::Granted,
Err(e) if is_not_found(&e) => Observed::Missing,
Err(e) => {
tracing::warn!(agent, error = %e, "docs grant: forge read failed");
Observed::Unknown
}
}
}
/// Whether `internal/docs` exists now: `None` when the forge could not
/// say. A missing repo makes every collaborator check answer 404 too, so
/// it has to be told apart from "not a collaborator" before they run.
async fn docs_repo_exists(&self) -> Option<bool> {
match self
.api
.call(|api| api.repo_get(SHARED_ORG, SHARED_DOCS_REPO).into_future())
.await
{
Ok(_) => Some(true),
Err(e) if is_not_found(&e) => Some(false),
Err(e) => {
tracing::warn!(error = %e, "docs grants: forge read of the repo failed");
None
}
}
}
/// One pass over `roster`.
async fn observe_grants(&self, roster: &[String]) -> Vec<(String, Observed)> {
let mut observed = Vec::with_capacity(roster.len());
for agent in roster {
observed.push((agent.clone(), self.observe_grant(agent).await));
}
observed
}
}
/// The store's `hive-agent-*` cert-auth roles: exactly the agents that hold a
/// store identity.
pub(super) async fn read_roster() -> Result<Vec<String>> {
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let roles = store
.list_cert_roles(DEFAULT_CERT_MOUNT)
.await
.context("listing the store's cert-auth roles")?;
Ok(policy::agents_from_role_names(&roles))
}
/// One pass: observe every agent of `roster` and return the ones without a
/// grant. A roster that could not be read yields none and touches nothing; so
/// does a pass whose `internal/docs` is missing or unreadable, which is checked
/// once before any agent.
async fn run_pass(client: &Client, roster: Result<Vec<String>>) -> Vec<String> {
let roster = match roster {
Ok(roster) => roster,
Err(e) => {
tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"docs grants: no roster; retrying next tick"
);
return Vec::new();
}
};
match client.docs_repo_exists().await {
Some(true) => {}
Some(false) => {
tracing::warn!(
repo = format!("{SHARED_ORG}/{SHARED_DOCS_REPO}"),
"docs grants: repo missing; no grants queued"
);
return Vec::new();
}
None => return Vec::new(),
}
let observed = client.observe_grants(&roster).await;
let agents = plan(&observed);
if agents.is_empty() {
tracing::debug!(checked = observed.len(), "docs grants: all current");
} else {
tracing::info!(
checked = observed.len(),
queueing = agents.len(),
"docs grants: queueing grants"
);
}
agents
}
/// Check every agent now and every [`RECONCILE_INTERVAL`] after, and hand the
/// agents without a grant to `enqueue`, which inserts a `GrantDocsRead` node
/// for each. A pass that fails is logged and retried on the next tick; it
/// never stops the daemon.
pub fn spawn(client: Arc<Client>, enqueue: impl Fn(Vec<String>) + Send + 'static) {
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
loop {
ticker.tick().await;
let Some(agents) = super::within_forge_deadline("docs grants", async {
run_pass(&client, read_roster().await).await
})
.await
else {
continue;
};
if !agents.is_empty() {
enqueue(agents);
}
}
});
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::sync::Mutex;
use axum::extract::{Path, State};
use axum::http::{StatusCode, header::CONTENT_TYPE};
use super::*;
/// What a stand-in `internal/docs` holds: who is a collaborator, and the
/// request log.
#[derive(Default)]
struct Docs {
/// The repo does not exist: its own lookup and every collaborator
/// check answer 404.
repo_missing: bool,
collaborators: BTreeMap<String, String>,
requests: Vec<(String, String)>,
/// Answer every collaborator check with a 500.
broken: bool,
}
type Shared = Arc<Mutex<Docs>>;
/// A stand-in forge on a loopback port — never the real one — serving
/// the collaborator check (`GET`) and add (`PUT`) on `internal/docs`.
async fn stub_forge(collaborators: &[&str], broken: bool) -> (Client, Shared) {
serve(Docs {
collaborators: collaborators
.iter()
.map(|c| ((*c).to_owned(), "read".to_owned()))
.collect(),
broken,
..Docs::default()
})
.await
}
async fn serve(docs: Docs) -> (Client, Shared) {
let docs: Shared = Arc::new(Mutex::new(docs));
let app = axum::Router::new()
.route("/api/v1/repos/internal/docs", axum::routing::get(repo))
.route(
"/api/v1/repos/internal/docs/collaborators/{user}",
axum::routing::get(check).put(add),
)
.route(
"/api/v1/repos/internal/docs/collaborators/{user}/permission",
axum::routing::get(permission),
)
// An agent's own config repo is served by the same stand-in.
.route(
"/api/v1/repos/agent-configs/alice/collaborators/{user}",
axum::routing::get(check).put(add),
)
.route(
"/api/v1/repos/agent-configs/alice/collaborators/{user}/permission",
axum::routing::get(permission),
)
.with_state(Arc::clone(&docs));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
tokio::spawn(async move { axum::serve(listener, app).await });
let api = crate::forge::api::tests::fixed(url.clone(), "stub-token");
(Client { api, url }, docs)
}
async fn check(
State(docs): State<Shared>,
Path(user): Path<String>,
) -> (
StatusCode,
[(axum::http::HeaderName, &'static str); 1],
&'static str,
) {
let mut docs = docs.lock().unwrap();
docs.requests.push(("GET".to_owned(), user.clone()));
let status = if docs.repo_missing {
StatusCode::NOT_FOUND
} else if docs.broken {
StatusCode::INTERNAL_SERVER_ERROR
} else if docs.collaborators.contains_key(&user) {
StatusCode::NO_CONTENT
} else {
StatusCode::NOT_FOUND
};
(status, [(CONTENT_TYPE, "application/json")], "{}")
}
async fn repo(
State(docs): State<Shared>,
) -> (
StatusCode,
[(axum::http::HeaderName, &'static str); 1],
&'static str,
) {
let mut docs = docs.lock().unwrap();
docs.requests.push(("GET".to_owned(), "repo".to_owned()));
let status = if docs.repo_missing {
StatusCode::NOT_FOUND
} else {
StatusCode::OK
};
(status, [(CONTENT_TYPE, "application/json")], "{}")
}
async fn permission(State(docs): State<Shared>, Path(user): Path<String>) -> String {
let mut docs = docs.lock().unwrap();
docs.requests
.push(("GET".to_owned(), format!("{user} permission")));
let level = docs.collaborators.get(&user).map_or("none", String::as_str);
format!(r#"{{"permission":"{level}"}}"#)
}
async fn add(State(docs): State<Shared>, Path(user): Path<String>, body: String) -> StatusCode {
let mut docs = docs.lock().unwrap();
docs.requests
.push(("PUT".to_owned(), format!("{user} {body}")));
docs.collaborators.insert(user, "read".to_owned());
StatusCode::NO_CONTENT
}
fn roster(agents: &[&str]) -> Vec<String> {
agents.iter().map(|a| (*a).to_owned()).collect()
}
fn puts(docs: &Shared) -> Vec<String> {
docs.lock()
.unwrap()
.requests
.iter()
.filter(|(m, _)| m == "PUT")
.map(|(_, what)| what.clone())
.collect()
}
#[test]
fn only_a_missing_grant_is_planned() {
let observed = [
("a".to_owned(), Observed::Granted),
("b".to_owned(), Observed::Missing),
("c".to_owned(), Observed::Unknown),
];
assert_eq!(plan(&observed), ["b"]);
}
/// The `GrantDocsRead` node's work: a **read** collaborator on
/// `internal/docs`, not write.
#[tokio::test]
async fn the_grant_adds_the_agent_as_a_read_collaborator() {
let (client, docs) = stub_forge(&[], false).await;
client.grant_docs_read("alice").await.unwrap();
let sent = puts(&docs);
assert_eq!(sent.len(), 1, "{sent:?}");
let (user, body) = sent[0].split_once(' ').unwrap();
assert_eq!(user, "alice");
let body: serde_json::Value = serde_json::from_str(body).unwrap();
assert_eq!(body["permission"], "read");
}
/// The backfill queues the agents that lack the grant, and only those.
#[tokio::test]
async fn the_pass_queues_the_agents_missing_the_grant() {
let (client, docs) = stub_forge(&["bob"], false).await;
let queued = run_pass(&client, Ok(roster(&["alice", "bob", "carol"]))).await;
assert_eq!(queued, ["alice", "carol"]);
assert!(puts(&docs).is_empty(), "the pass itself only reads");
}
/// Once every agent holds the grant a pass queues nothing, and writes
/// nothing — in particular it does not re-add a collaborator that holds a
/// higher permission.
#[tokio::test]
async fn the_pass_is_a_no_op_for_agents_already_granted() {
let (client, docs) = stub_forge(&["alice", "bob"], false).await;
let queued = run_pass(&client, Ok(roster(&["alice", "bob"]))).await;
assert!(queued.is_empty());
assert!(puts(&docs).is_empty());
}
/// A roster that could not be read changes nothing: no grant queued, no
/// request to the forge at all.
#[tokio::test]
async fn an_unreadable_roster_changes_nothing() {
let (client, docs) = stub_forge(&["alice"], false).await;
let queued = run_pass(&client, Err(anyhow::anyhow!("store is down"))).await;
assert!(queued.is_empty());
assert!(docs.lock().unwrap().requests.is_empty());
}
/// A forge that cannot answer the check is not a forge that says "not a
/// collaborator": nothing is queued.
#[tokio::test]
async fn an_unreadable_forge_queues_nothing() {
let (client, docs) = stub_forge(&[], true).await;
let queued = run_pass(&client, Ok(roster(&["alice"]))).await;
assert!(queued.is_empty());
assert!(puts(&docs).is_empty());
}
/// A missing `internal/docs` answers 404 to every collaborator check, which
/// would read as "not a collaborator" for every agent: nothing is queued,
/// and the agents are not asked about one by one.
#[tokio::test]
async fn a_missing_repo_queues_nothing() {
let (client, docs) = serve(Docs {
repo_missing: true,
..Docs::default()
})
.await;
let queued = run_pass(&client, Ok(roster(&["alice", "bob"]))).await;
assert!(queued.is_empty());
let requests = docs.lock().unwrap().requests.clone();
assert_eq!(requests, [("GET".to_owned(), "repo".to_owned())]);
}
/// An agent an operator already raised above read keeps it: the node reads
/// the permission first and sends no write.
#[tokio::test]
async fn the_grant_leaves_a_higher_permission_alone() {
let (client, docs) = serve(Docs {
collaborators: BTreeMap::from([("alice".to_owned(), "write".to_owned())]),
..Docs::default()
})
.await;
client.grant_docs_read("alice").await.unwrap();
assert!(puts(&docs).is_empty(), "{:?}", puts(&docs));
assert_eq!(docs.lock().unwrap().collaborators["alice"], "write");
}
/// An agent's grant on its own config repo is **read**: the `AddRepoMember`
/// node's work, not write.
#[tokio::test]
async fn the_config_repo_grant_adds_the_agent_as_a_read_collaborator() {
let (client, docs) = stub_forge(&[], false).await;
client.add_repo_member("alice", "alice").await.unwrap();
let sent = puts(&docs);
assert_eq!(sent.len(), 1, "{sent:?}");
let (user, body) = sent[0].split_once(' ').unwrap();
assert_eq!(user, "alice");
let body: serde_json::Value = serde_json::from_str(body).unwrap();
assert_eq!(body["permission"], "read");
}
/// A write grant an operator made on the agent's config repo survives the
/// node running again: the node reads the permission first and sends
/// nothing. This is the condition the change was approved on.
#[tokio::test]
async fn the_config_repo_grant_leaves_a_write_an_operator_made_alone() {
let (client, docs) = serve(Docs {
collaborators: BTreeMap::from([("alice".to_owned(), "write".to_owned())]),
..Docs::default()
})
.await;
client.add_repo_member("alice", "alice").await.unwrap();
assert!(puts(&docs).is_empty(), "{:?}", puts(&docs));
assert_eq!(docs.lock().unwrap().collaborators["alice"], "write");
}
}

View file

@ -0,0 +1,692 @@
//! Cutting a removed hive's credentials off at the forge and the store.
//!
//! A hive dropped from `swarm.hives` keeps everything the controller gave it:
//! the forge token (read on every config repo), the seat in the
//! `agent-configs/hives` team, the token secret, the OIDC client secret and the
//! cert-auth role it logs in to the store under. [`cut_off_removed`] ends each,
//! for every hive that holds one of them and is not in the roster, in this
//! order:
//!
//! 1. the hive's `swarm-hive` forge token is deleted,
//! 2. its account leaves the `hives` team,
//! 3. the token secret at `swarm/hives/<hive>/forge/token` is deleted,
//! 4. the OIDC client secret at `swarm/hives/<hive>/oidc/client` is deleted,
//! 5. the cert-auth role `hive-<hive>` is deleted.
//!
//! The role goes last because it marks that work is left: a failure above it
//! leaves the role, and the next pass runs every step again. The forge account
//! stays, so a hive put back in the roster gets its token and seat from
//! [`super::hive_token`]'s pass and its role from the store access at boot.
//!
//! Nothing is cut off from a roster that did not load or that holds no hive
//! (`startup::HiveRoster::absence_means_removal`): an unreadable roster would
//! otherwise read as every hive removed. A forge account counts as a hive's
//! only with the hive email (`is_hive_account`), and a role only with the
//! `hive-` prefix and not the agents' `hive-agent-` one.
//!
//! The grants are the `auth/cert/certs/hive-*` stanza and the
//! `metadata/swarm/hives/+/forge/token` and `.../oidc/client` deletes of
//! `swarm-bao.nix`'s `controllerPolicyText`. The OIDC step reads nothing: its
//! delete is the same for a secret that is not there, so it runs every pass.
use std::collections::BTreeSet;
use std::future::Future;
use anyhow::{Context, Result};
use forgejo_api::structs::AdminSearchUsersQuery;
use swarm_secret_client::{SecretStore, client::DEFAULT_CERT_MOUNT, forge, policy, queue};
use super::agent_token::is_not_found;
use super::hive_token::{HIVE_TOKEN_NAME, HIVES_TEAM, TeamSeen, is_hive_account};
use super::{CONFIG_ORG, Client};
/// Accounts read per page of the forge's user listing.
const USER_PAGE: u32 = 50;
/// A forge account as the user listing shows it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Account {
pub login: String,
pub email: Option<String>,
}
/// What one cut-off removed from one hive, by name, in the order of the steps.
pub type Removed = Vec<&'static str>;
/// The hives to cut off: those with a hive account on the forge or a
/// cert-auth role in `roles`, and not in `roster`.
///
/// Empty for an empty `roster`, whatever the forge and the store hold.
pub fn removed_hives(
roster: &[String],
accounts: &[Account],
roles: &[String],
) -> BTreeSet<String> {
if roster.is_empty() {
return BTreeSet::new();
}
let from_accounts = accounts
.iter()
.filter_map(|a| {
let hive = policy::hive_from_object_name(&a.login)?;
is_hive_account(hive, a.email.as_deref()).then(|| hive.to_owned())
})
.collect::<Vec<_>>();
from_accounts
.into_iter()
.chain(policy::hives_from_role_names(roles))
.filter(|hive| !roster.contains(hive))
.collect()
}
/// What a cut-off reads and removes. [`Live`] is the forge and the store;
/// tests stand in with a record of the calls.
pub trait Revoke {
/// Every forge account.
fn accounts(&self) -> impl Future<Output = Result<Vec<Account>>> + Send;
/// Every cert-auth role name.
fn roles(&self) -> impl Future<Output = Result<Vec<String>>> + Send;
/// Delete `hive`'s [`HIVE_TOKEN_NAME`] forge token; whether there was one.
fn delete_token(&self, hive: &str) -> impl Future<Output = Result<bool>> + Send;
/// Take `hive`'s account out of the `hives` team; whether it was in.
fn remove_team_seat(&self, hive: &str) -> impl Future<Output = Result<bool>> + Send;
/// Delete the secret holding `hive`'s forge token; whether there was one.
fn delete_token_secret(&self, hive: &str) -> impl Future<Output = Result<bool>> + Send;
/// Delete the secret holding `hive`'s OIDC client secret; safe when there is
/// none.
fn delete_oidc_secret(&self, hive: &str) -> impl Future<Output = Result<()>> + Send;
/// Delete the cert-auth role `hive-<hive>`; safe when there is none.
fn delete_role(&self, hive: &str) -> impl Future<Output = Result<()>> + Send;
}
/// Run the five steps for `hive`, in order, stopping at the first that fails.
///
/// `has_role` is whether the role listing named it, which is what makes the
/// role count as removed.
///
/// # Errors
/// The first failing step, with its name. Steps after it did not run, and the
/// role is still there.
pub async fn cut_off(revoke: &impl Revoke, hive: &str, has_role: bool) -> Result<Removed> {
let mut removed = Removed::new();
if revoke
.delete_token(hive)
.await
.context("deleting the forge token")?
{
removed.push("forge token");
}
if revoke
.remove_team_seat(hive)
.await
.context("removing the team seat")?
{
removed.push("team seat");
}
if revoke
.delete_token_secret(hive)
.await
.context("deleting the token secret")?
{
removed.push("token secret");
}
revoke
.delete_oidc_secret(hive)
.await
.context("deleting the OIDC client secret")?;
revoke
.delete_role(hive)
.await
.context("deleting the cert-auth role")?;
if has_role {
removed.push("login role");
}
Ok(removed)
}
/// [`cut_off`] every hive [`removed_hives`] names for `roster`, logging one
/// line per hive. A hive that fails is retried by the next pass.
pub async fn cut_off_removed(revoke: &impl Revoke, roster: &[String]) {
if roster.is_empty() {
tracing::error!("hive cut-off: the roster is empty; nothing is cut off");
return;
}
let accounts = revoke.accounts().await.unwrap_or_else(|e| {
tracing::warn!(error = %format!("{e:#}"), "hive cut-off: listing the forge accounts failed");
Vec::new()
});
let roles = revoke.roles().await.unwrap_or_else(|e| {
tracing::warn!(error = %format!("{e:#}"), "hive cut-off: listing the cert-auth roles failed");
Vec::new()
});
let with_role = policy::hives_from_role_names(&roles);
for hive in removed_hives(roster, &accounts, &roles) {
match cut_off(revoke, &hive, with_role.contains(&hive)).await {
Ok(removed) if !removed.is_empty() => tracing::info!(
hive,
removed = %removed.join(", "),
"hive is not in the roster: its credentials are revoked"
),
Ok(_) => tracing::debug!(
hive,
"hive is not in the roster and holds nothing to revoke"
),
Err(e) => tracing::warn!(
hive,
error = %format!("{e:#}"),
"hive is not in the roster: revoking its credentials failed; retried on the next pass"
),
}
}
}
/// The forge and the store as one [`Revoke`].
pub struct Live<'a> {
pub client: &'a Client,
pub store: &'a SecretStore,
}
impl Client {
/// Whether the forge account `hive-<hive>` exists and is the hive's.
/// An account by that name that is not (another email) is left alone.
async fn has_hive_account(&self, hive: &str) -> Result<bool> {
let login = forge::hive_login(hive);
match self
.api
.call(|api| api.user_get(&login).into_future())
.await
{
Ok(user) if is_hive_account(hive, user.email.as_deref()) => Ok(true),
Ok(user) => {
tracing::warn!(
hive,
email = ?user.email,
"forge account {login} is not the hive's; left alone"
);
Ok(false)
}
Err(e) if is_not_found(&e) => Ok(false),
Err(e) => Err(e).with_context(|| format!("reading forge user {login}")),
}
}
/// Every forge account, a page at a time.
async fn all_accounts(&self) -> Result<Vec<Account>> {
let mut accounts = Vec::new();
let mut page = 1;
loop {
let (_, users) = self
.api
.call(|api| {
api.admin_search_users(AdminSearchUsersQuery::default())
.page(page)
.page_size(USER_PAGE)
.into_future()
})
.await
.context("listing the forge's users")?;
let last = users.len() < USER_PAGE as usize;
accounts.extend(users.into_iter().filter_map(|u| {
Some(Account {
login: u.login?,
email: u.email,
})
}));
if last {
return Ok(accounts);
}
page += 1;
}
}
/// Delete the [`HIVE_TOKEN_NAME`] token of the hive's account, if the
/// account is the hive's and holds one.
async fn delete_hive_forge_token(&self, hive: &str) -> Result<bool> {
if !self.has_hive_account(hive).await? {
return Ok(false);
}
let login = forge::hive_login(hive);
let held = self.list_agent_tokens(&login).await?.is_some_and(|tokens| {
tokens
.iter()
.any(|t| t.name.as_deref() == Some(HIVE_TOKEN_NAME))
});
if !held {
return Ok(false);
}
match self
.api
.call(|api| {
api.admin_delete_user_access_token(&login, HIVE_TOKEN_NAME)
.into_future()
})
.await
{
Ok(()) => Ok(true),
Err(e) if is_not_found(&e) => Ok(false),
Err(e) => Err(e).with_context(|| format!("deleting {login}'s {HIVE_TOKEN_NAME} token")),
}
}
/// Take the hive's account out of [`HIVES_TEAM`], if the account is the
/// hive's and is a member.
async fn remove_hive_team_seat(&self, hive: &str) -> Result<bool> {
if !self.has_hive_account(hive).await? {
return Ok(false);
}
let login = forge::hive_login(hive);
let team = match self.observe_hives_team().await {
TeamSeen::Matches(id) | TeamSeen::Drifted(id) => id,
TeamSeen::Absent => return Ok(false),
TeamSeen::Unknown => {
anyhow::bail!("could not read the teams of {CONFIG_ORG}")
}
};
match self
.api
.call(|api| api.org_list_team_member(team, &login).into_future())
.await
{
Ok(_) => {}
Err(e) if is_not_found(&e) => return Ok(false),
Err(e) => {
return Err(e).with_context(|| format!("reading {login}'s team membership"));
}
}
match self
.api
.call(|api| api.org_remove_team_member(team, &login).into_future())
.await
{
Ok(()) => Ok(true),
Err(e) if is_not_found(&e) => Ok(false),
Err(e) => {
Err(e).with_context(|| format!("removing {login} from {CONFIG_ORG}/{HIVES_TEAM}"))
}
}
}
}
impl Revoke for Live<'_> {
async fn accounts(&self) -> Result<Vec<Account>> {
self.client.all_accounts().await
}
async fn roles(&self) -> Result<Vec<String>> {
Ok(self.store.list_cert_roles(DEFAULT_CERT_MOUNT).await?)
}
async fn delete_token(&self, hive: &str) -> Result<bool> {
self.client.delete_hive_forge_token(hive).await
}
async fn remove_team_seat(&self, hive: &str) -> Result<bool> {
self.client.remove_hive_team_seat(hive).await
}
async fn delete_token_secret(&self, hive: &str) -> Result<bool> {
let path = forge::hive_token_path(hive)?;
let held = self
.store
.read_optional::<serde_json::Value>(&path)
.await
.with_context(|| format!("reading {path}"))?
.is_some();
if held {
self.store
.delete_all_versions(&path)
.await
.with_context(|| format!("deleting {path}"))?;
}
Ok(held)
}
async fn delete_oidc_secret(&self, hive: &str) -> Result<()> {
let path = queue::hive_client_path(hive)?;
self.store
.delete_all_versions(&path)
.await
.with_context(|| format!("deleting {path}"))
}
async fn delete_role(&self, hive: &str) -> Result<()> {
let role = policy::hive_object_name(hive)?;
self.store
.delete_cert_role(DEFAULT_CERT_MOUNT, &role)
.await
.with_context(|| format!("deleting {role}"))
}
}
/// One pass: log in to the store and [`cut_off_removed`] against `roster`.
pub async fn run(client: &Client, roster: &[String]) {
let store = match crate::store::connect().await {
Ok(store) => store,
Err(e) => {
tracing::warn!(error = %format!("{e:#}"), "hive cut-off: logging in to the store failed");
return;
}
};
cut_off_removed(
&Live {
client,
store: &store,
},
roster,
)
.await;
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use super::super::agent_token::{Decision, MintReason, Observed, classify_named};
use super::super::hive_token::{HIVE_TOKEN_SCOPES, HiveSeen, plan};
use super::*;
fn roster(names: &[&str]) -> Vec<String> {
names.iter().map(|n| (*n).to_owned()).collect()
}
fn account(hive: &str) -> Account {
Account {
login: format!("hive-{hive}"),
email: Some(format!("hive-{hive}@hives.hyperhive.local")),
}
}
/// What the forge and the store hold for the hives it was built with, and a
/// record of every call.
#[derive(Default)]
struct Fake {
state: Mutex<State>,
/// The step that fails, as its [`Revoke`] method name.
failing: Option<&'static str>,
accounts: Vec<Account>,
}
#[derive(Default)]
struct State {
token: BTreeSet<String>,
seat: BTreeSet<String>,
secret: BTreeSet<String>,
oidc: BTreeSet<String>,
role: BTreeSet<String>,
calls: Vec<String>,
}
impl Fake {
/// A hive holding all four credentials, and a forge account.
fn holding(hives: &[&str]) -> Self {
let fake = Self {
accounts: hives.iter().map(|h| account(h)).collect(),
..Self::default()
};
{
let mut s = fake.state.lock().unwrap();
for h in hives {
s.token.insert((*h).to_owned());
s.seat.insert((*h).to_owned());
s.secret.insert((*h).to_owned());
s.oidc.insert((*h).to_owned());
s.role.insert(format!("hive-{h}"));
}
}
fake
}
fn failing(mut self, step: &'static str) -> Self {
self.failing = Some(step);
self
}
fn calls(&self) -> Vec<String> {
self.state.lock().unwrap().calls.clone()
}
fn holds(&self, hive: &str) -> [bool; 5] {
let s = self.state.lock().unwrap();
[
s.token.contains(hive),
s.seat.contains(hive),
s.secret.contains(hive),
s.oidc.contains(hive),
s.role.contains(&format!("hive-{hive}")),
]
}
fn step(&self, name: &'static str, hive: &str) -> Result<()> {
self.state
.lock()
.unwrap()
.calls
.push(format!("{name} {hive}"));
if self.failing == Some(name) {
anyhow::bail!("{name} refused");
}
Ok(())
}
}
impl Revoke for Fake {
async fn accounts(&self) -> Result<Vec<Account>> {
Ok(self.accounts.clone())
}
async fn roles(&self) -> Result<Vec<String>> {
Ok(self.state.lock().unwrap().role.iter().cloned().collect())
}
async fn delete_token(&self, hive: &str) -> Result<bool> {
self.step("delete_token", hive)?;
Ok(self.state.lock().unwrap().token.remove(hive))
}
async fn remove_team_seat(&self, hive: &str) -> Result<bool> {
self.step("remove_team_seat", hive)?;
Ok(self.state.lock().unwrap().seat.remove(hive))
}
async fn delete_token_secret(&self, hive: &str) -> Result<bool> {
self.step("delete_token_secret", hive)?;
Ok(self.state.lock().unwrap().secret.remove(hive))
}
async fn delete_oidc_secret(&self, hive: &str) -> Result<()> {
self.step("delete_oidc_secret", hive)?;
self.state.lock().unwrap().oidc.remove(hive);
Ok(())
}
async fn delete_role(&self, hive: &str) -> Result<()> {
self.step("delete_role", hive)?;
self.state
.lock()
.unwrap()
.role
.remove(&format!("hive-{hive}"));
Ok(())
}
}
#[test]
fn a_hive_outside_the_roster_with_an_account_or_a_role_is_a_target() {
let accounts = [account("gone"), account("kept")];
let roles = ["hive-kept".to_owned(), "hive-orphan".to_owned()];
assert_eq!(
removed_hives(&roster(&["kept"]), &accounts, &roles),
BTreeSet::from(["gone".to_owned(), "orphan".to_owned()])
);
// The control: with `gone` and `orphan` in the roster too, nothing is.
assert!(removed_hives(&roster(&["kept", "gone", "orphan"]), &accounts, &roles).is_empty());
}
#[test]
fn an_agents_role_or_account_is_never_a_hive_target() {
let agent_account = Account {
login: "hive-x".to_owned(),
email: Some("hive-x@hyperhive.local".to_owned()),
};
let no_email = Account {
login: "hive-y".to_owned(),
email: None,
};
let roles = [
"hive-agent-atlas".to_owned(),
"swarm-controller".to_owned(),
"hive-agent-".to_owned(),
];
assert!(
removed_hives(
&roster(&["kept"]),
&[agent_account, no_email, account("ok")],
&roles
)
.iter()
.eq(["ok"]),
"only the account with the hive email counts"
);
}
#[tokio::test]
async fn a_removed_hive_loses_its_token_seat_secrets_and_role_in_that_order() {
let fake = Fake::holding(&["gone", "kept"]);
cut_off_removed(&fake, &roster(&["kept"])).await;
assert_eq!(fake.holds("gone"), [false; 5], "{:?}", fake.calls());
assert_eq!(
fake.calls(),
[
"delete_token gone",
"remove_team_seat gone",
"delete_token_secret gone",
"delete_oidc_secret gone",
"delete_role gone",
]
);
}
/// The OIDC client secret goes with the rest, and a roster hive keeps its own.
#[tokio::test]
async fn a_removed_hives_oidc_client_secret_is_deleted_and_a_roster_hives_is_not() {
let fake = Fake::holding(&["gone", "kept"]);
cut_off_removed(&fake, &roster(&["kept"])).await;
assert!(!fake.state.lock().unwrap().oidc.contains("gone"));
assert!(fake.state.lock().unwrap().oidc.contains("kept"));
assert!(
fake.calls().contains(&"delete_oidc_secret gone".to_owned()),
"{:?}",
fake.calls()
);
}
/// A hive that never had an OIDC secret is cut off all the same.
#[tokio::test]
async fn a_hive_with_no_oidc_client_secret_is_cut_off_without_error() {
let fake = Fake::holding(&["gone"]);
fake.state.lock().unwrap().oidc.clear();
cut_off_removed(&fake, &roster(&["kept"])).await;
assert_eq!(fake.holds("gone"), [false; 5], "{:?}", fake.calls());
}
#[tokio::test]
async fn a_hive_in_the_roster_is_untouched() {
let fake = Fake::holding(&["gone", "kept"]);
cut_off_removed(&fake, &roster(&["kept"])).await;
assert_eq!(fake.holds("kept"), [true; 5], "{:?}", fake.calls());
assert!(fake.calls().iter().all(|c| !c.ends_with("kept")));
// The control: the same pass did cut the removed one.
assert_eq!(fake.holds("gone"), [false; 5]);
}
#[tokio::test]
async fn an_empty_roster_cuts_nothing_off() {
let fake = Fake::holding(&["a", "b"]);
cut_off_removed(&fake, &[]).await;
assert_eq!(fake.holds("a"), [true; 5]);
assert_eq!(fake.holds("b"), [true; 5]);
assert!(fake.calls().is_empty(), "{:?}", fake.calls());
// The control: a roster that names another hive cuts both.
cut_off_removed(&fake, &roster(&["c"])).await;
assert_eq!(fake.holds("a"), [false; 5]);
assert_eq!(fake.holds("b"), [false; 5]);
}
#[tokio::test]
async fn an_agents_role_is_not_deleted() {
let fake = Fake::holding(&["gone"]);
fake.state
.lock()
.unwrap()
.role
.insert("hive-agent-atlas".to_owned());
cut_off_removed(&fake, &roster(&["kept"])).await;
assert!(fake.state.lock().unwrap().role.contains("hive-agent-atlas"));
assert!(
fake.calls().iter().all(|c| !c.contains("atlas")),
"{:?}",
fake.calls()
);
// The control: the hive's own role went.
assert!(!fake.state.lock().unwrap().role.contains("hive-gone"));
}
#[tokio::test]
async fn a_failed_step_stops_the_rest_and_keeps_the_role_for_the_next_pass() {
for (step, left) in [
("delete_token", [true, true, true, true, true]),
("remove_team_seat", [false, true, true, true, true]),
("delete_token_secret", [false, false, true, true, true]),
("delete_oidc_secret", [false, false, false, true, true]),
("delete_role", [false, false, false, false, true]),
] {
let broken = Fake::holding(&["gone"]).failing(step);
cut_off_removed(&broken, &roster(&["kept"])).await;
assert_eq!(broken.holds("gone"), left, "{step}: {:?}", broken.calls());
assert!(
broken.holds("gone")[4],
"{step}: the role is the marker that work is left"
);
// The next pass, against a store and a forge that now accept it.
let healthy = Fake {
state: Mutex::new(std::mem::take(&mut *broken.state.lock().unwrap())),
accounts: broken.accounts.clone(),
failing: None,
};
cut_off_removed(&healthy, &roster(&["kept"])).await;
assert_eq!(healthy.holds("gone"), [false; 5], "{step}");
}
}
#[tokio::test]
async fn a_second_pass_finds_nothing_left_to_remove() {
let fake = Fake::holding(&["gone"]);
let first = cut_off(&fake, "gone", true).await.expect("first");
assert_eq!(
first,
["forge token", "team seat", "token secret", "login role"]
);
let again = cut_off(&fake, "gone", false).await.expect("second");
assert!(again.is_empty(), "{again:?}");
}
#[tokio::test]
async fn a_hive_put_back_in_the_roster_is_minted_again() {
let fake = Fake::holding(&["back"]);
cut_off_removed(&fake, &roster(&["kept"])).await;
// What hive_token's pass reads of the cut-off hive: no stored token,
// none listed, not in the team. The account is still there.
let token = classify_named(HIVE_TOKEN_NAME, HIVE_TOKEN_SCOPES, None, &[]);
assert_eq!(token, Decision::Mint(MintReason::NotOnForge));
let seen = HiveSeen {
token: Observed::Decided(token),
member: Some(fake.holds("back")[1]),
};
assert_eq!(
plan(TeamSeen::Matches(7), &[("back".to_owned(), seen)]),
["back"]
);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,324 @@
//! Deletes the `hyperhive-<unix-seconds>` access tokens `hive-c0re` used to
//! mint for agents on every spawn and rebuild, each one live on the forge
//! with write scopes.
//!
//! Two filters decide what goes, and both must pass:
//!
//! - **Whose tokens.** Only agents on the store's `hive-agent-*` roster, the
//! one [`super::agent_token`]'s pass walks, and only those whose
//! [`super::agent_token::AGENT_TOKEN_NAME`] token that pass would
//! [`Decision::Keep`]: until the replacement is stored and live, the agent
//! may still be reading its last `hyperhive-*` token from
//! `<state>/forge-token`. [`CORE_USER`] is refused by name at every step.
//! `hive-c0re` still names `core`'s live admin token
//! `hyperhive-<unix-seconds>`, so nothing about the token tells them apart.
//! - **Which tokens.** A name that is exactly `hyperhive-` followed by one or
//! more ASCII digits ([`is_legacy_token_name`]).
//! [`super::agent_token::AGENT_TOKEN_NAME`] cannot match.
//!
//! Runs from [`super::agent_token::spawn`]'s periodic pass, off the same
//! roster observation, so a boot where that pass's first tick fails (the
//! store or forge unreachable) retries the sweep on the next tick instead of
//! leaving the tokens live until a restart. A failed read or delete is
//! logged and skipped; a re-run with nothing left to remove deletes nothing.
use anyhow::Result;
use super::Client;
use super::agent_token::{Decision, Observed};
/// The forge user `hive-c0re` runs as. Its admin token carries a legacy-shaped
/// name and is in use.
pub const CORE_USER: &str = "core";
/// The prefix `hive-c0re`'s `mint_token` put before the unix seconds.
const LEGACY_TOKEN_PREFIX: &str = "hyperhive-";
/// Whether `name` is exactly `hyperhive-<digits>`, the shape of every token
/// `hive-c0re` minted.
pub fn is_legacy_token_name(name: &str) -> bool {
name.strip_prefix(LEGACY_TOKEN_PREFIX)
.is_some_and(|secs| !secs.is_empty() && secs.bytes().all(|b| b.is_ascii_digit()))
}
/// The agents a sweep may touch: those whose
/// [`super::agent_token::AGENT_TOKEN_NAME`] token is current, never
/// [`CORE_USER`].
pub fn sweepable(observed: &[(String, Observed)]) -> Vec<String> {
observed
.iter()
.filter(|(agent, o)| agent != CORE_USER && *o == Observed::Decided(Decision::Keep))
.map(|(agent, _)| agent.clone())
.collect()
}
impl Client {
/// Delete every legacy token the forge lists for `user`, and return how
/// many went. A delete the forge refuses is logged and skipped.
async fn sweep_user(&self, user: &str) -> Result<usize> {
if user == CORE_USER {
return Ok(0);
}
let Some(listed) = self.list_agent_tokens(user).await? else {
return Ok(0);
};
let mut removed = 0;
for name in listed
.iter()
.filter_map(|t| t.name.as_deref())
.filter(|n| is_legacy_token_name(n))
{
match self
.api
.call(|api| api.admin_delete_user_access_token(user, name).into_future())
.await
{
Ok(()) => removed += 1,
Err(e) if super::agent_token::is_not_found(&e) => {}
Err(e) => tracing::warn!(
agent = user,
token = name,
error = %e,
"legacy forge token sweep: delete failed; skipped"
),
}
}
Ok(removed)
}
/// Sweep each of `agents` and log what went, per agent and in total.
/// Returns the total.
pub(super) async fn sweep_legacy_tokens(&self, agents: &[String]) -> usize {
let mut total = 0;
for agent in agents {
match self.sweep_user(agent).await {
Ok(removed) => {
tracing::info!(agent, removed, "legacy forge token sweep: agent done");
total += removed;
}
Err(e) => tracing::warn!(
agent,
error = %format!("{e:#}"),
"legacy forge token sweep: listing failed; agent skipped"
),
}
}
tracing::info!(
agents = agents.len(),
removed = total,
"legacy forge token sweep: done"
);
total
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use super::super::agent_token::{AGENT_TOKEN_NAME, MintReason};
use super::*;
#[test]
fn only_hyperhive_digits_is_legacy() {
for name in ["hyperhive-1", "hyperhive-1700000000"] {
assert!(is_legacy_token_name(name), "{name}");
}
for name in [
AGENT_TOKEN_NAME,
"hyperhive",
"hyperhive-",
"hyperhive-abc",
"hyperhive-123abc",
"hyperhive-12 3",
"hyperhive-+123",
"xhyperhive-123",
"hyperhive-123-x",
"swarm-controller-boot-1700000000",
] {
assert!(!is_legacy_token_name(name), "{name}");
}
}
#[test]
fn only_current_non_core_agents_are_sweepable() {
let observed = [
("a".to_owned(), Observed::Decided(Decision::Keep)),
(CORE_USER.to_owned(), Observed::Decided(Decision::Keep)),
(
"b".to_owned(),
Observed::Decided(Decision::Mint(MintReason::NotOnForge)),
),
("c".to_owned(), Observed::Unknown),
("d".to_owned(), Observed::NoForgeUser),
("e".to_owned(), Observed::Decided(Decision::Conflict)),
("f".to_owned(), Observed::Decided(Decision::Keep)),
];
assert_eq!(sweepable(&observed), ["a", "f"]);
}
/// Each user's token names, as the stub forge holds them.
type Tokens = Arc<Mutex<BTreeMap<String, Vec<String>>>>;
/// Every `DELETE` the stub forge was sent, as `(user, token)`.
type Deletes = Arc<Mutex<Vec<(String, String)>>>;
/// A stand-in forge on a loopback port answering the admin token list and
/// delete from `tokens`. A delete of `fail` answers 500 and removes
/// nothing.
async fn stub_forge(tokens: Tokens, fail: (&'static str, &'static str)) -> (Client, Deletes) {
use axum::http::{Method, StatusCode, Uri, header::CONTENT_TYPE};
let deletes = Deletes::default();
let recorded = deletes.clone();
let app = axum::Router::new().fallback(move |method: Method, uri: Uri| {
let tokens = tokens.clone();
let recorded = recorded.clone();
async move {
let parts: Vec<&str> = uri.path().trim_matches('/').split('/').collect();
let (status, body) = match (method, parts.as_slice()) {
(Method::GET, ["api", "v1", "admin", "users", user, "tokens"]) => {
match tokens.lock().unwrap().get(*user) {
Some(held) => {
let list: Vec<serde_json::Value> = held
.iter()
.enumerate()
.map(|(i, name)| serde_json::json!({ "id": i, "name": name }))
.collect();
(StatusCode::OK, serde_json::Value::from(list))
}
None => (
StatusCode::NOT_FOUND,
serde_json::json!({ "message": "user does not exist" }),
),
}
}
(Method::DELETE, ["api", "v1", "admin", "users", user, "tokens", token]) => {
recorded
.lock()
.unwrap()
.push(((*user).to_owned(), (*token).to_owned()));
if (*user, *token) == fail {
(StatusCode::INTERNAL_SERVER_ERROR, serde_json::json!({}))
} else {
let mut all = tokens.lock().unwrap();
let held = all.entry((*user).to_owned()).or_default();
held.retain(|n| n != token);
(StatusCode::NO_CONTENT, serde_json::Value::Null)
}
}
_ => (
StatusCode::NOT_FOUND,
serde_json::json!({ "message": "not stubbed" }),
),
};
let count = body.as_array().map_or(0, Vec::len).to_string();
let body = if status == StatusCode::NO_CONTENT {
String::new()
} else {
body.to_string()
};
(
status,
[
(CONTENT_TYPE.as_str(), "application/json".to_owned()),
("x-total-count", count),
],
body,
)
}
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
tokio::spawn(async move { axum::serve(listener, app).await });
let api = crate::forge::api::tests::fixed(url.clone(), "stub-token");
(Client { api, url }, deletes)
}
const MIX: [&str; 5] = [
"hyperhive-123",
"hyperhive-1700000000",
"hyperhive-abc",
"hyperhive",
AGENT_TOKEN_NAME,
];
fn forge_with_core_and_two_agents() -> Tokens {
let held = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect();
Arc::new(Mutex::new(BTreeMap::from([
(CORE_USER.to_owned(), held(&MIX)),
("alice".to_owned(), held(&MIX)),
("bob".to_owned(), held(&MIX)),
])))
}
fn sorted(deletes: &Deletes) -> Vec<(String, String)> {
let mut d = deletes.lock().unwrap().clone();
d.sort();
d
}
fn pair(user: &str, token: &str) -> (String, String) {
(user.to_owned(), token.to_owned())
}
/// Core is in the list handed to the sweep, as a stand-in for any path
/// that lets it through [`sweepable`]; its tokens must survive anyway.
#[tokio::test]
async fn only_agents_legacy_tokens_go_and_a_rerun_removes_nothing() {
let tokens = forge_with_core_and_two_agents();
let (client, deletes) = stub_forge(tokens.clone(), ("", "")).await;
let users = [CORE_USER.to_owned(), "alice".to_owned(), "bob".to_owned()];
assert_eq!(client.sweep_legacy_tokens(&users).await, 4);
assert_eq!(
sorted(&deletes),
[
pair("alice", "hyperhive-123"),
pair("alice", "hyperhive-1700000000"),
pair("bob", "hyperhive-123"),
pair("bob", "hyperhive-1700000000"),
]
);
let left = tokens.lock().unwrap().clone();
assert_eq!(left[CORE_USER], MIX);
for agent in ["alice", "bob"] {
assert_eq!(
left[agent],
["hyperhive-abc", "hyperhive", AGENT_TOKEN_NAME]
);
}
deletes.lock().unwrap().clear();
assert_eq!(client.sweep_legacy_tokens(&users).await, 0);
assert!(deletes.lock().unwrap().is_empty());
}
#[tokio::test]
async fn a_refused_delete_moves_on_to_the_next() {
let tokens = forge_with_core_and_two_agents();
let (client, deletes) = stub_forge(tokens.clone(), ("alice", "hyperhive-123")).await;
let users = ["alice".to_owned(), "bob".to_owned()];
assert_eq!(client.sweep_legacy_tokens(&users).await, 3);
assert_eq!(deletes.lock().unwrap().len(), 4);
assert_eq!(
tokens.lock().unwrap()["alice"],
[
"hyperhive-123",
"hyperhive-abc",
"hyperhive",
AGENT_TOKEN_NAME
]
);
}
#[tokio::test]
async fn a_user_the_forge_does_not_have_removes_nothing() {
let tokens = forge_with_core_and_two_agents();
let (client, deletes) = stub_forge(tokens, ("", "")).await;
assert_eq!(client.sweep_legacy_tokens(&["ruth".to_owned()]).await, 0);
assert!(deletes.lock().unwrap().is_empty());
}
}

View file

@ -0,0 +1,166 @@
//! `internal/meta` on the forge: the repo the swarm meta flake is committed to
//! (`crate::meta_flake`), and the read grant each hive's account holds on it.
use anyhow::{Context, Result};
use base64::Engine as _;
use forgejo_api::structs::{
AddCollaboratorOptionPermission, ChangeFileOperation, ChangeFileOperationOperation,
ChangeFilesOptions,
};
use super::objects::SHARED_ORG;
use super::{Client, DefaultBranchFiles, is_repo_not_found};
use crate::meta_flake::{META_REPO, MetaFile, MetaForge};
impl MetaForge for Client {
async fn head_files(
&self,
owner: &str,
repo: &str,
branch: Option<&str>,
paths: &[&str],
) -> Result<Option<DefaultBranchFiles>> {
self.branch_files(owner, repo, branch, paths).await
}
async fn ensure_meta_repo(&self) -> Result<()> {
self.create_shared_repo(SHARED_ORG, META_REPO, true).await
}
async fn grant_meta_read(&self, login: &str) -> Result<()> {
self.add_collaborator_to(
SHARED_ORG,
META_REPO,
login,
AddCollaboratorOptionPermission::Read,
)
.await
}
async fn commits_ahead(
&self,
owner: &str,
repo: &str,
base: &str,
head: &str,
) -> Result<Option<u64>> {
let basehead = format!("{base}...{head}");
match self
.api
.call(|api| api.repo_compare_diff(owner, repo, &basehead).into_future())
.await
{
Ok(compare) => Ok(Some(
u64::try_from(compare.total_commits.unwrap_or(0)).unwrap_or(0),
)),
Err(e) if is_repo_not_found(&e) => Ok(None),
Err(e) => Err(e).with_context(|| format!("compare {basehead} in {owner}/{repo}")),
}
}
async fn commit_meta(&self, message: &str, files: Vec<MetaFile>) -> Result<()> {
let ops: Vec<ChangeFileOperation> = files
.into_iter()
.map(|f| ChangeFileOperation {
content: Some(base64::engine::general_purpose::STANDARD.encode(f.bytes)),
from_path: None,
operation: if f.sha.is_some() {
ChangeFileOperationOperation::Update
} else {
ChangeFileOperationOperation::Create
},
path: f.path.to_owned(),
sha: f.sha,
})
.collect();
self.api
.call(|api| {
api.repo_change_files(
SHARED_ORG,
META_REPO,
ChangeFilesOptions {
author: None,
branch: None,
committer: None,
dates: None,
files: ops.clone(),
force_overwrite_new_branch: None,
message: Some(message.to_owned()),
new_branch: None,
signoff: None,
},
)
.into_future()
})
.await
.with_context(|| format!("commit to {SHARED_ORG}/{META_REPO}"))?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use super::*;
/// A stand-in forge answering Forgejo's compare endpoint: `total_commits`
/// of 3 for `aaa...bbb`, 0 for `bbb...aaa`, 404 for anything else.
/// Records every request's path.
async fn compare_forge() -> (Client, Arc<Mutex<Vec<String>>>) {
use axum::http::{StatusCode, Uri};
let seen = Arc::new(Mutex::new(Vec::new()));
let recorded = Arc::clone(&seen);
let app = axum::Router::new().fallback(move |uri: Uri| {
let recorded = Arc::clone(&recorded);
async move {
recorded.lock().unwrap().push(uri.path().to_owned());
match uri.path() {
"/api/v1/repos/o/r/compare/aaa...bbb" => (
StatusCode::OK,
r#"{"total_commits":3,"commits":[],"files":[]}"#,
),
"/api/v1/repos/o/r/compare/bbb...aaa" => {
(StatusCode::OK, r#"{"total_commits":0,"commits":[]}"#)
}
_ => (StatusCode::NOT_FOUND, r#"{"message":"not found"}"#),
}
}
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
tokio::spawn(async move { axum::serve(listener, app).await });
let api = crate::forge::api::tests::fixed(url.clone(), "stub-token");
(Client { api, url }, seen)
}
#[tokio::test]
async fn commits_ahead_reads_the_compare_endpoint_as_base_dots_head() {
let (client, seen) = compare_forge().await;
assert_eq!(
client.commits_ahead("o", "r", "aaa", "bbb").await.unwrap(),
Some(3)
);
assert_eq!(
client.commits_ahead("o", "r", "bbb", "aaa").await.unwrap(),
Some(0)
);
assert_eq!(
*seen.lock().unwrap(),
[
"/api/v1/repos/o/r/compare/aaa...bbb",
"/api/v1/repos/o/r/compare/bbb...aaa"
]
);
}
#[tokio::test]
async fn a_commit_the_forge_lacks_is_no_count_not_an_error() {
let (client, _) = compare_forge().await;
assert_eq!(
client.commits_ahead("o", "r", "aaa", "zzz").await.unwrap(),
None
);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,287 @@
//! Each operator's forge-profile pronouns, published as one list under the
//! `operator-profiles` KV bucket's one key
//! (`swarm_queue_client::operator_profiles`) at start and every
//! [`RECONCILE_INTERVAL`] after. Every agent reads that key into its system
//! prompt.
//!
//! An operator is a member of authelia's operator group, read the way
//! `crate::matrix_account::operator_admin` reads it. A pass writes the key
//! only when the list changed, so a name no longer in the group drops out of
//! it. An operator whose forge profile could not be read keeps the entry the
//! stored list holds (name only when it holds none); one with no forge account
//! yet is listed with no pronouns.
use std::sync::Arc;
use anyhow::{Context, Result};
use async_nats::jetstream::kv::Store;
use swarm_queue_client::operator_profiles::{self, KEY, OperatorProfile};
use super::Client;
use super::agent_token::is_not_found;
use crate::auth::AuthBridge;
/// How often [`spawn`] re-reads the operator group and their profiles.
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// Where an operator's pronouns come from.
pub(crate) trait Profiles {
/// The pronouns on `name`'s forge profile: `None` when unset or when the
/// forge has no such account.
fn pronouns(&self, name: &str) -> impl Future<Output = Result<Option<String>>> + Send;
}
impl Profiles for Client {
async fn pronouns(&self, name: &str) -> Result<Option<String>> {
match self.api.call(|api| api.user_get(name).into_future()).await {
Ok(user) => Ok(user
.pronouns
.map(|p| p.trim().to_owned())
.filter(|p| !p.is_empty())),
Err(e) if is_not_found(&e) => Ok(None),
Err(e) => Err(e).with_context(|| format!("read forge user {name}")),
}
}
}
/// What one pass did.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Outcome {
/// The list differed from the stored one and was written.
written: bool,
/// Operators whose profile could not be read, left as stored.
kept: usize,
}
/// Bring [`KEY`] in `store` to the list of `operators`, each with its
/// pronouns as `forge` reports them, sorted by name.
///
/// # Errors
/// When the key cannot be read or written. A forge read that fails is logged
/// and keeps that operator's stored entry. A stored value this build cannot
/// decode reads as an empty list, so the pass replaces it.
pub(crate) async fn sync(
operators: &[String],
forge: &impl Profiles,
store: &Store,
) -> Result<Outcome> {
let stored: Vec<OperatorProfile> = store
.get(KEY)
.await
.context("reading the operator list")?
.and_then(|value| serde_json::from_slice(&value).ok())
.unwrap_or_default();
let mut outcome = Outcome::default();
let mut list = Vec::with_capacity(operators.len());
for name in operators {
let pronouns = match forge.pronouns(name).await {
Ok(pronouns) => pronouns,
Err(e) => {
tracing::warn!(
operator = %name,
error = %format!("{e:#}"),
"operator profiles: forge profile unreadable; keeping the stored entry"
);
outcome.kept += 1;
stored
.iter()
.find(|o| o.name == *name)
.and_then(|o| o.pronouns.clone())
}
};
list.push(OperatorProfile {
name: name.clone(),
pronouns,
});
}
list.sort_by(|a, b| a.name.cmp(&b.name));
list.dedup_by(|a, b| a.name == b.name);
if list != stored {
let value = serde_json::to_vec(&list).context("encoding the operator list")?;
store
.put(KEY, value.into())
.await
.context("writing the operator list")?;
outcome.written = true;
}
Ok(outcome)
}
/// One pass: read the operator group, then [`sync`] the key to it. Fails as a
/// whole, changing nothing, when the group cannot be read.
async fn pass(forge: &Client, bridge: &AuthBridge, queue: &async_nats::Client) -> Result<Outcome> {
let operators = bridge
.list_operators()
.await
.context("reading authelia's operator group")?;
let store = operator_profiles::open_or_create(queue)
.await
.context("opening the operator-profiles bucket")?;
sync(&operators, forge, &store).await
}
/// Publish the operators' profiles now and every [`RECONCILE_INTERVAL`]
/// after. A pass that fails is logged and retried on the next tick; it never
/// stops the daemon.
pub fn spawn(forge: Arc<Client>, bridge: Arc<AuthBridge>, queue: async_nats::Client) {
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
loop {
ticker.tick().await;
let Some(outcome) =
super::within_forge_deadline("operator profiles", pass(&forge, &bridge, &queue))
.await
else {
continue;
};
match outcome {
Ok(outcome) if outcome.written => tracing::info!(
kept = outcome.kept,
"operator profiles: operator list updated"
),
Ok(outcome) => tracing::debug!(kept = outcome.kept, "operator profiles: unchanged"),
Err(e) => tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"operator profiles: pass failed; retrying next tick"
),
}
}
});
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
/// A forge answering from a table: `Err` for a name whose read fails.
struct Fake(BTreeMap<&'static str, Result<Option<&'static str>, ()>>);
impl Profiles for Fake {
async fn pronouns(&self, name: &str) -> Result<Option<String>> {
match self.0.get(name) {
Some(Ok(p)) => Ok(p.map(str::to_owned)),
Some(Err(())) => anyhow::bail!("the forge refused the read"),
None => Ok(None),
}
}
}
fn names(names: &[&str]) -> Vec<String> {
names.iter().map(|&n| n.to_owned()).collect()
}
async fn stored(store: &Store) -> Vec<OperatorProfile> {
let value = store.get(KEY).await.unwrap().expect("the list is written");
serde_json::from_slice(&value).unwrap()
}
fn profile(name: &str, pronouns: Option<&str>) -> OperatorProfile {
OperatorProfile {
name: name.to_owned(),
pronouns: pronouns.map(str::to_owned),
}
}
#[tokio::test]
async fn the_list_is_written_once_and_a_departed_operator_drops_out() {
let nats = crate::test_nats::TestNats::start();
let client = nats.client().await;
let store = operator_profiles::open_or_create(&client).await.unwrap();
let forge = Fake([("mara", Ok(Some("she/her"))), ("sol", Ok(None))].into());
let outcome = sync(&names(&["sol", "mara"]), &forge, &store)
.await
.unwrap();
assert!(outcome.written);
assert_eq!(
stored(&store).await,
[profile("mara", Some("she/her")), profile("sol", None)]
);
let revision = store.entry(KEY).await.unwrap().unwrap().revision;
// An unchanged list is not rewritten.
let outcome = sync(&names(&["mara", "sol"]), &forge, &store)
.await
.unwrap();
assert_eq!(outcome, Outcome::default());
assert_eq!(store.entry(KEY).await.unwrap().unwrap().revision, revision);
let outcome = sync(&names(&["mara"]), &forge, &store).await.unwrap();
assert!(outcome.written);
assert_eq!(stored(&store).await, [profile("mara", Some("she/her"))]);
}
#[tokio::test]
async fn a_failed_forge_read_keeps_the_stored_entry() {
let nats = crate::test_nats::TestNats::start();
let client = nats.client().await;
let store = operator_profiles::open_or_create(&client).await.unwrap();
let reachable = Fake(
[
("mara", Ok(Some("she/her"))),
("sol", Ok(Some("they/them"))),
]
.into(),
);
sync(&names(&["mara", "sol"]), &reachable, &store)
.await
.unwrap();
// Control: the same sync does change a value the forge reads anew.
// `ren` is new and unreadable, so it is listed by name only.
let failing = Fake(
[
("mara", Err(())),
("sol", Ok(Some("he/him"))),
("ren", Err(())),
]
.into(),
);
let outcome = sync(&names(&["mara", "sol", "ren"]), &failing, &store)
.await
.unwrap();
assert_eq!(outcome.kept, 2);
assert_eq!(
stored(&store).await,
[
profile("mara", Some("she/her")),
profile("ren", None),
profile("sol", Some("he/him"))
]
);
}
/// The agent's read (`operator_profiles::read`, one direct get) finds
/// what a pass wrote, an empty list for a bucket with no key yet, and
/// `NoBucket` before the bucket exists.
#[tokio::test]
async fn the_agent_read_finds_the_list_and_falls_back_without_one() {
use swarm_queue_client::operator_profiles::{Read, read};
let nats = crate::test_nats::TestNats::start();
let client = nats.client().await;
assert!(matches!(read(&client).await.unwrap(), Read::NoBucket));
let store = operator_profiles::open_or_create(&client).await.unwrap();
let Read::Current(empty) = read(&client).await.unwrap() else {
panic!("the bucket exists");
};
assert_eq!(empty, []);
let forge = Fake([("mara", Ok(Some("she/her")))].into());
sync(&names(&["mara"]), &forge, &store).await.unwrap();
let Read::Current(list) = read(&client).await.unwrap() else {
panic!("the bucket exists");
};
assert_eq!(list, [profile("mara", Some("she/her"))]);
store.delete(KEY).await.unwrap();
let Read::Current(deleted) = read(&client).await.unwrap() else {
panic!("the bucket exists");
};
assert_eq!(deleted, []);
}
}

View file

@ -0,0 +1,330 @@
//! Comments on a pull request, posted once per marker.
use anyhow::{Context, Result};
use forgejo_api::structs::{
Comment, CreateIssueCommentOption, EditIssueCommentOption, IssueGetCommentsQuery,
};
use super::Client;
impl Client {
/// Every comment on pull request `pr` of `owner/repo` written by this
/// client's own forge login. A comment by anyone else can carry a marker
/// (a quote-reply copies it) and is neither counted nor edited.
async fn own_comments(&self, owner: &str, repo: &str, pr: u64) -> Result<Vec<Comment>> {
let me = self
.api
.call(|api| api.user_get_current().into_future())
.await
.context("reading this client's own forge login")?
.login
.context("the forge returned no login for this client")?;
Ok(self
.comments(owner, repo, pr)
.await?
.into_iter()
.filter(|c| c.user.as_ref().and_then(|u| u.login.as_deref()) == Some(me.as_str()))
.collect())
}
/// Every comment on pull request `pr` of `owner/repo`.
async fn comments(&self, owner: &str, repo: &str, pr: u64) -> Result<Vec<Comment>> {
let index = i64::try_from(pr).context("PR number out of range")?;
self.api
.call(|api| {
Box::pin(
api.issue_get_comments(
owner,
repo,
index,
IssueGetCommentsQuery {
since: None,
before: None,
},
)
.all(),
)
})
.await
.with_context(|| format!("listing the comments on {owner}/{repo}#{pr}"))
}
/// Comment `body` on pull request `pr` of `owner/repo` unless a comment
/// there already contains `marker`. Whether a comment was posted.
///
/// The marker is what the comment carries, so the check holds across a
/// restart and across every caller. It reads the comments first, so two
/// concurrent calls with one marker can both post.
pub(crate) async fn comment_once(
&self,
owner: &str,
repo: &str,
pr: u64,
marker: &str,
body: &str,
) -> Result<bool> {
let index = i64::try_from(pr).context("PR number out of range")?;
let existing = self.own_comments(owner, repo, pr).await?;
if existing
.iter()
.any(|c| c.body.as_deref().is_some_and(|b| b.contains(marker)))
{
return Ok(false);
}
let option = CreateIssueCommentOption {
body: body.to_owned(),
updated_at: None,
};
self.api
.call(|api| {
api.issue_create_comment(owner, repo, index, option.clone())
.into_future()
})
.await
.with_context(|| format!("commenting on {owner}/{repo}#{pr}"))?;
Ok(true)
}
/// Rewrite every comment of this client's own on pull request `pr` of
/// `owner/repo` that contains `marker`: the marker becomes `cleared`, which
/// lets [`Self::comment_once`] post that marker again, and `resolved` is
/// appended on a line of its own. A comment the forge refuses to edit is
/// logged and skipped, so one refusal leaves the rest cleared. How many
/// comments were rewritten.
///
/// # Errors
///
/// The comments could not be listed.
pub(crate) async fn clear_marker(
&self,
owner: &str,
repo: &str,
pr: u64,
marker: &str,
cleared: &str,
resolved: &str,
) -> Result<usize> {
let mut rewritten = 0;
for comment in self.own_comments(owner, repo, pr).await? {
let (Some(id), Some(body)) = (comment.id, comment.body.as_deref()) else {
continue;
};
if !body.contains(marker) {
continue;
}
let option = EditIssueCommentOption {
body: format!("{}\n\n{resolved}", body.replace(marker, cleared)),
updated_at: None,
};
let edited = self
.api
.call(|api| {
api.issue_edit_comment(owner, repo, id, option.clone())
.into_future()
})
.await;
match edited {
Ok(_) => rewritten += 1,
Err(e) => tracing::warn!(
id, %owner, %repo, pr, error = %format!("{e:#}"),
"swarm forge: could not rewrite a resolved build comment"
),
}
}
Ok(rewritten)
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::sync::{Arc, Mutex};
use axum::http::{Method, StatusCode, Uri};
use super::*;
/// The comments a stand-in forge holds, as the issue path they were
/// posted to and their body.
pub(crate) type Posted = Arc<Mutex<Vec<(String, String)>>>;
/// A comment whose body starts with this is written by someone other than
/// the client's own login.
pub(crate) const HUMAN: &str = "HUMAN:";
/// A comment whose body contains this is one the forge refuses to edit.
pub(crate) const REFUSED: &str = "REFUSED";
/// A stand-in forge that stores the comments posted to any issue path and
/// lists them back.
pub(crate) async fn stand_in() -> (Client, Posted) {
let held: Posted = Arc::default();
let state = Arc::clone(&held);
let app = axum::Router::new().fallback(
move |method: Method, uri: Uri, body: axum::body::Bytes| {
let state = Arc::clone(&state);
async move {
let path = uri.path().to_owned();
let mut held = state.lock().unwrap();
match method.as_str() {
"GET" if path == "/api/v1/user" => (
StatusCode::OK,
[("x-total-count", String::new())],
r#"{"login":"bot"}"#.to_owned(),
),
"GET" => {
let list: Vec<_> = held
.iter()
.enumerate()
.filter(|(_, (p, _))| *p == path)
.map(|(id, (_, body))| {
let author = if body.starts_with(HUMAN) { "human" } else { "bot" };
serde_json::json!({ "id": id, "body": body, "user": { "login": author } })
})
.collect();
let count = list.len().to_string();
(
StatusCode::OK,
[("x-total-count", count)],
serde_json::Value::from(list).to_string(),
)
}
"PATCH" => {
let sent: serde_json::Value = serde_json::from_slice(&body).unwrap();
let id: usize = path.rsplit('/').next().unwrap().parse().unwrap();
if held[id].1.contains(REFUSED) {
return (
StatusCode::FORBIDDEN,
[("x-total-count", String::new())],
r#"{"message":"refused"}"#.to_owned(),
);
}
held[id].1 = sent["body"].as_str().unwrap().to_owned();
(
StatusCode::OK,
[("x-total-count", String::new())],
serde_json::json!({ "id": id, "body": held[id].1 }).to_string(),
)
}
"POST" => {
let sent: serde_json::Value = serde_json::from_slice(&body).unwrap();
let text = sent["body"].as_str().unwrap().to_owned();
held.push((path, text.clone()));
(
StatusCode::CREATED,
[("x-total-count", String::new())],
serde_json::json!({ "id": held.len() - 1, "body": text })
.to_string(),
)
}
_ => (
StatusCode::NOT_FOUND,
[("x-total-count", String::new())],
r#"{"message":"no"}"#.to_owned(),
),
}
}
},
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = url::Url::parse(&format!("http://{}/", listener.local_addr().unwrap())).unwrap();
tokio::spawn(async move { axum::serve(listener, app).await });
(Client::for_test_forge(url), held)
}
#[tokio::test]
async fn a_marker_is_commented_once_and_a_new_marker_again() {
let (client, held) = stand_in().await;
let once = |marker: &'static str| {
let client = &client;
async move {
client
.comment_once("o", "r", 7, marker, &format!("{marker} text"))
.await
.unwrap()
}
};
assert!(once("<!-- a -->").await, "first comment is posted");
assert!(!once("<!-- a -->").await, "same marker is not posted again");
assert!(once("<!-- b -->").await, "control: another marker posts");
let held = held.lock().unwrap();
assert_eq!(held.len(), 2, "{held:?}");
assert_eq!(
held[0].0,
format!("/api/v1/repos/o/r/{}/7/comments", "issues")
);
}
fn issue_path() -> String {
format!("/api/v1/repos/o/r/{}/7/comments", "issues")
}
#[tokio::test]
async fn a_cleared_marker_can_be_posted_again_and_the_old_comment_says_resolved() {
let (client, held) = stand_in().await;
let (marker, cleared) = ("<!-- a -->", "<!-- a cleared -->");
assert!(
client
.comment_once("o", "r", 7, marker, marker)
.await
.unwrap()
);
let clear = || client.clear_marker("o", "r", 7, marker, cleared, "Resolved.");
assert_eq!(clear().await.unwrap(), 1);
assert_eq!(clear().await.unwrap(), 0);
assert!(
client
.comment_once("o", "r", 7, marker, marker)
.await
.unwrap()
);
let held = held.lock().unwrap();
assert_eq!(held[0].1, format!("{cleared}\n\nResolved."));
assert_eq!(held[1].1, marker);
}
/// A human's comment can carry the marker (a quote-reply copies it): it
/// neither counts as the bot's report nor is rewritten.
#[tokio::test]
async fn a_comment_by_someone_else_with_the_marker_is_neither_counted_nor_edited() {
let (client, held) = stand_in().await;
let marker = "<!-- a -->";
let quoted = format!("{HUMAN} > {marker}");
held.lock().unwrap().push((issue_path(), quoted.clone()));
assert!(
client
.comment_once("o", "r", 7, marker, marker)
.await
.unwrap(),
"the human's copy does not silence the bot"
);
let cleared = client
.clear_marker("o", "r", 7, marker, "<!-- c -->", "Resolved.")
.await
.unwrap();
assert_eq!(cleared, 1, "only the bot's own comment");
let held = held.lock().unwrap();
assert_eq!(held[0].1, quoted, "the human's comment is untouched");
assert!(held[1].1.contains("<!-- c -->"), "{:?}", held[1]);
}
/// The forge refusing one edit does not stop the next comment's clear.
#[tokio::test]
async fn a_refused_edit_still_clears_the_next_comment() {
let (client, held) = stand_in().await;
let marker = "<!-- a -->";
let refused = format!("{marker} {REFUSED}");
{
let mut held = held.lock().unwrap();
held.push((issue_path(), refused.clone()));
held.push((issue_path(), marker.to_owned()));
}
let cleared = client
.clear_marker("o", "r", 7, marker, "<!-- c -->", "Resolved.")
.await
.unwrap();
assert_eq!(cleared, 1);
let held = held.lock().unwrap();
assert_eq!(held[0].1, refused, "control: the refused one is as it was");
assert!(held[1].1.contains("<!-- c -->"), "{:?}", held[1]);
}
}

View file

@ -0,0 +1,666 @@
//! The open pull requests of a repo as the swarm UI's PR report reads them:
//! each with what a reviewer or merger wants to filter on already resolved, so
//! the page does no calls of its own. Read-only, over the controller's forge
//! token.
use anyhow::{Context, Result};
use forgejo_api::structs::{
BranchProtection, CombinedStatus, CommitStatusState, PullRequest, PullReview,
RepoListPullRequestsQuery, RepoListPullRequestsQueryState,
};
use futures_util::{StreamExt as _, TryStreamExt as _};
use serde::Serialize;
use std::collections::HashMap;
use utoipa::ToSchema;
use super::Client;
/// What the commit statuses on a PR's head say together.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CiState {
Success,
Pending,
Failure,
}
/// One open pull request, resolved for the PR report.
#[derive(Clone, Debug, PartialEq, Serialize, ToSchema)]
pub struct PrReportRow {
/// `owner/name`, on every row so the all-repos and the one-repo report
/// share one row type.
pub repo: String,
pub number: i64,
pub title: String,
pub html_url: Option<String>,
pub author: Option<String>,
pub labels: Vec<String>,
pub assignees: Vec<String>,
pub requested_reviewers: Vec<String>,
pub base_branch: String,
pub head_branch: String,
pub created_unix: Option<i64>,
pub updated_unix: Option<i64>,
/// Lines the PR adds and removes, as the forge counts them.
pub additions: Option<i64>,
pub deletions: Option<i64>,
/// The forge's draft flag (setting a `WIP:` title is what sets it).
pub wip: bool,
/// The forge cannot merge the PR as it is: its head conflicts with the
/// base.
pub has_conflicts: bool,
/// The base branch has a branch protection rule. A stacked PR targets a
/// feature branch, so `false` filters those out.
pub targets_protected_branch: bool,
/// Approvals the protection rule asks for; 0 when the base is not
/// protected.
pub required_approvals: u32,
/// Approvals that count now: the reviewer's latest review is an approval
/// of the current head, not dismissed, not stale, and counts toward the
/// rule (the forge's `official`).
pub approvals: u32,
/// Reviewers whose latest review asks for changes and is not dismissed.
pub changes_requested: u32,
/// `None` when the head has no commit status at all.
pub ci: Option<CiState>,
}
/// Whether `branch` is named by a branch protection pattern. The forge reads a
/// rule's name as a glob with `/` as the separator: `*` and `?` stop at a `/`,
/// `**` does not, `[a-z]` and `[!a-z]` are classes, `{a,b}` is a choice and a
/// backslash escapes the next character.
fn glob_matches(pattern: &str, branch: &str) -> bool {
let branch: Vec<char> = branch.chars().collect();
expand_choices(pattern).iter().any(|p| {
let p: Vec<char> = p.chars().collect();
glob_run(&p, &branch)
})
}
/// `pattern` with each `{a,b}` choice written out: `v{1,2}` is `v1` and `v2`.
/// A `{` with no closing `}` is itself.
fn expand_choices(pattern: &str) -> Vec<String> {
let chars: Vec<char> = pattern.chars().collect();
let mut escaped = false;
let mut open = None;
for (i, &c) in chars.iter().enumerate() {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'{' => {
open = Some(i);
break;
}
_ => {}
}
}
let Some(open) = open else {
return vec![pattern.to_owned()];
};
// The matching `}` and the commas between, at this nesting only.
let (mut depth, mut escaped) = (0_usize, false);
let mut cuts = vec![open];
for (i, &c) in chars.iter().enumerate().skip(open) {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'{' => depth += 1,
',' if depth == 1 => cuts.push(i),
'}' => {
depth -= 1;
if depth == 0 {
cuts.push(i);
let text = |from: usize, to: usize| chars[from..to].iter().collect::<String>();
let (head, tail) = (text(0, open), text(i + 1, chars.len()));
return cuts
.windows(2)
.flat_map(|w| {
expand_choices(&format!("{head}{}{tail}", text(w[0] + 1, w[1])))
})
.collect();
}
}
_ => {}
}
}
vec![pattern.to_owned()]
}
/// Whether the choice-free pattern `p` matches all of `s`.
fn glob_run(p: &[char], s: &[char]) -> bool {
let Some((&c, rest)) = p.split_first() else {
return s.is_empty();
};
match c {
'*' => {
if let Some(rest) = rest.strip_prefix(&['*']) {
// `**`: any run, slashes included.
(0..=s.len()).any(|i| glob_run(rest, &s[i..]))
} else {
// `*`: any run up to the next slash.
let reach = s.iter().position(|&d| d == '/').unwrap_or(s.len());
(0..=reach).any(|i| glob_run(rest, &s[i..]))
}
}
'?' => s
.split_first()
.is_some_and(|(&d, tail)| d != '/' && glob_run(rest, tail)),
'[' => match glob_class(rest) {
Some((members, negated, after)) => s.split_first().is_some_and(|(&d, tail)| {
d != '/' && members.contains(d) != negated && glob_run(after, tail)
}),
// No closing `]`: a literal bracket.
None => s
.split_first()
.is_some_and(|(&d, tail)| d == '[' && glob_run(rest, tail)),
},
'\\' if !rest.is_empty() => s
.split_first()
.is_some_and(|(&d, tail)| d == rest[0] && glob_run(&rest[1..], tail)),
_ => s
.split_first()
.is_some_and(|(&d, tail)| c == d && glob_run(rest, tail)),
}
}
/// What a `[` class holds: its members, whether it is negated (`[!a]`), and
/// the pattern after its `]`. `None` for a class with no `]`.
fn glob_class(after_bracket: &[char]) -> Option<(Members, bool, &[char])> {
let (negated, body) = match after_bracket.split_first() {
Some((&'!', body)) => (true, body),
_ => (false, after_bracket),
};
let end = body.iter().position(|&c| c == ']')?;
let mut members = Members::default();
let mut i = 0;
while i < end {
if i + 2 < end && body[i + 1] == '-' {
members.ranges.push((body[i], body[i + 2]));
i += 3;
} else {
members.ranges.push((body[i], body[i]));
i += 1;
}
}
Some((members, negated, &body[end + 1..]))
}
/// The characters and ranges a `[` class names.
#[derive(Default)]
struct Members {
ranges: Vec<(char, char)>,
}
impl Members {
fn contains(&self, c: char) -> bool {
self.ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&c))
}
}
/// The protection rule for `base`, as the approvals it asks for: `None` when
/// no rule names the branch. The first matching rule wins, which is how the
/// forge orders them.
fn required_approvals_for(rules: &[BranchProtection], base: &str) -> Option<u32> {
rules
.iter()
.find(|r| {
r.rule_name
.as_deref()
.or(r.branch_name.as_deref())
.is_some_and(|p| glob_matches(p, base))
})
.map(|r| u32::try_from(r.required_approvals.unwrap_or(0)).unwrap_or(0))
}
/// How a PR's reviews stand against its current head.
#[derive(Debug, PartialEq, Eq)]
struct Tally {
approvals: u32,
changes_requested: u32,
}
/// Each reviewer's latest review decides: an approval counts when it is of
/// `head_sha`, not dismissed, not stale and official; a review asking for
/// changes stands until it is dismissed or the reviewer reviews again. A
/// review that only comments does not replace an earlier decision.
fn tally_reviews(reviews: &[PullReview], head_sha: &str) -> Tally {
let mut latest: HashMap<&str, &PullReview> = HashMap::new();
for review in reviews {
let Some(login) = review.user.as_ref().and_then(|u| u.login.as_deref()) else {
continue;
};
let decides = matches!(
review.state.as_deref(),
Some("APPROVED" | "REQUEST_CHANGES")
);
if decides && review.dismissed != Some(true) {
latest.insert(login, review);
} else if decides {
// A dismissed decision no longer stands, and neither does the
// one it replaced.
latest.remove(login);
}
}
let mut tally = Tally {
approvals: 0,
changes_requested: 0,
};
for review in latest.values() {
match review.state.as_deref() {
Some("APPROVED") => {
if review.commit_id.as_deref() == Some(head_sha)
&& review.stale != Some(true)
&& review.official == Some(true)
{
tally.approvals += 1;
}
}
_ => tally.changes_requested += 1,
}
}
tally
}
/// The commit statuses on a head, as one state; `None` when it has none.
fn ci_state(status: &CombinedStatus) -> Option<CiState> {
if status.total_count.unwrap_or(0) == 0 {
return None;
}
Some(match status.state? {
CommitStatusState::Success | CommitStatusState::Skipped => CiState::Success,
CommitStatusState::Pending | CommitStatusState::Warning => CiState::Pending,
CommitStatusState::Failure | CommitStatusState::Error => CiState::Failure,
})
}
fn row(
repo: &str,
pr: &PullRequest,
rules: &[BranchProtection],
reviews: &[PullReview],
status: &CombinedStatus,
) -> Option<PrReportRow> {
let base_branch = pr.base.as_ref()?.r#ref.clone().unwrap_or_default();
let head = pr.head.as_ref()?;
let head_sha = head.sha.clone().unwrap_or_default();
let protection = required_approvals_for(rules, &base_branch);
let required_approvals = protection.unwrap_or(0);
let tally = tally_reviews(reviews, &head_sha);
let logins = |users: &Option<Vec<forgejo_api::structs::User>>| -> Vec<String> {
users
.iter()
.flatten()
.filter_map(|u| u.login.clone())
.collect()
};
Some(PrReportRow {
repo: repo.to_owned(),
number: pr.number?,
title: pr.title.clone().unwrap_or_default(),
html_url: pr.html_url.as_ref().map(ToString::to_string),
author: pr.user.as_ref().and_then(|u| u.login.clone()),
labels: pr
.labels
.iter()
.flatten()
.filter_map(|l| l.name.clone())
.collect(),
assignees: logins(&pr.assignees),
requested_reviewers: logins(&pr.requested_reviewers),
base_branch,
head_branch: head.r#ref.clone().unwrap_or_default(),
created_unix: pr.created_at.as_ref().map(|t| t.unix_timestamp()),
updated_unix: pr.updated_at.as_ref().map(|t| t.unix_timestamp()),
additions: pr.additions,
deletions: pr.deletions,
wip: pr.draft.unwrap_or(false),
has_conflicts: pr.mergeable == Some(false),
targets_protected_branch: protection.is_some(),
required_approvals,
approvals: tally.approvals,
changes_requested: tally.changes_requested,
ci: ci_state(status),
})
}
impl Client {
/// Every open pull request in `owner/repo`, resolved for the PR report.
///
/// The reviews and the commit statuses are one call per PR, run with
/// bounded concurrency like [`Client::issue_report`]'s dependency
/// lookups; the branch protection rules are one call for the repo.
///
/// # Errors
/// The forge refused or did not answer one of the calls.
pub async fn pr_report(&self, owner: &str, repo: &str) -> Result<Vec<PrReportRow>> {
const CONCURRENCY: usize = 8;
let query = RepoListPullRequestsQuery {
state: Some(RepoListPullRequestsQueryState::Open),
sort: None,
milestone: None,
labels: None,
poster: None,
base: None,
head: None,
};
let pulls = self
.api
.call(|api| {
Box::pin(
api.repo_list_pull_requests(owner, repo, query.clone())
.all(),
)
})
.await
.with_context(|| format!("list open pull requests in {owner}/{repo}"))?;
if pulls.is_empty() {
return Ok(Vec::new());
}
let rules = self
.api
.call(|api| api.repo_list_branch_protection(owner, repo).into_future())
.await
.with_context(|| format!("list branch protections of {owner}/{repo}"))?;
let full_name = format!("{owner}/{repo}");
let rules = &rules;
let full_name = &full_name;
let mut rows: Vec<PrReportRow> = futures_util::stream::iter(pulls)
.map(|pr| async move {
let Some(number) = pr.number else {
return Ok::<_, anyhow::Error>(None);
};
let head_sha = pr.head.as_ref().and_then(|h| h.sha.clone());
let reviews = self
.api
.call(|api| Box::pin(api.repo_list_pull_reviews(owner, repo, number).all()))
.await
.with_context(|| format!("list reviews of {owner}/{repo}#{number}"))?;
let status = match head_sha {
Some(sha) => {
self.api
.call(|api| {
api.repo_get_combined_status_by_ref(owner, repo, &sha)
.into_future()
})
.await
.with_context(|| {
format!("read the statuses of {owner}/{repo}#{number}")
})?
.1
}
None => CombinedStatus {
commit_url: None,
repository: None,
sha: None,
state: None,
statuses: None,
total_count: Some(0),
url: None,
},
};
Ok(row(full_name, &pr, rules, &reviews, &status))
})
.buffer_unordered(CONCURRENCY)
.try_filter_map(|row| async move { Ok(row) })
.try_collect()
.await?;
rows.sort_by_key(|r| std::cmp::Reverse(r.number));
Ok(rows)
}
/// The PR report of every repo with an open pull request. A repo whose
/// report fails is logged and skipped, as [`Client::issue_report_all`]
/// does: one flaky repo should not blank out the others' rows.
///
/// # Errors
/// The forge refused to list the repos.
pub async fn pr_report_all(&self) -> Result<Vec<PrReportRow>> {
const CONCURRENCY: usize = 4;
let repos = self.list_repos_with_open_pulls().await?;
let rows: Vec<Vec<PrReportRow>> = futures_util::stream::iter(repos)
.map(|full_name| async move {
let Some((owner, repo)) = full_name.split_once('/') else {
tracing::warn!(%full_name, "pr_report_all: repo full_name has no '/'");
return Vec::new();
};
match self.pr_report(owner, repo).await {
Ok(rows) => rows,
Err(e) => {
tracing::warn!(
error = %format!("{e:#}"),
%full_name,
"pr_report_all: one repo's report failed, skipping it"
);
Vec::new()
}
}
})
.buffer_unordered(CONCURRENCY)
.collect()
.await;
Ok(rows.into_iter().flatten().collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rule(name: &str, approvals: i64) -> BranchProtection {
serde_json::from_value(serde_json::json!({
"rule_name": name,
"required_approvals": approvals,
}))
.expect("a branch protection")
}
fn review(login: &str, state: &str, commit: &str, flags: &[(&str, bool)]) -> PullReview {
let mut v = serde_json::json!({
"user": { "login": login },
"state": state,
"commit_id": commit,
"official": true,
});
for (k, b) in flags {
v[*k] = serde_json::json!(b);
}
serde_json::from_value(v).expect("a review")
}
#[test]
fn a_pattern_names_a_branch() {
assert!(glob_matches("main", "main"));
assert!(!glob_matches("main", "main2"));
assert!(glob_matches("release/*", "release/1.0"));
assert!(!glob_matches("release/*", "release/1.0/hotfix"));
assert!(glob_matches("release/**", "release/1.0/hotfix"));
assert!(glob_matches("*", "main"));
assert!(!glob_matches("*", "iris/foo"));
}
/// Forgejo reads a rule's name as a glob with `/` as its separator, so
/// `?`, `[..]` and `{a,b}` name branches too. A rule read as naming none
/// would show a PR as needing no approvals.
#[test]
fn a_pattern_may_use_choices_classes_and_a_single_character() {
for (pattern, branch, matches) in [
("{main,release}", "main", true),
("{main,release}", "release", true),
("{main,release}", "dev", false),
("{main,release}", "mainx", false),
("release/{1,2}.*", "release/2.0", true),
("release/{1,2}.*", "release/3.0", false),
("{a,{b,c}}/x", "c/x", true),
("v?", "v1", true),
("v?", "v10", false),
("v?", "v/", false),
("v[0-9]", "v7", true),
("v[0-9]", "va", false),
("v[!0-9]", "va", true),
("v[!0-9]", "v7", false),
("v[abc]", "vb", true),
(r"v\*", "v*", true),
(r"v\*", "vx", false),
("a[b", "a[b", true),
("{a", "{a", true),
("**/main", "x/y/main", true),
] {
assert_eq!(
glob_matches(pattern, branch),
matches,
"{pattern} on {branch}"
);
}
}
#[test]
fn the_first_matching_rule_sets_the_approvals() {
let rules = [rule("main", 1), rule("*", 2)];
assert_eq!(required_approvals_for(&rules, "main"), Some(1));
assert_eq!(required_approvals_for(&rules, "dev"), Some(2));
assert_eq!(required_approvals_for(&rules, "iris/feature"), None);
assert_eq!(required_approvals_for(&[], "main"), None);
}
#[test]
fn an_approval_of_the_head_counts_once_per_reviewer() {
let reviews = [
review("argus", "APPROVED", "h1", &[]),
review("mara", "APPROVED", "h1", &[]),
review("mara", "COMMENT", "h1", &[]),
];
let t = tally_reviews(&reviews, "h1");
assert_eq!(
t,
Tally {
approvals: 2,
changes_requested: 0
}
);
}
#[test]
fn an_old_stale_dismissed_or_unofficial_approval_does_not_count() {
for (r, why) in [
(review("a", "APPROVED", "old", &[]), "of an older head"),
(review("a", "APPROVED", "h1", &[("stale", true)]), "stale"),
(
review("a", "APPROVED", "h1", &[("dismissed", true)]),
"dismissed",
),
(
review("a", "APPROVED", "h1", &[("official", false)]),
"not official",
),
] {
assert_eq!(tally_reviews(&[r], "h1").approvals, 0, "{why}");
}
}
#[test]
fn a_later_review_replaces_an_earlier_decision() {
let reviews = [
review("argus", "REQUEST_CHANGES", "h1", &[]),
review("argus", "APPROVED", "h1", &[]),
];
let t = tally_reviews(&reviews, "h1");
assert_eq!((t.approvals, t.changes_requested), (1, 0));
let reviews = [
review("argus", "APPROVED", "h1", &[]),
review("argus", "REQUEST_CHANGES", "h1", &[]),
];
let t = tally_reviews(&reviews, "h1");
assert_eq!((t.approvals, t.changes_requested), (0, 1));
let reviews = [review(
"argus",
"REQUEST_CHANGES",
"h1",
&[("dismissed", true)],
)];
assert_eq!(tally_reviews(&reviews, "h1").changes_requested, 0);
}
#[test]
fn the_commit_statuses_read_as_one_state() {
let status = |state: Option<CommitStatusState>, n: i64| CombinedStatus {
commit_url: None,
repository: None,
sha: None,
state,
statuses: None,
total_count: Some(n),
url: None,
};
assert_eq!(ci_state(&status(None, 0)), None);
assert_eq!(
ci_state(&status(Some(CommitStatusState::Pending), 0)),
None,
"no statuses is not pending"
);
assert_eq!(
ci_state(&status(Some(CommitStatusState::Success), 3)),
Some(CiState::Success)
);
assert_eq!(
ci_state(&status(Some(CommitStatusState::Error), 3)),
Some(CiState::Failure)
);
assert_eq!(
ci_state(&status(Some(CommitStatusState::Pending), 3)),
Some(CiState::Pending)
);
}
#[test]
fn a_row_resolves_protection_approvals_and_conflicts() {
let pr: PullRequest = serde_json::from_value(serde_json::json!({
"number": 7,
"title": "WIP: a thing",
"draft": true,
"mergeable": false,
"user": { "login": "iris" },
"labels": [{ "name": "type/chore" }],
"assignees": [{ "login": "iris" }],
"requested_reviewers": [{ "login": "argus" }],
"base": { "ref": "main" },
"head": { "ref": "iris/thing", "sha": "h1" },
"created_at": "2026-11-07T08:00:00Z",
"updated_at": "2026-11-07T09:00:00Z",
"additions": 120,
"deletions": 8,
}))
.expect("a pull request");
let status: CombinedStatus = serde_json::from_value(serde_json::json!({
"state": "success", "total_count": 2
}))
.expect("a combined status");
let reviews = [review("argus", "APPROVED", "h1", &[])];
let r = row("o/r", &pr, &[rule("main", 2)], &reviews, &status).expect("a row");
assert_eq!((r.number, r.wip, r.has_conflicts), (7, true, true));
assert_eq!(
(
r.targets_protected_branch,
r.required_approvals,
r.approvals
),
(true, 2, 1)
);
assert_eq!(r.ci, Some(CiState::Success));
assert_eq!(r.author.as_deref(), Some("iris"));
assert_eq!(r.requested_reviewers, ["argus"]);
assert_eq!(r.updated_unix, Some(1_794_042_000));
assert_eq!((r.additions, r.deletions), (Some(120), Some(8)));
// The same PR into a branch no rule names has nothing to approve.
let r = row("o/r", &pr, &[], &reviews, &status).expect("a row");
assert_eq!(
(r.targets_protected_branch, r.required_approvals),
(false, 0)
);
}
}

View file

@ -0,0 +1,276 @@
//! The diff the review classifier reads, built from both sides of each
//! changed file rather than taken from the forge's `.diff`, whose context is
//! fixed at 3 lines. [`CONTEXT_LINES`] of context shows an enclosing gate (a
//! `config = lib.mkIf …`, an option's `default`) only when it is within that
//! many lines of the change; a gate further away is still out of view.
use std::fmt::{self, Write as _};
use std::time::Duration;
use similar::TextDiff;
/// Lines of context around each change. A block's enclosing
/// `config = lib.mkIf …` is in view when it opens within this many lines above
/// the block.
pub const CONTEXT_LINES: usize = 25;
/// The largest wide diff sent, in bytes, about 64k tokens of code. A larger
/// one gives way to the forge's `.diff`.
pub const MAX_BYTES: usize = 256 * 1024;
/// The most changed files a wide diff is read for. Each costs a few forge
/// reads per side, all within the one deadline the PR read runs under.
pub const MAX_FILES: usize = 100;
/// How long one file's diff may search for the smallest edit before settling
/// for a larger one. Without it a rewritten file of tens of thousands of
/// lines takes minutes.
const DIFF_TIMEOUT: Duration = Duration::from_secs(1);
/// One changed file: its path and bytes at the merge base and at the head,
/// `None` on a side where it does not exist.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileChange {
pub old_path: String,
pub new_path: String,
pub old: Option<Vec<u8>>,
pub new: Option<Vec<u8>>,
}
/// Why a PR of `count` changed files gets the forge's `.diff`, if it does.
pub fn too_many_files(count: usize) -> Option<String> {
(count > MAX_FILES).then(|| {
format!("the PR changes {count} files, more than the {MAX_FILES} a wide diff is read for")
})
}
/// `files` as one diff with [`CONTEXT_LINES`] of context, or why the forge's
/// `.diff` stands in: the result is over [`MAX_BYTES`].
pub fn wide(files: &[FileChange]) -> Result<String, String> {
render(files, CONTEXT_LINES, MAX_BYTES).map_err(|_| {
format!(
"the diff with {CONTEXT_LINES} lines of context is over the {MAX_BYTES} bytes a \
review sends"
)
})
}
/// `files` as one unified diff with `context` lines around each change, each
/// file in `git diff`'s shape: a `diff --git` line, `---`/`+++`, then hunks.
/// A file with a non-UTF-8 or NUL-bearing side is one `Binary files` line.
///
/// # Errors
/// The bytes rendered when the output passed `cap`; rendering stops there.
pub fn render(files: &[FileChange], context: usize, cap: usize) -> Result<String, usize> {
let mut out = Capped {
out: String::new(),
cap,
};
for file in files {
if section(&mut out, file, context).is_err() {
return Err(out.out.len());
}
}
Ok(out.out)
}
/// A `String` whose writes fail once it holds more than `cap` bytes, which
/// stops a `Display` impl writing into it.
struct Capped {
out: String,
cap: usize,
}
impl fmt::Write for Capped {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.out.push_str(s);
if self.out.len() > self.cap {
Err(fmt::Error)
} else {
Ok(())
}
}
}
fn section(out: &mut Capped, file: &FileChange, context: usize) -> fmt::Result {
let (old_path, new_path) = (&file.old_path, &file.new_path);
writeln!(out, "diff --git a/{old_path} b/{new_path}")?;
if file.old.is_some() && file.new.is_some() && old_path != new_path {
writeln!(out, "rename from {old_path}\nrename to {new_path}")?;
}
let a = file
.old
.as_ref()
.map_or_else(|| "/dev/null".to_owned(), |_| format!("a/{old_path}"));
let b = file
.new
.as_ref()
.map_or_else(|| "/dev/null".to_owned(), |_| format!("b/{new_path}"));
let (Some(old), Some(new)) = (text(file.old.as_deref()), text(file.new.as_deref())) else {
return writeln!(out, "Binary files {a} and {b} differ");
};
let diff = TextDiff::configure()
.timeout(DIFF_TIMEOUT)
.diff_lines(old, new);
write!(
out,
"{}",
diff.unified_diff().context_radius(context).header(&a, &b)
)
}
/// A side's text: empty when the file is absent, `None` when it is binary.
fn text(bytes: Option<&[u8]>) -> Option<&str> {
let bytes = bytes.unwrap_or_default();
if bytes.contains(&0) {
return None;
}
std::str::from_utf8(bytes).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn change(path: &str, old: Option<&str>, new: Option<&str>) -> FileChange {
FileChange {
old_path: path.to_owned(),
new_path: path.to_owned(),
old: old.map(|s| s.as_bytes().to_vec()),
new: new.map(|s| s.as_bytes().to_vec()),
}
}
/// A Nix module whose `config = lib.mkIf …` block opens `gap` lines above
/// a firewall rule on the wireguard interface.
fn module(gap: usize, with_rule: bool) -> String {
let mut s =
String::from("{ lib, config, ... }:\n{\n config = lib.mkIf deployCfg.nats.enable {\n");
for i in 0..gap {
let _ = writeln!(s, " services.nats.settings.k{i} = {i};");
}
if with_rule {
s.push_str(
" networking.firewall.interfaces.wg0 = {\n allowedTCPPorts = lib.mkIf \
deployCfg.wireguard.enable [ 4222 ];\n };\n",
);
}
for i in 0..5 {
let _ = writeln!(s, " systemd.services.nats.environment.E{i} = \"{i}\";");
}
s.push_str(" };\n}\n");
s
}
/// The rule moves out of the module into a glue module that restates
/// both conditions.
fn move_into_glue() -> Vec<FileChange> {
let glue = "{ lib, config, ... }:\n{\n config = lib.mkIf (deployCfg.nats.enable && \
deployCfg.wireguard.enable) {\n networking.firewall.interfaces.wg0.\
allowedTCPPorts = [ 4222 ];\n };\n}\n";
vec![
change(
"nix/host-modules/glue-nats-oidc-client.nix",
None,
Some(glue),
),
change(
"nix/host-modules/swarm-nats.nix",
Some(&module(20, true)),
Some(&module(20, false)),
),
]
}
/// `count` lines, line `i` reading `line(i)`.
fn numbered(count: usize, line: impl Fn(usize) -> String) -> String {
(0..count).fold(String::new(), |mut s, i| {
let _ = writeln!(s, "{}", line(i));
s
})
}
const GATE: &str = "config = lib.mkIf deployCfg.nats.enable {";
#[test]
fn a_moved_block_keeps_its_enclosing_gate_in_view() {
let diff = wide(&move_into_glue()).expect("fits");
assert!(diff.contains(&format!("\n {GATE}\n")), "{diff}");
assert!(diff.contains("\n- allowedTCPPorts = lib.mkIf deployCfg.wireguard.enable"));
}
#[test]
fn three_lines_of_context_leave_that_gate_out() {
let diff = render(&move_into_glue(), 3, usize::MAX).unwrap();
assert!(!diff.contains(GATE), "{diff}");
}
#[test]
fn context_is_as_wide_as_asked_and_no_wider() {
let old = numbered(30, |i| format!("line {i}"));
let new = old.replace("line 15\n", "line fifteen\n");
let at = |n| render(&[change("f", Some(&old), Some(&new))], n, usize::MAX).unwrap();
let diff = at(10);
assert!(diff.contains("@@ -6,21 +6,21 @@"), "{diff}");
assert!(diff.contains(" line 5\n") && !diff.contains("line 4\n"));
assert!(at(CONTEXT_LINES).contains("@@ -1,30 +1,30 @@"));
}
#[test]
fn file_headers_follow_git_diff() {
let diff = render(
&[
change("added", None, Some("a\n")),
change("gone", Some("a\n"), None),
FileChange {
old_path: "old".to_owned(),
new_path: "new".to_owned(),
old: Some(b"a\n".to_vec()),
new: Some(b"b\n".to_vec()),
},
change("img", Some("a\n"), Some("\0")),
],
3,
usize::MAX,
)
.unwrap();
assert_eq!(
diff,
"diff --git a/added b/added\n--- /dev/null\n+++ b/added\n@@ -0,0 +1 @@\n+a\n\
diff --git a/gone b/gone\n--- a/gone\n+++ /dev/null\n@@ -1 +0,0 @@\n-a\n\
diff --git a/old b/new\nrename from old\nrename to new\n--- a/old\n+++ b/new\n\
@@ -1 +1 @@\n-a\n+b\n\
diff --git a/img b/img\nBinary files a/img and b/img differ\n"
);
}
#[test]
fn a_wide_diff_over_the_limit_gives_way() {
let big = numbered(MAX_BYTES / 8, |i| format!("{i:07}"));
let edited = numbered(MAX_BYTES / 8, |i| format!("{i:07}x"));
let files = [change("big", Some(&big), Some(&edited))];
let reason = wide(&files).expect_err("over the limit");
assert!(reason.contains("over the"), "{reason}");
let small = [change("small", Some("a\n"), Some("b\n"))];
assert!(wide(&small).is_ok());
}
#[test]
fn rendering_stops_once_past_the_limit() {
let huge = numbered(MAX_BYTES / 2, |i| format!("{i:07}"));
let files = [change("huge", None, Some(&huge))];
let written = render(&files, CONTEXT_LINES, MAX_BYTES).expect_err("over the limit");
assert!(
written <= MAX_BYTES + "0000000\n".len(),
"{written} bytes rendered of a {}-byte file",
huge.len()
);
}
#[test]
fn more_files_than_the_limit_give_way() {
assert!(too_many_files(MAX_FILES).is_none());
assert!(too_many_files(MAX_FILES + 1).is_some());
}
}

View file

@ -0,0 +1,159 @@
//! The avatar of an agent's config repo, `agent-configs/<agent>`: the agent's
//! icon, so the repos are told apart in the forge's lists. The builder renders
//! the icon to a PNG when it builds the agent (the forge takes bitmaps), and
//! the controller sets it here; an agent whose icon is removed loses it, and the
//! forge shows its default again.
//!
//! The controller sets the avatar as the forge admin, which may edit any repo's.
//! A marker per repo under the state directory holds the fingerprint of the
//! image last set, so a build whose icon did not change makes no forge call, the
//! way [`super::service_avatars`] spares its uploads.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use base64::Engine as _;
use forgejo_api::structs::UpdateRepoAvatarOption;
use super::service_avatars::fingerprint;
use super::{Client, is_repo_not_found};
/// What a build's icon asks of the forge.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Step {
/// The avatar is as the icon wants it already.
Keep,
/// Upload the image, then record this fingerprint.
Set(String),
/// Delete the avatar we set, then forget the fingerprint.
Remove,
}
/// What to do for an icon: `png` is its rendering (`None` for an agent with no
/// icon), `last` the fingerprint of the image set before (`None` for none).
pub(crate) fn plan(last: Option<&str>, png: Option<&[u8]>) -> Step {
match (png, last) {
(Some(png), Some(last)) if fingerprint(png) == last => Step::Keep,
(Some(png), _) => Step::Set(fingerprint(png)),
(None, Some(_)) => Step::Remove,
(None, None) => Step::Keep,
}
}
/// Where `repo`'s marker lives.
fn marker(state_dir: &Path, repo: &str) -> PathBuf {
state_dir.join(format!("forge-repo-avatar-{repo}"))
}
impl Client {
/// Make `owner/repo`'s avatar the PNG `png`, or remove it for `None`, unless
/// that is what was set last. Done by the controller, as the forge admin.
///
/// # Errors
/// The forge refusing the upload or the delete; a marker that cannot be
/// written only costs a repeat call.
pub async fn sync_repo_avatar(
&self,
owner: &str,
repo: &str,
png: Option<&[u8]>,
) -> Result<()> {
let marker = marker(&crate::webhook::state_dir(), repo);
let seen = std::fs::read_to_string(&marker).ok();
match plan(seen.as_deref().map(str::trim), png) {
Step::Keep => Ok(()),
Step::Set(print) => {
let image =
base64::engine::general_purpose::STANDARD.encode(png.unwrap_or_default());
self.api
.call(|api| {
api.repo_update_avatar(
owner,
repo,
UpdateRepoAvatarOption {
image: Some(image.clone()),
},
)
.into_future()
})
.await
.with_context(|| format!("set the avatar of {owner}/{repo}"))?;
write_marker(&marker, &print);
tracing::info!(%owner, %repo, "repo avatar: set from the agent's icon");
Ok(())
}
Step::Remove => {
match self
.api
.call(|api| api.repo_delete_avatar(owner, repo).into_future())
.await
{
Ok(()) => {}
// The repo is gone, so its avatar is too.
Err(e) if is_repo_not_found(&e) => {}
Err(e) => {
return Err(e)
.with_context(|| format!("remove the avatar of {owner}/{repo}"));
}
}
if let Err(e) = std::fs::remove_file(&marker)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!(error = %e, marker = %marker.display(), "repo avatar: removed, but its marker could not be deleted");
}
tracing::info!(%owner, %repo, "repo avatar: removed with the agent's icon");
Ok(())
}
}
}
}
fn write_marker(marker: &Path, print: &str) {
if let Err(e) = std::fs::write(marker, print) {
tracing::warn!(error = %e, marker = %marker.display(), "repo avatar: set, but its marker could not be written");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_new_icon_is_set() {
let png = b"PNG one";
assert_eq!(plan(None, Some(png)), Step::Set(fingerprint(png)));
}
#[test]
fn the_same_icon_again_makes_no_call() {
let png = b"PNG one";
assert_eq!(plan(Some(&fingerprint(png)), Some(png)), Step::Keep);
}
#[test]
fn a_changed_icon_is_set_again() {
let (old, new) = (b"PNG one", b"PNG two");
assert_eq!(
plan(Some(&fingerprint(old)), Some(new)),
Step::Set(fingerprint(new))
);
}
/// Only an avatar the controller set is taken away: an agent that never had
/// an icon costs no delete on each build.
#[test]
fn a_removed_icon_removes_the_avatar_we_set_and_only_that() {
assert_eq!(plan(Some("abc"), None), Step::Remove);
assert_eq!(plan(None, None), Step::Keep);
}
#[test]
fn each_repo_has_its_own_marker() {
let dir = Path::new("/state");
assert_ne!(marker(dir, "atlas"), marker(dir, "argus"));
assert_eq!(
marker(dir, "atlas"),
Path::new("/state/forge-repo-avatar-atlas")
);
}
}

Some files were not shown because too many files have changed in this diff Show more