Skip to content

fix(vcs): bind Entire and Origin installation state to the console user (appwrite:appwrite:alert#4626) - #15181

Merged
ChiragAgg5k merged 4 commits into
mainfrom
fix/vcs-entire-origin-state-binding
Nov 10, 2026
Merged

ChiragAgg5k merged 4 commits into
mainfrom
fix/vcs-entire-origin-state-binding

Conversation

@claudear

@claudear claudear commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

What

Closes code-scanning alert appwrite:appwrite:alert#4626.

The hardening that introduced Appwrite\Vcs\State — projectId plus userId, an expiry and a single-use nonce under the HMAC — reached GitHub/Callback/Get.php and the shared OAuth Callback/Base.php, but the Entire and Origin flows were never migrated. Before this PR, grep 'State::' over Modules/VCS/Http matched only those two call sites.

Both Entire and Origin signed hash_hmac('sha256', json_encode([$projectId, $success, $failure]), $key) — no user, no expiry, no nonce — and their scope => public callbacks injected no user and verified that HMAC alone.

Impact

A console user with vcs.read on any project could call GET /v1/vcs/entire/authorize (or /v1/vcs/origin/authorize) for their own project, capture the install URL that embeds the signed state verbatim, and send it to a victim. When the victim approved the Appwrite plugin for their own Entire project / Cursor workspace, the callback verified only the HMAC over the attacker's projectId and wrote an installations document holding the victim's providerInstallationId under the attacker's project. Factory::fromInstallation() mints provider credentials from the server-wide appId/privateKey plus that installation id, so no victim-held token is needed: the attacker's project gained the plugin's full scope set — including repository:contents:write and repository:pull_requests:write — over the victim's repositories.

Two secondary defects on the same path: the state never expired, so a leaked or logged one stayed usable forever, and the Origin callback had no single-use record at all.

How

All four actions move onto Appwrite\Vcs\State, mirroring GitHub/Callback/Get.php:

  • Entire/Authorize/Get.php, Origin/Authorize/Get.php — inject user and sign through State::create($project->getId(), $user->getId(), $success, $failure). Origin gains the APP_LIMIT_VCS_STATE check its sibling already had, and its callback's state param moves from a bare 4096 to that constant.
  • Entire/Callback/Get.php, Origin/Callback/Get.php — inject user, verify with State::verify(), then reject an expired state, reject $user->isEmpty() || $user->getId() !== $state->userId, and consume $state->nonce as a single-use vcsCommentLocks document. That last one is the single-use guard Origin had none of; Entire's existing receipt jti lock stays as defence in depth.
  • Both callbacks invert the state precedence: the receipt's state claim is now authoritative, and a query state present alongside it must hash_equals it, so a provider-signed receipt can no longer be re-paired with an attacker-supplied state.
  • The Entire cancel path (error, no receipt) still asks for no more than a valid signature — nothing is granted there, it only picks the redirect back to the console.

State grows the base64url transport Entire needs for its opaque state token (encode(), and verify() reading either form), replacing the decodeState() the Entire callback hand-rolled.

Tests

TDD, red first:

  • tests/e2e/Services/VCSEntire — testCreateInstallationCancelledWithUnboundState builds a state signed the legacy way (project + two redirect URLs, no user, expiry or nonce) with the server's real _APP_OPENSSL_KEY_V1 and asserts the callback refuses it with no location header. On main that state verifies and the callback redirects. Its counterpart testCreateInstallationCancelledWithBoundState asserts a properly bound state is still accepted, which also fails on main — the old three-field check rejects a six-field signature.
  • tests/unit/Vcs/StateTest.php — testVerifiesEncodedState / testRejectsEncodedOtherKey cover the new opaque-token transport (both errored before the change, as encode() did not exist), and testRejectsUnboundState pins, in both encodings, that a state without userId, expire and nonce never verifies.

Verified locally in a PHP 8.5 container: tests/unit/Vcs green (107 tests), Pint and PHPStan clean on the touched files, composer refactor:check clean. The Entire e2e lane was not run locally — the only Appwrite stack on this host belongs to another checkout and binds :80/:443/:9501, so a second stack would collide; .github/ci/e2e.json already maps src/Appwrite/Platform/Modules/VCS/ to the VCSEntire and VCSGitHub lanes, so CI covers it. The 17 unit errors outside tests/unit/Vcs are environmental (KeyTest needs _APP_OPENSSL_KEY_V1, ListCacheTest needs Redis) and are unrelated to this change.

🤖 Generated with Claude Code

The hardening that introduced Appwrite\Vcs\State -- projectId plus userId,
an expiry and a single-use nonce under the HMAC -- reached the GitHub App
callback and the shared OAuth callback, but not the Entire and Origin
flows. Those two still signed only the project id and the two redirect
URLs, and their public callbacks accepted any state whose HMAC verified,
with no user injected, no expiry and no nonce. A project member could
hand the resulting install link to a victim and have the victim's
installation -- and so the plugin's repository read and write access --
recorded under the member's own project.

Move all four actions onto State: the authorize actions inject the user
and sign through State::create(), and the callbacks verify with
State::verify(), reject an expired state and a user who did not start the
flow, and consume the nonce, which also gives Origin the single-use guard
it had none of. The receipt's state claim is now the authoritative one, so
a provider-signed receipt can no longer be re-paired with an
attacker-supplied state. State itself grows the base64url transport Entire
needs for its opaque state token, which the Entire callback used to
hand-roll.

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

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 State lock consumed before installation attach completes — Get.php:129

The change introduces a signed, expiring VCS state token (src/Appwrite/Vcs/State.php) used by the Entire and Origin authorize/callback endpoints, with HMAC verification, expiry, and user binding enforced before an installation is attached. Callbacks record one-time vcs-state- and entire-receipt- lock rows in vcsCommentLocks to prevent state/receipt replay, and redirect the browser to signed console success/failure URLs rather than returning API responses. E2E and unit tests cover the new state class and the Entire console client flow.

Files Change
src/Appwrite/Vcs/State.php, tests/unit/Vcs/StateTest.php New signed-state helper (sign/verify with HMAC, base64url, expiry) plus unit coverage
src/Appwrite/Platform/Modules/VCS/Http/Entire/*, src/Appwrite/Platform/Modules/VCS/Http/Origin/* Authorize and callback endpoints rewritten to use the signed state, replay locks, user binding, and signed redirects
tests/e2e/Services/VCSEntire/VCSEntireConsoleClientTest.php E2E coverage for the Entire install flow via the console client

Reviewed commit: 9e4ecd5

@ghost

ghost commented Nov 2, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

A non-string state claim is currently treated as absent, allowing a query state to replace it in an uncommon malformed-receipt case.

Entire and Origin installation callbacks now use signed, user-bound state with expiry and single-use nonce checks, while their authorization flows create that state. The shared State implementation supports base64url transport, and regression tests cover bound and legacy states. The callbacks also treat the provider receipt's state claim as authoritative over a query parameter.

Latest changes: The latest commits type-check the receipt state claim before using it, avoiding coercion of non-string claims in both callbacks.

Verdict New comments Fixed Still open
💬 Commented 1 0 0

Note

Not approving while a bug finding is open: Reject present non-string receipt state claims

Finding Where
🟡 Reject present non-string receipt state claims src/Appwrite/Platform/Modules/VCS/Http/Entire/Callback/Get.php:105
Fix with agent prompt
### Issue 1
src/Appwrite/Platform/Modules/VCS/Http/Entire/Callback/Get.php:105
**Reject present non-string receipt state claims**

If a verified receipt contains `state` as an array or number, this maps it to `''`, so the following fallback accepts the caller-supplied query state instead of rejecting the malformed claim. That weakens the receipt-authoritative check and regresses the previous behavior, which failed verification for these non-string values; the same issue is present in Origin's callback at line 92.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 7
File Change
src/Appwrite/Platform/Modules/VCS/Http/Entire/Authorize/Get.php Creates Entire installation state bound to the initiating user and encodes it for transport.
src/Appwrite/Platform/Modules/VCS/Http/Entire/Callback/Get.php Verifies Entire callback state, user, expiry, and nonce; checks receipt/query state consistency.
src/Appwrite/Platform/Modules/VCS/Http/Origin/Authorize/Get.php Creates user-bound Origin state and enforces the configured state size limit.
src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php Verifies Origin callback state, user, expiry, and nonce; checks receipt/query state consistency.
src/Appwrite/Vcs/State.php Adds base64url state encoding and verification while preserving the signed state fields.
tests/e2e/Services/VCSEntire/VCSEntireConsoleClientTest.php Covers cancellation callbacks with legacy unbound state and properly bound state.
tests/unit/Vcs/StateTest.php Tests encoded-state verification and rejection of unbound states.

Reviewed the commits since 9e4ecd5 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

A provider that echoed the state as a nested object instead of a string
would have reached \strval() on an array. The query parameter stays the
fallback for that case, as it was before the claim became authoritative.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions

github-actions Bot commented Nov 2, 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.

@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.

This PR reworks the VCS Entire/Origin OAuth install flows by moving state signing/verification into src/Appwrite/Vcs/State.php, adding single-use state and receipt locks in vcsCommentLocks, and binding callbacks to the initiating console user.

Key findings

  • 🟡 State lock consumed before installation attach completes — Get.php:129

@ghost ghost 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

$state = $this->verifiedState(!empty($state) ? $state : \strval($receiptClaims['state'] ?? ''));
$projectId = $state['projectId'] ?? '';
$redirectFailure = $state['failure'] ?? '';
$receiptState = \is_string($receiptClaims['state'] ?? null) ? $receiptClaims['state'] : '';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reject present non-string receipt state claims

If a verified receipt contains state as an array or number, this maps it to '', so the following fallback accepts the caller-supplied query state instead of rejecting the malformed claim. That weakens the receipt-authoritative check and regresses the previous behavior, which failed verification for these non-string values; the same issue is present in Origin's callback at line 92.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Platform/Modules/VCS/Http/Entire/Callback/Get.php
Line: 105

Comment:
**Reject present non-string receipt state claims**

If a verified receipt contains `state` as an array or number, this maps it to `''`, so the following fallback accepts the caller-supplied query state instead of rejecting the malformed claim. That weakens the receipt-authoritative check and regresses the previous behavior, which failed verification for these non-string values; the same issue is present in Origin's callback at line 92.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · security · Reply if this doesn't apply.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 5bc3223: both the Entire and Origin callbacks now refuse a receipt whose state claim is present but not a string, instead of falling back to the query parameter.

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/vcs-entire-origin-state-binding (after).

Metric Before After Change
🚀 Requests/sec 203.42 215.96 🟢 +6.2%
⏱️ Latency P50 86.25 ms 79.94 ms 🟢 -7.3%
⏱️ Latency P95 196.34 ms 192.78 ms ⚪ -1.8%
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 79.94 192.78 13,680 215.96 -3.56
Account 151.6 297.2 720 12.13 +4.05
TablesDB 76.34 138.99 7,440 120.21 -23.28
Storage 74.86 177.04 3,600 59.85 -2.89
Functions 117.34 245.79 1,920 32.72 +23.07

Top API waits (after)

API request Max wait (ms)
account.prefs.update 551.22
storage.files.download 521.06
storage.files.view 511.39
functions.create 460.82
functions.variables.update 437.98

…-state-binding

# Conflicts:
#	src/Appwrite/Platform/Modules/VCS/Http/Entire/Authorize/Get.php
#	src/Appwrite/Platform/Modules/VCS/Http/Entire/Callback/Get.php
#	src/Appwrite/Platform/Modules/VCS/Http/Origin/Authorize/Get.php
#	src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php
#	src/Appwrite/Vcs/State.php
…before the attach

A receipt whose state claim is present but not a string is now refused instead of falling back to the query parameter. The single-use state and receipt claims are taken after the project and installation id checks, so a callback that fails those checks can be retried with the same state.
@appwrite

appwrite Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

Moves Entire and Origin installation state onto the shared signed State format, binding it to the project, console user, expiry, and nonce. The callbacks now validate the bound state, enforce single use, and treat provider receipt state as authoritative; State also supports Entire’s base64url transport. Tests cover encoded and legacy-unbound state plus Entire cancellation behavior.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 7
File Change
src/Appwrite/Platform/Modules/VCS/Http/Entire/Authorize/Get.php Signs user-bound Entire state and encodes it for the provider.
src/Appwrite/Platform/Modules/VCS/Http/Entire/Callback/Get.php Verifies receipt/state consistency, expiry, user binding, and one-time use before installation.
src/Appwrite/Platform/Modules/VCS/Http/Origin/Authorize/Get.php Signs user-bound Origin state and applies the state size limit.
src/Appwrite/Platform/Modules/VCS/Http/Origin/Callback/Get.php Validates Origin receipt state, expiry, user binding, and one-time use.
src/Appwrite/Vcs/State.php Adds base64url encoding and verification support for either state representation.
tests/e2e/Services/VCSEntire/VCSEntireConsoleClientTest.php Adds regression coverage for rejecting unbound state and accepting bound state on cancellation.
tests/unit/Vcs/StateTest.php Tests encoded state verification and rejection of legacy unbound states.
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Cover the provider callback completion guards Verifier: The user-mismatch, expiry and replay guards in the Entire callback sit behind a provider-signed EdDSA receipt (verifyReceipt). An e2e test can't forge that receipt, so it can't reach the guards, unlike the GitHub suite, which sends the state directly. The state binding, expiry and nonce checks are already covered in tests/unit/Vcs/StateTest.php. The Entire e2e test also covers the signed-state cancel path. Asking for callback-path coverage that can't be built is not a concrete gap.

Reviewed 5bc3223 · Details · Comment @appwrite review to re-run, or mention @appwrite with a question.

@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

@ChiragAgg5k
ChiragAgg5k merged commit 2e592b3 into main Nov 10, 2026
77 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/vcs-entire-origin-state-binding branch November 10, 2026 21:17
ChiragAgg5k added a commit that referenced this pull request Nov 12, 2026
…inding

fix(vcs): bind Entire and Origin installation state to the console user (appwrite:appwrite:alert#4626)

(cherry picked from commit 2e592b3)
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