Skip to content

fix(auth): refuse unreadable HIBP ranges, cache empty HIBP ranges and JWKS key sets - #15705

Merged
ArnabChatterjee20k merged 5 commits into
fix/cache-store-emptyfrom
test/auth-cache-empty-answers
Nov 17, 2026
Merged

ArnabChatterjee20k merged 5 commits into
fix/cache-store-emptyfrom
test/auth-cache-empty-answers

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Issue

Closes #15703. Stacked on #15704.

With #15704, utopia-php/cache stores an empty array []. Two callers here return [] for an empty answer, and until now they fetched it again on every request:

  • PasswordPwned::remember(): a HIBP range with no breached hashes.
  • Jwks::getKey(): a JWKS with no usable RSA keys.

Caching [] also made an existing gap in HIBP last longer. HIBP::range() reads a 200 response line by line and keeps the SUFFIX:COUNT lines with a count above 0. A 200 with no such line at all (an empty body, an HTML error page) came back as [], which means "no breaches", so the password was accepted even though no lookup really happened. That contradicts the class contract in PasswordPwned: a password is never accepted when the lookup did not happen, and a nonsense answer throws. Before #15704 that [] was not cached, so it affected one request. With #15704 it would be cached for CACHE_TTL (one hour), and every password sharing that hash prefix would skip the check for that hour.

Solution

  • HIBP::range() counts the entries it reads (lines with a separator and a hex suffix, whatever the count). If a 200 response has none, it throws GENERAL_PWNED_PASSWORDS_UNAVAILABLE, like an unreachable service or a non-200 status, so nothing is cached and the next check asks again. A range of only padded entries (all count 0) is still valid and returns []. The real service is asked with Add-Padding: true, so a real answer always has hundreds of entries.
  • Regression tests showing each genuine empty answer is fetched once and then served from cache. The comment in PasswordPwned::remember() ("A miss reads back as false, so an answer is always wrapped in an array") is still accurate, so it is unchanged.

Tests

  • HIBPTest::testUnreadableRangeIsReportedAndNotCached (two cases: an empty body, an HTML page): a 200 without a single entry throws GENERAL_PWNED_PASSWORDS_UNAVAILABLE on both of two checks, and both checks reach the service, so it is not cached.
  • HIBPTest::testOnlyTheHashPrefixLeavesTheServer and testLookupsGoToTheConfiguredEndpoint used an empty body only to capture the request URL. They now get a padding-only range, so they keep testing the URL instead of tripping the new check.
  • HIBPTest::testRangeWithNoBreachesIsCached: a range with only padding entries (no breaches) is fetched once for two checks of the same prefix, using a Memory cache. testFailedLookupIsNotCached still covers that errors are not cached.
  • JwksTest::testEmptyKeySetIsCached: a JWKS with no keys is fetched once plus the one forced refetch for the unknown kid, and is cached as []. A second lookup in the 60s cooldown fetches nothing. Once the cache entries are aged past the cooldown, an unknown kid forces one more refetch and picks up a newly published key. Caching is proven by counting fetches through the fake transport, without building the cache keys.

Locally the app's PHPUnit bootstrap needs the utopia extension (it provides Utopia\Locale), so I ran these with --no-configuration --bootstrap vendor/autoload.php. The full unit suite runs in CI.

Red: against the cache source of origin/main (8e1e655)
HIBP (Tests\Unit\Auth\Validator\PasswordPwned\HIBP)
 ✔ Range is cached per prefix
 ✘ Range with no breaches is cached
   │ Failed asserting that actual size 2 matches expected size 1.
   │ tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php:97
FAILURES! Tests: 2, Assertions: 6, Failures: 1.

Jwks (Tests\Unit\Auth\OIDC\Jwks)
 ✔ Known kid is served from cache after one fetch
 ✔ Unknown kid triggers one forced refetch
 ✔ Cooldown suppresses repeated forced refetches
 ✘ Empty key set is cached
   │ Failed asserting that 3 is identical to 2.
   │ tests/unit/Auth/OIDC/JwksTest.php:94
FAILURES! Tests: 4, Assertions: 14, Failures: 1.
Green: on #15704
HIBP (Tests\Unit\Auth\Validator\PasswordPwned\HIBP)
 ✔ Range is cached per prefix
 ✔ Range with no breaches is cached
OK (2 tests, 6 assertions)

Jwks (Tests\Unit\Auth\OIDC\Jwks)
 ✔ Known kid is served from cache after one fetch
 ✔ Unknown kid triggers one forced refetch
 ✔ Cooldown suppresses repeated forced refetches
 ✔ Empty key set is cached
OK (4 tests, 17 assertions)
Red: the new HIBP tests before the fix

Appwrite\Extend\Exception reads the errors config, so for these I used a bootstrap that loads vendor/autoload.php and sets Config::setParam('errors', include 'app/config/errors.php').

$ vendor/bin/phpunit --no-configuration --bootstrap <autoload + errors config> --testdox tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php
HIBP (Tests\Unit\Auth\Validator\PasswordPwned\HIBP)
 ✔ Leaked password is rejected
 ✔ Clean password is accepted
 ✔ Any single breach is enough
 ✔ Padded entry with zero count is not a breach
 ✔ Suffix comparison ignores case
 ✔ Only the hash prefix leaves the server
 ✔ Range is cached per prefix
 ✔ Range with no breaches is cached
 ✔ Cache is scoped to endpoint
 ✔ Lookups go to the configured endpoint
 ✔ Unreachable service is reported
 ✔ Unexpected status is reported
 ✘ Unreadable range is reported and not cached with data set "empty body"
   │
   │ Expected a range without a single entry to surface
   │
   │ tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php:160
   │
 ✘ Unreadable range is reported and not cached with data set "html page"
   │
   │ Expected a range without a single entry to surface
   │
   │ tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php:160
   │
 ✔ Failed lookup is not cached

FAILURES!
Tests: 15, Assertions: 24, Failures: 2.
Green: after the fix
HIBP (Tests\Unit\Auth\Validator\PasswordPwned\HIBP)
 ✔ Leaked password is rejected
 ✔ Clean password is accepted
 ✔ Any single breach is enough
 ✔ Padded entry with zero count is not a breach
 ✔ Suffix comparison ignores case
 ✔ Only the hash prefix leaves the server
 ✔ Range is cached per prefix
 ✔ Range with no breaches is cached
 ✔ Cache is scoped to endpoint
 ✔ Lookups go to the configured endpoint
 ✔ Unreachable service is reported
 ✔ Unexpected status is reported
 ✔ Unreadable range is reported and not cached with data set "empty body"
 ✔ Unreadable range is reported and not cached with data set "html page"
 ✔ Failed lookup is not cached

OK (15 tests, 28 assertions)

JwksTest is unchanged and still passes (7 tests). composer lint, PHPStan and Rector (tests/tools/rector.php) pass on both changed files.

New files, classes and tests

No new files or classes. New test methods: testRangeWithNoBreachesIsCached, testEmptyKeySetIsCached, unreadableRanges (data provider) and testUnreadableRangeIsReportedAndNotCached, each explained above.

🤖 Generated with Claude Code

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 1 nitpick below.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Test hardcodes internal Jwks cache keys (JwksTest.php:95) — testEmptyKeySetIsCached reaches into Jwks's private cache-key format by building 'oidc-jwks-pem:' .

This PR only adds two unit tests; no library behavior changes. Both tests were verified against their subjects (Jwks::getKey() and PasswordPwned::remember()), and the assertion counts and cache semantics match the implementation.

Files Change
tests/unit/Auth/OIDC/JwksTest.php New test asserting an empty key set is cached and a forced refetch respects the cooldown TTL.
tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php New test asserting an empty breach range is cached so a second lookup skips the fetch.

Reviewed commit: 2727e7a

@appwrite

appwrite Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

HIBP now rejects responses with no recognized hash suffix entries as unavailable. Its tests cover valid padded ranges plus retrying after empty or HTML responses. The JWKS test verifies that an empty set is cached during the refresh cooldown and that a newly published key is picked up after the cooldown expires.

Latest changes: The newest commits add HIBP response sanity checks and update the HIBP fixtures and tests to distinguish valid padded empty ranges from unreadable responses that must be retried.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 3
File Change
src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php Rejects HIBP responses with no hex suffix entries instead of treating them as an empty range.
tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php Uses valid padded-range fixtures and tests that empty or HTML responses fail and are fetched again.
tests/unit/Auth/OIDC/JwksTest.php Covers caching an empty JWKS during the cooldown and refreshing after a key is published.
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Reject malformed HIBP records before counting them Verifier: This asks for stricter parsing against a hypothetical malformed 200 response. The change already rejects empty or non-hex bodies, such as an HTML error page, and a malformed line that still has a hex suffix is unlikely from the real HIBP API. It is a hardening nit, not a reachable bug.

Reviewed the commits since 6ca61e6 · Details · Comment @appwrite review to re-run, or mention @appwrite with a question.

@appwrite appwrite Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Tier S · Looks good to merge. Summary

luxor-code-review[bot]
luxor-code-review Bot previously approved these changes Nov 17, 2026
@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.

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@Luxor-Code-Review Fixed in 6ca61e6. testEmptyKeySetIsCached no longer builds the oidc-jwks-pem: or oidc-jwks-refresh: keys:

  • The fetch count through the fake transport is enough to prove the empty set is cached: 2 fetches after two lookups (the initial load plus one forced refetch). Without caching it would be 3. So I removed the direct load of the cached [].
  • To end the cooldown, the test now ages every Memory entry by Jwks::REFRESH_COOLDOWN + 1 seconds instead of purging the cooldown key by name. The next unknown-kid lookup then forces one refetch and returns the newly published key (3 fetches).

It still fails on main's cache (Failed asserting that 3 is identical to 2) and passes on #15704.

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing fix/cache-store-empty (before) → test/auth-cache-empty-answers (after).

Metric Before After Change
🚀 Requests/sec 196.55 219.06 🟢 +11.4%
⏱️ Latency P50 88.44 ms 78.23 ms 🟢 -11.5%
⏱️ Latency P95 204.7 ms 189.03 ms 🟢 -7.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 78.23 189.03 13,680 219.06 -15.67
Account 151.76 323.34 720 12.14 +13.67
TablesDB 75.8 137.72 7,440 121.95 -20.85
Storage 70.79 161.77 3,600 60.81 -20.02
Functions 112.96 237.83 1,920 33.13 -17.34

Top API waits (after)

API request Max wait (ms)
storage.files.create 515.84
account.prefs.update 510.2
account.name.update 490.21
functions.delete 426.5
tablesdb.rows.create 408.78

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@appwrite review

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@tenki-reviewer review

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 1 nitpick below.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Cooldown expiry test mutates Memory internals (JwksTest.php:97) — testEmptyKeySetIsCached simulates cooldown expiry by rewriting the private time field of every $memory->store entry directly (tests/unit/Auth/OIDC/JwksTest.php:97-100) instead of going through the Cache API.

The PR introduces unit coverage for two caching hot paths in authentication: the OIDC JWKS key-set fetch (cooldown, forced refetch, failure fallback) and the HIBP pwned-password range lookup (cache hits, expiry, empty-range handling). Tests use named fakes and avoid network calls.

Files Change
tests/unit/Auth/OIDC/JwksTest.php New unit tests exercising JWKS cache cooldown, forced refresh triggers, and key selection.
tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php New unit tests covering HIBP range-fetch caching and hit/miss counting.

Reviewed commit: 6ca61e6

@appwrite appwrite Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Tier S · Looks good to merge. Summary

luxor-code-review[bot]
luxor-code-review Bot previously approved these changes Nov 17, 2026
@luxor-code-review
luxor-code-review Bot dismissed their stale review November 17, 2026 08:26

Superseded by a newer Luxor approval on this pull request.

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@Luxor-Code-Review Thanks. Keeping this step as is:

  • Memory::$store is a public property (packages/cache/src/Adapter/Memory.php:43), so the test isn't using reflection or private state.
  • This step checks the main risk of caching an empty key set: a newly published key must still be served once the cooldown ends (Jwks.php:53-60). Dropping it would leave that untested.
  • The alternatives are worse. Purging the cooldown key by name couples the test to Jwks's key format (the previous nitpick). A sleep(61) slows the suite. Jwks and Cache take no clock to inject.

Ageing every entry moves time forward for the whole cache without naming any key, and the assertions are only on what's observable: the key returned and the fetch count.

@ArnabChatterjee20k ArnabChatterjee20k changed the title test(auth): cache empty HIBP ranges and JWKS key sets fix(auth): refuse unreadable HIBP ranges, cache empty HIBP ranges and JWKS key sets Nov 17, 2026
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@appwrite review

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@tenki-reviewer review

@appwrite

appwrite Bot commented Nov 17, 2026

Copy link
Copy Markdown

A review of f1e52d2 is already running, so I didn't start another one.

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Truncated 200 range body is cached as a clean range — HIBP.php:103

This PR makes the Pwned-Passwords range lookup fail closed when the HIBP range response cannot be read, instead of treating it as a no-breaches answer, and strengthens the unit suite around that behavior and the OIDC JWKS cache.

Files Change
src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php Adds an entry-count gate so empty/unreadable range responses throw instead of reporting the password as unbreached.
tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php Unit coverage for the new fail-closed range handling, including padded-response edge cases.
tests/unit/Auth/OIDC/JwksTest.php Additional unit coverage for JWKS empty-key-set caching and refetch cooldown behavior.

Reviewed commit: f1e52d2

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

Hardens the HIBP password-breach validator to fail closed on unreadable range responses and adds unit coverage for that path plus JWKS cache behavior.

Key findings

  • 🟡 Truncated 200 range body is cached as a clean range — HIBP.php:103

@luxor-code-review
luxor-code-review Bot dismissed their stale review November 17, 2026 08:41

A newer Luxor review found issues on this pull request.

@ArnabChatterjee20k
ArnabChatterjee20k merged commit 8263cc3 into fix/cache-store-empty Nov 17, 2026
134 of 136 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