diff --git a/README.md b/README.md index c216f74..a2268ff 100644 --- a/README.md +++ b/README.md @@ -259,6 +259,10 @@ that head branch to target the default branch with no recorded base change, the exact trusted reusable pin, a run head equal to the receipt head, and a PR whose head branch matches the run. A receipt for an older head never satisfies a newer one. If a PR was retargeted, push the change on a fresh branch. +Base-history proof uses the filtered timeline nodes and requires a complete +connection with no base-change events. GitHub's timeline `totalCount` can include +unrelated events despite the `itemTypes` filter, so it cannot prove that a base +changed. Missing, malformed, or incomplete filtered results fail closed. ### Thin completion caller (example) diff --git a/scripts/profile_consumer.mjs b/scripts/profile_consumer.mjs index c5f2068..7a8b9cd 100644 --- a/scripts/profile_consumer.mjs +++ b/scripts/profile_consumer.mjs @@ -69,7 +69,8 @@ const HEAD_PULLS_QUERY = ' repository(owner: $owner, name: $name) {' + ` pullRequests(headRefName: $head, first: ${MAX_HEAD_PULL_REQUESTS}, states: [OPEN, CLOSED, MERGED]) {` + ' totalCount nodes { number baseRefName headRepository { nameWithOwner }' + - ' timelineItems(itemTypes: [BASE_REF_CHANGED_EVENT, AUTOMATIC_BASE_CHANGE_SUCCEEDED_EVENT], first: 1) { totalCount } } } } }'; + ' timelineItems(itemTypes: [BASE_REF_CHANGED_EVENT, AUTOMATIC_BASE_CHANGE_SUCCEEDED_EVENT], first: 1) {' + + ' nodes { __typename } pageInfo { hasNextPage } } } } } }'; const BRANCH_RE = /^[^\x00-\x1f\x7f ~^:?*\[\\]{1,255}$/; function unauthorized(reason) { @@ -237,11 +238,18 @@ export async function verifyTargetBase(github, { owner, repo, repository, defaul if (node.headRepository?.nameWithOwner !== repository.full_name) { continue; } - const changed = node.timelineItems?.totalCount; - if (!Number.isInteger(node.number) || node.number <= 0 || !Number.isInteger(changed)) { + // GitHub's timeline totalCount includes items outside the itemTypes filter. + // Only an empty, complete filtered connection proves no base change. + const changes = node.timelineItems?.nodes; + if ( + !Number.isInteger(node.number) || + node.number <= 0 || + !Array.isArray(changes) || + node.timelineItems?.pageInfo?.hasNextPage !== false + ) { throw new Error('head branch pull request entry is invalid'); } - if (node.baseRefName !== defaultBranch || changed !== 0) { + if (node.baseRefName !== defaultBranch || changes.length !== 0) { throw new Error('pull_request_target head branch has a non-default or changed base'); } numbers.push(node.number); diff --git a/scripts/profile_github.py b/scripts/profile_github.py index adfdbc9..f80d898 100644 --- a/scripts/profile_github.py +++ b/scripts/profile_github.py @@ -41,7 +41,8 @@ " repository(owner: $owner, name: $name) {" " pullRequests(headRefName: $head, first: %d, states: [OPEN, CLOSED, MERGED]) {" " totalCount nodes { number baseRefName headRepository { nameWithOwner }" - " timelineItems(itemTypes: [%s], first: 1) { totalCount } } } } }" + " timelineItems(itemTypes: [%s], first: 1) {" + " nodes { __typename } pageInfo { hasNextPage } } } } } }" ) % (MAX_HEAD_PULL_REQUESTS, _BASE_CHANGE_ITEMS) @@ -568,16 +569,20 @@ def verify_target_base(self, head_branch: str) -> tuple[int, ...]: continue # Fork runs are rejected by head_repository; forks cannot retarget ours. number = node.get("number") changes = node.get("timelineItems") - changed = changes.get("totalCount") if isinstance(changes, Mapping) else None + # GitHub's timeline totalCount includes items outside the itemTypes filter. + # Only an empty, complete filtered connection proves no base change. + events = changes.get("nodes") if isinstance(changes, Mapping) else None + page = changes.get("pageInfo") if isinstance(changes, Mapping) else None if ( not isinstance(number, int) or isinstance(number, bool) or number <= 0 - or not isinstance(changed, int) - or isinstance(changed, bool) + or not isinstance(events, list) + or not isinstance(page, Mapping) + or page.get("hasNextPage") is not False ): raise ProfileGitHubError("head branch pull request entry is invalid") - if node.get("baseRefName") != self.config.default_branch or changed != 0: + if node.get("baseRefName") != self.config.default_branch or events: raise ProfileGitHubError( "pull_request_target head branch has a non-default or changed base" ) diff --git a/tests/profile-consumer.test.mjs b/tests/profile-consumer.test.mjs index 52e135f..cf32576 100644 --- a/tests/profile-consumer.test.mjs +++ b/tests/profile-consumer.test.mjs @@ -233,7 +233,7 @@ function buildStore(options = {}) { number: PULL_NUMBER, baseRefName: DEFAULT_BRANCH, headRepository: { nameWithOwner: REPOSITORY.full_name }, - timelineItems: { totalCount: 0 }, + timelineItems: { nodes: [], pageInfo: { hasNextPage: false } }, }, ]; return { repository: { pullRequests: { totalCount: options.targetTotal ?? nodes.length, nodes } } }; @@ -678,7 +678,7 @@ describe('authorizeProfileReceipt trusted caller events', () => { number: PULL_NUMBER, baseRefName: DEFAULT_BRANCH, headRepository: { nameWithOwner: REPOSITORY.full_name }, - timelineItems: { totalCount: 0 }, + timelineItems: { nodes: [], pageInfo: { hasNextPage: false } }, ...overrides, }); @@ -695,6 +695,64 @@ describe('authorizeProfileReceipt trusted caller events', () => { assert.deepEqual(store.graphqlCalls[0].variables, { owner: OWNER, name: REPO, head: 'topic' }); assert.match(store.graphqlCalls[0].query, /BASE_REF_CHANGED_EVENT/); assert.match(store.graphqlCalls[0].query, /AUTOMATIC_BASE_CHANGE_SUCCEEDED_EVENT/); + assert.match(store.graphqlCalls[0].query, /nodes \{ __typename \} pageInfo \{ hasNextPage \}/); + }); + + it('ignores unfiltered timeline totals when the filtered connection is empty and complete', async () => { + const { github, store } = buildStore({ + reviewRunOverrides: target, + reviewRuns: [reviewRun(target)], + targetPulls: [targetPull({ + timelineItems: { totalCount: 17, nodes: [], pageInfo: { hasNextPage: false } }, + })], + }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, true, result.reason); + }); + + it('rejects manual and automatic base changes even if the timeline total is zero', async () => { + for (const __typename of ['BaseRefChangedEvent', 'AutomaticBaseChangeSucceededEvent']) { + const { github, store } = buildStore({ + reviewRunOverrides: target, + reviewRuns: [reviewRun(target)], + targetPulls: [targetPull({ + timelineItems: { totalCount: 0, nodes: [{ __typename }], pageInfo: { hasNextPage: false } }, + })], + }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, false); + assert.match(result.reason, /changed base/); + } + }); + + it('rejects missing, malformed or incomplete filtered timeline connections', async () => { + for (const timelineItems of [ + undefined, + null, + [], + {}, + { totalCount: 0 }, + { nodes: null, pageInfo: { hasNextPage: false } }, + { nodes: {}, pageInfo: { hasNextPage: false } }, + { nodes: [], pageInfo: null }, + { nodes: [], pageInfo: {} }, + { nodes: [], pageInfo: { hasNextPage: true } }, + { nodes: [], pageInfo: { hasNextPage: null } }, + { nodes: [], pageInfo: { hasNextPage: 0 } }, + { nodes: [], pageInfo: { hasNextPage: 'false' } }, + { nodes: [null], pageInfo: { hasNextPage: false } }, + { nodes: [{}], pageInfo: { hasNextPage: false } }, + { nodes: [{ __typename: 'IssueComment' }], pageInfo: { hasNextPage: false } }, + ]) { + const { github, store } = buildStore({ + reviewRunOverrides: target, + reviewRuns: [reviewRun(target)], + targetPulls: [targetPull({ timelineItems })], + }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, false, JSON.stringify(timelineItems)); + assert.match(result.reason, /head branch/); + } }); it('ignores fork PRs that share the head branch name', async () => { @@ -713,7 +771,6 @@ describe('authorizeProfileReceipt trusted caller events', () => { it('rejects retargeted, non-default, unbounded or missing head-branch PRs', async () => { for (const options of [ - { targetPulls: [targetPull({ timelineItems: { totalCount: 1 } })] }, { targetPulls: [targetPull({ baseRefName: 'release' })] }, { targetPulls: [targetPull(), targetPull({ number: 8, baseRefName: 'release' })] }, { targetPulls: [] }, diff --git a/tests/test_profile_completion.py b/tests/test_profile_completion.py index e503371..48a4ba3 100644 --- a/tests/test_profile_completion.py +++ b/tests/test_profile_completion.py @@ -559,7 +559,10 @@ def handler(method, url, headers, cap, data): "number": PR, "baseRefName": base, "headRepository": {"nameWithOwner": REPO}, - "timelineItems": {"totalCount": changes}, + "timelineItems": { + "nodes": [{"__typename": "BaseRefChangedEvent"}] if changes else [], + "pageInfo": {"hasNextPage": False}, + }, } ], } diff --git a/tests/test_profile_github.py b/tests/test_profile_github.py index 761d593..468e878 100644 --- a/tests/test_profile_github.py +++ b/tests/test_profile_github.py @@ -458,12 +458,12 @@ def head_pulls(*nodes, total=None): } -def head_pull(number=7, base="main", owner="RetireGolden/example", changes=0): +def head_pull(number=7, base="main", owner="RetireGolden/example"): return { "number": number, "baseRefName": base, "headRepository": None if owner is None else {"nameWithOwner": owner}, - "timelineItems": {"totalCount": changes}, + "timelineItems": {"nodes": [], "pageInfo": {"hasNextPage": False}}, } @@ -506,6 +506,7 @@ def handler(method, url, headers, cap, data): self.assertIn("headRefName: $head", payload["query"]) self.assertIn("BASE_REF_CHANGED_EVENT", payload["query"]) self.assertIn("AUTOMATIC_BASE_CHANGE_SUCCEEDED_EVENT", payload["query"]) + self.assertIn("nodes { __typename } pageInfo { hasNextPage }", payload["query"]) self.assertEqual( payload["variables"], {"owner": "RetireGolden", "name": "example", "head": "topic"}, @@ -539,10 +540,54 @@ def test_pull_request_target_ignores_fork_prs_sharing_the_branch_name(self): ) self.assertEqual(client.verify_target_base("topic"), (7,)) + def test_pull_request_target_ignores_unfiltered_timeline_total(self): + node = head_pull() + node["timelineItems"]["totalCount"] = 17 + client = self.client(head_pulls(node)) + self.assertEqual(client.verify_target_base("topic"), (7,)) + + def test_pull_request_target_rejects_manual_and_automatic_base_changes(self): + for typename in ("BaseRefChangedEvent", "AutomaticBaseChangeSucceededEvent"): + with self.subTest(typename=typename): + node = head_pull() + node["timelineItems"] = { + "totalCount": 0, + "nodes": [{"__typename": typename}], + "pageInfo": {"hasNextPage": False}, + } + with self.assertRaisesRegex(ProfileGitHubError, "changed base"): + self.client(head_pulls(node)).verify_target_base("topic") + + def test_pull_request_target_rejects_invalid_filtered_timeline_connections(self): + for timeline in ( + None, + [], + {}, + {"totalCount": 0}, + {"nodes": None, "pageInfo": {"hasNextPage": False}}, + {"nodes": {}, "pageInfo": {"hasNextPage": False}}, + {"nodes": [], "pageInfo": None}, + {"nodes": [], "pageInfo": {}}, + {"nodes": [], "pageInfo": {"hasNextPage": True}}, + {"nodes": [], "pageInfo": {"hasNextPage": None}}, + {"nodes": [], "pageInfo": {"hasNextPage": 0}}, + {"nodes": [], "pageInfo": {"hasNextPage": "false"}}, + {"nodes": [None], "pageInfo": {"hasNextPage": False}}, + {"nodes": [{}], "pageInfo": {"hasNextPage": False}}, + {"nodes": [{"__typename": "IssueComment"}], "pageInfo": {"hasNextPage": False}}, + ): + with self.subTest(timeline=timeline): + node = {**head_pull(), "timelineItems": timeline} + with self.assertRaises(ProfileGitHubError): + self.client(head_pulls(node)).verify_target_base("topic") + node = head_pull() + del node["timelineItems"] + with self.assertRaises(ProfileGitHubError): + self.client(head_pulls(node)).verify_target_base("topic") + def test_pull_request_target_rejects_retargeted_or_non_default_bases(self): for graphql in ( head_pulls(head_pull(base="release")), - head_pulls(head_pull(changes=1)), head_pulls(head_pull(), head_pull(8, base="release")), head_pulls(head_pull(owner="fork/example")), head_pulls(), @@ -552,7 +597,7 @@ def test_pull_request_target_rejects_retargeted_or_non_default_bases(self): {"data": {"repository": None}}, head_pulls({"number": True, "baseRefName": "main", "headRepository": {"nameWithOwner": "RetireGolden/example"}, - "timelineItems": {"totalCount": 0}}), + "timelineItems": {"nodes": [], "pageInfo": {"hasNextPage": False}}}), head_pulls({**head_pull(), "timelineItems": None}), ): with self.subTest(graphql=graphql): diff --git a/tests/test_profile_requests.py b/tests/test_profile_requests.py index e93942f..25a9a22 100644 --- a/tests/test_profile_requests.py +++ b/tests/test_profile_requests.py @@ -377,7 +377,7 @@ def wrapped(method, url, headers, cap, data): "number": PR, "baseRefName": base, "headRepository": {"nameWithOwner": REPO}, - "timelineItems": {"totalCount": 0}, + "timelineItems": {"nodes": [], "pageInfo": {"hasNextPage": False}}, } return response( {"data": {"repository": {"pullRequests": {"totalCount": 1, "nodes": [node]}}}}