Skip to content

fix(vcs): build a webhook push only at the branch head the provider reports (appwrite:appwrite:alert#4648) - #15279

Merged
ChiragAgg5k merged 6 commits into
mainfrom
fix/vcs-push-branch-head
Nov 10, 2026
Merged

ChiragAgg5k merged 6 commits into
mainfrom
fix/vcs-push-branch-head

Conversation

@claudear

@claudear claudear commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes code-scanning alert appwrite:appwrite:alert#4648.

GitLab, Gitea and Bitbucket authenticate every webhook delivery with the one instance-wide secret (_APP_VCS_<PROVIDER>_WEBHOOK_SECRET) that Appwrite itself registers on each connected repository's webhook (RepositoryWebhooks::ensure()), so any tenant that has connected a repository on the instance holds the secret every other tenant's deliveries are signed with. c092f4d040 pinned a webhook deployment's owner and repository name to the resolved repository, so a forged delivery can no longer name a repository the sender controls — but the branch and the commit hash were still taken from the delivery body:

  • $activate was set when the body's branch equalled the resource's production branch, and
  • the body's commit hash went straight into createFromVcs() as the build ref.

So a signed delivery naming a victim's provider repository id, the victim's production branch and any commit that resolves in the victim's repository produced an activated production deployment of a revision the victim never pushed to that branch: a rollback to a known-vulnerable commit, an unmerged branch head, or a revision contributed through a pull request — built and run with the victim project's installation token, build configuration and variables.

A delivery authenticated with that secret speaks for no particular repository, so createGitDeployments() now trusts a push's branch and commit only once the provider itself reports the commit as that branch's head (getLatestCommit() through the stored installation), which a forged delivery cannot choose. A mismatch is skipped with a span reason; a provider lookup failure still surfaces as a failed delivery the provider can retry. GitHub is unaffected — its webhook secret belongs to the Appwrite-owned App, which is why it registers no repository webhook of its own — and the pull request path is untouched (it creates no deployment).

Longer term, the alert's other recommendation still stands: issue a per-repository webhook secret at RepositoryWebhooks::ensure() time, store it on the repositories document and verify a delivery against the secret of the repository it claims, which would also remove the need for the unscoped providerRepositoryId-only lookup.

Test Plan

tests/unit/Vcs/GitDeploymentsTest.php (new, written first and failing before the fix — the forged push created a deployment with activate => true):

  • testAPushNamingACommitThatIsNotTheBranchHeadIsRefused — a push on the production branch naming a commit the provider does not report as that branch's head makes no deployment.
  • testAPushOfTheBranchHeadIsBuiltOnAProviderWithAnInstanceWideSecret — a genuine push of the branch head still builds and still activates.

tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php:

  • testGiteaPushCannotActivateARevisionTheBranchDoesNotPointAt (new) — a signed delivery naming the production branch with a commit only a side branch points at yields no deployment of that revision and leaves the live deployment where it was.
  • testGiteaPushCannotRedirectBuildSource — the forged delivery now carries the victim's real head commit, so it still reaches deployment creation and still proves owner/name pinning.

Run locally: vendor/bin/phpunit tests/unit/Vcs tests/unit/Deployment tests/unit/Functions (159 tests, OK), composer lint and PHPStan on the changed files. The Gitea API shapes the new e2e test relies on (branches/main, contents/<path> with new_branch) were verified against a real gitea/gitea:1.21.5; the VCSGitea e2e lane itself runs in CI.

Related PRs and Issues

  • Follows up c092f4d040 ("fix(vcs): pin a webhook deployment's source to the resolved repository").

Checklist

🤖 Generated with Claude Code

…eports

GitLab, Gitea and Bitbucket authenticate every webhook delivery with the one
instance-wide secret Appwrite registers on each connected repository's webhook,
so any tenant on the instance can sign a push for another tenant's repository
id. Pinning the source to the resolved repository stopped a forged push from
naming a repository the sender controls, but the branch and the commit still
came from the delivery body: a push naming the victim's production branch and
any commit that resolves in the victim's repository was built and activated.
That let a sender roll a victim's production back to an old revision, promote an
unmerged branch, or promote a revision they contributed through a pull request,
all built and run with the victim project's token, build configuration and
variables.

A delivery authenticated with that secret speaks for no particular repository,
so trust its branch and commit only once the provider itself reports the commit
as that branch's head, which a forged delivery cannot choose. GitHub is
unaffected: its webhook secret belongs to the Appwrite-owned App, which is why
it registers no repository webhook of its own.

Co-Authored-By: Claude Opus 5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Review complete. 🟠 1 high · 🟡 2 medium

💬 Inline comments (2)

📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — Head-check gate exempts pull-request deliveries · Deployment.php:176–193 · unchanged line

// src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php
176	                if (empty($providerPullRequestId) && !\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $vcs->getSupportedWebhookScopes(), true)) {
177	                    $head = $vcs->getLatestCommit($owner, $repositoryName, $providerBranch)['commitHash'] ?? '';
178	
179	                    if (empty($providerCommitHash) || $providerCommitHash !== $head) {
180	                        Span::add("{$logBase}.build.skipped.reason", 'commit is not the branch head');
181	                        Span::add("{$logBase}.build.skipped", 'true');
182	                        Console::warning("Skipping repository '{$repositoryId}': pushed commit '{$providerCommitHash}' is not the head of branch '{$providerBranch}'");
183	                        continue;
184	                    }
185	                }
186	
187	                $isAuthorized = !$external;

The new branch-head verification only applies when $providerPullRequestId is empty (src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php:176), but the threat model it guards — deliveries authenticated only by the instance-wide webhook secret, so the body can name any repository, branch, and commit — applies equally to pull-request deliveries on those providers. PR authorization trusts the delivery body: $isAuthorized = !$external where external is body-derived, and the PR id is checked against an attacker-visible providerPullRequestIds list (lines 189-193), so a forged PR delivery passes and — at minimum — updates providerCommentId on matching deployments and creates/updates comments on any pull request of the victim repository, with an arbitrary-code build also reachable on the PR path.


This PR hardens the push-deployment webhook path against forged deliveries when the provider only supports an instance-wide webhook secret: before enqueueing a build, the code asks the provider for the latest commit on the target branch and skips repositories whose reported commit hash does not match the delivery's commit. Coverage is added at the unit level (adapter webhook-scope behavior and head-check skipping) and in the Gitea console e2e suite.

Files Change
src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php Adds a branch-head check that skips builds when the delivered commit is not the provider's current branch head, gated on missing installation webhook scope.
tests/unit/Vcs/GitDeploymentsTest.php Adds unit tests for getSupportedWebhookScopes behavior and head-mismatch skipping.
tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php Extends the Gitea e2e suite to cover the new skip path end to end.

Reviewed commit: 69eafe6

@appwrite

appwrite Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental change safely handles a non-array headers value, and I found no actionable issue in the reviewed diff.

Push deployments from GitLab, Gitea, and Bitbucket now use a commit only when the provider confirms it is the named branch’s head; mismatches and missing branches are skipped, while other lookup failures remain retryable. Gogs also verifies branch existence, and the GitHub installation-scoped flow and pull-request path remain unchanged. Unit and Gitea end-to-end tests cover genuine and forged pushes, repository-source pinning, and missing branches.

Latest changes: The newest commit checks that Gitea’s fallback branch-lookup headers are an array before reading the status code, avoiding an invalid offset when the response shape is unexpected.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 7
File Change
packages/vcs/src/Adapter/Git/Bitbucket.php Maps a missing branch from the branch-head lookup to RepositoryNotFound.
packages/vcs/src/Adapter/Git/GitLab.php Maps a missing branch from the branch-head lookup to RepositoryNotFound.
packages/vcs/src/Adapter/Git/Gitea.php Checks branch existence when the commits lookup errors; the latest change validates the fallback headers shape before reading its status.
packages/vcs/src/Adapter/Git/Gogs.php Verifies branch existence before returning its latest commit.
src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php Confirms provider-reported branch heads before creating push deployments for providers using instance-wide webhook secrets.
tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php Covers forged push revisions, repository-source pinning, and missing-branch acknowledgement.
tests/unit/Vcs/GitDeploymentsTest.php Covers refusal of a commit that is not the provider-reported branch head and acceptance of a genuine push.

Reviewed the commits since e782c19 · Details · Comment @appwrite review to re-run, or mention @appwrite with a question.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@appwrite appwrite Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adds a provider-API branch-head verification gate to GitHub webhook deployments for VCS providers without installation-scoped webhooks, plus unit and e2e coverage.

Key findings

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/vcs-push-branch-head (after).

Metric Before After Change
🚀 Requests/sec 195.89 197.6 ⚪ +0.9%
⏱️ Latency P50 88.81 ms 88.93 ms ⚪ +0.1%
⏱️ Latency P95 203.79 ms 200.6 ms ⚪ -1.6%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 88.93 200.6 12,540 197.6 -3.19
Account 159.48 309.4 660 11.1 +8.8
TablesDB 85.04 163.56 6,820 110.9 +3.11
Storage 82.94 181.56 3,300 55.04 -12.06
Functions 125.03 230.12 1,760 29.97 -7.15

Top API waits (after)

API request Max wait (ms)
account.name.update 461.93
tablesdb.rows.create 371.06
account.prefs.update 345.08
account.get 340.06
tablesdb.rows.delete 331.74

A provider error during the branch head lookup now skips that repository and records the reason on the span, so the delivery is still acknowledged. The head is looked up once per owner, repository and branch within a delivery.

@appwrite appwrite Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

… errors

A branch the provider does not know is skipped and recorded on the span. Any other head lookup error reaches the existing error path, so the delivery is reported as failed and can be redelivered. The Gitea, Gogs, GitLab and Bitbucket adapters now report a missing branch as RepositoryNotFound, as the GitHub adapter already does.

@appwrite appwrite Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · Looks good to merge. Summary

The existing Gitea e2e test now also sends a delivery for a missing branch and checks it is acknowledged without creating a deployment.

@appwrite appwrite Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

Gitea 1.21 answers the latest commit lookup for a missing branch with a server error, so the adapter checks the branch itself before reporting the failure.
Keeps the package static analysis baseline unchanged.
@ChiragAgg5k
ChiragAgg5k merged commit 8d99ba4 into main Nov 10, 2026
36 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/vcs-push-branch-head branch November 10, 2026 21:39
ChiragAgg5k added a commit that referenced this pull request Nov 12, 2026
fix(vcs): build a webhook push only at the branch head the provider reports (appwrite:appwrite:alert#4648)

(cherry picked from commit 8d99ba4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants