Skip to content

fix(migrations): cap migration authority to the creating key's scopes - #15145

Merged
ChiragAgg5k merged 3 commits into
mainfrom
fix/migrations-key-scope-grant
Oct 31, 2026
Merged

ChiragAgg5k merged 3 commits into
mainfrom
fix/migrations-key-scope-grant

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Migrations ran every destination write with the worker's own authority: an ephemeral key holding every project scope, plus direct database writers. The only check on POST /v1/migrations/* was migrations.write, so a key restricted to that scope could import users, memberships, project auth settings, webhooks and API keys with arbitrary scopes.

This caps a migration's authority to the key that created it:

  • Request-time gate. The Appwrite, Firebase, Supabase, NHost and CSV/JSON import endpoints reject a key that lacks the write scope of any requested resource with general_unauthorized_scope. The map lives on the shared Migrations/Http/Migrations/Action and uses the same scopes as the real endpoints. Project settings need project.write. Imports need the row/document write scope for the database type, plus files.read for non-internal files.
  • Recorded grant. The key's scopes are saved in options.scopes. Console sessions record nothing and keep full authority.
  • Worker key intersection. generateAPIKey() intersects its scopes with the recorded grant. getAPIKeyScopes() is unchanged, so Cloud's override still applies.
  • Imported API keys. The Appwrite destination takes an optional scopes grant, and createApiKey() rejects imported keys holding scopes outside it, since that writer bypasses Key::mayCreate().

Behaviour change: keys running full migrations now need the write scopes of what they import. The e2e project key gains keys.write, platforms.write, policies.write, project.oauth2.write and templates.write for testCreateAppwriteMigration.

Test Plan

  • New e2e tests: testAppwriteMigrationRejectsKeyWithoutResourceScopes (401 without the needed scopes, 202 with them and the grant recorded) and testAppwriteMigrationRejectsApiKeyBroaderThanGrant.
  • Unit: tests/unit/Platform/Workers/MigrationsTest.php and tests/unit/Migration/MigrationsWorkerExportTest.php pass.
  • Pint and PHPStan are clean on the changed files. E2E runs in CI.

Not in scope: imported key expiry vs the creator's, read-scope checks on CSV/JSON exports, and reinstating the destination report() probe.

Related: appwrite-labs/cloud#6666

A key holding only migrations.write could import users, memberships, project
auth settings and API keys, because the worker wrote with an all-scope key and
direct database writers. Requests now need the write scopes of every imported
resource, the grant is recorded on the migration, the worker key is intersected
with it, and imported API keys may not exceed it.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (2)

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 SDK spec descriptions omit new scope requirements (Create.php:41) — The new authorize() gate rejects API keys lacking per-resource write scopes (e.g. users.write, databases.write), but the new Method(...) SDK specs still carry only the legacy descriptions with no mention of scope requirements (src/Appwrite/Platform/Modules/Migrations/Http/Migrations/Appwrite/Create.php:41-51 and the Firebase/NHost/Supabase/CSV/JSON counterparts).

This PR restricts Appwrite-to-Appwrite migrations so the ephemeral key used by the migration worker can only grant scopes the creating API key actually holds. Endpoints now pre-validate the key's grant against per-resource write scopes, the persisted migration records options.scopes, and the worker intersects the grant when generating the key.

Files Change
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/* and Action.php Adds an authorize() gate to all migration create endpoints (Appwrite, Firebase, NHost, Supabase, CSV/JSON imports) validating per-resource scope grants
src/Appwrite/Platform/Workers/Migrations.php Caps the ephemeral migration key to array_intersect(scopes, options.scopes)
packages/migration/src/Destinations/Appwrite.php Destination generateAPIKey accepts the capped scope set
tests/e2e/*, tests/unit/* Adds e2e reject/success paths and unit tests for the persisted scope grant

Reviewed commit: 9cfecd7

@ghost

ghost commented Oct 31, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The previously reported unrestricted API-key retry path is now covered by the new authorization check, and I found no remaining issue in these incremental changes.

The PR validates migration requests against the caller's resource scopes, records the creating key's grant, and limits worker authority and imported API keys to that grant. Retry requests also apply the retrying key's scope limits, including for migrations without a recorded key grant.

Latest changes: The latest commits authorize API-key retries of migrations without a recorded grant against the migration resources, intersect retries of granted migrations with the retrying key's scopes, and add e2e coverage for the retry behavior.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 16
File Change
packages/migration/src/Destinations/Appwrite.php Rejects imported API keys whose scopes exceed the migration grant.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/Action.php Defines resource and database-family scope requirements for migration authorization.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/Appwrite/Create.php Checks requested resource scopes and records the creator's grant.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/CSV/Exports/Create.php Checks source read scopes and records the export creator's grant.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/CSV/Imports/Create.php Checks destination write scopes and records the import creator's grant.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/Firebase/Create.php Checks requested resource scopes and records the creator's grant.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/JSON/Exports/Create.php Checks source read scopes and records the export creator's grant.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/JSON/Imports/Create.php Checks destination write scopes and records the import creator's grant.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/NHost/Create.php Checks requested resource scopes and records the creator's grant.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/Supabase/Create.php Checks requested resource scopes and records the creator's grant.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/Update.php Constrains retry authority to the retrying key and authorizes legacy or session-created migrations against their resources.
src/Appwrite/Platform/Workers/Migrations.php Intersects worker API-key scopes with the migration's recorded grant and fails closed without one.
tests/e2e/Scopes/ProjectCustom.php Adds scopes required by the Appwrite migration e2e coverage.
tests/e2e/Services/Migrations/MigrationsBase.php Covers resource-scope rejection, retry scope limits, and imported API-key grants.
tests/unit/Migration/MigrationsWorkerExportTest.php Updates the worker API-key generator test override for its grant-aware signature.
tests/unit/Platform/Workers/MigrationsTest.php Updates the worker API-key generator test override for its grant-aware signature.
✅ Fixed since the last review · 1
  • Do not preserve an unrestricted grant on API-key retries · src/Appwrite/Platform/Modules/Migrations/Http/Migrations/Update.php:84

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

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

@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 per-resource scope attenuation to the migrations service: create endpoints validate API-key grants, and the worker caps the ephemeral migration key to the grant.

Key findings

Comment on lines +582 to +584
if (\is_array($grant)) {
$scopes = \array_values(\array_intersect($scopes, $grant));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 bug · medium

Scope cap breaks function imports mid-migration

The worker's ephemeral key is now intersected down to the creating key's grant (src/Appwrite/Platform/Workers/Migrations.php:582-584), but the destination still imports functions over the HTTP API passing the function's stored scopes (packages/migration/src/Destinations/Appwrite.php:2742-2760). The API rejects a function whose scopes the key cannot grant with An API key cannot grant scopes it does not hold (src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php:205-206). A source function with exec scopes broader than the migration key's grant therefore fails mid-transfer with a bare 401, failing the whole migration — a regression from the previous all-scopes ephemeral key, and the over-scope case is never surfaced as a clear per-resource error like the analogous createApiKey check does. The same applies to sites with broader scopes.

📋 Prompt for AI Agents

In src/Appwrite/Platform/Workers/Migrations.php around lines 577-584 the ephemeral JWT scopes are capped to the creating key's grant via array_intersect, which makes destination function/site imports fail mid-migration: packages/migration/src/Destinations/Appwrite.php createFunction (lines 2742-2760) passes resource->getScopes() to the HTTP API, and src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php:205 rejects functions whose scopes the key cannot grant. Fix so an over-scoped resource does not hard-fail the migration: either intersect the resource's stored scopes with the grant before import, or catch the GENERAL_UNAUTHORIZED_SCOPE failure for TYPE_FUNCTION/TYPE_SITE in the destination and record it as a skipped-resource error instead of a migration-fatal error. Keep the destination-side cap in createApiKey consistent with the chosen policy.

Comment on lines 340 to 344
#[\Override]
protected function generateAPIKey(Document $project): string
protected function generateAPIKey(Document $project, Document $migration): string
{
return 'key';
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 bug · medium

Unit tests stub generateAPIKey, attenuation untested

Both MigrationsWorkerExportTest and MigrationsTest override generateAPIKey(...) to return a hardcoded 'key', so the new attenuation logic (array_intersect($scopes, $grant)) at src/Appwrite/Platform/Workers/Migrations.php:582-584 is never executed by a unit test. The only checks are indirect: the e2e reject paths and a success-path assertion on the persisted options.scopes — no test decodes the emitted ephemeral JWT and asserts its scope set equals the grant intersection, nor runs the migration to completion with the capped key. A regression in the intersection (e.g. dropping migrations.write, or ignoring the grant on the success path) would pass the whole suite.

📋 Prompt for AI Agents

Add unit coverage for the attenuation in src/Appwrite/Platform/Workers/Migrations.php lines 577-606: call the real (non-overridden) generateAPIKey with a migration whose options.scopes is a strict subset of getAPIKeyScopes(), decode the returned API_KEY_EPHEMERAL_... JWT, and assert the payload scopes array equals the intersection; add a case with options.scopes absent expecting the full getAPIKeyScopes() set. Currently tests/unit/Platform/Workers/MigrationsTest.php (lines 340-344) and tests/unit/Platform/Workers/MigrationsWorkerExportTest.php override the method to return 'key', leaving the logic untested. Additionally, extend the success branch of testAppwriteMigrationRejectsKeyWithoutResourceScopes in tests/e2e/Services/Migrations/MigrationsBase.php (around lines 946-969) to poll GET /migrations/:id until stage 'finished' and assert status 'completed', proving the capped ephemeral key can actually perform the export.

ghost
ghost previously requested changes Oct 31, 2026

@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 C · 2 blocking findings to address. Summary

@github-actions

github-actions Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/migrations-key-scope-grant (after).

Metric Before After Change
🚀 Requests/sec 163.01 169.79 ⚪ +4.2%
⏱️ Latency P50 104.95 ms 101.42 ms ⚪ -3.4%
⏱️ Latency P95 251.28 ms 237.07 ms 🟢 -5.7%
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 101.42 237.07 10,716 169.79 -14.21
Account 197.93 363.52 564 9.31 -21.14
TablesDB 97.88 184.6 5,828 94.5 +0.04
Storage 94.44 217.17 2,820 47.8 -10.57
Functions 139.27 278.7 1,504 26.19 -52.57

Top API waits (after)

API request Max wait (ms)
storage.buckets.create 604.55
account.name.update 505.49
functions.create 482.87
functions.variables.update 472.8
account.prefs.update 459.51

…thout a grant

Shared names like collection and document are written straight to the database,
so a TablesDB scope must not authorize a DocumentsDB or VectorsDB import. A
migration with no recorded grant now gets none instead of every scope; retries
stamp the retrying caller's grant, and exports record one too.
@ghost
ghost dismissed their stale review October 31, 2026 15:16

The findings that requested changes are resolved. See the summary comment for what is still open.

ghost
ghost previously requested changes Oct 31, 2026

@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 D · 1 blocking finding to address. Summary

A key retrying a Console-created migration kept its null grant and reran it with
every scope. A key retry now intersects the recorded grant with its own scopes,
and checks the resources when the recorded grant was never checked against them.
@ghost
ghost dismissed their stale review October 31, 2026 15:30

The findings that requested changes are resolved. See the summary comment for what is still open.

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

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