diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index 1714192d85..3527178c5a 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -719,6 +719,7 @@ dependencies = [ "fleet-dispatch", "fleet-dispatch-test", "fleet-laptop-agent", + "fleet-orgs", "fleet-proxy", "fleet-proxy-proto", "fleet-queue", @@ -820,6 +821,19 @@ dependencies = [ "sha2", ] +[[package]] +name = "fleet-orgs" +version = "0.1.0" +dependencies = [ + "fleet-config", + "fleet-secrets", + "libc", + "proptest", + "rusqlite", + "serde_json", + "ureq", +] + [[package]] name = "fleet-proxy" version = "0.1.0" diff --git a/pkgs/fleet/Cargo.toml b/pkgs/fleet/Cargo.toml index e208e6cb82..9ab0d993c3 100644 --- a/pkgs/fleet/Cargo.toml +++ b/pkgs/fleet/Cargo.toml @@ -30,6 +30,7 @@ members = [ "crates/fleet-agent", "crates/fleet-kv", "crates/fleet-cert", + "crates/fleet-orgs", "crates/fleet", ] resolver = "2" @@ -54,6 +55,7 @@ fleet-search = { path = "crates/fleet-search", default-features = false } fleet-bridge = { path = "crates/fleet-bridge" } fleet-agent = { path = "crates/fleet-agent" } fleet-cert = { path = "crates/fleet-cert" } +fleet-orgs = { path = "crates/fleet-orgs" } serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.11" diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index 46a2680abb..c1c8ebc727 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -304,8 +304,8 @@ and every build compiles it, so no build can know a domain another build forgot. The registered domains are `fleet queue`, `fleet serve`, `fleet proxy`, `fleet dispatch`, `fleet dispatch-test`, `fleet secrets`, `fleet gh`, `fleet bridge`, `fleet agent`, -`fleet shell`, `fleet search`, `fleet laptop-agent`, `fleet cert` and -`fleet actions`, and the +`fleet shell`, `fleet search`, `fleet laptop-agent`, `fleet cert`, +`fleet actions` and `fleet orgs`, and the laptop route forms (#13717): `fleet laptop` (tier T0, the generic tiered command), `fleet commander` (T1), `fleet http` (T2) and `fleet ssh` (T3), plus the diff --git a/pkgs/fleet/crates/fleet-orgs/Cargo.toml b/pkgs/fleet/crates/fleet-orgs/Cargo.toml new file mode 100644 index 0000000000..d9ed08c5e5 --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "fleet-orgs" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The `fleet orgs` domain: the Turso-backed org/App registry, synced from each GitHub App's own JWT (developing-today/code#8884)." + +[dependencies] +fleet-config = { workspace = true } +fleet-secrets = { workspace = true } +serde_json = { workspace = true } +# Pipe fd and fcntl for the App-key handoff to openssl (jwt.rs). +libc = "0.2" +# The GitHub API and Turso pipeline clients; the same ureq pin the +# fleet binary uses (rustls, no native-tls). +ureq = { version = "3", default-features = false, features = [ + "rustls", + "platform-verifier", +] } + +[dev-dependencies] +# The offline store: the same SQL runs against SQLite in tests, so the +# schema, upserts and sync run are exercised without a network. +rusqlite = { version = "0.42", features = ["bundled"] } +proptest = "1.12" diff --git a/pkgs/fleet/crates/fleet-orgs/src/cli.rs b/pkgs/fleet/crates/fleet-orgs/src/cli.rs new file mode 100644 index 0000000000..f3bd2a1725 --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/cli.rs @@ -0,0 +1,197 @@ +//! `fleet orgs`: `list` reads the Turso registry, `sync` refreshes it from +//! each App's JWT. Configuration: `FLEET_ORGS_TURSO_URL` (the database's +//! HTTP URL) and the token secret `turso.fleet-orgs-token`. + +use crate::github::HttpGitHub; +use crate::jwt::app_jwt; +use crate::list::{self, Filter}; +use crate::sql::Sql; +use crate::sync::{AppJwt, sync}; +use crate::turso::Turso; +use fleet_config::Config; +use fleet_secrets::Resolver; +use std::time::{SystemTime, UNIX_EPOCH}; + +const EXIT_OK: i32 = 0; +const EXIT_USAGE: i32 = 2; +const EXIT_UNAVAILABLE: i32 = 69; + +pub const ORGS_USAGE: &str = "\ +Usage: fleet orgs list [--app SLUG] [--org LOGIN] [--permission NAME[=LEVEL]] [--json] + fleet orgs sync + +list: the stored registry, one row per installation (org, App, +installation id, repository selection, permissions) and the last +successful sync time. --app matches the App's GitHub slug, --org the +account login, --permission a permission name (any level) or NAME=LEVEL. +--json prints the same rows as JSON. + +sync: records a sync run, then for each fleet App (app, devtoday, +backup) reads the App's own GET /app and GET /app/installations with +its JWT, every page, and upserts orgs, Apps and installations. An +installation GitHub no longer lists is removed. OAuth-token org reads +are never used for coverage. + +Store: FLEET_ORGS_TURSO_URL, token secret turso.fleet-orgs-token."; + +/// The fleet's Apps by fleet slug, as `gh`'s rotation names them, with +/// the secret holding each App's private key and, if not public, its ID. +const APPS: [(&str, &str, Option<&str>); 3] = [ + ("app", "github-app.developing-today-fleet.private-key", None), + ( + "devtoday", + "kaneo.github-app-private-key", + Some("kaneo.github-app-id"), + ), + ( + "backup", + "github-app.backup-private-key", + Some("github-app.backup-app-id"), + ), +]; +const FLEET_APP_ID: &str = "5612056"; +const TOKEN_SECRET: &str = "turso.fleet-orgs-token"; + +pub fn run(config: &Config, args: &[String]) -> i32 { + match args.first().map(String::as_str) { + Some("list") => match list_cmd(config, &args[1..]) { + Ok(out) => { + print!("{out}"); + EXIT_OK + } + Err(Failure::Usage(m)) => usage(&m), + Err(Failure::Unavailable(m)) => fail(EXIT_UNAVAILABLE, &m), + }, + Some("sync") if args.len() == 1 => match sync_cmd(config) { + Ok(line) => { + println!("{line}"); + EXIT_OK + } + Err(Failure::Usage(m)) => usage(&m), + Err(Failure::Unavailable(m)) => fail(EXIT_UNAVAILABLE, &m), + }, + Some("--help") | Some("-h") | None => { + println!("{ORGS_USAGE}"); + EXIT_OK + } + Some(other) => usage(&format!("unknown orgs command {other:?}")), + } +} + +enum Failure { + Usage(String), + Unavailable(String), +} + +fn usage(msg: &str) -> i32 { + eprintln!("error: {msg}\n\n{ORGS_USAGE}"); + EXIT_USAGE +} + +fn fail(code: i32, msg: &str) -> i32 { + eprintln!("error: {msg}"); + code +} + +fn store(config: &Config) -> Result { + let url = std::env::var("FLEET_ORGS_TURSO_URL") + .ok() + .filter(|u| !u.trim().is_empty()) + .ok_or_else(|| Failure::Unavailable("FLEET_ORGS_TURSO_URL is not set".into()))?; + let token = resolve(config, TOKEN_SECRET)?; + Ok(Turso::new(&url, &token)) +} + +fn resolve(config: &Config, name: &str) -> Result { + Resolver::default_chain(config) + .resolve(name) + .map(|v| v.expose().to_string()) + .map_err(|e| Failure::Unavailable(format!("secret '{name}' unresolved: {e}"))) +} + +fn list_cmd(config: &Config, args: &[String]) -> Result { + let mut filter = Filter::default(); + let mut json = false; + let mut it = args.iter(); + while let Some(arg) = it.next() { + let mut value = |flag: &str| { + it.next() + .cloned() + .ok_or_else(|| Failure::Usage(format!("{flag} needs a value"))) + }; + match arg.as_str() { + "--app" => filter.app = Some(value("--app")?), + "--org" => filter.org = Some(value("--org")?), + "--permission" => { + let raw = value("--permission")?; + filter.permission = Some(list::parse_permission(&raw).map_err(Failure::Usage)?); + } + "--json" => json = true, + other => return Err(Failure::Usage(format!("unknown option {other:?}"))), + } + } + let db = store(config)?; + let registry = list::load(&db).map_err(Failure::Unavailable)?; + let entries = list::filter(®istry.entries, &filter); + if json { + let body = list::render_json(®istry, &entries); + Ok(format!( + "{}\n", + serde_json::to_string_pretty(&body).unwrap_or_default() + )) + } else { + Ok(list::render_table(®istry, &entries)) + } +} + +fn sync_cmd(config: &Config) -> Result { + let db = store(config)?; + let source = SecretJwts { config }; + let gh = HttpGitHub::default(); + let apps: Vec<&str> = APPS.iter().map(|(slug, _, _)| *slug).collect(); + let clock = || { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) + }; + let report = + sync(&db as &dyn Sql, &gh, &source, &apps, &clock).map_err(Failure::Unavailable)?; + let parts: Vec = report + .apps + .iter() + .map(|(slug, n)| format!("{slug}={n}")) + .collect(); + Ok(format!( + "sync run {} ok: {}", + report.run_id, + parts.join(" ") + )) +} + +/// App JWTs minted from the broker's App keys (and IDs, where not public). +struct SecretJwts<'a> { + config: &'a Config, +} + +impl AppJwt for SecretJwts<'_> { + fn jwt(&self, app: &str) -> Result { + let (_, key_name, id_name) = APPS + .iter() + .find(|(slug, _, _)| *slug == app) + .ok_or_else(|| format!("unknown fleet app {app:?}"))?; + let app_id = match id_name { + None => std::env::var("FLEET_GH_APP_ID") + .ok() + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| FLEET_APP_ID.to_string()), + Some(name) => resolve(self.config, name) + .map_err(|_| format!("app id secret for {app} unresolved"))? + .trim() + .to_string(), + }; + let key = resolve(self.config, key_name) + .map_err(|_| format!("app key secret for {app} unresolved"))?; + app_jwt(&app_id, &key) + } +} diff --git a/pkgs/fleet/crates/fleet-orgs/src/github.rs b/pkgs/fleet/crates/fleet-orgs/src/github.rs new file mode 100644 index 0000000000..d4056a2022 --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/github.rs @@ -0,0 +1,293 @@ +//! GitHub's App endpoints, read with an App JWT only. Pages are followed +//! through the `Link` header until it names no `next`, never by counting. + +use crate::link::next_link; +use crate::sync::{AppMeta, GitHubApi, Installation}; +use serde_json::Value; + +pub const GITHUB_API: &str = "https://api.github.com"; + +/// Hard stop against a server that keeps naming a next page. +const MAX_PAGES: usize = 1000; + +/// Follow `Link: rel="next"` from `first` until the last page, returning +/// every page's items in order. +pub fn collect_pages(first: &str, mut fetch: F) -> Result, String> +where + F: FnMut(&str) -> Result<(Value, Option), String>, +{ + let mut items = Vec::new(); + let mut url = first.to_string(); + for _ in 0..MAX_PAGES { + let (page, next) = fetch(&url)?; + match page { + Value::Array(list) => items.extend(list), + _ => return Err("paginated body is not an array".to_string()), + } + match next { + Some(n) => url = n, + None => return Ok(items), + } + } + Err(format!("more than {MAX_PAGES} pages; refusing to continue")) +} + +pub fn parse_app(body: &Value) -> Result { + let slug = body + .get("slug") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .ok_or("GET /app: no slug")?; + Ok(AppMeta { + slug: slug.to_string(), + app_id: body + .get("id") + .and_then(Value::as_i64) + .ok_or("GET /app: no id")?, + name: body + .get("name") + .and_then(Value::as_str) + .unwrap_or(slug) + .to_string(), + owner: body + .get("owner") + .and_then(|o| o.get("login")) + .and_then(Value::as_str) + .unwrap_or("") + .to_string(), + permissions: body + .get("permissions") + .cloned() + .unwrap_or(Value::Object(Default::default())), + events: body + .get("events") + .cloned() + .unwrap_or(Value::Array(Vec::new())), + }) +} + +pub fn parse_installation(entry: &Value) -> Option { + let account = entry.get("account")?; + Some(Installation { + installation_id: entry.get("id").and_then(Value::as_i64)?, + account_login: account.get("login").and_then(Value::as_str)?.to_string(), + account_type: account + .get("type") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(), + repository_selection: entry + .get("repository_selection") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(), + permissions: entry + .get("permissions") + .cloned() + .unwrap_or(Value::Object(Default::default())), + }) +} + +/// The live client: ureq over the GitHub REST API. +pub struct HttpGitHub { + agent: ureq::Agent, + base: String, +} + +impl Default for HttpGitHub { + fn default() -> Self { + Self::new(GITHUB_API) + } +} + +impl HttpGitHub { + pub fn new(base: &str) -> Self { + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(std::time::Duration::from_secs(60))) + .timeout_connect(Some(std::time::Duration::from_secs(10))) + .http_status_as_error(false) + .tls_config( + ureq::tls::TlsConfig::builder() + .root_certs(ureq::tls::RootCerts::PlatformVerifier) + .build(), + ) + .build() + .into(); + HttpGitHub { + agent, + base: base.trim_end_matches('/').to_string(), + } + } + + fn get(&self, jwt: &str, url: &str) -> Result<(Value, Option), String> { + let mut resp = self + .agent + .get(url) + .header("Authorization", &format!("Bearer {jwt}")) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .header("User-Agent", "fleet-orgs") + .call() + .map_err(|e| format!("github transport error: {e}"))?; + let status = resp.status().as_u16(); + let next = resp + .headers() + .get("link") + .and_then(|v| v.to_str().ok()) + .and_then(next_link); + let text = resp + .body_mut() + .read_to_string() + .map_err(|e| format!("github body read error: {e}"))?; + if status != 200 { + return Err(format!("GET {url}: HTTP {status}")); + } + let body = + serde_json::from_str(&text).map_err(|_| format!("GET {url}: unparseable body"))?; + Ok((body, next)) + } +} + +impl GitHubApi for HttpGitHub { + fn app(&self, jwt: &str) -> Result { + let (body, _) = self.get(jwt, &format!("{}/app", self.base))?; + parse_app(&body) + } + + fn installations(&self, jwt: &str) -> Result, String> { + let first = format!("{}/app/installations?per_page=100", self.base); + let entries = collect_pages(&first, |url| self.get(jwt, url))?; + entries + .iter() + .map(|e| { + parse_installation(e).ok_or_else(|| "installation entry missing fields".to_string()) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn follows_every_link_page_in_order() { + let pages = |url: &str| -> Result<(Value, Option), String> { + match url { + "p1" => Ok((json!([{"id": 1}]), Some("p2".into()))), + "p2" => Ok((json!([{"id": 2}]), Some("p3".into()))), + "p3" => Ok((json!([{"id": 3}]), None)), + other => Err(format!("unexpected {other}")), + } + }; + let items = collect_pages("p1", pages).unwrap(); + let ids: Vec = items.iter().map(|v| v["id"].as_i64().unwrap()).collect(); + assert_eq!(ids, vec![1, 2, 3]); + } + + #[test] + fn a_non_array_page_is_an_error() { + let r = collect_pages("p1", |_| Ok((json!({"total_count": 0}), None))); + assert!(r.is_err()); + } + + #[test] + fn parses_an_installation_with_its_permissions() { + let entry = json!({ + "id": 42, + "account": {"login": "acme", "type": "Organization"}, + "repository_selection": "all", + "permissions": {"contents": "write", "issues": "read"} + }); + let inst = parse_installation(&entry).unwrap(); + assert_eq!(inst.installation_id, 42); + assert_eq!(inst.account_login, "acme"); + assert_eq!(inst.account_type, "Organization"); + assert_eq!(inst.permissions["contents"], "write"); + } + + #[test] + fn parses_app_identity_permissions_events_and_owner() { + let app = parse_app(&json!({ + "slug": "fleet-app", + "id": 42, + "name": "Fleet App", + "owner": {"login": "developing-today"}, + "permissions": {"contents": "write"}, + "events": ["push"] + })) + .unwrap(); + assert_eq!(app.slug, "fleet-app"); + assert_eq!(app.owner, "developing-today"); + assert_eq!(app.permissions["contents"], "write"); + assert_eq!(app.events, json!(["push"])); + } + + #[test] + fn an_entry_without_an_id_or_account_is_skipped_as_invalid() { + assert!(parse_installation(&json!({"id": 1})).is_none()); + assert!(parse_installation(&json!({"account": {"login": "a"}})).is_none()); + } + + #[test] + fn regression_2026_11_12_app_jwt_listing_recovers_33_oauth_false_negatives() { + use std::io::{Read, Write}; + use std::net::TcpListener; + use std::thread; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = thread::spawn(move || { + for page in 1..=2 { + let (mut stream, _) = listener.accept().unwrap(); + let mut request = [0; 4096]; + let n = stream.read(&mut request).unwrap(); + let request = String::from_utf8_lossy(&request[..n]); + let first = request.lines().next().unwrap(); + assert!(first.starts_with("GET ")); + assert!(first.contains("/app/installations?per_page=100")); + assert!( + request + .to_ascii_lowercase() + .contains("authorization: bearer app-jwt") + ); + let values: Vec = (0..if page == 1 { 32 } else { 1 }) + .map(|i| json!({ + "id": (page - 1) * 32 + i + 1, + "account": {"login": format!("org{}", (page - 1) * 32 + i + 1), "type": "Organization"}, + "repository_selection": "all", + "permissions": {"contents": "read"} + })) + .collect(); + let body = serde_json::to_string(&values).unwrap(); + let link = if page == 1 { + format!( + "Link: ; rel=\"next\"\r\n" + ) + } else { + String::new() + }; + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n{link}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .unwrap(); + } + }); + + let github = HttpGitHub::new(&format!("http://{addr}")); + let installations = github.installations("app-jwt").unwrap(); + server.join().unwrap(); + // The 2026-11-12 incident had 33 installations omitted by the OAuth + // organization-installation path. This fixture models that oracle: + // the App-JWT endpoint returns all 33 across pages; OAuth is never used. + assert_eq!( + installations.len(), + 33, + "oracle: all 33 installations absent from the OAuth false-negative result are covered" + ); + assert_eq!(installations[32].account_login, "org33"); + } +} diff --git a/pkgs/fleet/crates/fleet-orgs/src/jwt.rs b/pkgs/fleet/crates/fleet-orgs/src/jwt.rs new file mode 100644 index 0000000000..7725578fe1 --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/jwt.rs @@ -0,0 +1,104 @@ +//! App JWTs (RS256). The private key reaches `openssl dgst` on an inherited +//! pipe fd, never a file, argv or the environment; only the signature +//! touches it. The same construction as the gh domain's minter. + +use std::io::Write; +use std::process::{Command, Stdio}; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub fn app_jwt(app_id: &str, key_pem: &str) -> Result { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|_| "system clock before epoch".to_string())? + .as_secs(); + let header = base64url(br#"{"alg":"RS256","typ":"JWT"}"#); + let payload = base64url( + format!( + "{{\"iat\":{},\"exp\":{},\"iss\":\"{}\"}}", + now.saturating_sub(60), + now + 540, + app_id + ) + .as_bytes(), + ); + let signing_input = format!("{header}.{payload}"); + let signature = rs256_sign(key_pem.as_bytes(), signing_input.as_bytes())?; + Ok(format!("{signing_input}.{}", base64url(&signature))) +} + +fn rs256_sign(key_pem: &[u8], data: &[u8]) -> Result, String> { + use std::os::unix::io::AsRawFd; + use std::os::unix::process::CommandExt; + let (reader, mut writer) = std::io::pipe().map_err(|e| format!("openssl sign: pipe: {e}"))?; + // The key is ~1.7 KB, far under the pipe buffer, so this write + // completes before the child starts and cannot deadlock. + writer + .write_all(key_pem) + .map_err(|_| "openssl sign: key pipe write failed".to_string())?; + drop(writer); + let key_arg = format!("/dev/fd/{}", reader.as_raw_fd()); + let mut cmd = Command::new("openssl"); + cmd.args(["dgst", "-sha256", "-sign", &key_arg]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let fd = reader.as_raw_fd(); + // SAFETY: runs in the forked child before exec; only clears CLOEXEC on + // the key pipe so `openssl` can open it through /dev/fd. + unsafe { + cmd.pre_exec(move || { + let flags = libc::fcntl(fd, libc::F_GETFD); + if flags < 0 || libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let mut child = cmd + .spawn() + .map_err(|e| format!("openssl sign: spawn failed: {e}"))?; + drop(reader); + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(data); + } + let out = child + .wait_with_output() + .map_err(|e| format!("openssl sign: wait failed: {e}"))?; + if !out.status.success() { + return Err("openssl sign: signing failed (key shape?)".to_string()); + } + Ok(out.stdout) +} + +/// base64url without padding (RFC 7515). +pub fn base64url(data: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for chunk in data.chunks(3) { + let b = [ + chunk[0], + *chunk.get(1).unwrap_or(&0), + *chunk.get(2).unwrap_or(&0), + ]; + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + for i in 0..=chunk.len() { + out.push(ALPHABET[((n >> (18 - 6 * i)) & 0x3f) as usize] as char); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base64url_rfc4648_vectors() { + assert_eq!(base64url(b""), ""); + assert_eq!(base64url(b"f"), "Zg"); + assert_eq!(base64url(b"fo"), "Zm8"); + assert_eq!(base64url(b"foo"), "Zm9v"); + assert_eq!(base64url(b"foob"), "Zm9vYg"); + assert_eq!(base64url(&[0xfb, 0xff]), "-_8"); + } +} diff --git a/pkgs/fleet/crates/fleet-orgs/src/lib.rs b/pkgs/fleet/crates/fleet-orgs/src/lib.rs new file mode 100644 index 0000000000..122dd36118 --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/lib.rs @@ -0,0 +1,19 @@ +//! The `fleet orgs` domain (developing-today/code#8884): a registry of +//! GitHub organisations, the fleet Apps and their installations, kept +//! in Turso and regenerated from each App's own JWT. +//! +//! Coverage is never read through an OAuth token: `GET /app` and +//! `GET /app/installations` answer for the App itself, paginated by +//! their `Link` headers, so a sync sees every installation. + +pub mod cli; +pub mod github; +pub mod jwt; +pub mod link; +pub mod list; +pub mod schema; +pub mod sql; +pub mod sync; +pub mod turso; + +pub use cli::run; diff --git a/pkgs/fleet/crates/fleet-orgs/src/link.rs b/pkgs/fleet/crates/fleet-orgs/src/link.rs new file mode 100644 index 0000000000..b731311906 --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/link.rs @@ -0,0 +1,37 @@ +//! RFC 8288 `Link` header parsing for GitHub's pagination. + +/// The `rel="next"` target of a `Link` header, if there is one. +pub fn next_link(header: &str) -> Option { + header.split(',').find_map(|part| { + let mut pieces = part.split(';'); + let target = pieces.next()?.trim(); + let url = target.strip_prefix('<')?.strip_suffix('>')?; + pieces + .any(|p| { + let p = p.trim(); + p == r#"rel="next""# || p == "rel=next" + }) + .then(|| url.to_string()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_next_among_other_rels() { + let h = r#"; rel="next", ; rel="last""#; + assert_eq!( + next_link(h).as_deref(), + Some("https://api.github.com/app/installations?per_page=100&page=3") + ); + } + + #[test] + fn last_page_has_no_next() { + let h = r#"; rel="prev", ; rel="first""#; + assert_eq!(next_link(h), None); + assert_eq!(next_link(""), None); + } +} diff --git a/pkgs/fleet/crates/fleet-orgs/src/list.rs b/pkgs/fleet/crates/fleet-orgs/src/list.rs new file mode 100644 index 0000000000..c6b8f37bba --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/list.rs @@ -0,0 +1,291 @@ +//! `fleet orgs list`: the registry read back, one row per installation, +//! with the filters and the last successful sync time. + +use crate::sql::Sql; +use serde_json::{Value, json}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Entry { + pub org: String, + pub app: String, + pub installation_id: i64, + pub repository_selection: String, + /// `(permission name, access level)`, sorted by name. + pub permissions: Vec<(String, String)>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Registry { + /// `finished_at` of the latest successful sync, Unix seconds. + pub last_sync: Option, + pub entries: Vec, +} + +/// `--permission NAME` matches any level; `NAME=LEVEL` matches that level. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Filter { + pub app: Option, + pub org: Option, + pub permission: Option<(String, Option)>, +} + +pub fn parse_permission(raw: &str) -> Result<(String, Option), String> { + match raw.split_once('=') { + Some((name, level)) if !name.is_empty() && !level.is_empty() => { + Ok((name.to_string(), Some(level.to_string()))) + } + None if !raw.is_empty() => Ok((raw.to_string(), None)), + _ => Err(format!("--permission {raw:?}: expected NAME or NAME=LEVEL")), + } +} + +pub fn load(db: &dyn Sql) -> Result { + let rows = db.execute( + "SELECT i.account_login, i.app_slug, i.installation_id, i.repository_selection, + i.permissions, + (SELECT MAX(finished_at) FROM sync_runs WHERE status = 'ok') + FROM installations i + ORDER BY i.account_login, i.app_slug", + &[], + )?; + let mut last_sync = None; + let mut entries = Vec::new(); + for row in rows.rows { + let text = |i: usize| row.get(i).and_then(Value::as_str).unwrap_or("").to_string(); + let perms: Value = serde_json::from_str(&text(4)).unwrap_or(Value::Null); + let mut permissions: Vec<(String, String)> = perms + .as_object() + .map(|o| { + o.iter() + .map(|(k, v)| (k.clone(), v.as_str().unwrap_or("").to_string())) + .collect() + }) + .unwrap_or_default(); + permissions.sort(); + last_sync = last_sync.or(row.get(5).and_then(Value::as_i64)); + entries.push(Entry { + org: text(0), + app: text(1), + installation_id: row.get(2).and_then(Value::as_i64).unwrap_or(0), + repository_selection: text(3), + permissions, + }); + } + Ok(Registry { last_sync, entries }) +} + +pub fn filter(entries: &[Entry], f: &Filter) -> Vec { + entries + .iter() + .filter(|e| f.app.as_ref().is_none_or(|a| &e.app == a)) + .filter(|e| f.org.as_ref().is_none_or(|o| &e.org == o)) + .filter(|e| match &f.permission { + None => true, + Some((name, level)) => e + .permissions + .iter() + .any(|(k, v)| k == name && level.as_ref().is_none_or(|l| l == v)), + }) + .cloned() + .collect() +} + +fn perms_text(perms: &[(String, String)]) -> String { + if perms.is_empty() { + return "-".to_string(); + } + perms + .iter() + .map(|(k, v)| format!("{k}:{v}")) + .collect::>() + .join(",") +} + +fn sync_text(last: Option) -> String { + match last { + Some(secs) => rfc3339(secs), + None => "never".to_string(), + } +} + +pub fn render_table(reg: &Registry, entries: &[Entry]) -> String { + let header = ["ORG", "APP", "INSTALLATION", "SELECTION", "PERMISSIONS"]; + let body: Vec<[String; 5]> = entries + .iter() + .map(|e| { + [ + e.org.clone(), + e.app.clone(), + e.installation_id.to_string(), + e.repository_selection.clone(), + perms_text(&e.permissions), + ] + }) + .collect(); + let mut widths = header.map(str::len); + for row in &body { + for (w, cell) in widths.iter_mut().zip(row) { + *w = (*w).max(cell.len()); + } + } + let line = |cells: &[String]| { + cells + .iter() + .zip(&widths) + .map(|(c, w)| format!("{c:>() + .join(" ") + .trim_end() + .to_string() + }; + let mut out = String::new(); + out.push_str(&line(&header.map(str::to_string))); + out.push('\n'); + for row in &body { + out.push_str(&line(row)); + out.push('\n'); + } + out.push_str(&format!( + "{} installation(s); last sync: {}\n", + entries.len(), + sync_text(reg.last_sync) + )); + out +} + +pub fn render_json(reg: &Registry, entries: &[Entry]) -> Value { + json!({ + "last_sync": reg.last_sync.map(rfc3339), + "installations": entries.iter().map(|e| json!({ + "org": e.org, + "app": e.app, + "installation_id": e.installation_id, + "repository_selection": e.repository_selection, + "permissions": e.permissions.iter() + .map(|(k, v)| (k.clone(), Value::String(v.clone()))) + .collect::>(), + })).collect::>(), + }) +} + +/// RFC 3339 UTC for Unix seconds (civil-from-days, no dependency). +pub fn rfc3339(secs: i64) -> String { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + rem % 3600 / 60, + rem % 60 + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rfc3339_known_instants() { + assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z"); + assert_eq!(rfc3339(86_400 * 365), "1971-01-01T00:00:00Z"); + assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z"); + } + + #[test] + fn permission_spec_forms() { + assert_eq!( + parse_permission("contents").unwrap(), + ("contents".into(), None) + ); + assert_eq!( + parse_permission("contents=write").unwrap(), + ("contents".into(), Some("write".into())) + ); + assert!(parse_permission("").is_err()); + assert!(parse_permission("=write").is_err()); + assert!(parse_permission("contents=").is_err()); + } + + fn entry(org: &str, app: &str, perms: &[(&str, &str)]) -> Entry { + Entry { + org: org.into(), + app: app.into(), + installation_id: 1, + repository_selection: "all".into(), + permissions: perms + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + } + } + + #[test] + fn filters_compose() { + let all = vec![ + entry("acme", "app", &[("contents", "write")]), + entry("acme", "backup", &[("contents", "read")]), + entry("beta", "app", &[("issues", "write")]), + ]; + let by = |f: Filter| filter(&all, &f).len(); + assert_eq!(by(Filter::default()), 3); + assert_eq!( + by(Filter { + app: Some("app".into()), + ..Default::default() + }), + 2 + ); + assert_eq!( + by(Filter { + org: Some("acme".into()), + ..Default::default() + }), + 2 + ); + assert_eq!( + by(Filter { + permission: Some(("contents".into(), Some("write".into()))), + ..Default::default() + }), + 1 + ); + assert_eq!( + by(Filter { + permission: Some(("contents".into(), None)), + ..Default::default() + }), + 2 + ); + assert_eq!( + by(Filter { + org: Some("acme".into()), + app: Some("app".into()), + permission: Some(("issues".into(), None)), + }), + 0 + ); + } + + #[test] + fn table_and_json_carry_last_sync() { + let reg = Registry { + last_sync: Some(0), + entries: vec![entry("acme", "app", &[("contents", "write")])], + }; + let table = render_table(®, ®.entries); + assert!(table.contains("contents:write")); + assert!(table.ends_with("last sync: 1970-01-01T00:00:00Z\n")); + let json = render_json(®, ®.entries); + assert_eq!(json["last_sync"], "1970-01-01T00:00:00Z"); + assert_eq!(json["installations"][0]["permissions"]["contents"], "write"); + } +} diff --git a/pkgs/fleet/crates/fleet-orgs/src/schema.rs b/pkgs/fleet/crates/fleet-orgs/src/schema.rs new file mode 100644 index 0000000000..682112b6f1 --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/schema.rs @@ -0,0 +1,86 @@ +//! The registry's tables and their upserts. Every statement is safe to +//! run again: `CREATE ... IF NOT EXISTS` for the schema, `ON CONFLICT ... +//! DO UPDATE` for the rows, so a re-sync rewrites the same keys. + +use crate::sql::Sql; + +pub const SCHEMA: &[&str] = &[ + "CREATE TABLE IF NOT EXISTS sync_runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + started_at INTEGER NOT NULL, + finished_at INTEGER, + status TEXT NOT NULL, + installations INTEGER, + error TEXT + )", + "CREATE TABLE IF NOT EXISTS apps ( + slug TEXT PRIMARY KEY, + app_id INTEGER NOT NULL, + name TEXT NOT NULL, + owner TEXT NOT NULL, + permissions TEXT NOT NULL, + events TEXT NOT NULL, + verified_at INTEGER NOT NULL + )", + "CREATE TABLE IF NOT EXISTS orgs ( + login TEXT PRIMARY KEY, + role TEXT, + repo_count INTEGER, + verified_at INTEGER NOT NULL + )", + "CREATE TABLE IF NOT EXISTS installations ( + app_slug TEXT NOT NULL, + installation_id INTEGER NOT NULL, + account_login TEXT NOT NULL, + account_type TEXT NOT NULL, + repository_selection TEXT NOT NULL, + permissions TEXT NOT NULL, + sync_run_id INTEGER NOT NULL, + verified_at INTEGER NOT NULL, + PRIMARY KEY (app_slug, account_login) + )", +]; + +pub const START_RUN: &str = + "INSERT INTO sync_runs (started_at, status) VALUES (?, 'running') RETURNING id"; + +pub const FINISH_RUN: &str = + "UPDATE sync_runs SET finished_at = ?, status = ?, installations = ?, error = ? WHERE id = ?"; + +pub const UPSERT_APP: &str = + "INSERT INTO apps (slug, app_id, name, owner, permissions, events, verified_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (slug) DO UPDATE SET + app_id = excluded.app_id, + name = excluded.name, + owner = excluded.owner, + permissions = excluded.permissions, + events = excluded.events, + verified_at = excluded.verified_at"; + +pub const UPSERT_ORG: &str = + "INSERT INTO orgs (login, role, repo_count, verified_at) VALUES (?, NULL, NULL, ?) + ON CONFLICT (login) DO UPDATE SET verified_at = excluded.verified_at"; + +pub const UPSERT_INSTALLATION: &str = "INSERT INTO installations + (app_slug, installation_id, account_login, account_type, repository_selection, + permissions, sync_run_id, verified_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (app_slug, account_login) DO UPDATE SET + account_login = excluded.account_login, + installation_id = excluded.installation_id, + account_type = excluded.account_type, + repository_selection = excluded.repository_selection, + permissions = excluded.permissions, + sync_run_id = excluded.sync_run_id, + verified_at = excluded.verified_at"; + +/// Installations of one App that this run did not see: removed on GitHub. +pub const PRUNE_STALE: &str = "DELETE FROM installations WHERE app_slug = ? AND sync_run_id <> ?"; + +pub fn migrate(db: &dyn Sql) -> Result<(), String> { + for stmt in SCHEMA { + db.execute(stmt, &[])?; + } + Ok(()) +} diff --git a/pkgs/fleet/crates/fleet-orgs/src/sql.rs b/pkgs/fleet/crates/fleet-orgs/src/sql.rs new file mode 100644 index 0000000000..4ba84b72fb --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/sql.rs @@ -0,0 +1,14 @@ +//! The storage seam: one statement at a time, with JSON-typed +//! arguments and rows. Turso answers over HTTP ([`crate::turso`]); +//! tests answer from SQLite. + +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq)] +pub struct Rows { + pub rows: Vec>, +} + +pub trait Sql { + fn execute(&self, sql: &str, args: &[Value]) -> Result; +} diff --git a/pkgs/fleet/crates/fleet-orgs/src/sync.rs b/pkgs/fleet/crates/fleet-orgs/src/sync.rs new file mode 100644 index 0000000000..689c779cca --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/sync.rs @@ -0,0 +1,167 @@ +//! One sync run: each App's own metadata and installations, written into +//! the registry. A run is recorded in `sync_runs` before any write and +//! closed as `ok` or `failed`; a failed App is never pruned. + +use crate::schema::{ + FINISH_RUN, PRUNE_STALE, START_RUN, UPSERT_APP, UPSERT_INSTALLATION, UPSERT_ORG, migrate, +}; +use crate::sql::Sql; +use serde_json::{Value, json}; + +#[derive(Debug, Clone, PartialEq)] +pub struct AppMeta { + pub slug: String, + pub app_id: i64, + pub name: String, + pub owner: String, + pub permissions: Value, + pub events: Value, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Installation { + pub installation_id: i64, + pub account_login: String, + pub account_type: String, + pub repository_selection: String, + pub permissions: Value, +} + +/// The App-scoped reads. The live client is [`crate::github::HttpGitHub`]. +pub trait GitHubApi { + fn app(&self, jwt: &str) -> Result; + fn installations(&self, jwt: &str) -> Result, String>; +} + +/// A short-lived App JWT for one App, named by its fleet slug. +pub trait AppJwt { + fn jwt(&self, app: &str) -> Result; +} + +#[derive(Debug, Clone, PartialEq)] +pub struct SyncReport { + pub run_id: i64, + /// `(app slug, installations written)` per App, in sync order. + pub apps: Vec<(String, usize)>, +} + +pub fn sync( + db: &dyn Sql, + gh: &dyn GitHubApi, + jwts: &dyn AppJwt, + apps: &[&str], + clock: &dyn Fn() -> i64, +) -> Result { + migrate(db)?; + let run_id = start_run(db, clock())?; + match sync_apps(db, gh, jwts, apps, clock, run_id) { + Ok(report) => { + let total: usize = report.apps.iter().map(|(_, n)| n).sum(); + finish_run(db, run_id, clock(), "ok", Some(total as i64), None)?; + Ok(report) + } + Err(e) => { + finish_run(db, run_id, clock(), "failed", None, Some(&e))?; + Err(e) + } + } +} + +fn sync_apps( + db: &dyn Sql, + gh: &dyn GitHubApi, + jwts: &dyn AppJwt, + apps: &[&str], + clock: &dyn Fn() -> i64, + run_id: i64, +) -> Result { + let mut report = SyncReport { + run_id, + apps: Vec::new(), + }; + for app in apps { + let jwt = jwts.jwt(app)?; + let meta = gh.app(&jwt)?; + let installs = gh.installations(&jwt)?; + let now = clock(); + write_app(db, &meta, now)?; + for inst in &installs { + write_installation(db, &meta.slug, inst, run_id, now)?; + } + db.execute(PRUNE_STALE, &[json!(meta.slug), json!(run_id)])?; + report.apps.push((meta.slug, installs.len())); + } + Ok(report) +} + +fn start_run(db: &dyn Sql, now: i64) -> Result { + let rows = db.execute(START_RUN, &[json!(now)])?; + rows.rows + .first() + .and_then(|r| r.first()) + .and_then(Value::as_i64) + .ok_or_else(|| "sync_runs: no id returned".to_string()) +} + +fn finish_run( + db: &dyn Sql, + run_id: i64, + finished: i64, + status: &str, + installations: Option, + error: Option<&str>, +) -> Result<(), String> { + db.execute( + FINISH_RUN, + &[ + json!(finished), + json!(status), + installations.map_or(Value::Null, Value::from), + error.map_or(Value::Null, Value::from), + json!(run_id), + ], + )?; + Ok(()) +} + +fn write_app(db: &dyn Sql, meta: &AppMeta, now: i64) -> Result<(), String> { + db.execute( + UPSERT_APP, + &[ + json!(meta.slug), + json!(meta.app_id), + json!(meta.name), + json!(meta.owner), + json!(meta.permissions.to_string()), + json!(meta.events.to_string()), + json!(now), + ], + )?; + Ok(()) +} + +fn write_installation( + db: &dyn Sql, + app: &str, + inst: &Installation, + run_id: i64, + now: i64, +) -> Result<(), String> { + db.execute( + UPSERT_INSTALLATION, + &[ + json!(app), + json!(inst.installation_id), + json!(inst.account_login), + json!(inst.account_type), + json!(inst.repository_selection), + json!(inst.permissions.to_string()), + json!(run_id), + json!(now), + ], + )?; + if inst.account_type == "Organization" { + db.execute(UPSERT_ORG, &[json!(inst.account_login), json!(now)])?; + } + Ok(()) +} diff --git a/pkgs/fleet/crates/fleet-orgs/src/turso.rs b/pkgs/fleet/crates/fleet-orgs/src/turso.rs new file mode 100644 index 0000000000..deb877862b --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/src/turso.rs @@ -0,0 +1,169 @@ +//! The Turso store over its HTTP pipeline (`POST /v2/pipeline`), one +//! execute per request. + +use crate::sql::{Rows, Sql}; +use serde_json::{Value, json}; + +pub struct Turso { + url: String, + token: String, + agent: ureq::Agent, +} + +impl Turso { + pub fn new(url: &str, token: &str) -> Turso { + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(std::time::Duration::from_secs(60))) + .http_status_as_error(false) + .tls_config( + ureq::tls::TlsConfig::builder() + .root_certs(ureq::tls::RootCerts::PlatformVerifier) + .build(), + ) + .build() + .into(); + Turso { + url: url.trim_end_matches('/').to_string(), + token: token.to_string(), + agent, + } + } +} + +/// JSON argument → Turso typed argument. +pub fn arg_json(v: &Value) -> Value { + match v { + Value::Null => json!({"type": "null"}), + Value::Bool(b) => json!({"type": "integer", "value": if *b { "1" } else { "0" }}), + Value::Number(n) if n.is_i64() => json!({"type": "integer", "value": n.to_string()}), + Value::Number(n) => json!({"type": "float", "value": n.as_f64().unwrap_or(0.0)}), + Value::String(s) => json!({"type": "text", "value": s}), + other => json!({"type": "text", "value": other.to_string()}), + } +} + +pub fn pipeline_body(sql: &str, args: &[Value]) -> Value { + json!({ + "requests": [ + {"type": "execute", "stmt": { + "sql": sql, + "args": args.iter().map(arg_json).collect::>(), + }}, + {"type": "close"} + ] + }) +} + +fn cell_to_json(cell: &Value) -> Value { + let raw = cell.get("value"); + match cell.get("type").and_then(Value::as_str).unwrap_or("null") { + "text" => raw + .and_then(Value::as_str) + .map_or(Value::Null, |s| json!(s)), + "integer" => raw + .and_then(Value::as_str) + .and_then(|s| s.parse::().ok()) + .map_or(Value::Null, |n| json!(n)), + "float" => raw + .and_then(Value::as_f64) + .and_then(serde_json::Number::from_f64) + .map_or(Value::Null, Value::Number), + _ => Value::Null, + } +} + +/// The first execute result of a pipeline response. A per-request error +/// or a missing `ok` result is a failure, never an empty result set. +pub fn parse_rows(body: &Value) -> Result { + if let Some(err) = body.get("error") { + return Err(format!("Turso request failed: {err}")); + } + let first = body + .get("results") + .and_then(Value::as_array) + .and_then(|r| r.first()) + .ok_or("Turso answered without results")?; + if first.get("type").and_then(Value::as_str) != Some("ok") { + return Err(format!("Turso statement failed: {}", first)); + } + let result = first + .pointer("/response/result") + .ok_or("Turso execute result missing")?; + let rows = result + .get("rows") + .and_then(Value::as_array) + .ok_or("Turso execute result has no rows array")? + .iter() + .map(|row| { + row.as_array() + .map(|cells| cells.iter().map(cell_to_json).collect()) + .unwrap_or_default() + }) + .collect(); + Ok(Rows { rows }) +} + +impl Sql for Turso { + fn execute(&self, sql: &str, args: &[Value]) -> Result { + let url = format!("{}/v2/pipeline", self.url); + let body = serde_json::to_string(&pipeline_body(sql, args)).map_err(|e| e.to_string())?; + let mut resp = self + .agent + .post(&url) + .header("Authorization", &format!("Bearer {}", self.token)) + .header("Content-Type", "application/json") + .send(body.as_str()) + .map_err(|e| format!("Turso store unreachable: {e}"))?; + let status = resp.status().as_u16(); + let text = resp + .body_mut() + .read_to_string() + .map_err(|e| format!("cannot read Turso response: {e}"))?; + if !(200..300).contains(&status) { + let snippet: String = text.chars().take(300).collect(); + return Err(format!("Turso store HTTP {status}: {snippet}")); + } + let parsed: Value = + serde_json::from_str(&text).map_err(|e| format!("Turso non-JSON body: {e}"))?; + parse_rows(&parsed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn typed_args() { + assert_eq!(arg_json(&json!("x")), json!({"type": "text", "value": "x"})); + assert_eq!( + arg_json(&json!(7)), + json!({"type": "integer", "value": "7"}) + ); + assert_eq!(arg_json(&Value::Null), json!({"type": "null"})); + } + + #[test] + fn parses_typed_rows() { + let body = json!({"results": [ + {"type": "ok", "response": {"type": "execute", "result": { + "cols": [], "rows": [[ + {"type": "text", "value": "acme"}, + {"type": "integer", "value": "42"}, + {"type": "null"} + ]] + }}}, + {"type": "ok", "response": {"type": "close"}} + ]}); + let rows = parse_rows(&body).unwrap(); + assert_eq!(rows.rows, vec![vec![json!("acme"), json!(42), Value::Null]]); + } + + #[test] + fn failures_are_errors_not_empty_results() { + assert!(parse_rows(&json!({"error": "boom"})).is_err()); + let per_request = + json!({"results": [{"type": "error", "error": {"message": "no such table"}}]}); + assert!(parse_rows(&per_request).is_err()); + } +} diff --git a/pkgs/fleet/crates/fleet-orgs/tests/registry.rs b/pkgs/fleet/crates/fleet-orgs/tests/registry.rs new file mode 100644 index 0000000000..7d311f649f --- /dev/null +++ b/pkgs/fleet/crates/fleet-orgs/tests/registry.rs @@ -0,0 +1,380 @@ +//! Offline registry tests: the real schema and SQL against in-memory +//! SQLite, a fake GitHub, and fake App JWTs. No network. + +use fleet_orgs::github::{collect_pages, parse_installation}; +use fleet_orgs::list::{self, Filter}; +use fleet_orgs::sql::{Rows, Sql}; +use fleet_orgs::sync::{AppJwt, AppMeta, GitHubApi, Installation, sync}; +use proptest::prelude::*; +use rusqlite::{Connection, types::ValueRef}; +use serde_json::{Value, json}; +use std::cell::{Cell, RefCell}; +use std::collections::BTreeMap; + +struct Sqlite(RefCell); + +impl Sqlite { + fn memory() -> Sqlite { + Sqlite(RefCell::new(Connection::open_in_memory().unwrap())) + } +} + +impl Sql for Sqlite { + fn execute(&self, sql: &str, args: &[Value]) -> Result { + let conn = self.0.borrow(); + let params: Vec = args + .iter() + .map(|a| match a { + Value::Null => rusqlite::types::Value::Null, + Value::Number(n) => rusqlite::types::Value::Integer(n.as_i64().unwrap()), + Value::String(s) => rusqlite::types::Value::Text(s.clone()), + other => rusqlite::types::Value::Text(other.to_string()), + }) + .collect(); + let mut stmt = conn.prepare(sql).map_err(|e| e.to_string())?; + let cols = stmt.column_count(); + let mut out = stmt + .query(rusqlite::params_from_iter(params.iter())) + .map_err(|e| e.to_string())?; + let mut rows = Vec::new(); + while let Some(row) = out.next().map_err(|e| e.to_string())? { + let mut cells = Vec::new(); + for i in 0..cols { + cells.push(match row.get_ref(i).map_err(|e| e.to_string())? { + ValueRef::Null => Value::Null, + ValueRef::Integer(n) => json!(n), + ValueRef::Text(t) => json!(String::from_utf8_lossy(t)), + _ => Value::Null, + }); + } + rows.push(cells); + } + Ok(Rows { rows }) + } +} + +/// Fake GitHub: per App, its metadata and its installations, served in +/// pages of `page_size` linked by `next`. Keys are App JWT strings. +#[derive(Default)] +struct FakeGitHub { + apps: BTreeMap)>, + fail_installations: RefCell>, +} + +impl GitHubApi for FakeGitHub { + fn app(&self, jwt: &str) -> Result { + self.apps + .get(jwt) + .map(|(m, _)| m.clone()) + .ok_or_else(|| format!("no app for {jwt}")) + } + + fn installations(&self, jwt: &str) -> Result, String> { + if self.fail_installations.borrow().iter().any(|j| j == jwt) { + return Err("installations: HTTP 500".into()); + } + let (_, installs) = self.apps.get(jwt).ok_or("no app")?; + let pages: Vec = installs + .chunks(2) + .map(|c| Value::Array(c.iter().map(install_json).collect())) + .collect(); + let pages = RefCell::new(pages); + let fetch = |url: &str| -> Result<(Value, Option), String> { + let i: usize = url.rsplit('=').next().unwrap().parse().unwrap(); + let pages = pages.borrow(); + let page = pages.get(i - 1).cloned().unwrap_or(json!([])); + let next = (i < pages.len()).then(|| format!("https://x/?page={}", i + 1)); + Ok((page, next)) + }; + let entries = collect_pages("https://x/?page=1", fetch)?; + entries + .iter() + .map(|e| parse_installation(e).ok_or_else(|| "bad".to_string())) + .collect() + } +} + +fn install_json(i: &Installation) -> Value { + json!({ + "id": i.installation_id, + "account": {"login": i.account_login, "type": i.account_type}, + "repository_selection": i.repository_selection, + "permissions": i.permissions, + }) +} + +struct Jwts; +impl AppJwt for Jwts { + fn jwt(&self, app: &str) -> Result { + Ok(app.to_string()) + } +} + +fn inst(id: i64, login: &str, ty: &str, perms: Value) -> Installation { + Installation { + installation_id: id, + account_login: login.into(), + account_type: ty.into(), + repository_selection: "all".into(), + permissions: perms, + } +} + +fn meta(slug: &str, id: i64) -> AppMeta { + AppMeta { + slug: slug.into(), + app_id: id, + name: slug.into(), + owner: "developing-today".into(), + permissions: json!({"contents": "write", "issues": "read"}), + events: json!(["push"]), + } +} + +fn fleet() -> FakeGitHub { + let mut gh = FakeGitHub::default(); + gh.apps.insert( + "app".into(), + ( + meta("developing-today-fleet", 5612056), + vec![ + inst(1, "acme", "Organization", json!({"contents": "write"})), + inst(2, "beta", "Organization", json!({"issues": "read"})), + inst(3, "dez", "User", json!({"contents": "read"})), + ], + ), + ); + gh.apps.insert( + "backup".into(), + ( + meta("developing-today-backup", 99), + vec![inst(7, "acme", "Organization", json!({"contents": "read"}))], + ), + ); + gh +} + +fn clock() -> impl Fn() -> i64 { + let t = Cell::new(1_700_000_000); + move || { + t.set(t.get() + 1); + t.get() + } +} + +#[test] +fn sync_writes_apps_orgs_and_installations_from_all_pages() { + let db = Sqlite::memory(); + let gh = fleet(); + let report = sync(&db, &gh, &Jwts, &["app", "backup"], &clock()).unwrap(); + assert_eq!( + report.apps, + vec![ + ("developing-today-fleet".into(), 3), + ("developing-today-backup".into(), 1) + ] + ); + + let reg = list::load(&db).unwrap(); + assert_eq!(reg.entries.len(), 4); + assert!(reg.last_sync.is_some()); + + let app = db + .execute( + "SELECT owner FROM apps WHERE slug = 'developing-today-fleet'", + &[], + ) + .unwrap(); + assert_eq!(app.rows, vec![vec![json!("developing-today")]]); + let org_columns = db.execute("PRAGMA table_info(orgs)", &[]).unwrap(); + let names: Vec<&str> = org_columns + .rows + .iter() + .filter_map(|r| r.get(1).and_then(Value::as_str)) + .collect(); + for expected in ["login", "role", "repo_count", "verified_at"] { + assert!( + names.contains(&expected), + "orgs schema must include {expected}" + ); + } + + let orgs = db + .execute("SELECT login FROM orgs ORDER BY login", &[]) + .unwrap(); + assert_eq!(orgs.rows, vec![vec![json!("acme")], vec![json!("beta")]]); +} + +#[test] +fn a_resync_is_idempotent() { + let db = Sqlite::memory(); + let gh = fleet(); + sync(&db, &gh, &Jwts, &["app", "backup"], &clock()).unwrap(); + let before = list::load(&db).unwrap().entries; + sync(&db, &gh, &Jwts, &["app", "backup"], &clock()).unwrap(); + let after = list::load(&db).unwrap(); + assert_eq!(before, after.entries); + let runs = db + .execute("SELECT COUNT(*), SUM(status = 'ok') FROM sync_runs", &[]) + .unwrap(); + assert_eq!(runs.rows, vec![vec![json!(2), json!(2)]]); +} + +#[test] +fn same_app_and_account_upsert_updates_installation_and_verified_time() { + let db = Sqlite::memory(); + let mut gh = FakeGitHub::default(); + gh.apps.insert( + "app".into(), + ( + meta("fleet", 1), + vec![inst( + 10, + "acme", + "Organization", + json!({"contents": "read"}), + )], + ), + ); + let time = clock(); + sync(&db, &gh, &Jwts, &["app"], &time).unwrap(); + let prior = db.execute( + "SELECT MAX(verified_at) FROM installations WHERE app_slug = 'fleet' AND account_login = 'acme'", + &[], + ).unwrap().rows[0][0].as_i64().unwrap(); + gh.apps.get_mut("app").unwrap().1 = vec![inst( + 11, + "acme", + "Organization", + json!({"contents": "write"}), + )]; + sync(&db, &gh, &Jwts, &["app"], &time).unwrap(); + + let rows = db.execute( + "SELECT COUNT(*), MAX(installation_id), MAX(verified_at) FROM installations WHERE app_slug = 'fleet' AND account_login = 'acme'", + &[], + ).unwrap(); + assert_eq!( + rows.rows[0][0], + json!(1), + "oracle: one (App, account) row remains" + ); + assert_eq!( + rows.rows[0][1], + json!(11), + "oracle: the latest installation id is stored" + ); + assert!( + rows.rows[0][2].as_i64().unwrap() > prior, + "oracle: verified_at advances on upsert" + ); +} + +#[test] +fn an_installation_removed_on_github_is_pruned_on_the_next_run() { + let db = Sqlite::memory(); + let mut gh = fleet(); + sync(&db, &gh, &Jwts, &["app"], &clock()).unwrap(); + gh.apps + .get_mut("app") + .unwrap() + .1 + .retain(|i| i.installation_id != 2); + sync(&db, &gh, &Jwts, &["app"], &clock()).unwrap(); + let ids: Vec = list::load(&db) + .unwrap() + .entries + .iter() + .map(|e| e.installation_id) + .collect(); + assert_eq!(ids, vec![1, 3]); +} + +#[test] +fn a_failed_app_is_recorded_as_failed_and_its_rows_are_kept() { + let db = Sqlite::memory(); + let gh = fleet(); + sync(&db, &gh, &Jwts, &["app"], &clock()).unwrap(); + gh.fail_installations.borrow_mut().push("backup".into()); + let err = sync(&db, &gh, &Jwts, &["app", "backup"], &clock()); + assert!(err.is_err()); + let runs = db + .execute("SELECT status, error FROM sync_runs ORDER BY id", &[]) + .unwrap(); + assert_eq!(runs.rows[1][0], json!("failed")); + assert!(runs.rows[1][1].as_str().unwrap().contains("HTTP 500")); + let reg = list::load(&db).unwrap(); + assert_eq!( + reg.entries.len(), + 3, + "the failed App keeps its last good rows" + ); +} + +#[test] +fn last_sync_reflects_only_successful_runs() { + let db = Sqlite::memory(); + let gh = fleet(); + sync(&db, &gh, &Jwts, &["app"], &clock()).unwrap(); + let ok_at = list::load(&db).unwrap().last_sync; + gh.fail_installations.borrow_mut().push("app".into()); + let _ = sync(&db, &gh, &Jwts, &["app"], &clock()); + assert_eq!(list::load(&db).unwrap().last_sync, ok_at); +} + +#[test] +fn list_filters_and_renders_over_the_stored_registry() { + let db = Sqlite::memory(); + sync(&db, &fleet(), &Jwts, &["app", "backup"], &clock()).unwrap(); + let reg = list::load(&db).unwrap(); + + let writers = list::filter( + ®.entries, + &Filter { + permission: Some(list::parse_permission("contents=write").unwrap()), + ..Default::default() + }, + ); + assert_eq!(writers.len(), 1); + assert_eq!(writers[0].org, "acme"); + + let backup = list::filter( + ®.entries, + &Filter { + app: Some("developing-today-backup".into()), + ..Default::default() + }, + ); + assert_eq!(backup.len(), 1); + + let table = list::render_table(®, &writers); + assert!(table.contains("ORG")); + assert!(table.contains("contents:write")); + assert!(table.contains("last sync: ")); + + let json = list::render_json(®, &backup); + assert_eq!(json["installations"][0]["org"], "acme"); + assert!(json["last_sync"].is_string()); +} + +proptest! { + #[test] + fn any_resync_leaves_the_registry_as_the_last_run_saw_it( + ids in proptest::collection::btree_set(1i64..50, 0..12), + second in proptest::collection::btree_set(1i64..50, 0..12), + ) { + let db = Sqlite::memory(); + let mut gh = FakeGitHub::default(); + let make = |set: &std::collections::BTreeSet| -> Vec { + set.iter().map(|id| inst(*id, &format!("org{id}"), "Organization", json!({"contents": "read"}))).collect() + }; + gh.apps.insert("app".into(), (meta("fleet", 1), make(&ids))); + sync(&db, &gh, &Jwts, &["app"], &clock()).unwrap(); + gh.apps.get_mut("app").unwrap().1 = make(&second); + sync(&db, &gh, &Jwts, &["app"], &clock()).unwrap(); + let mut got: Vec = list::load(&db).unwrap().entries.iter().map(|e| e.installation_id).collect(); + got.sort(); + let want: Vec = second.iter().copied().collect(); + prop_assert_eq!(got, want); + } +} diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs index 47758a10c2..ff9cf8ec85 100644 --- a/pkgs/fleet/crates/fleet-registry/src/lib.rs +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -87,6 +87,8 @@ pub enum Capability { /// runner-side agent, and the egress helper. A working-seat /// client surface, so full only. Actions, + /// `fleet orgs …` — the Turso-backed GitHub org/App registry. + Orgs, } impl Capability { @@ -115,6 +117,7 @@ impl Capability { Capability::Laptop => "laptop", Capability::Cert => "cert", Capability::Actions => "actions", + Capability::Orgs => "orgs", } } @@ -142,6 +145,7 @@ impl Capability { Capability::Laptop, Capability::Cert, Capability::Actions, + Capability::Orgs, ]; } @@ -368,6 +372,14 @@ pub const DOMAINS: &[Domain] = &[ "send", "agents", "log", "hello", "inbox", "post", "ack", "health", ], }, + Domain { + name: "orgs", + summary: "Turso-backed GitHub org, App and installation registry.", + capabilities: &[Capability::Orgs], + primary: Capability::Orgs, + aliases: &[], + subcommands: &["list", "sync"], + }, Domain { name: "agent", summary: "The agent's front door: enrol an agent of any kind, check what this seat reaches, and take the next piece of work down the intake ladder (pushed command, queue, local shortlist, highest priority).", diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml index 94b22a4701..d5d8b2537c 100644 --- a/pkgs/fleet/crates/fleet/Cargo.toml +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -39,6 +39,7 @@ fleet-agent = { workspace = true, optional = true } # The cert domain (code#9157): PKI/X.509 roots, issuers, leaves, # chains and bundles over the fleet-cert library crate. fleet-cert = { workspace = true, optional = true } +fleet-orgs = { workspace = true, optional = true } serde_json = { workspace = true } # The OpenCode session liveness probe (session_state.rs) only; # optional so the connect variant stays under the D7 size gate. @@ -96,6 +97,7 @@ full = [ "agent", "cert", "actions", + "orgs", "opencode-probe", ] # The serve variant's set, as one feature for the nix build. @@ -177,6 +179,7 @@ agent = ["dep:fleet-agent"] # The cert domain: a working-seat PKI client surface, so full only — # never in serve (no daemon role) or connect (size gate). cert = ["dep:fleet-cert"] +orgs = ["dep:fleet-orgs"] [dev-dependencies] # Property tests for the gh read classifier (AGENTS.md testing diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 12451e16fa..553970b705 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -122,6 +122,9 @@ fn compiled_capabilities() -> CapabilitySet { if cfg!(feature = "dispatch") { caps.insert(Capability::Dispatch); } + if cfg!(feature = "orgs") { + caps.insert(Capability::Orgs); + } if cfg!(feature = "dispatch-test") { caps.insert(Capability::DispatchTest); } @@ -1065,6 +1068,10 @@ fn run_domain_with_initializer( if d.name == "gh" { return gh::run(&surface.config, args); } + #[cfg(feature = "orgs")] + if d.name == "orgs" { + return fleet_orgs::run(&surface.config, args); + } // The bridge domain runs for real: fleet mailboxes on the // message bridge (central send/agents/log; agent // hello/inbox/post/ack). diff --git a/pkgs/fleet/doc/fleet/orgs-registry.md b/pkgs/fleet/doc/fleet/orgs-registry.md new file mode 100644 index 0000000000..2a1d85f6d4 --- /dev/null +++ b/pkgs/fleet/doc/fleet/orgs-registry.md @@ -0,0 +1,23 @@ +# Fleet GitHub organization registry + +`fleet orgs list` reads the stored Turso snapshot; it does not call GitHub. +Use `--json` for machine-readable output, or `--app`, `--org`, and +`--permission` to narrow the rows. The output includes the last recorded sync +time. + +`fleet orgs sync` records a sync run and refreshes orgs, Apps, and +installations idempotently. Installation coverage is sourced only from each +App's JWT-authenticated `GET /app/installations` response, following all +pagination links. OAuth-token organization installation reads are explicitly +not coverage evidence: they have produced false negatives. + +The registry stores organization login and verification time; role and +repository count are nullable because the permitted App installation endpoint +does not provide them. App slug, id, owner, permissions and events are stored, +along with each App × account installation id, repository selection, +installed permissions and verification time. The command is capability-gated +as `orgs`; builds without that capability retain the normal Fleet exit-69 stub +behavior. + +Tests use fixtures and a fixed registry snapshot only. They do not contact +GitHub or Turso. diff --git a/pkgs/fleet/docs/verbs.md b/pkgs/fleet/docs/verbs.md index 68cc7636dd..7f62d73ec6 100644 --- a/pkgs/fleet/docs/verbs.md +++ b/pkgs/fleet/docs/verbs.md @@ -233,6 +233,18 @@ filters. It is the client half of the Atlas search service; the service itself runs on the laptop (`fleet serve search`, 127.0.0.1:18760), and the Cloudflare worker surface (pkgs/atlas-search/worker) forwards to it. +## `orgs` — GitHub organization registry + +| Command | Purpose | +| --- | --- | +| `fleet orgs list` | List the locally stored org/App/installation snapshot as a table or JSON; supports `--app`, `--org`, and `--permission` filters. | +| `fleet orgs sync` | Refresh the Turso registry from each configured GitHub App's own installation listing. | + +The registry only makes coverage claims from `GET /app/installations` authenticated +with that App's JWT and follows every Link page. OAuth-token +`/orgs//installations` reads are not authoritative. See +[`orgs-registry.md`](../doc/fleet/orgs-registry.md) for configuration and schema. + | Command | Purpose | | --------------------------------------------------- | ----------------------------------------------------------------------------------- | | `fleet search QUERY` or `fleet search search QUERY` | Search the Atlas corpus using its filters and output modes. |