Skip to content

fix: confine migration and certificate check connections to public addresses - #14794

Merged
ChiragAgg5k merged 8 commits into
mainfrom
fix/migrations-health-hostnames
Oct 23, 2026
Merged

ChiragAgg5k merged 8 commits into
mainfrom
fix/migrations-health-hostnames

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Two endpoints let a request reach things it shouldn't. Each is shown below with real requests against a local stack, first on main and then on this branch.

Problem After this PR
1 GET /v1/health/certificate opens a TLS connection to whatever the domain resolves to, including private and cloud-metadata addresses, and returns the raw socket error Private and reserved addresses are refused with 400 general_argument_invalid before connecting; connection errors are generic
2 CSV/JSON imports with internalFile: true read any file in the shared internal bucket, so one project can import another project's export An internal file can only be imported by the project that exported it or the console user who uploaded it; others get 404 storage_file_not_found

1. The certificate check reaches private addresses

The domain param was validated as a public domain name, but nothing checked what it resolves to. Any hostname that points at 10.x, 169.254.169.254 or 127.0.0.1 passed, and the server then connected to it on port 443. The error text ((111) Connection refused vs (110) Operation timed out) and the response time told the caller whether something was listening, which makes the endpoint a probe of the internal network.

 Before
 ──────
   ?domain=169.254.169.254.nip.io
        │
        ▼
   PublicDomain("…nip.io") ✔  ──►  stream_socket_client("ssl://169.254.169.254.nip.io:443")
                                       │   (resolves again here; DNS may answer differently)
                                       ▼
                                   404 "Failed to connect to host: (110) Operation timed out"   after 30 s


 After
 ─────
   ?domain=169.254.169.254.nip.io
        │
        ▼
   publicHostname->address()  ── resolves once ── private/reserved? ──► 400 general_argument_invalid
                                                   │ public
                                                   ▼
                              connect to that exact IP, peer_name = hostname (SNI + cert check unchanged)
                                                   │ fails
                                                   ▼
                              404 "Failed to connect to host <domain>."   (no socket details)

A host that does not resolve now returns 400 too; it used to be a 404 after a failed connect.

The certificate check on private and metadata addresses: 30 s timeouts with socket errors on main, immediate 400 on this PR

2. One project can import another project's export

CSV exports are written to the platform's internal bucket, which all projects share. The import endpoints read that bucket when internalFile is true, and they looked up the file by id only. Any project that knew an export's file id could import another tenant's data into its own collection.

 Before
 ──────
   Project A ── POST /v1/migrations/csv/exports ──► internal bucket: file 6adb…c93 (A's customers)
                                                                   ▲
   Project B ── POST /v1/migrations/csv/imports { internalFile, fileId: 6adb…c93 } ──┘
                                                 ──► 202, B's collection now holds A's rows


 After
 ─────
   worker writes  metadata.projectInternalId = A        (exports)
   storage writes metadata.uploaderId = <console user>   (Console "import local CSV" uploads)

   import accepts  projectInternalId == calling project
               or  uploaderId == calling console user
                    A, or the uploader ──► 202
                    anyone else       ──► 404 storage_file_not_found

The uploader rule keeps the Console's "Import CSV from a local file" working: the Console uploads the file to the console project's default bucket and imports it with internalFile: true, and those uploads carry uploaderId, not projectInternalId.

Export files written before this change have no owner recorded, so they can no longer be imported through internalFile. They expire with the export retention period anyway.

Project B importing project A's export: B gets A's three customers on main, 404 on this PR

Migrations source confinement

Destination confinement for migration sources (Appwrite report, NHost report, and the worker for remote Appwrite, Supabase and NHost sources) now comes from #14870 (publicHostname->getDestinations(), with deploymentHostname exempting this deployment's own hosts). This PR no longer adds its own publicInternet resource or wiring.

Changes

  • Health/Http/Health/Certificate/Get.php: resolve and check the host with the existing publicHostname validator, connect to the checked IP with peer_name set to the hostname, and return a generic connection error.
  • Workers/Migrations.php: store the exporting project's internal id in the export file's metadata.
  • Migrations/Http/Migrations/{CSV,JSON}/Imports/Create.php: with internalFile, require that id to match the calling project, or the file's uploaderId to match the calling console user.

Test Plan

  • E2E Health: testCertificateRefusesHostThatDoesNotResolve checks the 400, the error type and that no socket error details come back. The existing doesnotexist.com expectation moves from 404 to 400.
  • E2E Migrations: testCreateCSVExport now imports the export file back into the exporting project (202, completes) and from another project (404 storage_file_not_found).
  • E2E Migrations: testCreateCSVImportFromConsoleUpload and testCreateJSONImportFromConsoleUpload follow the Console's local-file import: upload to the console bucket, then import with internalFile as the uploader (202, 100 rows); the same file imported with an API key returns 404. Each fails without the uploader rule.
  • No e2e tests for the pinned certificate connection: that needs a hostname that resolves differently between the check and the connect, and the e2e stack can't provide one without third-party services.
  • Ran locally: Pint, PHPStan (host config) on the touched files, Rector dry-run on the touched tests, and tests/unit/Network.
  • The screenshots above come from a local dev stack (docker compose up), running the same requests on main (d5ccf14) and on this branch (2faaf82). The hostnames use nip.io, which resolves a.b.c.d.nip.io to a.b.c.d.

Related PRs and Issues

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

…dresses

The certificate health check and the Appwrite and NHost migration sources
connect to hosts a request names. Validate those hosts, connect the
certificate check to the address that was checked, and confine the
migration sources' HTTP clients to public destinations so DNS cannot
answer differently between the check and the connection. NHost subdomain
and region must be DNS labels and the database name an identifier, since
the source builds hostnames and a DSN from them.

Internal export files now record the project that created them, and an
import from the internal bucket requires the same project.

The certificate check no longer returns socket error details.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 1 high · 🟡 1 medium

💬 Inline comments (2)

  • 🟠 Postgres PDO connections bypass destinations pinning — Migrations.php:328
  • 🟡 database narrowed, rejects hyphenated Postgres names — Create.php:63
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Pre-upgrade export files fail owner check (Create.php:115) — The new ownership check rejects internal files whose metadata lacks projectInternalId, since $owner is null and never equals $project->getSequence() (src/Appwrite/Platform/Modules/Migrations/Http/Migrations/CSV/Imports/Create.php:117).

The change adds a fail-closed PublicInternet destinations resource and applies it to migration sources, reworks the health certificate check to connect by resolved IP while preserving SNI, narrows NHost hostname/database inputs to DNS-label and identifier validators, and adds a projectInternalId ownership check to internal export imports.

Files Change
app/init/resources.php Registers the shared publicInternet DI resource used by all guarded endpoints.
src/Appwrite/Platform/Modules/Migrations/*, src/Appwrite/Platform/Workers/Migrations.php Applies setDestinations to report/import endpoints and the worker, writes projectInternalId metadata on exports, and enforces the owner check on import.
src/Appwrite/Network/Validator/Label.php, tests/unit/Network/Validators/LabelTest.php New DNS-label validator with unit coverage for NHost subdomain/region inputs.
src/Appwrite/Platform/Modules/Health/Http/Health/Certificate/Get.php, tests/e2e/Services/Health/CertificateTest.php Certificate check now connects to the resolved IP with peer_name set to the original domain; error detail leakage removed; e2e updated.
src/Appwrite/SDK/Specification/Format/OpenAPI3.php, tests/e2e/Services/Migrations/MigrationsBase.php OpenAPI3 formatting support and e2e base updates for the narrowed parameters.

Reviewed commit: d20ba34

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

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The certificate health check now resolves hostnames through the public-hostname policy and connects to the checked address while retaining the hostname for TLS verification. Migration exports record their owning project, and CSV/JSON imports enforce ownership for internal files while allowing the uploading Console user. The E2E coverage exercises unresolved certificate hosts, same-project and cross-project exports, and Console-upload imports.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 6
File Change
src/Appwrite/Platform/Modules/Health/Http/Health/Certificate/Get.php Validates and pins the resolved address for certificate connections and hides socket details on connect failures.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/CSV/Imports/Create.php Restricts internal CSV imports to the exporting project or the uploading user.
src/Appwrite/Platform/Modules/Migrations/Http/Migrations/JSON/Imports/Create.php Restricts internal JSON imports to the exporting project or the uploading user.
src/Appwrite/Platform/Workers/Migrations.php Records the exporting project ID in export-file metadata.
tests/e2e/Services/Health/CertificateTest.php Covers unresolved-host validation and generic error responses.
tests/e2e/Services/Migrations/MigrationsBase.php Covers Console-upload ownership and same-project versus cross-project export imports.

Reviewed 3c31ad8 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

ghost
ghost previously requested changes Oct 22, 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 B · 1 blocking finding to address. 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.

This PR hardens migration and health endpoints against SSRF/DNS rebinding via a shared publicInternet destination guard, pins the health certificate TLS check to a resolved IP, and restricts internal export files to the exporting project.

Key findings

  • 🟠 Postgres PDO connections bypass destinations pinning — Migrations.php:328
  • 🟡 database narrowed, rejects hyphenated Postgres names — Create.php:63

Comment on lines +63 to +66
->param('subdomain', '', new Label(), 'Source\'s Subdomain')
->param('region', '', new Label(), 'Source\'s Region')
->param('adminSecret', '', new Text(512), 'Source\'s Admin Secret')
->param('database', '', new Text(512), 'Source\'s Database Name')
->param('database', '', new Identifier(63), 'Source\'s Database Name')

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

database narrowed, rejects hyphenated Postgres names

The database parameter changed from Text(512) to Identifier(63), which accepts only the C-identifier shape ^[A-Za-z_]\w*$ — no hyphens, dots, or empty string (src/Appwrite/Platform/Modules/Migrations/Http/Migrations/NHost/Create.php:66). Postgres database names may legitimately contain hyphens, and the NHost source connects with dbname=<databaseName> verbatim (packages/migration/src/Sources/NHost.php:132), so callers migrating a hyphenated database now get a 400 where the migration previously proceeded. The same narrowing appears in src/Appwrite/Platform/Modules/Migrations/Http/Migrations/NHost/Report/Get.php at line 59; the subdomain/region switch to Label (lines 63-64) is similarly a wire-contract narrowing, though those values form DNS labels so it likely matches reality.

📋 Prompt for AI Agents

In src/Appwrite/Platform/Modules/Migrations/Http/Migrations/NHost/Create.php line 66 and src/Appwrite/Platform/Modules/Migrations/Http/Migrations/NHost/Report/Get.php line 59, the database parameter uses new Identifier(63), whose regex ^[A-Za-z_]\w*$ rejects hyphens and dots — characters legal in Postgres database names that the PDO connection in packages/migration/src/Sources/NHost.php accepts. Replace it with a length-bounded validator that permits Postgres-legal database names (e.g. new Text(63)), and update the subdomain/region param descriptions on both endpoints to state the Label constraints so SDK consumers learn the new accepted format.

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.

Keeping this on purpose. The value goes straight into a PDO DSN, where ; separates key/value pairs that libpq accepts (a later host= would win), and the DSN has no way to escape it. So the name has to be restricted to a safe charset. NHost provisions the project database under the project subdomain, a lowercase alphanumeric string, so Identifier(63) (63 is the Postgres name limit) covers real NHost databases. If a hyphenated name ever turns up we can widen the allowed charset, but not to free text.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That's a reasonable security rationale — DSN injection via a semicolon or other special characters is a real concern, and restricting to Identifier(63) does close that vector. The key question is whether it breaks existing legitimate users. Your point that NHost provisions databases under the project subdomain (lowercase alphanumeric) is a strong mitigating argument, since in practice no real NHost database name would contain a hyphen.

The finding stands as-is in the diff (still new Identifier(63)), but given your explanation the risk is lower than initially assessed. If you do encounter hyphenated names in the future, a regex-based validator that allows hyphens but blocks ;, =, and whitespace would be the right middle ground rather than reverting to Text(512).

The NHost source resolves its database hostname again when it connects,
so a check made beforehand can be bypassed by a changing DNS answer.
Extend the source app-side to connect through libpq hostaddr to the
checked address, keeping the hostname for TLS, in the report route and
the worker.
@ghost
ghost dismissed their stale review October 22, 2026 14:43

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

ghost
ghost previously requested changes Oct 22, 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 B · 1 blocking finding to address. Summary

Migrations created before subdomain, region and database were validated
can still reach the worker. Check them again before connecting, and put
hostaddr last so no earlier value can override it.
@ghost
ghost dismissed their stale review October 22, 2026 14:46

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

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/migrations-health-hostnames (after).

Metric Before After Change
🚀 Requests/sec 145.5 148.7 ⚪ +2.2%
⏱️ Latency P50 117.89 ms 116.81 ms ⚪ -0.9%
⏱️ Latency P95 287.14 ms 271.56 ms 🟢 -5.4%
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 116.81 271.56 9,291 148.7 -15.59
Account 216.34 402.68 489 8.06 -28.46
TablesDB 113.22 210.86 5,053 82.62 -34.27
Storage 105.93 248.84 2,445 42.25 -7.03
Functions 169.07 325.3 1,304 23.25 +9.39

Top API waits (after)

API request Max wait (ms)
account.name.update 599.43
account.prefs.update 523.8
functions.variables.update 491.4
storage.buckets.create 484.91
functions.variables.create 452.87

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

…-hostnames

# Conflicts:
#	src/Appwrite/Platform/Modules/Migrations/Http/Migrations/NHost/Create.php
#	src/Appwrite/Platform/Modules/Migrations/Http/Migrations/NHost/Report/Get.php
#	src/Appwrite/Platform/Workers/Migrations.php
#	tests/e2e/Services/Migrations/MigrationsBase.php
# Conflicts:
#	src/Appwrite/Platform/Modules/Migrations/Http/Migrations/Appwrite/Report/Get.php
#	src/Appwrite/Platform/Modules/Migrations/Http/Migrations/NHost/Report/Get.php
#	src/Appwrite/Platform/Workers/Migrations.php
…mport it

The Console imports a local CSV by uploading it to the console bucket and importing it with internalFile. Those uploads carry uploaderId, not projectInternalId, so binding internal files to the exporting project alone refused every Console CSV import.
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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

@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

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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

@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

@ChiragAgg5k
ChiragAgg5k merged commit 74e4d5f into main Oct 23, 2026
37 checks passed
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ernal imports to their owner (backport #14794)

1.9.x stores no uploader on files, so uploads now record uploaderId in the file metadata for the internal import ownership check. PublicHostname gains address() for the certificate check.

(cherry picked from commit 74e4d5f)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ernal imports to their owner (backport #14794)

1.9.x stores no uploader on files, so uploads now record uploaderId in the file metadata for the internal import ownership check. PublicHostname gains address() for the certificate check.

(cherry picked from commit 74e4d5f)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ernal imports to their owner (backport #14794)

1.9.x stores no uploader on files, so uploads now record uploaderId in the file metadata for the internal import ownership check. PublicHostname gains address() for the certificate check.

(cherry picked from commit 74e4d5f)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ernal imports to their owner (backport #14794)

1.9.x stores no uploader on files, so uploads now record uploaderId in the file metadata for the internal import ownership check. PublicHostname gains address() for the certificate check.

(cherry picked from commit 74e4d5f)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ernal imports to their owner (backport #14794)

1.9.x stores no uploader on files, so uploads now record uploaderId in the file metadata for the internal import ownership check. PublicHostname gains address() for the certificate check.

(cherry picked from commit 74e4d5f)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ernal imports to their owner (backport #14794)

1.9.x stores no uploader on files, so uploads now record uploaderId in the file metadata for the internal import ownership check. PublicHostname gains address() for the certificate check.

(cherry picked from commit 74e4d5f)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ernal imports to their owner (backport #14794)

1.9.x stores no uploader on files, so uploads now record uploaderId in the file metadata for the internal import ownership check. PublicHostname gains address() for the certificate check.

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

fix: confine migration and certificate check connections to public addresses
(cherry picked from commit 74e4d5f)
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