Skip to content

fix: close remaining medium issues - #14048

Merged
abnegate merged 26 commits into
mainfrom
cursor/security-mediums-2026-10-02-68be
Oct 2, 2026
Merged

abnegate merged 26 commits into
mainfrom
cursor/security-mediums-2026-10-02-68be

Conversation

@abnegate

@abnegate abnegate commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Closes the remaining verified Medium Help Scout issues on CE main (4f07216c). One reviewable security PR covering default signing keys, installer auth, session invalidation, recovery-token reuse, and X-Forwarded-For trust.

Fixes in this PR

  • Default openssl / JWT signing key — fresh installs generate token-filtered secrets instead of keeping your-secret-key (EncryptionKey::resolve()). Upgrades keep the existing key, since a new one would make encrypted data unreadable. The web installer passes the placeholder on as empty, so the same rule decides there and a placeholder can never overwrite an installed key. Production HTTP/worker/realtime/mqtt refuse to start when _APP_OPENSSL_KEY_V1 is empty and warn when it is still the placeholder. variables.php default is empty (install generates). The repo .env keeps your-secret-key (development only warns), so existing local volumes stay readable.
  • Installer auth — every installer API route needs a one-time secret (Appwrite\Installer\Secret) in x-appwrite-installer-secret. That covers validate, install, complete, reset and shutdown, which also check CSRF, plus the status and certificate GET polls. Only the page itself is served without it. The install/upgrade task generates the secret, passes it to the background server as APPWRITE_INSTALLER_SECRET (the server's STDOUT goes to a log file), and prints http://localhost:20080/?secret=… in the foreground right after launching the server, so a slow start that misses the readiness wait still shows it. The page keeps the secret in sessionStorage and sends it on each request. Running Server.php directly still prints its own secret. README publishes 127.0.0.1:20080:20080.
  • Session invalidation — invalidateSessions ?? true on password change, recovery confirmation, recovery OTP, and Users password update (matches new-project / policy defaults, and the 1.x V26 response filter now reports it the same way). When invalidating, outstanding MFA challenges are deleted so a pending 2FA cannot be completed.
  • Recovery token race — the recovery token is consumed (delete) in the same transaction as the password write; a second use or a concurrent race fails. The 401 is thrown after the transaction so the adapter does not retry it.
  • X-Forwarded-For — new _APP_TRUSTED_PROXIES CIDR list. Trusted IP headers are honored only when remote_addr is in that list. Unset defaults to loopback + RFC1918 + RFC 6598 (Docker/Traefik/Kubernetes). Behind a trusted proxy the client IP is the rightmost header entry that is not itself a trusted proxy, so a spoofed leftmost entry is ignored even when the proxy appends. Direct public clients are not in that list, so they cannot rotate XFF. An empty value trusts nobody. Passed to both appwrite and appwrite-realtime (the only services that build Appwrite\Utopia\Request).

Upgrade note (for the release notes)

The client IP is now the rightmost X-Forwarded-For entry that is not in _APP_TRUSTED_PROXIES. Setups that record a public hop in the forwarding header must list it, or switch _APP_TRUSTED_HEADERS to a header the edge overwrites. Otherwise every client resolves to that hop's address and shares the IP-based abuse buckets (429s). Common cases:

  • Cloudflare in front of Traefik with forwardedHeaders.trustedIPs set: add the Cloudflare IP ranges to _APP_TRUSTED_PROXIES, or set _APP_TRUSTED_HEADERS=cf-connecting-ip.
  • GCP external Application Load Balancer (appends <client-ip>,<load-balancer-ip>): add the load balancer's address or range to _APP_TRUSTED_PROXIES.

Help Scout verdicts

HS Verdict
338078 NON_ISSUE
408445 LEGIT_FIXED_IN_PR
421366 LEGIT_FIXED_IN_PR
435040 NON_ISSUE
496611 LEGIT_FIXED_IN_PR
523085 LEGIT_FIXED_IN_PR
540314 FIXED_ALREADY (#14028)
574221 LEGIT_FIXED_IN_PR
592131 LEGIT_FIXED_IN_PR
681868 FIXED_ALREADY (#14028)
1024776 NON_ISSUE
1068273 LEGIT_FIXED_IN_PR
1365005 LEGIT_FIXED_IN_PR
1467473 LEGIT_FIXED_IN_PR

FIXED_ALREADY webhook SSRF / TOCTOU work is #14028 — not duplicated here. Residual Destination policy remains #13998.

Test Plan

Unit tests (local src/Appwrite libraries only, per AGENTS.md):

  • tests/unit/Auth/EncryptionKeyTest.php — placeholder / empty detection, production warn vs refuse, resolve() generates on fresh install and keeps existing keys on upgrade
  • tests/unit/Installer/SecretTest.php — constant-time match, nothing issued never matches, secret handed over via APPWRITE_INSTALLER_SECRET, generated otherwise
  • tests/unit/Network/TrustedProxiesTest.php — CIDR / empty-list / unset default
  • tests/unit/Utopia/RequestTest.php — getIP() ignores client XFF unless the connection is a trusted proxy, and takes the rightmost untrusted hop of an appended chain

E2E (tests/e2e/Services/Account/AccountCustomClientTest.php):

  • testUpdateAccountRecovery / testUpdateAccountRecoveryConcurrently — recovery token cannot be reused, and only one of 8 concurrent resets succeeds
  • testUpdatePasswordInvalidatesSessionsAndMFAChallenges — current session kept, other sessions revoked, pending MFA challenge rejected
  • testUpdateRecoveryInvalidatesSessionsAndMFAChallenges — all sessions revoked, pending MFA challenge rejected
  • testUpdateUserPasswordInvalidatesSessionsAndMFAChallenges — server-side PATCH /v1/users/:userId/password revokes all sessions and rejects the pending MFA challenge
docker compose exec appwrite test tests/unit/Auth/EncryptionKeyTest.php
docker compose exec appwrite test tests/unit/Installer/SecretTest.php
docker compose exec appwrite test tests/unit/Network/TrustedProxiesTest.php
docker compose exec appwrite test tests/unit/Utopia/RequestTest.php
docker compose exec appwrite test tests/e2e/Services/Account --filter='Recovery|InvalidatesSessionsAndMFAChallenges'

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?
Open in Web Open in Cursor 

Refuse the public openssl placeholder, require an installer secret,
invalidate sessions and MFA challenges by default, consume recovery
tokens atomically, and honor X-Forwarded-For only from trusted proxies.

Co-authored-by: Jake Barnby <[email protected]>
@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → cursor/security-mediums-2026-10-02-68be (after).

Metric Before After Change
🚀 Requests/sec 193.21 198.75 ⚪ +2.9%
⏱️ Latency P50 87.83 ms 88.06 ms ⚪ +0.3%
⏱️ Latency P95 213.5 ms 201.42 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 88.06 201.42 12,540 198.75 -12.08
Account 166.12 301.84 660 11.04 -66.31
TablesDB 86.16 162.91 6,820 110.4 -0.04
Storage 78.99 166.39 3,300 55.19 -19.43
Functions 125.66 247.96 1,760 30.12 -13.94

Top API waits (after)

API request Max wait (ms)
account.name.update 543.52
account.prefs.update 429.53
tablesdb.rows.get 424.42
functions.delete 398.99
functions.variables.create 360.33

cursoragent and others added 8 commits October 1, 2026 12:20
Keep production refuse of empty/your-secret-key. Give compose a unique
non-placeholder signing key and trust loopback/RFC1918 proxies so JWT
and X-Forwarded-For e2e keep working. Convert new data providers to yield.

Co-authored-by: Jake Barnby <[email protected]>
…ms-2026-10-02-68be

# Conflicts:
#	app/mqtt.php
The attribute-create worker writes status "available" before it publishes
its realtime update, so the polling helper can return while that event is
still in flight and land on the freshly opened socket. The delete tests
then read the stale update first and the real delete event second, failing
the ".delete" assertion. Drain frames until the deleting update and the
delete event arrive instead of assuming they are the next two frames.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The documented default covers loopback and RFC1918 ranges, but the code
fell back to an empty list when the variable was absent. Installs upgraded
by bumping the image tag, without regenerating .env, would then ignore
X-Forwarded-For from the bundled Traefik and see every client as the proxy
address, collapsing abuse limits and session IPs into one bucket. An unset
variable now uses the documented default; an explicitly empty value still
trusts no hop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sequential reuse already fails, so it does not exercise the race the
transaction is meant to close. Fire several resets with the same secret at
once and require exactly one to succeed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
deleteDocument locks the token row and returns false when it is already
gone. The transaction ignored that result, so a reset racing another one
waited on the lock, found nothing to delete and still wrote the password.
Only the request that actually removes the token may change the password.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Upgrades feed the installed .env values in as defaults and disable secret
generation. The token handling then blanked any value it considered
insecure, so an install still on the old placeholder came out of the
upgrade with an empty _APP_OPENSSL_KEY_V1 and could no longer decrypt its
data. Token values are now only replaced when secrets are being generated
for a fresh install.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Encrypted attributes are always written with _APP_OPENSSL_KEY_V1 and there
is no rotation path, so an existing install on the public placeholder
cannot switch keys without losing every encrypted value. Refusing to boot
left those installs stuck after an upgrade. Production still refuses an
empty key; the placeholder now logs a warning, and fresh installs never
receive it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@abnegate

abnegate commented Oct 2, 2026

Copy link
Copy Markdown
Member Author

Self-review follow-ups (no Greptile review had run on this PR yet):

Bugs fixed

  1. Recovery race was still open (e93a8fb2). The transaction ignored deleteDocument()'s return value. That call takes a FOR UPDATE lock and returns false once the token is gone, so a racing reset waited on the lock, deleted nothing, and still wrote the password. The new testUpdateAccountRecoveryConcurrently sends 8 resets with one secret at the same time. Before the fix, CI on 40526d61 returned [200,200,200,200,200,200,200,200]. Now only the request that actually deletes the token can change the password.
  2. Upgrade blanked the encryption key (b90ff5f3). On upgrade, the installed .env values become the defaults and secret generation is off. Under the token handling here, an install still on your-secret-key came out with an empty _APP_OPENSSL_KEY_V1, which left it unable to boot and unable to decrypt its data. Existing token values are now kept as-is unless secrets are being generated for a fresh install.
  3. Boot guard on the placeholder key (720eed3a). encrypt always uses _APP_OPENSSL_KEY_V1 and there is no rotation, so an existing install on the placeholder can't switch keys without losing every encrypted attribute. Refusing to boot left those installs stuck with no way out. Production still refuses an empty key. The placeholder now logs a warning, and fresh installs never receive it. Real rotation (_APP_OPENSSL_KEY_V2 plus re-encryption) belongs in a follow-up.
  4. _APP_TRUSTED_PROXIES unset meant trust nobody (0af77311). This contradicted the documented RFC1918 default. Installs upgraded by bumping the image tag would see every client as Traefik's IP, which collapses abuse limits into one bucket. Unset now uses TrustedProxies::DEFAULT; an explicitly empty value still trusts no hop.

CI

  • Merged main (import-only conflict in app/mqtt.php).
  • Fixed the Realtime testDeleteAttribute{Collections,Tables}API race (d5e1523e). The create worker writes available before it publishes its realtime update, so a stale update could land on the new socket. The test now waits for the matching event.

Worth a close look: the warn-vs-refuse decision in (3), and the getenv unset-vs-empty distinction in TrustedProxies::fromEnv().

@greptileai review

@abnegate abnegate changed the title fix: close remaining Medium Help Scout security issues fix: close remaining medium issues Oct 2, 2026
@abnegate
abnegate marked this pull request as ready for review October 2, 2026 02:44
@ghost

ghost commented Oct 2, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental changes are consistent with their callers and regression tests, with no concrete new defects identified.

This PR hardens signing-key generation and production startup checks, adds secret-based installer authorization, and limits forwarded IP headers to trusted proxies. It also invalidates sessions and pending MFA challenges during password changes and recovery, consumes recovery tokens transactionally, and adds regression coverage. The latest changes refine forwarded-chain handling, extend proxy defaults, restore the development key placeholder, and test administrator-initiated password changes.

Latest changes: The new commits select the rightmost untrusted forwarded IP, add RFC 6598 to trusted-proxy defaults, remove the unused proxy-list emptiness method, restore the local development key placeholder, and add Users password-update invalidation coverage.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 26
File Change
.env Adds trusted-proxy configuration including RFC 6598 while retaining the development signing-key placeholder.
README.md, README-CN.md Documents loopback installer publishing and authenticated setup URLs.
app/config/variables.php Updates signing-key defaults and documents trusted proxies and forwarded-chain resolution.
app/controllers/api/account.php Consumes recovery tokens transactionally and shares session and MFA-challenge invalidation.
app/http.php, app/mqtt.php, app/realtime.php, app/worker.php Validates production encryption-key configuration at startup.
app/views/install/installer/js/modules/progress.js Stores the installer secret and sends it with installer API requests.
docker-compose.yml Passes trusted-proxy and trusted-header configuration to HTTP and realtime services.
src/Appwrite/Auth/EncryptionKey.php Detects insecure keys, generates fresh-install secrets, and validates production configuration.
src/Appwrite/Installer/Secret.php Provides installer-secret generation, environment inheritance, and constant-time matching.
src/Appwrite/Network/TrustedProxies.php Parses proxy lists and matches IPs against CIDRs, with loopback, private, and RFC 6598 defaults.
src/Appwrite/Platform/Installer/Http/Installer/Certificate/Get.php, src/Appwrite/Platform/Installer/Http/Installer/Status.php Requires installer authorization for certificate and status polling.
src/Appwrite/Platform/Installer/Http/Installer/Complete.php, src/Appwrite/Platform/Installer/Http/Installer/Reset.php, src/Appwrite/Platform/Installer/Http/Installer/Shutdown.php, src/Appwrite/Platform/Installer/Http/Installer/Validate.php Requires installer-secret authorization alongside CSRF validation.
src/Appwrite/Platform/Installer/Http/Installer/Install.php Authorizes installation requests and delegates fresh-install key generation.
src/Appwrite/Platform/Installer/Server.php Initializes the installer secret and prints authenticated setup details.
src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php Uses shared session and pending MFA-challenge invalidation.
src/Appwrite/Platform/Tasks/Doctor.php Reuses insecure encryption-key detection.
src/Appwrite/Platform/Tasks/Install.php Resolves installation keys and passes and prints background installer credentials.
src/Appwrite/Utopia/Database/Documents/User.php Adds shared session revocation and pending MFA-challenge deletion.
src/Appwrite/Utopia/Request.php Caches proxy configuration and resolves forwarded chains from the rightmost untrusted hop.
src/Appwrite/Utopia/Response/Filters/V26.php Aligns the legacy response's missing invalidation default with the enabled policy.
tests/e2e/Services/Account/AccountCustomClientTest.php Tests recovery-token races and session/MFA invalidation, including Users password updates.
tests/e2e/Services/Realtime/RealtimeConsoleClientTest.php Waits for matching schema lifecycle events.
tests/unit/Auth/EncryptionKeyTest.php Tests insecure-key detection, production validation, generation, and upgrade preservation.
tests/unit/Installer/SecretTest.php Tests installer-secret generation, matching, and environment inheritance.
tests/unit/Network/TrustedProxiesTest.php Tests proxy parsing and environment defaults, including RFC 6598.
tests/unit/Utopia/RequestTest.php Tests forwarded-header trust and single, appended, invalid, and all-trusted chains.

Reviewed the commits since c0011bb · 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 B · 1 blocking finding to address. Summary

Comment thread docker-compose.yml Resolved
…s redirected

The web installer backgrounds Server.php with stdout in a log file, so the
child-printed secret never reached the operator. Generate the secret in
Install.php, pass it as APPWRITE_INSTALLER_SECRET, and print the
authenticated URL after the server is ready. Also pass trusted-proxy
env vars into the realtime service.

Co-authored-by: Jake Barnby <[email protected]>

@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

cursoragent and others added 2 commits October 2, 2026 03:01
…in libraries

AGENTS.md keeps unit tests off CLI tasks and HTTP actions. The installer
secret now lives in Appwrite\Installer\Secret and the keep-or-generate
decision for token secrets in EncryptionKey::resolve(), both covered by
library unit tests; the Install task and installer Validate action tests
are removed.

Co-authored-by: Jake Barnby <[email protected]>
…rd reset

Password change keeps the current session but revokes others; recovery
revokes every session. Both must delete the pending MFA challenge so it
cannot be completed from a new session.

Co-authored-by: Jake Barnby <[email protected]>

@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

cursoragent and others added 2 commits October 2, 2026 03:04
Same race as the attribute delete tests: the index-create worker can
publish its "available" update after the polling helper returns, so it
lands on the new socket before the delete events. Drain frames until the
deleting update and the delete event arrive.

Co-authored-by: Jake Barnby <[email protected]>
A session still waiting on MFA already gets 401 on /account, so that alone
does not show it was revoked. List the user's sessions with the server key
before and after the reset, and assert the revoked session no longer fails
with user_more_factors_required.

Co-authored-by: Jake Barnby <[email protected]>

@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

@abnegate abnegate left a comment

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.

Reviewed the full diff at f00f0171 and checked each point below against the code (utopia-php/database 7.4.0, packages/http, the installer JS/routes). CI is green. The fixes hold up; these are the follow-ups I'd make:

Not on diff lines

  1. GET /install/status and GET /install/certificate don't check the secret. The description says every installer request needs it, but only Validate/Install/Complete/Reset/Shutdown call Validate::authorize/validateSecret. /install/certificate lets any caller who can reach :20080 make the installer curl https://<domain>:<port>/ with CURLOPT_RESOLVE pinned to the Docker gateway, which is a TLS port probe of the host. /install/status returns progress for any installId (sensitive fields are stripped). The localhost-only publish limits this. Gating both is cheap because progress.js already has the header helper (pollCertificate L343, fetchInstallStatus L425). If they should stay open, the description should say so.

  2. The V26 response filter still reports authInvalidateSessions as false when the key is missing (src/Appwrite/Utopia/Response/Filters/V26.php:63, getAttribute('invalidateSessions', false)). This PR makes a missing key mean "invalidate" (?? true) in all four enforcement paths, and Policies/Get/XList already default to true. So older-format clients would show invalidation off while it's actually on. Change the default to true.

Nit: the new classes have several explanatory docblocks (EncryptionKey, Secret, TrustedProxies, Request::getIP, User::invalidateAuthentication) that repeat what the code says. The rationale fits better in the commit message.

Comment thread app/controllers/api/account.php Outdated
$recoveryDocument = $dbForProject->withTransaction(function () use ($dbForProject, $verifiedToken, $profile, $newPassword, $history, $passwordPwned, $proofForPassword) {
$document = $dbForProject->getDocument('tokens', $verifiedToken->getId());
if (!$dbForProject->deleteDocument('tokens', $verifiedToken->getId())) {
throw new Exception(Exception::USER_INVALID_TOKEN);

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.

Throwing the business error inside withTransaction sets off the adapter's retry loop.

Adapter::withTransaction (database 7.4.0, Adapter.php:447-491) rethrows right away only for Duplicate/Restricted/Authorization/Relationship/Conflict/Limit/Timeout. Anything else, including this Appwrite\Extend\Exception, gets rolled back and retried twice with usleep(50ms) and usleep(100ms). So every losing request in a race, and every plain token reuse, runs the SELECT … FOR UPDATE + delete 3 times and sleeps about 150ms before returning 401. The result is still correct, but a business-rule failure isn't transient and shouldn't be retried.

Have the callback signal the failure and throw after the transaction:

$recoveryDocument = $dbForProject->withTransaction(function () use (...) {
    $document = $dbForProject->getDocument('tokens', $verifiedToken->getId());
    if (!$dbForProject->deleteDocument('tokens', $verifiedToken->getId())) {
        return null;
    }
    $dbForProject->updateDocument('users', ...);
    return $document;
});

if ($recoveryDocument === null) {
    throw new Exception(Exception::USER_INVALID_TOKEN);
}

The same applies to the OTP recovery copy at L4741.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in 7719413 for both the link and OTP recovery paths. The callback returns null when the delete loses, and USER_INVALID_TOKEN is thrown after withTransaction returns, so the adapter no longer retries it.

Comment thread src/Appwrite/Platform/Tasks/Install.php Outdated
return;
}

Console::info('Installer secret: ' . $secret);

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.

If the readiness wait times out, the operator never gets the secret.

The secret and URL are only printed after waitForWebServer($port) succeeds. On the timeout branch just above, we print Web installer did not respond in time. Please refresh the browser. and return. The server may still come up, but every request will 401 because the operator has no secret, and the old Open your browser at line (printed before the wait) was removed. The secret only appears if the server log happened to be non-empty when it was dumped.

Print the secret/URL before the wait, or in the timeout branch too, so a slow start (common on Docker Desktop) is still recoverable.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in 21a30cd. The secret and the ?secret= URL are now printed right after the server is launched, before the readiness wait, so the timeout branch still leaves the operator with both.

Comment thread app/config/variables.php Outdated
[
'name' => '_APP_TRUSTED_PROXIES',
'description' => 'Comma-separated CIDRs (or exact IPs) of reverse proxies that may set `_APP_TRUSTED_HEADERS` such as X-Forwarded-For. The default covers loopback and RFC1918 ranges used by Docker/Traefik. Direct clients whose connection address is not in this list are not trusted — their X-Forwarded-For is ignored. Set it to an empty value to always use the connection IP. If your load balancer has a public address, add that CIDR.',
'introduction' => '1.8.0',

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.

'introduction' => '1.8.0' is wrong for a variable added in this PR. APP_VERSION_STABLE is 2.3.0, and recently added variables use 2.3.0. Set it to the release this ships in, otherwise the generated env docs say it has existed since 1.8.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in c0011bb: _APP_TRUSTED_PROXIES now has 'introduction' => '2.3.0'.

return;
}

$challenges = $dbForProject->find('challenges', [

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.

find + Query::limit(APP_LIMIT_COUNT) + a per-document delete loop can be one bulk delete. That also drops the arbitrary cap and the no-op Query::orderAsc():

$dbForProject->deleteDocuments('challenges', [
    Query::equal('userInternalId', [$sequence]),
]);

deleteDocuments is in database 7.4.0 and already used in Workers/Deletes.php, and _key_user indexes userInternalId.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in acfcde7. It's now a single deleteDocuments('challenges', [Query::equal('userInternalId', [$sequence])]), with no cap and no orderAsc.

Comment thread src/Appwrite/Utopia/Request.php Outdated
{
$remoteAddr = $this->getServer('remote_addr') ?? '0.0.0.0';

if (!TrustedProxies::fromEnv()->contains($remoteAddr)) {

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.

getIP() runs many times per request (abuse keys, audits, sessions, geo, spans), and each call re-reads the env and re-parses the CIDR list. The constructor already reads _APP_TRUSTED_HEADERS once. Build TrustedProxies there too and keep it on a private readonly property.

Naming: TrustedProxies::fromEnv sits next to Secret::fromEnvironment in this same PR. Use the full word for both, and use System::getEnv instead of raw getenv to match the rest of Request.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in 0d6776a. TrustedProxies is built once in the Request constructor and kept on a private readonly property. fromEnv is now fromEnvironment(), with parse() for explicit values.

I kept raw getenv in fromEnvironment(), with a one-line comment. System::getEnv() is getenv($name) ?: $default, so an empty _APP_TRUSTED_PROXIES would fall back to the private-network default, but empty has to mean "trust no proxy". testEmptyEnvironmentTrustsNobody covers that case.

if ($opensslKey === '' && !$config->isUpgrade()) {
$this->sendBadRequest($response, $swooleResponse, $wantsStream, 'Secret key is required');
return;
if (EncryptionKey::isInsecure($opensslKey)) {

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.

This block duplicates what prepareEnvironmentVariables now does. Its token loop calls EncryptionKey::resolve($value, $shouldGenerateSecrets), and here $shouldGenerateSecrets = !hasExistingConfig() && !isUpgrade(). An empty key on upgrade is already skipped by the user-input override ($value !== ''), so the existing value is kept.

Generating here also has a side effect. The random key is hashed into the progress file's opensslKeyHash. If a client resumes the same installId after sending the placeholder, it generates a different key and hits Installation payload mismatch.

Dropping the block keeps one place deciding generate-vs-keep.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in 68c2948. The generation is gone, so prepareEnvironmentVariables is the only place that decides between generating and keeping. I kept one line, though: an insecure value is turned into '' instead of being passed through. On upgrade a placeholder sent by the client would otherwise override the installed key, because the user-input override only skips empty values. On a fresh install EncryptionKey::resolve('', true) generates the key. As a bonus, the progress-file hash is now of a stable value, so resuming the same installId no longer hits Installation payload mismatch.

cursoragent and others added 6 commits October 2, 2026 03:32
withTransaction retries anything that is not a database conflict, so
throwing USER_INVALID_TOKEN inside it re-ran the locked delete twice and
slept about 150ms before every 401. Return null from the callback and
throw once the transaction has finished.

Co-authored-by: Jake Barnby <[email protected]>
Drops the APP_LIMIT_COUNT cap and the per-document loop; _key_user
indexes userInternalId.

Co-authored-by: Jake Barnby <[email protected]>
…lients

Every enforcement path treats a missing invalidateSessions as true, and
the policy endpoints already default to true.

Co-authored-by: Jake Barnby <[email protected]>
… checks

/install/certificate makes the installer probe a TLS port on the Docker
gateway, and /install/status returns progress for any install id. The
page now sends the secret header on both polls.

Co-authored-by: Jake Barnby <[email protected]>
A slow start hit the timeout branch, which returned without ever showing
the secret, leaving every request to 401.

Co-authored-by: Jake Barnby <[email protected]>
…ion key

The web installer generated its own key, duplicating EncryptionKey::resolve
and hashing a fresh random value into the progress file, so resuming an
install id after sending the placeholder failed with a payload mismatch.
An insecure value is now sent on as empty, which never overrides the
installed key and is generated only on a fresh install.

Co-authored-by: Jake Barnby <[email protected]>
cursoragent and others added 2 commits October 2, 2026 03:32
getIP() runs many times per request and re-read and re-parsed the
environment each time. Build TrustedProxies in the constructor and
rename fromEnv to fromEnvironment, with parse() for explicit values.
System::getEnv() is not used because it turns an empty value into the
default, and empty must trust no proxy.

Co-authored-by: Jake Barnby <[email protected]>
@cursor

cursor Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

@abnegate thanks, all addressed:

  1. /install/status and /install/certificate now require the installer secret (ecb0425) and return 401 without it. Both are GET polls, so they check only the secret, not CSRF. progress.js now sends the header on pollCertificate and fetchInstallStatus. The only routes left open are the page itself and the error handler.
  2. V26 filter: authInvalidateSessions now defaults to true (594b65f).
  3. Docblocks: removed from EncryptionKey, Secret, TrustedProxies, Request::getIP and User::invalidateAuthentication, with the reasoning moved into commit messages. Two one-line comments remain, both for constraints the code can't show: why getenv is used rather than System::getEnv, and why the recovery error is thrown outside the transaction.

Inline threads are answered individually.

@abnegate abnegate left a comment

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.

Second round, at c0011bba. CI is green. I re-checked every first-round fix against the code, and all of them hold:

  • Recovery: the callback returns null and USER_INVALID_TOKEN is thrown after withTransaction, so the adapter no longer retries. The race also holds on Mongo, where Client::delete returns the deleted count, so !!0 is false.
  • Installer secret: printed before the readiness wait. /install/status and /install/certificate now require it, and the JS sends it. The CLI's waitForWebServer/isInstallationComplete use raw TCP probes, so they aren't affected.
  • Encryption key: prepareEnvironmentVariables is now the only place that decides between generating and keeping. Mapping insecure input to '' keeps an installed key on upgrade, and the resume hash is now stable.
  • Challenges: deleteDocuments('challenges', …) applies the same permission rule as before. Recovery adds Role::user before it runs, so the guest path still deletes.
  • Trusted proxies: parsed once per Request. Keeping raw getenv is right, because System::getEnv is getenv($name) ?: $default, which would turn an explicit empty value into the default.
  • Smaller fixes: the V26 default and the 2.3.0 introduction version are fixed, and the docblocks are trimmed.

Two new inline findings below. Smaller notes:

  1. PATCH /v1/users/:userId/password has no e2e test for its new behaviour (it now deletes pending MFA challenges, and invalidates when the setting is unset). The account tests cover the shared User::invalidateAuthentication, but deleting the call from Users/Http/Users/Password/Update.php wouldn't fail any test. A server-side counterpart of testUpdatePasswordInvalidatesSessionsAndMFAChallenges would close that.
  2. Nit: TrustedProxies::isEmpty() is only called from tests. The tests can assert contains() instead and the method can go.
  3. Non-blocking: consider adding 100.64.0.0/10 (RFC 6598) to TrustedProxies::DEFAULT. EKS custom networking and Tailscale both put the proxy hop in that range. There, every client would show up as the ingress pod's address, so the default url:{url},ip:{ip} abuse keys would be shared by all users. A public client can't arrive from that range, so it isn't any looser than the RFC1918 entries already in the list.

Comment thread .env Outdated
_APP_EDITION=self-hosted
_APP_LOCALE=en
_APP_OPENSSL_KEY_V1=your-secret-key
_APP_OPENSSL_KEY_V1=appwrite-local-development-openssl-key

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.

Changing the dev key locks contributors out of their existing local data.

users.password is stored with the encrypt filter (app/config/collections/common.php:167), and so are token secrets, identity access tokens and MFA recovery codes. The filter decrypts with _APP_OPENSSL_KEY_V1. A contributor who pulls this and recreates containers keeps their existing volumes, which were encrypted with your-secret-key. So every existing local account, including the console login, fails until they wipe volumes.

This change isn't needed any more. Since 720eed3 the placeholder only warns, and EncryptionKey::assertProduction returns early for non-production; this file sets _APP_ENV=development. main ran CI with your-secret-key, and the tests that touch the key set their own or accept any value. I'd revert this line to your-secret-key.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reverted in 5469f23: .env is back to _APP_OPENSSL_KEY_V1=your-secret-key. Development only gets a warning, so existing local volumes stay readable.

Comment thread src/Appwrite/Utopia/Request.php Outdated
return $remoteAddr;
}

return parent::getIP();

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.

Behind a proxy that appends, the leftmost X-Forwarded-For entry is still client-controlled.

The parent returns $ips[0] (packages/http/src/Adapter/Swoole/Request.php:75-81). That's only safe when the last hop overwrites the header, as the bundled Traefik does by default. Some proxies append instead and keep whatever the client sent at the front: nginx with $proxy_add_x_forwarded_for, Cloudflare, and Traefik once forwardedHeaders.trustedIPs is set. Behind any of those, a client sends X-Forwarded-For: 1.2.3.4, the header arrives as 1.2.3.4, <real client>, <proxy>, and getIP() returns 1.2.3.4. So the abuse-key rotation this PR closes for direct clients stays open for operators who set up their proxy chain properly.

$this->trustedProxies is everything needed to fix this here. When the connection is trusted, walk each trusted header's list right to left, skip addresses the proxy list contains, and return the first valid one that isn't trusted (the usual "rightmost untrusted" rule). Fall back to the leftmost entry when every entry is trusted. Single-value headers such as cf-connecting-ip resolve the same as today, and so do the existing e2e tests that send a single 198.51.100.x. A unit case with 'x-forwarded-for' => '1.2.3.4, 198.51.100.1, 10.0.0.3' from a trusted remote_addr should return 198.51.100.1.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in e65a378. Once the connection is from a trusted proxy, Request::getIP() reads the valid entries of each trusted header from right to left. It returns the first entry that isn't a trusted proxy, and falls back to the leftmost entry when every entry is trusted. A header with no valid entry is skipped, and with no usable header the connection address is used. The new unit cases include your chain: 1.2.3.4, 198.51.100.1, 10.0.0.3 from a trusted remote_addr returns 198.51.100.1. Single-value headers resolve the same as before.

cursoragent and others added 4 commits October 2, 2026 03:53
Existing local volumes are encrypted with it; the placeholder only warns outside production.

Co-authored-by: Jake Barnby <[email protected]>
Proxies that append to X-Forwarded-For keep client-supplied entries on the left.

Co-authored-by: Jake Barnby <[email protected]>
@cursor

cursor Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

@abnegate second round addressed:

  • Dev key: reverted (5469f23).
  • Rightmost untrusted X-Forwarded-For hop: fixed (e65a378), with unit cases.
  • PATCH /v1/users/:userId/password: added testUpdateUserPasswordInvalidatesSessionsAndMFAChallenges (3774c91). It sets the password with the server key, then checks that both sessions are revoked rather than waiting on MFA, that the server-side session list is empty, and that the old challenge is rejected with user_invalid_token. Removing the invalidateAuthentication call from Users/Http/Users/Password/Update.php now fails it. The "setting unset" default isn't covered, because the project API can't clear the attribute. The ?? true fallback is the same one the account routes use.
  • TrustedProxies::isEmpty(): removed. The tests now assert contains() (93aefad).
  • 100.64.0.0/10: added to TrustedProxies::DEFAULT and .env, and the variable description now mentions it and the rightmost-hop rule.

@abnegate abnegate left a comment

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.

Third round, at 3774c91f. All checks are green. Every second-round point is fixed, and I have no blocking findings.

  • .env: back to your-secret-key.
  • Request::getIP(): now takes the rightmost entry that isn't a trusted proxy. It falls back to the leftmost entry when every entry is trusted, and to remote_addr when no header has a valid address. $this->trusted is protected in packages/http/src/Request.php:70, so overriding it is fine. The unit cases cover the appended chain, invalid entries, the all-trusted fallback and the no-valid-entry fallback.
  • New e2e test: testUpdateUserPasswordInvalidatesSessionsAndMFAChallenges fails without the invalidateAuthentication call: the current session would still return 200.
  • Smaller fixes: isEmpty() is gone and 100.64.0.0/10 is in the default.

Two non-blocking notes:

  1. Worth an upgrade note in the release. With the rightmost-untrusted rule, any public hop that gets recorded in the forwarding header now has to be listed in _APP_TRUSTED_PROXIES. Two common setups put one there:

    • Cloudflare in front of a Traefik with forwardedHeaders.trustedIPs set. Traefik appends the Cloudflare edge address after the client.
    • GCP's external Application Load Balancer, which appends <client-ip>,<load-balancer-ip>.

    Before this PR those setups got the real client from the leftmost entry. After upgrading, every client resolves to the edge or load-balancer address and shares the url:{url},ip:{ip} abuse buckets until the operator adds those ranges, or switches _APP_TRUSTED_HEADERS to a header the edge overwrites, such as cf-connecting-ip. The variable description covers this, but operators usually only notice through 429s, so a line in the release notes would help.

  2. Optional: testUpdateUserPasswordInvalidatesSessionsAndMFAChallenges tests a Users server route from AccountCustomClientTest. AGENTS.md puts it under tests/e2e/Services/Users/ (UsersCustomServerTest), and the Users CI job won't run it where it is. Moving it means moving createFreshAccountWithSession/createPendingMFAChallenge/listUserSessionIds into a shared trait, so leaving it is a fair call.

@cursor

cursor Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

@abnegate thanks.

  1. Upgrade note: added an "Upgrade note (for the release notes)" section to the PR description, so whoever drafts the release notes can lift it. It covers the Cloudflare and Traefik case (list the Cloudflare ranges, or use cf-connecting-ip) and the GCP external Application Load Balancer case (list the load balancer's range).
  2. Test placement: leaving testUpdateUserPasswordInvalidatesSessionsAndMFAChallenges where it is for now. It shares the MFA setup and session-listing helpers with the account tests, and it runs in the Account job. Moving it into UsersCustomServerTest through a shared trait can be a follow-up.

@abnegate
abnegate merged commit 57fc7f1 into main Oct 2, 2026
54 checks passed
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