diff --git a/crates/ai-comfy-env/src/source/pack/mod.rs b/crates/ai-comfy-env/src/source/pack/mod.rs index 4c24cec..25cd731 100644 --- a/crates/ai-comfy-env/src/source/pack/mod.rs +++ b/crates/ai-comfy-env/src/source/pack/mod.rs @@ -4,6 +4,8 @@ //! module is built around one rule: **nothing runs, ever, during an install.** What it does: //! //! - [`parse_pack`] understands `https://github.com/owner/repo` (optionally `/tree/`). +//! A ref written as a commit id is accepted only when the repository's default branch +//! contains it, because GitHub also serves a fork's commits under the original name. //! - [`Resolver::resolve_pack`](super::Resolver::resolve_pack) pins the address to one commit and //! describes it for the person: the commit, its first line, its date, the licence, and whether //! the repository is archived. Only public repositories. @@ -37,7 +39,8 @@ pub(super) use archive::unpack; pub struct PackSpec { pub owner: String, pub repo: String, - /// A branch or tag; the repository's default branch when absent. + /// A branch, a tag or a commit id; the repository's default branch when absent. A commit + /// id is installed only when the default branch contains it. pub reference: Option, } diff --git a/crates/ai-comfy-env/src/source/pack/resolve.rs b/crates/ai-comfy-env/src/source/pack/resolve.rs index 0c82395..dbeb80e 100644 --- a/crates/ai-comfy-env/src/source/pack/resolve.rs +++ b/crates/ai-comfy-env/src/source/pack/resolve.rs @@ -1,6 +1,7 @@ //! Pinning a GitHub repository to one commit and describing it for the person. use craft_ai_core::{AiError, SecretString}; +use serde::Deserialize; use serde_json::Value; use super::{PackCandidate, PackSpec}; @@ -52,6 +53,43 @@ impl Resolver { .and_then(Value::as_str) .filter(|s| is_hex(s, 40) && s.bytes().all(|b| !b.is_ascii_uppercase())) .ok_or_else(|| refused("the source did not name a commit"))?; + // GitHub serves any commit of a repository's forks under the repository's own name, and + // reads many spellings as a commit (an id of any length, `--g` and more), so + // a pasted reference could be a fork's code shown as this repository's. Only a reference + // that is one of the repository's own branches or tags, pointing at this very commit, + // skips the check; anything else is accepted only when the default branch contains it. + let own = match spec.reference.as_deref() { + None => true, + Some(r) => names_own_ref( + &api, + &settings.bases.github_api, + token, + [owner, repo], + r, + sha, + )?, + }; + if !own { + let main = info + .get("default_branch") + .and_then(Value::as_str) + .filter(|b| revision_ok(b)) + .ok_or_else(|| refused("the repository names no branch to install"))?; + let comparison: Comparison = api.get_streamed( + kind, + &join( + &settings.bases.github_api, + &["repos", owner, repo, "compare", &format!("{main}...{sha}")], + )?, + token, + MAX_COMPARE_BYTES, + )?; + if !matches!(comparison.status.as_str(), "behind" | "identical") { + return Err(refused( + "this commit is not part of the repository's main line, so it may be someone else's copy; paste the address of a branch or tag instead", + )); + } + } let subject = commit .pointer("/commit/message") .and_then(Value::as_str) @@ -86,6 +124,67 @@ impl Resolver { } } +/// Largest compare reply read. Only its status is kept, so memory stays small. +const MAX_COMPARE_BYTES: u64 = 32 * 1024 * 1024; + +/// The one field of GitHub's compare reply that matters: how the pasted commit stands +/// against the default branch. `behind` or `identical` means the branch contains it. +#[derive(Deserialize)] +struct Comparison { + status: String, +} + +/// Most annotated tags followed before a tag is treated as not pointing at the commit. +const MAX_TAG_DEPTH: usize = 4; + +/// Whether `reference` is exactly one of the repository's own branches or tags and points at +/// `sha`. GitHub's single-ref lookup matches the whole name, never a prefix, and answers 404 +/// for a name that is no such ref. An annotated tag is followed to the commit it marks. Any +/// other failure is an error, so the caller never skips the check on a reply it could not read. +fn names_own_ref( + api: &Api<'_>, + base: &str, + token: Option<&SecretString>, + [owner, repo]: [&str; 2], + reference: &str, + sha: &str, +) -> Result { + for space in ["heads", "tags"] { + let address = join( + base, + &["repos", owner, repo, "git", "ref", space, reference], + )?; + let Some(found) = api.get_if_found(SourceKind::NodePack, &address, token)? else { + continue; + }; + let mut target = found.get("object").cloned().unwrap_or(Value::Null); + for _ in 0..MAX_TAG_DEPTH { + if target.get("type").and_then(Value::as_str) != Some("tag") { + break; + } + let Some(tag) = target + .get("sha") + .and_then(Value::as_str) + .filter(|s| is_hex(s, 40)) + else { + break; + }; + let address = join(base, &["repos", owner, repo, "git", "tags", tag])?; + target = api + .get(SourceKind::NodePack, &address, token)? + .get("object") + .cloned() + .unwrap_or(Value::Null); + } + if target.get("type").and_then(Value::as_str) == Some("commit") + && target.get("sha").and_then(Value::as_str) == Some(sha) + { + return Ok(true); + } + } + Ok(false) +} + /// One short clean line: no control characters, at most 120 characters. fn subject_line(line: &str) -> String { let clean: String = line.chars().filter(|c| !c.is_control()).take(120).collect(); diff --git a/crates/ai-comfy-env/src/source/resolve/api.rs b/crates/ai-comfy-env/src/source/resolve/api.rs index 8264dd8..8748cd1 100644 --- a/crates/ai-comfy-env/src/source/resolve/api.rs +++ b/crates/ai-comfy-env/src/source/resolve/api.rs @@ -44,6 +44,59 @@ impl<'a> Api<'a> { url: &str, token: Option<&SecretString>, ) -> Result { + self.read(self.send_get(kind, url, token)) + } + + /// Like [`Api::get`], but a 404 is `Ok(None)`: the thing asked about does not exist. Every + /// other failure is still an error. + pub fn get_if_found( + &self, + kind: SourceKind, + url: &str, + token: Option<&SecretString>, + ) -> Result, AiError> { + let response = self.send_get(kind, url, token)?; + if response.status().as_u16() == 404 { + return Ok(None); + } + self.read(Ok(response)).map(Some) + } + + /// Reads a reply that may be large (GitHub's compare lists the changed files) into `T` + /// as it arrives, so only the fields `T` names are kept. At most `max_bytes` are accepted: + /// one byte more is read, and a reply that reaches it is refused even when what came + /// before it parsed, so a cut-off reply is never taken as a whole one. + pub fn get_streamed( + &self, + kind: SourceKind, + url: &str, + token: Option<&SecretString>, + max_bytes: u64, + ) -> Result { + let body = self.body(self.send_get(kind, url, token))?; + let mut limited = body.into_reader().take(max_bytes.saturating_add(1)); + let unreadable = + |_: serde_json::Error| refused("the source's reply was too large or not readable"); + let parsed = { + let mut reader = serde_json::Deserializer::from_reader(&mut limited); + let parsed = T::deserialize(&mut reader).map_err(unreadable)?; + reader.end().map_err(unreadable)?; + parsed + }; + if limited.limit() == 0 { + return Err(refused("the source's reply was too large or not readable")); + } + Ok(parsed) + } + + /// Sends one checked GET: the address must be one of the kind's hosts, and the token goes + /// only to the kind's token host. + fn send_get( + &self, + kind: SourceKind, + url: &str, + token: Option<&SecretString>, + ) -> Result, AiError> { let (url, token) = self.checked(kind, url, token)?; // The agent itself carries no proxy, so a loopback source an app allowed never sends // its requests (token included) to a proxy host; a hosted one may use the environment's. @@ -59,7 +112,9 @@ impl<'a> Api<'a> { if let Some(token) = token { request = request.header("Authorization", format!("Bearer {}", token.expose())); } - self.read(request.call()) + request + .call() + .map_err(|_| AiError::new(ErrorKind::Network, "could not reach the model source")) } pub fn post( @@ -84,7 +139,11 @@ impl<'a> Api<'a> { if let Some(token) = token { request = request.header("Authorization", format!("Bearer {}", token.expose())); } - self.read(request.send(body.to_string().as_bytes())) + self.read( + request + .send(body.to_string().as_bytes()) + .map_err(|_| AiError::new(ErrorKind::Network, "could not reach the model source")), + ) } /// The parsed address, and the token only if this address is the kind's token host. @@ -111,12 +170,34 @@ impl<'a> Api<'a> { Ok((parsed, token)) } + /// A small JSON reply, read whole and parsed. fn read( &self, - result: Result, ureq::Error>, + result: Result, AiError>, ) -> Result { - let response = result - .map_err(|_| AiError::new(ErrorKind::Network, "could not reach the model source"))?; + let mut bytes = Vec::new(); + self.body(result)? + .into_reader() + .take(MAX_REPLY_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|_| { + AiError::new( + ErrorKind::Network, + "the connection broke while reading the reply", + ) + })?; + if bytes.len() as u64 > MAX_REPLY_BYTES { + return Err(refused("the source's reply was too large")); + } + serde_json::from_slice(&bytes).map_err(|_| refused("the source's reply was not readable")) + } + + /// The reply's body when its status is a success; otherwise the error the status means. + fn body( + &self, + result: Result, AiError>, + ) -> Result { + let response = result?; let status = response.status().as_u16(); match status { 200..=299 => {} @@ -144,22 +225,7 @@ impl<'a> Api<'a> { )); } } - let mut bytes = Vec::new(); - response - .into_body() - .into_reader() - .take(MAX_REPLY_BYTES + 1) - .read_to_end(&mut bytes) - .map_err(|_| { - AiError::new( - ErrorKind::Network, - "the connection broke while reading the reply", - ) - })?; - if bytes.len() as u64 > MAX_REPLY_BYTES { - return Err(refused("the source's reply was too large")); - } - serde_json::from_slice(&bytes).map_err(|_| refused("the source's reply was not readable")) + Ok(response.into_body()) } } diff --git a/crates/ai-comfy-env/tests/nodepack_commit.rs b/crates/ai-comfy-env/tests/nodepack_commit.rs new file mode 100644 index 0000000..a0ee211 --- /dev/null +++ b/crates/ai-comfy-env/tests/nodepack_commit.rs @@ -0,0 +1,279 @@ +#![allow(dead_code)] +//! A pasted node pack address that names something other than one of the repository's own +//! branches or tags. GitHub serves a fork's commits under the original repository's name, and +//! reads many spellings as a commit, so such an address could show a fork's code as the trusted +//! repository's. These tests pin that only an exact branch or tag pointing at the resolved commit +//! skips the check, and that anything else is accepted only when GitHub's compare says the +//! repository's default branch contains it. Scripted localhost servers only: no real repository +//! is read. +mod nodepack_rig; + +use craft_ai_comfy_env::source::{PackCandidate, Resolver, parse_pack}; +use craft_ai_core::AiError; +use nodepack_rig::support::{Reply, Server}; +use nodepack_rig::*; +use serde_json::{Value, json}; + +/// Another commit, for a branch that exists but points elsewhere. +const OTHER: &str = "fedcba9876543210fedcba9876543210fedcba98"; +/// An annotated tag object. +const TAG_OBJECT: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + +/// The compare path the resolver must ask for a reference that is not the repository's own. +fn compare_path() -> String { + format!("/repos/owner/Pack/compare/main...{COMMIT}") +} + +/// One of the repository's own refs: `space` is `heads` or `tags`, `object` what it points at. +struct Ref { + space: &'static str, + name: &'static str, + object: Value, +} + +fn branch(name: &'static str, sha: &str) -> Ref { + Ref { + space: "heads", + name, + object: json!({"type": "commit", "sha": sha}), + } +} + +fn tag(name: &'static str, object: Value) -> Ref { + Ref { + space: "tags", + name, + object, + } +} + +/// A stand-in for GitHub whose compare reply is `compare` (`None` answers 404 there) and whose +/// own branches and tags are `refs`. Every commit lookup resolves to [`COMMIT`]. +fn github_with(compare: Option, refs: Vec) -> Server { + Server::start(move |r| { + if r.path == "/repos/owner/Pack" { + Reply::Json( + 200, + json!({"default_branch": "main", "private": false, "archived": false, + "license": {"spdx_id": "MIT"}}) + .to_string(), + ) + } else if r.path.starts_with("/repos/owner/Pack/commits/") { + Reply::Json( + 200, + json!({"sha": COMMIT, "commit": {"message": "Add the nodes", + "committer": {"date": "2026-10-01T12:00:00Z"}}}) + .to_string(), + ) + } else if r.path == compare_path() { + match &compare { + Some(body) => Reply::Json(200, body.clone()), + None => Reply::Json(404, "{}".into()), + } + } else if r.path == format!("/repos/owner/Pack/git/tags/{TAG_OBJECT}") { + Reply::Json( + 200, + json!({"object": {"type": "commit", "sha": COMMIT}}).to_string(), + ) + } else if let Some(found) = refs + .iter() + .find(|f| r.path == format!("/repos/owner/Pack/git/ref/{}/{}", f.space, f.name)) + { + Reply::Json( + 200, + json!({"ref": format!("refs/{}/{}", found.space, found.name), + "object": found.object}) + .to_string(), + ) + } else { + Reply::Json(404, "{}".into()) + } + }) +} + +/// A stand-in with no branches or tags besides the default one. +fn github(compare: Option) -> Server { + github_with(compare, Vec::new()) +} + +/// A compare reply with this status. +fn status(s: &str) -> Option { + Some(json!({"status": s, "ahead_by": 0, "behind_by": 3, "files": []}).to_string()) +} + +/// Resolves `address` against `server`. +fn resolve(server: &Server, address: &str) -> Result { + Resolver::new(settings(&origin(server), &["127.0.0.1"])) + .resolve_pack(&parse_pack(address).unwrap(), None) +} + +/// The paths the stand-in was asked for. +fn paths(server: &Server) -> Vec { + server.recorded().iter().map(|r| r.path.clone()).collect() +} + +fn at(reference: &str) -> String { + format!("https://github.com/owner/Pack/tree/{reference}") +} + +#[test] +fn a_commit_on_the_default_branch_is_accepted() { + for s in ["behind", "identical"] { + let server = github(status(s)); + let c = resolve(&server, &at(COMMIT)).unwrap(); + assert_eq!(c.commit, COMMIT); + assert_eq!(c.reference, COMMIT); + assert!(paths(&server).contains(&compare_path()), "{s}"); + } +} + +#[test] +fn a_commit_the_default_branch_does_not_contain_is_refused() { + // `ahead` or `diverged` means the commit is not on the branch: a fork's own commit, or + // one only on another branch. Anything else GitHub might say is refused too. + for s in ["ahead", "diverged", "", "Behind"] { + let server = github(status(s)); + let e = resolve(&server, &at(COMMIT)).unwrap_err(); + assert!(e.message.contains("main line"), "{s}: {}", e.message); + } +} + +#[test] +fn a_commit_is_refused_when_the_comparison_cannot_be_read() { + for compare in [None, Some("{}".to_owned()), Some("not json".to_owned())] { + let server = github(compare.clone()); + assert!(resolve(&server, &at(COMMIT)).is_err(), "{compare:?}"); + } +} + +#[test] +fn a_long_comparison_is_read_without_keeping_it() { + // An old commit compared with a busy branch lists many changed files: far more than the + // 2 MiB a listing reply may be. Only the status is kept. + let files: Vec<_> = (0..3000) + .map(|i| json!({"filename": format!("nodes/{i}.py"), "patch": "x".repeat(1000)})) + .collect(); + let body = json!({"status": "behind", "files": files}).to_string(); + assert!(body.len() > 2 * 1024 * 1024); + let server = github(Some(body)); + let c = resolve(&server, &at(COMMIT)).unwrap(); + assert_eq!(c.commit, COMMIT); +} + +#[test] +fn a_comparison_longer_than_the_limit_is_refused_even_when_its_start_parses() { + // A complete answer followed by padding: what was read parses, but more was left unread. + const LIMIT: usize = 32 * 1024 * 1024; + let head = r#"{"status":"behind"}"#; + let exact = format!("{head}{}", " ".repeat(LIMIT - head.len())); + let server = github(Some(exact)); + assert_eq!(resolve(&server, &at(COMMIT)).unwrap().commit, COMMIT); + let over = format!("{head}{}", " ".repeat(LIMIT + 1 - head.len())); + let server = github(Some(over)); + let e = resolve(&server, &at(COMMIT)).unwrap_err(); + assert!(e.message.contains("too large"), "{}", e.message); +} + +#[test] +fn a_short_commit_id_of_any_length_is_checked_too() { + // GitHub accepts any unambiguous prefix, so a six- or four-character id must not slip past + // the check that a seven-character one gets. + for short in ["0123456", "012345", "0123", "0123456789AB"] { + let server = github(status("ahead")); + let e = resolve(&server, &at(short)).unwrap_err(); + assert!(e.message.contains("main line"), "{short}: {}", e.message); + let server = github(status("behind")); + let c = resolve(&server, &at(short)).unwrap(); + assert_eq!(c.commit, COMMIT, "{short}"); + assert!(paths(&server).contains(&compare_path()), "{short}"); + } +} + +#[test] +fn any_other_spelling_github_reads_as_a_commit_is_checked() { + // GitHub also reads `git describe` output (`--g`) and names like `HEAD` as a + // commit. None of these is one of the repository's own branches or tags, so each must reach + // the compare and be refused when the default branch does not contain the commit. + for reference in [ + "a-1-g0123456", + "0-0-g0123456789ab", + "v1.0.0-3-g01234567", + "main-0-g0123", + "HEAD", + "0123456789abcdef0123456789abcdef01234567", + ] { + let server = github(status("ahead")); + let e = resolve(&server, &at(reference)).unwrap_err(); + assert!( + e.message.contains("main line"), + "{reference}: {}", + e.message + ); + assert!(paths(&server).contains(&compare_path()), "{reference}"); + } +} + +#[test] +fn a_branch_that_points_at_another_commit_is_checked() { + // The branch exists, but the commit GitHub resolved is not the one it points at, so the + // name was not read as that branch. + let server = github_with( + status("ahead"), + vec![ + branch("dev", OTHER), + tag("dev", json!({"type": "commit", "sha": OTHER})), + ], + ); + let e = resolve(&server, &at("dev")).unwrap_err(); + assert!(e.message.contains("main line"), "{}", e.message); +} + +#[test] +fn a_failed_branch_lookup_is_never_taken_as_the_repositorys_own() { + // Only a 404 means "no such branch"; a server error stops the install. + let server = Server::start(|r| { + if r.path.contains("/git/ref/") { + Reply::Json(500, "{}".into()) + } else if r.path == "/repos/owner/Pack" { + Reply::Json( + 200, + json!({"default_branch": "main", "private": false}).to_string(), + ) + } else if r.path.starts_with("/repos/owner/Pack/commits/") { + Reply::Json(200, json!({"sha": COMMIT}).to_string()) + } else { + Reply::Json(200, json!({"status": "behind"}).to_string()) + } + }); + assert!(resolve(&server, &at("dev")).is_err()); +} + +#[test] +fn branch_and_tag_names_and_the_default_branch_need_no_comparison() { + // Each of these is one of the repository's own branches or tags pointing at the resolved + // commit, even the ones made of hex digits, so no comparison is asked for. + let refs = || { + vec![ + branch("dev-1.2", COMMIT), + branch("abc123", COMMIT), + branch("fedcba9", COMMIT), + tag("2024", json!({"type": "commit", "sha": COMMIT})), + tag("v1.0.0", json!({"type": "tag", "sha": TAG_OBJECT})), + ] + }; + for address in [ + "https://github.com/owner/Pack".to_owned(), + at("dev-1.2"), + at("v1.0.0"), + at("abc123"), + at("2024"), + at("fedcba9"), + ] { + let server = github_with(None, refs()); + resolve(&server, &address).unwrap(); + assert!( + !paths(&server).iter().any(|p| p.contains("/compare/")), + "{address}" + ); + } +} diff --git a/tools/mutation/mutation_check.py b/tools/mutation/mutation_check.py index 13091ab..f3980f6 100644 --- a/tools/mutation/mutation_check.py +++ b/tools/mutation/mutation_check.py @@ -221,6 +221,14 @@ U4 = [ ('pack-subject-unclean', PACK_RESOLVE, 'let clean: String = line.chars().filter(|c| !c.is_control()).take(120).collect();', 'let clean: String = line.chars().take(120).collect();', E, 'nodepack', 'one_short_clean_line'), ('pack-subject-unbounded', PACK_RESOLVE, '.take(120)', '.take(1200)', E, 'nodepack', 'one_short_clean_line'), ('pack-archive-unpinned', PACK_RESOLVE, '&format!("{sha}.tar.gz")', '&format!("{}.tar.gz", spec.reference.as_deref().unwrap_or("main"))', E, 'nodepack', 'pinned_to_a_commit'), + ('pack-commit-not-compared', PACK_RESOLVE, 'if !matches!(comparison.status.as_str(), "behind" | "identical") {', 'if false {', E, 'nodepack_commit', 'does_not_contain'), + ('pack-commit-ahead-accepted', PACK_RESOLVE, '"behind" | "identical"', '"behind" | "identical" | "ahead" | "diverged"', E, 'nodepack_commit', 'does_not_contain'), + ('pack-every-ref-trusted', PACK_RESOLVE, 'Some(r) => names_own_ref(', 'Some(r) => r.is_empty() || !r.is_empty() || names_own_ref(', E, 'nodepack_commit', 'other_spelling'), + ('pack-ref-sha-unchecked', PACK_RESOLVE, '&& target.get("sha").and_then(Value::as_str) == Some(sha)', '', E, 'nodepack_commit', 'points_at_another_commit'), + ('pack-ref-lookup-error-ignored', PACK_RESOLVE, 'api.get_if_found(SourceKind::NodePack, &address, token)? else {', 'api.get_if_found(SourceKind::NodePack, &address, token).ok().flatten() else {', E, 'nodepack_commit', 'failed_branch_lookup'), + ('pack-tag-not-peeled', PACK_RESOLVE, 'for _ in 0..MAX_TAG_DEPTH {', 'for _ in 0..0 {', E, 'nodepack_commit', 'need_no_comparison'), + ('pack-compare-overflow-accepted', API, 'if limited.limit() == 0 {', 'if false {', E, 'nodepack_commit', 'longer_than_the_limit'), + ('pack-compare-read-small', PACK_RESOLVE, 'const MAX_COMPARE_BYTES: u64 = 32 * 1024 * 1024;', 'const MAX_COMPARE_BYTES: u64 = 2 * 1024 * 1024;', E, 'nodepack_commit', 'long_comparison'), ('pack-consent-for-any-commit', PACK_INSTALL, 'if !consent.is_some_and(|c| c.commit == candidate.commit) {', 'if consent.is_none() {', E, 'nodepack', 'consent_to_run_code'), ('pack-consent-not-needed', PACK_INSTALL, 'if !consent.is_some_and(|c| c.commit == candidate.commit) {', 'if false {', E, 'nodepack', 'consent_to_run_code'), ('pack-folder-checked-after-download', PACK_INSTALL, 'if std::fs::symlink_metadata(&target).is_ok() {\n return Err(PackError::Refused(PackRefusal::FolderTaken));\n }\n if cancel', 'if false {\n return Err(PackError::Refused(PackRefusal::FolderTaken));\n }\n if cancel', E, 'nodepack', 'existing_folder_is_never'),