Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
16 changes: 12 additions & 4 deletions scripts/profile_consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down
15 changes: 10 additions & 5 deletions scripts/profile_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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"
)
Expand Down
63 changes: 60 additions & 3 deletions tests/profile-consumer.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 } } };
Expand Down Expand Up @@ -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,
});

Expand All @@ -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 () => {
Expand All @@ -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: [] },
Expand Down
5 changes: 4 additions & 1 deletion tests/test_profile_completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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},
},
}
],
}
Expand Down
53 changes: 49 additions & 4 deletions tests/test_profile_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}},
}


Expand Down Expand Up @@ -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"},
Expand Down Expand Up @@ -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(),
Expand All @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_profile_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]}}}}
Expand Down
Loading