diff --git a/pkgs/atlas-search/book/reference/atlas-github-comments.md b/pkgs/atlas-search/book/reference/atlas-github-comments.md index bee2d8769..a848fb16b 100644 --- a/pkgs/atlas-search/book/reference/atlas-github-comments.md +++ b/pkgs/atlas-search/book/reference/atlas-github-comments.md @@ -36,6 +36,10 @@ The state file keeps the original `repos` map for comment streams and a `reviews A completed repository's output is synced before its state is replaced. On a handled failure, the feed removes that repository's partial append and preserves its previous checkpoint. The process holds an advisory lock on the output and on a sibling `.lock` file next to the state. A hard crash between the append and checkpoint can leave replayed output; downstream promotion must deduplicate by source occurrence and revision. The feed's checkpoint only establishes extraction progress. Classification, promotion, publication, and retrieval need their own receipts. +### First-party source scope + +An explicit `--repo` must name a single repository owned by `developing-today`, `developing-today-forks`, or `dezren39`. Comparison of owner names is case-insensitive. A malformed path or external owner fails argument parsing before output is opened. For both default discovery and explicit selection, the feed verifies the canonical API repository URL on returned issue, comment, and review rows. If GitHub follows a transfer or rename to a different repository, that pass fails closed; select the current eligible name explicitly after review. This checks exported provenance and cannot suppress redirects internal to the GitHub CLI. + ### The HTTP 451 exception One failure does not stop the run: a repository that is permanently access-blocked (HTTP 451, for example a DMCA block) is logged as `<repo>: skipped — repository access blocked (HTTP 451)`, counted in a final `skipped_repos: N (repository access blocked, HTTP 451)` line, and the run continues with the next repository. If nothing else failed, the run still exits 0. @@ -47,9 +51,9 @@ See [Ingest today: staging, classification, promotion](../concepts/ingest.md) fo Extracting one toy repository into a fresh state and records file: ``` -$ atlas-github-comments --state /tmp/toy-watermarks.json --out /tmp/toy-records.jsonl --repo toy-owner/toy-repo +$ atlas-github-comments --state /tmp/toy-watermarks.json --out /tmp/toy-records.jsonl --repo developing-today/example-fixture estate: 1 repos -toy-owner/toy-repo: issue_comments=2 review_comments=1 reviews=1 documents=4 +developing-today/example-fixture: issue_comments=2 review_comments=1 reviews=1 documents=4 totals: … ``` diff --git a/pkgs/atlas-search/crates/atlas-core/src/bin/atlas-github-comments.rs b/pkgs/atlas-search/crates/atlas-core/src/bin/atlas-github-comments.rs index a9c2121cc..829fb4e22 100644 --- a/pkgs/atlas-search/crates/atlas-core/src/bin/atlas-github-comments.rs +++ b/pkgs/atlas-search/crates/atlas-core/src/bin/atlas-github-comments.rs @@ -51,6 +51,51 @@ struct Args { observed_date: Option, } +const ESTATE_OWNERS: [&str; 3] = ["developing-today", "developing-today-forks", "dezren39"]; + +fn validate_repo(repo: &str) -> Result<(), String> { + let Some((owner, name)) = repo.split_once('/') else { + return Err("--repo needs an owned owner/name pair".into()); + }; + let allowed = ESTATE_OWNERS.iter().any(|o| o.eq_ignore_ascii_case(owner)); + if !allowed + || name.is_empty() + || matches!(name, "." | "..") + || !name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + { + return Err( + "repository outside the permitted GitHub comments estate or malformed repository name" + .into(), + ); + } + Ok(()) +} + +// GitHub can redirect a renamed or transferred repository. Validate the +// canonical source named by each response row before exporting any of it. +fn check_row_repo(row: &Json, field: &str, repo: &str) -> Result<(), String> { + let source = row + .get(field) + .and_then(Json::as_str) + .and_then(|u| u.strip_prefix("https://api.github.com/repos/")) + .and_then(|r| r.split_once('/')); + let (owner, name) = repo.split_once('/').ok_or("invalid repository name")?; + if source.is_some_and(|(o, rest)| { + o.eq_ignore_ascii_case(owner) + && rest + .split('/') + .next() + .is_some_and(|n| n.eq_ignore_ascii_case(name)) + }) { + return Ok(()); + } + Err(format!( + "missing or unexpected GitHub repository in {field}" + )) +} + fn parse_args() -> Result { let mut state: Option = None; let mut out: Option = None; @@ -62,7 +107,11 @@ fn parse_args() -> Result { match arg.as_str() { "--state" => state = Some(PathBuf::from(it.next().ok_or("--state needs a path")?)), "--out" => out = Some(PathBuf::from(it.next().ok_or("--out needs a path")?)), - "--repo" => repos.push(it.next().ok_or("--repo needs owner/name")?), + "--repo" => { + let repo = it.next().ok_or("--repo needs owner/name")?; + validate_repo(&repo)?; + repos.push(repo); + } "--skip-reviews" => skip_reviews = true, "--observed-date" => { observed_date = Some(it.next().ok_or("--observed-date needs YYYY-MM-DD")?) @@ -137,7 +186,11 @@ fn enumerate_estate() -> Result, String> { let text = gh_api(path, ".[].full_name")?; for line in text.lines() { let name = line.trim(); - if !name.is_empty() && !repos.iter().any(|r| r == name) { + if name.is_empty() { + continue; + } + validate_repo(name)?; + if !repos.iter().any(|r| r == name) { repos.push(name.to_string()); } } @@ -191,6 +244,7 @@ fn extract_repo( let issues = gh_api_objects(&format!("repos/{repo}/issues?state=all&per_page=100"))?; let mut threads: BTreeMap = BTreeMap::new(); for issue in &issues { + check_row_repo(issue, "repository_url", repo)?; let Some(number) = issue.get("number").and_then(Json::as_u64) else { continue; }; @@ -235,6 +289,9 @@ fn extract_repo( let raw = gh_api_objects(&format!( "repos/{repo}/issues/comments?per_page=100{since_q}" ))?; + for row in &raw { + check_row_repo(row, "issue_url", repo)?; + } let comments: Vec = raw .iter() .filter_map(|c| { @@ -265,6 +322,9 @@ fn extract_repo( let raw = gh_api_objects(&format!( "repos/{repo}/pulls/comments?per_page=100{since_q}" ))?; + for row in &raw { + check_row_repo(row, "pull_request_url", repo)?; + } let comments: Vec = raw .iter() .filter_map(|c| { @@ -302,6 +362,9 @@ fn extract_repo( .collect(); for number in pr_numbers { let raw = gh_api_objects(&format!("repos/{repo}/pulls/{number}/reviews?per_page=100"))?; + for row in &raw { + check_row_repo(row, "pull_request_url", repo)?; + } let reviews: Vec = raw .iter() .filter_map(|r| { diff --git a/pkgs/atlas-search/tests/test_github_comments_checkpoint.py b/pkgs/atlas-search/tests/test_github_comments_checkpoint.py index 99246645e..f3a0509e5 100644 --- a/pkgs/atlas-search/tests/test_github_comments_checkpoint.py +++ b/pkgs/atlas-search/tests/test_github_comments_checkpoint.py @@ -18,17 +18,19 @@ def record(n, key, thread): "created_at":stamp(n), "submitted_at":stamp(n), "updated_at":stamp(n), key:f"https://api.github.com/repos/developing-today/atlas-fixture/issues/{thread}"} if route.endswith("/issues"): - rows = [{"number":n, "pull_request":{}, "labels":[]} for n in (1, 2)] + owner = "external-fixture" if os.environ.get("FIXTURE_TRANSFER") else "developing-today" + rows = [{"number":n, "repository_url":f"https://api.github.com/repos/{owner}/atlas-fixture", + "pull_request":{}, "labels":[]} for n in (1, 2)] elif route.endswith("/issues/comments"): rows = [record(5, "issue_url", 1)] elif route.endswith("/pulls/comments"): rows = [record(3, "pull_request_url", 2)] elif route.endswith("/pulls/1/reviews"): - rows = [record(4, "unused", 1)] + rows = [record(4, "pull_request_url", 1)] elif route.endswith("/pulls/2/reviews"): if os.environ.get("FIXTURE_FAILURE"): sys.exit(1) - rows = [record(2, "unused", 2)] + rows = [record(2, "pull_request_url", 2)] else: raise SystemExit("unexpected fixture route") for row in rows: @@ -52,6 +54,19 @@ def exercise(directory, cli): def ids(): return [json.loads(line)["comment_id"] for line in output.read_text().splitlines()] + # Explicit targets must fail before creating output or using the fake gh. + scratch = directory / "forbidden-output" + for target in ("outside-fixture/name", "dezren39/../repos", "dezren39/%2e%2e", + "developing-today/name?query=1", "developing-today-forks/.."): + invalid = subprocess.run([str(cli), "--repo", target, "--state", str(state), + "--out", str(scratch)], env=env, capture_output=True) + assert invalid.returncode == 1 and b"permitted" in invalid.stderr + assert not scratch.exists() + # A transfer reflected in the canonical repository URL must fail closed. + transfer = subprocess.run(cmd, env=dict(env, FIXTURE_TRANSFER="1"), capture_output=True) + assert transfer.returncode == 1 and b"unexpected GitHub repository" in transfer.stderr + assert state.read_text() == initial and ids() == [] + # Independent oracle: an unsuccessful last stream leaves the entire prior # checkpoint and append unchanged. Successful retry emits every eligible ID. failure = subprocess.run(cmd, env=dict(env, FIXTURE_FAILURE="1"), capture_output=True)