Skip to content

fix(vcs): bind installation state to the console user and an expiry - #14793

Merged
ChiragAgg5k merged 3 commits into
mainfrom
fix/vcs-oauth-state-binding
Oct 22, 2026
Merged

ChiragAgg5k merged 3 commits into
mainfrom
fix/vcs-oauth-state-binding

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Hardens the S3-compatible gateway around multipart limits, staging cleanup, duplicate names and the bucket antivirus setting.

Multipart limits

  • UploadPart now checks the part number against the S3 range (1 to 10000) and checks the part size and the running total of the upload's other parts against the bucket's maximumFileSize before writing to the device. Before this, only CompleteMultipartUpload checked the total, after every part was already staged. Re-uploading a part number replaces its earlier size instead of adding to it.

Expired staging

  • Expired uploads used to have only their index entry dropped, which left staged chunks on the device. getMultipartUploads() now aborts the device staging of an expired upload and then purges it. The cached state outlives MULTIPART_TTL until it is purged, so it is read back with a long retention to find the path and the device upload ID. Staging that already backs a committed object is left in place. Abort failures are logged and don't fail the request.
  • CreateMultipartUpload runs the same sweep for its bucket, so expired staging is reclaimed even when nobody lists uploads.

Antivirus

  • The gateway doesn't scan objects. PutObject, CopyObject, CreateMultipartUpload, UploadPart and CompleteMultipartUpload now refuse buckets that the REST upload would scan: _APP_STORAGE_ANTIVIRUS=enabled, bucket antivirus on, and a Local device. Before, the gateway wrote to those buckets without scanning. The condition matches the REST path, so non-Local devices and deployments with antivirus off behave as before. Reads are unchanged. Buckets created through S3 keep antivirus: false, since enabling it would make them unwritable through the gateway.

Duplicate names

  • REST allows two files with the same name in a folder. ListObjects / ListObjectsV2 used to fail for the whole bucket when that happened. They now list the oldest file per key, using the existing $sequence ordering. Single-object operations on an ambiguous key still return 400 for that key only.

Also replaced an inline \Utopia\System\System with an import.

Test Plan

New E2E tests in tests/e2e/Services/Storage/S3CustomServerTest.php:

  • testUploadPartLimits (also in the s3 group so it runs against MinIO): with a 1 KiB bucket, a 1025-byte part, a second part that pushes the total past the limit, and part numbers 0 and 10001 return 400. Re-uploading part 1 succeeds, and the upload still completes and reads back.
  • testListObjectsWithDuplicateNames: two REST files with the same name plus one other. Both V1 and V2 listings return 200 with each key once.
  • testWriteAntivirusBucket: on an antivirus-enabled bucket, PutObject and CreateMultipartUpload return 400 when antivirus is enabled on a Local device (the antivirus CI lane), and 200 otherwise.
  • setupBucket() now creates buckets with antivirus: false, so the existing S3 tests also run in the antivirus lane.

The expired-staging sweep has no E2E test: forcing expiry means waiting 24 hours or rewriting the cache envelope's timestamp in Redis, which ties the test to the cache encoding.

Pint, PHPStan (host, phpstan.neon) and Rector pass on touched files. E2E is left to the CI lanes; I didn't bring up a local stack.

Related PRs and Issues

None.

Related: appwrite-labs/cloud#6666

The state handed to GitHub, GitLab, Gitea and Bitbucket was an HMAC over
the project and redirect URLs only, so a state minted by one console user
stayed valid forever and for anyone. Sign the initiating user id, an
expiry and a nonce into it, and have the callbacks require the current
console session to belong to that user before connecting an installation.
@luxor-code-review

luxor-code-review Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Review complete. 🟠 1 high

💬 Inline comments (1)

  • 🟠 Signed state is replayable; nonce is never consumed — State.php:48
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Project-not-found bypasses the failure URL fallback (Get.php:105) — The project-not-found branch passes the raw signed $state->failure to failure() instead of the computed $redirectFailure (src/Appwrite/Platform/Modules/VCS/Http/GitHub/Callback/Get.php:105).

This PR introduces Appwrite\Vcs\State, an HMAC-signed state bundle (user, provider, project, installation, success/failure URLs, expire, nonce) used to protect the VCS OAuth round-trip, and refactors the GitHub and Gitea authorize/callback endpoints to sign it at authorize time and verify it at callback time, with failure redirects on tampered, expired, or user-mismatched state. Unit tests cover tampering and expiry, and e2e tests cover the console callback flow.

Files Change
src/Appwrite/Vcs/State.php, tests/unit/Vcs/StateTest.php New signed-state helper (sign/verify) with a 1-hour TTL and nonce, plus tamper/expiry unit tests.
src/Appwrite/Platform/Modules/VCS/Http/Authorize/*, Callback/Base.php, GitHub/Callback/Get.php Sign state on authorize; verify and enforce user binding on callback; centralize failure redirects.
tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php E2E coverage of the Gitea console callback flow including the anonymous-session path.
src/Appwrite/Platform/Modules/VCS/Http/GitHub/Authorize/Get.php GitHub authorize now issues the signed state and accepts optional success/failure URLs.

Reviewed commit: 8894555

@ChiragAgg5k ChiragAgg5k self-assigned this Oct 22, 2026
@ghost

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental changes correctly wire the existing OAuth2 client into the callback and test the missing-code failure path; no fixes are needed.

VCS installation callbacks now use signed, expiring state bound to the initiating Console user, and reject mismatched or replayed state. GitHub also exchanges the returned authorization code and verifies access to the selected installation before persisting it. Unit and end-to-end tests cover state validation and callback failures.

Latest changes: The latest commits pass the injected OAuth2 client into the GitHub callback action and add an end-to-end check that a callback without an authorization code does not create an installation.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 8
File Change
src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php Mints signed OAuth state bound to the initiating Console user and an expiry.
src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php Validates OAuth callback state, owner, expiry, and one-time use for OAuth-based providers.
src/Appwrite/Platform/Modules/VCS/Http/GitHub/Authorize/Get.php Creates signed, user-bound state for GitHub installation authorization.
src/Appwrite/Platform/Modules/VCS/Http/GitHub/Callback/Get.php Validates GitHub callback state and installation access; the latest change supplies the OAuth2 client to the action.
src/Appwrite/Vcs/State.php Defines the signed state value and its verification and expiry checks.
tests/e2e/Services/VCSGitHub/VCSGitHubConsoleClientTest.php Covers GitHub callback state failures and, in the latest change, missing authorization codes.
tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php Updates Gitea callback state setup and covers owner, expiry, and replay failures.
tests/unit/Vcs/StateTest.php Tests state signing, verification, malformed values, tampering, and expiry.

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

@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 · 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 signed, expiring VCS OAuth state helper and wires GitHub/Gitea authorize and callback endpoints to it, plus unit and e2e coverage.

Key findings

  • 🟠 Signed state is replayable; nonce is never consumed — State.php:48

Comment on lines +48 to +85
public static function verify(string $state, string $key): ?self
{
$decoded = \json_decode($state, true);

if (!\is_array($decoded)) {
return null;
}

foreach (['projectId', 'userId', 'success', 'failure', 'nonce', 'signature'] as $field) {
if (!\is_string($decoded[$field] ?? null)) {
return null;
}
}

if (!\is_int($decoded['expire'] ?? null)) {
return null;
}

$verified = new self(
$decoded['projectId'],
$decoded['userId'],
$decoded['success'],
$decoded['failure'],
$decoded['expire'],
$decoded['nonce'],
);

if (!\hash_equals($verified->signature($key), $decoded['signature'])) {
return null;
}

return $verified;
}

public function isExpired(): bool
{
return $this->expire < \time();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 security · high

Signed state is replayable; nonce is never consumed

The nonce in Appwrite\Vcs\State is random but never persisted, so any validly signed state is replayable for its full 1-hour TTL — State::verify checks only the HMAC and expiry (src/Appwrite/Vcs/State.php:48). The user-binding check stops cross-account use but does not bind the OAuth transaction: driving the victim's logged-in browser to the callback with the victim's own signed state plus an attacker's installation_id/code passes every check and attaches the attacker's VCS installation — and its access — to the victim's project. Signed states travel in redirect URLs (browser history, access logs, Referer), so obtaining one within the TTL is realistic.

📋 Prompt for AI Agents

Enforce one-time use of the VCS state. In the Authorize actions (src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php and src/Appwrite/Platform/Modules/VCS/Http/GitHub/Authorize/Get.php), after State::create(...), persist the state's nonce in the platform cache/DB keyed by nonce with a 3600-second TTL before redirecting to the provider. In each callback (src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php:94 and src/Appwrite/Platform/Modules/VCS/Http/GitHub/Callback/Get.php:81), after State::verify() succeeds, atomically claim the nonce (add-if-absent) and route the flow through the existing failure() redirect when the nonce is missing or already consumed. Without this, a leaked signed state can be replayed within the TTL with a different installation_id/code to attach an attacker-controlled VCS installation to the victim's project.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in b359313: after the signature, expiry and user checks pass, each callback claims the state's nonce in vcsCommentLocks (the same pattern the Entire and Origin handlers use), so a state connects at most one installation. A replay redirects to the failure URL. There are e2e tests for this on both the Gitea and GitHub callbacks.

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

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

Metric Before After Change
🚀 Requests/sec 204.18 219.09 🟢 +7.3%
⏱️ Latency P50 83.63 ms 78.95 ms 🟢 -5.6%
⏱️ Latency P95 203.94 ms 183.55 ms 🟢 -10%
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 78.95 183.55 13,680 219.09 -20.38
Account 144.04 294.4 720 12.33 +0.15
TablesDB 76.38 148.8 7,440 121.98 -30.18
Storage 71.87 168.26 3,600 60.59 -3.03
Functions 110.52 206.87 1,920 33.07 -17.54

Top API waits (after)

API request Max wait (ms)
account.name.update 423.79
account.prefs.update 355.43
functions.create 345.93
tablesdb.rows.create 340.25
storage.buckets.create 336.52

The state was bound to its user and expiry but could be completed more
than once within that hour. Claim its nonce in the callback so each state
connects at most one installation, and cover the GitHub callback's state
checks end to end.

@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 · Looks good to merge. Summary

@github-actions

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.

…inding

# Conflicts:
#	src/Appwrite/Platform/Modules/VCS/Http/GitHub/Callback/Get.php
#	tests/e2e/Services/VCSGitHub/VCSGitHubConsoleClientTest.php
@ChiragAgg5k
ChiragAgg5k merged commit bbbc01d into main Oct 22, 2026
67 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/vcs-oauth-state-binding branch October 22, 2026 18:23
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…kport #14793)

1.9.x passed the GitHub installation state unsigned, so this also adds the HMAC signature the callback now verifies. Only the GitHub provider exists on 1.9.x.

(cherry picked from commit bbbc01d)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…kport #14793)

1.9.x passed the GitHub installation state unsigned, so this also adds the HMAC signature the callback now verifies. Only the GitHub provider exists on 1.9.x.

(cherry picked from commit bbbc01d)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…kport #14793)

1.9.x passed the GitHub installation state unsigned, so this also adds the HMAC signature the callback now verifies. Only the GitHub provider exists on 1.9.x.

(cherry picked from commit bbbc01d)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…kport #14793)

1.9.x passed the GitHub installation state unsigned, so this also adds the HMAC signature the callback now verifies. Only the GitHub provider exists on 1.9.x.

(cherry picked from commit bbbc01d)
Tapraj-Pathak pushed a commit to Tapraj-Pathak/appwrite that referenced this pull request Oct 24, 2026
…inding

fix(vcs): bind installation state to the console user and an expiry

(cherry picked from commit bbbc01d)
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.

1 participant