Skip to content

Keep authorization codes and access tokens in the protocol cache only, as an option - #364

Merged
cicnavi merged 6 commits into
masterfrom
feature/cache-only-protocol-artifacts
Dec 3, 2026
Merged

cicnavi merged 6 commits into
masterfrom
feature/cache-only-protocol-artifacts

Conversation

@cicnavi

@cicnavi cicnavi commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

With the protocol cache on, the reads of a login come from the cache, but every login still writes to the database: the authorization code twice (when it is issued and when it is redeemed), the access token once, and the user's row. When many users log in at once, those writes can make the database the bottleneck. This adds an option that keeps authorization codes, and optionally access tokens, in the protocol cache only, and stops rewriting a user's row when the claims have not changed.

The option, off by default

  • ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS lists the artifacts kept in the protocol cache only. With ProtocolArtifactEnum::AuthorizationCode, both writes of a code are gone. With ProtocolArtifactEnum::AccessToken as well (it requires the first), an access token is not written either, unless a refresh token is issued for it: the refresh token's foreign key and the refresh grant need its row.
  • ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE is the lock store, a DSN or a client object, through which a code is redeemed only once. Single use stays atomic through symfony/lock, a new dependency: only the request that claims a code records it consumed, every cache write is read back, and a code proceeds only on positive evidence, so a lost or failed write fails closed. A replay revokes the tokens issued for the code, the cache-only ones included.
  • Requirements, checked on every request: a MemcachedAdapter or RedisAdapter protocol cache, a lock store, and an authorization code lifetime that stays within 30 days with a margin of three hours and one minute. A lock store under which a code could be redeemed twice or the lock could not run is refused (a Memcached client that buffers writes, sends no replies or uses UDP, and a Predis 1 cluster). The rest of its set-up is left to the administrator, with the trade-offs documented.

The configuration documentation, under "Keeping authorization codes and access tokens in the cache only", covers the requirements, how to switch the option on or off across nodes, and an outage runbook.

Changes with the option off too

  • A login no longer writes the user's row when both the row and the user's cache entry hold its claims already (without a protocol cache, the row alone decides), so updated_at no longer tracks the last login.
  • A token request with an unexpired authorization code the OP does not know gets invalid_grant (HTTP 400), and a UserInfo request with an access token the OP does not know gets access_denied (HTTP 401). Both ended on the SimpleSAMLphp error page, with HTTP 500.
  • A lookup of a code or token that finds it in the cache no longer writes the entry back, which could overwrite a revocation written in the meantime.

CI

  • The unit job runs Memcached and Redis service containers, so the tests against real backends run on every PHP version. In CI, a missing server fails them instead of skipping them.
  • The conformance job runs every plan a second time in cache-only mode, on Memcached (docker/docker-compose.cache-only.yml), then checks the OP's database: after the cache-only run, no authorization code and no access token except those backing a refresh token; after the database run, some of each. This doubles the conformance jobs.
  • "Stop SSP" now stops the compose project that "Start SSP docker" started, and docker/docker-compose.yml gives an unset SSP_VERSION or OIDC_VERSION the Dockerfile's default.

Tested

  • CI on the branch: https://github.com/simplesamlphp/simplesamlphp-module-oidc/actions/runs/46913649605. Besides the unit and integration suites, 13 tests run against real Memcached (binary and text protocol) and Redis servers, among them eight forked concurrent claims of one code with exactly one winner.
  • All four conformance plans (Basic, Implicit, RP-initiated logout, back-channel logout) pass in both modes on suite release-v5.3.4, oidcc-codereuse and oidcc-codereuse-30seconds included.

Upgrading

The upgrade guide's entry is headed "Version 6.5 to 6.6", for a v6.6.0 release.

Each of the six commits has a message of its own, with the details and the reasoning.

Assisted-by: Claude Code (claude-opus-5-5, design, implementation, tests & verification)
Assisted-by: OpenAI Codex (gpt-6.2-sol, xhigh review)
Assisted-by: Google Antigravity (gemini-4-neon-high, review)

With the protocol cache in front of the database, the reads of a login
come from the cache, but each login still writes its authorization code
to the database twice. With ProtocolArtifactEnum::AuthorizationCode in
the new protocol_cache_only_artifacts option, new codes are kept in the
protocol cache only (Memcached or Redis), and both writes are gone. The
option is empty by default.

Single use stays atomic through symfony/lock, a new dependency: a code
is claimed in a separate lock store (protocol_cache_only_lock_store, a
DSN or a client object), and only the request which claimed it records
it consumed, with a nonce drawn for that request. A code's cache entry
and its guard are each written by one party only, every write is read
back, and a code proceeds only on positive evidence, so a lost or
failed write fails closed. A replay is recorded in the guard and
revokes the tokens issued for the code: one UPDATE on the primary
database, then a revoked copy of each token written to the cache. While
codes are kept in the cache only, a token found in the database on a
cache miss is not cached again, so a lookup can not overwrite a revoked
copy. With codes in the cache only, the client, redirect URI and PKCE
checks come before the replay check, the scopes after it, and the
code's one deadline, computed before it is persisted, gives the
payload's expiry and every TTL.

The configuration refuses what makes the lock not lock or not run,
checking a DSN by building its client lazily, and leaves the rest of
the lock store's set-up to the administrator; the documentation sets
out the trade-offs, how to switch the option, and an outage runbook.
CI's unit job installs the memcached and redis extensions, which the
new tests use without connecting.

With the option empty: findById() of codes, access tokens and refresh
tokens no longer writes a cache hit back (it could overwrite a
revocation written in the meantime), and an unknown authorization code
answers invalid_grant instead of an error page.

Assisted-by: Claude Code (claude-opus-5-5, design, implementation & tests)
Assisted-by: OpenAI Codex (gpt-6.2-sol, xhigh review)
Assisted-by: Google Antigravity (gemini-4-neon-high, review)
With ProtocolArtifactEnum::AccessToken in the cache-only artifacts list
(next to AuthorizationCode, which it requires), a new access token is
written to the protocol cache only, with a checked write, and not to the
database: one more database write off every login without a refresh
token. A token issued for a code with a database row still goes to the
database.

A token kept in the cache only is valid only while its entry is there
and not revoked and, for a token issued for an authorization code, while
the code's entry records its consumption by the token request which
issued the token (the same issuance nonce) and the code's guard is
clean. A replay of the code thus invalidates all of its cache-only
tokens at once, and a request which lost a race for the code never gets
a valid token.

An access token for which a refresh token is issued is promoted first:
its cache entry is rewritten without the marker, then its row inserted,
so that the refresh token's foreign key and the refresh grant find it.
Only a token the request itself stored is promoted. While access tokens
are kept in the cache only, tokens with a database row and refresh
tokens are neither trusted from the cache nor written to it, and
revocations by authorization code are one UPDATE on the primary.

A cache-only code whose consumed entry landed but whose read-back missed
is now confirmed by the recovery read finding the request's own
consumption, and the final read still runs.

With the option off too, a missing access token counts as revoked: the
UserInfo endpoint answers 401 access_denied instead of a 500, on its
second lookup as well.

Assisted-by: Claude Code (claude-opus-5-5, implementation & tests)
Assisted-by: OpenAI Codex (gpt-6.2-sol, xhigh review)
Assisted-by: Google Antigravity (gemini-4-neon-high, review)
The test set the code's deadline to the current second. When that second
ended before consumption checked the deadline, the code was refused before
it was claimed, and the test's final claim of the code then succeeded. A
deadline one second ahead keeps the check before the claim passing.

Assisted-by: Claude Code (claude-opus-5-5, test fix)
Every login wrote the user's row even when its claims had not changed, a
database write on the login path for nothing but updated_at. A login now
reads the user's row, then the user's protocol cache entry, and writes
nothing when both hold the claims the update would write, compared as
stored JSON strings; without a protocol cache the row alone decides. A
difference in either, a missing row or entry, or a read that fails updates
the user as every login did before.

The cache entry alone is not trusted: it can differ from the row without
any failure (caches local to each node, a lookup refilling it from an older
row, interleaved logins), and a write skipped on its word would leave the
row outdated. Since an update writes the row and then the entry, a login
skips only if it read each before another login's update wrote it, and that
update's claims then stand in both places.

updated_at no longer moves on a login with unchanged claims, and such a
login does not renew the user's cache entry. The upgrade guide says so, and
that with lagging database secondaries a login bringing back earlier claims
moments after a change can leave the change in the row when the cache does
not show it either.

Assisted-by: Claude Code (claude-opus-5-5, implementation & unit tests)
Assisted-by: OpenAI Codex (gpt-6.2-sol, xhigh review)
Assisted-by: Google Antigravity (gemini-4-neon-high, review)
CI never exercised authorization codes and access tokens kept in the
protocol cache only: the conformance OP used FilesystemAdapter, which that
mode refuses, and the tests against real Memcached and Redis servers were
skipped for want of a server.

- The unit job gets Memcached and Redis service containers, so
  CacheOnlyBackendsTest runs on every PHP version. With
  OIDC_TEST_BACKENDS_REQUIRED=1, set in CI, a missing server fails those
  tests instead of skipping them.
- The conformance job runs every plan a second time with
  docker/docker-compose.cache-only.yml, which adds a Memcached container
  and switches the OP to MemcachedAdapter, with codes and access tokens
  kept in the cache only and the same server as the lock store. The plans
  pass in either mode, so a step then checks the OP's database: no
  authorization code, and no access token except those backing a refresh
  token, after the cache-only run; some of each after the database run.
- "Stop SSP" now addresses the compose project that "Start SSP docker"
  created (--project-directory was missing, so it stopped nothing).
- docker-compose.yml gives SSP_VERSION and OIDC_VERSION the Dockerfile's
  defaults, since an empty build argument overrode them. The docs show the
  cache-only command, the network and working directory the compose
  commands need, and link the Docker Compose section directly.

Assisted-by: Claude Code (claude-opus-5-5, implementation & verification)
Assisted-by: OpenAI Codex (gpt-6.2-sol, xhigh review)
Assisted-by: Google Antigravity (gemini-4-neon-high, review)
The case "buffer writes as a string" expected a Memcached lock store DSN
with buffer_writes=true to be accepted, because the memcached extension
3.4.0 reads the string "true" as 0. The build CI installs reads it as on,
so the resolver rightly refused the client, and the unit job failed on
every PHP version on the branch's first CI run. The case is now a test of
its own: it builds the client from the DSN and expects a refusal exactly
when that client buffers writes, whichever way the extension read the
value.

Assisted-by: Claude Code (claude-opus-5-5, test fix)
@cicnavi
cicnavi merged commit 88fa81a into master Dec 3, 2026
19 of 20 checks passed
@cicnavi
cicnavi deleted the feature/cache-only-protocol-artifacts branch December 3, 2026 05:49
@codecov

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.73774% with 90 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.57%. Comparing base (f813c29) to head (eb902b0).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
src/Repositories/AbstractDatabaseRepository.php 0.00% 45 Missing ⚠️
src/Services/Container.php 0.00% 13 Missing ⚠️
src/Utils/LockStoreResolver.php 93.89% 8 Missing ⚠️
src/Utils/IssuanceContext.php 0.00% 6 Missing ⚠️
src/Utils/ConsumptionGate.php 92.85% 5 Missing ⚠️
src/Repositories/AccessTokenRepository.php 97.22% 4 Missing ⚠️
src/Server/Grants/AuthCodeGrant.php 93.93% 4 Missing ⚠️
src/Factories/Grant/AuthCodeGrantFactory.php 0.00% 3 Missing ⚠️
src/Repositories/AuthCodeRepository.php 99.14% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master     #364      +/-   ##
============================================
+ Coverage     58.71%   62.57%   +3.86%     
- Complexity     1517     1818     +301     
============================================
  Files           141      145       +4     
  Lines          6114     6892     +778     
============================================
+ Hits           3590     4313     +723     
- Misses         2524     2579      +55     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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