Skip to content

Commit 88fa81a

Browse files
authored
Keep authorization codes and access tokens in the protocol cache only, as an option (#364)
* Keep authorization codes in the protocol cache only, as an option 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) * Keep access tokens in the protocol cache only, as an option 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) * Make the cache-only deadline test independent of the clock's second 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) * Skip the per-login user update when the claims have not changed 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) * Run cache-only mode in CI: real backends and a conformance run 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) * Judge a buffer_writes string in a lock store DSN by the client built 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)
1 parent f813c29 commit 88fa81a

52 files changed

Lines changed: 8590 additions & 142 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/test.yaml‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,25 @@ jobs:
1414
fail-fast: false
1515
matrix:
1616
php-versions: ["8.3", "8.4", "8.5"]
17+
# Servers for the cache-only artifact tests which run against real backends (CacheOnlyBackendsTest).
18+
services:
19+
memcached:
20+
image: memcached:1.6
21+
ports:
22+
- 11211:11211
23+
redis:
24+
image: redis:7
25+
ports:
26+
- 6379:6379
1727

1828
steps:
1929
- name: Setup PHP, with composer and extensions
2030
uses: shivammathur/setup-php@v2 #https://github.com/shivammathur/setup-php
2131
with:
2232
php-version: ${{ matrix.php-versions }}
23-
extensions: mbstring, xml
33+
# memcached and redis: the cache-only artifact tests build clients of both, and the integration tests
34+
# connect them to the servers above.
35+
extensions: mbstring, xml, memcached, redis
2436
tools: composer:v2
2537
coverage: pcov
2638

@@ -65,6 +77,11 @@ jobs:
6577
./vendor/bin/phpunit $NO_COVERAGE
6678
6779
- name: Run integration tests
80+
env:
81+
OIDC_TEST_MEMCACHED_HOST: 127.0.0.1:11211
82+
OIDC_TEST_REDIS_HOST: 127.0.0.1:6379
83+
# Fail, rather than skip, the real-backend tests if a server is not given.
84+
OIDC_TEST_BACKENDS_REQUIRED: "1"
6885
run: |
6986
echo $NO_COVERAGE
7087
./vendor/bin/phpunit $NO_COVERAGE --no-configuration -c phpunit.integration.xml
@@ -207,11 +224,20 @@ jobs:
207224
run: php vendor/bin/psalm --show-info=true
208225

209226
conformance-suite:
227+
# Named, since the default name would list every matrix value, the compose file arguments included.
228+
name: Conformance suite, SSP ${{ matrix.ssp-version }}, ${{ matrix.protocol-storage }}
210229
runs-on: ubuntu-latest
211230
strategy:
212231
fail-fast: false
213232
matrix:
214233
ssp-version: ["v2.5.0"]
234+
# cache-only: authorization codes and access tokens kept in the protocol cache only, on Memcached.
235+
protocol-storage: ["database", "cache-only"]
236+
include:
237+
- protocol-storage: database
238+
compose-files: -f docker/docker-compose.yml
239+
- protocol-storage: cache-only
240+
compose-files: -f docker/docker-compose.yml -f docker/docker-compose.cache-only.yml
215241
env:
216242
SUITE_BASE_URL: https://localhost.emobix.co.uk:8443
217243
VERSION: release-v5.3.4
@@ -244,7 +270,7 @@ jobs:
244270
working-directory: ./main
245271
# Must run after conformance suite since they share a docker network.
246272
run: |
247-
SSP_VERSION=${{ matrix.ssp-version }} OIDC_VERSION=@dev docker compose -f docker/docker-compose.yml --project-directory . up -d --build
273+
SSP_VERSION=${{ matrix.ssp-version }} OIDC_VERSION=@dev docker compose ${{ matrix.compose-files }} --project-directory . up -d --build
248274
sleep 30
249275
# while ! curl -skfail https://op.local.stack-dev.cirrusidentity.com/.well-known/openid-configuration >/dev/null; do sleep 2; done
250276
- name: Run Basic conformance tests
@@ -259,6 +285,31 @@ jobs:
259285
- name: Run RP backchannel
260286
run: |
261287
./conformance-suite/scripts/run-test-plan.py "oidcc-backchannel-rp-initiated-logout-certification-test-plan[response_type=code][client_registration=static_client]" ./main/conformance-tests/conformance-back-channel-logout-ci.json
288+
- name: Check where codes and access tokens were stored
289+
working-directory: ./main
290+
# The plans pass in either mode, so they can not tell a cache-only run which fell back to the database. A
291+
# code or access token kept in the cache only never gets a database row; one stored in the database always
292+
# does. Access tokens that back a refresh token are written to the database in both modes, so only the others
293+
# are counted. Users are written in both modes (the seeded database has none), which shows the queries read
294+
# the OP's database.
295+
run: |
296+
count() {
297+
docker compose ${{ matrix.compose-files }} --project-directory . exec -T oidc-op \
298+
sqlite3 /var/simplesamlphp/data/mydb.sq3 "SELECT COUNT(*) FROM $1"
299+
}
300+
users=$(count oidc_user)
301+
codes=$(count oidc_auth_code)
302+
tokens=$(count "oidc_access_token a WHERE NOT EXISTS
303+
(SELECT 1 FROM oidc_refresh_token r WHERE r.access_token_id = a.id)")
304+
echo "User rows: $users, authorization code rows: $codes, access token rows without a refresh token: $tokens"
305+
[ "$users" -gt 0 ] || { echo "::error::No user in the database: the check does not read the OP's."; exit 1; }
306+
if [ "${{ matrix.protocol-storage }}" = "cache-only" ]; then
307+
[ "$codes" = "0" ] || { echo "::error::Codes reached the database in a cache-only run."; exit 1; }
308+
[ "$tokens" = "0" ] || { echo "::error::Access tokens reached the database in a cache-only run."; exit 1; }
309+
else
310+
[ "$codes" -gt 0 ] || { echo "::error::No code reached the database in a database run."; exit 1; }
311+
[ "$tokens" -gt 0 ] || { echo "::error::No access token reached the database in a database run."; exit 1; }
312+
fi
262313
- name: Dump OP logs
263314
if: failure()
264315
working-directory: ./main
@@ -267,11 +318,11 @@ jobs:
267318
# failed check anywhere. The reason is in the OP's log, which otherwise leaves with the container.
268319
# Same compose invocation as "Start SSP docker", so this addresses the project that step created.
269320
run: |
270-
docker compose -f docker/docker-compose.yml --project-directory . logs --no-color --tail 2000 oidc-op || true
321+
docker compose ${{ matrix.compose-files }} --project-directory . logs --no-color --tail 2000 oidc-op || true
271322
- name: Stop SSP
272323
working-directory: ./main
273324
run: |
274-
docker compose -f docker/docker-compose.yml down
325+
docker compose ${{ matrix.compose-files }} --project-directory . down
275326
- name: Stop Conformance Suite
276327
working-directory: ./conformance-suite
277328
# cleaning up errors out on removing the network, so add "|| true" to prevent that from breaking the build

‎composer.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
"spomky-labs/base64url": "^2.0",
3737
"symfony/cache": "^7.4",
3838
"symfony/expression-language": "^7.4",
39+
"symfony/lock": "^7.4",
3940
"symfony/psr-http-message-bridge": "^7.4",
4041
"web-token/jwt-framework": "^3.4.10"
4142
},

‎config/module_oidc.php.dist‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,42 @@ $config = [
324324
// 60 * 60 * 6, // Default lifetime in seconds (used when particular cache item doesn't define its own lifetime)
325325
// ],
326326

327+
/**
328+
* (optional) Protocol artifacts kept in the protocol cache only, without a database row. Empty by default: the
329+
* database stores every artifact, and the protocol cache (if set) sits in front of it. Keeping authorization
330+
* codes in the cache only takes two database writes off every login. Keeping access tokens in the cache only as
331+
* well takes one more off every login without a refresh token; it requires AuthorizationCode in the list.
332+
*
333+
* Requires the protocol cache adapter above to be MemcachedAdapter or RedisAdapter, and a lock store (next
334+
* option). Read "Keeping authorization codes and access tokens in the cache only" in the configuration
335+
* documentation first: switching this on or off has to be coordinated across all nodes, and logins stop while
336+
* the cache is down.
337+
*/
338+
ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => [
339+
// \SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum::AuthorizationCode,
340+
// \SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum::AccessToken,
341+
],
342+
343+
/**
344+
* Lock store which lets an authorization code kept in the cache only be redeemed once: a DSN, from which the
345+
* module builds a client of its own, connected lazily (memcached:, redis:, rediss:, valkey: or valkeys:), or a
346+
* client object (Memcached, Redis, RedisCluster, RedisArray, a Relay or a Predis client). Only used when the
347+
* option above is not empty. The documentation explains the trade-offs of each choice.
348+
*/
349+
ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => null,
350+
// The cache's own Memcached servers: the simplest set-up.
351+
// ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => 'memcached://localhost:11211',
352+
// A dedicated instance which never evicts (Redis with "maxmemory-policy noeviction", or memcached -M).
353+
// ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => 'redis://locks.example.org:6379',
354+
// A client object, for a set-up a DSN can not express. It must not be left in a transaction or a pipeline.
355+
// ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => (static function (): \Memcached {
356+
// $client = new \Memcached();
357+
// $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
358+
// $client->setSaslAuthData('user', 'password');
359+
// $client->addServer('locks.example.org', 11211);
360+
// return $client;
361+
// })(),
362+
327363
/**
328364
* Protocol cache duration for particular entities. This is only relevant if protocol cache adapter is set up.
329365
* For duration format info, check https://www.php.net/manual/en/dateinterval.construct.php.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Used on top of docker-compose.yml: the OP keeps authorization codes and access tokens in the protocol cache only,
2+
# on a Memcached server which is its lock store too (docker/ssp/module_oidc.php reads OIDC_CONFORMANCE_MEMCACHED).
3+
# docker compose -f docker/docker-compose.yml -f docker/docker-compose.cache-only.yml --project-directory . up
4+
services:
5+
oidc-memcached:
6+
image: memcached:1.6
7+
oidc-op:
8+
environment:
9+
- OIDC_CONFORMANCE_MEMCACHED=oidc-memcached:11211
10+
depends_on:
11+
- oidc-memcached

‎docker/docker-compose.yml‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@ services:
1616
context: .
1717
dockerfile: docker/Dockerfile
1818
args:
19-
SSP_VERSION: "${SSP_VERSION}"
20-
OIDC_VERSION: "${OIDC_VERSION}"
19+
# Unset, the defaults of docker/Dockerfile: an empty build argument would override them.
20+
SSP_VERSION: "${SSP_VERSION:-v2.5.0}"
21+
OIDC_VERSION: "${OIDC_VERSION:-@dev}"
2122
environment:
2223
- STAGINGCOMPOSERREPOS=oidc
2324
- SSP_ADMIN_PASSWORD=secret1

‎docker/ssp/module_oidc.php‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,19 @@
121121
// Use defaults
122122
],
123123
];
124+
125+
// Set by docker/docker-compose.cache-only.yml: authorization codes and access tokens kept in the protocol cache only,
126+
// on this Memcached server ("host:port"), which is the lock store too.
127+
$cacheOnlyMemcached = getenv('OIDC_CONFORMANCE_MEMCACHED');
128+
if (is_string($cacheOnlyMemcached) && $cacheOnlyMemcached !== '') {
129+
$config[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER] = \Symfony\Component\Cache\Adapter\MemcachedAdapter::class;
130+
$config[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER_ARGUMENTS] = [
131+
\Symfony\Component\Cache\Adapter\MemcachedAdapter::createConnection("memcached://$cacheOnlyMemcached"),
132+
'oidcConformance',
133+
];
134+
$config[ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS] = [
135+
\SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum::AuthorizationCode,
136+
\SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum::AccessToken,
137+
];
138+
$config[ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE] = "memcached://$cacheOnlyMemcached";
139+
}

0 commit comments

Comments
 (0)