diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 1bd08d09b..ce1dfce8a 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -14,13 +14,25 @@ jobs: fail-fast: false matrix: php-versions: ["8.3", "8.4", "8.5"] + # Servers for the cache-only artifact tests which run against real backends (CacheOnlyBackendsTest). + services: + memcached: + image: memcached:1.6 + ports: + - 11211:11211 + redis: + image: redis:7 + ports: + - 6379:6379 steps: - name: Setup PHP, with composer and extensions uses: shivammathur/setup-php@v2 #https://github.com/shivammathur/setup-php with: php-version: ${{ matrix.php-versions }} - extensions: mbstring, xml + # memcached and redis: the cache-only artifact tests build clients of both, and the integration tests + # connect them to the servers above. + extensions: mbstring, xml, memcached, redis tools: composer:v2 coverage: pcov @@ -65,6 +77,11 @@ jobs: ./vendor/bin/phpunit $NO_COVERAGE - name: Run integration tests + env: + OIDC_TEST_MEMCACHED_HOST: 127.0.0.1:11211 + OIDC_TEST_REDIS_HOST: 127.0.0.1:6379 + # Fail, rather than skip, the real-backend tests if a server is not given. + OIDC_TEST_BACKENDS_REQUIRED: "1" run: | echo $NO_COVERAGE ./vendor/bin/phpunit $NO_COVERAGE --no-configuration -c phpunit.integration.xml @@ -207,11 +224,20 @@ jobs: run: php vendor/bin/psalm --show-info=true conformance-suite: + # Named, since the default name would list every matrix value, the compose file arguments included. + name: Conformance suite, SSP ${{ matrix.ssp-version }}, ${{ matrix.protocol-storage }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: ssp-version: ["v2.5.0"] + # cache-only: authorization codes and access tokens kept in the protocol cache only, on Memcached. + protocol-storage: ["database", "cache-only"] + include: + - protocol-storage: database + compose-files: -f docker/docker-compose.yml + - protocol-storage: cache-only + compose-files: -f docker/docker-compose.yml -f docker/docker-compose.cache-only.yml env: SUITE_BASE_URL: https://localhost.emobix.co.uk:8443 VERSION: release-v5.3.4 @@ -244,7 +270,7 @@ jobs: working-directory: ./main # Must run after conformance suite since they share a docker network. run: | - SSP_VERSION=${{ matrix.ssp-version }} OIDC_VERSION=@dev docker compose -f docker/docker-compose.yml --project-directory . up -d --build + SSP_VERSION=${{ matrix.ssp-version }} OIDC_VERSION=@dev docker compose ${{ matrix.compose-files }} --project-directory . up -d --build sleep 30 # while ! curl -skfail https://op.local.stack-dev.cirrusidentity.com/.well-known/openid-configuration >/dev/null; do sleep 2; done - name: Run Basic conformance tests @@ -259,6 +285,31 @@ jobs: - name: Run RP backchannel run: | ./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 + - name: Check where codes and access tokens were stored + working-directory: ./main + # The plans pass in either mode, so they can not tell a cache-only run which fell back to the database. A + # code or access token kept in the cache only never gets a database row; one stored in the database always + # does. Access tokens that back a refresh token are written to the database in both modes, so only the others + # are counted. Users are written in both modes (the seeded database has none), which shows the queries read + # the OP's database. + run: | + count() { + docker compose ${{ matrix.compose-files }} --project-directory . exec -T oidc-op \ + sqlite3 /var/simplesamlphp/data/mydb.sq3 "SELECT COUNT(*) FROM $1" + } + users=$(count oidc_user) + codes=$(count oidc_auth_code) + tokens=$(count "oidc_access_token a WHERE NOT EXISTS + (SELECT 1 FROM oidc_refresh_token r WHERE r.access_token_id = a.id)") + echo "User rows: $users, authorization code rows: $codes, access token rows without a refresh token: $tokens" + [ "$users" -gt 0 ] || { echo "::error::No user in the database: the check does not read the OP's."; exit 1; } + if [ "${{ matrix.protocol-storage }}" = "cache-only" ]; then + [ "$codes" = "0" ] || { echo "::error::Codes reached the database in a cache-only run."; exit 1; } + [ "$tokens" = "0" ] || { echo "::error::Access tokens reached the database in a cache-only run."; exit 1; } + else + [ "$codes" -gt 0 ] || { echo "::error::No code reached the database in a database run."; exit 1; } + [ "$tokens" -gt 0 ] || { echo "::error::No access token reached the database in a database run."; exit 1; } + fi - name: Dump OP logs if: failure() working-directory: ./main @@ -267,11 +318,11 @@ jobs: # failed check anywhere. The reason is in the OP's log, which otherwise leaves with the container. # Same compose invocation as "Start SSP docker", so this addresses the project that step created. run: | - docker compose -f docker/docker-compose.yml --project-directory . logs --no-color --tail 2000 oidc-op || true + docker compose ${{ matrix.compose-files }} --project-directory . logs --no-color --tail 2000 oidc-op || true - name: Stop SSP working-directory: ./main run: | - docker compose -f docker/docker-compose.yml down + docker compose ${{ matrix.compose-files }} --project-directory . down - name: Stop Conformance Suite working-directory: ./conformance-suite # cleaning up errors out on removing the network, so add "|| true" to prevent that from breaking the build diff --git a/composer.json b/composer.json index b25aa7b46..ef75a4295 100644 --- a/composer.json +++ b/composer.json @@ -36,6 +36,7 @@ "spomky-labs/base64url": "^2.0", "symfony/cache": "^7.4", "symfony/expression-language": "^7.4", + "symfony/lock": "^7.4", "symfony/psr-http-message-bridge": "^7.4", "web-token/jwt-framework": "^3.4.10" }, diff --git a/config/module_oidc.php.dist b/config/module_oidc.php.dist index a3a487b60..867fecc89 100644 --- a/config/module_oidc.php.dist +++ b/config/module_oidc.php.dist @@ -324,6 +324,42 @@ $config = [ // 60 * 60 * 6, // Default lifetime in seconds (used when particular cache item doesn't define its own lifetime) // ], + /** + * (optional) Protocol artifacts kept in the protocol cache only, without a database row. Empty by default: the + * database stores every artifact, and the protocol cache (if set) sits in front of it. Keeping authorization + * codes in the cache only takes two database writes off every login. Keeping access tokens in the cache only as + * well takes one more off every login without a refresh token; it requires AuthorizationCode in the list. + * + * Requires the protocol cache adapter above to be MemcachedAdapter or RedisAdapter, and a lock store (next + * option). Read "Keeping authorization codes and access tokens in the cache only" in the configuration + * documentation first: switching this on or off has to be coordinated across all nodes, and logins stop while + * the cache is down. + */ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => [ +// \SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum::AuthorizationCode, +// \SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum::AccessToken, + ], + + /** + * Lock store which lets an authorization code kept in the cache only be redeemed once: a DSN, from which the + * module builds a client of its own, connected lazily (memcached:, redis:, rediss:, valkey: or valkeys:), or a + * client object (Memcached, Redis, RedisCluster, RedisArray, a Relay or a Predis client). Only used when the + * option above is not empty. The documentation explains the trade-offs of each choice. + */ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => null, + // The cache's own Memcached servers: the simplest set-up. +// ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => 'memcached://localhost:11211', + // A dedicated instance which never evicts (Redis with "maxmemory-policy noeviction", or memcached -M). +// ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => 'redis://locks.example.org:6379', + // A client object, for a set-up a DSN can not express. It must not be left in a transaction or a pipeline. +// ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => (static function (): \Memcached { +// $client = new \Memcached(); +// $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); +// $client->setSaslAuthData('user', 'password'); +// $client->addServer('locks.example.org', 11211); +// return $client; +// })(), + /** * Protocol cache duration for particular entities. This is only relevant if protocol cache adapter is set up. * For duration format info, check https://www.php.net/manual/en/dateinterval.construct.php. diff --git a/docker/docker-compose.cache-only.yml b/docker/docker-compose.cache-only.yml new file mode 100644 index 000000000..24ff24119 --- /dev/null +++ b/docker/docker-compose.cache-only.yml @@ -0,0 +1,11 @@ +# Used on top of docker-compose.yml: the OP keeps authorization codes and access tokens in the protocol cache only, +# on a Memcached server which is its lock store too (docker/ssp/module_oidc.php reads OIDC_CONFORMANCE_MEMCACHED). +# docker compose -f docker/docker-compose.yml -f docker/docker-compose.cache-only.yml --project-directory . up +services: + oidc-memcached: + image: memcached:1.6 + oidc-op: + environment: + - OIDC_CONFORMANCE_MEMCACHED=oidc-memcached:11211 + depends_on: + - oidc-memcached diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 83bb8fa30..b49c7af1d 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -16,8 +16,9 @@ services: context: . dockerfile: docker/Dockerfile args: - SSP_VERSION: "${SSP_VERSION}" - OIDC_VERSION: "${OIDC_VERSION}" + # Unset, the defaults of docker/Dockerfile: an empty build argument would override them. + SSP_VERSION: "${SSP_VERSION:-v2.5.0}" + OIDC_VERSION: "${OIDC_VERSION:-@dev}" environment: - STAGINGCOMPOSERREPOS=oidc - SSP_ADMIN_PASSWORD=secret1 diff --git a/docker/ssp/module_oidc.php b/docker/ssp/module_oidc.php index bd16a2d7e..4bd1daa43 100644 --- a/docker/ssp/module_oidc.php +++ b/docker/ssp/module_oidc.php @@ -121,3 +121,19 @@ // Use defaults ], ]; + +// Set by docker/docker-compose.cache-only.yml: authorization codes and access tokens kept in the protocol cache only, +// on this Memcached server ("host:port"), which is the lock store too. +$cacheOnlyMemcached = getenv('OIDC_CONFORMANCE_MEMCACHED'); +if (is_string($cacheOnlyMemcached) && $cacheOnlyMemcached !== '') { + $config[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER] = \Symfony\Component\Cache\Adapter\MemcachedAdapter::class; + $config[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER_ARGUMENTS] = [ + \Symfony\Component\Cache\Adapter\MemcachedAdapter::createConnection("memcached://$cacheOnlyMemcached"), + 'oidcConformance', + ]; + $config[ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS] = [ + \SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum::AuthorizationCode, + \SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum::AccessToken, + ]; + $config[ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE] = "memcached://$cacheOnlyMemcached"; +} diff --git a/docs/3-oidc-configuration.md b/docs/3-oidc-configuration.md index 5d90ef3b2..6ae3b6e50 100644 --- a/docs/3-oidc-configuration.md +++ b/docs/3-oidc-configuration.md @@ -19,12 +19,241 @@ It complements the inline comments in `config/module_oidc.php`. The configured database is the primary storage for protocol artifacts: access tokens, authorization codes, refresh tokens, clients, and user -records. In production, you should also configure a cache in front of the -DB to improve performance during traffic spikes. +records, unless authorization codes or access tokens are kept in the cache +only (below). In +production, you should also configure a cache in front of the DB to improve +performance during traffic spikes. Caching uses Symfony Cache, so any compatible adapter can be used. See the `module_oidc.php` configuration file for adapter selection and parameters. +### Keeping authorization codes and access tokens in the cache only + +With the protocol cache in front of the database, the reads of a login come +from the cache while it holds what they need, except one read of the user's +row, which tells whether the user's claims have changed (the row is written +only then, on the user's first login, or when the cache's copy of the user +disagrees). But each login still writes the authorization code to the +database twice, when the code is issued and when it is redeemed, and the +access token once. With +`ProtocolArtifactEnum::AuthorizationCode` in +`ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS`, new codes are kept in +the protocol cache only, and the two writes of the code are gone. With +`ProtocolArtifactEnum::AccessToken` in the list as well, new access tokens are +kept in the cache only too, except those for which a refresh token is issued +(see [Access tokens in the cache only](#access-tokens-in-the-cache-only)). +`AccessToken` requires `AuthorizationCode`, since such a token depends on its +code's cache entries. Both are off by default. + +Requirements, checked on every request (otherwise every page shows a +configuration error): + +- the protocol cache adapter is `MemcachedAdapter` or `RedisAdapter`, or a +subclass of either which keeps their storage behaviour. Other adapters are +refused: some keep nothing, some keep entries on one node only, and wrappers +such as `ChainAdapter` could confirm a write which did not persist; +- a lock store, in `ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE`, +through which a code is redeemed only once (it uses `symfony/lock`); +- the authorization code lifetime, plus a margin of three hours and one +minute, is at most 30 days (a lock store reads a longer TTL as a date); a +lifetime in months is refused. + +Not checked, but required: every node uses the same cache servers with the +same distribution, prefix and database settings; Redis reads go to the primary +(no replica reads); Redis Cluster runs on Predis 2 or the redis extension; +Relay's client-side cache is off for the protocol cache. The Memcached options +the lock store refuses (below) should not be set on the cache's client either. + +#### Choosing the lock store + +The module refuses a lock store under which a code could be redeemed twice or +the lock could not run: a Memcached client with `buffer_writes`, `noreply` or +`use_udp` on (it answers before the server has decided), and a Predis 1 +cluster (the lock script can not be loaded there). Those are refused with the +configuration, as is a Memcached client object with no servers. A Relay +client with `throw-on-error` on or phpredis compatibility off, and a client +object left in a transaction or a pipeline, can only be seen when a code is +redeemed, which then fails with `server_error`. Everything else is your choice, +with these trade-offs: + +- **A DSN** (recommended): the module builds a client of its own, used for +nothing else, and connects it only when a code is redeemed. **A client +object**: for TLS, SASL or other set-ups a DSN can not express, or to share +the cache's connection. The module checks less of it, and other code must +not leave it in a transaction or a pipeline. Relay and Predis clients are +accepted, but are not tested against the real libraries. +- **The cache's own servers** (simplest, no extra instance): a lock can then be +evicted. That matters only if it happens in the few milliseconds between a +code's claim and the recording of its use; an LRU makes that very unlikely on +a cache which is not starved of memory. Avoid Redis's `volatile-ttl` policy, +which evicts the keys closest to expiry first. **A dedicated instance which +never evicts** (`memcached -M`, Redis `maxmemory-policy noeviction`) closes +that window, but needs sizing and monitoring: when full, it refuses +redemptions (Memcached as a replay, answering `invalid_grant`; Redis with +`server_error`). +- **Memcached's `auto_eject_hosts`, `remove_failed_servers` or replicas, and +Redis client-side sharding** (several hosts without a cluster) keep the token +endpoint up when a server drops out, at the price of a short window, while the +pool changes, in which two nodes can place the same lock on different servers. +- **`lazy=0`** in a Redis DSN connects as soon as the module builds the lock +store, so an unreachable lock store can fail other pages too, not only +redemptions. + +The configuration check covers the DSN's form and the options the cache +component reads when it builds a client; option values it only reads when it +connects (a timeout or retry interval which is not a number, for example) show +up as `server_error` on the first redemption, in the log. + +A code is redeemed once even when two requests race for it, except in the +windows above, or when the backend itself loses a key (a Redis failover which +drops recent writes, a Memcached server lost from the pool), the limit of any +lock on these backends. A failing Memcached lock store refuses redemptions as +replays (`invalid_grant`), a failing Redis one with `server_error`. + +#### What changes + +- A code's cache entries live for up to the code lifetime plus the access +token lifetime and a margin of a few hours, which adds to the memory the cache +needs. Federation or VCI entries on the same instance can push them out; only +a separate instance prevents that. +- A replay of a code revokes the access and refresh tokens issued for it, in +the database and in the cache, for as long as the evidence of the code's use +lasts: up to the access token lifetime (and a few hours) after the code +expired, renewed by each replay recorded (a renewal the cache drops can not +be told from one it keeps). A replay after that, or after an +eviction of the code's entries, is still refused, but without revoking the +tokens; a refresh token issued for the code stays usable then. The database +rows are revoked on the primary database, and a revoked copy of each is +written to the cache; the rows are read for that from the primary database on +SimpleSAMLphp 2.5.3.1 and later, and from any database before, where a +secondary may miss tokens issued moments before. While access tokens are kept +in the cache only, no copies are written, since cached copies of rows are not +trusted then. A replay racing the original +redemption relies on its record in the cache: if the cache refuses that write, +the tokens of the original redemption may stay usable until they expire (the +error is logged). +- With authorization codes alone in the list, access and refresh tokens are +still stored in the database and cached when +issued, but a token found in the database on a cache miss is no longer cached +again, so that a lookup can not overwrite a revoked copy. When a token's +cached copy is evicted, it is read from the database, where a secondary which +lags behind may still show a revocation made moments before as not done, as +with any revocation. +- When the cache evicts a code's entries before they expire (Memcached does +when full, Redis does under an eviction policy), the code can no longer be +redeemed, and the user has to log in again. With `-M` or `noeviction` on the +cache, writes fail instead, and logins answer `server_error`. +- Every write of a code's cache entries is read back. A request which can not +confirm its writes issues no credentials (`server_error`), and the user may +have to log in again. Logins stop while the cache or the lock store is down +(see the runbook below); there is no automatic fallback to the database. +- Flushing the cache, or restarting it without keeping its data, cancels the +logins in progress. +- Codes issued before the switch, with a database row, keep working; their +redemption is recorded in the database only. + +#### Access tokens in the cache only + +With `ProtocolArtifactEnum::AccessToken` in the list as well, a new access +token is written to the cache only, and the write is read back. Such a token +is valid only while all of these hold: + +- its cache entry is there and not revoked; +- for a token issued for an authorization code, the code's cache entries show +that the token request which issued the token redeemed the code, and that no +replay of the code was seen. + +So a replay of a code invalidates all of the code's tokens kept in the cache +only at once, and such a token issued by a request which lost a race for the +code never becomes valid; a request which fails hands out no tokens. A token +issued for no code (by the implicit grant) depends on its own entry only; the +refresh grant issues a refresh token with each access token, so its tokens go +to the database too (below). A token issued for a code with a database row +(one issued before codes were kept in the cache only) is stored in the +database, as before. + +What else changes: + +- An access token for which a refresh token is issued (with the +`offline_access` scope, and at every refresh) is written to the database as +well, before the refresh token: the refresh token refers to it, and the +refresh grant reads it from the database, also after it expired. From then on +it is a token with a database row. So logins with a refresh token keep the +access token's database write. +- Tokens with a database row (those above, those issued before the switch) +and refresh tokens are neither cached nor trusted from the cache: a cached copy +of them is no longer kept current. They are read from the database at the +UserInfo endpoint and at a refresh (reads, not writes), and their revocation +is written to the database only. On a database with secondaries, such a read +may go to a secondary which does not have a token written moments before yet: +a UserInfo request right after a login with a refresh token can then be +refused (HTTP 401). +- Checking a bearer token kept in the cache only and issued for a code takes +one cache round trip more than before: its code's entries are read after its +own entry (and before the client, as always). +- Each token kept in the cache only adds a cache entry for its lifetime and a +minute. A revoked one keeps it for an upper bound of the access token lifetime +(a few hours more, or a few days more for a lifetime in months) and a minute. +So does a token written to the database for its refresh token, at every login +with a refresh token and at every refresh: its entry is then no longer +trusted, only read to see that it is no longer kept in the cache only. +- A token kept in the cache only can not be looked up in the database. When +its entry, or one of its code's, is lost (evicted, or gone with a flush of the +cache or a restart which does not keep its data), the token is refused with +HTTP 401 and the client needs a new one. Tokens with a database row are not +affected. +- If the cache refuses to record a replay of a code while it still serves +reads, the code's tokens kept in the cache only may stay valid until they +expire, unless a later replay of the code is recorded; the error is logged. +- A refresh which fails after the old refresh token was revoked (when the new +access token can not be written, for example) leaves the client without a +usable refresh token, as a database failure at that point does with the +option off. + +#### Switching it on or off, and changing lifetimes + +Switching, either way, is a coordinated change: drain traffic on every node, +make sure every node runs a version which supports the option, change the +configuration on every node, then resume traffic. A rolling switch would let a +node on the old setting trust a cached copy which a node on the new one no +longer keeps current. + +Removing an artifact from the list also needs a cache namespace which has +never been used (a new namespace argument for the adapter), or a backend-wide +flush you verify independently: copies cached before are stale. That cancels +the logins in progress, invalidates the access tokens kept in the cache only, +and forgets the `private_key_jwt` client assertions already used. Adding an +artifact keeps the namespace. + +Change the authorization code or access token lifetime the same way, drained +and on every node: the cache entries take their TTLs from the lifetimes set +when they are written. + +#### Outage runbook + +Logins fail while the cache is down. Logins with the authorization code flow +also fail while the lock store is down: codes kept in the cache only can not +be redeemed then. While the cache is down, UserInfo requests with access +tokens kept in the cache only fail too, and so do token refreshes with access +tokens kept in the cache only: a refresh which gets as far as storing its new +access token has revoked the old refresh token by then, so its client has to +log in again. + +1. To run on the database alone: with traffic drained, clear +`ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS` and remove the protocol +cache adapter together on every node (the configuration refuses the list +without the adapter), then resume. The reuse check of `private_key_jwt` +client assertions is off while there is no protocol cache. +2. To come back: with traffic drained again, configure the adapter with a +never-used namespace on every node (and the list, if wanted), let one request +through so that the namespace is started, then resume. A namespaced clear can +not be verified on Redis; an independently verified backend-wide flush is the +alternative. The same applies to a cache restored from a snapshot, or after a +Redis failover which may have dropped recent writes. + +Codes and access tokens kept in the cache only before the outage are lost, and +their users log in again. + ## Relying Party (RP) administration The module provides a UI to manage clients (create, read, update, delete). diff --git a/docs/4-oidc-docker.md b/docs/4-oidc-docker.md index 6b0d13c3e..015980722 100644 --- a/docs/4-oidc-docker.md +++ b/docs/4-oidc-docker.md @@ -121,7 +121,13 @@ Conformance tests are easier to run locally. See [Conformance](5-oidc-conformanc Docker Compose runs multiple containers to ease testing. It builds an image containing the OIDC module. You can remove `--build` to reuse an -existing container. +existing container. Run the commands below from the root of this +repository. + +The containers join the conformance suite's Docker network, +`conformance-suite_default`, so start the suite first (see +[Conformance](5-oidc-conformance.md)). To run the OP without the suite, +create the network with `docker network create conformance-suite_default`. ```bash # Use current branch/git checkout. Composer installs local checkout @@ -129,6 +135,11 @@ OIDC_VERSION=@dev docker-compose -f docker/docker-compose.yml --project-director # Use a specific module version OIDC_VERSION=dev-master docker-compose -f docker/docker-compose.yml --project-directory . up --build + +# Keep authorization codes and access tokens in the protocol cache only, +# on a Memcached container which is also the lock store +OIDC_VERSION=@dev docker-compose -f docker/docker-compose.yml \ + -f docker/docker-compose.cache-only.yml --project-directory . up --build ``` Visit the OP and verify a few clients exist: diff --git a/docs/5-oidc-conformance.md b/docs/5-oidc-conformance.md index 3b2a24445..7fb5b1b6e 100644 --- a/docs/5-oidc-conformance.md +++ b/docs/5-oidc-conformance.md @@ -35,8 +35,15 @@ Next, run your SSP OIDC image. ### Run SSP Run SSP with OIDC on the same Docker network as the conformance tests so -containers can communicate. See the "Docker Compose" section in the -README for details. +containers can communicate. See +[Docker Compose](4-oidc-docker.md#docker-compose) for details. + +To test with authorization codes and access tokens kept in the protocol +cache only, start SSP with `docker/docker-compose.cache-only.yml` as well +(the same section shows the command). CI runs every plan in both modes, +and checks after a cache-only run that no authorization code reached the +database, and no access token either, except those that back a refresh +token. ### Run conformance tests (interactive) diff --git a/docs/6-oidc-upgrade.md b/docs/6-oidc-upgrade.md index c0e8028cc..98c3c2aad 100644 --- a/docs/6-oidc-upgrade.md +++ b/docs/6-oidc-upgrade.md @@ -3,6 +3,52 @@ This is an upgrade guide from versions 1 → 6. Review the changes and apply those relevant to your deployment. +## Version 6.5 to 6.6 + +New options, disabled by default: + +- `ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS`: protocol artifacts kept +in the protocol cache only, without a database row. With +`ProtocolArtifactEnum::AuthorizationCode` in it, authorization codes are no +longer written to the database, which takes two database writes off every +login. With `ProtocolArtifactEnum::AccessToken` as well, access tokens are not +either, unless a refresh token is issued for them: one more write off every +login without a refresh token. It requires a Memcached or Redis protocol cache +and a lock store, and switching it on or off has to be coordinated across all +nodes: read "Keeping authorization codes and access tokens in the cache only" +in the configuration documentation. Set it only once every node runs this +version. +- `ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE`: the lock store for +the option above, given as a DSN or as a client object. + +New dependency: `symfony/lock`. + +Changes a client can see, with the new options off too: + +- A token request with an unexpired authorization code the OP does not know +gets `invalid_grant`, HTTP 400. It ended on the SimpleSAMLphp error page, with +HTTP 500. +- A UserInfo request with an access token the OP does not know gets +`access_denied`, HTTP 401, as a request with a revoked token does. It ended on +the SimpleSAMLphp error page, with HTTP 500. + +A change in the database, with the new options off too: a login reads the +user's row (table `oidc_user`), and writes nothing when both the row and the +user's protocol cache entry hold the user's claims already, encoded as JSON +and compared as strings (without a protocol cache, the row alone decides). In +any other case, a row that can not be read included, it writes the row and +the cache entry, as every login did before. So `updated_at`, the time the row +was last written, no longer moves on a login with unchanged claims, and no +longer tracks the last login; nothing else in the module records the last +login. Such a login does not renew the user's cache entry either, so the entry +is read again from the database when it expires. The row is read as other +lookups are, so with database secondaries it may come from one that has not +caught up yet: a login that brings back a user's earlier claims moments after +another login stored a change can leave the changed claims in the row, and the +earlier ones in the cache entry until it expires, if the protocol cache does +not show the change either (there is no cache, the caches are local to each +node, writing to it failed, or the entry was refilled from a secondary). + ## Version 6.4 to 6.5 New option, disabled by default: diff --git a/routing/services/services.yml b/routing/services/services.yml index 60f08be9e..b08289502 100644 --- a/routing/services/services.yml +++ b/routing/services/services.yml @@ -109,6 +109,10 @@ services: factory: ['@SimpleSAML\Module\oidc\Factories\CacheFactory', 'forFederation'] # Can return null SimpleSAML\Module\oidc\Utils\ProtocolCache: factory: ['@SimpleSAML\Module\oidc\Factories\CacheFactory', 'forProtocol'] # Can return null + SimpleSAML\Module\oidc\Utils\LockStoreResolver: ~ + SimpleSAML\Module\oidc\Utils\IssuanceContext: ~ # Shared: one issuance nonce for the grant and the repositories + SimpleSAML\Module\oidc\Utils\ConsumptionGate: + factory: ['@SimpleSAML\Module\oidc\Factories\CacheFactory', 'forConsumptionGate'] # Can return null # Use (already available) Laminas\Diactoros package as PSR HTTP Factories. Laminas\Diactoros\ServerRequestFactory: ~ diff --git a/src/Codebooks/ProtocolArtifactEnum.php b/src/Codebooks/ProtocolArtifactEnum.php new file mode 100644 index 000000000..924cbd476 --- /dev/null +++ b/src/Codebooks/ProtocolArtifactEnum.php @@ -0,0 +1,16 @@ +getAttribute('oauth_scopes'); + // Looked up again after the validator: a token which is gone, or kept in the protocol cache only and no longer + // valid (its code replayed in the meantime, for one), is refused as the validator refuses it. $accessToken = $this->accessTokenRepository->findById($tokenId); if (!$accessToken instanceof AccessTokenEntity) { - throw new Error\UserNotFound('Access token not found'); + throw OidcServerException::accessDenied('Access token not found'); } $user = $this->getUser($accessToken); diff --git a/src/Factories/CacheFactory.php b/src/Factories/CacheFactory.php index 73c9258bf..95c1aada1 100644 --- a/src/Factories/CacheFactory.php +++ b/src/Factories/CacheFactory.php @@ -8,10 +8,14 @@ use SimpleSAML\Module\oidc\ModuleConfig; use SimpleSAML\Module\oidc\Services\LoggerService; use SimpleSAML\Module\oidc\Utils\ClassInstanceBuilder; +use SimpleSAML\Module\oidc\Utils\ConsumptionGate; use SimpleSAML\Module\oidc\Utils\FederationCache; +use SimpleSAML\Module\oidc\Utils\LockStoreResolver; use SimpleSAML\Module\oidc\Utils\ProtocolCache; use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\Cache\Psr16Cache; +use Symfony\Component\Lock\Store\MemcachedStore; +use Symfony\Component\Lock\Store\RedisStore; class CacheFactory { @@ -19,6 +23,7 @@ public function __construct( protected ModuleConfig $moduleConfig, protected LoggerService $loggerService, protected ClassInstanceBuilder $classInstanceBuilder, + protected LockStoreResolver $lockStoreResolver = new LockStoreResolver(), ) { } @@ -83,4 +88,47 @@ public function forProtocol(): ?ProtocolCache return new ProtocolCache(new Psr16Cache($adapter)); } + + /** + * The gate consuming authorization codes kept in the protocol cache only, or null while no artifact is kept in + * the cache only. Building a client from a DSN does not connect, unless a Redis DSN sets "lazy" off. + * + * @throws \SimpleSAML\Module\oidc\Exceptions\OidcException + */ + public function forConsumptionGate(): ?ConsumptionGate + { + if ($this->moduleConfig->getProtocolCacheOnlyArtifacts() === []) { + return null; + } + + try { + $client = $this->lockStoreResolver->buildClient($this->moduleConfig->getProtocolCacheOnlyLockStore()); + $ttl = $this->moduleConfig->getProtocolCacheOnlyLockTtl(); + + if ($client instanceof \Memcached) { + $store = new MemcachedStore($client, $ttl); + } else { + $store = $this->buildRedisLockStore($client, $ttl); + } + } catch (\Throwable $exception) { + // The exception's message may quote the DSN, which may hold a password. + $message = sprintf( + 'Error building the lock store (%s).', + (new \ReflectionClass($exception))->getShortName(), + ); + $this->loggerService->error($message); + throw new OidcException($message); + } + + return new ConsumptionGate($store, $client); + } + + /** + * The client class was checked with the module configuration; a client of another class fails here. + */ + protected function buildRedisLockStore(object $client, int $ttl): RedisStore + { + /** @psalm-suppress ArgumentTypeCoercion, PossiblyInvalidArgument, InvalidArgument */ + return new RedisStore($client, (float)$ttl); // @phpstan-ignore argument.type + } } diff --git a/src/Factories/Grant/AuthCodeGrantFactory.php b/src/Factories/Grant/AuthCodeGrantFactory.php index a72a53c4c..40091c81c 100644 --- a/src/Factories/Grant/AuthCodeGrantFactory.php +++ b/src/Factories/Grant/AuthCodeGrantFactory.php @@ -26,6 +26,8 @@ use SimpleSAML\Module\oidc\Server\Grants\AuthCodeGrant; use SimpleSAML\Module\oidc\Server\RequestRules\RequestRulesManager; use SimpleSAML\Module\oidc\Server\TokenIssuers\RefreshTokenIssuer; +use SimpleSAML\Module\oidc\Services\LoggerService; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; use SimpleSAML\Module\oidc\Utils\RequestParamsResolver; class AuthCodeGrantFactory @@ -41,6 +43,8 @@ public function __construct( private readonly AuthCodeEntityFactory $authCodeEntityFactory, private readonly RefreshTokenIssuer $refreshTokenIssuer, private readonly Helpers $helpers, + private readonly LoggerService $loggerService, + private readonly IssuanceContext $issuanceContext, ) { } @@ -60,6 +64,9 @@ public function build(): AuthCodeGrant $this->authCodeEntityFactory, $this->refreshTokenIssuer, $this->helpers, + $this->moduleConfig, + $this->loggerService, + $this->issuanceContext, ); $authCodeGrant->setRefreshTokenTTL($this->moduleConfig->getRefreshTokenDuration()); diff --git a/src/Helpers/DateTime.php b/src/Helpers/DateTime.php index 2813b2082..31091dcb5 100644 --- a/src/Helpers/DateTime.php +++ b/src/Helpers/DateTime.php @@ -4,11 +4,17 @@ namespace SimpleSAML\Module\oidc\Helpers; +use DateInterval; use DateTimeImmutable; use DateTimeZone; class DateTime { + /** + * Margin for a daylight-saving shift, which is two hours at most (Antarctica/Troll). + */ + final public const int DAYLIGHT_SAVING_MARGIN_SECONDS = 3 * 3600; + public function getUtc(string $time = 'now'): DateTimeImmutable { return new DateTimeImmutable($time, new DateTimeZone('UTC')); @@ -23,4 +29,23 @@ public function getSecondsToExpirationTime(int $expirationTime): int { return $expirationTime - $this->getUtc()->getTimestamp(); } + + /** + * An upper bound, in seconds, of the time the interval spans when it is added to any moment in any time zone: a + * year counts 366 days and a month 31, and a daylight-saving margin is added. A calendar interval spans a + * different number of seconds depending on when it is added (31 January plus P1M is 3 March, 1 February plus P1M + * is 1 March), so its exact length can not be known in advance. + */ + public function getMaxSecondsOf(DateInterval $interval): int + { + if ($interval->days === false) { + $days = $interval->y * 366 + $interval->m * 31 + $interval->d; + } else { + $days = $interval->days; + } + + $seconds = $interval->h * 3600 + $interval->i * 60 + $interval->s + (int)ceil($interval->f); + + return $days * 86400 + $seconds + self::DAYLIGHT_SAVING_MARGIN_SECONDS; + } } diff --git a/src/ModuleConfig.php b/src/ModuleConfig.php index 48d36a06a..7c495ae26 100644 --- a/src/ModuleConfig.php +++ b/src/ModuleConfig.php @@ -23,9 +23,14 @@ use SimpleSAML\Configuration; use SimpleSAML\Error\ConfigurationError; use SimpleSAML\Module\oidc\Bridges\SspBridge; +use SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum; +use SimpleSAML\Module\oidc\Helpers\DateTime as DateTimeHelper; use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; +use SimpleSAML\Module\oidc\Utils\LockStoreResolver; use SimpleSAML\OpenID\Codebooks\ScopesEnum; use SimpleSAML\OpenID\Codebooks\TrustMarkStatusEndpointUsagePolicyEnum; +use Symfony\Component\Cache\Adapter\MemcachedAdapter; +use Symfony\Component\Cache\Adapter\RedisAdapter; class ModuleConfig { @@ -37,6 +42,16 @@ class ModuleConfig */ final public const string DEFAULT_FILE_NAME = 'module_oidc.php'; + /** + * Memcached reads a TTL above 30 days as a Unix timestamp. + */ + final public const int MEMCACHED_MAX_RELATIVE_TTL_SECONDS = 30 * 86400; + + /** + * Added to the TTLs of entries the protocol cache is the only authority on, beyond the moment they are needed. + */ + final public const int CACHE_ONLY_TTL_MARGIN_SECONDS = 60; + final public const string OPTION_PKI_PRIVATE_KEY_PASSPHRASE = 'pass_phrase'; final public const string OPTION_PKI_PRIVATE_KEY_FILENAME = 'privatekey'; final public const string DEFAULT_PKI_PRIVATE_KEY_FILENAME = 'oidc_module.key'; @@ -96,6 +111,8 @@ class ModuleConfig final public const string OPTION_PROTOCOL_CLIENT_ENTITY_CACHE_DURATION = 'protocol_client_entity_cache_duration'; final public const string OPTION_PROTOCOL_DISCOVERY_SHOW_CLAIMS_SUPPORTED = 'protocol_discover_show_claims_supported'; + final public const string OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS = 'protocol_cache_only_artifacts'; + final public const string OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE = 'protocol_cache_only_lock_store'; final public const string OPTION_DISALLOW_IMPLICIT_FOR_CONFIDENTIAL_CLIENTS = 'disallow_implicit_for_confidential_clients'; @@ -147,6 +164,7 @@ public function __construct( array $overrides = [], // Primarily used for easy (unit) testing overrides. ?Configuration $sspConfig = null, private readonly SspBridge $sspBridge = new SspBridge(), + private readonly LockStoreResolver $lockStoreResolver = new LockStoreResolver(), ) { $this->moduleConfig = Configuration::loadFromArray( array_merge(Configuration::getConfig($fileName)->toArray(), $overrides), @@ -228,6 +246,89 @@ function (array $scope, string $name): void { ' null value or string value indicating particular supported ACR.'); } } + + $this->validateProtocolCacheOnlyArtifacts(); + } + + /** + * Checks the cache-only artifacts and their lock store, without connecting to anything: validation runs on every + * request, and an unreachable lock store must not take down the pages which do not use it. + * + * @throws \SimpleSAML\Error\ConfigurationError + * @throws \Exception + */ + private function validateProtocolCacheOnlyArtifacts(): void + { + /** @var mixed $artifacts */ + $artifacts = $this->config()->getOptionalValue(self::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS, []); + + if (!is_array($artifacts)) { + throw new ConfigurationError(sprintf( + 'Config option %s must be an array of %s cases.', + self::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS, + ProtocolArtifactEnum::class, + )); + } + + /** @psalm-suppress MixedAssignment */ + foreach ($artifacts as $artifact) { + if (!$artifact instanceof ProtocolArtifactEnum) { + throw new ConfigurationError(sprintf( + 'Config option %s must contain %s cases only.', + self::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS, + ProtocolArtifactEnum::class, + )); + } + } + + if ($artifacts === []) { + return; + } + + if ( + in_array(ProtocolArtifactEnum::AccessToken, $artifacts, true) && + !in_array(ProtocolArtifactEnum::AuthorizationCode, $artifacts, true) + ) { + throw new ConfigurationError(sprintf( + 'Config option %s: %s requires %s, since an access token kept in the cache only depends on its ' . + 'authorization code\'s cache entries.', + self::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS, + ProtocolArtifactEnum::AccessToken->name, + ProtocolArtifactEnum::AuthorizationCode->name, + )); + } + + $adapterClass = $this->getProtocolCacheAdapterClass(); + + // Subclasses are accepted on trust that they keep their parent's storage behaviour. Wrappers (chain, proxy) + // could confirm a write from a layer which does not persist it, and node-local adapters (array, filesystem, + // APCu) do not share entries between nodes. + if ( + $adapterClass === null || + (!is_a($adapterClass, MemcachedAdapter::class, true) && !is_a($adapterClass, RedisAdapter::class, true)) + ) { + throw new ConfigurationError(sprintf( + 'Config option %s requires the protocol cache adapter (%s) to be %s or %s.', + self::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS, + self::OPTION_PROTOCOL_CACHE_ADAPTER, + MemcachedAdapter::class, + RedisAdapter::class, + )); + } + + // Memcached reads a TTL above 30 days as a Unix timestamp, and the lock store passes its TTL on as given. + $lockTtl = $this->getProtocolCacheOnlyLockTtl(); + if ($lockTtl > self::MEMCACHED_MAX_RELATIVE_TTL_SECONDS) { + throw new ConfigurationError(sprintf( + 'Config option %s: the authorization code lifetime (%s) makes the lock TTL %d seconds, above the ' . + '30 days a lock store accepts.', + self::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS, + self::OPTION_TOKEN_AUTHORIZATION_CODE_TTL, + $lockTtl, + )); + } + + $this->lockStoreResolver->validate($this->getProtocolCacheOnlyLockStore()); } public function moduleName(): string @@ -490,6 +591,46 @@ public function getProtocolCacheAdapterArguments(): array return $this->config()->getOptionalArray(self::OPTION_PROTOCOL_CACHE_ADAPTER_ARGUMENTS, []); } + /** + * Artifacts kept in the protocol cache only, without a database row. Empty by default. + * + * @return \SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum[] + */ + public function getProtocolCacheOnlyArtifacts(): array + { + /** @var mixed $artifacts */ + $artifacts = $this->config()->getOptionalValue(self::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS, []); + + // Validated on construction; filtered for the type checkers. + return is_array($artifacts) ? + array_values(array_filter($artifacts, fn(mixed $a): bool => $a instanceof ProtocolArtifactEnum)) : + []; + } + + public function isProtocolArtifactCacheOnly(ProtocolArtifactEnum $artifact): bool + { + return in_array($artifact, $this->getProtocolCacheOnlyArtifacts(), true); + } + + /** + * The lock store consuming authorization codes kept in the protocol cache only: a DSN or a client object. + */ + public function getProtocolCacheOnlyLockStore(): mixed + { + return $this->config()->getOptionalValue(self::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE, null); + } + + /** + * TTL of a claim in the lock store, in seconds: an upper bound of the authorization code lifetime, plus margin. + * + * @throws \Exception + */ + public function getProtocolCacheOnlyLockTtl(): int + { + return (new DateTimeHelper())->getMaxSecondsOf($this->getAuthCodeDuration()) + + self::CACHE_ONLY_TTL_MARGIN_SECONDS; + } + /** * Get cache duration for user entities (user data). If not set in configuration, it will fall back to SSP session * duration. diff --git a/src/Repositories/AbstractDatabaseRepository.php b/src/Repositories/AbstractDatabaseRepository.php index 9434eafb9..449602835 100644 --- a/src/Repositories/AbstractDatabaseRepository.php +++ b/src/Repositories/AbstractDatabaseRepository.php @@ -15,12 +15,27 @@ */ namespace SimpleSAML\Module\oidc\Repositories; +use PDO; use SimpleSAML\Database; +use SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum; use SimpleSAML\Module\oidc\ModuleConfig; +use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; use SimpleSAML\Module\oidc\Utils\ProtocolCache; +use Throwable; abstract class AbstractDatabaseRepository { + /** + * Marks a cached entry as kept in the protocol cache only, without a database row. An extra key in the cached + * array, never in an entity's state: it is never bound to a statement, and the entity factories ignore it. + */ + final public const string KEY_CACHE_ONLY = 'cache_only'; + + /** + * The issuance nonce stored with an entry kept in the cache only, beside the marker. + */ + final public const string KEY_CACHE_ONLY_ISSUANCE_NONCE = 'cache_only_issuance_nonce'; + /** * ClientRepository constructor. * @throws \Exception @@ -40,4 +55,121 @@ public function getCacheKey(string $identifier): string } abstract public function getTableName(): ?string; + + /** + * Whether authorization codes are kept in the protocol cache only. Tokens found in the database are then not + * cached again on a lookup: a replay's revoked copy must not be overwritten by a lookup which read the row before + * it was revoked. + */ + protected function areAuthCodesCacheOnly(): bool + { + return $this->moduleConfig->isProtocolArtifactCacheOnly(ProtocolArtifactEnum::AuthorizationCode); + } + + /** + * Whether new access tokens are kept in the protocol cache only. Tokens with a database row (refresh tokens, and + * access tokens issued before the switch or promoted for a refresh token) are then neither trusted from the cache + * nor written to it: their cached copies are no longer kept current. + */ + protected function areAccessTokensCacheOnly(): bool + { + return $this->moduleConfig->isProtocolArtifactCacheOnly(ProtocolArtifactEnum::AccessToken); + } + + /** + * Whether a cached value is an entry kept in the protocol cache only. + */ + protected function isCacheOnlyEntry(mixed $data): bool + { + return is_array($data) && ($data[self::KEY_CACHE_ONLY] ?? null) === true; + } + + /** + * The protocol cache, on a path where it is the only authority. The configuration refuses cache-only artifacts + * without a protocol cache, so its absence here is a server error, never a write to skip. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function requireProtocolCache(): ProtocolCache + { + return $this->protocolCache ?? throw OidcServerException::serverError( + 'Protocol artifacts are kept in the cache only, but no protocol cache is configured.', + ); + } + + /** + * For a replay of an authorization code kept in the protocol cache only, in a table of tokens issued for codes: + * revokes every row issued for the code with one UPDATE on the primary database, which also reaches rows a + * secondary does not have yet, then writes a revoked cached copy of each row and reads it back, whether or not a + * copy was cached (a failed read looks like a miss), so that no reader trusts an unrevoked copy. The rows are read + * from the primary database where SimpleSAMLphp offers it (2.5.3.1 and later), else as other reads are. While codes + * are kept in the cache only, a token read from the database is not cached again (findById()), so the revoked + * copy is not overwritten by a lookup which read the row before it was revoked. + * + * While access tokens are kept in the cache only, no cached copy of a row is trusted, so the UPDATE is all there + * is to do: no rows are read and no copies written. + * + * @param int $cachedCopyTtl Seconds; an upper bound of the tokens' lifetime, since stored expiries can not be + * trusted for a TTL. + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException When a row or a cached copy could not be + * revoked; every cached copy is attempted first. + */ + protected function revokeAllByAuthCodeIdOnPrimary(string $authCodeId, int $cachedCopyTtl): void + { + $tableName = (string)$this->getTableName(); + + try { + $this->database->write( + "UPDATE $tableName SET is_revoked = :is_revoked WHERE auth_code_id = :auth_code_id", + [ + 'is_revoked' => [true, PDO::PARAM_BOOL], + 'auth_code_id' => $authCodeId, + ], + ); + } catch (Throwable $exception) { + throw OidcServerException::serverError( + 'Could not revoke the tokens issued for an authorization code.', + $exception, + ); + } + + if ($this->protocolCache === null || $this->areAccessTokensCacheOnly()) { + return; + } + + try { + $selectStatement = "SELECT * FROM $tableName WHERE auth_code_id = :auth_code_id"; + $selectParameters = ['auth_code_id' => $authCodeId]; + $rows = (method_exists($this->database, 'readPrimary') ? + $this->database->readPrimary($selectStatement, $selectParameters) : + $this->database->read($selectStatement, $selectParameters))->fetchAll(PDO::FETCH_ASSOC); + } catch (Throwable $exception) { + throw OidcServerException::serverError( + 'Could not read the revoked tokens issued for an authorization code: their cached copies stay ' . + 'valid for readers of the cache until they expire.', + $exception, + ); + } + + $failures = 0; + + /** @var array $row */ + foreach ($rows as $row) { + try { + $row['is_revoked'] = true; + $this->protocolCache->setChecked($row, $cachedCopyTtl, $this->getCacheKey((string)$row['id'])); + } catch (Throwable) { + $failures++; + } + } + + if ($failures > 0) { + throw OidcServerException::serverError(sprintf( + 'Could not revoke %d cached cop%s of tokens issued for an authorization code: they stay valid ' . + 'for readers of the cache until they expire.', + $failures, + $failures === 1 ? 'y' : 'ies', + )); + } + } } diff --git a/src/Repositories/AccessTokenRepository.php b/src/Repositories/AccessTokenRepository.php index 7be4ac561..5341600bc 100644 --- a/src/Repositories/AccessTokenRepository.php +++ b/src/Repositories/AccessTokenRepository.php @@ -31,12 +31,34 @@ use SimpleSAML\Module\oidc\ModuleConfig; use SimpleSAML\Module\oidc\Repositories\Interfaces\AccessTokenRepositoryInterface; use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; use SimpleSAML\Module\oidc\Utils\ProtocolCache; +use Throwable; +/** + * Access tokens, in the database (the default) or, with ProtocolArtifactEnum::AccessToken in + * ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS, in the protocol cache only. + * + * A token kept in the cache only has one cache key, its entry: the token's state with the cache-only marker and, for + * a token issued for an authorization code, the issuance nonce of the request which issued it. Such a token is valid + * only while its entry is there and not revoked and, for a token issued for a code, while the code's entry records + * its consumption by that same request and the code's guard is clean: a replay of the code invalidates it, and so do + * the tokens of a request which did not consume the code. A token follows its code's storage: one issued for a code + * with a database row is stored in the database. A token for which a refresh token is issued is promoted to the + * database first (ensureStoredInDatabase()). + */ class AccessTokenRepository extends AbstractDatabaseRepository implements AccessTokenRepositoryInterface { final public const string TABLE_NAME = 'oidc_access_token'; + /** + * The tokens this request stored: true for one it persisted in the cache only and has neither promoted nor + * revoked, false for one found or stored in the database. It decides whether a token is promoted, never what a + * lookup answers. A marked entry this request only looked up is not remembered, and is never promoted. + * + * @var array + */ + protected array $cacheOnlyResidency = []; public function __construct( ModuleConfig $moduleConfig, @@ -45,6 +67,8 @@ public function __construct( protected readonly ClientRepository $clientRepository, protected readonly AccessTokenEntityFactory $accessTokenEntityFactory, protected readonly Helpers $helpers, + protected readonly AuthCodeRepository $authCodeRepository, + protected readonly IssuanceContext $issuanceContext, ) { parent::__construct($moduleConfig, $database, $protocolCache); } @@ -101,75 +125,132 @@ public function persistNewAccessToken(OAuth2AccessTokenEntityInterface $accessTo throw new Error('Invalid AccessTokenEntity'); } - $stmt = sprintf( - "INSERT INTO %s (id, scopes, expires_at, user_id, client_id, is_revoked, auth_code_id, requested_claims) " - . "VALUES (:id, :scopes, :expires_at, :user_id, :client_id, :is_revoked, :auth_code_id, :requested_claims)", - $this->getTableName(), - ); + if ($this->isToBeKeptInCacheOnly($accessTokenEntity)) { + $this->persistCacheOnly($accessTokenEntity); + return; + } - $this->database->write( - $stmt, - $this->preparePdoState($accessTokenEntity->getState()), - ); + $this->insert($accessTokenEntity); - $this->protocolCache?->set( - $accessTokenEntity->getState(), - $this->helpers->dateTime()->getSecondsToExpirationTime( - $accessTokenEntity->getExpiryDateTime()->getTimestamp(), - ), - $this->getCacheKey((string)$accessTokenEntity->getIdentifier()), - ); + $this->cacheOnlyResidency[(string)$accessTokenEntity->getIdentifier()] = false; + + // While access tokens are kept in the cache only, a token with a row is not cached. + if (!$this->areAccessTokensCacheOnly()) { + $this->protocolCache?->set( + $accessTokenEntity->getState(), + $this->helpers->dateTime()->getSecondsToExpirationTime( + $accessTokenEntity->getExpiryDateTime()->getTimestamp(), + ), + $this->getCacheKey((string)$accessTokenEntity->getIdentifier()), + ); + } } /** * Find Access Token by id. + * + * A token kept in the cache only is trusted from the cache, and found only while it is valid (see the class + * description): a revoked one, or one whose code was replayed or not consumed by the request which issued it, is + * not found. While access tokens are kept in the cache only, a cached copy of a token with a database row is not + * trusted. A cache hit is never written back. + * * @throws \Exception * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException */ public function findById(string $tokenId): ?AccessTokenEntity { - /** @var ?array $data */ + /** @var mixed $data */ $data = $this->protocolCache?->get(null, $this->getCacheKey($tokenId)); - if (!is_array($data)) { - $stmt = $this->database->read( - "SELECT * FROM {$this->getTableName()} WHERE id = :id", - [ - 'id' => $tokenId, - ], - ); - - if (empty($rows = $stmt->fetchAll())) { - return null; - } - + if ($this->isCacheOnlyEntry($data)) { /** @var array $data */ - $data = current($rows); + return $this->isCacheOnlyEntryValid($data) ? $this->hydrate($data) : null; } - $data['client'] = $this->clientRepository->findById((string)$data['client_id']); + if (is_array($data) && !$this->areAccessTokensCacheOnly()) { + return $this->hydrate($data); + } - $accessTokenEntity = $this->accessTokenEntityFactory->fromState($data); + $accessTokenEntity = $this->findByIdInDatabase($tokenId); - $this->protocolCache?->set( - $accessTokenEntity->getState(), - $this->helpers->dateTime()->getSecondsToExpirationTime( - $accessTokenEntity->getExpiryDateTime()->getTimestamp(), - ), - $this->getCacheKey((string)$accessTokenEntity->getIdentifier()), - ); + // A row found on a miss is cached, except while codes or access tokens are kept in the cache only: a replay's + // revoked copy must not be overwritten by a lookup which read the row before it was revoked, and copies of + // rows are not trusted while access tokens are kept in the cache only. + if ( + $accessTokenEntity !== null && + !$this->areAuthCodesCacheOnly() && + !$this->areAccessTokensCacheOnly() + ) { + $this->protocolCache?->set( + $accessTokenEntity->getState(), + $this->helpers->dateTime()->getSecondsToExpirationTime( + $accessTokenEntity->getExpiryDateTime()->getTimestamp(), + ), + $this->getCacheKey((string)$accessTokenEntity->getIdentifier()), + ); + } return $accessTokenEntity; } + /** + * Find Access Token by its database row, whatever the cache holds: for callers which know the token has a row, + * such as the refresh token repository loading a refresh token's access token (expired or not). + * + * @throws \Exception + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + public function findByIdInDatabase(string $tokenId): ?AccessTokenEntity + { + $row = $this->findRow($tokenId); + + if ($row === null) { + return null; + } + + $this->cacheOnlyResidency[$tokenId] = false; + + return $this->hydrate($row); + } + /** * {@inheritdoc} + * + * A token kept in the cache only gets its entry written revoked, marker and nonce kept. + * * @throws \JsonException * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException */ public function revokeAccessToken($tokenId): void { - $accessToken = $this->findById($tokenId); + // A token this request is issuing is no longer promoted once its revocation was attempted, even one which + // fails: the revocation may have landed. + if (($this->cacheOnlyResidency[$tokenId] ?? null) === true) { + unset($this->cacheOnlyResidency[$tokenId]); + } + + /** @var mixed $data */ + $data = $this->protocolCache?->get(null, $this->getCacheKey($tokenId)); + + if ($this->isCacheOnlyEntry($data)) { + /** @var array $data */ + $data['is_revoked'] = true; + + $this->requireProtocolCache()->setChecked( + $data, + $this->accessTokenMaxSeconds() + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + $this->getCacheKey($tokenId), + ); + + return; + } + + // The value read above decides, never a second read: a marked entry missed by that read (a failed read looks + // like a miss) must not be taken for a token with a row, whose UPDATE would then change nothing. Such a token + // is not found in the database, and its revocation fails. + $accessToken = is_array($data) && !$this->areAccessTokensCacheOnly() ? + $this->hydrate($data) : + $this->findByIdInDatabase($tokenId); if (!$accessToken instanceof AccessTokenEntity) { throw new RuntimeException("AccessToken not found: $tokenId"); @@ -180,11 +261,72 @@ public function revokeAccessToken($tokenId): void } /** + * Makes sure that an access token, for which a refresh token is about to be stored, has a database row: the + * refresh token's foreign key needs it, and the refresh grant loads it from the database, also once it expired. + * Only while access tokens are kept in the cache only, since every other token has its row already. A token kept + * in the cache only is promoted: its cache entry is written without the marker, so that it is no longer trusted + * from the cache, then its row is inserted, and its revocation goes to the row from then on. In that order, no + * failure leaves a row behind a token which is still marked: until the row is there, the token is not valid. + * + * Only a token this request stored in the cache only is promoted: the grants issue a refresh token in the request + * which issued its access token, before handing either out. A token kept in the cache only by another request is + * refused: it may be in use, and its promotion could race its revocation, or a replay of its code, and undo it. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException When the token could not be promoted, or + * is neither this request's nor in the database: the refresh token must not be stored. + */ + public function ensureStoredInDatabase(OAuth2AccessTokenEntityInterface $accessTokenEntity): void + { + if (!$this->areAccessTokensCacheOnly()) { + return; + } + + if (!$accessTokenEntity instanceof AccessTokenEntityInterface) { + throw OidcServerException::serverError('Unexpected access token entity type.'); + } + + $tokenId = $accessTokenEntity->getIdentifier(); + + if (!($this->cacheOnlyResidency[$tokenId] ?? $this->resolveCacheOnlyResidency($tokenId))) { + return; + } + + $this->requireProtocolCache()->setChecked( + $accessTokenEntity->getState(), + $this->accessTokenMaxSeconds() + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + $this->getCacheKey($tokenId), + ); + + try { + $this->insert($accessTokenEntity); + } catch (Throwable $exception) { + throw OidcServerException::serverError( + 'Could not store the access token for which a refresh token is issued.', + $exception, + ); + } + + $this->cacheOnlyResidency[$tokenId] = false; + } + + /** + * {@inheritdoc} + * + * While access tokens are kept in the cache only, one UPDATE on the primary database (revokeAllByAuthCodeId()), + * which also reaches rows a lagging secondary does not have yet. The tokens kept in the cache only go with their + * code's guard. + * * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException * @throws \JsonException + * @throws \Exception */ public function revokeByAuthCodeId(string $authCodeId): void { + if ($this->areAccessTokensCacheOnly()) { + $this->revokeAllByAuthCodeId($authCodeId); + return; + } + $stmt = $this->database->read( "SELECT id FROM {$this->getTableName()} WHERE auth_code_id = :auth_code_id", ['auth_code_id' => $authCodeId], @@ -197,17 +339,29 @@ public function revokeByAuthCodeId(string $authCodeId): void /** * {@inheritdoc} + * @throws \Exception + */ + public function revokeAllByAuthCodeId(string $authCodeId): void + { + $this->revokeAllByAuthCodeIdOnPrimary( + $authCodeId, + $this->helpers->dateTime()->getMaxSecondsOf($this->moduleConfig->getAccessTokenDuration()) + + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + ); + } + + /** + * {@inheritdoc} + * + * A token not found counts as revoked, and so does a token kept in the cache only which is no longer valid. + * * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException */ public function isAccessTokenRevoked($tokenId): bool { $accessToken = $this->findById($tokenId); - if (!$accessToken) { - throw new RuntimeException("AccessToken not found: $tokenId"); - } - - return $accessToken->isRevoked(); + return $accessToken === null || $accessToken->isRevoked(); } /** @@ -234,6 +388,174 @@ public function removeExpired(): void ); } + /** + * Whether a new token is to be kept in the cache only: while access tokens are, for a token issued for no + * authorization code, or for a code kept in the cache only. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + protected function isToBeKeptInCacheOnly(AccessTokenEntity $accessTokenEntity): bool + { + if (!$this->areAccessTokensCacheOnly()) { + return false; + } + + $authCodeId = $accessTokenEntity->getAuthCodeId(); + + return $authCodeId === null || $authCodeId === '' || $this->authCodeRepository->isKeptInCacheOnly($authCodeId); + } + + /** + * A checked store of the marked entry, with the issuance nonce for a token issued for an authorization code. The + * TTL comes from the expiry held in memory, never from a stored one. + * + * @throws \JsonException + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function persistCacheOnly(AccessTokenEntity $accessTokenEntity): void + { + $tokenId = (string)$accessTokenEntity->getIdentifier(); + $entry = [ + ...$accessTokenEntity->getState(), + self::KEY_CACHE_ONLY => true, + ]; + + $authCodeId = $accessTokenEntity->getAuthCodeId(); + + if ($authCodeId !== null && $authCodeId !== '') { + $issuanceNonce = $this->issuanceContext->getNonce(); + + if ($issuanceNonce === null || $issuanceNonce === '') { + throw OidcServerException::serverError( + 'No issuance nonce for an access token issued for an authorization code.', + ); + } + + $entry[self::KEY_CACHE_ONLY_ISSUANCE_NONCE] = $issuanceNonce; + } + + $this->requireProtocolCache()->setChecked( + $entry, + $accessTokenEntity->getExpiryDateTime()->getTimestamp() - time() + + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + $this->getCacheKey($tokenId), + ); + + $this->cacheOnlyResidency[$tokenId] = true; + } + + /** + * Whether a token kept in the cache only is valid: its entry not revoked and, for a token issued for an + * authorization code, the code's entry recording its consumption by the request which issued the token (the same + * issuance nonce) and the code's guard clean. Anything missing fails closed. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + protected function isCacheOnlyEntryValid(array $entry): bool + { + if (($entry['is_revoked'] ?? null) !== false || !array_key_exists('auth_code_id', $entry)) { + return false; + } + + /** @var mixed $authCodeId */ + $authCodeId = $entry['auth_code_id']; + + if ($authCodeId === null || $authCodeId === '') { + return true; + } + + /** @var mixed $issuanceNonce */ + $issuanceNonce = $entry[self::KEY_CACHE_ONLY_ISSUANCE_NONCE] ?? null; + + return is_string($authCodeId) && + is_string($issuanceNonce) && + $this->authCodeRepository->isConsumedWithIssuanceNonce($authCodeId, $issuanceNonce); + } + + /** + * For a token this request did not store: false when it has a row, so that there is nothing to promote. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException When it has none. + * @throws \Exception + */ + protected function resolveCacheOnlyResidency(string $tokenId): bool + { + try { + if ($this->findRow($tokenId) !== null) { + return $this->cacheOnlyResidency[$tokenId] = false; + } + } catch (Throwable $exception) { + throw OidcServerException::serverError('Could not look up an access token.', $exception); + } + + throw OidcServerException::serverError( + 'The access token for which a refresh token is issued was not stored by this request, and has no ' . + 'database row.', + ); + } + + /** + * @throws \Exception + */ + protected function findRow(string $tokenId): ?array + { + $stmt = $this->database->read( + "SELECT * FROM {$this->getTableName()} WHERE id = :id", + [ + 'id' => $tokenId, + ], + ); + + $rows = $stmt->fetchAll(); + + if (empty($rows)) { + return null; + } + + /** @var array $row */ + $row = current($rows); + + return $row; + } + + /** + * @throws \Exception + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function hydrate(array $data): AccessTokenEntity + { + $data['client'] = $this->clientRepository->findById((string)$data['client_id']); + + return $this->accessTokenEntityFactory->fromState($data); + } + + /** + * @throws \Exception + */ + protected function accessTokenMaxSeconds(): int + { + return $this->helpers->dateTime()->getMaxSecondsOf($this->moduleConfig->getAccessTokenDuration()); + } + + /** + * @throws \JsonException + */ + protected function insert(AccessTokenEntityInterface $accessTokenEntity): void + { + $stmt = sprintf( + "INSERT INTO %s (id, scopes, expires_at, user_id, client_id, is_revoked, auth_code_id, requested_claims) " + . "VALUES (:id, :scopes, :expires_at, :user_id, :client_id, :is_revoked, :auth_code_id, :requested_claims)", + $this->getTableName(), + ); + + $this->database->write( + $stmt, + $this->preparePdoState($accessTokenEntity->getState()), + ); + } + /** * @throws \JsonException */ @@ -251,13 +573,16 @@ private function update(AccessTokenEntity $accessTokenEntity): void $this->preparePdoState($accessTokenEntity->getState()), ); - $this->protocolCache?->set( - $accessTokenEntity->getState(), - $this->helpers->dateTime()->getSecondsToExpirationTime( - $accessTokenEntity->getExpiryDateTime()->getTimestamp(), - ), - $this->getCacheKey((string)$accessTokenEntity->getIdentifier()), - ); + // While access tokens are kept in the cache only, a token with a row is not cached. + if (!$this->areAccessTokensCacheOnly()) { + $this->protocolCache?->set( + $accessTokenEntity->getState(), + $this->helpers->dateTime()->getSecondsToExpirationTime( + $accessTokenEntity->getExpiryDateTime()->getTimestamp(), + ), + $this->getCacheKey((string)$accessTokenEntity->getIdentifier()), + ); + } } protected function preparePdoState(array $state): array diff --git a/src/Repositories/AuthCodeRepository.php b/src/Repositories/AuthCodeRepository.php index a4fe33019..e47c29feb 100644 --- a/src/Repositories/AuthCodeRepository.php +++ b/src/Repositories/AuthCodeRepository.php @@ -17,6 +17,7 @@ namespace SimpleSAML\Module\oidc\Repositories; use League\OAuth2\Server\Entities\AuthCodeEntityInterface as OAuth2AuthCodeEntityInterface; +use League\OAuth2\Server\Exception\OAuthServerException; use PDO; use RuntimeException; use SimpleSAML\Database; @@ -28,12 +29,44 @@ use SimpleSAML\Module\oidc\Helpers; use SimpleSAML\Module\oidc\ModuleConfig; use SimpleSAML\Module\oidc\Repositories\Interfaces\AuthCodeRepositoryInterface; +use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; +use SimpleSAML\Module\oidc\Utils\ConsumptionGate; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; use SimpleSAML\Module\oidc\Utils\ProtocolCache; +use Throwable; +/** + * Authorization codes, in the database (the default) or, with ProtocolArtifactEnum::AuthorizationCode in + * ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS, in the protocol cache only. + * + * A code kept in the cache only has two cache keys, each written by one party only: + * - its entry, the code's state with the cache-only marker and a status: written "issued" at issuance, and + * "consumed", with the issuance nonce of the request which consumed it, only by the request which claimed the code + * through the consumption gate; + * - its guard: "clean" at issuance, and "replayed" only once a replay was found. + * Every write is checked (written, then read back), and a code proceeds only on positive evidence (an issued entry + * and a clean guard), so a lost key fails closed. + */ class AuthCodeRepository extends AbstractDatabaseRepository implements AuthCodeRepositoryInterface { final public const string TABLE_NAME = 'oidc_auth_code'; + final public const string KEY_CACHE_ONLY_STATUS = 'cache_only_status'; + final public const string STATUS_ISSUED = 'issued'; + final public const string STATUS_CONSUMED = 'consumed'; + + final public const string GUARD_CLEAN = 'clean'; + final public const string GUARD_REPLAYED = 'replayed'; + + protected const string GUARD_KEY_ELEMENT = 'guard'; + + /** + * The codes this request persisted or looked up, and whether each is kept in the cache only. It decides which + * write path a code takes, never what a lookup answers. + * + * @var array + */ + protected array $cacheOnlyResidency = []; public function __construct( ModuleConfig $moduleConfig, @@ -42,6 +75,8 @@ public function __construct( protected readonly ClientRepository $clientRepository, protected readonly AuthCodeEntityFactory $authCodeEntityFactory, protected readonly Helpers $helpers, + protected readonly IssuanceContext $issuanceContext, + protected readonly ?ConsumptionGate $consumptionGate, ) { parent::__construct($moduleConfig, $database, $protocolCache); } @@ -51,6 +86,22 @@ public function getTableName(): string return $this->database->applyPrefix(self::TABLE_NAME); } + /** + * @return non-empty-list + */ + public function getEntryCacheKeyElements(string $codeId): array + { + return [$this->getCacheKey($codeId)]; + } + + /** + * @return non-empty-list + */ + public function getGuardCacheKeyElements(string $codeId): array + { + return [$this->getCacheKey($codeId), self::GUARD_KEY_ELEMENT]; + } + /** * @return \SimpleSAML\Module\oidc\Entities\Interfaces\AuthCodeEntityInterface */ @@ -63,6 +114,7 @@ public function getNewAuthCode(): AuthCodeEntityInterface * {@inheritdoc} * @throws \JsonException * @throws \SimpleSAML\Error\Error + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException */ public function persistNewAuthCode(OAuth2AuthCodeEntityInterface $authCodeEntity): void { @@ -70,6 +122,11 @@ public function persistNewAuthCode(OAuth2AuthCodeEntityInterface $authCodeEntity throw new Error('Invalid AuthCodeEntity'); } + if ($this->isCacheOnly()) { + $this->persistCacheOnly($authCodeEntity); + return; + } + $stmt = sprintf( "INSERT INTO %s (id, scopes, expires_at, user_id, client_id, is_revoked, redirect_uri, nonce) " . "VALUES (:id, :scopes, :expires_at, :user_id, :client_id, :is_revoked, :redirect_uri, :nonce)", @@ -81,6 +138,8 @@ public function persistNewAuthCode(OAuth2AuthCodeEntityInterface $authCodeEntity $this->preparePdoState($authCodeEntity->getState()), ); + $this->cacheOnlyResidency[(string)$authCodeEntity->getIdentifier()] = false; + $this->protocolCache?->set( $authCodeEntity->getState(), $this->helpers->dateTime()->getSecondsToExpirationTime( @@ -92,74 +151,246 @@ public function persistNewAuthCode(OAuth2AuthCodeEntityInterface $authCodeEntity /** * Find Auth Code by id. + * + * An entry kept in the cache only is trusted from the cache. While codes are kept in the cache only, a cached + * copy of a code with a database row is not trusted (such copies are no longer kept current), and reads write + * nothing. A cache hit is never written back. + * * @throws \Exception */ public function findById(string $codeId): ?AuthCodeEntityInterface { - /** @var ?array $data */ - $data = $this->protocolCache?->get(null, $this->getCacheKey($codeId)); - - if (!is_array($data)) { - $stmt = $this->database->read( - "SELECT * FROM {$this->getTableName()} WHERE id = :id", - [ - 'id' => $codeId, - ], - ); + $isCacheOnly = $this->isCacheOnly(); - if (empty($rows = $stmt->fetchAll())) { - return null; - } + /** @var mixed $data */ + $data = $this->protocolCache?->get(null, ...$this->getEntryCacheKeyElements($codeId)); + if ($this->isCacheOnlyEntry($data)) { /** @var array $data */ - $data = current($rows); + $this->cacheOnlyResidency[$codeId] = true; + return $this->hydrate($data); } - $data['client'] = $this->clientRepository->findById((string)$data['client_id']); + if (is_array($data) && !$isCacheOnly) { + $this->cacheOnlyResidency[$codeId] = false; + return $this->hydrate($data); + } - $authCodeEntity = $this->authCodeEntityFactory->fromState($data); + $row = $this->findRow($codeId); - $this->protocolCache?->set( - $authCodeEntity->getState(), - $this->helpers->dateTime()->getSecondsToExpirationTime( - $authCodeEntity->getExpiryDateTime()->getTimestamp(), - ), - $this->getCacheKey((string)$authCodeEntity->getIdentifier()), - ); + if ($row === null) { + return null; + } + + $this->cacheOnlyResidency[$codeId] = false; + $authCodeEntity = $this->hydrate($row); + + if (!$isCacheOnly) { + $this->protocolCache?->set( + $authCodeEntity->getState(), + $this->helpers->dateTime()->getSecondsToExpirationTime( + $authCodeEntity->getExpiryDateTime()->getTimestamp(), + ), + $this->getCacheKey((string)$authCodeEntity->getIdentifier()), + ); + } return $authCodeEntity; } /** * {@inheritdoc} + * + * For a code kept in the cache only: claims the code and records it consumed with no issuance nonce, so that no + * access token kept in the cache only is valid for it. A code another request claimed first is left as it is. + * * @throws \Exception * @throws \JsonException */ public function revokeAuthCode($codeId): void { - $authCode = $this->findById($codeId); + if (!$this->isCacheOnly()) { + $authCode = $this->findById($codeId); + + if (!$authCode instanceof AuthCodeEntity) { + throw new RuntimeException("AuthCode not found: $codeId"); + } - if (!$authCode instanceof AuthCodeEntity) { + $authCode->revoke(); + $this->update($authCode); + return; + } + + $isCacheOnlyCode = $this->resolveCacheOnlyResidency($codeId); + + if ($isCacheOnlyCode === null) { throw new RuntimeException("AuthCode not found: $codeId"); } - $authCode->revoke(); - $this->update($authCode); + if ($isCacheOnlyCode === false) { + $this->consumeDatabaseBacked($codeId); + return; + } + + if (!$this->requireConsumptionGate()->claim($codeId)) { + return; + } + + [$entry] = $this->readCacheOnlyState($codeId); + + if ($entry === null) { + throw OidcServerException::serverError('The authorization code\'s cache entry was lost.'); + } + + if (($entry[self::KEY_CACHE_ONLY_STATUS] ?? null) !== self::STATUS_ISSUED) { + return; + } + + $consumedEntry = $this->consumedEntryFrom($entry); + unset($consumedEntry[self::KEY_CACHE_ONLY_ISSUANCE_NONCE]); + + $this->requireProtocolCache()->setChecked( + $consumedEntry, + $this->authCodeMaxSeconds() + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + ...$this->getEntryCacheKeyElements($codeId), + ); } /** * {@inheritdoc} + * + * For a code kept in the cache only, true means the code was used or replayed, false that it was issued and is + * unused; partial evidence (its entry or its guard gone) is refused with invalid_grant, without cleanup. + * + * @throws \League\OAuth2\Server\Exception\OAuthServerException invalid_grant for a code not found. * @throws \Exception */ public function isAuthCodeRevoked($codeId): bool { - $authCode = $this->findById($codeId); + if (!$this->isCacheOnly()) { + $authCode = $this->findById($codeId); - if (!$authCode instanceof AuthCodeEntity) { - throw new RuntimeException("AuthCode not found: $codeId"); + if (!$authCode instanceof AuthCodeEntity) { + throw OAuthServerException::invalidGrant('Authorization code is not known'); + } + + return $authCode->isRevoked(); } - return $authCode->isRevoked(); + [$entry, $guard] = $this->readCacheOnlyState($codeId); + + if ($entry !== null || $guard !== null) { + $this->cacheOnlyResidency[$codeId] = true; + + if ($this->showsUse($entry, $guard)) { + return true; + } + + if (($entry[self::KEY_CACHE_ONLY_STATUS] ?? null) === self::STATUS_ISSUED && $guard === self::GUARD_CLEAN) { + return false; + } + + throw OAuthServerException::invalidGrant('Authorization code is not valid'); + } + + $row = $this->findRow($codeId); + + if ($row === null) { + throw OAuthServerException::invalidGrant('Authorization code is not known'); + } + + $this->cacheOnlyResidency[$codeId] = false; + + return (bool)$row['is_revoked']; + } + + /** + * {@inheritdoc} + * + * With codes in the database (the default), the code is revoked as before, and this answers true. + * + * @throws \Exception + */ + public function consumeAuthCode(string $codeId, int $deadline, ?int $accessTokenExpiresAt = null): bool + { + if (!$this->isCacheOnly()) { + $this->revokeAuthCode($codeId); + return true; + } + + $isCacheOnlyCode = $this->resolveCacheOnlyResidency($codeId); + + if ($isCacheOnlyCode === null) { + throw OAuthServerException::invalidGrant('Authorization code is not known'); + } + + if ($isCacheOnlyCode === false) { + return $this->consumeDatabaseBacked($codeId); + } + + return $this->consumeCacheOnly($codeId, $deadline, $accessTokenExpiresAt); + } + + /** + * {@inheritdoc} + */ + public function recordAuthCodeReplay(string $codeId, int $deadline): void + { + if (!$this->isCacheOnly() || $this->resolveCacheOnlyResidency($codeId) !== true) { + return; + } + + $this->requireProtocolCache()->setChecked( + self::GUARD_REPLAYED, + max($deadline - time(), 0) + $this->accessTokenMaxSeconds() + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + ...$this->getGuardCacheKeyElements($codeId), + ); + } + + /** + * Whether the code is kept in the protocol cache only, for an access token issued for it to follow the code's + * storage: from this request's memory, else from the code's cache keys. A code found in neither is taken to have a + * database row, and its token is then stored in the database. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function isKeptInCacheOnly(string $codeId): bool + { + if (array_key_exists($codeId, $this->cacheOnlyResidency)) { + return $this->cacheOnlyResidency[$codeId]; + } + + if (!$this->isCacheOnly()) { + return false; + } + + [$entry, $guard] = $this->readCacheOnlyState($codeId); + + if ($entry === null && $guard === null) { + return false; + } + + return $this->cacheOnlyResidency[$codeId] = true; + } + + /** + * The code's part of the validity of an access token kept in the cache only, issued for the code with the given + * issuance nonce: the code's entry consumed by the request with that nonce, and its guard clean. Both keys are read + * raw, together; a key missing, from an eviction or a failed read, answers false. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function isConsumedWithIssuanceNonce(string $codeId, string $issuanceNonce): bool + { + if ($issuanceNonce === '') { + return false; + } + + [$entry, $guard] = $this->readCacheOnlyState($codeId); + + return $this->showsOwnConsumption($entry, $guard, $issuanceNonce); } /** @@ -176,6 +407,332 @@ public function removeExpired(): void ); } + protected function isCacheOnly(): bool + { + return $this->areAuthCodesCacheOnly(); + } + + /** + * The guard is written first, so that an entry never exists without it. The TTLs come from the expiry held in + * memory, never from a stored one. + * + * @throws \JsonException + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + * @throws \Exception + */ + protected function persistCacheOnly(AuthCodeEntity $authCodeEntity): void + { + $protocolCache = $this->requireProtocolCache(); + $codeId = (string)$authCodeEntity->getIdentifier(); + $deadline = $authCodeEntity->getExpiryDateTime()->getTimestamp(); + $now = time(); + + $protocolCache->setChecked( + self::GUARD_CLEAN, + $deadline - $now + $this->accessTokenMaxSeconds() + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + ...$this->getGuardCacheKeyElements($codeId), + ); + + $protocolCache->setChecked( + [ + ...$authCodeEntity->getState(), + self::KEY_CACHE_ONLY => true, + self::KEY_CACHE_ONLY_STATUS => self::STATUS_ISSUED, + ], + $deadline - $now + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + ...$this->getEntryCacheKeyElements($codeId), + ); + + $this->cacheOnlyResidency[$codeId] = true; + } + + /** + * Consumes a code kept in the cache only, in five steps: + * 1. its deadline: once passed, evidence of an earlier use answers a replay, anything else invalid_grant; + * 2. the claim through the gate: lost answers a replay; + * 3. its entry and guard read again: a use found answers a replay, a lost entry or guard server_error, and the + * deadline passed in the meantime invalid_grant (the claim then spends the expired code); + * 4. the consumed entry written with this request's issuance nonce; a write which can not be confirmed answers a + * replay if another request's consumption or a replay is found instead, goes on if this request's own + * consumption and a clean guard are found (only the read-back missed), else server_error; + * 5. both read once more: a replay recorded in the meantime, or a consumption by another request, answers a + * replay, so that the caller revokes the tokens rather than returning them; anything but this request's + * consumed entry and a clean guard is server_error. + * + * @throws \League\OAuth2\Server\Exception\OAuthServerException + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + * @throws \Exception + */ + protected function consumeCacheOnly(string $codeId, int $deadline, ?int $accessTokenExpiresAt): bool + { + $protocolCache = $this->requireProtocolCache(); + $consumptionGate = $this->requireConsumptionGate(); + $issuanceNonce = $this->issuanceContext->getNonce(); + + if ($issuanceNonce === null || $issuanceNonce === '') { + throw OidcServerException::serverError('No issuance nonce for consuming the authorization code.'); + } + + if (time() > $deadline) { + [$entry, $guard] = $this->readCacheOnlyState($codeId); + + if ($this->showsUse($entry, $guard)) { + return false; + } + + throw OAuthServerException::invalidGrant('Authorization code has expired'); + } + + if (!$consumptionGate->claim($codeId)) { + return false; + } + + [$entry, $guard] = $this->readCacheOnlyState($codeId); + + if ($this->showsUse($entry, $guard)) { + return false; + } + + if ( + $entry === null || + ($entry[self::KEY_CACHE_ONLY_STATUS] ?? null) !== self::STATUS_ISSUED || + $guard !== self::GUARD_CLEAN + ) { + throw OidcServerException::serverError( + 'The authorization code\'s cache entries were lost after it was claimed.', + ); + } + + if (time() > $deadline) { + throw OAuthServerException::invalidGrant('Authorization code has expired'); + } + + $consumedEntry = $this->consumedEntryFrom($entry); + $consumedEntry[self::KEY_CACHE_ONLY_ISSUANCE_NONCE] = $issuanceNonce; + + try { + $protocolCache->setChecked( + $consumedEntry, + max($deadline, $accessTokenExpiresAt ?? $deadline) - time() + + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + ...$this->getEntryCacheKeyElements($codeId), + ); + } catch (OidcServerException $exception) { + // Another request's consumption written over this one before its read-back (its lock was lost), or a + // replay recorded meanwhile, is a replay. This request's own consumption found, with a clean guard, means + // the write landed and only its read-back missed: confirmed, and checked once more below. Anything else + // leaves the outcome unknown. + [$entry, $guard] = $this->readCacheOnlyState($codeId); + + if ($this->showsUseByAnother($entry, $guard, $issuanceNonce)) { + return false; + } + + if (!$this->showsOwnConsumption($entry, $guard, $issuanceNonce)) { + throw $exception; + } + } + + [$entry, $guard] = $this->readCacheOnlyState($codeId); + + if ($this->showsUseByAnother($entry, $guard, $issuanceNonce)) { + return false; + } + + if ( + $guard !== self::GUARD_CLEAN || + ($entry[self::KEY_CACHE_ONLY_STATUS] ?? null) !== self::STATUS_CONSUMED + ) { + throw OidcServerException::serverError( + 'The authorization code\'s cache entries were lost while the code was consumed.', + ); + } + + return true; + } + + /** + * A code with a database row, issued before codes were kept in the cache only, is consumed by a conditional + * UPDATE: the row is the gate, and only the request which changed it consumed the code. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function consumeDatabaseBacked(string $codeId): bool + { + try { + $affectedRows = $this->database->write( + "UPDATE {$this->getTableName()} SET is_revoked = :is_revoked " . + "WHERE id = :id AND is_revoked = :was_revoked", + [ + 'is_revoked' => [true, PDO::PARAM_BOOL], + 'id' => $codeId, + 'was_revoked' => [false, PDO::PARAM_BOOL], + ], + ); + } catch (Throwable $exception) { + throw OidcServerException::serverError('Could not consume the authorization code.', $exception); + } + + return is_int($affectedRows) && $affectedRows > 0; + } + + /** + * Whether the code is kept in the cache only: from this request's memory, else from its cache keys, else from + * its database row. Null when it is found nowhere. + * + * @throws \Exception + */ + protected function resolveCacheOnlyResidency(string $codeId): ?bool + { + if (array_key_exists($codeId, $this->cacheOnlyResidency)) { + return $this->cacheOnlyResidency[$codeId]; + } + + [$entry, $guard] = $this->readCacheOnlyState($codeId); + + if ($entry !== null || $guard !== null) { + return $this->cacheOnlyResidency[$codeId] = true; + } + + if ($this->findRow($codeId) !== null) { + return $this->cacheOnlyResidency[$codeId] = false; + } + + return null; + } + + /** + * The entry and the guard of a code kept in the cache only, read together. A cached copy without the marker, + * or a value of another shape, counts as missing. + * + * @return array{0: array|null, 1: string|null} + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + protected function readCacheOnlyState(string $codeId): array + { + $values = $this->requireProtocolCache()->getMany([ + 'entry' => $this->getEntryCacheKeyElements($codeId), + 'guard' => $this->getGuardCacheKeyElements($codeId), + ]); + + /** @var array|null $entry */ + $entry = $this->isCacheOnlyEntry($values['entry']) ? $values['entry'] : null; + $guard = in_array($values['guard'], [self::GUARD_CLEAN, self::GUARD_REPLAYED], true) ? + $values['guard'] : null; + + /** @var array{0: array|null, 1: string|null} */ + return [$entry, $guard]; + } + + protected function showsUse(?array $entry, ?string $guard): bool + { + return ($entry[self::KEY_CACHE_ONLY_STATUS] ?? null) === self::STATUS_CONSUMED || + $guard === self::GUARD_REPLAYED; + } + + /** + * A replay recorded, or a consumption by a request other than the one with this issuance nonce. + */ + protected function showsUseByAnother(?array $entry, ?string $guard, string $issuanceNonce): bool + { + if ($guard === self::GUARD_REPLAYED) { + return true; + } + + if (($entry[self::KEY_CACHE_ONLY_STATUS] ?? null) !== self::STATUS_CONSUMED) { + return false; + } + + /** @var mixed $entryNonce */ + $entryNonce = $entry[self::KEY_CACHE_ONLY_ISSUANCE_NONCE] ?? null; + + return !is_string($entryNonce) || !hash_equals($issuanceNonce, $entryNonce); + } + + /** + * The code consumed by the request with this issuance nonce, and its guard clean. + */ + protected function showsOwnConsumption(?array $entry, ?string $guard, string $issuanceNonce): bool + { + if ($guard !== self::GUARD_CLEAN || ($entry[self::KEY_CACHE_ONLY_STATUS] ?? null) !== self::STATUS_CONSUMED) { + return false; + } + + /** @var mixed $entryNonce */ + $entryNonce = $entry[self::KEY_CACHE_ONLY_ISSUANCE_NONCE] ?? null; + + return $issuanceNonce !== '' && is_string($entryNonce) && hash_equals($entryNonce, $issuanceNonce); + } + + protected function consumedEntryFrom(array $entry): array + { + $entry['is_revoked'] = true; + $entry[self::KEY_CACHE_ONLY_STATUS] = self::STATUS_CONSUMED; + + return $entry; + } + + /** + * @throws \Exception + */ + protected function findRow(string $codeId): ?array + { + $stmt = $this->database->read( + "SELECT * FROM {$this->getTableName()} WHERE id = :id", + [ + 'id' => $codeId, + ], + ); + + $rows = $stmt->fetchAll(); + + if (empty($rows)) { + return null; + } + + /** @var array $row */ + $row = current($rows); + + return $row; + } + + /** + * @throws \Exception + */ + protected function hydrate(array $data): AuthCodeEntity + { + $data['client'] = $this->clientRepository->findById((string)$data['client_id']); + + return $this->authCodeEntityFactory->fromState($data); + } + + /** + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function requireConsumptionGate(): ConsumptionGate + { + return $this->consumptionGate ?? throw OidcServerException::serverError( + 'Authorization codes are kept in the cache only, but no lock store is configured.', + ); + } + + /** + * @throws \Exception + */ + protected function accessTokenMaxSeconds(): int + { + return $this->helpers->dateTime()->getMaxSecondsOf($this->moduleConfig->getAccessTokenDuration()); + } + + /** + * @throws \Exception + */ + protected function authCodeMaxSeconds(): int + { + return $this->helpers->dateTime()->getMaxSecondsOf($this->moduleConfig->getAuthCodeDuration()); + } + /** * @throws \JsonException */ diff --git a/src/Repositories/Interfaces/AccessTokenRepositoryInterface.php b/src/Repositories/Interfaces/AccessTokenRepositoryInterface.php index 18453a203..19d9bb804 100644 --- a/src/Repositories/Interfaces/AccessTokenRepositoryInterface.php +++ b/src/Repositories/Interfaces/AccessTokenRepositoryInterface.php @@ -15,6 +15,14 @@ interface AccessTokenRepositoryInterface extends OAuth2AccessTokenRepositoryInte */ public function revokeByAuthCodeId(string $authCodeId): void; + /** + * Revoke every access token associated with the given auth code ID, for a replay of a code kept in the protocol + * cache only: on the primary database, and in each cached copy, every write checked. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + public function revokeAllByAuthCodeId(string $authCodeId): void; + /** * Create a new access token * diff --git a/src/Repositories/Interfaces/AuthCodeRepositoryInterface.php b/src/Repositories/Interfaces/AuthCodeRepositoryInterface.php index bbe99bdb0..e71ac0d07 100644 --- a/src/Repositories/Interfaces/AuthCodeRepositoryInterface.php +++ b/src/Repositories/Interfaces/AuthCodeRepositoryInterface.php @@ -13,4 +13,26 @@ interface AuthCodeRepositoryInterface extends OAuth2AuthCodeRepositoryInterface * Creates a new AuthCode */ public function getNewAuthCode(): AuthCodeEntityInterface; + + /** + * Marks the code used, as the last step of its redemption. Answers true when this request consumed it, and + * false when the code had been used or reused before, which the caller handles as a reuse (RFC 6749 section + * 4.1.2). + * + * @param int $deadline The code's expiry as a Unix timestamp, as the code's payload carries it. + * @param int|null $accessTokenExpiresAt The expiry of the access token this request issued, as a Unix timestamp. + * @throws \League\OAuth2\Server\Exception\OAuthServerException invalid_grant when the code expired or was found + * reused on the way; server_error when its state could not be read or written, in which case the request issues + * no credentials. + */ + public function consumeAuthCode(string $codeId, int $deadline, ?int $accessTokenExpiresAt = null): bool; + + /** + * Records a replay of a code kept in the protocol cache only, which invalidates the access tokens kept in the + * cache only for it. Does nothing for a code with a database row. + * + * @param int $deadline The code's expiry as a Unix timestamp, as the code's payload carries it. + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException When the record can not be confirmed. + */ + public function recordAuthCodeReplay(string $codeId, int $deadline): void; } diff --git a/src/Repositories/Interfaces/RefreshTokenRepositoryInterface.php b/src/Repositories/Interfaces/RefreshTokenRepositoryInterface.php index cf30eb485..c3708577b 100644 --- a/src/Repositories/Interfaces/RefreshTokenRepositoryInterface.php +++ b/src/Repositories/Interfaces/RefreshTokenRepositoryInterface.php @@ -14,6 +14,14 @@ interface RefreshTokenRepositoryInterface extends OAuth2RefreshTokenRepositoryIn */ public function revokeByAuthCodeId(string $authCodeId): void; + /** + * Revoke every refresh token associated with the given auth code ID, for a replay of a code kept in the protocol + * cache only: on the primary database, and in each cached copy, every write checked. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + public function revokeAllByAuthCodeId(string $authCodeId): void; + /** * Creates a new refresh token */ diff --git a/src/Repositories/RefreshTokenRepository.php b/src/Repositories/RefreshTokenRepository.php index 638768436..18bb781fd 100644 --- a/src/Repositories/RefreshTokenRepository.php +++ b/src/Repositories/RefreshTokenRepository.php @@ -64,6 +64,10 @@ public function getNewRefreshToken(): RefreshTokenEntityInterface /** * {@inheritdoc} + * + * While access tokens are kept in the protocol cache only, the refresh token's access token is given its database + * row first (AccessTokenRepository::ensureStoredInDatabase()), and the refresh token is not cached. + * * @throws \League\OAuth2\Server\Exception\OAuthServerException */ public function persistNewRefreshToken(OAuth2RefreshTokenEntityInterface $refreshTokenEntity): void @@ -72,6 +76,8 @@ public function persistNewRefreshToken(OAuth2RefreshTokenEntityInterface $refres throw OAuthServerException::invalidRefreshToken(); } + $this->accessTokenRepository->ensureStoredInDatabase($refreshTokenEntity->getAccessToken()); + $stmt = sprintf( "INSERT INTO %s (id, expires_at, access_token_id, is_revoked, auth_code_id) " . "VALUES (:id, :expires_at, :access_token_id, :is_revoked, :auth_code_id)", @@ -83,24 +89,33 @@ public function persistNewRefreshToken(OAuth2RefreshTokenEntityInterface $refres $this->preparePdoState($refreshTokenEntity->getState()), ); - $this->protocolCache?->set( - $refreshTokenEntity->getState(), - $this->helpers->dateTime()->getSecondsToExpirationTime( - $refreshTokenEntity->getExpiryDateTime()->getTimestamp(), - ), - $this->getCacheKey((string)$refreshTokenEntity->getIdentifier()), - ); + if (!$this->areAccessTokensCacheOnly()) { + $this->protocolCache?->set( + $refreshTokenEntity->getState(), + $this->helpers->dateTime()->getSecondsToExpirationTime( + $refreshTokenEntity->getExpiryDateTime()->getTimestamp(), + ), + $this->getCacheKey((string)$refreshTokenEntity->getIdentifier()), + ); + } } /** * Find Refresh Token by id. + * + * While access tokens are kept in the protocol cache only, refresh tokens are read from the database, and so is + * their access token (which always has a row): cached copies are no longer kept current. + * * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException * @throws \Exception */ public function findById(string $tokenId): ?RefreshTokenEntityInterface { + $areAccessTokensCacheOnly = $this->areAccessTokensCacheOnly(); + /** @var ?array $data */ - $data = $this->protocolCache?->get(null, $this->getCacheKey($tokenId)); + $data = $areAccessTokensCacheOnly ? null : $this->protocolCache?->get(null, $this->getCacheKey($tokenId)); + $isCacheHit = is_array($data); if (!is_array($data)) { $stmt = $this->database->read( @@ -118,17 +133,24 @@ public function findById(string $tokenId): ?RefreshTokenEntityInterface $data = current($rows); } - $data['access_token'] = $this->accessTokenRepository->findById((string)$data['access_token_id']); + $data['access_token'] = $areAccessTokensCacheOnly ? + $this->accessTokenRepository->findByIdInDatabase((string)$data['access_token_id']) : + $this->accessTokenRepository->findById((string)$data['access_token_id']); $refreshTokenEntity = $this->refreshTokenEntityFactory->fromState($data); - $this->protocolCache?->set( - $refreshTokenEntity->getState(), - $this->helpers->dateTime()->getSecondsToExpirationTime( - $refreshTokenEntity->getExpiryDateTime()->getTimestamp(), - ), - $this->getCacheKey((string)$refreshTokenEntity->getIdentifier()), - ); + // A cache hit is not written back: a concurrent revocation written in the meantime would be overwritten. With + // codes or access tokens kept in the cache only, a row found on a miss is not cached either (see + // areAuthCodesCacheOnly() and areAccessTokensCacheOnly()). + if (!$isCacheHit && !$this->areAuthCodesCacheOnly() && !$areAccessTokensCacheOnly) { + $this->protocolCache?->set( + $refreshTokenEntity->getState(), + $this->helpers->dateTime()->getSecondsToExpirationTime( + $refreshTokenEntity->getExpiryDateTime()->getTimestamp(), + ), + $this->getCacheKey((string)$refreshTokenEntity->getIdentifier()), + ); + } return $refreshTokenEntity; } @@ -150,10 +172,21 @@ public function revokeRefreshToken($tokenId): void } /** + * {@inheritdoc} + * + * While access tokens are kept in the cache only, one UPDATE on the primary database (revokeAllByAuthCodeId()), + * which also reaches rows a lagging secondary does not have yet. + * * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + * @throws \Exception */ public function revokeByAuthCodeId(string $authCodeId): void { + if ($this->areAccessTokensCacheOnly()) { + $this->revokeAllByAuthCodeId($authCodeId); + return; + } + $stmt = $this->database->read( "SELECT id FROM {$this->getTableName()} WHERE auth_code_id = :auth_code_id", ['auth_code_id' => $authCodeId], @@ -164,6 +197,19 @@ public function revokeByAuthCodeId(string $authCodeId): void } } + /** + * {@inheritdoc} + * @throws \Exception + */ + public function revokeAllByAuthCodeId(string $authCodeId): void + { + $this->revokeAllByAuthCodeIdOnPrimary( + $authCodeId, + $this->helpers->dateTime()->getMaxSecondsOf($this->moduleConfig->getRefreshTokenDuration()) + + ModuleConfig::CACHE_ONLY_TTL_MARGIN_SECONDS, + ); + } + /** * {@inheritdoc} * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException @@ -206,13 +252,16 @@ private function update(RefreshTokenEntityInterface $refreshTokenEntity): void $this->preparePdoState($refreshTokenEntity->getState()), ); - $this->protocolCache?->set( - $refreshTokenEntity->getState(), - $this->helpers->dateTime()->getSecondsToExpirationTime( - $refreshTokenEntity->getExpiryDateTime()->getTimestamp(), - ), - $this->getCacheKey($refreshTokenEntity->getIdentifier()), - ); + // While access tokens are kept in the cache only, refresh tokens are not cached. + if (!$this->areAccessTokensCacheOnly()) { + $this->protocolCache?->set( + $refreshTokenEntity->getState(), + $this->helpers->dateTime()->getSecondsToExpirationTime( + $refreshTokenEntity->getExpiryDateTime()->getTimestamp(), + ), + $this->getCacheKey($refreshTokenEntity->getIdentifier()), + ); + } } protected function preparePdoState(array $state): array diff --git a/src/Repositories/UserRepository.php b/src/Repositories/UserRepository.php index faf7da06c..800bcf248 100644 --- a/src/Repositories/UserRepository.php +++ b/src/Repositories/UserRepository.php @@ -157,4 +157,78 @@ public function update(UserEntity $userEntity, ?DateTimeImmutable $updatedAt = n $this->getCacheKey($userEntity->getIdentifier()), ); } + + /** + * Updates the user, as every login did before, unless both its database row and its protocol cache entry hold + * its claims already: then nothing is written, so a login whose claims have not changed leaves updated_at as it + * is and does not renew the cache entry. Claims are compared as stored, as JSON strings, with the claims as the + * entity would store them. Without a protocol cache the row alone decides. + * + * The row decides because the cache entry can differ from it (a cache write that failed after an UPDATE, caches + * local to each node, a lookup refilling the cache from an older row), and a write skipped on the entry's word + * would leave the row outdated. The entry must agree too. Another login's update writes the row and then the + * entry, so this login skips only if it read each of them before that update wrote it; the update finishes after + * it, and its claims stand in both places. Otherwise one of the reads shows the change and this login updates as + * well, so its own claims stand in both, as before. Nothing is ever written to the cache from the row. + * + * The row is read with read(), as lookups are, so a database secondary that has not caught up with a change + * written moments before shows the earlier claims; a login bringing them back then writes nothing if the cache + * entry does not show the change either: no cache, caches local to each node, a cache write that failed, or an + * entry refilled from such a secondary or from a row read before the change. The row then keeps the change while + * the entry holds the earlier claims, until it expires or a login writes. A row or a cache entry that can not be + * read, a missing row and a missing cache entry all lead to the update. + * + * @return bool Whether the user was updated. + * @throws \Exception + */ + public function updateIfClaimsChanged(UserEntity $userEntity): bool + { + /** @var string|false $claims The JSON update() writes; false for claims json_encode() refuses. */ + $claims = $userEntity->getState()['claims']; + + try { + $stmt = $this->database->read( + "SELECT * FROM {$this->getTableName()} WHERE id = :id", + [ + 'id' => $userEntity->getIdentifier(), + ], + ); + /** @var array|false $row */ + $row = current($stmt->fetchAll()); + } catch (Exception) { + // A secondary that is down, or a standby that cancelled the query. + $row = false; + } + + if ( + is_array($row) && + ($row['claims'] ?? null) === $claims && + $this->isCachedWithClaims($userEntity, $claims) + ) { + return false; + } + + $this->update($userEntity); + return true; + } + + /** + * Whether the user's protocol cache entry holds these claims, as stored; true when there is no protocol cache. + */ + protected function isCachedWithClaims(UserEntity $userEntity, string|false $claims): bool + { + if ($this->protocolCache === null) { + return true; + } + + try { + /** @var ?array $cachedState */ + $cachedState = $this->protocolCache->get(null, $this->getCacheKey($userEntity->getIdentifier())); + } catch (Exception) { + // Counts as a miss, so the user is updated, as when the row can not be read. + return false; + } + + return is_array($cachedState) && ($cachedState['claims'] ?? null) === $claims; + } } diff --git a/src/Server/Grants/AuthCodeGrant.php b/src/Server/Grants/AuthCodeGrant.php index 8b8cf00c1..ad983ce7c 100644 --- a/src/Server/Grants/AuthCodeGrant.php +++ b/src/Server/Grants/AuthCodeGrant.php @@ -21,6 +21,7 @@ use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface; use LogicException; use Psr\Http\Message\ServerRequestInterface; +use SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum; use SimpleSAML\Module\oidc\Entities\Interfaces\AccessTokenEntityInterface; use SimpleSAML\Module\oidc\Entities\Interfaces\AuthCodeEntityInterface; use SimpleSAML\Module\oidc\Entities\Interfaces\RefreshTokenEntityInterface; @@ -28,6 +29,7 @@ use SimpleSAML\Module\oidc\Factories\Entities\AccessTokenEntityFactory; use SimpleSAML\Module\oidc\Factories\Entities\AuthCodeEntityFactory; use SimpleSAML\Module\oidc\Helpers; +use SimpleSAML\Module\oidc\ModuleConfig; use SimpleSAML\Module\oidc\Repositories\Interfaces\AccessTokenRepositoryInterface; use SimpleSAML\Module\oidc\Repositories\Interfaces\AuthCodeRepositoryInterface; use SimpleSAML\Module\oidc\Repositories\Interfaces\RefreshTokenRepositoryInterface; @@ -59,9 +61,12 @@ use SimpleSAML\Module\oidc\Server\ResponseTypes\Interfaces\NonceResponseTypeInterface; use SimpleSAML\Module\oidc\Server\ResponseTypes\Interfaces\SessionIdResponseTypeInterface; use SimpleSAML\Module\oidc\Server\TokenIssuers\RefreshTokenIssuer; +use SimpleSAML\Module\oidc\Services\LoggerService; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; use SimpleSAML\Module\oidc\Utils\RequestParamsResolver; use SimpleSAML\OpenID\Codebooks\HttpMethodsEnum; use SimpleSAML\OpenID\Codebooks\ParamsEnum; +use Throwable; use function array_key_exists; @@ -165,6 +170,9 @@ public function __construct( protected AuthCodeEntityFactory $authCodeEntityFactory, protected RefreshTokenIssuer $refreshTokenIssuer, protected Helpers $helpers, + protected ModuleConfig $moduleConfig, + protected LoggerService $loggerService, + protected IssuanceContext $issuanceContext, ) { parent::__construct($authCodeRepository, $refreshTokenRepository, $authCodeTTL); @@ -277,7 +285,11 @@ public function completeOidcAuthorizationRequest( 'auth_code_id' => $authCode->getIdentifier(), 'scopes' => $authCode->getScopes(), 'user_id' => $authCode->getUserIdentifier(), - 'expire_time' => (new DateTimeImmutable())->add($this->authCodeTTL)->getTimestamp(), + // With codes kept in the cache only, the code's one deadline, computed before it was persisted: its cache + // entries take their TTLs from it too. Otherwise counted from now, after the persist, as before. + 'expire_time' => $this->isAuthCodeCacheOnly() ? + $authCode->getExpiryDateTime()->getTimestamp() : + (new DateTimeImmutable())->add($this->authCodeTTL)->getTimestamp(), 'code_challenge' => $authorizationRequest->getCodeChallenge(), 'code_challenge_method' => $authorizationRequest->getCodeChallengeMethod(), 'nonce' => $authorizationRequest->getNonce(), @@ -382,6 +394,32 @@ public function respondToAccessTokenRequest( ServerRequestInterface $request, ResponseTypeInterface $responseType, DateInterval $accessTokenTTL, + ): ResponseTypeInterface { + // A fresh issuance nonce for each redemption, which a code kept in the cache only records when this request + // consumes it. + $this->issuanceContext->begin(); + + try { + return $this->respondToAccessTokenRequestWithIssuanceNonce($request, $responseType, $accessTokenTTL); + } finally { + $this->issuanceContext->end(); + } + } + + /** + * With authorization codes kept in the protocol cache only, the code's binding to the client, the redirect URI + * and the PKCE proof are checked first, then the evidence of an earlier use, then the code's expiry: tokens are + * revoked only on a request which proved it holds the code, and a replay after the expiry still revokes them. + * Otherwise the order is the one from before. + * + * @throws \League\OAuth2\Server\Exception\OAuthServerException + * @throws \JsonException + * @throws \Throwable + */ + protected function respondToAccessTokenRequestWithIssuanceNonce( + ServerRequestInterface $request, + ResponseTypeInterface $responseType, + DateInterval $accessTokenTTL, ): ResponseTypeInterface { // OAuth2 implementation //[$clientId] = $this->getClientCredentials($request); @@ -447,11 +485,11 @@ public function respondToAccessTokenRequest( $this->validateAuthorizationCode($authCodePayload, $client, $request); - $scopes = $this->scopeRepository->finalizeScopes( - $this->validateScopes($authCodePayload->scopes), - $this->getIdentifier(), + // With codes kept in the cache only, the scopes come after the replay check: a scope no longer + // supported must not keep a replay from its cleanup. + $scopes = $this->isAuthCodeCacheOnly() ? null : $this->finalizeAuthorizationCodeScopes( + $authCodePayload, $client, - $authCodePayload->user_id, ); } catch (LogicException $e) { throw OAuthServerException::invalidRequest('code', 'Cannot decrypt the authorization code', $e); @@ -506,6 +544,11 @@ public function respondToAccessTokenRequest( } } + if ($scopes === null) { + $this->validateAuthorizationCodeUse($authCodePayload); + $scopes = $this->finalizeAuthorizationCodeScopes($authCodePayload, $client); + } + /** @var array $claims */ $claims = property_exists($authCodePayload, 'claims') ? json_decode(json_encode($authCodePayload->claims, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR) @@ -570,12 +613,117 @@ public function respondToAccessTokenRequest( throw OidcServerException::serverError('Unexpected auth code repository entity type.'); } - // Revoke used auth code - $this->authCodeRepository->revokeAuthCode($authCodePayload->auth_code_id); + // Consume the used auth code. With codes in the database this revokes it, as before. + $isConsumed = $this->authCodeRepository->consumeAuthCode( + $authCodePayload->auth_code_id, + (int)$authCodePayload->expire_time, + $accessToken->getExpiryDateTime()->getTimestamp(), + ); + + if (!$isConsumed) { + // Another request consumed the code first: RFC 6749 section 4.1.2, as on a replay found at the start. + $this->loggerService->warning( + 'An authorization code was redeemed after another request had consumed it: a replay, or a lock ' . + 'store failure. Revoking the tokens issued for it.', + ['client_id' => $client->getIdentifier()], + ); + $this->revokeTokensOfReplayedCode($authCodePayload->auth_code_id, (int)$authCodePayload->expire_time); + throw OAuthServerException::invalidGrant('Authorization code has been revoked'); + } return $responseType; } + /** + * For authorization codes kept in the protocol cache only: the evidence of an earlier use, then the code's + * expiry, once the request proved it holds the code. + * + * @psalm-param AuthCodePayloadObject $authCodePayload + * @throws \League\OAuth2\Server\Exception\OAuthServerException + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function validateAuthorizationCodeUse(object $authCodePayload): void + { + if (! is_a($this->authCodeRepository, AuthCodeRepositoryInterface::class)) { + throw OidcServerException::serverError('Unexpected auth code repository entity type.'); + } + + if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) { + // Code is reused, all related tokens must be revoked, per https://tools.ietf.org/html/rfc6749#section-4.1.2 + $this->revokeTokensOfReplayedCode($authCodePayload->auth_code_id, (int)$authCodePayload->expire_time); + throw OAuthServerException::invalidGrant('Authorization code has been revoked'); + } + + if (time() > $authCodePayload->expire_time) { + throw OAuthServerException::invalidGrant('Authorization code has expired'); + } + } + + /** + * For authorization codes kept in the protocol cache only. Each step runs whatever the others do: the replay is + * recorded in the code's guard, which invalidates the access tokens kept in the cache only for the code, and the + * tokens with database rows are revoked. A failure is logged; the request is refused either way, and a later + * replay runs the steps again for as long as the evidence lasts. + */ + protected function revokeTokensOfReplayedCode(string $authCodeId, int $deadline): void + { + try { + if (! is_a($this->authCodeRepository, AuthCodeRepositoryInterface::class)) { + throw OidcServerException::serverError('Unexpected auth code repository entity type.'); + } + $this->authCodeRepository->recordAuthCodeReplay($authCodeId, $deadline); + } catch (Throwable $exception) { + $this->loggerService->error( + 'Could not record an authorization code replay in the protocol cache: access tokens kept in the ' . + 'cache only for the code stay valid until they expire. ' . $exception->getMessage(), + ); + } + + try { + if (! is_a($this->accessTokenRepository, AccessTokenRepositoryInterface::class)) { + throw OidcServerException::serverError('Unexpected access token repository entity type.'); + } + $this->accessTokenRepository->revokeAllByAuthCodeId($authCodeId); + } catch (Throwable $exception) { + $this->loggerService->error( + 'Could not revoke the access tokens of a replayed authorization code. ' . $exception->getMessage(), + ); + } + + try { + if (! is_a($this->refreshTokenRepository, RefreshTokenRepositoryInterface::class)) { + throw OidcServerException::serverError('Unexpected refresh token repository entity type.'); + } + $this->refreshTokenRepository->revokeAllByAuthCodeId($authCodeId); + } catch (Throwable $exception) { + $this->loggerService->error( + 'Could not revoke the refresh tokens of a replayed authorization code. ' . $exception->getMessage(), + ); + } + } + + /** + * @psalm-param AuthCodePayloadObject $authCodePayload + * @return \League\OAuth2\Server\Entities\ScopeEntityInterface[] + * @throws \League\OAuth2\Server\Exception\OAuthServerException + */ + protected function finalizeAuthorizationCodeScopes( + object $authCodePayload, + OAuth2ClientEntityInterface $client, + ): array { + return $this->scopeRepository->finalizeScopes( + $this->validateScopes($authCodePayload->scopes), + $this->getIdentifier(), + $client, + $authCodePayload->user_id, + ); + } + + protected function isAuthCodeCacheOnly(): bool + { + return $this->moduleConfig->isProtocolArtifactCacheOnly(ProtocolArtifactEnum::AuthorizationCode); + } + /** * Reimplementation because of private parent access * @@ -611,15 +759,20 @@ protected function validateAuthorizationCode( throw OidcServerException::serverError('Unexpected refresh token repository entity type.'); } - if (time() > $authCodePayload->expire_time) { - throw OAuthServerException::invalidGrant('Authorization code has expired'); - } + // With codes kept in the protocol cache only, these two come after the PKCE check + // (validateAuthorizationCodeUse()). + if (!$this->isAuthCodeCacheOnly()) { + if (time() > $authCodePayload->expire_time) { + throw OAuthServerException::invalidGrant('Authorization code has expired'); + } - if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) { - // Code is reused, all related tokens must be revoked, per https://tools.ietf.org/html/rfc6749#section-4.1.2 - $this->accessTokenRepository->revokeByAuthCodeId($authCodePayload->auth_code_id); - $this->refreshTokenRepository->revokeByAuthCodeId($authCodePayload->auth_code_id); - throw OAuthServerException::invalidGrant('Authorization code has been revoked'); + if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) { + // Code is reused, all related tokens must be revoked, per + // https://tools.ietf.org/html/rfc6749#section-4.1.2 + $this->accessTokenRepository->revokeByAuthCodeId($authCodePayload->auth_code_id); + $this->refreshTokenRepository->revokeByAuthCodeId($authCodePayload->auth_code_id); + throw OAuthServerException::invalidGrant('Authorization code has been revoked'); + } } if ($authCodePayload->client_id !== $client->getIdentifier()) { diff --git a/src/Services/AuthenticationService.php b/src/Services/AuthenticationService.php index 24f0215b9..9f575178e 100644 --- a/src/Services/AuthenticationService.php +++ b/src/Services/AuthenticationService.php @@ -153,7 +153,8 @@ public function getAuthenticateUser( if ($user) { $user->setClaims($claims); - $this->userRepository->update($user); + // Writes nothing when the user's database row and cache entry hold these claims already. + $this->userRepository->updateIfClaimsChanged($user); } else { $user = $this->userEntityFactory->fromData($userId, $claims); $this->userRepository->add($user); diff --git a/src/Services/Container.php b/src/Services/Container.php index c09acd246..0df1e182b 100644 --- a/src/Services/Container.php +++ b/src/Services/Container.php @@ -101,9 +101,12 @@ use SimpleSAML\Module\oidc\Stores\Session\LogoutTicketStoreDb; use SimpleSAML\Module\oidc\Utils\ClaimTranslatorExtractor; use SimpleSAML\Module\oidc\Utils\ClassInstanceBuilder; +use SimpleSAML\Module\oidc\Utils\ConsumptionGate; use SimpleSAML\Module\oidc\Utils\FederationCache; use SimpleSAML\Module\oidc\Utils\FederationParticipationValidator; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; use SimpleSAML\Module\oidc\Utils\JwksResolver; +use SimpleSAML\Module\oidc\Utils\LockStoreResolver; use SimpleSAML\Module\oidc\Utils\ProtocolCache; use SimpleSAML\Module\oidc\Utils\RequestParamsResolver; use SimpleSAML\Module\oidc\Utils\Routes; @@ -214,7 +217,9 @@ public function __construct() $this->services[Core::class] = $core; $classInstanceBuilder = new ClassInstanceBuilder(); $this->services[ClassInstanceBuilder::class] = $classInstanceBuilder; - $cacheFactory = new CacheFactory($moduleConfig, $loggerService, $classInstanceBuilder); + $lockStoreResolver = new LockStoreResolver(); + $this->services[LockStoreResolver::class] = $lockStoreResolver; + $cacheFactory = new CacheFactory($moduleConfig, $loggerService, $classInstanceBuilder, $lockStoreResolver); $this->services[CacheFactory::class] = $cacheFactory; $federationCache = $cacheFactory->forFederation(); $this->services[FederationCache::class] = $federationCache; @@ -268,6 +273,12 @@ public function __construct() ); $this->services[AuthCodeEntityFactory::class] = $authCodeEntityFactory; + $issuanceContext = new IssuanceContext(); + $this->services[IssuanceContext::class] = $issuanceContext; + + $consumptionGate = $cacheFactory->forConsumptionGate(); + $this->services[ConsumptionGate::class] = $consumptionGate; + $authCodeRepository = new AuthCodeRepository( $moduleConfig, $database, @@ -275,6 +286,8 @@ public function __construct() $clientRepository, $authCodeEntityFactory, $helpers, + $issuanceContext, + $consumptionGate, ); $this->services[AuthCodeRepository::class] = $authCodeRepository; @@ -301,6 +314,8 @@ public function __construct() $clientRepository, $accessTokenEntityFactory, $helpers, + $authCodeRepository, + $issuanceContext, ); $this->services[AccessTokenRepository::class] = $accessTokenRepository; @@ -447,6 +462,8 @@ public function __construct() $authCodeEntityFactory, $refreshTokenIssuer, $helpers, + $loggerService, + $issuanceContext, ); $this->services[AuthCodeGrant::class] = $authCodeGrantFactory->build(); diff --git a/src/Utils/ConsumptionGate.php b/src/Utils/ConsumptionGate.php new file mode 100644 index 000000000..0cfa3b771 --- /dev/null +++ b/src/Utils/ConsumptionGate.php @@ -0,0 +1,204 @@ +assertClientCanClaim($resource); + + try { + $this->store->save(new Key($resource)); + } catch (LockConflictedException) { + return false; + } catch (Throwable $exception) { + throw OidcServerException::serverError( + 'Could not claim the authorization code: the lock store failed.', + $exception, + ); + } + + return true; + } + + /** + * A phpredis or Relay client left in a transaction or a pipeline answers a command with a queued reply, which + * the store would take for a successful claim. For a RedisArray, every shard is checked: the one the store sends + * the resource to, and the one its time probe goes to. A Relay client which throws on errors breaks the store's + * script loading. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function assertClientCanClaim(string $resource): void + { + $client = $this->client; + + if ($client === null) { + return; + } + + try { + if ($client instanceof \RedisArray) { + $this->assertRedisArrayCanClaim($client, $resource); + return; + } + + if ($client instanceof \Redis || $client instanceof \RedisCluster) { + $this->assertAtomicMode($client->getMode(), \Redis::MULTI | \Redis::PIPELINE); + return; + } + + if ($this->isRelayClient($client)) { + $this->assertRelayClientCanClaim($client); + } + } catch (OidcServerException $exception) { + throw $exception; + } catch (Throwable $exception) { + throw OidcServerException::serverError( + 'Could not claim the authorization code: the lock store client failed.', + $exception, + ); + } + } + + /** + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function assertRedisArrayCanClaim(\RedisArray $client, string $resource): void + { + /** @var mixed $hosts */ + $hosts = $client->_hosts(); + /** @var mixed $target */ + $target = $client->_target($resource); + + if (!is_array($hosts) || !in_array($target, $hosts, true)) { + throw OidcServerException::serverError( + 'Could not claim the authorization code: the lock store has no shard for it.', + ); + } + + /** @psalm-suppress MixedAssignment */ + foreach ($hosts as $host) { + /** @var mixed $shard */ + $shard = is_string($host) ? $client->_instance($host) : null; + + if (!$shard instanceof \Redis) { + throw OidcServerException::serverError( + 'Could not claim the authorization code: a lock store shard can not be reached.', + ); + } + + $this->assertAtomicMode($shard->getMode(), \Redis::MULTI | \Redis::PIPELINE); + } + } + + /** + * Relay is accepted with "throw-on-error" off and phpredis compatibility on (without it, Redis errors throw too), + * and is not covered by tests against a real Relay client. + * + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function assertRelayClientCanClaim(object $client): void + { + $throwOnError = $this->relayConstant('OPT_THROW_ON_ERROR'); + $phpredisCompatibility = $this->relayConstant('OPT_PHPREDIS_COMPATIBILITY'); + + if (method_exists($client, 'getOption')) { + if ($throwOnError !== null && (bool)$client->getOption($throwOnError)) { + throw OidcServerException::serverError( + 'Could not claim the authorization code: the Relay lock store client throws on errors.', + ); + } + + if ($phpredisCompatibility !== null && !(bool)$client->getOption($phpredisCompatibility)) { + throw OidcServerException::serverError( + 'Could not claim the authorization code: the Relay lock store client has phpredis ' . + 'compatibility off, so it throws on errors.', + ); + } + } + + $multi = $this->relayConstant('MULTI'); + $pipeline = $this->relayConstant('PIPELINE'); + + if ($multi !== null && $pipeline !== null && method_exists($client, 'getMode')) { + $this->assertAtomicMode($client->getMode(), $multi | $pipeline); + } + } + + protected function isRelayClient(object $client): bool + { + return $this->isInstanceOf($client, 'Relay\Relay') || $this->isInstanceOf($client, 'Relay\Cluster'); + } + + /** + * A constant of the Relay client class, or null without Relay. + */ + protected function relayConstant(string $name): ?int + { + $constant = 'Relay\Relay::' . $name; + + return defined($constant) ? (int)constant($constant) : null; + } + + /** + * For client classes of extensions which may not be installed. + * + * @psalm-suppress ArgumentTypeCoercion + */ + protected function isInstanceOf(object $object, string $className): bool + { + return is_a($object, $className); + } + + /** + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException + */ + protected function assertAtomicMode(mixed $mode, int $nonAtomicModes): void + { + if (!is_int($mode) || ($mode & $nonAtomicModes) !== 0) { + throw OidcServerException::serverError( + 'Could not claim the authorization code: the lock store client is in a transaction or a pipeline.', + ); + } + } +} diff --git a/src/Utils/IssuanceContext.php b/src/Utils/IssuanceContext.php new file mode 100644 index 000000000..d98e97069 --- /dev/null +++ b/src/Utils/IssuanceContext.php @@ -0,0 +1,37 @@ +nonce = bin2hex(random_bytes(32)); + } + + public function end(): void + { + $this->nonce = null; + } + + public function getNonce(): ?string + { + return $this->nonce; + } +} diff --git a/src/Utils/LockStoreResolver.php b/src/Utils/LockStoreResolver.php new file mode 100644 index 000000000..11b973b93 --- /dev/null +++ b/src/Utils/LockStoreResolver.php @@ -0,0 +1,339 @@ +validateClient($this->buildClientForValidation($lockStore)); + return; + } + + if (is_object($lockStore)) { + $this->validateClient($lockStore); + return; + } + + throw $this->error('A lock store is required, given as a DSN or as a client object.'); + } + + /** + * Builds the client from a DSN (a Redis client lazily, so that nothing connects before a code is claimed, unless + * the DSN sets "lazy" itself), or answers the client object as given. + * + * @throws \Throwable If the client can not be built. + */ + public function buildClient(#[\SensitiveParameter] mixed $lockStore): object + { + if (is_object($lockStore)) { + return $lockStore; + } + + if (!is_string($lockStore)) { + throw new InvalidArgumentException('A lock store is required, given as a DSN or as a client object.'); + } + + return $this->buildClientFromDsn($lockStore, false); + } + + /** + * @psalm-suppress UndefinedClass The client classes of extensions and packages which may not be installed. + * @throws \Throwable + */ + protected function buildClientFromDsn(#[\SensitiveParameter] string $dsn, bool $forceLazy): object + { + if ($this->isMemcachedDsn($dsn)) { + return MemcachedAdapter::createConnection($dsn); + } + + if ($this->isRedisDsn($dsn)) { + return RedisAdapter::createConnection( + $forceLazy ? $this->withLazyConnection($dsn) : $dsn, + ['lazy' => true], + ); + } + + throw new InvalidArgumentException('Unsupported lock store DSN scheme.'); + } + + /** + * @throws \SimpleSAML\Error\ConfigurationError + */ + protected function buildClientForValidation(#[\SensitiveParameter] string $dsn): object + { + if ($this->isMemcachedDsn($dsn)) { + if (!$this->isExtensionLoaded('memcached')) { + throw $this->error('A Memcached lock store requires the memcached extension.'); + } + } elseif ($this->isRedisDsn($dsn)) { + if ( + !$this->isExtensionLoaded('redis') && + !$this->isExtensionLoaded('relay') && + !$this->isPredisAvailable() + ) { + throw $this->error( + 'A Redis lock store requires the redis or the relay extension, or the predis/predis package.', + ); + } + } else { + throw $this->error( + 'Unsupported lock store DSN: it must start with "memcached:", "redis:", "rediss:", "valkey:" or ' . + '"valkeys:".', + ); + } + + try { + return $this->buildClientFromDsn($dsn, true); + } catch (ConfigurationError $error) { + throw $error; + } catch (Throwable $exception) { + throw $this->error(sprintf( + 'A client can not be built from the lock store DSN (%s); check its form and its options.', + (new ReflectionClass($exception))->getShortName(), + )); + } + } + + /** + * @throws \SimpleSAML\Error\ConfigurationError + */ + protected function validateClient(object $client): void + { + if ($client instanceof \Memcached) { + $this->validateMemcachedClient($client); + return; + } + + foreach (self::REDIS_CLIENT_CLASSES as $class) { + if ($this->isInstanceOf($client, $class)) { + return; + } + } + + if ($this->isInstanceOf($client, $this->predisClientInterface())) { + $this->validatePredisClient($client); + return; + } + + throw $this->error(sprintf( + 'Unsupported lock store client class: %s. Supported: Memcached, %s, or a Predis client.', + $client::class, + implode(', ', self::REDIS_CLIENT_CLASSES), + )); + } + + /** + * A client which answers before the server has decided lets two requests both claim one code. + * + * @throws \SimpleSAML\Error\ConfigurationError + */ + protected function validateMemcachedClient(\Memcached $client): void + { + if ($client->getServerList() === []) { + throw $this->error('The Memcached lock store client has no servers.'); + } + + $refusedOptions = [ + 'buffer_writes' => \Memcached::OPT_BUFFER_WRITES, + 'noreply' => \Memcached::OPT_NOREPLY, + 'use_udp' => \Memcached::OPT_USE_UDP, + ]; + + foreach ($refusedOptions as $name => $option) { + if ((bool)$client->getOption($option)) { + throw $this->error(sprintf( + 'The Memcached lock store client must not have the "%s" option on: the client then answers ' . + 'before the server has decided, and two requests could both claim one authorization code.', + $name, + )); + } + } + } + + /** + * The lock store recognises a Predis cluster by Predis 2's interface only, so it can not load its script on a + * Predis 1 cluster. A Predis client does not connect before its first command. + * + * @throws \SimpleSAML\Error\ConfigurationError + */ + protected function validatePredisClient(object $client): void + { + if (!method_exists($client, 'getConnection')) { + return; + } + + /** @var mixed $connection */ + $connection = $client->getConnection(); + + if ( + is_object($connection) && + $this->isInstanceOf($connection, $this->predis1ClusterInterface()) && + !$this->isInstanceOf($connection, $this->predis2ClusterInterface()) + ) { + throw $this->error( + 'A Redis lock store on a Predis 1 cluster can not load the lock script: use Predis 2, the ' . + 'redis extension, or a single host.', + ); + } + } + + protected function isMemcachedDsn(#[\SensitiveParameter] string $dsn): bool + { + return str_starts_with($dsn, self::SCHEME_MEMCACHED . ':'); + } + + protected function isRedisDsn(#[\SensitiveParameter] string $dsn): bool + { + foreach (self::REDIS_SCHEMES as $scheme) { + if (str_starts_with($dsn, $scheme . ':')) { + return true; + } + } + + return false; + } + + /** + * The DSN with "lazy" on, which wins over any "lazy" the DSN sets: building the client then connects to nothing. + * The scheme and the user and password are left as they are, found the way the cache component finds them (a + * password may hold any character but "@", "?" and "#" included), and so is a fragment. + * + * @throws \SimpleSAML\Error\ConfigurationError + */ + protected function withLazyConnection(#[\SensitiveParameter] string $dsn): string + { + if (preg_match('#^[a-z]+:(?://)?(?:(?:[^:@]*+:)?[^@]*+@)?#', $dsn, $match) !== 1) { + return $dsn; + } + + $prefix = $match[0]; + $rest = substr($dsn, strlen($prefix)); + $fragment = ''; + $fragmentPosition = strpos($rest, '#'); + + if ($fragmentPosition !== false) { + $fragment = substr($rest, $fragmentPosition); + $rest = substr($rest, 0, $fragmentPosition); + } + + $query = []; + $queryPosition = strpos($rest, '?'); + + if ($queryPosition !== false) { + parse_str(substr($rest, $queryPosition + 1), $query); + $rest = substr($rest, 0, $queryPosition); + } + + $this->validateRedisQuery($query); + $query['lazy'] = '1'; + + // Joined with a separator the cache component's parse_str() splits on, whatever arg_separator.output says. + $separators = (string)ini_get('arg_separator.input'); + $separator = $separators === '' ? '&' : $separators[0]; + + return $prefix . $rest . '?' . http_build_query($query, '', $separator) . $fragment; + } + + /** + * Options the cache component only reads when the client connects, so that a lazy client built for the check + * would not reveal them. + * + * @throws \SimpleSAML\Error\ConfigurationError + */ + protected function validateRedisQuery(array $query): void + { + if ( + array_key_exists('failover', $query) && + !in_array($query['failover'], ['none', 'error', 'distribute', 'slaves'], true) + ) { + throw $this->error( + 'Unsupported "failover" option in the lock store DSN: use none, error, distribute or slaves.', + ); + } + } + + /** + * For classes of extensions and packages which may not be installed. + * + * @psalm-suppress ArgumentTypeCoercion + */ + protected function isInstanceOf(object $object, string $className): bool + { + return is_a($object, $className); + } + + protected function predisClientInterface(): string + { + return 'Predis\ClientInterface'; + } + + protected function predis1ClusterInterface(): string + { + return 'Predis\Connection\Aggregate\ClusterInterface'; + } + + protected function predis2ClusterInterface(): string + { + return 'Predis\Connection\Cluster\ClusterInterface'; + } + + protected function isExtensionLoaded(string $extension): bool + { + return extension_loaded($extension); + } + + protected function isPredisAvailable(): bool + { + return class_exists('Predis\Client'); + } + + protected function error(string $message): ConfigurationError + { + return new ConfigurationError( + sprintf('Config option %s: %s', ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE, $message), + ModuleConfig::DEFAULT_FILE_NAME, + ); + } +} diff --git a/src/Utils/ProtocolCache.php b/src/Utils/ProtocolCache.php index b449c8325..bda2eb54e 100644 --- a/src/Utils/ProtocolCache.php +++ b/src/Utils/ProtocolCache.php @@ -4,8 +4,78 @@ namespace SimpleSAML\Module\oidc\Utils; +use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; use SimpleSAML\OpenID\Decorators\CacheDecorator; +use stdClass; +use Throwable; class ProtocolCache extends CacheDecorator { + /** + * Writes the value and reads it back, for entries the protocol cache is the only authority on. Symfony cache + * adapters swallow backend failures, and a write reported as successful may not have landed (a failed Redis + * pipeline counts as success), so a write counts only once a read answers the same value. The read-back proves + * the value, not its TTL. + * + * The values are arrays or strings of scalars, so a strict comparison is sound. + * + * @param int $ttl Seconds; must be above zero, since a save of an already expired item deletes it and reports + * success. + * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException When the write can not be confirmed; the + * stored outcome is then unknown. + */ + public function setChecked(mixed $value, int $ttl, string $keyElement, string ...$keyElements): void + { + if ($ttl <= 0) { + throw OidcServerException::serverError( + sprintf('Refusing a protocol cache write with a TTL of %d seconds.', $ttl), + ); + } + + $key = self::keyFor($keyElement, ...$keyElements); + $missing = new stdClass(); + + try { + $isWritten = $this->cache->set($key, $value, $ttl); + /** @var mixed $readBack */ + $readBack = $isWritten ? $this->cache->get($key, $missing) : $missing; + } catch (Throwable $exception) { + throw OidcServerException::serverError('The protocol cache write failed.', $exception); + } + + if ($isWritten !== true) { + throw OidcServerException::serverError('The protocol cache refused a write.'); + } + + if ($readBack !== $value) { + throw OidcServerException::serverError('A protocol cache write could not be confirmed.'); + } + } + + /** + * Reads several entries in one round trip. Each element of $keys lists the key elements of one entry; the answer + * has the same array keys, with null for an entry which is missing or could not be read. + * + * @param array> $keys + * @return array + * @throws \Psr\SimpleCache\InvalidArgumentException + */ + public function getMany(array $keys): array + { + $cacheKeys = array_map( + static fn(array $keyElements): string => self::keyFor(...$keyElements), + $keys, + ); + + $values = $this->cache->getMultiple(array_values(array_unique($cacheKeys))); + $valuesByCacheKey = is_array($values) ? $values : iterator_to_array($values); + + $result = []; + foreach ($cacheKeys as $name => $cacheKey) { + /** @psalm-suppress MixedAssignment */ + $result[$name] = $valuesByCacheKey[$cacheKey] ?? null; + } + + return $result; + } } diff --git a/tests/integration/src/CacheOnly/CacheOnlyBackendsTest.php b/tests/integration/src/CacheOnly/CacheOnlyBackendsTest.php new file mode 100644 index 000000000..d26217520 --- /dev/null +++ b/tests/integration/src/CacheOnly/CacheOnlyBackendsTest.php @@ -0,0 +1,271 @@ + 'sqlite::memory:', + 'database.username' => null, + 'database.password' => null, + 'database.prefix' => 'phpunit_', + 'database.persistent' => true, + 'database.secondaries' => [], + ], + '', + 'simplesaml', + ); + (new DatabaseMigration())->migrate(); + } + + public static function backendProvider(): array + { + return [ + 'memcached, binary protocol' => ['memcached', true], + 'memcached, text protocol' => ['memcached', false], + 'redis' => ['redis', true], + ]; + } + + protected function hostOrSkip(string $backend): string + { + $variable = $backend === 'redis' ? 'OIDC_TEST_REDIS_HOST' : 'OIDC_TEST_MEMCACHED_HOST'; + $host = getenv($variable); + + if (!is_string($host) || $host === '') { + // A skip would let a CI run which lost its servers pass without testing anything. + if (getenv('OIDC_TEST_BACKENDS_REQUIRED') === '1') { + $this->fail("No $backend server given in $variable, and OIDC_TEST_BACKENDS_REQUIRED is set."); + } + $this->markTestSkipped("No $backend server given."); + } + + return $host; + } + + /** + * A fresh client, as another node or request would have. + */ + protected function client(string $backend, bool $binaryProtocol): object + { + $host = $this->hostOrSkip($backend); + + if ($backend === 'redis') { + return (new LockStoreResolver())->buildClient("redis://$host"); + } + + if ($binaryProtocol) { + return (new LockStoreResolver())->buildClient("memcached://$host"); + } + + [$name, $port] = explode(':', $host . ':11211'); + $client = new \Memcached(); + $client->addServer($name, (int)$port); + + return $client; + } + + protected function adapter(object $client, string $namespace): AdapterInterface + { + return $client instanceof \Memcached ? + new MemcachedAdapter($client, $namespace) : + new RedisAdapter($client, $namespace); // @phpstan-ignore argument.type + } + + protected function protocolCache(string $backend, bool $binaryProtocol, string $namespace): ProtocolCache + { + return new ProtocolCache( + new Psr16Cache($this->adapter($this->client($backend, $binaryProtocol), $namespace)), + ); + } + + protected function store(object $client): PersistingStoreInterface + { + return $client instanceof \Memcached ? + new MemcachedStore($client, 600) : + new RedisStore($client, 600.0); // @phpstan-ignore argument.type + } + + #[DataProvider('backendProvider')] + public function testCheckedStoreIsSeenFromAnotherClient(string $backend, bool $binaryProtocol): void + { + $namespace = 'oidc_test_' . bin2hex(random_bytes(6)); + $writer = $this->protocolCache($backend, $binaryProtocol, $namespace); + $reader = $this->protocolCache($backend, $binaryProtocol, $namespace); + $entry = ['id' => 'code', 'is_revoked' => false, 'cache_only' => true, 'cache_only_status' => 'issued']; + + $writer->setChecked($entry, 60, 'entry'); + $writer->setChecked('clean', 60, 'guard'); + + $this->assertSame(['entry' => $entry, 'guard' => 'clean'], $reader->getMany([ + 'entry' => ['entry'], + 'guard' => ['guard'], + ])); + } + + #[DataProvider('backendProvider')] + public function testOnlyTheFirstClaimWinsAcrossClients(string $backend, bool $binaryProtocol): void + { + $codeId = bin2hex(random_bytes(20)); + $first = new ConsumptionGate($this->store($this->client($backend, $binaryProtocol))); + $second = new ConsumptionGate($this->store($this->client($backend, $binaryProtocol))); + + $this->assertTrue($first->claim($codeId)); + $this->assertFalse($second->claim($codeId)); + $this->assertFalse($first->claim($codeId)); + } + + #[DataProvider('backendProvider')] + public function testOfConcurrentClaimsExactlyOneWins(string $backend, bool $binaryProtocol): void + { + $this->hostOrSkip($backend); + if (!function_exists('pcntl_fork')) { + $this->markTestSkipped('No pcntl.'); + } + + $codeId = bin2hex(random_bytes(20)); + $startAt = microtime(true) + 0.5; + $children = []; + + for ($i = 0; $i < 8; $i++) { + $pid = pcntl_fork(); + if ($pid === 0) { + $gate = new ConsumptionGate($this->store($this->client($backend, $binaryProtocol))); + time_sleep_until($startAt); + exit($gate->claim($codeId) ? 10 : 20); + } + $children[] = $pid; + } + + $outcomes = []; + foreach ($children as $pid) { + pcntl_waitpid($pid, $status); + $outcomes[] = pcntl_wexitstatus($status); + } + sort($outcomes); + + $this->assertSame([10, 20, 20, 20, 20, 20, 20, 20], $outcomes); + } + + public function testRedisClaimWorksWithAColdScriptCache(): void + { + $client = $this->client('redis', true); + $this->assertInstanceOf(\Redis::class, $client); + $this->assertTrue($client->script('flush'), 'The script cache could not be flushed.'); + + $this->assertTrue((new ConsumptionGate($this->store($client), $client))->claim(bin2hex(random_bytes(20)))); + } + + #[DataProvider('backendProvider')] + public function testACodeIsRedeemedOnceAcrossRequests(string $backend, bool $binaryProtocol): void + { + $namespace = 'oidc_test_' . bin2hex(random_bytes(6)); + $authCode = $this->authCode(); + $codeId = $authCode->getIdentifier(); + + $this->repository($backend, $binaryProtocol, $namespace)->persistNewAuthCode($authCode); + + $winner = $this->repository($backend, $binaryProtocol, $namespace, true); + $loser = $this->repository($backend, $binaryProtocol, $namespace, true); + $this->assertFalse($winner->isAuthCodeRevoked($codeId)); + $this->assertFalse($loser->isAuthCodeRevoked($codeId)); + + $deadline = $authCode->getExpiryDateTime()->getTimestamp(); + $this->assertTrue($winner->consumeAuthCode($codeId, $deadline, time() + 3600)); + $this->assertFalse($loser->consumeAuthCode($codeId, $deadline, time() + 3600)); + + $loser->recordAuthCodeReplay($codeId, $deadline); + $this->assertTrue($this->repository($backend, $binaryProtocol, $namespace)->isAuthCodeRevoked($codeId)); + } + + protected function authCode(): AuthCodeEntity + { + $client = $this->createStub(ClientEntity::class); + $client->method('getIdentifier')->willReturn('client-id'); + + return new AuthCodeEntity( + bin2hex(random_bytes(20)), + $client, + [new ScopeEntity('openid')], + new DateTimeImmutable('+10 minutes'), + 'user-id', + 'https://rp.example.org/callback', + ); + } + + /** + * A repository as one request on one node has it: its own clients, its own issuance context. + */ + protected function repository( + string $backend, + bool $binaryProtocol, + string $namespace, + bool $beginsIssuance = false, + ): AuthCodeRepository { + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturnCallback( + fn(ProtocolArtifactEnum $artifact): bool => $artifact === ProtocolArtifactEnum::AuthorizationCode, + ); + $moduleConfig->method('getAccessTokenDuration')->willReturn(new DateInterval('PT1H')); + $moduleConfig->method('getAuthCodeDuration')->willReturn(new DateInterval('PT10M')); + $issuanceContext = new IssuanceContext(); + if ($beginsIssuance) { + $issuanceContext->begin(); + } + $helpers = new Helpers(); + + return new AuthCodeRepository( + $moduleConfig, + Database::getInstance(), + $this->protocolCache($backend, $binaryProtocol, $namespace), + $this->createStub(ClientRepository::class), + new AuthCodeEntityFactory($helpers, new ScopeEntityFactory()), + $helpers, + $issuanceContext, + new ConsumptionGate($this->store($this->client($backend, $binaryProtocol))), + ); + } +} diff --git a/tests/integration/src/Repositories/AccessTokenRepositoryTest.php b/tests/integration/src/Repositories/AccessTokenRepositoryTest.php index 2c0963347..096b1cc86 100644 --- a/tests/integration/src/Repositories/AccessTokenRepositoryTest.php +++ b/tests/integration/src/Repositories/AccessTokenRepositoryTest.php @@ -4,6 +4,7 @@ namespace SimpleSAML\Test\Module\oidc\integration\Repositories; +use DateInterval; use League\OAuth2\Server\CryptKey; use PDO; use PHPUnit\Framework\Attributes\CoversClass; @@ -15,20 +16,28 @@ use SimpleSAML\Module\oidc\Entities\AccessTokenEntity; use SimpleSAML\Module\oidc\Entities\ClientEntity; use SimpleSAML\Module\oidc\Entities\Interfaces\ClientEntityInterface; +use SimpleSAML\Module\oidc\Entities\RefreshTokenEntity; use SimpleSAML\Module\oidc\Entities\ScopeEntity; use SimpleSAML\Module\oidc\Entities\UserEntity; use SimpleSAML\Module\oidc\Factories\Entities\AccessTokenEntityFactory; use SimpleSAML\Module\oidc\Factories\Entities\ClientEntityFactory; +use SimpleSAML\Module\oidc\Factories\Entities\RefreshTokenEntityFactory; use SimpleSAML\Module\oidc\Factories\Entities\ScopeEntityFactory; use SimpleSAML\Module\oidc\Factories\Entities\UserEntityFactory; use SimpleSAML\Module\oidc\Helpers; use SimpleSAML\Module\oidc\ModuleConfig; use SimpleSAML\Module\oidc\Repositories\AbstractDatabaseRepository; use SimpleSAML\Module\oidc\Repositories\AccessTokenRepository; +use SimpleSAML\Module\oidc\Repositories\AuthCodeRepository; use SimpleSAML\Module\oidc\Repositories\ClientRepository; +use SimpleSAML\Module\oidc\Repositories\RefreshTokenRepository; use SimpleSAML\Module\oidc\Repositories\UserRepository; use SimpleSAML\Module\oidc\Services\DatabaseMigration; use SimpleSAML\Module\oidc\Services\JsonWebTokenBuilderService; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; +use SimpleSAML\Module\oidc\Utils\ProtocolCache; +use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\Cache\Psr16Cache; use Testcontainers\Container\MySQLContainer; use Testcontainers\Container\PostgresContainer; use Testcontainers\Wait\WaitForHealthCheck; @@ -67,6 +76,8 @@ class AccessTokenRepositoryTest extends TestCase protected array $accessTokenState; protected AccessTokenEntityFactory $accessTokenEntityFactory; protected CryptKey $privateKey; + protected Database $database; + protected ClientRepository $clientRepository; public static function setUpBeforeClass(): void { @@ -173,7 +184,11 @@ public function getDatabase(): Database $clientRepositoryMock, $this->accessTokenEntityFactory, new Helpers(), + $this->createStub(AuthCodeRepository::class), + new IssuanceContext(), ); + $this->database = $database; + $this->clientRepository = $clientRepositoryMock; $client = self::clientRepositoryGetClient(self::CLIENT_ID); $this->mock->getDatabase()->write('DELETE from ' . $clientRepositoryMock->getTableName()); @@ -312,6 +327,71 @@ public function testRevokeByAuthCodeId(string $database): void $this->assertTrue($isRevoked); } + /** + * With access tokens kept in the protocol cache only, a refresh token's access token is promoted to the database + * before the refresh token is stored, which the refresh token's foreign key needs (enforced on MySQL and + * PostgreSQL; SQLite runs with foreign keys off, so the access token's row is asserted explicitly). + */ + #[DataProvider('databaseToTest')] + public function testPromotionSatisfiesTheRefreshTokenForeignKey(string $database): void + { + $this->useDatabase(self::$$database); + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturn(true); + $moduleConfig->method('getAccessTokenDuration')->willReturn(new DateInterval('PT1H')); + $protocolCache = new ProtocolCache(new Psr16Cache(new ArrayAdapter())); + $helpers = new Helpers(); + $accessTokenRepository = new AccessTokenRepository( + $moduleConfig, + $this->database, + $protocolCache, + $this->clientRepository, + $this->accessTokenEntityFactory, + $helpers, + $this->createStub(AuthCodeRepository::class), + new IssuanceContext(), + ); + $refreshTokenRepository = new RefreshTokenRepository( + $moduleConfig, + $this->database, + $protocolCache, + $accessTokenRepository, + new RefreshTokenEntityFactory($helpers), + $helpers, + ); + $tokenId = 'promoted_' . bin2hex(random_bytes(16)); + // An access token of the refresh grant: for no authorization code. + $accessToken = $this->accessTokenEntityFactory->fromData( + $tokenId, + self::clientRepositoryGetClient(self::CLIENT_ID), + $this->scopes, + new \DateTimeImmutable('+1 hour'), + self::USER_ID, + ); + $accessTokenRepository->persistNewAccessToken($accessToken); + $this->assertSame([], $this->accessTokenRows($tokenId)); + + $refreshTokenRepository->persistNewRefreshToken(new RefreshTokenEntity( + 'refresh_' . $tokenId, + new \DateTimeImmutable('+1 month'), + $accessToken, + )); + + $this->assertCount(1, $this->accessTokenRows($tokenId)); + $this->assertCount(1, $this->database->read( + 'SELECT id FROM ' . $refreshTokenRepository->getTableName() . ' WHERE access_token_id = :id', + ['id' => $tokenId], + )->fetchAll()); + } + + protected function accessTokenRows(string $tokenId): array + { + return $this->database->read( + 'SELECT id FROM ' . $this->accessTokenRepository->getTableName() . ' WHERE id = :id', + ['id' => $tokenId], + )->fetchAll(); + } + /** * @param string $id * @param bool $enabled diff --git a/tests/unit/src/Controllers/UserInfoControllerTest.php b/tests/unit/src/Controllers/UserInfoControllerTest.php index 2b1a0e5ca..cfc13f738 100644 --- a/tests/unit/src/Controllers/UserInfoControllerTest.php +++ b/tests/unit/src/Controllers/UserInfoControllerTest.php @@ -4,24 +4,44 @@ namespace SimpleSAML\Test\Module\oidc\unit\Controllers; +use DateInterval; +use DateTimeImmutable; use Laminas\Diactoros\ServerRequest; use League\OAuth2\Server\ResourceServer; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ServerRequestInterface; +use SimpleSAML\Database; use SimpleSAML\Error\UserNotFound; use SimpleSAML\Module\oidc\Bridges\PsrHttpBridge; use SimpleSAML\Module\oidc\Controllers\Traits\RequestTrait; use SimpleSAML\Module\oidc\Controllers\UserInfoController; use SimpleSAML\Module\oidc\Entities\AccessTokenEntity; +use SimpleSAML\Module\oidc\Entities\AuthCodeEntity; +use SimpleSAML\Module\oidc\Entities\ClientEntity; +use SimpleSAML\Module\oidc\Entities\ScopeEntity; use SimpleSAML\Module\oidc\Entities\UserEntity; +use SimpleSAML\Module\oidc\Factories\Entities\AccessTokenEntityFactory; +use SimpleSAML\Module\oidc\Factories\Entities\AuthCodeEntityFactory; +use SimpleSAML\Module\oidc\Factories\Entities\ScopeEntityFactory; +use SimpleSAML\Module\oidc\Helpers; +use SimpleSAML\Module\oidc\ModuleConfig; use SimpleSAML\Module\oidc\Repositories\AccessTokenRepository; use SimpleSAML\Module\oidc\Repositories\AllowedOriginRepository; +use SimpleSAML\Module\oidc\Repositories\AuthCodeRepository; +use SimpleSAML\Module\oidc\Repositories\ClientRepository; use SimpleSAML\Module\oidc\Repositories\UserRepository; +use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; use SimpleSAML\Module\oidc\Services\ErrorResponder; use SimpleSAML\Module\oidc\Utils\ClaimTranslatorExtractor; +use SimpleSAML\Module\oidc\Utils\ConsumptionGate; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; +use SimpleSAML\Module\oidc\Utils\ProtocolCache; use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; +use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\Cache\Psr16Cache; use Symfony\Component\HttpFoundation\ResponseHeaderBag; +use Symfony\Component\Lock\Store\InMemoryStore; /** * @covers \SimpleSAML\Module\oidc\Controllers\UserInfoController @@ -187,8 +207,127 @@ public function testItThrowsIfAccessTokenNotFound(): void ->method('findById') ->willReturn(null); - $this->expectException(UserNotFound::class); - $this->mock()->__invoke($this->serverRequestMock); + // A token gone after the validator, or no longer valid (kept in the protocol cache only, its code replayed in + // the meantime), is refused as the validator refuses it: 401, not a 500. + try { + $this->mock()->__invoke($this->serverRequestMock); + $this->fail('A token not found was not refused.'); + } catch (OidcServerException $exception) { + $this->assertSame('access_denied', $exception->getErrorType()); + $this->assertSame(401, $exception->getHttpStatusCode()); + } + } + + /** + * With access tokens kept in the protocol cache only, on a real repository: a replay of the token's code recorded + * after the bearer check passed, before the controller looks the token up again, is refused with 401. + */ + public function testATokenWhoseCodeIsReplayedBetweenTheTwoLookupsIsRefused(): void + { + $protocolCache = new ProtocolCache(new Psr16Cache(new ArrayAdapter())); + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturn(true); + $moduleConfig->method('getAccessTokenDuration')->willReturn(new DateInterval('PT1H')); + $moduleConfig->method('getAuthCodeDuration')->willReturn(new DateInterval('PT10M')); + // Tokens and codes kept in the cache only never reach the database. + $database = $this->createMock(Database::class); + $database->method('applyPrefix')->willReturnArgument(0); + $database->expects($this->never())->method('read'); + $database->expects($this->never())->method('write'); + $client = $this->createStub(ClientEntity::class); + $client->method('getIdentifier')->willReturn('client_id'); + $clientRepository = $this->createStub(ClientRepository::class); + $clientRepository->method('findById')->willReturn($client); + $helpers = new Helpers(); + $issuanceContext = new IssuanceContext(); + $authCodeRepository = new AuthCodeRepository( + $moduleConfig, + $database, + $protocolCache, + $clientRepository, + new AuthCodeEntityFactory($helpers, new ScopeEntityFactory()), + $helpers, + $issuanceContext, + new ConsumptionGate(new InMemoryStore()), + ); + $accessTokenEntityFactory = $this->createStub(AccessTokenEntityFactory::class); + $accessTokenEntityFactory->method('fromState')->willReturn($this->accessTokenEntityMock); + $accessTokenRepository = new AccessTokenRepository( + $moduleConfig, + $database, + $protocolCache, + $clientRepository, + $accessTokenEntityFactory, + $helpers, + $authCodeRepository, + $issuanceContext, + ); + + // A redemption: the code issued, the token stored, the code consumed by the same request. + $authCode = new AuthCodeEntity( + 'code_id', + $client, + [new ScopeEntity('openid')], + new DateTimeImmutable('+10 minutes'), + 'user_id', + 'https://rp.example.org/callback', + 'oidc-nonce', + ); + $deadline = $authCode->getExpiryDateTime()->getTimestamp(); + $authCodeRepository->persistNewAuthCode($authCode); + $issuanceContext->begin(); + $this->assertFalse($authCodeRepository->isAuthCodeRevoked('code_id')); + $expiry = new DateTimeImmutable('+1 hour'); + $accessToken = $this->createStub(AccessTokenEntity::class); + $accessToken->method('getIdentifier')->willReturn('token_id'); + $accessToken->method('getAuthCodeId')->willReturn('code_id'); + $accessToken->method('getExpiryDateTime')->willReturn($expiry); + $accessToken->method('getState')->willReturn([ + 'id' => 'token_id', + 'scopes' => '["openid"]', + 'expires_at' => $expiry->format('Y-m-d H:i:s'), + 'user_id' => 'user_id', + 'client_id' => 'client_id', + 'is_revoked' => false, + 'auth_code_id' => 'code_id', + 'requested_claims' => '[]', + ]); + $accessTokenRepository->persistNewAccessToken($accessToken); + $this->assertTrue($authCodeRepository->consumeAuthCode('code_id', $deadline, $expiry->getTimestamp())); + $issuanceContext->end(); + + $this->serverRequestMock->method('getMethod')->willReturn('GET'); + $this->authorizationServerRequestMock->method('getAttribute')->willReturnCallback( + fn(string $name): mixed => ['oauth_access_token_id' => 'token_id', 'oauth_scopes' => ['openid']][$name] ?? + null, + ); + $this->resourceServerMock->method('validateAuthenticatedRequest')->willReturnCallback( + function () use ($accessTokenRepository, $authCodeRepository, $deadline): ServerRequestInterface { + // The bearer check passes, then a replay of the code is recorded. + $this->assertFalse($accessTokenRepository->isAccessTokenRevoked('token_id')); + $authCodeRepository->recordAuthCodeReplay('code_id', $deadline); + + return $this->authorizationServerRequestMock; + }, + ); + $this->userRepositoryMock->expects($this->never())->method('getUserEntityByIdentifier'); + $controller = new UserInfoController( + $this->resourceServerMock, + $accessTokenRepository, + $this->userRepositoryMock, + $this->allowedOriginRepositoryMock, + $this->claimTranslatorExtractorMock, + $this->psrHttpBridgeMock, + $this->errorResponderMock, + ); + + try { + $controller->__invoke($this->serverRequestMock); + $this->fail('A token whose code was replayed was served.'); + } catch (OidcServerException $exception) { + $this->assertSame('access_denied', $exception->getErrorType()); + $this->assertSame(401, $exception->getHttpStatusCode()); + } } /** diff --git a/tests/unit/src/Factories/CacheFactoryTest.php b/tests/unit/src/Factories/CacheFactoryTest.php new file mode 100644 index 000000000..38b94e3f6 --- /dev/null +++ b/tests/unit/src/Factories/CacheFactoryTest.php @@ -0,0 +1,103 @@ +createStub(ModuleConfig::class); + $moduleConfig->method('getProtocolCacheOnlyArtifacts')->willReturn($artifacts); + $moduleConfig->method('getProtocolCacheOnlyLockStore')->willReturn($lockStore); + $moduleConfig->method('getProtocolCacheOnlyLockTtl')->willReturn(11460); + + return new CacheFactory($moduleConfig, $this->createStub(LoggerService::class), new ClassInstanceBuilder()); + } + + protected function storeOf(ConsumptionGate $gate): object + { + $store = (new ReflectionProperty(ConsumptionGate::class, 'store'))->getValue($gate); + $this->assertIsObject($store); + + return $store; + } + + public function testNoGateWhileNoArtifactIsKeptInTheCacheOnly(): void + { + $this->assertNull($this->sut([], 'memcached://10.255.255.1')->forConsumptionGate()); + } + + #[RequiresPhpExtension('memcached')] + public function testBuildsAMemcachedStoreWithTheLockTtl(): void + { + $gate = $this->sut([ProtocolArtifactEnum::AuthorizationCode], 'memcached://10.255.255.1') + ->forConsumptionGate(); + + $this->assertInstanceOf(ConsumptionGate::class, $gate); + $store = $this->storeOf($gate); + $this->assertInstanceOf(MemcachedStore::class, $store); + $this->assertSame(11460, (new ReflectionProperty(MemcachedStore::class, 'initialTtl'))->getValue($store)); + } + + #[RequiresPhpExtension('redis')] + public function testBuildsARedisStoreWithTheLockTtlWithoutConnecting(): void + { + // Nothing listens on port 1: the client is built lazily. + $gate = $this->sut([ProtocolArtifactEnum::AuthorizationCode], 'redis://127.0.0.1:1')->forConsumptionGate(); + + $this->assertInstanceOf(ConsumptionGate::class, $gate); + $store = $this->storeOf($gate); + $this->assertInstanceOf(RedisStore::class, $store); + $this->assertSame(11460.0, (new ReflectionProperty(RedisStore::class, 'initialTtl'))->getValue($store)); + } + + #[RequiresPhpExtension('memcached')] + public function testUsesAClientObjectAsGiven(): void + { + $client = new \Memcached(); + + $gate = $this->sut([ProtocolArtifactEnum::AuthorizationCode], $client)->forConsumptionGate(); + + $this->assertInstanceOf(ConsumptionGate::class, $gate); + $this->assertSame($client, (new ReflectionProperty(ConsumptionGate::class, 'client'))->getValue($gate)); + } + + public function testFailingToBuildTheStoreIsAnOidcException(): void + { + $this->expectException(OidcException::class); + + $this->sut([ProtocolArtifactEnum::AuthorizationCode], new \stdClass())->forConsumptionGate(); + } + + /** + * The cache component quotes the "class" query value in its exception. + */ + #[RequiresPhpExtension('redis')] + public function testTheErrorDoesNotQuoteTheDsn(): void + { + try { + $this->sut([ProtocolArtifactEnum::AuthorizationCode], 'redis://10.255.255.1?class=s3cr3t-pa55') + ->forConsumptionGate(); + $this->fail('A lock store of an unsupported scheme was built.'); + } catch (OidcException $exception) { + $this->assertStringNotContainsString('s3cr3t-pa55', $exception->getMessage()); + } + } +} diff --git a/tests/unit/src/Helpers/DateTimeTest.php b/tests/unit/src/Helpers/DateTimeTest.php index f5d673f69..921b31766 100644 --- a/tests/unit/src/Helpers/DateTimeTest.php +++ b/tests/unit/src/Helpers/DateTimeTest.php @@ -4,8 +4,11 @@ namespace SimpleSAML\Test\Module\oidc\unit\Helpers; +use DateInterval; use DateTimeImmutable; +use DateTimeZone; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use SimpleSAML\Module\oidc\Helpers\DateTime; @@ -45,4 +48,72 @@ public function testCanGetSecondsToExpirationTime(): void $this->sut()->getSecondsToExpirationTime($expirationTime), ); } + + public function testMaxSecondsOfAFixedIntervalAddsTheDaylightSavingMargin(): void + { + $this->assertSame(600 + 3 * 3600, $this->sut()->getMaxSecondsOf(new DateInterval('PT10M'))); + $this->assertSame( + 366 * 86400 + 31 * 86400 + 2 * 86400 + 3 * 3600 + 4 * 60 + 5 + 3 * 3600, + $this->sut()->getMaxSecondsOf(new DateInterval('P1Y1M2DT3H4M5S')), + ); + } + + public function testMaxSecondsOfAnIntervalFromADifferenceUsesItsDays(): void + { + $interval = (new DateTimeImmutable('2027-01-01 00:00:00', new DateTimeZone('UTC'))) + ->diff(new DateTimeImmutable('2027-03-01 01:00:00', new DateTimeZone('UTC'))); + + $this->assertSame(59 * 86400 + 3600 + 3 * 3600, $this->sut()->getMaxSecondsOf($interval)); + } + + /** + * Calendar intervals across month ends and daylight-saving changes, in UTC, west of UTC, and in a zone with a + * two-hour shift. + */ + public static function calendarIntervalProvider(): array + { + $cases = []; + $starts = [ + 'month end' => '2027-01-31 12:00:00', + 'month start' => '2027-02-01 12:00:00', + 'leap day' => '2028-02-29 12:00:00', + 'New York spring' => '2027-03-13 12:00:00', + 'New York autumn' => '2027-11-06 12:00:00', + 'Troll spring' => '2027-03-27 12:00:00', + 'Troll autumn' => '2027-10-30 12:00:00', + 'day before spring change' => '2027-03-28 00:30:00', + ]; + + foreach (['UTC', 'America/New_York', 'Antarctica/Troll'] as $zone) { + foreach ($starts as $startName => $start) { + foreach (['P1D', 'P2D', 'P1M', 'P1Y', 'PT24H', 'P1DT1H'] as $interval) { + $cases["$interval from $startName in $zone"] = [$interval, $start, $zone]; + } + } + } + + return $cases; + } + + #[DataProvider('calendarIntervalProvider')] + public function testMaxSecondsOfIsNeverShorterThanTheIntervalAdded( + string $interval, + string $start, + string $zone, + ): void { + $startMoment = new DateTimeImmutable($start, new DateTimeZone($zone)); + $span = $startMoment->add(new DateInterval($interval))->getTimestamp() - $startMoment->getTimestamp(); + + $this->assertGreaterThanOrEqual($span, $this->sut()->getMaxSecondsOf(new DateInterval($interval))); + } + + public function testMaxSecondsOfCoversTheLongestDayInAZoneWithATwoHourShift(): void + { + // Antarctica/Troll moves from UTC+2 back to UTC+0 on the last Sunday of October: that day lasts 26 hours. + $start = new DateTimeImmutable('2027-10-31 00:00:00', new DateTimeZone('Antarctica/Troll')); + $span = $start->add(new DateInterval('P1D'))->getTimestamp() - $start->getTimestamp(); + + $this->assertSame(26 * 3600, $span); + $this->assertGreaterThanOrEqual($span, $this->sut()->getMaxSecondsOf(new DateInterval('P1D'))); + } } diff --git a/tests/unit/src/ModuleConfigTest.php b/tests/unit/src/ModuleConfigTest.php index 429df6762..0c16c6e23 100644 --- a/tests/unit/src/ModuleConfigTest.php +++ b/tests/unit/src/ModuleConfigTest.php @@ -8,17 +8,29 @@ use Lcobucci\JWT\Signer; use Lcobucci\JWT\Signer\Rsa\Sha256; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\RequiresPhpExtension; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use SimpleSAML\Configuration; use SimpleSAML\Error\ConfigurationError; use SimpleSAML\Module\oidc\Bridges\SspBridge; +use SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum; use SimpleSAML\Module\oidc\ModuleConfig; use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; use SimpleSAML\OpenID\Codebooks\TrustMarkStatusEndpointUsagePolicyEnum; use SimpleSAML\Utils\Config; use SimpleSAML\Utils\HTTP; use stdClass; +use Symfony\Component\Cache\Adapter\ApcuAdapter; +use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\Cache\Adapter\ChainAdapter; +use Symfony\Component\Cache\Adapter\FilesystemAdapter; +use Symfony\Component\Cache\Adapter\MemcachedAdapter; +use Symfony\Component\Cache\Adapter\NullAdapter; +use Symfony\Component\Cache\Adapter\ProxyAdapter; +use Symfony\Component\Cache\Adapter\RedisAdapter; +use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter; #[CoversClass(ModuleConfig::class)] class ModuleConfigTest extends TestCase @@ -508,4 +520,187 @@ public function testCanGetFederationTrustMarkStatusEndpointUsagePolicy(): void $sut->getFederationTrustMarkStatusEndpointUsagePolicy(), ); } + + /** + * Overrides keeping authorization codes in the protocol cache only, on Memcached, with no server reachable. + */ + protected function cacheOnlyOverrides(array $overrides = []): array + { + return array_merge( + [ + ModuleConfig::OPTION_TOKEN_AUTHORIZATION_CODE_TTL => 'PT10M', + ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => MemcachedAdapter::class, + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => [ProtocolArtifactEnum::AuthorizationCode], + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => 'memcached://10.255.255.1:11211', + ], + $overrides, + ); + } + + public function testNoArtifactIsKeptInTheCacheOnlyByDefault(): void + { + $sut = $this->sut(overrides: [ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => null]); + + $this->assertSame([], $sut->getProtocolCacheOnlyArtifacts()); + $this->assertFalse($sut->isProtocolArtifactCacheOnly(ProtocolArtifactEnum::AuthorizationCode)); + $this->assertNull($sut->getProtocolCacheOnlyLockStore()); + } + + public static function acceptedCacheOnlyProvider(): array + { + return [ + 'codes on Memcached' => [[]], + 'codes and tokens' => [[ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => [ + ProtocolArtifactEnum::AuthorizationCode, + ProtocolArtifactEnum::AccessToken, + ], + ]], + 'longest code lifetime' => [[ + ModuleConfig::OPTION_TOKEN_AUTHORIZATION_CODE_TTL => 'P29DT20H', + ]], + ]; + } + + #[DataProvider('acceptedCacheOnlyProvider')] + #[RequiresPhpExtension('memcached')] + public function testAcceptsCacheOnlyArtifacts(array $overrides): void + { + $sut = $this->sut(overrides: $this->cacheOnlyOverrides($overrides)); + + $this->assertTrue($sut->isProtocolArtifactCacheOnly(ProtocolArtifactEnum::AuthorizationCode)); + $this->assertNotNull($sut->getProtocolCacheOnlyLockStore()); + } + + #[RequiresPhpExtension('memcached')] + public function testAcceptsALockStoreClientObject(): void + { + $client = new \Memcached(); + $client->addServer('10.255.255.1', 11211); + + $sut = $this->sut(overrides: $this->cacheOnlyOverrides([ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => $client, + ])); + + $this->assertSame($client, $sut->getProtocolCacheOnlyLockStore()); + } + + public static function acceptedRedisCacheOnlyProvider(): array + { + return [ + 'codes on Redis' => ['redis://10.255.255.1:6379'], + 'lock store not lazy, unreachable' => ['redis://127.0.0.1:1?lazy=0'], + ]; + } + + #[DataProvider('acceptedRedisCacheOnlyProvider')] + #[RequiresPhpExtension('redis')] + public function testAcceptsCacheOnlyArtifactsOnRedisWithoutConnecting(string $lockStore): void + { + $sut = $this->sut(overrides: $this->cacheOnlyOverrides([ + ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => RedisAdapter::class, + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => $lockStore, + ])); + + $this->assertTrue($sut->isProtocolArtifactCacheOnly(ProtocolArtifactEnum::AuthorizationCode)); + } + + #[RequiresPhpExtension('memcached')] + public function testAcceptsSubclassesOfTheSupportedAdapters(): void + { + foreach ([MemcachedAdapter::class, RedisAdapter::class] as $adapterClass) { + $subclass = $this->createStub($adapterClass)::class; + + $this->sut(overrides: $this->cacheOnlyOverrides([ + ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => $subclass, + ])); + } + + $this->addToAssertionCount(2); + } + + #[RequiresPhpExtension('memcached')] + public function testCanGetCacheOnlyArtifactsAndLockTtl(): void + { + $sut = $this->sut(overrides: $this->cacheOnlyOverrides([ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => [ + ProtocolArtifactEnum::AuthorizationCode, + ProtocolArtifactEnum::AccessToken, + ], + ])); + + $this->assertSame( + [ProtocolArtifactEnum::AuthorizationCode, ProtocolArtifactEnum::AccessToken], + $sut->getProtocolCacheOnlyArtifacts(), + ); + $this->assertTrue($sut->isProtocolArtifactCacheOnly(ProtocolArtifactEnum::AccessToken)); + $this->assertSame('memcached://10.255.255.1:11211', $sut->getProtocolCacheOnlyLockStore()); + // Ten minutes, the daylight-saving margin, and the cache-only margin. + $this->assertSame(600 + 3 * 3600 + 60, $sut->getProtocolCacheOnlyLockTtl()); + } + + public static function refusedCacheOnlyProvider(): array + { + return [ + 'not an array' => [[ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => ProtocolArtifactEnum::AuthorizationCode, + ]], + 'a string' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => ['authorization_code']]], + 'an unknown value' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => [1]]], + 'another enum' => [[ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => [ + TrustMarkStatusEndpointUsagePolicyEnum::Required, + ], + ]], + 'access tokens without codes' => [[ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => [ProtocolArtifactEnum::AccessToken], + ]], + 'no adapter' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => null]], + 'array adapter' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => ArrayAdapter::class]], + 'null adapter' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => NullAdapter::class]], + 'chain adapter' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => ChainAdapter::class]], + 'proxy adapter' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => ProxyAdapter::class]], + 'tag aware Redis adapter' => [[ + ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => RedisTagAwareAdapter::class, + ]], + 'filesystem adapter' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => FilesystemAdapter::class]], + 'APCu adapter' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => ApcuAdapter::class]], + 'unknown adapter class' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => 'No\Such\Adapter']], + 'no lock store' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => null]], + 'unsupported lock store scheme' => [[ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => 'mysql://10.255.255.1', + ]], + 'unsupported lock store class' => [[ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => new stdClass()]], + 'buffered Memcached lock store' => [[ + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => 'memcached://10.255.255.1?buffer_writes=1', + ]], + // 29 days, 21 hours, the daylight-saving margin and the cache-only margin: one minute over 30 days. + 'lock TTL above 30 days' => [[ModuleConfig::OPTION_TOKEN_AUTHORIZATION_CODE_TTL => 'P29DT21H']], + 'code lifetime in months' => [[ModuleConfig::OPTION_TOKEN_AUTHORIZATION_CODE_TTL => 'P1M']], + ]; + } + + /** + * The refusals other than the lock store's own come before the lock store is looked at, but the test needs the + * memcached extension so that the lock store given would be accepted. + */ + #[DataProvider('refusedCacheOnlyProvider')] + #[RequiresPhpExtension('memcached')] + public function testRefusesCacheOnlyArtifacts(array $overrides): void + { + $this->expectException(ConfigurationError::class); + + $this->sut(overrides: $this->cacheOnlyOverrides($overrides)); + } + + public function testEmptyListNeedsNoLockStoreAndAnyAdapter(): void + { + $sut = $this->sut(overrides: [ + ModuleConfig::OPTION_PROTOCOL_CACHE_ADAPTER => ArrayAdapter::class, + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_ARTIFACTS => [], + ModuleConfig::OPTION_PROTOCOL_CACHE_ONLY_LOCK_STORE => 'mysql://unchecked', + ]); + + $this->assertSame([], $sut->getProtocolCacheOnlyArtifacts()); + } } diff --git a/tests/unit/src/Repositories/AccessTokenRepositoryTest.php b/tests/unit/src/Repositories/AccessTokenRepositoryTest.php index efe6fe323..2506c327c 100644 --- a/tests/unit/src/Repositories/AccessTokenRepositoryTest.php +++ b/tests/unit/src/Repositories/AccessTokenRepositoryTest.php @@ -15,27 +15,42 @@ */ namespace SimpleSAML\Test\Module\oidc\unit\Repositories; +use DateInterval; use DateTimeImmutable; use Exception; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use SimpleSAML\Configuration; use SimpleSAML\Database; use SimpleSAML\Error\Error; use SimpleSAML\Module\oidc\Codebooks\DateFormatsEnum; +use SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum; use SimpleSAML\Module\oidc\Entities\AccessTokenEntity; +use SimpleSAML\Module\oidc\Entities\AuthCodeEntity; use SimpleSAML\Module\oidc\Entities\ClientEntity; use SimpleSAML\Module\oidc\Entities\Interfaces\AccessTokenEntityInterface; +use SimpleSAML\Module\oidc\Entities\ScopeEntity; use SimpleSAML\Module\oidc\Factories\Entities\AccessTokenEntityFactory; +use SimpleSAML\Module\oidc\Factories\Entities\AuthCodeEntityFactory; use SimpleSAML\Module\oidc\Factories\Entities\ClientEntityFactory; +use SimpleSAML\Module\oidc\Factories\Entities\ScopeEntityFactory; use SimpleSAML\Module\oidc\Helpers; use SimpleSAML\Module\oidc\ModuleConfig; +use SimpleSAML\Module\oidc\Repositories\AbstractDatabaseRepository; use SimpleSAML\Module\oidc\Repositories\AccessTokenRepository; +use SimpleSAML\Module\oidc\Repositories\AuthCodeRepository; use SimpleSAML\Module\oidc\Repositories\ClientRepository; use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; use SimpleSAML\Module\oidc\Services\DatabaseMigration; +use SimpleSAML\Module\oidc\Utils\ConsumptionGate; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; use SimpleSAML\Module\oidc\Utils\ProtocolCache; +use SimpleSAML\Test\Module\oidc\unit\Utils\FaultyArrayAdapter; +use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\Cache\Psr16Cache; +use Symfony\Component\Lock\Store\InMemoryStore; #[CoversClass(AccessTokenRepository::class)] class AccessTokenRepositoryTest extends TestCase @@ -58,6 +73,10 @@ class AccessTokenRepositoryTest extends TestCase protected array $accessTokenState; protected Database $database; protected MockObject $protocolCacheMock; + protected FaultyArrayAdapter $cacheAdapter; + protected ProtocolCache $protocolCache; + protected InMemoryStore $lockStore; + protected string $defaultTimezone; /** * @throws \Exception @@ -109,6 +128,16 @@ protected function setUp(): void $this->database = Database::getInstance(); $this->protocolCacheMock = $this->createMock(ProtocolCache::class); + + $this->cacheAdapter = new FaultyArrayAdapter(); + $this->protocolCache = new ProtocolCache(new Psr16Cache($this->cacheAdapter)); + $this->lockStore = new InMemoryStore(); + $this->defaultTimezone = date_default_timezone_get(); + } + + protected function tearDown(): void + { + date_default_timezone_set($this->defaultTimezone); } protected function sut( @@ -118,6 +147,8 @@ protected function sut( ?ClientRepository $clientRepository = null, ?AccessTokenEntityFactory $accessTokenEntityFactory = null, ?Helpers $helpers = null, + ?AuthCodeRepository $authCodeRepository = null, + ?IssuanceContext $issuanceContext = null, ): AccessTokenRepository { $moduleConfig ??= $this->moduleConfigMock; $database ??= $this->database; @@ -125,6 +156,8 @@ protected function sut( $clientRepository ??= $this->clientRepositoryMock; $accessTokenEntityFactory ??= $this->accessTokenEntityFactoryMock; $helpers ??= $this->helpersMock; + $authCodeRepository ??= $this->createStub(AuthCodeRepository::class); + $issuanceContext ??= new IssuanceContext(); return new AccessTokenRepository( $moduleConfig, @@ -133,6 +166,8 @@ protected function sut( $clientRepository, $accessTokenEntityFactory, $helpers, + $authCodeRepository, + $issuanceContext, ); } @@ -216,13 +251,13 @@ public function testErrorRevokeInvalidToken(): void } /** + * A token not found counts as revoked, so that the bearer token validator answers 401 rather than a 500. + * * @throws \SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException */ - public function testErrorCheckIsRevokedInvalidToken(): void + public function testCheckIsRevokedInvalidTokenCountsAsRevoked(): void { - $this->expectException(Exception::class); - - $this->sut()->isAccessTokenRevoked('notoken'); + $this->assertTrue($this->sut()->isAccessTokenRevoked('notoken')); } /** @@ -311,4 +346,1070 @@ public function testCanRevokeByAuthCodeId(): void $sut->revokeByAuthCodeId(self::AUTH_CODE_ID); } + + /** + * Persists tokens for the code through a repository on a real cache, and answers it with its cache adapter. + * + * @param string[] $tokenIds + * @return array{0: \SimpleSAML\Module\oidc\Repositories\AccessTokenRepository, 1: FaultyArrayAdapter} + */ + protected function sutWithTokensFor(string $authCodeId, array $tokenIds): array + { + $adapter = new FaultyArrayAdapter(); + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('getAccessTokenDuration')->willReturn(new DateInterval('PT1H')); + $sut = $this->sut( + moduleConfig: $moduleConfig, + protocolCache: new ProtocolCache(new Psr16Cache($adapter)), + helpers: new Helpers(), + ); + + foreach ($tokenIds as $tokenId) { + $accessToken = $this->createStub(AccessTokenEntity::class); + $accessToken->method('getIdentifier')->willReturn($tokenId); + $accessToken->method('getState')->willReturn( + ['id' => $tokenId, 'auth_code_id' => $authCodeId] + $this->accessTokenState, + ); + $accessToken->method('getExpiryDateTime')->willReturn(new DateTimeImmutable('+1 hour')); + $sut->persistNewAccessToken($accessToken); + } + + return [$sut, $adapter]; + } + + protected function isRowRevoked(string $tokenId): bool + { + $rows = $this->database->read( + 'SELECT is_revoked FROM phpunit_oidc_access_token WHERE id = :id', + ['id' => $tokenId], + )->fetchAll(); + $this->assertCount(1, $rows); + + return (bool)$rows[0]['is_revoked']; + } + + public function testRevokeAllByAuthCodeIdRevokesEveryRowAndEachCachedCopy(): void + { + $authCodeId = 'replayed_' . bin2hex(random_bytes(8)); + [$sut] = $this->sutWithTokensFor($authCodeId, ["$authCodeId-cached", "$authCodeId-not-cached"]); + [$otherSut] = $this->sutWithTokensFor('another_code', ["$authCodeId-of-another-code"]); + $protocolCache = $this->getProtocolCacheOf($sut); + $protocolCache->delete($sut->getCacheKey("$authCodeId-not-cached")); + + $sut->revokeAllByAuthCodeId($authCodeId); + + $this->assertTrue($this->isRowRevoked("$authCodeId-cached")); + $this->assertTrue($this->isRowRevoked("$authCodeId-not-cached")); + $this->assertFalse($this->isRowRevoked("$authCodeId-of-another-code")); + // A revoked copy of every row, cached before or not. + foreach (["$authCodeId-cached", "$authCodeId-not-cached"] as $tokenId) { + $cachedCopy = $protocolCache->get(null, $sut->getCacheKey($tokenId)); + $this->assertIsArray($cachedCopy); + $this->assertTrue($cachedCopy['is_revoked']); + $this->assertSame($authCodeId, $cachedCopy['auth_code_id']); + } + $this->assertFalse( + $this->getProtocolCacheOf($otherSut) + ->get(null, $sut->getCacheKey("$authCodeId-of-another-code"))['is_revoked'], + ); + } + + public function testRevokeAllByAuthCodeIdFailsWhenACachedCopyCanNotBeRevoked(): void + { + $authCodeId = 'replayed_' . bin2hex(random_bytes(8)); + [$sut, $adapter] = $this->sutWithTokensFor($authCodeId, ["$authCodeId-1", "$authCodeId-2"]); + $adapter->dropWrites = true; + + try { + $sut->revokeAllByAuthCodeId($authCodeId); + $this->fail('A cached copy which could not be revoked went unreported.'); + } catch (OidcServerException $exception) { + $this->assertStringContainsString('2 cached copies', $exception->getMessage()); + } + + // The rows are revoked whatever the cache does. + $this->assertTrue($this->isRowRevoked("$authCodeId-1")); + $this->assertTrue($this->isRowRevoked("$authCodeId-2")); + } + + /** + * A failing read looks like a miss: the cleanup must not take it for "nothing cached". + */ + public function testRevokeAllByAuthCodeIdWritesRevokedCopiesWhenCacheReadsFail(): void + { + $authCodeId = 'replayed_' . bin2hex(random_bytes(8)); + [$sut, $adapter] = $this->sutWithTokensFor($authCodeId, ["$authCodeId-1"]); + $adapter->missReads = true; + + try { + $sut->revokeAllByAuthCodeId($authCodeId); + $this->fail('A cached copy which could not be read back went unreported.'); + } catch (OidcServerException) { + // The read-back failed too, so the outcome is reported as unknown. + } + + $adapter->missReads = false; + $cachedCopy = $this->getProtocolCacheOf($sut)->get(null, $sut->getCacheKey("$authCodeId-1")); + $this->assertIsArray($cachedCopy); + $this->assertTrue($cachedCopy['is_revoked']); + } + + public function testFindByIdDoesNotCacheARowFoundOnAMissWhileCodesAreKeptInTheCacheOnly(): void + { + $tokenId = 'access_token_not_cached_again'; + $this->accessTokenEntityMock->method('getState')->willReturn(['id' => $tokenId] + $this->accessTokenState); + $this->accessTokenEntityMock->method('getIdentifier')->willReturn($tokenId); + $this->accessTokenEntityMock->method('getExpiryDateTime')->willReturn(new DateTimeImmutable()); + $this->accessTokenEntityFactoryMock->method('fromState')->willReturn($this->accessTokenEntityMock); + $this->sut()->persistNewAccessToken($this->accessTokenEntityMock); + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturnCallback( + fn(ProtocolArtifactEnum $artifact): bool => $artifact === ProtocolArtifactEnum::AuthorizationCode, + ); + $protocolCache = $this->createMock(ProtocolCache::class); + $protocolCache->method('get')->willReturn(null); + $protocolCache->expects($this->never())->method('set'); + + $this->assertSame( + $this->accessTokenEntityMock, + $this->sut(moduleConfig: $moduleConfig, protocolCache: $protocolCache)->findById($tokenId), + ); + } + + protected function getProtocolCacheOf(AccessTokenRepository $sut): ProtocolCache + { + $protocolCache = (new \ReflectionProperty($sut, 'protocolCache'))->getValue($sut); + $this->assertInstanceOf(ProtocolCache::class, $protocolCache); + + return $protocolCache; + } + + /** + * A cache hit written back would overwrite a revocation written in the meantime. + */ + public function testFindByIdDoesNotWriteACacheHitBack(): void + { + $this->protocolCacheMock->method('get')->willReturn($this->accessTokenState); + $this->protocolCacheMock->expects($this->never())->method('set'); + $this->accessTokenEntityFactoryMock->method('fromState')->willReturn($this->accessTokenEntityMock); + + $this->assertSame($this->accessTokenEntityMock, $this->sut()->findById(self::ACCESS_TOKEN_ID)); + } + + public function testFindByIdCachesARowFoundOnAMiss(): void + { + $tokenId = 'access_token_found_on_a_miss'; + $this->accessTokenEntityMock->method('getState')->willReturn(['id' => $tokenId] + $this->accessTokenState); + $this->accessTokenEntityMock->method('getIdentifier')->willReturn($tokenId); + $this->accessTokenEntityMock->method('getExpiryDateTime')->willReturn(new DateTimeImmutable()); + $this->accessTokenEntityFactoryMock->method('fromState')->willReturn($this->accessTokenEntityMock); + $this->sut()->persistNewAccessToken($this->accessTokenEntityMock); + $protocolCache = $this->createMock(ProtocolCache::class); + $protocolCache->method('get')->willReturn(null); + $protocolCache->expects($this->once())->method('set'); + + $this->assertSame( + $this->accessTokenEntityMock, + $this->sut(protocolCache: $protocolCache)->findById($tokenId), + ); + } + + // Access tokens kept in the protocol cache only. + + /** + * The repositories of one request on the shared protocol cache and lock store, with authorization codes and, + * unless told otherwise, access tokens kept in the cache only, and the request's own issuance context. + * + * @return array{0: AccessTokenRepository, 1: AuthCodeRepository, 2: IssuanceContext} + */ + protected function cacheOnlyRequest( + bool $areAccessTokensCacheOnly = true, + ?Database $database = null, + ?AccessTokenEntityFactory $accessTokenEntityFactory = null, + ): array { + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturnCallback( + fn(ProtocolArtifactEnum $artifact): bool => $artifact === ProtocolArtifactEnum::AuthorizationCode || + ($areAccessTokensCacheOnly && $artifact === ProtocolArtifactEnum::AccessToken), + ); + $moduleConfig->method('getAccessTokenDuration')->willReturn(new DateInterval('PT1H')); + $moduleConfig->method('getAuthCodeDuration')->willReturn(new DateInterval('PT10M')); + $helpers = new Helpers(); + $issuanceContext = new IssuanceContext(); + + $authCodeRepository = new AuthCodeRepository( + $moduleConfig, + $this->database, + $this->protocolCache, + $this->clientRepositoryMock, + new AuthCodeEntityFactory($helpers, new ScopeEntityFactory()), + $helpers, + $issuanceContext, + new ConsumptionGate($this->lockStore), + ); + + $sut = $this->sut( + moduleConfig: $moduleConfig, + database: $database, + protocolCache: $this->protocolCache, + accessTokenEntityFactory: $accessTokenEntityFactory, + helpers: $helpers, + authCodeRepository: $authCodeRepository, + issuanceContext: $issuanceContext, + ); + + return [$sut, $authCodeRepository, $issuanceContext]; + } + + /** + * Issues an authorization code in the cache only, and answers its id and deadline. + * + * @return array{0: string, 1: int} + */ + protected function issueCode(AuthCodeRepository $authCodeRepository): array + { + $authCode = new AuthCodeEntity( + 'code_' . bin2hex(random_bytes(16)), + $this->codeClient(), + [new ScopeEntity('openid')], + new DateTimeImmutable('+10 minutes'), + 'user123', + 'http://localhost/redirect', + 'oidc-nonce', + ); + $authCodeRepository->persistNewAuthCode($authCode); + + return [(string)$authCode->getIdentifier(), $authCode->getExpiryDateTime()->getTimestamp()]; + } + + protected function codeClient(): ClientEntity + { + $client = $this->createStub(ClientEntity::class); + $client->method('getIdentifier')->willReturn(self::CLIENT_ID); + + return $client; + } + + /** + * Begins a token request for the code, as the grant does: a fresh issuance nonce, then the start check. + */ + protected function beginRedemption( + AuthCodeRepository $authCodeRepository, + IssuanceContext $context, + string $codeId, + ): string { + $issuanceNonce = $context->begin(); + $this->assertFalse($authCodeRepository->isAuthCodeRevoked($codeId)); + + return $issuanceNonce; + } + + protected function newAccessToken(?string $authCodeId, string $expiry = '+1 hour'): AccessTokenEntity + { + $tokenId = 'access_token_' . bin2hex(random_bytes(16)); + $expiryDateTime = new DateTimeImmutable($expiry); + + $accessToken = $this->createStub(AccessTokenEntity::class); + $accessToken->method('getIdentifier')->willReturn($tokenId); + $accessToken->method('getAuthCodeId')->willReturn($authCodeId); + $accessToken->method('getExpiryDateTime')->willReturn($expiryDateTime); + $accessToken->method('getState')->willReturn([ + 'id' => $tokenId, + 'scopes' => '["openid"]', + 'expires_at' => $expiryDateTime->format('Y-m-d H:i:s'), + 'user_id' => 'user123', + 'client_id' => self::CLIENT_ID, + 'is_revoked' => false, + 'auth_code_id' => $authCodeId, + 'requested_claims' => '[]', + ]); + + return $accessToken; + } + + /** + * Redeems a new code in one request, as the grant does, and answers the access token it issued, with the + * request's repositories and the code's id. + * + * @return array{0: AccessTokenEntity, 1: AccessTokenRepository, 2: AuthCodeRepository, 3: string, 4: int} + */ + protected function redeemNewCode(): array + { + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest(); + [$codeId, $deadline] = $this->issueCode($authCodeRepository); + $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId); + $sut->persistNewAccessToken($accessToken); + $this->assertTrue( + $authCodeRepository->consumeAuthCode($codeId, $deadline, $accessToken->getExpiryDateTime()->getTimestamp()), + ); + $context->end(); + + return [$accessToken, $sut, $authCodeRepository, $codeId, $deadline]; + } + + protected function entryOf(AccessTokenRepository $sut, string $tokenId): mixed + { + return $this->protocolCache->get(null, $sut->getCacheKey($tokenId)); + } + + protected function rowOf(string $tokenId): ?array + { + $rows = $this->database->read( + 'SELECT * FROM phpunit_oidc_access_token WHERE id = :id', + ['id' => $tokenId], + )->fetchAll(); + + return empty($rows) ? null : (array)current($rows); + } + + /** + * Seconds until the cache entry expires, as the array adapter stores it. + */ + protected function ttlOf(string ...$keyElements): int + { + $expiries = (new \ReflectionProperty(ArrayAdapter::class, 'expiries'))->getValue($this->cacheAdapter); + $this->assertIsArray($expiries); + $expiry = $expiries[ProtocolCache::keyFor(...$keyElements)] ?? null; + $this->assertIsFloat($expiry); + + return (int)round($expiry - microtime(true)); + } + + public static function timezoneProvider(): array + { + return [['UTC'], ['America/New_York'], ['Antarctica/Troll']]; + } + + /** + * The TTL comes from the expiry held in memory, never from the stored one (written in the default zone, read as + * UTC), whatever the default zone. + */ + #[DataProvider('timezoneProvider')] + public function testCacheOnlyTokenIsStoredInTheCacheOnlyWithItsIssuanceNonce(string $timezone): void + { + date_default_timezone_set($timezone); + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest(); + [$codeId] = $this->issueCode($authCodeRepository); + $issuanceNonce = $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId, '+1 hour'); + $tokenId = (string)$accessToken->getIdentifier(); + + $sut->persistNewAccessToken($accessToken); + + $entry = $this->entryOf($sut, $tokenId); + $this->assertIsArray($entry); + $this->assertTrue($entry[AbstractDatabaseRepository::KEY_CACHE_ONLY]); + $this->assertSame($issuanceNonce, $entry[AbstractDatabaseRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE]); + $this->assertSame($codeId, $entry['auth_code_id']); + $this->assertFalse($entry['is_revoked']); + $this->assertNull($this->rowOf($tokenId)); + // The token's expiry held in memory, plus the margin. + $this->assertEqualsWithDelta(3600 + 60, $this->ttlOf($sut->getCacheKey($tokenId)), 2); + } + + public static function unconfirmedWriteProvider(): array + { + return [ + 'the write refused' => ['refuseWrites'], + 'the write answering true without landing' => ['dropWrites'], + 'the read-back missing' => ['missReads'], + ]; + } + + /** + * A token whose write can not be confirmed is not issued: no database row, and the caller gets server_error + * before it hands the token out. + */ + #[DataProvider('unconfirmedWriteProvider')] + public function testCacheOnlyTokenWhoseWriteCanNotBeConfirmedIsAServerError(string $fault): void + { + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest(); + [$codeId] = $this->issueCode($authCodeRepository); + $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId); + $this->cacheAdapter->$fault = true; + + try { + $sut->persistNewAccessToken($accessToken); + $this->fail('A token whose write could not be confirmed was stored.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + + $this->cacheAdapter->$fault = false; + $this->assertNull($this->rowOf((string)$accessToken->getIdentifier())); + } + + public function testCacheOnlyTokenIsValidOnlyOnceItsRequestConsumedTheCode(): void + { + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest(); + [$codeId, $deadline] = $this->issueCode($authCodeRepository); + $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId); + $tokenId = (string)$accessToken->getIdentifier(); + $sut->persistNewAccessToken($accessToken); + + // The code is issued, not consumed yet. + $this->assertNull($sut->findById($tokenId)); + $this->assertTrue($sut->isAccessTokenRevoked($tokenId)); + + $this->assertTrue( + $authCodeRepository->consumeAuthCode($codeId, $deadline, $accessToken->getExpiryDateTime()->getTimestamp()), + ); + + $this->assertSame($this->accessTokenEntityMock, $sut->findById($tokenId)); + $this->assertFalse($sut->isAccessTokenRevoked($tokenId)); + } + + public static function invalidationProvider(): array + { + return [ + 'a replay of the code recorded' => ['replayed'], + "the code's entry evicted" => ['code entry evicted'], + "the code's guard evicted" => ['guard evicted'], + "the token's entry evicted" => ['token entry evicted'], + 'the token revoked' => ['token revoked'], + 'reads failing' => ['reads failing'], + 'the code consumed with another nonce' => ['code consumed by another request'], + "the token's entry without a nonce" => ['token without a nonce'], + "the token's entry with another nonce" => ['token with another nonce'], + "the token's entry with an empty nonce, the code's too" => ['empty nonces'], + "the code's entry back to issued" => ['code not consumed'], + "a replay recorded after the token's entry was read" => ['replayed during the check'], + "the reads of the code's entries failing" => ['code reads failing'], + ]; + } + + #[DataProvider('invalidationProvider')] + public function testCacheOnlyTokenIsInvalidWhenAnyOfItsEvidenceFails(string $case): void + { + [$accessToken, $sut, $authCodeRepository, $codeId, $deadline] = $this->redeemNewCode(); + $tokenId = (string)$accessToken->getIdentifier(); + $tokenKey = $sut->getCacheKey($tokenId); + $codeEntryKey = $authCodeRepository->getEntryCacheKeyElements($codeId); + $this->assertFalse($sut->isAccessTokenRevoked($tokenId)); + + $tokenEntry = $this->entryOf($sut, $tokenId); + $codeEntry = $this->protocolCache->get(null, ...$codeEntryKey); + $this->assertIsArray($tokenEntry); + $this->assertIsArray($codeEntry); + $nonceKey = AbstractDatabaseRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE; + $codeKeys = [ + ProtocolCache::keyFor(...$codeEntryKey), + ProtocolCache::keyFor(...$authCodeRepository->getGuardCacheKeyElements($codeId)), + ]; + + match ($case) { + 'replayed' => $authCodeRepository->recordAuthCodeReplay($codeId, $deadline), + 'code entry evicted' => $this->protocolCache->delete(...$codeEntryKey), + 'guard evicted' => $this->protocolCache->delete(...$authCodeRepository->getGuardCacheKeyElements($codeId)), + 'token entry evicted' => $this->protocolCache->delete($tokenKey), + 'token revoked' => $sut->revokeAccessToken($tokenId), + 'reads failing' => $this->cacheAdapter->missReads = true, + 'code consumed by another request' => $this->protocolCache->set( + [$nonceKey => 'another'] + $codeEntry, + 600, + ...$codeEntryKey, + ), + 'token without a nonce' => $this->protocolCache->set( + array_diff_key($tokenEntry, [$nonceKey => true]), + 600, + $tokenKey, + ), + 'token with another nonce' => $this->protocolCache->set( + [$nonceKey => 'another'] + $tokenEntry, + 600, + $tokenKey, + ), + 'empty nonces' => [ + $this->protocolCache->set([$nonceKey => ''] + $tokenEntry, 600, $tokenKey), + $this->protocolCache->set([$nonceKey => ''] + $codeEntry, 600, ...$codeEntryKey), + ], + 'code not consumed' => $this->protocolCache->set( + [AuthCodeRepository::KEY_CACHE_ONLY_STATUS => AuthCodeRepository::STATUS_ISSUED] + $codeEntry, + 600, + ...$codeEntryKey, + ), + // The token's entry read and found, then the replay recorded before the code's guard is read. + 'replayed during the check' => $this->cacheAdapter->beforeRead = function (string $key) use ( + $codeKeys, + $authCodeRepository, + $codeId, + $deadline, + ): void { + if ($key === $codeKeys[0]) { + $this->cacheAdapter->beforeRead = null; + $authCodeRepository->recordAuthCodeReplay($codeId, $deadline); + } + }, + // The token's entry is read; the code's entries are not. + 'code reads failing' => $this->cacheAdapter->beforeRead = function (string $key) use ($codeKeys): void { + $this->cacheAdapter->missReads = in_array($key, $codeKeys, true); + }, + }; + + $this->assertNull($sut->findById($tokenId)); + $this->assertTrue($sut->isAccessTokenRevoked($tokenId)); + // And in a later request. + [$laterSut] = $this->cacheOnlyRequest(); + $this->assertTrue($laterSut->isAccessTokenRevoked($tokenId)); + } + + /** + * Two requests redeem the same code at once: each draws its own nonce, the one which lost the code never gets a + * valid token, and its replay branch invalidates the winner's. + */ + public function testTokensOfARequestWhichLostTheCodeAreNeverValidAndItsReplayInvalidatesTheWinners(): void + { + [$winner, $winnerCodes, $winnerContext] = $this->cacheOnlyRequest(); + [$loser, $loserCodes, $loserContext] = $this->cacheOnlyRequest(); + [$codeId, $deadline] = $this->issueCode($winnerCodes); + $winnerNonce = $this->beginRedemption($winnerCodes, $winnerContext, $codeId); + $loserNonce = $this->beginRedemption($loserCodes, $loserContext, $codeId); + $this->assertNotSame($winnerNonce, $loserNonce); + $winnerToken = $this->newAccessToken($codeId); + $loserToken = $this->newAccessToken($codeId); + $winner->persistNewAccessToken($winnerToken); + $loser->persistNewAccessToken($loserToken); + $expiry = $winnerToken->getExpiryDateTime()->getTimestamp(); + + $this->assertTrue($winnerCodes->consumeAuthCode($codeId, $deadline, $expiry)); + $this->assertFalse($loserCodes->consumeAuthCode($codeId, $deadline, $expiry)); + + $this->assertFalse($winner->isAccessTokenRevoked((string)$winnerToken->getIdentifier())); + $this->assertTrue($winner->isAccessTokenRevoked((string)$loserToken->getIdentifier())); + + $loserCodes->recordAuthCodeReplay($codeId, $deadline); + + $this->assertTrue($winner->isAccessTokenRevoked((string)$winnerToken->getIdentifier())); + $this->assertTrue($loser->isAccessTokenRevoked((string)$loserToken->getIdentifier())); + } + + public function testCacheOnlyTokenForACodeWithoutAnIssuanceNonceIsAServerError(): void + { + [$sut, $authCodeRepository] = $this->cacheOnlyRequest(); + [$codeId] = $this->issueCode($authCodeRepository); + $accessToken = $this->newAccessToken($codeId); + + try { + $sut->persistNewAccessToken($accessToken); + $this->fail('A token for a code was stored without an issuance nonce.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + + $this->assertNull($this->entryOf($sut, (string)$accessToken->getIdentifier())); + $this->assertNull($this->rowOf((string)$accessToken->getIdentifier())); + } + + public function testCacheOnlyTokenWithoutACodeDependsOnItsOwnEntryOnly(): void + { + [$sut] = $this->cacheOnlyRequest(); + $accessToken = $this->newAccessToken(null); + $tokenId = (string)$accessToken->getIdentifier(); + + $sut->persistNewAccessToken($accessToken); + + $entry = $this->entryOf($sut, $tokenId); + $this->assertIsArray($entry); + $this->assertTrue($entry[AbstractDatabaseRepository::KEY_CACHE_ONLY]); + $this->assertArrayNotHasKey(AbstractDatabaseRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE, $entry); + $this->assertNull($this->rowOf($tokenId)); + $this->assertFalse($sut->isAccessTokenRevoked($tokenId)); + + $this->protocolCache->delete($sut->getCacheKey($tokenId)); + + $this->assertTrue($sut->isAccessTokenRevoked($tokenId)); + } + + public function testCacheOnlyRevocationKeepsTheMarkerAndTheNonce(): void + { + [$accessToken, $sut] = $this->redeemNewCode(); + $tokenId = (string)$accessToken->getIdentifier(); + $entryBefore = $this->entryOf($sut, $tokenId); + $this->assertIsArray($entryBefore); + + $sut->revokeAccessToken($tokenId); + + $expectedEntry = $entryBefore; + $expectedEntry['is_revoked'] = true; + $this->assertSame($expectedEntry, $this->entryOf($sut, $tokenId)); + $this->assertTrue($sut->isAccessTokenRevoked($tokenId)); + // An upper bound of the access token lifetime (PT1H plus three hours), plus the margin. + $this->assertEqualsWithDelta(3600 + 10800 + 60, $this->ttlOf($sut->getCacheKey($tokenId)), 2); + $this->assertNull($this->rowOf($tokenId)); + } + + public function testCacheOnlyRevocationFailsWhenItCanNotBeConfirmed(): void + { + [$accessToken, $sut] = $this->redeemNewCode(); + $this->cacheAdapter->dropWrites = true; + + $this->expectException(OidcServerException::class); + + $sut->revokeAccessToken((string)$accessToken->getIdentifier()); + } + + public function testCacheOnlyLookupsWriteNothing(): void + { + [$accessToken, $sut] = $this->redeemNewCode(); + $savedKeys = $this->cacheAdapter->savedKeys; + + $sut->findById((string)$accessToken->getIdentifier()); + $sut->isAccessTokenRevoked((string)$accessToken->getIdentifier()); + + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + /** + * A code with a database row, issued before codes were kept in the cache only. + */ + protected function issueCodeWithARow(): string + { + $moduleConfig = $this->createStub(ModuleConfig::class); + $helpers = new Helpers(); + $codesInTheDatabase = new AuthCodeRepository( + $moduleConfig, + $this->database, + null, + $this->clientRepositoryMock, + new AuthCodeEntityFactory($helpers, new ScopeEntityFactory()), + $helpers, + new IssuanceContext(), + null, + ); + $codeId = 'code_with_a_row_' . bin2hex(random_bytes(16)); + $codesInTheDatabase->persistNewAuthCode(new AuthCodeEntity( + $codeId, + $this->codeClient(), + [new ScopeEntity('openid')], + new DateTimeImmutable('+10 minutes'), + 'user123', + 'http://localhost/redirect', + 'oidc-nonce', + )); + + return $codeId; + } + + public function testTokenForACodeWithARowIsStoredInTheDatabaseAndNotCached(): void + { + $codeId = $this->issueCodeWithARow(); + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest(); + $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId); + $tokenId = (string)$accessToken->getIdentifier(); + + $sut->persistNewAccessToken($accessToken); + + $this->assertNotNull($this->rowOf($tokenId)); + $this->assertNull($this->entryOf($sut, $tokenId)); + $this->assertFalse($sut->isAccessTokenRevoked($tokenId)); + } + + public function testTokenForACodeThisRequestDoesNotKnowFollowsTheCodesCacheKeys(): void + { + [, $issuingCodes] = $this->cacheOnlyRequest(); + [$codeId] = $this->issueCode($issuingCodes); + [$sut, , $context] = $this->cacheOnlyRequest(); + $context->begin(); + $accessToken = $this->newAccessToken($codeId); + $sut->persistNewAccessToken($accessToken); + $unknownCodeToken = $this->newAccessToken('code_found_nowhere_' . bin2hex(random_bytes(8))); + $sut->persistNewAccessToken($unknownCodeToken); + + $entry = $this->entryOf($sut, (string)$accessToken->getIdentifier()); + $this->assertIsArray($entry); + $this->assertTrue($entry[AbstractDatabaseRepository::KEY_CACHE_ONLY]); + $this->assertNull($this->rowOf((string)$accessToken->getIdentifier())); + // A code found in neither the request's memory nor the cache is taken to have a row. + $this->assertNotNull($this->rowOf((string)$unknownCodeToken->getIdentifier())); + $this->assertNull($this->entryOf($sut, (string)$unknownCodeToken->getIdentifier())); + } + + /** + * A factory whose entities answer their state as hydrated, revoked once revoke() was called on them. + */ + protected function revocableAccessTokenEntityFactory(): AccessTokenEntityFactory + { + $accessTokenEntityFactory = $this->createStub(AccessTokenEntityFactory::class); + $accessTokenEntityFactory->method('fromState')->willReturnCallback( + function (array $state): AccessTokenEntity { + // A row as fetched has numeric keys too. + $state = array_filter($state, 'is_string', ARRAY_FILTER_USE_KEY); + unset($state['client']); + $accessToken = $this->createStub(AccessTokenEntity::class); + $accessToken->method('revoke')->willReturnCallback(function () use (&$state): void { + $state['is_revoked'] = true; + }); + $accessToken->method('getState')->willReturnCallback(function () use (&$state): array { + return $state; + }); + $accessToken->method('getIdentifier')->willReturn($state['id']); + $accessToken->method('isRevoked')->willReturnCallback(fn(): bool => (bool)$state['is_revoked']); + + return $accessToken; + }, + ); + + return $accessTokenEntityFactory; + } + + public function testPromotionUnmarksTheEntryThenInsertsTheRow(): void + { + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest( + accessTokenEntityFactory: $this->revocableAccessTokenEntityFactory(), + ); + [$codeId] = $this->issueCode($authCodeRepository); + $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId); + $tokenId = (string)$accessToken->getIdentifier(); + $sut->persistNewAccessToken($accessToken); + $rowsWhenUnmarked = []; + $this->cacheAdapter->afterSave = function () use ($tokenId, &$rowsWhenUnmarked): void { + $rowsWhenUnmarked[] = $this->rowOf($tokenId); + }; + + // As the grant does, before it consumes the code. + $sut->ensureStoredInDatabase($accessToken); + + $this->cacheAdapter->afterSave = null; + $this->assertSame([null], $rowsWhenUnmarked); + $this->assertNotNull($this->rowOf($tokenId)); + $this->assertSame($accessToken->getState(), $this->entryOf($sut, $tokenId)); + $this->assertEqualsWithDelta(3600 + 10800 + 60, $this->ttlOf($sut->getCacheKey($tokenId)), 2); + // Remembered as promoted: a second call inserts nothing (a second INSERT would fail). + $sut->ensureStoredInDatabase($accessToken); + // Backed by the database from now on: its revocation goes to the row, and the cache is not written. + $this->assertFalse($sut->isAccessTokenRevoked($tokenId)); + $savedKeys = $this->cacheAdapter->savedKeys; + $sut->revokeAccessToken($tokenId); + $this->assertTrue((bool)$this->rowOf($tokenId)['is_revoked']); + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + $this->assertTrue($sut->isAccessTokenRevoked($tokenId)); + } + + public function testPromotionOfATokenWithoutACode(): void + { + [$sut] = $this->cacheOnlyRequest(); + $accessToken = $this->newAccessToken(null); + $sut->persistNewAccessToken($accessToken); + + $sut->ensureStoredInDatabase($accessToken); + + $this->assertNotNull($this->rowOf((string)$accessToken->getIdentifier())); + $this->assertSame($accessToken->getState(), $this->entryOf($sut, (string)$accessToken->getIdentifier())); + } + + public function testPromotionAfterTheEntryWasEvicted(): void + { + [$accessToken, $sut] = $this->redeemNewCode(); + $tokenId = (string)$accessToken->getIdentifier(); + $this->protocolCache->delete($sut->getCacheKey($tokenId)); + + $sut->ensureStoredInDatabase($accessToken); + + $this->assertNotNull($this->rowOf($tokenId)); + $this->assertSame($accessToken->getState(), $this->entryOf($sut, $tokenId)); + } + + public function testPromotionOfATokenWithARowDoesNothing(): void + { + $codeId = $this->issueCodeWithARow(); + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest(); + $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId); + $sut->persistNewAccessToken($accessToken); + $savedKeys = $this->cacheAdapter->savedKeys; + + // Known to this request as backed by the database. + $sut->ensureStoredInDatabase($accessToken); + // Not known to another request, which finds the row. + [$anotherRequest] = $this->cacheOnlyRequest(); + $anotherRequest->ensureStoredInDatabase($accessToken); + + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + /** + * A token another request stored in the cache only is in use, valid or not: its promotion could race its + * revocation, or a replay of its code, and undo it. Looking it up does not make it this request's own. + */ + public function testPromotionOfATokenAnotherRequestStoredInTheCacheOnlyIsRefused(): void + { + [$accessToken] = $this->redeemNewCode(); + $tokenId = (string)$accessToken->getIdentifier(); + [$sut] = $this->cacheOnlyRequest(); + $this->assertNotNull($sut->findById($tokenId)); + + try { + $sut->ensureStoredInDatabase($accessToken); + $this->fail('Another request\'s token was promoted.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + + $this->assertNull($this->rowOf($tokenId)); + $entry = $this->entryOf($sut, $tokenId); + $this->assertIsArray($entry); + $this->assertTrue($entry[AbstractDatabaseRepository::KEY_CACHE_ONLY]); + $this->assertFalse($sut->isAccessTokenRevoked($tokenId)); + } + + public static function revocationOutcomeProvider(): array + { + return [ + 'revoked' => [false], + 'revoked, its read-back missed' => [true], + ]; + } + + /** + * Promoting the caller's stale entity of a token this request revoked would undo the revocation; so would + * promoting it after a revocation which landed but whose read-back missed. + */ + #[DataProvider('revocationOutcomeProvider')] + public function testPromotionOfATokenThisRequestRevokedIsRefused(bool $isReadBackMissed): void + { + [$sut] = $this->cacheOnlyRequest(); + $accessToken = $this->newAccessToken(null); + $tokenId = (string)$accessToken->getIdentifier(); + $sut->persistNewAccessToken($accessToken); + if ($isReadBackMissed) { + $this->cacheAdapter->afterSave = function (): void { + $this->cacheAdapter->afterSave = null; + $this->cacheAdapter->missReads = true; + }; + try { + $sut->revokeAccessToken($tokenId); + $this->fail('A revocation whose read-back missed reported success.'); + } catch (OidcServerException) { + // The revocation landed; the caller does not know. + } + $this->cacheAdapter->missReads = false; + } else { + $sut->revokeAccessToken($tokenId); + } + + try { + $sut->ensureStoredInDatabase($accessToken); + $this->fail('A revoked token was promoted.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + + $this->assertNull($this->rowOf($tokenId)); + $this->assertTrue($sut->isAccessTokenRevoked($tokenId)); + } + + public function testPromotionOfATokenFoundNowhereIsAServerError(): void + { + [$sut] = $this->cacheOnlyRequest(); + + $this->expectException(OidcServerException::class); + + $sut->ensureStoredInDatabase($this->newAccessToken(null)); + } + + /** + * The entry is unmarked first: a failed INSERT leaves a token which is not valid, rather than a row behind a + * marked entry. + */ + public function testPromotionWhoseInsertFailsIsAServerErrorAndLeavesTheTokenInvalid(): void + { + $realDatabase = $this->database; + $database = $this->createMock(Database::class); + $database->method('applyPrefix')->willReturnCallback(fn(string $table): string => "phpunit_$table"); + $database->method('read')->willReturnCallback( + fn(string $statement, array $parameters) => $realDatabase->read($statement, $parameters), + ); + $database->method('write')->willThrowException(new Exception('The database is down.')); + [$sut] = $this->cacheOnlyRequest(database: $database); + $accessToken = $this->newAccessToken(null); + $tokenId = (string)$accessToken->getIdentifier(); + $sut->persistNewAccessToken($accessToken); + $this->assertFalse($sut->isAccessTokenRevoked($tokenId)); + + try { + $sut->ensureStoredInDatabase($accessToken); + $this->fail('A failed promotion went unreported.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + + $this->assertNull($this->rowOf($tokenId)); + $this->assertSame($accessToken->getState(), $this->entryOf($sut, $tokenId)); + $this->assertTrue($sut->isAccessTokenRevoked($tokenId)); + } + + public function testPromotionWhoseUnmarkingCanNotBeConfirmedIsAServerErrorAndInsertsNoRow(): void + { + [$sut] = $this->cacheOnlyRequest(); + $accessToken = $this->newAccessToken(null); + $sut->persistNewAccessToken($accessToken); + $this->cacheAdapter->dropWrites = true; + + try { + $sut->ensureStoredInDatabase($accessToken); + $this->fail('A failed promotion went unreported.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + + $this->assertNull($this->rowOf((string)$accessToken->getIdentifier())); + } + + /** + * A marked entry missed by a failed read must not be taken for a token with a row, whose UPDATE would change + * nothing and report success. + */ + public function testRevocationOfATokenKeptInTheCacheOnlyFailsWhenItsEntryCanNotBeRead(): void + { + [$accessToken, $sut] = $this->redeemNewCode(); + $tokenId = (string)$accessToken->getIdentifier(); + $entryKey = ProtocolCache::keyFor($sut->getCacheKey($tokenId)); + $readsOfTheEntry = 0; + $this->cacheAdapter->beforeRead = function (string $key) use ($entryKey, &$readsOfTheEntry): void { + // The first read of the entry misses; a later one would find it. + $this->cacheAdapter->missReads = $key === $entryKey && ++$readsOfTheEntry === 1; + }; + + try { + $sut->revokeAccessToken($tokenId); + $this->fail('A revocation which changed nothing reported success.'); + } catch (\RuntimeException $exception) { + // Not found, so not revoked: the caller learns it. + $this->assertSame("AccessToken not found: $tokenId", $exception->getMessage()); + } + + $this->cacheAdapter->beforeRead = null; + $this->cacheAdapter->missReads = false; + $entry = $this->entryOf($sut, $tokenId); + $this->assertIsArray($entry); + $this->assertFalse($entry['is_revoked']); + // Its revocation was attempted, so it is no longer promoted by this request. + try { + $sut->ensureStoredInDatabase($accessToken); + $this->fail('A token whose revocation was attempted was promoted.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + $this->assertNull($this->rowOf($tokenId)); + } + + public function testPromotionDoesNothingUnlessAccessTokensAreKeptInTheCacheOnly(): void + { + $database = $this->createMock(Database::class); + $database->expects($this->never())->method('write'); + $database->expects($this->never())->method('read'); + [$sut] = $this->cacheOnlyRequest(areAccessTokensCacheOnly: false, database: $database); + + $sut->ensureStoredInDatabase($this->newAccessToken(null)); + + $this->assertSame([], $this->cacheAdapter->savedKeys); + } + + public function testRevokeByAuthCodeIdWhileAccessTokensAreKeptInTheCacheOnlyIsOneUpdateOnThePrimary(): void + { + $database = $this->createMock(Database::class); + $database->method('applyPrefix')->willReturnCallback(fn(string $table): string => "phpunit_$table"); + $database->expects($this->once())->method('write')->with( + $this->stringStartsWith('UPDATE phpunit_oidc_access_token SET is_revoked'), + $this->callback(fn(array $parameters): bool => $parameters['auth_code_id'] === 'replayed_code'), + ); + $database->expects($this->never())->method('read'); + [$sut] = $this->cacheOnlyRequest(database: $database); + + $sut->revokeByAuthCodeId('replayed_code'); + + $this->assertSame([], $this->cacheAdapter->savedKeys); + } + + public function testRevokeAllByAuthCodeIdWritesNoCachedCopiesWhileAccessTokensAreKeptInTheCacheOnly(): void + { + $codeId = $this->issueCodeWithARow(); + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest(); + $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId); + $sut->persistNewAccessToken($accessToken); + $savedKeys = $this->cacheAdapter->savedKeys; + + $sut->revokeAllByAuthCodeId($codeId); + + $this->assertTrue((bool)$this->rowOf((string)$accessToken->getIdentifier())['is_revoked']); + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + /** + * While access tokens are kept in the cache only, a cached copy of a token with a row is no longer kept current: + * a stale unrevoked copy must not hide the row's revocation. + */ + public function testTokenWithARowIsNotTrustedFromTheCacheWhileAccessTokensAreKeptInTheCacheOnly(): void + { + $codeId = $this->issueCodeWithARow(); + $hydratedStates = []; + $accessTokenEntityFactory = $this->createMock(AccessTokenEntityFactory::class); + $accessTokenEntityFactory->method('fromState')->willReturnCallback( + function (array $state) use (&$hydratedStates): AccessTokenEntity { + $hydratedStates[] = $state; + return $this->accessTokenEntityMock; + }, + ); + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest( + accessTokenEntityFactory: $accessTokenEntityFactory, + ); + $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId); + $tokenId = (string)$accessToken->getIdentifier(); + $sut->persistNewAccessToken($accessToken); + $this->protocolCache->set($accessToken->getState(), 600, $sut->getCacheKey($tokenId)); + $this->database->write( + 'UPDATE phpunit_oidc_access_token SET is_revoked = :is_revoked WHERE id = :id', + ['is_revoked' => [true, \PDO::PARAM_BOOL], 'id' => $tokenId], + ); + $savedKeys = $this->cacheAdapter->savedKeys; + + $sut->findById($tokenId); + + $this->assertCount(1, $hydratedStates); + $this->assertTrue((bool)$hydratedStates[0]['is_revoked']); + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + /** + * With authorization codes alone in the cache only, a cached copy of a token is trusted as before. + */ + public function testTokenWithARowIsTrustedFromTheCacheWithCodesAloneKeptInTheCacheOnly(): void + { + $codeId = $this->issueCodeWithARow(); + $hydratedStates = []; + $accessTokenEntityFactory = $this->createMock(AccessTokenEntityFactory::class); + $accessTokenEntityFactory->method('fromState')->willReturnCallback( + function (array $state) use (&$hydratedStates): AccessTokenEntity { + $hydratedStates[] = $state; + return $this->accessTokenEntityMock; + }, + ); + [$sut, $authCodeRepository, $context] = $this->cacheOnlyRequest( + areAccessTokensCacheOnly: false, + accessTokenEntityFactory: $accessTokenEntityFactory, + ); + $this->beginRedemption($authCodeRepository, $context, $codeId); + $accessToken = $this->newAccessToken($codeId); + $tokenId = (string)$accessToken->getIdentifier(); + + $sut->persistNewAccessToken($accessToken); + + $this->assertNotNull($this->rowOf($tokenId)); + $this->assertSame($accessToken->getState(), $this->entryOf($sut, $tokenId)); + // The row and its cached copy disagree: the copy is trusted, as before. + $this->database->write( + 'UPDATE phpunit_oidc_access_token SET is_revoked = :is_revoked WHERE id = :id', + ['is_revoked' => [true, \PDO::PARAM_BOOL], 'id' => $tokenId], + ); + $sut->findById($tokenId); + $this->assertCount(1, $hydratedStates); + $this->assertFalse($hydratedStates[0]['is_revoked']); + } } diff --git a/tests/unit/src/Repositories/AuthCodeRepositoryTest.php b/tests/unit/src/Repositories/AuthCodeRepositoryTest.php index 966ed1888..433c55678 100644 --- a/tests/unit/src/Repositories/AuthCodeRepositoryTest.php +++ b/tests/unit/src/Repositories/AuthCodeRepositoryTest.php @@ -15,26 +15,42 @@ */ namespace SimpleSAML\Test\Module\oidc\unit\Repositories; +use DateInterval; use DateTimeImmutable; use DateTimeZone; use Exception; use League\OAuth2\Server\Entities\AuthCodeEntityInterface; +use League\OAuth2\Server\Exception\OAuthServerException; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use ReflectionProperty; use SimpleSAML\Configuration; use SimpleSAML\Database; use SimpleSAML\Error\Error; use SimpleSAML\Module\oidc\Codebooks\DateFormatsEnum; +use SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum; use SimpleSAML\Module\oidc\Entities\AuthCodeEntity; use SimpleSAML\Module\oidc\Entities\ClientEntity; use SimpleSAML\Module\oidc\Entities\ScopeEntity; use SimpleSAML\Module\oidc\Factories\Entities\AuthCodeEntityFactory; +use SimpleSAML\Module\oidc\Factories\Entities\ScopeEntityFactory; use SimpleSAML\Module\oidc\Helpers; use SimpleSAML\Module\oidc\ModuleConfig; use SimpleSAML\Module\oidc\Repositories\AuthCodeRepository; use SimpleSAML\Module\oidc\Repositories\ClientRepository; +use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; use SimpleSAML\Module\oidc\Services\DatabaseMigration; +use SimpleSAML\Module\oidc\Utils\ConsumptionGate; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; use SimpleSAML\Module\oidc\Utils\ProtocolCache; +use SimpleSAML\Test\Module\oidc\unit\Utils\FaultyArrayAdapter; +use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\Cache\Psr16Cache; +use Symfony\Component\Lock\Exception\LockStorageException; +use Symfony\Component\Lock\Key; +use Symfony\Component\Lock\PersistingStoreInterface; +use Symfony\Component\Lock\Store\InMemoryStore; /** * @covers \SimpleSAML\Module\oidc\Repositories\AuthCodeRepository @@ -56,6 +72,11 @@ class AuthCodeRepositoryTest extends TestCase protected MockObject $dateTimeHelperMock; /** @var \League\OAuth2\Server\Entities\ScopeEntityInterface[] */ protected array $scopes; + protected FaultyArrayAdapter $cacheAdapter; + protected ProtocolCache $protocolCache; + protected InMemoryStore $lockStore; + protected IssuanceContext $issuanceContext; + protected string $defaultTimezone; /** * @throws \Exception @@ -77,6 +98,7 @@ public static function setUpBeforeClass(): void protected function setUp(): void { + $this->defaultTimezone = date_default_timezone_get(); $this->moduleConfigMock = $this->createMock(ModuleConfig::class); $this->protocolCacheMock = $this->createMock(ProtocolCache::class); @@ -102,7 +124,119 @@ protected function setUp(): void $this->clientRepositoryMock, $this->authCodeEntityFactoryMock, $this->helpersMock, + new IssuanceContext(), + null, ); + + $this->cacheAdapter = new FaultyArrayAdapter(); + $this->protocolCache = new ProtocolCache(new Psr16Cache($this->cacheAdapter)); + $this->lockStore = new InMemoryStore(); + $this->issuanceContext = new IssuanceContext(); + } + + protected function tearDown(): void + { + date_default_timezone_set($this->defaultTimezone); + } + + /** + * A repository on a real protocol cache and lock store, with authorization codes kept in the cache only, or in + * the database. + */ + protected function sut( + bool $isCacheOnly = true, + ?PersistingStoreInterface $lockStore = null, + ?IssuanceContext $issuanceContext = null, + ?Database $database = null, + ): AuthCodeRepository { + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturnCallback( + fn(ProtocolArtifactEnum $artifact): bool => $isCacheOnly && + $artifact === ProtocolArtifactEnum::AuthorizationCode, + ); + $moduleConfig->method('getAccessTokenDuration')->willReturn(new DateInterval('PT1H')); + $moduleConfig->method('getAuthCodeDuration')->willReturn(new DateInterval('PT10M')); + + $helpers = new Helpers(); + + return new AuthCodeRepository( + $moduleConfig, + $database ?? Database::getInstance(), + $this->protocolCache, + $this->clientRepositoryMock, + new AuthCodeEntityFactory($helpers, new ScopeEntityFactory()), + $helpers, + $issuanceContext ?? $this->issuanceContext, + new ConsumptionGate($lockStore ?? $this->lockStore), + ); + } + + protected function newAuthCode(?string $id = null, string $expiry = '+10 minutes'): AuthCodeEntity + { + return new AuthCodeEntity( + $id ?? bin2hex(random_bytes(20)), + $this->clientEntityMock, + $this->scopes, + new DateTimeImmutable($expiry), + self::USER_ID, + self::REDIRECT_URI, + 'oidc-nonce', + ); + } + + protected function entry(AuthCodeRepository $sut, string $codeId): mixed + { + return $this->protocolCache->get(null, ...$sut->getEntryCacheKeyElements($codeId)); + } + + protected function guard(AuthCodeRepository $sut, string $codeId): mixed + { + return $this->protocolCache->get(null, ...$sut->getGuardCacheKeyElements($codeId)); + } + + /** + * Seconds until the cache entry expires, as the array adapter stores it. + */ + protected function ttlOf(array $keyElements): int + { + $expiries = (new ReflectionProperty(ArrayAdapter::class, 'expiries'))->getValue($this->cacheAdapter); + $this->assertIsArray($expiries); + $expiry = $expiries[ProtocolCache::keyFor(...$keyElements)] ?? null; + $this->assertIsFloat($expiry); + + return (int)round($expiry - microtime(true)); + } + + protected function rowOf(string $codeId): ?array + { + $rows = Database::getInstance()->read( + 'SELECT * FROM phpunit_oidc_auth_code WHERE id = :id', + ['id' => $codeId], + )->fetchAll(); + + return empty($rows) ? null : (array)current($rows); + } + + /** + * Persists a code in the cache only and begins a request's issuance context. + */ + protected function issueCacheOnly(?AuthCodeRepository $sut = null): AuthCodeEntity + { + $authCode = $this->newAuthCode(); + ($sut ?? $this->sut())->persistNewAuthCode($authCode); + $this->issuanceContext->begin(); + + return $authCode; + } + + protected function assertOAuthError(string $errorType, callable $callable): void + { + try { + $callable(); + $this->fail("Expected the $errorType error."); + } catch (OAuthServerException $exception) { + $this->assertSame($errorType, $exception->getErrorType()); + } } public function testGetTableName(): void @@ -241,4 +375,858 @@ public function testPersistNewAuthCodeThrowsIfNotAuthCodeEntity(): void $this->createMock(AuthCodeEntityInterface::class), ); } + + /** + * A lock store which claims through the given store, then runs the callback: what another request, or an + * eviction, does between this request's claim and its next read. + */ + protected function lockStoreRunningAfterClaim(callable $afterClaim): PersistingStoreInterface + { + return new class ($this->lockStore, $afterClaim) implements PersistingStoreInterface { + /** @var callable */ + private $afterClaim; + + public function __construct(private readonly InMemoryStore $inner, callable $afterClaim) + { + $this->afterClaim = $afterClaim; + } + + public function save(Key $key): void + { + $this->inner->save($key); + ($this->afterClaim)(); + } + + public function delete(Key $key): void + { + $this->inner->delete($key); + } + + public function exists(Key $key): bool + { + return $this->inner->exists($key); + } + + public function putOffExpiration(Key $key, float $ttl): void + { + $this->inner->putOffExpiration($key, $ttl); + } + }; + } + + // Cache-only mode: issuance. + + public function testCacheOnlyPersistWritesTheGuardThenTheMarkedEntryAndNoRow(): void + { + $sut = $this->sut(); + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + + $sut->persistNewAuthCode($authCode); + + $entry = $this->entry($sut, $codeId); + $this->assertIsArray($entry); + $this->assertTrue($entry[AuthCodeRepository::KEY_CACHE_ONLY]); + $this->assertSame(AuthCodeRepository::STATUS_ISSUED, $entry[AuthCodeRepository::KEY_CACHE_ONLY_STATUS]); + $this->assertArrayNotHasKey(AuthCodeRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE, $entry); + $this->assertSame($authCode->getState(), array_intersect_key($entry, $authCode->getState())); + $this->assertSame(AuthCodeRepository::GUARD_CLEAN, $this->guard($sut, $codeId)); + $this->assertSame( + [ + ProtocolCache::keyFor(...$sut->getGuardCacheKeyElements($codeId)), + ProtocolCache::keyFor(...$sut->getEntryCacheKeyElements($codeId)), + ], + $this->cacheAdapter->savedKeys, + ); + $this->assertNull($this->rowOf($codeId)); + } + + public static function timezoneProvider(): array + { + return [['UTC'], ['America/New_York'], ['Antarctica/Troll']]; + } + + #[DataProvider('timezoneProvider')] + public function testCacheOnlyPersistTakesTheTtlsFromTheExpiryInMemory(string $timezone): void + { + date_default_timezone_set($timezone); + $sut = $this->sut(); + $authCode = $this->newAuthCode(null, '+600 seconds'); + $codeId = $authCode->getIdentifier(); + + $sut->persistNewAuthCode($authCode); + + // The code's remaining lifetime plus the margin; the guard adds a bound of the access token lifetime. + $this->assertEqualsWithDelta(600 + 60, $this->ttlOf($sut->getEntryCacheKeyElements($codeId)), 2); + $this->assertEqualsWithDelta( + 600 + 3600 + 3 * 3600 + 60, + $this->ttlOf($sut->getGuardCacheKeyElements($codeId)), + 2, + ); + } + + public function testCacheOnlyPersistFailsWhenAWriteCanNotBeConfirmed(): void + { + $this->cacheAdapter->dropWrites = true; + + $this->assertOAuthError('server_error', fn() => $this->sut()->persistNewAuthCode($this->newAuthCode())); + } + + public function testCacheOnlyPersistFailsWithoutAProtocolCache(): void + { + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturn(true); + $sut = new AuthCodeRepository( + $moduleConfig, + Database::getInstance(), + null, + $this->clientRepositoryMock, + $this->authCodeEntityFactoryMock, + new Helpers(), + $this->issuanceContext, + null, + ); + + $this->assertOAuthError('server_error', fn() => $sut->persistNewAuthCode($this->newAuthCode())); + } + + // Reads. + + public function testCacheOnlyFindByIdTrustsTheMarkedEntryAndWritesNothing(): void + { + $sut = $this->sut(); + $authCode = $this->newAuthCode(); + $sut->persistNewAuthCode($authCode); + $savedKeys = $this->cacheAdapter->savedKeys; + + $found = $this->sut()->findById($authCode->getIdentifier()); + + $this->assertInstanceOf(AuthCodeEntity::class, $found); + $this->assertSame($authCode->getIdentifier(), $found->getIdentifier()); + $this->assertFalse($found->isRevoked()); + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + public function testCacheOnlyFindByIdDoesNotTrustAnUnmarkedCopyAndWritesNothing(): void + { + $authCode = $this->newAuthCode(); + $this->sut(false)->persistNewAuthCode($authCode); + // A stale copy, which the cache would answer. + $staleState = $authCode->getState(); + $staleState['is_revoked'] = true; + $this->protocolCache->set( + $staleState, + 600, + ...$this->sut()->getEntryCacheKeyElements($authCode->getIdentifier()), + ); + $savedKeys = $this->cacheAdapter->savedKeys; + + $found = $this->sut()->findById($authCode->getIdentifier()); + + $this->assertInstanceOf(AuthCodeEntity::class, $found); + $this->assertFalse($found->isRevoked()); + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + public function testDatabaseModeFindByIdDoesNotWriteACacheHitBack(): void + { + $authCode = $this->newAuthCode(); + $this->sut(false)->persistNewAuthCode($authCode); + $savedKeys = $this->cacheAdapter->savedKeys; + + $this->assertInstanceOf(AuthCodeEntity::class, $this->sut(false)->findById($authCode->getIdentifier())); + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + public function testDatabaseModeFindByIdCachesARowFoundOnAMiss(): void + { + $authCode = $this->newAuthCode(); + $this->sut(false)->persistNewAuthCode($authCode); + $this->protocolCache->delete(...$this->sut()->getEntryCacheKeyElements($authCode->getIdentifier())); + $savedKeys = $this->cacheAdapter->savedKeys; + + $this->assertInstanceOf(AuthCodeEntity::class, $this->sut(false)->findById($authCode->getIdentifier())); + $this->assertCount(count($savedKeys) + 1, $this->cacheAdapter->savedKeys); + } + + public function testDatabaseModePersistKeepsTheRowAndTheCacheCopyAsBefore(): void + { + $authCode = $this->newAuthCode(); + $sut = $this->sut(false); + + $sut->persistNewAuthCode($authCode); + + $this->assertNotNull($this->rowOf($authCode->getIdentifier())); + $this->assertSame($authCode->getState(), $this->entry($sut, $authCode->getIdentifier())); + $this->assertNull($this->guard($sut, $authCode->getIdentifier())); + } + + // The start check. + + public static function startCheckProvider(): array + { + $issued = AuthCodeRepository::STATUS_ISSUED; + $consumed = AuthCodeRepository::STATUS_CONSUMED; + $clean = AuthCodeRepository::GUARD_CLEAN; + $replayed = AuthCodeRepository::GUARD_REPLAYED; + + return [ + 'issued, clean' => [$issued, $clean, false], + 'issued, replayed' => [$issued, $replayed, true], + 'issued, guard gone' => [$issued, null, 'invalid_grant'], + 'consumed, clean' => [$consumed, $clean, true], + 'consumed, replayed' => [$consumed, $replayed, true], + 'consumed, guard gone' => [$consumed, null, true], + 'entry gone, clean' => [null, $clean, 'invalid_grant'], + 'entry gone, replayed' => [null, $replayed, true], + 'both gone' => [null, null, 'invalid_grant'], + ]; + } + + #[DataProvider('startCheckProvider')] + public function testCacheOnlyStartCheck(?string $status, ?string $guard, bool|string $expected): void + { + $sut = $this->sut(); + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + $sut->persistNewAuthCode($authCode); + + if ($status === null) { + $this->protocolCache->delete(...$sut->getEntryCacheKeyElements($codeId)); + } else { + $entry = (array)$this->entry($sut, $codeId); + $entry[AuthCodeRepository::KEY_CACHE_ONLY_STATUS] = $status; + $this->protocolCache->set($entry, 600, ...$sut->getEntryCacheKeyElements($codeId)); + } + + if ($guard === null) { + $this->protocolCache->delete(...$sut->getGuardCacheKeyElements($codeId)); + } else { + $this->protocolCache->set($guard, 600, ...$sut->getGuardCacheKeyElements($codeId)); + } + + $savedKeys = $this->cacheAdapter->savedKeys; + $check = fn(): bool => $this->sut()->isAuthCodeRevoked($codeId); + + if (is_string($expected)) { + $this->assertOAuthError($expected, $check); + } else { + $this->assertSame($expected, $check()); + } + + // The start check writes nothing, and takes no claim. + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + $this->assertTrue((new ConsumptionGate($this->lockStore))->claim($codeId)); + } + + public function testCacheOnlyStartCheckReadsTheRowOfACodeIssuedBeforeTheSwitch(): void + { + $unused = $this->newAuthCode(); + $used = $this->newAuthCode(); + $this->sut(false)->persistNewAuthCode($unused); + $this->sut(false)->persistNewAuthCode($used); + $this->sut(false)->revokeAuthCode($used->getIdentifier()); + // Copies cached in database mode are not trusted. + $this->protocolCache->set( + ['is_revoked' => true] + $unused->getState(), + 600, + ...$this->sut()->getEntryCacheKeyElements($unused->getIdentifier()), + ); + + $this->assertFalse($this->sut()->isAuthCodeRevoked($unused->getIdentifier())); + $this->assertTrue($this->sut()->isAuthCodeRevoked($used->getIdentifier())); + } + + public function testMissingCodeIsAnInvalidGrantInBothModes(): void + { + $this->assertOAuthError('invalid_grant', fn() => $this->sut()->isAuthCodeRevoked('no-such-code')); + $this->assertOAuthError('invalid_grant', fn() => $this->sut(false)->isAuthCodeRevoked('no-such-code')); + $this->assertOAuthError('invalid_grant', fn() => $this->sut()->consumeAuthCode('no-such-code', time() + 60)); + } + + // Consumption. + + public function testCacheOnlyConsumptionRecordsTheNonceAndRetainsTheEntryForTheAccessToken(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + $deadline = $authCode->getExpiryDateTime()->getTimestamp(); + $accessTokenExpiresAt = time() + 3600; + + $this->assertTrue($sut->consumeAuthCode($codeId, $deadline, $accessTokenExpiresAt)); + + $entry = $this->entry($sut, $codeId); + $this->assertIsArray($entry); + $this->assertSame(AuthCodeRepository::STATUS_CONSUMED, $entry[AuthCodeRepository::KEY_CACHE_ONLY_STATUS]); + $this->assertTrue($entry['is_revoked']); + $this->assertSame( + $this->issuanceContext->getNonce(), + $entry[AuthCodeRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE], + ); + $this->assertEqualsWithDelta(3600 + 60, $this->ttlOf($sut->getEntryCacheKeyElements($codeId)), 2); + $this->assertSame(AuthCodeRepository::GUARD_CLEAN, $this->guard($sut, $codeId)); + $this->assertTrue($this->sut()->isAuthCodeRevoked($codeId)); + } + + public function testCacheOnlyConsumptionKeepsTheEntryForTheCodeWhenItOutlivesTheAccessToken(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + + $this->assertTrue($sut->consumeAuthCode($codeId, time() + 600, time() + 60)); + + $this->assertEqualsWithDelta(600 + 60, $this->ttlOf($sut->getEntryCacheKeyElements($codeId)), 2); + } + + public function testCacheOnlyConsumptionNeedsAnIssuanceNonce(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $this->issuanceContext->end(); + + $this->assertOAuthError( + 'server_error', + fn() => $sut->consumeAuthCode($authCode->getIdentifier(), time() + 600), + ); + $this->assertTrue((new ConsumptionGate($this->lockStore))->claim($authCode->getIdentifier())); + } + + public function testTwoConsumptionsOfOneCodeOnlyOneWins(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + $otherContext = new IssuanceContext(); + $otherContext->begin(); + + $first = $this->sut()->consumeAuthCode($codeId, time() + 600); + $second = $this->sut(true, null, $otherContext)->consumeAuthCode($codeId, time() + 600); + + $this->assertTrue($first); + $this->assertFalse($second); + $entry = (array)$this->entry($this->sut(), $codeId); + $this->assertSame( + $this->issuanceContext->getNonce(), + $entry[AuthCodeRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE], + ); + } + + public function testCacheOnlyConsumptionAfterTheDeadlineWithoutEvidenceIsAnInvalidGrantWithoutAClaim(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + + $this->assertOAuthError('invalid_grant', fn() => $this->sut()->consumeAuthCode($codeId, time() - 1)); + $this->assertTrue((new ConsumptionGate($this->lockStore))->claim($codeId)); + } + + public function testCacheOnlyConsumptionAfterTheDeadlineWithEvidenceIsAReplay(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + $this->assertTrue($this->sut()->consumeAuthCode($codeId, time() + 600)); + + $this->assertFalse($this->sut()->consumeAuthCode($codeId, time() - 1)); + } + + public function testCacheOnlyConsumptionLostClaimIsAReplay(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + $this->assertTrue((new ConsumptionGate($this->lockStore))->claim($codeId)); + $savedKeys = $this->cacheAdapter->savedKeys; + + $this->assertFalse($this->sut()->consumeAuthCode($codeId, time() + 600)); + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + public function testCacheOnlyConsumptionGateFailureIsAServerError(): void + { + $authCode = $this->issueCacheOnly(); + $lockStore = $this->createStub(PersistingStoreInterface::class); + $lockStore->method('save')->willThrowException(new LockStorageException('backend failure')); + + $this->assertOAuthError( + 'server_error', + fn() => $this->sut(true, $lockStore)->consumeAuthCode($authCode->getIdentifier(), time() + 600), + ); + $this->assertSame( + AuthCodeRepository::STATUS_ISSUED, + ((array)$this->entry($this->sut(), $authCode->getIdentifier()))[AuthCodeRepository::KEY_CACHE_ONLY_STATUS], + ); + } + + public function testCacheOnlyConsumptionFindingAnotherConsumptionAfterItsClaimIsAReplay(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + // Another request consumed the code after this request's claim (its lock evicted, say). + $lockStore = $this->lockStoreRunningAfterClaim(function () use ($codeId): void { + $entry = (array)$this->entry($this->sut(), $codeId); + $entry[AuthCodeRepository::KEY_CACHE_ONLY_STATUS] = AuthCodeRepository::STATUS_CONSUMED; + $entry[AuthCodeRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE] = 'the other request'; + $this->protocolCache->set($entry, 600, ...$this->sut()->getEntryCacheKeyElements($codeId)); + }); + + $this->assertFalse($this->sut(true, $lockStore)->consumeAuthCode($codeId, time() + 600)); + $entry = (array)$this->entry($this->sut(), $codeId); + $this->assertSame('the other request', $entry[AuthCodeRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE]); + } + + public function testCacheOnlyConsumptionFindingAReplayAfterItsClaimIsAReplay(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + $lockStore = $this->lockStoreRunningAfterClaim(function () use ($codeId): void { + $this->protocolCache->set( + AuthCodeRepository::GUARD_REPLAYED, + 600, + ...$this->sut()->getGuardCacheKeyElements($codeId), + ); + }); + + $this->assertFalse($this->sut(true, $lockStore)->consumeAuthCode($codeId, time() + 600)); + $this->assertSame( + AuthCodeRepository::STATUS_ISSUED, + ((array)$this->entry($this->sut(), $codeId))[AuthCodeRepository::KEY_CACHE_ONLY_STATUS], + ); + } + + public static function lostAfterClaimProvider(): array + { + return [ + 'entry' => ['entry'], + 'guard' => ['guard'], + ]; + } + + #[DataProvider('lostAfterClaimProvider')] + public function testCacheOnlyConsumptionLosingAKeyAfterItsClaimIsAServerError(string $lostKey): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + $lockStore = $this->lockStoreRunningAfterClaim(function () use ($codeId, $lostKey): void { + $this->protocolCache->delete(...($lostKey === 'entry' ? + $this->sut()->getEntryCacheKeyElements($codeId) : + $this->sut()->getGuardCacheKeyElements($codeId))); + }); + + $this->assertOAuthError( + 'server_error', + fn() => $this->sut(true, $lockStore)->consumeAuthCode($codeId, time() + 600), + ); + } + + public function testCacheOnlyConsumptionWhoseDeadlinePassesDuringTheClaimIsAnInvalidGrant(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + // A second ahead, so the check before the claim passes even if the clock ticks before it runs. + $deadline = time() + 1; + $lockStore = $this->lockStoreRunningAfterClaim(function () use ($deadline): void { + while (time() <= $deadline) { + usleep(20000); + } + }); + + $this->assertOAuthError( + 'invalid_grant', + fn() => $this->sut(true, $lockStore)->consumeAuthCode($codeId, $deadline), + ); + // The claim spent the expired code. + $this->assertFalse((new ConsumptionGate($this->lockStore))->claim($codeId)); + } + + public function testCacheOnlyConsumptionWhoseWriteFailsIsAServerErrorAndARetryIsAReplay(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + $lockStore = $this->lockStoreRunningAfterClaim(function (): void { + $this->cacheAdapter->dropWrites = true; + }); + + $this->assertOAuthError( + 'server_error', + fn() => $this->sut(true, $lockStore)->consumeAuthCode($codeId, time() + 600), + ); + + $this->cacheAdapter->dropWrites = false; + $this->issuanceContext->begin(); + $this->assertFalse($this->sut()->consumeAuthCode($codeId, time() + 600)); + } + + /** + * The consumed entry lands, but its read-back misses: the recovery read finds this request's own consumption and + * a clean guard, which confirms it, so the request does not end in an error while its token is valid. + */ + public function testCacheOnlyConsumptionWhoseReadBackMissesButWhoseWriteLandedIsConfirmed(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + $issuanceNonce = (string)$this->issuanceContext->getNonce(); + $entryKey = ProtocolCache::keyFor(...$sut->getEntryCacheKeyElements($codeId)); + $this->cacheAdapter->afterSave = function (string $key) use ($entryKey): void { + if ($key !== $entryKey) { + return; + } + + $this->cacheAdapter->afterSave = null; + $reads = 0; + $this->cacheAdapter->beforeRead = function () use (&$reads): void { + // The write's own read-back misses; every later read is served. + $this->cacheAdapter->missReads = ++$reads === 1; + }; + }; + + $this->assertTrue($sut->consumeAuthCode($codeId, time() + 600)); + + $this->cacheAdapter->beforeRead = null; + $this->cacheAdapter->missReads = false; + $this->assertTrue($sut->isConsumedWithIssuanceNonce($codeId, $issuanceNonce)); + } + + /** + * After the recovery read confirmed this request's consumption, the final read still runs: a replay recorded in + * between is a replay, so that the caller revokes the tokens rather than returning them. + */ + public function testCacheOnlyConsumptionConfirmedByItsRecoveryReadStillFindsALaterReplay(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + $entryKey = ProtocolCache::keyFor(...$sut->getEntryCacheKeyElements($codeId)); + $this->cacheAdapter->afterSave = function (string $key) use ($sut, $codeId, $entryKey): void { + if ($key !== $entryKey) { + return; + } + + $this->cacheAdapter->afterSave = null; + $reads = 0; + $this->cacheAdapter->beforeRead = function () use ($sut, $codeId, &$reads): void { + $reads++; + // 1: the write's own read-back, which misses; 2 and 3: the recovery read of the entry and the guard; + // 4 and 5: the final read, before whose guard read a replay is recorded. + $this->cacheAdapter->missReads = $reads === 1; + if ($reads === 4) { + $this->cacheAdapter->beforeRead = null; + $this->protocolCache->set( + AuthCodeRepository::GUARD_REPLAYED, + 600, + ...$sut->getGuardCacheKeyElements($codeId), + ); + } + }; + }; + + $this->assertFalse($sut->consumeAuthCode($codeId, time() + 600)); + } + + /** + * Runs the callback once, after this request's consumed entry is written and read back, before the final read: + * what another request, or an eviction, does in between. + */ + protected function afterTheConsumedEntryIsWritten(AuthCodeRepository $sut, string $codeId, callable $then): void + { + $entryKey = ProtocolCache::keyFor(...$sut->getEntryCacheKeyElements($codeId)); + $this->cacheAdapter->afterSave = function (string $key) use ($entryKey, $then): void { + if ($key !== $entryKey) { + return; + } + + $this->cacheAdapter->afterSave = null; + $readsOfTheEntry = 0; + $this->cacheAdapter->beforeRead = function (string $readKey) use ( + $entryKey, + $then, + &$readsOfTheEntry, + ): void { + // The first read is the write's own read-back; the second is the final read. + if ($readKey === $entryKey && ++$readsOfTheEntry === 2) { + $this->cacheAdapter->beforeRead = null; + $then(); + } + }; + }; + } + + public function testCacheOnlyConsumptionFindingAReplayRecordedAfterItsWriteIsAReplay(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + $this->afterTheConsumedEntryIsWritten($sut, $codeId, function () use ($sut, $codeId): void { + $this->protocolCache->set( + AuthCodeRepository::GUARD_REPLAYED, + 600, + ...$sut->getGuardCacheKeyElements($codeId), + ); + }); + + // The caller then revokes the tokens this request stored, rather than returning them. + $this->assertFalse($sut->consumeAuthCode($codeId, time() + 600)); + } + + public function testCacheOnlyConsumptionFindingAnotherConsumptionAfterItsWriteIsAReplay(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + $this->afterTheConsumedEntryIsWritten($sut, $codeId, function () use ($sut, $codeId): void { + $entry = (array)$this->entry($sut, $codeId); + $entry[AuthCodeRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE] = 'the other request'; + $this->protocolCache->set($entry, 600, ...$sut->getEntryCacheKeyElements($codeId)); + }); + + $this->assertFalse($sut->consumeAuthCode($codeId, time() + 600)); + } + + /** + * Two requests both past their claim (a lock lost in between): the other's consumption lands between this + * request's write and its read-back. + */ + public function testCacheOnlyConsumptionWhoseWriteIsOverwrittenByAnotherConsumptionIsAReplay(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + $entryKey = ProtocolCache::keyFor(...$sut->getEntryCacheKeyElements($codeId)); + $this->cacheAdapter->afterSave = function (string $key) use ($sut, $codeId, $entryKey): void { + if ($key !== $entryKey) { + return; + } + $this->cacheAdapter->afterSave = null; + $entry = (array)$this->entry($sut, $codeId); + $entry[AuthCodeRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE] = 'the other request'; + $this->protocolCache->set($entry, 600, ...$sut->getEntryCacheKeyElements($codeId)); + }; + + $this->assertFalse($sut->consumeAuthCode($codeId, time() + 600)); + } + + #[DataProvider('lostAfterClaimProvider')] + public function testCacheOnlyConsumptionLosingAKeyAfterItsWriteIsAServerError(string $lostKey): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + $this->afterTheConsumedEntryIsWritten($sut, $codeId, function () use ($sut, $codeId, $lostKey): void { + $this->protocolCache->delete(...($lostKey === 'entry' ? + $sut->getEntryCacheKeyElements($codeId) : + $sut->getGuardCacheKeyElements($codeId))); + }); + + $this->assertOAuthError('server_error', fn() => $sut->consumeAuthCode($codeId, time() + 600)); + } + + public function testDatabaseModeNeverRewritesAnEntryKeptInTheCacheOnly(): void + { + $authCode = $this->newAuthCode(); + $this->sut()->persistNewAuthCode($authCode); + $savedKeys = $this->cacheAdapter->savedKeys; + + $found = $this->sut(false)->findById($authCode->getIdentifier()); + + $this->assertInstanceOf(AuthCodeEntity::class, $found); + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + public function testCacheOnlyConsumptionOfACodeWithARowIsAConditionalUpdate(): void + { + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + $this->sut(false)->persistNewAuthCode($authCode); + $this->issuanceContext->begin(); + + $this->assertTrue($this->sut()->consumeAuthCode($codeId, time() + 600)); + $this->assertFalse($this->sut()->consumeAuthCode($codeId, time() + 600)); + $this->assertSame(1, (int)($this->rowOf($codeId)['is_revoked'] ?? 0)); + // No claim was taken: the row is the gate. + $this->assertTrue((new ConsumptionGate($this->lockStore))->claim($codeId)); + } + + public function testCacheOnlyConsumptionOfACodeWithARowFailingToUpdateIsAServerError(): void + { + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + $this->sut(false)->persistNewAuthCode($authCode); + $database = $this->createMock(Database::class); + $database->method('applyPrefix')->willReturnCallback(fn(string $table): string => 'phpunit_' . $table); + $database->method('read')->willReturnCallback( + fn(string $stmt, array $params) => Database::getInstance()->read($stmt, $params), + ); + $database->method('write')->willThrowException(new Exception('database failure')); + + $this->assertOAuthError( + 'server_error', + fn() => $this->sut(true, null, null, $database)->consumeAuthCode($codeId, time() + 600), + ); + } + + public function testDatabaseModeConsumptionRevokesTheCodeAsBefore(): void + { + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + $this->sut(false)->persistNewAuthCode($authCode); + + $this->assertTrue($this->sut(false)->consumeAuthCode($codeId, time() + 600)); + $this->assertTrue($this->sut(false)->isAuthCodeRevoked($codeId)); + $this->assertSame(1, (int)($this->rowOf($codeId)['is_revoked'] ?? 0)); + } + + // Revocation and replays. + + public function testCacheOnlyRevokeClaimsAndRecordsTheCodeConsumedWithoutANonce(): void + { + $sut = $this->sut(); + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + $sut->persistNewAuthCode($authCode); + + $this->sut()->revokeAuthCode($codeId); + + $entry = (array)$this->entry($sut, $codeId); + $this->assertSame(AuthCodeRepository::STATUS_CONSUMED, $entry[AuthCodeRepository::KEY_CACHE_ONLY_STATUS]); + $this->assertArrayNotHasKey(AuthCodeRepository::KEY_CACHE_ONLY_ISSUANCE_NONCE, $entry); + // A bound of the code lifetime plus the margin. + $this->assertEqualsWithDelta(600 + 3 * 3600 + 60, $this->ttlOf($sut->getEntryCacheKeyElements($codeId)), 2); + $this->assertTrue($this->sut()->isAuthCodeRevoked($codeId)); + $this->issuanceContext->begin(); + $this->assertFalse($this->sut()->consumeAuthCode($codeId, time() + 600)); + } + + public function testCacheOnlyRevokeLeavesACodeAnotherRequestClaimed(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + $this->assertTrue($this->sut()->consumeAuthCode($codeId, time() + 600)); + $consumedEntry = $this->entry($this->sut(), $codeId); + + $this->sut()->revokeAuthCode($codeId); + + $this->assertSame($consumedEntry, $this->entry($this->sut(), $codeId)); + } + + public function testCacheOnlyRevokeOfACodeWithARowUpdatesTheRowOnly(): void + { + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + $this->sut(false)->persistNewAuthCode($authCode); + $cachedCopy = $this->entry($this->sut(), $codeId); + + $this->sut()->revokeAuthCode($codeId); + + $this->assertSame(1, (int)($this->rowOf($codeId)['is_revoked'] ?? 0)); + $this->assertSame($cachedCopy, $this->entry($this->sut(), $codeId)); + } + + public function testRecordReplayWritesTheReplayedGuardForACodeKeptInTheCacheOnly(): void + { + $sut = $this->sut(); + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + $sut->persistNewAuthCode($authCode); + + $this->sut()->recordAuthCodeReplay($codeId, time() + 300); + + $this->assertSame(AuthCodeRepository::GUARD_REPLAYED, $this->guard($sut, $codeId)); + $this->assertEqualsWithDelta( + 300 + 3600 + 3 * 3600 + 60, + $this->ttlOf($sut->getGuardCacheKeyElements($codeId)), + 2, + ); + $this->assertTrue($this->sut()->isAuthCodeRevoked($codeId)); + } + + public function testRecordReplayAfterTheDeadlineKeepsTheGuardForTheAccessTokenLifetime(): void + { + $sut = $this->sut(); + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + $sut->persistNewAuthCode($authCode); + + $this->sut()->recordAuthCodeReplay($codeId, time() - 300); + + $this->assertEqualsWithDelta(3600 + 3 * 3600 + 60, $this->ttlOf($sut->getGuardCacheKeyElements($codeId)), 2); + } + + public function testRecordReplayDoesNothingForACodeWithARowOrInDatabaseMode(): void + { + $authCode = $this->newAuthCode(); + $codeId = $authCode->getIdentifier(); + $this->sut(false)->persistNewAuthCode($authCode); + $savedKeys = $this->cacheAdapter->savedKeys; + + $this->sut()->recordAuthCodeReplay($codeId, time() + 300); + $this->sut(false)->recordAuthCodeReplay($codeId, time() + 300); + + $this->assertSame($savedKeys, $this->cacheAdapter->savedKeys); + } + + public function testRecordReplayFailsWhenTheGuardCanNotBeConfirmed(): void + { + $sut = $this->sut(); + $authCode = $this->newAuthCode(); + $sut->persistNewAuthCode($authCode); + $this->cacheAdapter->refuseWrites = true; + + $this->expectException(OidcServerException::class); + + $sut->recordAuthCodeReplay($authCode->getIdentifier(), time() + 300); + } + + public function testIsKeptInCacheOnlyFromTheRequestsMemoryElseFromTheCodesCacheKeys(): void + { + $authCode = $this->issueCacheOnly(); + $codeId = $authCode->getIdentifier(); + $codeWithARow = $this->newAuthCode(); + $this->sut(false)->persistNewAuthCode($codeWithARow); + $anotherRequest = $this->sut(); + + $this->assertTrue($anotherRequest->isKeptInCacheOnly($codeId)); + // A code with a row, or found nowhere, is taken to have a row. + $this->assertFalse($anotherRequest->isKeptInCacheOnly($codeWithARow->getIdentifier())); + $this->assertFalse($anotherRequest->isKeptInCacheOnly('code_found_nowhere')); + // Known to this request: from its memory, whatever the cache holds now. + $this->protocolCache->delete(...$anotherRequest->getEntryCacheKeyElements($codeId)); + $this->protocolCache->delete(...$anotherRequest->getGuardCacheKeyElements($codeId)); + $this->assertTrue($anotherRequest->isKeptInCacheOnly($codeId)); + // With codes in the database, no code is. + $this->assertFalse($this->sut(false)->isKeptInCacheOnly($codeId)); + } + + public function testIsConsumedWithIssuanceNonce(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + $deadline = $authCode->getExpiryDateTime()->getTimestamp(); + $issuanceNonce = (string)$this->issuanceContext->getNonce(); + + $this->assertFalse($sut->isConsumedWithIssuanceNonce($codeId, $issuanceNonce)); + + $this->assertTrue($sut->consumeAuthCode($codeId, $deadline)); + + $this->assertTrue($sut->isConsumedWithIssuanceNonce($codeId, $issuanceNonce)); + $this->assertFalse($sut->isConsumedWithIssuanceNonce($codeId, 'another nonce')); + $this->assertFalse($sut->isConsumedWithIssuanceNonce($codeId, '')); + + $sut->recordAuthCodeReplay($codeId, $deadline); + + $this->assertFalse($sut->isConsumedWithIssuanceNonce($codeId, $issuanceNonce)); + } + + public function testIsConsumedWithIssuanceNonceNeedsBothKeys(): void + { + $sut = $this->sut(); + $authCode = $this->issueCacheOnly($sut); + $codeId = $authCode->getIdentifier(); + $issuanceNonce = (string)$this->issuanceContext->getNonce(); + $this->assertTrue($sut->consumeAuthCode($codeId, $authCode->getExpiryDateTime()->getTimestamp())); + + $this->protocolCache->delete(...$sut->getGuardCacheKeyElements($codeId)); + + $this->assertFalse($sut->isConsumedWithIssuanceNonce($codeId, $issuanceNonce)); + } } diff --git a/tests/unit/src/Repositories/RefreshTokenRepositoryTest.php b/tests/unit/src/Repositories/RefreshTokenRepositoryTest.php index 6c706c846..3ef5fb528 100644 --- a/tests/unit/src/Repositories/RefreshTokenRepositoryTest.php +++ b/tests/unit/src/Repositories/RefreshTokenRepositoryTest.php @@ -15,6 +15,7 @@ */ namespace SimpleSAML\Test\Module\oidc\unit\Repositories; +use DateInterval; use DateTimeImmutable; use DateTimeZone; use League\OAuth2\Server\Entities\RefreshTokenEntityInterface; @@ -24,6 +25,7 @@ use RuntimeException; use SimpleSAML\Configuration; use SimpleSAML\Database; +use SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum; use SimpleSAML\Module\oidc\Entities\AccessTokenEntity; use SimpleSAML\Module\oidc\Entities\RefreshTokenEntity; use SimpleSAML\Module\oidc\Factories\Entities\RefreshTokenEntityFactory; @@ -31,7 +33,11 @@ use SimpleSAML\Module\oidc\ModuleConfig; use SimpleSAML\Module\oidc\Repositories\AccessTokenRepository; use SimpleSAML\Module\oidc\Repositories\RefreshTokenRepository; +use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; use SimpleSAML\Module\oidc\Services\DatabaseMigration; +use SimpleSAML\Module\oidc\Utils\ProtocolCache; +use SimpleSAML\Test\Module\oidc\unit\Utils\FaultyArrayAdapter; +use Symfony\Component\Cache\Psr16Cache; /** * @covers \SimpleSAML\Module\oidc\Repositories\RefreshTokenRepository @@ -228,4 +234,271 @@ public function testCanRevokeByAuthCodeId(): void $this->repository->revokeByAuthCodeId(self::AUTH_CODE_ID); } + + public function testRevokeAllByAuthCodeIdRevokesEveryRowAndEachCachedCopy(): void + { + $authCodeId = 'replayed_' . bin2hex(random_bytes(8)); + $protocolCache = new ProtocolCache(new Psr16Cache(new FaultyArrayAdapter())); + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('getRefreshTokenDuration')->willReturn(new DateInterval('P1M')); + $repository = new RefreshTokenRepository( + $moduleConfig, + Database::getInstance(), + $protocolCache, + $this->accessTokenRepositoryMock, + $this->refreshTokenEntityFactoryMock, + new Helpers(), + ); + foreach (['cached', 'not-cached'] as $suffix) { + $repository->persistNewRefreshToken(new RefreshTokenEntity( + "$authCodeId-$suffix", + new DateTimeImmutable('tomorrow', new DateTimeZone('UTC')), + $this->accessTokenMock, + $authCodeId, + )); + } + $protocolCache->delete($repository->getCacheKey("$authCodeId-not-cached")); + + $repository->revokeAllByAuthCodeId($authCodeId); + + foreach (['cached', 'not-cached'] as $suffix) { + $rows = Database::getInstance()->read( + 'SELECT is_revoked FROM phpunit_oidc_refresh_token WHERE id = :id', + ['id' => "$authCodeId-$suffix"], + )->fetchAll(); + $this->assertCount(1, $rows); + $this->assertSame(1, (int)$rows[0]['is_revoked']); + } + // A revoked copy of every row, cached before or not. + foreach (['cached', 'not-cached'] as $suffix) { + $cachedCopy = $protocolCache->get(null, $repository->getCacheKey("$authCodeId-$suffix")); + $this->assertIsArray($cachedCopy); + $this->assertTrue($cachedCopy['is_revoked']); + } + } + + /** + * A cache hit written back would overwrite a revocation written in the meantime. + */ + public function testFindByIdDoesNotWriteACacheHitBack(): void + { + $protocolCache = $this->createMock(ProtocolCache::class); + $protocolCache->method('get')->willReturn([ + 'id' => self::REFRESH_TOKEN_ID, + 'access_token_id' => self::ACCESS_TOKEN_ID, + ]); + $protocolCache->expects($this->never())->method('set'); + $this->refreshTokenEntityFactoryMock->method('fromState')->willReturn($this->refreshTokenEntityMock); + $this->accessTokenRepositoryMock->method('findById')->willReturn($this->accessTokenMock); + $repository = new RefreshTokenRepository( + new ModuleConfig(), + Database::getInstance(), + $protocolCache, + $this->accessTokenRepositoryMock, + $this->refreshTokenEntityFactoryMock, + new Helpers(), + ); + + $this->assertSame($this->refreshTokenEntityMock, $repository->findById(self::REFRESH_TOKEN_ID)); + } + + public function testFindByIdCachesARowFoundOnAMiss(): void + { + $refreshToken = new RefreshTokenEntity( + 'refresh_token_found_on_a_miss', + new DateTimeImmutable('tomorrow', new DateTimeZone('UTC')), + $this->accessTokenMock, + ); + $this->repository->persistNewRefreshToken($refreshToken); + $protocolCache = $this->createMock(ProtocolCache::class); + $protocolCache->method('get')->willReturn(null); + $protocolCache->expects($this->once())->method('set'); + $this->refreshTokenEntityFactoryMock->method('fromState')->willReturn($refreshToken); + $this->accessTokenRepositoryMock->method('findById')->willReturn($this->accessTokenMock); + $repository = new RefreshTokenRepository( + new ModuleConfig(), + Database::getInstance(), + $protocolCache, + $this->accessTokenRepositoryMock, + $this->refreshTokenEntityFactoryMock, + new Helpers(), + ); + + $this->assertSame($refreshToken, $repository->findById('refresh_token_found_on_a_miss')); + } + + // Access tokens kept in the protocol cache only. + + protected function newRefreshToken(AccessTokenEntity $accessToken, ?string $authCodeId = null): RefreshTokenEntity + { + return new RefreshTokenEntity( + 'refresh_token_' . bin2hex(random_bytes(16)), + new DateTimeImmutable('+1 month'), + $accessToken, + $authCodeId, + ); + } + + protected function refreshTokenRowOf(string $tokenId): ?array + { + $rows = Database::getInstance()->read( + 'SELECT * FROM phpunit_oidc_refresh_token WHERE id = :id', + ['id' => $tokenId], + )->fetchAll(); + + return empty($rows) ? null : (array)current($rows); + } + + protected function moduleConfigWithAccessTokensKeptInTheCacheOnly(): ModuleConfig + { + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturn(true); + $moduleConfig->method('getAccessTokenDuration')->willReturn(new DateInterval('PT1H')); + $moduleConfig->method('getAuthCodeDuration')->willReturn(new DateInterval('PT10M')); + $moduleConfig->method('getRefreshTokenDuration')->willReturn(new DateInterval('P1M')); + + return $moduleConfig; + } + + public function testPersistMakesSureTheAccessTokenHasARowBeforeItsInsert(): void + { + $refreshToken = $this->newRefreshToken($this->accessTokenMock); + $this->accessTokenRepositoryMock->expects($this->once())->method('ensureStoredInDatabase') + ->with($this->accessTokenMock) + ->willReturnCallback(function () use ($refreshToken): void { + $this->assertNull($this->refreshTokenRowOf((string)$refreshToken->getIdentifier())); + }); + + $this->repository->persistNewRefreshToken($refreshToken); + + $this->assertNotNull($this->refreshTokenRowOf((string)$refreshToken->getIdentifier())); + } + + public function testPersistWritesNoRefreshTokenWhenItsAccessTokenCanNotBeStored(): void + { + $refreshToken = $this->newRefreshToken($this->accessTokenMock); + $this->accessTokenRepositoryMock->method('ensureStoredInDatabase') + ->willThrowException(OidcServerException::serverError('The promotion failed.')); + + try { + $this->repository->persistNewRefreshToken($refreshToken); + $this->fail('A refresh token was stored for an access token without a row.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + + $this->assertNull($this->refreshTokenRowOf((string)$refreshToken->getIdentifier())); + } + + /** + * While access tokens are kept in the cache only, refresh tokens are read from the database, their access token + * too, and nothing about them is written to the cache. + */ + public function testWhileAccessTokensAreKeptInTheCacheOnlyRefreshTokensAreNotCachedNorReadFromIt(): void + { + $protocolCache = $this->createMock(ProtocolCache::class); + $protocolCache->expects($this->never())->method('get'); + $protocolCache->expects($this->never())->method('set'); + $protocolCache->expects($this->never())->method('setChecked'); + $this->accessTokenRepositoryMock->expects($this->never())->method('findById'); + $this->accessTokenRepositoryMock->expects($this->atLeastOnce())->method('findByIdInDatabase') + ->with(self::ACCESS_TOKEN_ID) + ->willReturn($this->accessTokenMock); + $repository = new RefreshTokenRepository( + $this->moduleConfigWithAccessTokensKeptInTheCacheOnly(), + Database::getInstance(), + $protocolCache, + $this->accessTokenRepositoryMock, + new RefreshTokenEntityFactory(new Helpers()), + new Helpers(), + ); + $refreshToken = $this->newRefreshToken($this->accessTokenMock); + $tokenId = (string)$refreshToken->getIdentifier(); + + $repository->persistNewRefreshToken($refreshToken); + $this->assertFalse($repository->isRefreshTokenRevoked($tokenId)); + $repository->revokeRefreshToken($tokenId); + + $this->assertTrue($repository->isRefreshTokenRevoked($tokenId)); + $this->assertSame(1, (int)$this->refreshTokenRowOf($tokenId)['is_revoked']); + } + + public function testRevokeByAuthCodeIdWhileAccessTokensAreKeptInTheCacheOnlyIsOneUpdateOnThePrimary(): void + { + $database = $this->createMock(Database::class); + $database->method('applyPrefix')->willReturnCallback(fn(string $table): string => "phpunit_$table"); + $database->expects($this->once())->method('write')->with( + $this->stringStartsWith('UPDATE phpunit_oidc_refresh_token SET is_revoked'), + $this->callback(fn(array $parameters): bool => $parameters['auth_code_id'] === 'replayed_code'), + ); + $database->expects($this->never())->method('read'); + $repository = new RefreshTokenRepository( + $this->moduleConfigWithAccessTokensKeptInTheCacheOnly(), + $database, + new ProtocolCache(new Psr16Cache(new FaultyArrayAdapter())), + $this->accessTokenRepositoryMock, + $this->refreshTokenEntityFactoryMock, + new Helpers(), + ); + + $repository->revokeByAuthCodeId('replayed_code'); + } + + public function testRevokeAllByAuthCodeIdWritesNoCachedCopiesWhileAccessTokensAreKeptInTheCacheOnly(): void + { + $authCodeId = 'replayed_' . bin2hex(random_bytes(8)); + $adapter = new FaultyArrayAdapter(); + $repository = new RefreshTokenRepository( + $this->moduleConfigWithAccessTokensKeptInTheCacheOnly(), + Database::getInstance(), + new ProtocolCache(new Psr16Cache($adapter)), + $this->accessTokenRepositoryMock, + $this->refreshTokenEntityFactoryMock, + new Helpers(), + ); + $refreshToken = $this->newRefreshToken($this->accessTokenMock, $authCodeId); + $repository->persistNewRefreshToken($refreshToken); + + $repository->revokeAllByAuthCodeId($authCodeId); + + $this->assertSame(1, (int)$this->refreshTokenRowOf((string)$refreshToken->getIdentifier())['is_revoked']); + $this->assertSame([], $adapter->savedKeys); + } + + /** + * With authorization codes alone in the cache only, refresh tokens are cached when stored, and a cached copy is + * trusted, as before; the access token is looked up as before too. + */ + public function testWithCodesAloneKeptInTheCacheOnlyRefreshTokensAreCachedAndTrustedAsBefore(): void + { + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturnCallback( + fn(ProtocolArtifactEnum $artifact): bool => $artifact === ProtocolArtifactEnum::AuthorizationCode, + ); + $protocolCache = new ProtocolCache(new Psr16Cache(new FaultyArrayAdapter())); + $this->accessTokenRepositoryMock->expects($this->never())->method('findByIdInDatabase'); + $this->accessTokenRepositoryMock->expects($this->once())->method('findById') + ->with(self::ACCESS_TOKEN_ID) + ->willReturn($this->accessTokenMock); + $repository = new RefreshTokenRepository( + $moduleConfig, + Database::getInstance(), + $protocolCache, + $this->accessTokenRepositoryMock, + new RefreshTokenEntityFactory(new Helpers()), + new Helpers(), + ); + $refreshToken = $this->newRefreshToken($this->accessTokenMock); + $tokenId = (string)$refreshToken->getIdentifier(); + + $repository->persistNewRefreshToken($refreshToken); + + $this->assertIsArray($protocolCache->get(null, $repository->getCacheKey($tokenId))); + // The row and its cached copy disagree: the copy is trusted. + Database::getInstance()->write( + 'UPDATE phpunit_oidc_refresh_token SET is_revoked = :is_revoked WHERE id = :id', + ['is_revoked' => [true, \PDO::PARAM_BOOL], 'id' => $tokenId], + ); + $this->assertFalse($repository->isRefreshTokenRevoked($tokenId)); + } } diff --git a/tests/unit/src/Repositories/UserRepositoryTest.php b/tests/unit/src/Repositories/UserRepositoryTest.php index 9daed4eb7..7b9abd0ff 100644 --- a/tests/unit/src/Repositories/UserRepositoryTest.php +++ b/tests/unit/src/Repositories/UserRepositoryTest.php @@ -17,6 +17,7 @@ use DateTimeImmutable; use PDOStatement; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Framework\TestCase; @@ -30,13 +31,20 @@ use SimpleSAML\Module\oidc\Repositories\UserRepository; use SimpleSAML\Module\oidc\Services\DatabaseMigration; use SimpleSAML\Module\oidc\Utils\ProtocolCache; +use SimpleSAML\Test\Module\oidc\unit\Utils\FaultyArrayAdapter; +use Symfony\Component\Cache\Exception\CacheException; +use Symfony\Component\Cache\Psr16Cache; /** * @covers \SimpleSAML\Module\oidc\Repositories\UserRepository */ class UserRepositoryTest extends TestCase { + final protected const string OLD_TIME = '2020-01-02 03:04:05'; + protected static UserRepository $repository; + protected ProtocolCache $protocolCache; + protected FaultyArrayAdapter $cacheAdapter; protected Stub $helpersStub; protected MockObject $userEntityFactoryMock; protected MockObject $userEntityMock; @@ -309,6 +317,396 @@ public function testWillDeleteFromDatabaseAndCache(): void )->delete($this->userEntityMock); } + /** + * A repository on the real database, with a real protocol cache and real factories, as a login uses it. + */ + protected function conditionalUpdateRepository(): UserRepository + { + $this->moduleConfigMock->method('getProtocolUserEntityCacheDuration') + ->willReturn(new \DateInterval('PT1H')); + $this->cacheAdapter = new FaultyArrayAdapter(); + $this->protocolCache = new ProtocolCache(new Psr16Cache($this->cacheAdapter)); + + return $this->mock( + protocolCache: $this->protocolCache, + helpers: new Helpers(), + userEntityFactory: new UserEntityFactory(new Helpers()), + ); + } + + protected function insertRow(?string $claims): string + { + $id = uniqid('conditional-update-', true); + $this->database->write( + 'INSERT INTO phpunit_oidc_user (id, claims, updated_at, created_at) ' . + 'VALUES (:id, :claims, :updated_at, :created_at)', + ['id' => $id, 'claims' => $claims, 'updated_at' => self::OLD_TIME, 'created_at' => self::OLD_TIME], + ); + + return $id; + } + + protected function rowOf(string $id): ?array + { + $rows = $this->database->read('SELECT * FROM phpunit_oidc_user WHERE id = :id', ['id' => $id])->fetchAll(); + if ($rows === []) { + return null; + } + $row = array_filter($rows[0], 'is_string', ARRAY_FILTER_USE_KEY); + ksort($row); + + return $row; + } + + protected function cachedStateOf(UserRepository $repository, string $id): mixed + { + $state = $this->protocolCache->get(null, $repository->getCacheKey($id)); + if (is_array($state)) { + ksort($state); + } + + return $state; + } + + protected function stateOf(string $id, string $claims, string $updatedAt = self::OLD_TIME): array + { + $state = ['id' => $id, 'claims' => $claims, 'updated_at' => $updatedAt, 'created_at' => self::OLD_TIME]; + ksort($state); + + return $state; + } + + public static function storedClaimsProvider(): array + { + $claims = ['uid' => ['jdoe'], 'mail' => ['jdoe@example.org', 'john@example.org']]; + + return [ + 'the same claims' => [json_encode($claims), $claims], + 'no claims' => ['[]', []], + 'invalid UTF-8, stored replaced' => [ + json_encode(['cn' => ["a\xFFb"]], JSON_INVALID_UTF8_SUBSTITUTE), + ['cn' => ["a\xFFb"]], + ], + ]; + } + + #[DataProvider('storedClaimsProvider')] + public function testConditionalUpdateWritesNothingWhenTheRowStoresTheClaims( + string $storedClaims, + array $claims, + ): void { + $repository = $this->conditionalUpdateRepository(); + $id = $this->insertRow($storedClaims); + $user = $repository->getUserEntityByIdentifier($id); + $this->assertNotNull($user); + $user->setClaims($claims); + + $this->assertFalse($repository->updateIfClaimsChanged($user)); + + $this->assertSame($this->stateOf($id, $storedClaims), $this->rowOf($id)); + $this->assertSame($this->stateOf($id, $storedClaims), $this->cachedStateOf($repository, $id)); + } + + public static function changedClaimsProvider(): array + { + $claims = ['uid' => ['jdoe'], 'mail' => ['jdoe@example.org', 'john@example.org']]; + $stored = json_encode($claims); + + return [ + 'a changed value' => [$stored, ['uid' => ['jdoe'], 'mail' => ['jdoe@example.org']]], + 'an added attribute' => [$stored, [...$claims, 'cn' => ['John Doe']]], + 'a removed attribute' => [$stored, ['uid' => ['jdoe']]], + 'values in another order' => [ + $stored, + ['uid' => ['jdoe'], 'mail' => ['john@example.org', 'jdoe@example.org']], + ], + 'attributes in another order' => [ + $stored, + ['mail' => ['jdoe@example.org', 'john@example.org'], 'uid' => ['jdoe']], + ], + 'a number for its string' => ['{"n":["1"]}', ['n' => [1]]], + 'the same claims, stored in another spelling' => ['{"uid": ["jdoe"]}', ['uid' => ['jdoe']]], + 'no stored claims' => ['', []], + 'NULL stored claims' => [null, []], + ]; + } + + #[DataProvider('changedClaimsProvider')] + public function testConditionalUpdateWritesChangedClaims(?string $storedClaims, array $claims): void + { + $repository = $this->conditionalUpdateRepository(); + $id = $this->insertRow($storedClaims); + // The cache entry agrees with the login, so only the row can make it write. + $this->protocolCache->set($this->stateOf($id, json_encode($claims)), 3600, $repository->getCacheKey($id)); + // As a login has it: the stored user, given this login's claims. + $user = new UserEntity( + $id, + new DateTimeImmutable(self::OLD_TIME), + new DateTimeImmutable(self::OLD_TIME), + [], + ); + $user->setClaims($claims); + + $this->assertTrue($repository->updateIfClaimsChanged($user)); + + $row = $this->rowOf($id); + $this->assertNotNull($row); + $this->assertSame(json_encode($claims), $row['claims']); + $this->assertNotSame(self::OLD_TIME, $row['updated_at']); + $this->assertSame($row, $this->cachedStateOf($repository, $id)); + } + + public static function disagreementProvider(): array + { + return [ + 'the row outdated, the cache entry as the login' => ['admin', 'member'], + 'the row as the login, the cache entry outdated' => ['member', 'admin'], + ]; + } + + /** + * The cache entry differs from the row, as after a cache write that failed, or with caches local to each node. + * The login brings member: it is written to both, as before, whichever of the two disagrees. + */ + #[DataProvider('disagreementProvider')] + public function testConditionalUpdateUpdatesWhenTheRowAndTheCacheDisagree(string $rowRole, string $cachedRole): void + { + $repository = $this->conditionalUpdateRepository(); + $member = json_encode(['uid' => ['jdoe'], 'role' => ['member']]); + $id = $this->insertRow(json_encode(['uid' => ['jdoe'], 'role' => [$rowRole]])); + $this->protocolCache->set( + $this->stateOf($id, json_encode(['uid' => ['jdoe'], 'role' => [$cachedRole]])), + 3600, + $repository->getCacheKey($id), + ); + $user = $repository->getUserEntityByIdentifier($id); + $this->assertNotNull($user); + $this->assertSame(['uid' => ['jdoe'], 'role' => [$cachedRole]], $user->getClaims()); + $user->setClaims(['uid' => ['jdoe'], 'role' => ['member']]); + + $this->assertTrue($repository->updateIfClaimsChanged($user)); + + $row = $this->rowOf($id); + $this->assertSame($member, $row['claims'] ?? null); + $this->assertNotSame(self::OLD_TIME, $row['updated_at'] ?? null); + $this->assertSame($row, $this->cachedStateOf($repository, $id)); + } + + /** + * Another login's update lands between this login's read of the row and its read of the cache entry: this login + * writes its claims over it in both places, as before, rather than leaving the other's in the row behind an entry + * that disagrees with it. + */ + public function testConditionalUpdateOverwritesAnUpdateLandingBetweenItsTwoReads(): void + { + $repository = $this->conditionalUpdateRepository(); + $admin = json_encode(['uid' => ['jdoe'], 'role' => ['admin']]); + $id = $this->insertRow($admin); + $user = $repository->getUserEntityByIdentifier($id); + $this->assertNotNull($user); + $user->setClaims(['uid' => ['jdoe'], 'role' => ['admin']]); + $cacheKey = ProtocolCache::keyFor($repository->getCacheKey($id)); + $this->cacheAdapter->beforeRead = function (string $key) use ($repository, $id, $cacheKey): void { + if ($key !== $cacheKey) { + return; + } + $this->cacheAdapter->beforeRead = null; + $repository->update(new UserEntity( + $id, + new DateTimeImmutable(self::OLD_TIME), + new DateTimeImmutable(self::OLD_TIME), + ['uid' => ['jdoe'], 'role' => ['member']], + )); + }; + + $this->assertTrue($repository->updateIfClaimsChanged($user)); + + $this->assertNull($this->cacheAdapter->beforeRead, 'The other update did not run.'); + $row = $this->rowOf($id); + $this->assertSame($admin, $row['claims'] ?? null); + $this->assertSame($row, $this->cachedStateOf($repository, $id)); + } + + /** + * A cache entry that can not be read after the lookup read it counts as missing: the user is updated, as when the + * row can not be read, rather than the login failing. + */ + public function testConditionalUpdateUpdatesWhenTheCacheEntryCanNotBeRead(): void + { + $repository = $this->conditionalUpdateRepository(); + $claims = json_encode(['uid' => ['jdoe']]); + $id = $this->insertRow($claims); + $user = $repository->getUserEntityByIdentifier($id); + $this->assertNotNull($user); + $user->setClaims(['uid' => ['jdoe']]); + $this->cacheAdapter->beforeRead = function (): void { + throw new CacheException('The backend went away.'); + }; + + $this->assertTrue($repository->updateIfClaimsChanged($user)); + + $this->cacheAdapter->beforeRead = null; + $row = $this->rowOf($id); + $this->assertSame($claims, $row['claims'] ?? null); + $this->assertNotSame(self::OLD_TIME, $row['updated_at'] ?? null); + $this->assertSame($row, $this->cachedStateOf($repository, $id)); + } + + public function testConditionalUpdateUpdatesWhenTheCacheEntryIsMissing(): void + { + $repository = $this->conditionalUpdateRepository(); + $claims = json_encode(['uid' => ['jdoe']]); + $id = $this->insertRow($claims); + $user = new UserEntity( + $id, + new DateTimeImmutable(self::OLD_TIME), + new DateTimeImmutable(self::OLD_TIME), + ['uid' => ['jdoe']], + ); + + $this->assertTrue($repository->updateIfClaimsChanged($user)); + + $row = $this->rowOf($id); + $this->assertSame($claims, $row['claims'] ?? null); + $this->assertNotSame(self::OLD_TIME, $row['updated_at'] ?? null); + $this->assertSame($row, $this->cachedStateOf($repository, $id)); + } + + public function testConditionalUpdateWithoutARowUpdatesAsBefore(): void + { + $repository = $this->conditionalUpdateRepository(); + $id = uniqid('conditional-update-', true); + // Found only in the cache, with the login's claims: the cache alone never makes it skip. + $this->protocolCache->set($this->stateOf($id, '{"uid":["jdoe"]}'), 3600, $repository->getCacheKey($id)); + $user = new UserEntity( + $id, + new DateTimeImmutable(self::OLD_TIME), + new DateTimeImmutable(self::OLD_TIME), + ['uid' => ['jdoe']], + ); + + $this->assertTrue($repository->updateIfClaimsChanged($user)); + // update() changes no row, as before, and writes the cache entry. + $this->assertNull($this->rowOf($id)); + $this->assertNotSame(self::OLD_TIME, $this->cachedStateOf($repository, $id)['updated_at'] ?? null); + } + + /** + * The entry agrees with the row, so nothing is written, the entry included, not even to renew it. + */ + public function testConditionalUpdateLeavesACacheEntryThatAgreesWithTheRow(): void + { + $repository = $this->conditionalUpdateRepository(); + $claims = json_encode(['uid' => ['jdoe']]); + $id = $this->insertRow($claims); + $cachedState = $this->stateOf($id, $claims, '2021-01-01 00:00:00'); + $this->protocolCache->set($cachedState, 3600, $repository->getCacheKey($id)); + $user = $repository->getUserEntityByIdentifier($id); + $this->assertNotNull($user); + $user->setClaims(['uid' => ['jdoe']]); + $this->cacheAdapter->savedKeys = []; + + $this->assertFalse($repository->updateIfClaimsChanged($user)); + + $this->assertSame([], $this->cacheAdapter->savedKeys); + $this->assertSame($cachedState, $this->cachedStateOf($repository, $id)); + $this->assertSame($this->stateOf($id, $claims), $this->rowOf($id)); + } + + public static function unencodableClaimsProvider(): array + { + return [ + 'against an empty column' => [''], + 'against a NULL column' => [null], + ]; + } + + /** + * Claims json_encode() refuses are stored as false, which the database keeps as an empty string and the cache as + * false: they never count as stored, so they are written, as before. The cache entry holds the false an earlier + * update of such claims leaves there, so only the row can make it write. + */ + #[DataProvider('unencodableClaimsProvider')] + public function testConditionalUpdateWritesClaimsThatCanNotBeEncoded(?string $storedClaims): void + { + $repository = $this->conditionalUpdateRepository(); + $id = $this->insertRow($storedClaims); + $this->protocolCache->set( + ['id' => $id, 'claims' => false, 'updated_at' => self::OLD_TIME, 'created_at' => self::OLD_TIME], + 3600, + $repository->getCacheKey($id), + ); + $user = new UserEntity( + $id, + new DateTimeImmutable(self::OLD_TIME), + new DateTimeImmutable(self::OLD_TIME), + ['n' => [NAN]], + ); + + $this->assertTrue($repository->updateIfClaimsChanged($user)); + $this->assertNotSame(self::OLD_TIME, $this->rowOf($id)['updated_at'] ?? null); + } + + public function testConditionalUpdateWithoutACache(): void + { + $this->moduleConfigMock->method('getProtocolUserEntityCacheDuration') + ->willReturn(new \DateInterval('PT1H')); + $repository = $this->mock(helpers: new Helpers(), userEntityFactory: new UserEntityFactory(new Helpers())); + $stored = json_encode(['uid' => ['jdoe']]); + $id = $this->insertRow($stored); + $user = new UserEntity( + $id, + new DateTimeImmutable(self::OLD_TIME), + new DateTimeImmutable(self::OLD_TIME), + ['uid' => ['jdoe']], + ); + + $this->assertFalse($repository->updateIfClaimsChanged($user)); + $this->assertSame($this->stateOf($id, $stored), $this->rowOf($id)); + + $user->setClaims(['uid' => ['jdoe'], 'cn' => ['John Doe']]); + + $this->assertTrue($repository->updateIfClaimsChanged($user)); + $this->assertSame('{"uid":["jdoe"],"cn":["John Doe"]}', $this->rowOf($id)['claims'] ?? null); + $this->assertNotSame(self::OLD_TIME, $this->rowOf($id)['updated_at'] ?? null); + } + + /** + * A row that can not be read (a secondary down, a standby that cancelled the query) does not fail the login: the + * user is updated, as every login did before, even though the cache entry agrees with the login. + */ + public function testConditionalUpdateUpdatesWhenTheRowCanNotBeRead(): void + { + $this->moduleConfigMock->method('getProtocolUserEntityCacheDuration') + ->willReturn(new \DateInterval('PT1H')); + $this->databaseMock->method('applyPrefix')->willReturnArgument(0); + $this->databaseMock->expects($this->once())->method('read') + ->willThrowException(new \Exception('Database error: canceling statement due to conflict with recovery')); + $this->databaseMock->expects($this->once())->method('write') + ->with($this->stringContains('UPDATE'), $this->callback( + fn (array $state): bool => $state['id'] === 'unreadable' && $state['claims'] === '{"uid":["jdoe"]}', + )); + $protocolCache = new ProtocolCache(new Psr16Cache(new FaultyArrayAdapter())); + $repository = $this->mock(database: $this->databaseMock, protocolCache: $protocolCache, helpers: new Helpers()); + $protocolCache->set( + $this->stateOf('unreadable', '{"uid":["jdoe"]}'), + 3600, + $repository->getCacheKey('unreadable'), + ); + $user = new UserEntity( + 'unreadable', + new DateTimeImmutable(self::OLD_TIME), + new DateTimeImmutable(self::OLD_TIME), + ['uid' => ['jdoe']], + ); + + $this->assertTrue($repository->updateIfClaimsChanged($user)); + $this->assertNotSame( + self::OLD_TIME, + $protocolCache->get(null, $repository->getCacheKey('unreadable'))['updated_at'] ?? null, + ); + } + public function testGetUserEntityByUserCredentialsThrows(): void { $this->expectException(\Exception::class); diff --git a/tests/unit/src/Server/Grants/AuthCodeGrantTest.php b/tests/unit/src/Server/Grants/AuthCodeGrantTest.php index 4479ddf35..28cf07908 100644 --- a/tests/unit/src/Server/Grants/AuthCodeGrantTest.php +++ b/tests/unit/src/Server/Grants/AuthCodeGrantTest.php @@ -5,25 +5,65 @@ namespace SimpleSAML\Test\Module\oidc\unit\Server\Grants; use DateInterval; +use DateTimeImmutable; +use Defuse\Crypto\Crypto; +use Defuse\Crypto\Key; +use Laminas\Diactoros\ServerRequest; +use League\OAuth2\Server\Exception\OAuthServerException; +use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; +use League\OAuth2\Server\ResponseTypes\RedirectResponse; +use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Framework\TestCase; +use RuntimeException; +use SimpleSAML\Database; +use SimpleSAML\Module\oidc\Codebooks\ProtocolArtifactEnum; +use SimpleSAML\Module\oidc\Entities\AccessTokenEntity; +use SimpleSAML\Module\oidc\Entities\AuthCodeEntity; +use SimpleSAML\Module\oidc\Entities\ClientEntity; +use SimpleSAML\Module\oidc\Entities\ScopeEntity; +use SimpleSAML\Module\oidc\Entities\UserEntity; use SimpleSAML\Module\oidc\Factories\Entities\AccessTokenEntityFactory; use SimpleSAML\Module\oidc\Factories\Entities\AuthCodeEntityFactory; +use SimpleSAML\Module\oidc\Factories\Entities\ScopeEntityFactory; use SimpleSAML\Module\oidc\Helpers; use SimpleSAML\Module\oidc\ModuleConfig; +use SimpleSAML\Module\oidc\Repositories\AccessTokenRepository; +use SimpleSAML\Module\oidc\Repositories\AuthCodeRepository; +use SimpleSAML\Module\oidc\Repositories\ClientRepository; use SimpleSAML\Module\oidc\Repositories\Interfaces\AccessTokenRepositoryInterface; use SimpleSAML\Module\oidc\Repositories\Interfaces\AuthCodeRepositoryInterface; use SimpleSAML\Module\oidc\Repositories\Interfaces\RefreshTokenRepositoryInterface; +use SimpleSAML\Module\oidc\Server\Exceptions\OidcServerException; use SimpleSAML\Module\oidc\Server\Grants\AuthCodeGrant; use SimpleSAML\Module\oidc\Server\RequestRules\RequestRulesManager; +use SimpleSAML\Module\oidc\Server\RequestRules\Result; +use SimpleSAML\Module\oidc\Server\RequestRules\ResultBag; +use SimpleSAML\Module\oidc\Server\RequestRules\Rules\ClientAuthenticationRule; +use SimpleSAML\Module\oidc\Server\RequestRules\Rules\ClientIdRule; +use SimpleSAML\Module\oidc\Server\RequestRules\Rules\CodeVerifierRule; +use SimpleSAML\Module\oidc\Server\RequestTypes\AuthorizationRequest; use SimpleSAML\Module\oidc\Server\TokenIssuers\RefreshTokenIssuer; +use SimpleSAML\Module\oidc\Services\LoggerService; +use SimpleSAML\Module\oidc\Utils\ConsumptionGate; +use SimpleSAML\Module\oidc\Utils\IssuanceContext; +use SimpleSAML\Module\oidc\Utils\ProtocolCache; use SimpleSAML\Module\oidc\Utils\RequestParamsResolver; +use Symfony\Component\Cache\Adapter\ArrayAdapter; +use Symfony\Component\Cache\Psr16Cache; +use Symfony\Component\Lock\Store\InMemoryStore; /** * @covers \SimpleSAML\Module\oidc\Server\Grants\AuthCodeGrant */ class AuthCodeGrantTest extends TestCase { + protected const string CLIENT_ID = 'client-id'; + protected const string REDIRECT_URI = 'https://rp.example.org/callback'; + protected const string AUTH_CODE_ID = 'auth-code-id'; + protected const string CODE_VERIFIER = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk-and-more-entropy'; + protected Stub $authCodeRepositoryStub; protected Stub $accessTokenRepositoryStub; protected Stub $refreshTokenRepositoryStub; @@ -35,6 +75,16 @@ class AuthCodeGrantTest extends TestCase protected Stub $authCodeEntityFactoryStub; protected Stub $refreshTokenIssuerStub; protected Stub $helpersStub; + protected Stub $loggerServiceStub; + + protected MockObject $authCodeRepositoryMock; + protected MockObject $accessTokenRepositoryMock; + protected MockObject $refreshTokenRepositoryMock; + protected MockObject $loggerServiceMock; + protected Stub $clientStub; + protected IssuanceContext $issuanceContext; + protected Key $encryptionKey; + protected int $accessTokenExpiresAt; /** * @throws \Exception @@ -52,6 +102,18 @@ protected function setUp(): void $this->authCodeEntityFactoryStub = $this->createStub(AuthcodeEntityFactory::class); $this->refreshTokenIssuerStub = $this->createStub(RefreshTokenIssuer::class); $this->helpersStub = $this->createStub(Helpers::class); + $this->loggerServiceStub = $this->createStub(LoggerService::class); + + $this->authCodeRepositoryMock = $this->createMock(AuthCodeRepositoryInterface::class); + $this->accessTokenRepositoryMock = $this->createMock(AccessTokenRepositoryInterface::class); + $this->refreshTokenRepositoryMock = $this->createMock(RefreshTokenRepositoryInterface::class); + $this->loggerServiceMock = $this->createMock(LoggerService::class); + $this->clientStub = $this->createStub(ClientEntity::class); + $this->clientStub->method('getIdentifier')->willReturn(self::CLIENT_ID); + $this->clientStub->method('getRedirectUri')->willReturn([self::REDIRECT_URI]); + $this->issuanceContext = new IssuanceContext(); + $this->encryptionKey = Key::createNewRandomKey(); + $this->accessTokenExpiresAt = time() + 3600; } /** @@ -72,7 +134,629 @@ public function testCanCreateInstance(): void $this->authCodeEntityFactoryStub, $this->refreshTokenIssuerStub, $this->helpersStub, + $this->moduleConfigStub, + $this->loggerServiceStub, + new IssuanceContext(), + ), + ); + } + + /** + * A grant ready to answer token requests, with the repositories, the logger and the issuance context of this + * test, and authorization codes kept in the protocol cache only or in the database. + * + * @throws \Exception + */ + protected function sut(bool $isCacheOnly, ?AuthCodeEntityFactory $authCodeEntityFactory = null): AuthCodeGrant + { + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturnCallback( + fn(ProtocolArtifactEnum $artifact): bool => $isCacheOnly && + $artifact === ProtocolArtifactEnum::AuthorizationCode, + ); + + $requestRulesManager = $this->createStub(RequestRulesManager::class); + $requestRulesManager->method('check')->willReturnCallback(function (): ResultBag { + $resultBag = new ResultBag(); + $resultBag->add(new Result(ClientIdRule::class, $this->clientStub)); + $resultBag->add(new Result(ClientAuthenticationRule::class, null)); + $resultBag->add(new Result(CodeVerifierRule::class, self::CODE_VERIFIER)); + + return $resultBag; + }); + + $accessTokenEntityFactory = $this->createStub(AccessTokenEntityFactory::class); + $accessTokenEntityFactory->method('fromData')->willReturnCallback(function (): AccessTokenEntity { + $accessToken = $this->createStub(AccessTokenEntity::class); + $accessToken->method('getExpiryDateTime')->willReturn( + (new DateTimeImmutable())->setTimestamp($this->accessTokenExpiresAt), + ); + + return $accessToken; + }); + + $scopeRepository = $this->createStub(ScopeRepositoryInterface::class); + $scopeRepository->method('getScopeEntityByIdentifier')->willReturnCallback( + fn(string $identifier): ScopeEntity => new ScopeEntity($identifier), + ); + $scopeRepository->method('finalizeScopes')->willReturnArgument(0); + + $grant = new AuthCodeGrant( + $this->authCodeRepositoryMock, + $this->accessTokenRepositoryMock, + $this->refreshTokenRepositoryMock, + new DateInterval('PT10M'), + $requestRulesManager, + $this->requestParamsResolverStub, + $accessTokenEntityFactory, + $authCodeEntityFactory ?? $this->authCodeEntityFactoryStub, + $this->refreshTokenIssuerStub, + new Helpers(), + $moduleConfig, + $this->loggerServiceMock, + $this->issuanceContext, + ); + $grant->setEncryptionKey($this->encryptionKey); + $grant->setScopeRepository($scopeRepository); + + return $grant; + } + + /** + * A token request redeeming a code with the given payload changes. + * + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \JsonException + */ + protected function tokenRequest( + array $payloadChanges = [], + ?string $redirectUri = self::REDIRECT_URI, + ): ServerRequest { + $codeChallenge = rtrim(strtr(base64_encode(hash('sha256', self::CODE_VERIFIER, true)), '+/', '-_'), '='); + $payload = array_merge( + [ + 'client_id' => self::CLIENT_ID, + 'redirect_uri' => self::REDIRECT_URI, + 'auth_code_id' => self::AUTH_CODE_ID, + 'scopes' => ['openid'], + 'user_id' => 'user-id', + 'expire_time' => time() + 600, + 'code_challenge' => $codeChallenge, + 'code_challenge_method' => 'S256', + 'nonce' => null, + 'auth_time' => null, + 'claims' => null, + 'acr' => null, + 'session_id' => null, + ], + $payloadChanges, + ); + + $body = ['code' => Crypto::encrypt(json_encode($payload, JSON_THROW_ON_ERROR), $this->encryptionKey)]; + if ($redirectUri !== null) { + $body['redirect_uri'] = $redirectUri; + } + + return (new ServerRequest([], [], null, 'POST'))->withParsedBody($body); + } + + /** + * @throws \Throwable + */ + protected function respond(AuthCodeGrant $grant, ServerRequest $request): ResponseTypeInterface + { + return $grant->respondToAccessTokenRequest( + $request, + $this->createStub(ResponseTypeInterface::class), + new DateInterval('PT1H'), + ); + } + + protected function assertOAuthError(string $errorType, callable $callable): OAuthServerException + { + try { + $callable(); + } catch (OAuthServerException $exception) { + $this->assertSame($errorType, $exception->getErrorType(), (string)$exception->getHint()); + return $exception; + } + + $this->fail("Expected the $errorType error."); + } + + protected function expectNoTokenIssued(): void + { + $this->accessTokenRepositoryMock->expects($this->never())->method('persistNewAccessToken'); + $this->authCodeRepositoryMock->expects($this->never())->method('consumeAuthCode'); + } + + protected function expectNoCleanup(): void + { + $this->authCodeRepositoryMock->expects($this->never())->method('recordAuthCodeReplay'); + $this->accessTokenRepositoryMock->expects($this->never())->method('revokeByAuthCodeId'); + $this->refreshTokenRepositoryMock->expects($this->never())->method('revokeByAuthCodeId'); + $this->accessTokenRepositoryMock->expects($this->never())->method('revokeAllByAuthCodeId'); + $this->refreshTokenRepositoryMock->expects($this->never())->method('revokeAllByAuthCodeId'); + } + + /** + * The cache-only replay branch: the guard, then every token on the primary database and in the cache. + */ + protected function expectCleanup(int $deadline): void + { + $this->authCodeRepositoryMock->expects($this->once())->method('recordAuthCodeReplay') + ->with(self::AUTH_CODE_ID, $deadline); + $this->accessTokenRepositoryMock->expects($this->once())->method('revokeAllByAuthCodeId') + ->with(self::AUTH_CODE_ID); + $this->refreshTokenRepositoryMock->expects($this->once())->method('revokeAllByAuthCodeId') + ->with(self::AUTH_CODE_ID); + $this->accessTokenRepositoryMock->expects($this->never())->method('revokeByAuthCodeId'); + $this->refreshTokenRepositoryMock->expects($this->never())->method('revokeByAuthCodeId'); + } + + // The order of the start checks. + + public static function failedProofProvider(): array + { + return [ + 'another client' => [['client_id' => 'another-client'], self::REDIRECT_URI, 'invalid_request'], + 'another redirect URI' => [[], 'https://rp.example.org/other', 'invalid_request'], + 'no redirect URI' => [[], null, 'invalid_request'], + 'a wrong PKCE proof' => [['code_challenge' => 'not-the-challenge'], self::REDIRECT_URI, 'invalid_grant'], + ]; + } + + /** + * @dataProvider failedProofProvider + */ + public function testCacheOnlyRequestNotProvingItHoldsTheCodeIsRefusedBeforeAnyReplayCheck( + array $payloadChanges, + ?string $redirectUri, + string $errorType, + ): void { + $this->authCodeRepositoryMock->expects($this->never())->method('isAuthCodeRevoked'); + $this->expectNoTokenIssued(); + $this->expectNoCleanup(); + + $this->assertOAuthError( + $errorType, + fn() => $this->respond($this->sut(true), $this->tokenRequest($payloadChanges, $redirectUri)), + ); + } + + /** + * @dataProvider failedProofProvider + */ + public function testDatabaseModeKeepsTheOrderFromBefore( + array $payloadChanges, + ?string $redirectUri, + string $errorType, + ): void { + // The replay check comes first, and revokes the code's tokens before the client, redirect URI and PKCE + // checks, as before. + $this->authCodeRepositoryMock->expects($this->once())->method('isAuthCodeRevoked')->willReturn(true); + $this->accessTokenRepositoryMock->expects($this->once())->method('revokeByAuthCodeId'); + $this->refreshTokenRepositoryMock->expects($this->once())->method('revokeByAuthCodeId'); + $this->accessTokenRepositoryMock->expects($this->never())->method('revokeAllByAuthCodeId'); + $this->refreshTokenRepositoryMock->expects($this->never())->method('revokeAllByAuthCodeId'); + $this->authCodeRepositoryMock->expects($this->never())->method('recordAuthCodeReplay'); + $this->expectNoTokenIssued(); + + $exception = $this->assertOAuthError( + 'invalid_grant', + fn() => $this->respond($this->sut(false), $this->tokenRequest($payloadChanges, $redirectUri)), + ); + $this->assertStringContainsString('revoked', (string)$exception->getHint()); + } + + public function testDatabaseModeChecksTheExpiryFirst(): void + { + $this->authCodeRepositoryMock->expects($this->never())->method('isAuthCodeRevoked'); + $this->expectNoTokenIssued(); + $this->expectNoCleanup(); + + $exception = $this->assertOAuthError( + 'invalid_grant', + fn() => $this->respond( + $this->sut(false), + $this->tokenRequest(['expire_time' => time() - 1, 'client_id' => 'another-client']), ), ); + $this->assertStringContainsString('expired', (string)$exception->getHint()); + } + + public function testCacheOnlyExpiredCodeWithEvidenceOfUseStillRunsTheCleanup(): void + { + $deadline = time() - 60; + $this->authCodeRepositoryMock->expects($this->once())->method('isAuthCodeRevoked')->willReturn(true); + $this->expectCleanup($deadline); + $this->expectNoTokenIssued(); + + $this->assertOAuthError( + 'invalid_grant', + fn() => $this->respond($this->sut(true), $this->tokenRequest(['expire_time' => $deadline])), + ); + } + + public function testCacheOnlyExpiredUnusedCodeIsRefusedWithoutCleanup(): void + { + $this->authCodeRepositoryMock->expects($this->once())->method('isAuthCodeRevoked')->willReturn(false); + $this->expectNoCleanup(); + $this->expectNoTokenIssued(); + + $exception = $this->assertOAuthError( + 'invalid_grant', + fn() => $this->respond($this->sut(true), $this->tokenRequest(['expire_time' => time() - 1])), + ); + $this->assertStringContainsString('expired', (string)$exception->getHint()); + } + + public function testCacheOnlyMissingCodeIsAnInvalidGrantWithoutCleanup(): void + { + $this->authCodeRepositoryMock->expects($this->once())->method('isAuthCodeRevoked') + ->willThrowException(OAuthServerException::invalidGrant('Authorization code is not known')); + $this->expectNoCleanup(); + $this->expectNoTokenIssued(); + + $this->assertOAuthError('invalid_grant', fn() => $this->respond($this->sut(true), $this->tokenRequest())); + } + + // Consumption. + + public function testCacheOnlyRedemptionConsumesTheCodeWithTheDeadlineAndTheAccessTokenExpiry(): void + { + $deadline = time() + 600; + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(false); + $this->accessTokenRepositoryMock->expects($this->once())->method('persistNewAccessToken'); + $nonces = []; + $this->authCodeRepositoryMock->expects($this->once())->method('consumeAuthCode') + ->with(self::AUTH_CODE_ID, $deadline, $this->accessTokenExpiresAt) + ->willReturnCallback(function () use (&$nonces): bool { + $nonces[] = $this->issuanceContext->getNonce(); + return true; + }); + $this->expectNoCleanup(); + + $this->respond($this->sut(true), $this->tokenRequest(['expire_time' => $deadline])); + + $this->assertIsString($nonces[0]); + $this->assertNotSame('', $nonces[0]); + $this->assertNull($this->issuanceContext->getNonce()); + } + + public function testEachRedemptionDrawsItsOwnIssuanceNonce(): void + { + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(false); + $nonces = []; + $this->authCodeRepositoryMock->method('consumeAuthCode')->willReturnCallback( + function () use (&$nonces): bool { + $nonces[] = $this->issuanceContext->getNonce(); + return true; + }, + ); + $grant = $this->sut(true); + + $this->respond($grant, $this->tokenRequest()); + $this->respond($grant, $this->tokenRequest()); + + $this->assertCount(2, $nonces); + $this->assertNotSame($nonces[0], $nonces[1]); + } + + public function testTheIssuanceNonceIsClearedWhenTheRequestFails(): void + { + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(false); + $this->authCodeRepositoryMock->method('consumeAuthCode') + ->willThrowException(OidcServerException::serverError('gate failure')); + $this->loggerServiceMock->expects($this->never())->method('warning'); + + $this->assertOAuthError('server_error', fn() => $this->respond($this->sut(true), $this->tokenRequest())); + $this->assertNull($this->issuanceContext->getNonce()); + } + + public function testCacheOnlyLostConsumptionRunsTheCleanupAndIsAnInvalidGrant(): void + { + $deadline = time() + 600; + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(false); + $this->authCodeRepositoryMock->expects($this->once())->method('consumeAuthCode')->willReturn(false); + $this->expectCleanup($deadline); + $this->loggerServiceMock->expects($this->once())->method('warning') + ->with($this->stringContains('lock store failure')); + + $this->assertOAuthError( + 'invalid_grant', + fn() => $this->respond($this->sut(true), $this->tokenRequest(['expire_time' => $deadline])), + ); + } + + public function testCacheOnlyGateFailureIsAServerErrorWithoutCleanup(): void + { + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(false); + $this->authCodeRepositoryMock->method('consumeAuthCode') + ->willThrowException(OidcServerException::serverError('gate failure')); + $this->expectNoCleanup(); + + $this->assertOAuthError('server_error', fn() => $this->respond($this->sut(true), $this->tokenRequest())); + } + + public function testDatabaseModeRedemptionConsumesTheCodeAsBefore(): void + { + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(false); + $this->authCodeRepositoryMock->expects($this->once())->method('consumeAuthCode')->willReturn(true); + $this->expectNoCleanup(); + + $this->respond($this->sut(false), $this->tokenRequest()); + } + + // The replay branch. + + public function testReplayBranchRevokesTheDatabaseTokensWhenTheGuardCanNotBeWritten(): void + { + $deadline = time() + 600; + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(true); + $this->authCodeRepositoryMock->expects($this->once())->method('recordAuthCodeReplay') + ->willThrowException(OidcServerException::serverError('cache failure')); + $this->accessTokenRepositoryMock->expects($this->once())->method('revokeAllByAuthCodeId'); + $this->refreshTokenRepositoryMock->expects($this->once())->method('revokeAllByAuthCodeId'); + $this->loggerServiceMock->expects($this->once())->method('error') + ->with($this->stringContains('stay valid until they expire')); + + $this->assertOAuthError( + 'invalid_grant', + fn() => $this->respond($this->sut(true), $this->tokenRequest(['expire_time' => $deadline])), + ); + } + + public function testReplayBranchRunsEachStepWhateverTheOthersDoAndARetryCompletesIt(): void + { + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(true); + $this->authCodeRepositoryMock->expects($this->exactly(2))->method('recordAuthCodeReplay'); + $accessTokenCalls = 0; + $this->accessTokenRepositoryMock->expects($this->exactly(2))->method('revokeAllByAuthCodeId') + ->willReturnCallback(function () use (&$accessTokenCalls): void { + if (++$accessTokenCalls === 1) { + throw new RuntimeException('database failure'); + } + }); + $this->refreshTokenRepositoryMock->expects($this->exactly(2))->method('revokeAllByAuthCodeId'); + $this->loggerServiceMock->expects($this->once())->method('error') + ->with($this->stringContains('access tokens')); + $grant = $this->sut(true); + + $this->assertOAuthError('invalid_grant', fn() => $this->respond($grant, $this->tokenRequest())); + $this->assertOAuthError('invalid_grant', fn() => $this->respond($grant, $this->tokenRequest())); + } + + public function testReplayBranchLogsAFailingRefreshTokenRevocation(): void + { + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(true); + $this->refreshTokenRepositoryMock->method('revokeAllByAuthCodeId') + ->willThrowException(new RuntimeException('database failure')); + $this->loggerServiceMock->expects($this->once())->method('error') + ->with($this->stringContains('refresh tokens')); + + $this->assertOAuthError('invalid_grant', fn() => $this->respond($this->sut(true), $this->tokenRequest())); + } + + public function testCacheOnlyReplayOfACodeWithAScopeNoLongerSupportedStillRunsTheCleanup(): void + { + $deadline = time() + 600; + $this->authCodeRepositoryMock->method('isAuthCodeRevoked')->willReturn(true); + $this->expectCleanup($deadline); + $grant = $this->sut(true); + $scopeRepository = $this->createStub(ScopeRepositoryInterface::class); + $scopeRepository->method('getScopeEntityByIdentifier')->willReturn(null); + $grant->setScopeRepository($scopeRepository); + + $exception = $this->assertOAuthError( + 'invalid_grant', + fn() => $this->respond($grant, $this->tokenRequest(['expire_time' => $deadline])), + ); + $this->assertStringContainsString('revoked', (string)$exception->getHint()); + } + + public function testCacheOnlyRedemptionWithAScopeNoLongerSupportedIsRefusedAfterTheChecks(): void + { + $this->authCodeRepositoryMock->expects($this->once())->method('isAuthCodeRevoked')->willReturn(false); + $this->expectNoTokenIssued(); + $grant = $this->sut(true); + $scopeRepository = $this->createStub(ScopeRepositoryInterface::class); + $scopeRepository->method('getScopeEntityByIdentifier')->willReturn(null); + $grant->setScopeRepository($scopeRepository); + + $this->assertOAuthError('invalid_scope', fn() => $this->respond($grant, $this->tokenRequest())); + } + + // Issuance. + + /** + * Issues a code with a persist slow enough for the second to change, and answers the entity's expiry and the + * payload's. + * + * @return array{0: int, 1: int} + * @throws \Exception + */ + protected function issueCodeWithASlowPersist(bool $isCacheOnly): array + { + $persistedExpiries = []; + $this->authCodeRepositoryMock->method('persistNewAuthCode')->willReturnCallback( + function ($authCode) use (&$persistedExpiries): void { + $persistedExpiries[] = $authCode->getExpiryDateTime()->getTimestamp(); + $start = time(); + while (time() === $start) { + usleep(20000); + } + }, + ); + $grant = $this->sut($isCacheOnly, new AuthCodeEntityFactory(new Helpers(), new ScopeEntityFactory())); + $authorizationRequest = new AuthorizationRequest(); + $authorizationRequest->setClient($this->clientStub); + $authorizationRequest->setUser(new UserEntity('user-id', new DateTimeImmutable(), new DateTimeImmutable())); + $authorizationRequest->setRedirectUri(self::REDIRECT_URI); + $authorizationRequest->setScopes([new ScopeEntity('openid')]); + $authorizationRequest->setAuthorizationApproved(true); + + $response = $grant->completeAuthorizationRequest($authorizationRequest); + + $this->assertInstanceOf(RedirectResponse::class, $response); + $location = $response->generateHttpResponse(new \Laminas\Diactoros\Response())->getHeaderLine('Location'); + parse_str((string)parse_url($location, PHP_URL_QUERY), $query); + $this->assertIsString($query['code'] ?? null); + $payload = json_decode(Crypto::decrypt($query['code'], $this->encryptionKey), true); + $this->assertIsArray($payload); + $this->assertCount(1, $persistedExpiries); + + return [$persistedExpiries[0], (int)$payload['expire_time']]; + } + + public function testCacheOnlyCodePayloadCarriesTheDeadlineComputedBeforeTheCodeWasPersisted(): void + { + [$entityExpiry, $payloadExpiry] = $this->issueCodeWithASlowPersist(true); + + $this->assertSame($entityExpiry, $payloadExpiry); + } + + public function testDatabaseModeCodePayloadCountsTheDeadlineAfterThePersistAsBefore(): void + { + [$entityExpiry, $payloadExpiry] = $this->issueCodeWithASlowPersist(false); + + $this->assertGreaterThan($entityExpiry, $payloadExpiry); + } + + /** + * A redemption through the grant, on real code and access token repositories with codes and access tokens kept in + * the protocol cache only: the token the grant issues is bound to its code, so it is valid once the redemption + * consumed the code, and refused once a replay of the code is recorded. + */ + public function testCacheOnlyRedemptionIssuesATokenBoundToItsCode(): void + { + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturn(true); + $moduleConfig->method('getAccessTokenDuration')->willReturn(new DateInterval('PT1H')); + $moduleConfig->method('getAuthCodeDuration')->willReturn(new DateInterval('PT10M')); + $protocolCache = new ProtocolCache(new Psr16Cache(new ArrayAdapter())); + // Codes and tokens kept in the cache only never reach the database; the replay's cleanup UPDATEs do. + $database = $this->createStub(Database::class); + $database->method('applyPrefix')->willReturnArgument(0); + $clientRepository = $this->createStub(ClientRepository::class); + $clientRepository->method('findById')->willReturn($this->clientStub); + $helpers = new Helpers(); + $authCodeRepository = new AuthCodeRepository( + $moduleConfig, + $database, + $protocolCache, + $clientRepository, + new AuthCodeEntityFactory($helpers, new ScopeEntityFactory()), + $helpers, + $this->issuanceContext, + new ConsumptionGate(new InMemoryStore()), + ); + $hydratedAccessToken = $this->createStub(AccessTokenEntity::class); + $accessTokenEntityFactory = $this->createStub(AccessTokenEntityFactory::class); + $accessTokenEntityFactory->method('fromState')->willReturn($hydratedAccessToken); + $accessTokenRepository = new AccessTokenRepository( + $moduleConfig, + $database, + $protocolCache, + $clientRepository, + $accessTokenEntityFactory, + $helpers, + $authCodeRepository, + $this->issuanceContext, + ); + + // The grant's tokens, as its factory builds them: with whatever code id the grant passes. + $issuedAccessTokenFactory = $this->createStub(AccessTokenEntityFactory::class); + $issuedAccessTokenFactory->method('fromData')->willReturnCallback( + function ( + string $id, + $client, + array $scopes, + DateTimeImmutable $expiry, + $userIdentifier = null, + ?string $authCodeId = null, + ): AccessTokenEntity { + $accessToken = $this->createStub(AccessTokenEntity::class); + $accessToken->method('getIdentifier')->willReturn($id); + $accessToken->method('getAuthCodeId')->willReturn($authCodeId); + $accessToken->method('getExpiryDateTime')->willReturn($expiry); + $accessToken->method('getState')->willReturn([ + 'id' => $id, + 'scopes' => '["openid"]', + 'expires_at' => $expiry->format('Y-m-d H:i:s'), + 'user_id' => (string)$userIdentifier, + 'client_id' => self::CLIENT_ID, + 'is_revoked' => false, + 'auth_code_id' => $authCodeId, + 'requested_claims' => '[]', + ]); + + return $accessToken; + }, + ); + $requestRulesManager = $this->createStub(RequestRulesManager::class); + $requestRulesManager->method('check')->willReturnCallback(function (): ResultBag { + $resultBag = new ResultBag(); + $resultBag->add(new Result(ClientIdRule::class, $this->clientStub)); + $resultBag->add(new Result(ClientAuthenticationRule::class, null)); + $resultBag->add(new Result(CodeVerifierRule::class, self::CODE_VERIFIER)); + + return $resultBag; + }); + $scopeRepository = $this->createStub(ScopeRepositoryInterface::class); + $scopeRepository->method('getScopeEntityByIdentifier')->willReturnCallback( + fn(string $identifier): ScopeEntity => new ScopeEntity($identifier), + ); + $scopeRepository->method('finalizeScopes')->willReturnArgument(0); + $grant = new AuthCodeGrant( + $authCodeRepository, + $accessTokenRepository, + $this->refreshTokenRepositoryMock, + new DateInterval('PT10M'), + $requestRulesManager, + $this->requestParamsResolverStub, + $issuedAccessTokenFactory, + $this->authCodeEntityFactoryStub, + $this->refreshTokenIssuerStub, + $helpers, + $moduleConfig, + $this->loggerServiceMock, + $this->issuanceContext, + ); + $grant->setEncryptionKey($this->encryptionKey); + $grant->setScopeRepository($scopeRepository); + + $codeId = 'code_' . bin2hex(random_bytes(16)); + $deadline = time() + 600; + $authCodeRepository->persistNewAuthCode(new AuthCodeEntity( + $codeId, + $this->clientStub, + [new ScopeEntity('openid')], + (new DateTimeImmutable())->setTimestamp($deadline), + 'user-id', + self::REDIRECT_URI, + null, + )); + $request = $this->tokenRequest(['auth_code_id' => $codeId, 'expire_time' => $deadline]); + $issued = []; + $responseType = $this->createStub(ResponseTypeInterface::class); + $responseType->method('setAccessToken')->willReturnCallback(function ($accessToken) use (&$issued): void { + $issued[] = $accessToken; + }); + + $grant->respondToAccessTokenRequest($request, $responseType, new DateInterval('PT1H')); + + $this->assertCount(1, $issued); + $this->assertInstanceOf(AccessTokenEntity::class, $issued[0]); + $tokenId = $issued[0]->getIdentifier(); + $this->assertSame($codeId, $issued[0]->getAuthCodeId()); + $this->assertFalse($accessTokenRepository->isAccessTokenRevoked($tokenId)); + + // A replay of the code: refused, and the token issued for it is refused from then on. + $this->assertOAuthError( + 'invalid_grant', + fn() => $grant->respondToAccessTokenRequest($request, $responseType, new DateInterval('PT1H')), + ); + $this->assertTrue($accessTokenRepository->isAccessTokenRevoked($tokenId)); } } diff --git a/tests/unit/src/Server/Grants/RefreshTokenGrantTest.php b/tests/unit/src/Server/Grants/RefreshTokenGrantTest.php new file mode 100644 index 000000000..c68f884ac --- /dev/null +++ b/tests/unit/src/Server/Grants/RefreshTokenGrantTest.php @@ -0,0 +1,442 @@ + 'sqlite::memory:', + 'database.username' => null, + 'database.password' => null, + 'database.prefix' => 'phpunit_', + 'database.persistent' => true, + 'database.secondaries' => [], + ], + '', + 'simplesaml', + ); + (new DatabaseMigration())->migrate(); + } + + protected function setUp(): void + { + $this->cacheAdapter = new FaultyArrayAdapter(); + $this->protocolCache = new ProtocolCache(new Psr16Cache($this->cacheAdapter)); + $this->encryptionKey = Key::createNewRandomKey(); + $this->client = $this->createStub(ClientEntity::class); + $this->client->method('getIdentifier')->willReturn(self::CLIENT_ID); + } + + /** + * The repositories of one request on the shared cache, with authorization codes and access tokens kept in the + * cache only. + * + * @return array{0: RefreshTokenRepository, 1: AccessTokenRepository} + */ + protected function repositories(?Database $accessTokenDatabase = null): array + { + $moduleConfig = $this->createStub(ModuleConfig::class); + $moduleConfig->method('isProtocolArtifactCacheOnly')->willReturnCallback( + fn(ProtocolArtifactEnum $artifact): bool => in_array( + $artifact, + [ProtocolArtifactEnum::AuthorizationCode, ProtocolArtifactEnum::AccessToken], + true, + ), + ); + $moduleConfig->method('getAccessTokenDuration')->willReturn(new DateInterval('PT1H')); + $moduleConfig->method('getAuthCodeDuration')->willReturn(new DateInterval('PT10M')); + $moduleConfig->method('getRefreshTokenDuration')->willReturn(new DateInterval('P1M')); + $helpers = new Helpers(); + $issuanceContext = new IssuanceContext(); + $clientRepository = $this->createStub(ClientRepository::class); + $clientRepository->method('findById')->willReturn($this->client); + + // Access tokens hydrated from a row answer its state, revoked once revoke() was called on them. + $accessTokenEntityFactory = $this->createStub(AccessTokenEntityFactory::class); + $accessTokenEntityFactory->method('fromState')->willReturnCallback( + function (array $state): AccessTokenEntity { + $state = array_filter($state, 'is_string', ARRAY_FILTER_USE_KEY); + unset($state['client']); + $accessToken = $this->createStub(AccessTokenEntity::class); + $accessToken->method('revoke')->willReturnCallback(function () use (&$state): void { + $state['is_revoked'] = true; + }); + $accessToken->method('getState')->willReturnCallback(function () use (&$state): array { + return $state; + }); + $accessToken->method('getIdentifier')->willReturn($state['id']); + $accessToken->method('isRevoked')->willReturnCallback(fn(): bool => (bool)$state['is_revoked']); + + return $accessToken; + }, + ); + + $authCodeRepository = new AuthCodeRepository( + $moduleConfig, + Database::getInstance(), + $this->protocolCache, + $clientRepository, + new AuthCodeEntityFactory($helpers, new ScopeEntityFactory()), + $helpers, + $issuanceContext, + new ConsumptionGate(new InMemoryStore()), + ); + $accessTokenRepository = new AccessTokenRepository( + $moduleConfig, + $accessTokenDatabase ?? Database::getInstance(), + $this->protocolCache, + $clientRepository, + $accessTokenEntityFactory, + $helpers, + $authCodeRepository, + $issuanceContext, + ); + $refreshTokenRepository = new RefreshTokenRepository( + $moduleConfig, + Database::getInstance(), + $this->protocolCache, + $accessTokenRepository, + new RefreshTokenEntityFactory($helpers), + $helpers, + ); + + return [$refreshTokenRepository, $accessTokenRepository]; + } + + /** + * New access tokens as the grant creates them, for no authorization code. + */ + protected function issuedAccessTokenFactory(): AccessTokenEntityFactory + { + $accessTokenEntityFactory = $this->createStub(AccessTokenEntityFactory::class); + $accessTokenEntityFactory->method('fromData')->willReturnCallback( + function (string $id, $client, array $scopes, DateTimeImmutable $expiry): AccessTokenEntity { + return $this->newAccessToken($id, $expiry, $scopes); + }, + ); + + return $accessTokenEntityFactory; + } + + /** + * @param \League\OAuth2\Server\Entities\ScopeEntityInterface[] $scopes + */ + protected function newAccessToken(string $id, DateTimeImmutable $expiry, array $scopes = []): AccessTokenEntity + { + $accessToken = $this->createStub(AccessTokenEntity::class); + $accessToken->method('getIdentifier')->willReturn($id); + $accessToken->method('getAuthCodeId')->willReturn(null); + $accessToken->method('getExpiryDateTime')->willReturn($expiry); + $accessToken->method('getScopes')->willReturn($scopes); + $accessToken->method('getState')->willReturn([ + 'id' => $id, + 'scopes' => '["openid","offline_access"]', + 'expires_at' => $expiry->format('Y-m-d H:i:s'), + 'user_id' => self::USER_ID, + 'client_id' => self::CLIENT_ID, + 'is_revoked' => false, + 'auth_code_id' => null, + 'requested_claims' => '[]', + ]); + + return $accessToken; + } + + protected function grant( + RefreshTokenRepository $refreshTokens, + AccessTokenRepository $accessTokens, + ): RefreshTokenGrant { + $helpers = new Helpers(); + $grant = new RefreshTokenGrant( + $refreshTokens, + $this->issuedAccessTokenFactory(), + new RefreshTokenIssuer( + $helpers, + $refreshTokens, + new RefreshTokenEntityFactory($helpers), + $this->createStub(LoggerService::class), + ), + ); + $grant->setRefreshTokenTTL(new DateInterval('P1M')); + $grant->setAccessTokenRepository($accessTokens); + $clientRepository = $this->createStub(ClientRepositoryInterface::class); + $clientRepository->method('validateClient')->willReturn(true); + $clientRepository->method('getClientEntity')->willReturn($this->client); + $grant->setClientRepository($clientRepository); + $scopeRepository = $this->createStub(ScopeRepositoryInterface::class); + $scopeRepository->method('getScopeEntityByIdentifier')->willReturnCallback( + fn(string $identifier): ScopeEntity => new ScopeEntity($identifier), + ); + $grant->setScopeRepository($scopeRepository); + $grant->setEncryptionKey($this->encryptionKey); + $grant->revokeRefreshTokens(true); + + return $grant; + } + + /** + * A login with offline_access: an access token kept in the cache only, promoted for its refresh token. + * + * @return array{0: string, 1: string} The access token's and the refresh token's ids. + */ + protected function login(): array + { + [$refreshTokens, $accessTokens] = $this->repositories(); + $accessToken = $this->newAccessToken( + 'access_token_' . bin2hex(random_bytes(16)), + new DateTimeImmutable('+1 hour'), + ); + $accessTokens->persistNewAccessToken($accessToken); + $refreshToken = new RefreshTokenEntity( + 'refresh_token_' . bin2hex(random_bytes(16)), + new DateTimeImmutable('+1 month'), + $accessToken, + ); + $refreshTokens->persistNewRefreshToken($refreshToken); + + return [$accessToken->getIdentifier(), $refreshToken->getIdentifier()]; + } + + /** + * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException + * @throws \JsonException + */ + protected function refreshRequest(string $accessTokenId, string $refreshTokenId): ServerRequest + { + $payload = [ + 'client_id' => self::CLIENT_ID, + 'refresh_token_id' => $refreshTokenId, + 'access_token_id' => $accessTokenId, + 'scopes' => ['openid', 'offline_access'], + 'user_id' => self::USER_ID, + 'expire_time' => time() + 3600, + ]; + + return (new ServerRequest([], [], null, 'POST'))->withParsedBody([ + 'grant_type' => 'refresh_token', + 'client_id' => self::CLIENT_ID, + 'refresh_token' => Crypto::encrypt(json_encode($payload, JSON_THROW_ON_ERROR), $this->encryptionKey), + ]); + } + + /** + * Refreshes in a new request, and answers the access token and refresh token handed out. + * + * @return array{0: ?AccessTokenEntity, 1: ?RefreshTokenEntity} + * @throws \League\OAuth2\Server\Exception\OAuthServerException + */ + protected function refresh( + string $accessTokenId, + string $refreshTokenId, + ?Database $accessTokenDatabase = null, + ): array { + [$refreshTokens, $accessTokens] = $this->repositories($accessTokenDatabase); + $issued = [null, null]; + $responseType = $this->createStub(ResponseTypeInterface::class); + $responseType->method('setAccessToken')->willReturnCallback(function ($accessToken) use (&$issued): void { + $issued[0] = $accessToken; + }); + $responseType->method('setRefreshToken')->willReturnCallback(function ($refreshToken) use (&$issued): void { + $issued[1] = $refreshToken; + }); + + $this->grant($refreshTokens, $accessTokens)->respondToAccessTokenRequest( + $this->refreshRequest($accessTokenId, $refreshTokenId), + $responseType, + new DateInterval('PT1H'), + ); + + /** @var array{0: ?AccessTokenEntity, 1: ?RefreshTokenEntity} */ + return $issued; + } + + protected function rowOf(string $table, string $id): ?array + { + $rows = Database::getInstance()->read("SELECT * FROM phpunit_$table WHERE id = :id", ['id' => $id])->fetchAll(); + + return empty($rows) ? null : (array)current($rows); + } + + protected function refreshTokenCount(): int + { + return (int)Database::getInstance()->read('SELECT COUNT(*) FROM phpunit_oidc_refresh_token')->fetchColumn(); + } + + protected function assertRefreshIsRefused(string $accessTokenId, string $refreshTokenId): void + { + try { + $this->refresh($accessTokenId, $refreshTokenId); + $this->fail('A revoked refresh token was accepted.'); + } catch (OAuthServerException $exception) { + $this->assertSame('invalid_grant', $exception->getErrorType()); + } + } + + /** + * The access token of a login expires: gone from the cache, its row kept for its refresh token. + */ + protected function expire(string $accessTokenId): void + { + $this->protocolCache->delete('phpunit_oidc_access_token_' . $accessTokenId); + Database::getInstance()->write( + 'UPDATE phpunit_oidc_access_token SET expires_at = :expires_at WHERE id = :id', + ['expires_at' => '2000-01-01 00:00:00', 'id' => $accessTokenId], + ); + } + + public function testRefreshOnceTheOldAccessTokenExpired(): void + { + [$oldAccessTokenId, $oldRefreshTokenId] = $this->login(); + $this->expire($oldAccessTokenId); + + [$newAccessToken, $newRefreshToken] = $this->refresh($oldAccessTokenId, $oldRefreshTokenId); + + $this->assertInstanceOf(AccessTokenEntity::class, $newAccessToken); + $this->assertInstanceOf(RefreshTokenEntity::class, $newRefreshToken); + $this->assertSame(1, (int)$this->rowOf('oidc_access_token', $oldAccessTokenId)['is_revoked']); + $this->assertSame(1, (int)$this->rowOf('oidc_refresh_token', $oldRefreshTokenId)['is_revoked']); + // The new access token is promoted for its refresh token: a row, and an entry no longer marked. + $newAccessTokenId = $newAccessToken->getIdentifier(); + $this->assertNotNull($this->rowOf('oidc_access_token', $newAccessTokenId)); + $this->assertSame( + $newAccessToken->getState(), + $this->protocolCache->get(null, 'phpunit_oidc_access_token_' . $newAccessTokenId), + ); + $this->assertNotNull($this->rowOf('oidc_refresh_token', $newRefreshToken->getIdentifier())); + // The revocations went to the rows only. + $this->assertNull($this->protocolCache->get(null, 'phpunit_oidc_access_token_' . $oldAccessTokenId)); + $this->assertNull($this->protocolCache->get(null, 'phpunit_oidc_refresh_token_' . $oldRefreshTokenId)); + + // A stale unrevoked copy of the old refresh token is not trusted: its reuse is refused. + $this->protocolCache->set( + [ + 'id' => $oldRefreshTokenId, + 'expires_at' => '2100-01-01 00:00:00', + 'access_token_id' => $oldAccessTokenId, + 'is_revoked' => false, + 'auth_code_id' => null, + ], + 600, + 'phpunit_oidc_refresh_token_' . $oldRefreshTokenId, + ); + $this->assertRefreshIsRefused($oldAccessTokenId, $oldRefreshTokenId); + // The new refresh token works. + [$newerAccessToken] = $this->refresh($newAccessTokenId, $newRefreshToken->getIdentifier()); + $this->assertInstanceOf(AccessTokenEntity::class, $newerAccessToken); + } + + /** + * A failure after the old refresh token was revoked (here, the new access token can not be stored) leaves the + * client without a usable refresh token, as a database failure at that point does with the option off. + */ + public function testRefreshFailingAfterTheOldRefreshTokenWasRevoked(): void + { + [$oldAccessTokenId, $oldRefreshTokenId] = $this->login(); + $this->expire($oldAccessTokenId); + $refreshTokenCount = $this->refreshTokenCount(); + $this->cacheAdapter->dropWrites = true; + + try { + $this->refresh($oldAccessTokenId, $oldRefreshTokenId); + $this->fail('A refresh whose access token could not be stored succeeded.'); + } catch (OAuthServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + + $this->cacheAdapter->dropWrites = false; + $this->assertSame($refreshTokenCount, $this->refreshTokenCount()); + $this->assertSame(1, (int)$this->rowOf('oidc_refresh_token', $oldRefreshTokenId)['is_revoked']); + $this->assertRefreshIsRefused($oldAccessTokenId, $oldRefreshTokenId); + } + + /** + * A failure before the old refresh token is revoked (here, revoking the old access token) leaves it usable: the + * client can retry. + */ + public function testRefreshFailingBeforeTheOldRefreshTokenIsRevoked(): void + { + [$oldAccessTokenId, $oldRefreshTokenId] = $this->login(); + $this->expire($oldAccessTokenId); + $realDatabase = Database::getInstance(); + $failingDatabase = $this->createStub(Database::class); + $failingDatabase->method('applyPrefix')->willReturnCallback( + fn(string $table): string => $realDatabase->applyPrefix($table), + ); + $failingDatabase->method('read')->willReturnCallback( + fn(string $statement, array $parameters = []) => $realDatabase->read($statement, $parameters), + ); + $failingDatabase->method('write')->willThrowException(new Exception('The database is down.')); + + try { + $this->refresh($oldAccessTokenId, $oldRefreshTokenId, $failingDatabase); + $this->fail('A refresh whose old access token could not be revoked succeeded.'); + } catch (Exception $exception) { + $this->assertSame('The database is down.', $exception->getMessage()); + } + + $this->assertSame(0, (int)$this->rowOf('oidc_refresh_token', $oldRefreshTokenId)['is_revoked']); + [$newAccessToken] = $this->refresh($oldAccessTokenId, $oldRefreshTokenId); + $this->assertInstanceOf(AccessTokenEntity::class, $newAccessToken); + } +} diff --git a/tests/unit/src/Services/AuthenticationServiceTest.php b/tests/unit/src/Services/AuthenticationServiceTest.php index 4c500730d..c46e866a9 100644 --- a/tests/unit/src/Services/AuthenticationServiceTest.php +++ b/tests/unit/src/Services/AuthenticationServiceTest.php @@ -221,7 +221,9 @@ public function testItReturnsAnUser(): void $this->userRepositoryMock->expects($this->once())->method('getUserEntityByIdentifier') ->willReturn($this->userEntityMock); - $this->userRepositoryMock->expects($this->once())->method('update')->with($this->userEntityMock); + $this->userRepositoryMock->expects($this->once())->method('updateIfClaimsChanged') + ->with($this->userEntityMock); + $this->userRepositoryMock->expects($this->never())->method('update'); $this->claimTranslatorExtractorMock->expects($this->once())->method('extract') ->with(['openid'], $this->isType('array')) @@ -233,6 +235,41 @@ public function testItReturnsAnUser(): void ); } + /** + * The repository decides whether to write, from the database row, so the user it gets must carry this login's + * claims already when it is called. + */ + public function testItHandsAnExistingUserWithThisLoginsClaimsToTheConditionalUpdate(): void + { + $storedUser = (new UserEntityFactory(new Helpers()))->fromState([ + 'id' => self::USERNAME, + 'claims' => json_encode(self::USER_ENTITY_ATTRIBUTES), + 'updated_at' => '2026-01-02 03:04:05', + 'created_at' => '2026-01-01 00:00:00', + ]); + $attributes = [...self::USER_ENTITY_ATTRIBUTES, 'mail' => ['user@example.org']]; + + $this->clientRepositoryMock->method('findById')->willReturn($this->clientEntityMock); + $this->clientEntityMock->method('getIdentifier')->willReturn('client123'); + $this->claimTranslatorExtractorMock->method('extract')->willReturn([]); + + $this->userRepositoryMock->expects($this->once())->method('getUserEntityByIdentifier') + ->with(self::USERNAME)->willReturn($storedUser); + $this->userRepositoryMock->expects($this->once())->method('updateIfClaimsChanged') + ->with($this->callback( + fn (UserEntity $user): bool => $user === $storedUser && $user->getClaims() === $attributes, + )) + ->willReturn(true); + $this->userRepositoryMock->expects($this->never())->method('update'); + $this->userRepositoryMock->expects($this->never())->method('add'); + $this->userEntityFactoryMock->expects($this->never())->method('fromData'); + + $user = $this->mock()->getAuthenticateUser([...self::STATE, 'Attributes' => $attributes]); + + $this->assertSame($storedUser, $user); + $this->assertSame($attributes, $user->getClaims()); + } + /** * @return array */ diff --git a/tests/unit/src/Utils/ConsumptionGateTest.php b/tests/unit/src/Utils/ConsumptionGateTest.php new file mode 100644 index 000000000..abfb3212f --- /dev/null +++ b/tests/unit/src/Utils/ConsumptionGateTest.php @@ -0,0 +1,324 @@ +assertTrue($first->claim('code-1')); + $this->assertFalse($second->claim('code-1')); + $this->assertFalse($first->claim('code-1')); + $this->assertTrue($second->claim('code-2')); + } + + public function testClaimSavesAFreshKeyForTheResource(): void + { + $saved = []; + $store = $this->createMock(PersistingStoreInterface::class); + $store->expects($this->exactly(2))->method('save') + ->willReturnCallback(function (Key $key) use (&$saved): void { + $saved[] = $key; + }); + $store->expects($this->never())->method('delete'); + + $sut = new ConsumptionGate($store); + $sut->claim('code-1'); + $sut->claim('code-1'); + + $this->assertCount(2, $saved); + $this->assertNotSame($saved[0], $saved[1]); + $this->assertSame(ConsumptionGate::resourceFor('code-1'), (string)$saved[0]); + } + + public function testResourceIsAFixedPrefixAndTheCodeIdHash(): void + { + $this->assertSame( + 'oidc_auth_code_claim_' . hash('sha256', 'code id with spaces'), + ConsumptionGate::resourceFor('code id with spaces'), + ); + } + + public function testConflictMeansClaimedByAnotherRequest(): void + { + $store = $this->createStub(PersistingStoreInterface::class); + $store->method('save')->willThrowException(new LockConflictedException()); + + $this->assertFalse((new ConsumptionGate($store))->claim('code-1')); + } + + public static function failureProvider(): array + { + return [ + 'storage' => [new LockStorageException('backend failure')], + 'expired' => [new LockExpiredException('expired')], + 'other' => [new RuntimeException('extension error')], + ]; + } + + #[DataProvider('failureProvider')] + public function testOtherFailuresAreServerErrors(Throwable $failure): void + { + $store = $this->createStub(PersistingStoreInterface::class); + $store->method('save')->willThrowException($failure); + + try { + (new ConsumptionGate($store))->claim('code-1'); + $this->fail('A lock store failure was answered as a claim outcome.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + $this->assertSame($failure, $exception->getPrevious()); + } + } + + /** + * Mode names, resolved in the test: the redis extension may not be installed when providers run. + */ + public static function nonAtomicModeProvider(): array + { + return [ + 'multi' => ['MULTI'], + 'pipeline' => ['PIPELINE'], + ]; + } + + protected function redisMode(string $name): int + { + $mode = constant(\Redis::class . '::' . $name); + $this->assertIsInt($mode); + + return $mode; + } + + #[DataProvider('nonAtomicModeProvider')] + #[RequiresPhpExtension('redis')] + public function testRedisClientInATransactionOrPipelineIsRefusedBeforeSaving(string $mode): void + { + $client = $this->createMock(\Redis::class); + $client->method('getMode')->willReturn($this->redisMode($mode)); + $store = $this->createMock(PersistingStoreInterface::class); + $store->expects($this->never())->method('save'); + + $this->expectException(OidcServerException::class); + + (new ConsumptionGate($store, $client))->claim('code-1'); + } + + #[DataProvider('nonAtomicModeProvider')] + #[RequiresPhpExtension('redis')] + public function testRedisClusterClientInATransactionIsRefused(string $mode): void + { + $client = $this->createMock(\RedisCluster::class); + $client->method('getMode')->willReturn($this->redisMode($mode)); + $store = $this->createMock(PersistingStoreInterface::class); + $store->expects($this->never())->method('save'); + + $this->expectException(OidcServerException::class); + + (new ConsumptionGate($store, $client))->claim('code-1'); + } + + #[RequiresPhpExtension('redis')] + public function testRedisClientInAtomicModeClaims(): void + { + $client = $this->createMock(\Redis::class); + $client->method('getMode')->willReturn(\Redis::ATOMIC); + + $this->assertTrue((new ConsumptionGate(new InMemoryStore(), $client))->claim('code-1')); + } + + #[RequiresPhpExtension('redis')] + public function testRedisClientFailingToAnswerItsModeIsAServerError(): void + { + $client = $this->createMock(\Redis::class); + $client->method('getMode')->willThrowException(new \RedisException('connection refused')); + $store = $this->createMock(PersistingStoreInterface::class); + $store->expects($this->never())->method('save'); + + $this->expectException(OidcServerException::class); + + (new ConsumptionGate($store, $client))->claim('code-1'); + } + + #[RequiresPhpExtension('memcached')] + public function testOtherClientsAreNotChecked(): void + { + $this->assertTrue((new ConsumptionGate(new InMemoryStore(), new \Memcached()))->claim('code-1')); + } + + /** + * A RedisArray of two shards in the given modes, the code's shard first. + */ + protected function redisArrayWithShardsIn(int $codeShardMode, int $otherShardMode, string $codeId): \RedisArray + { + $codeShard = $this->createMock(\Redis::class); + $codeShard->method('getMode')->willReturn($codeShardMode); + $otherShard = $this->createMock(\Redis::class); + $otherShard->method('getMode')->willReturn($otherShardMode); + $client = $this->createMock(\RedisArray::class); + $client->method('_hosts')->willReturn(['10.0.0.2:6379', '10.0.0.3:6379']); + $client->expects($this->once())->method('_target') + ->with(ConsumptionGate::resourceFor($codeId))->willReturn('10.0.0.2:6379'); + $client->method('_instance')->willReturnMap([ + ['10.0.0.2:6379', $codeShard], + ['10.0.0.3:6379', $otherShard], + ]); + + return $client; + } + + #[DataProvider('nonAtomicModeProvider')] + #[RequiresPhpExtension('redis')] + public function testRedisArrayWhoseShardIsInATransactionOrPipelineIsRefusedBeforeSaving(string $mode): void + { + $store = $this->createMock(PersistingStoreInterface::class); + $store->expects($this->never())->method('save'); + $client = $this->redisArrayWithShardsIn($this->redisMode($mode), $this->redisMode('ATOMIC'), 'code-1'); + + $this->expectException(OidcServerException::class); + + (new ConsumptionGate($store, $client))->claim('code-1'); + } + + /** + * The store's time probe may go to another shard than the code's. + */ + #[DataProvider('nonAtomicModeProvider')] + #[RequiresPhpExtension('redis')] + public function testRedisArrayWithAnotherShardInATransactionOrPipelineIsRefused(string $mode): void + { + $store = $this->createMock(PersistingStoreInterface::class); + $store->expects($this->never())->method('save'); + $client = $this->redisArrayWithShardsIn($this->redisMode('ATOMIC'), $this->redisMode($mode), 'code-1'); + + $this->expectException(OidcServerException::class); + + (new ConsumptionGate($store, $client))->claim('code-1'); + } + + #[RequiresPhpExtension('redis')] + public function testRedisArrayWhoseShardsAreAtomicClaims(): void + { + $client = $this->redisArrayWithShardsIn($this->redisMode('ATOMIC'), $this->redisMode('ATOMIC'), 'code-1'); + + $this->assertTrue((new ConsumptionGate(new InMemoryStore(), $client))->claim('code-1')); + } + + #[RequiresPhpExtension('redis')] + public function testRedisArrayWithoutAShardForTheCodeIsAServerError(): void + { + $client = $this->createMock(\RedisArray::class); + $client->method('_hosts')->willReturn(['10.0.0.2:6379']); + $client->method('_target')->willReturn('10.0.0.9:6379'); + $client->method('_instance')->willReturn(false); + $store = $this->createMock(PersistingStoreInterface::class); + $store->expects($this->never())->method('save'); + + $this->expectException(OidcServerException::class); + + (new ConsumptionGate($store, $client))->claim('code-1'); + } + + /** + * A gate which takes the given object for a Relay client, with Relay's option and mode constants stood in. + */ + protected function gateWithRelayClient(PersistingStoreInterface $store, object $client): ConsumptionGate + { + return new class ($store, $client) extends ConsumptionGate { + protected function isRelayClient(object $client): bool + { + return true; + } + + protected function relayConstant(string $name): ?int + { + return [ + 'OPT_THROW_ON_ERROR' => 105, + 'OPT_PHPREDIS_COMPATIBILITY' => 104, + 'ATOMIC' => 1, + 'MULTI' => 2, + 'PIPELINE' => 4, + ][$name] ?? null; + } + }; + } + + /** + * A stand-in Relay client with the given options and mode. + * + * @param array $options + */ + protected function relayClient(array $options, int $mode): object + { + return new class ($options, $mode) { + public function __construct(private readonly array $options, private readonly int $mode) + { + } + + public function getOption(int $option): mixed + { + return $this->options[$option] ?? false; + } + + public function getMode(bool $masked = false): int + { + return $this->mode; + } + }; + } + + public static function refusedRelayClientProvider(): array + { + return [ + 'throws on errors' => [[105 => true, 104 => true], 1], + 'phpredis compatibility off' => [[105 => false, 104 => false], 1], + 'in a transaction' => [[105 => false, 104 => true], 2], + 'in a pipeline' => [[105 => false, 104 => true], 4], + ]; + } + + /** + * @param array $options + */ + #[DataProvider('refusedRelayClientProvider')] + public function testRelayClientWhichWouldTakeAFailureOrAQueuedReplyForAClaimIsRefused( + array $options, + int $mode, + ): void { + $store = $this->createMock(PersistingStoreInterface::class); + $store->expects($this->never())->method('save'); + + $this->expectException(OidcServerException::class); + + $this->gateWithRelayClient($store, $this->relayClient($options, $mode))->claim('code-1'); + } + + public function testRelayClientWithThrowOnErrorOffCompatibilityOnAndAtomicClaims(): void + { + $gate = $this->gateWithRelayClient(new InMemoryStore(), $this->relayClient([105 => false, 104 => true], 1)); + + $this->assertTrue($gate->claim('code-1')); + } +} diff --git a/tests/unit/src/Utils/FaultyArrayAdapter.php b/tests/unit/src/Utils/FaultyArrayAdapter.php new file mode 100644 index 000000000..b3bc05c7d --- /dev/null +++ b/tests/unit/src/Utils/FaultyArrayAdapter.php @@ -0,0 +1,95 @@ + Keys of the saves which stored a value, in order. */ + public array $savedKeys = []; + + public function save(CacheItemInterface $item): bool + { + if ($this->refuseWrites) { + return false; + } + + if ($this->dropWrites) { + return true; + } + + $isSaved = parent::save($item); + + if ($isSaved) { + $this->savedKeys[] = $item->getKey(); + + if ($this->afterSave !== null) { + ($this->afterSave)($item->getKey()); + } + } + + return $isSaved; + } + + public function getItem(mixed $key): CacheItem + { + if ($this->beforeRead !== null) { + ($this->beforeRead)((string)$key); + } + + if ($this->missReads) { + return parent::getItem('missing.' . (string)$key); + } + + $item = parent::getItem($key); + + if ($this->readFilter !== null && $item->isHit()) { + $filtered = ($this->readFilter)((string)$key, $item->get()); + $item->set($filtered); + } + + return $item; + } + + public function getItems(array $keys = []): iterable + { + $items = []; + foreach ($keys as $key) { + $item = $this->getItem($key); + if ($item->getKey() === $key) { + $items[$key] = $item; + } + } + + return $items; + } +} diff --git a/tests/unit/src/Utils/LockStoreDoubles/Predis1ClusterDouble.php b/tests/unit/src/Utils/LockStoreDoubles/Predis1ClusterDouble.php new file mode 100644 index 000000000..aef049ab5 --- /dev/null +++ b/tests/unit/src/Utils/LockStoreDoubles/Predis1ClusterDouble.php @@ -0,0 +1,12 @@ +extensions, true); + } + + protected function isPredisAvailable(): bool + { + return $this->hasPredis; + } + + protected function predisClientInterface(): string + { + return PredisClientDouble::class; + } + + protected function predis1ClusterInterface(): string + { + return Predis1ClusterDouble::class; + } + + protected function predis2ClusterInterface(): string + { + return Predis2ClusterDouble::class; + } + }; + } + + public static function acceptedMemcachedDsnProvider(): array + { + return [ + 'memcached' => ['memcached://10.255.255.1'], + 'with port' => ['memcached://10.255.255.1:11212'], + 'socket' => ['memcached:///var/run/memcached.sock'], + 'hosts' => ['memcached:?host[10.255.255.1:11211]&host[10.255.255.2:11211]'], + 'auto eject' => ['memcached://10.255.255.1?auto_eject_hosts=1'], + 'remove failed' => ['memcached://10.255.255.1?remove_failed_servers=1'], + 'replicas' => ['memcached://10.255.255.1?number_of_replicas=1'], + 'buffer writes off' => ['memcached://10.255.255.1?buffer_writes=0'], + ]; + } + + #[DataProvider('acceptedMemcachedDsnProvider')] + #[RequiresPhpExtension('memcached')] + public function testAcceptsMemcachedDsn(string $dsn): void + { + $this->sut()->validate($dsn); + $this->addToAssertionCount(1); + } + + /** + * Builds of the memcached extension read the string "true" for a boolean option differently: 3.4.0 reads it as + * 0, the build CI installs as on. What is checked is the client built from the DSN, so the verdict follows it. + */ + #[RequiresPhpExtension('memcached')] + public function testJudgesBufferWritesGivenAsAStringByTheClientBuilt(): void + { + $dsn = 'memcached://10.255.255.1?buffer_writes=true'; + $client = $this->sut()->buildClient($dsn); + $this->assertInstanceOf(\Memcached::class, $client); + + if ((bool)$client->getOption(\Memcached::OPT_BUFFER_WRITES)) { + $this->expectException(ConfigurationError::class); + $this->expectExceptionMessage('buffer_writes'); + } + + $this->sut()->validate($dsn); + $this->addToAssertionCount(1); + } + + public static function acceptedRedisDsnProvider(): array + { + return [ + 'redis' => ['redis://10.255.255.1'], + 'with password and database' => ['redis://secret@10.255.255.1:6380/2'], + 'rediss' => ['rediss://10.255.255.1'], + 'valkey' => ['valkey://10.255.255.1'], + 'valkeys' => ['valkeys://10.255.255.1'], + 'socket' => ['redis:///var/run/redis.sock'], + 'not lazy, unreachable' => ['redis://127.0.0.1:1?lazy=0'], + 'sharded' => ['redis:?host[10.255.255.1:6379]&host[10.255.255.2:6379]'], + 'cluster' => ['redis:?host[10.255.255.1:7000]&host[10.255.255.2:7000]&redis_cluster=1'], + 'sentinel' => ['redis:?host[10.255.255.1:26379]&host[10.255.255.2:26379]&redis_sentinel=mymaster'], + 'password with "?" and "#"' => ['redis://user:p?ss#w@10.255.255.1:6379'], + 'password with "?", then options' => ['redis://p?ss@10.255.255.1:6379/1?timeout=2&lazy=0'], + 'fragment' => ['redis://10.255.255.1?class=Redis#locks'], + 'cluster failover' => ['redis:?host[10.255.255.1:7000]&redis_cluster=1&failover=distribute&lazy=0'], + ]; + } + + #[DataProvider('acceptedRedisDsnProvider')] + #[RequiresPhpExtension('redis')] + public function testAcceptsRedisDsnWithoutConnecting(string $dsn): void + { + $this->sut()->validate($dsn); + $this->addToAssertionCount(1); + } + + public static function refusedMemcachedOptionProvider(): array + { + return [ + 'buffer_writes' => ['memcached://10.255.255.1?buffer_writes=1', 'buffer_writes'], + 'noreply' => ['memcached://10.255.255.1?noreply=1', 'noreply'], + // libmemcached turns "noreply" on with UDP, so either option may be the one named. + 'use_udp' => ['memcached://10.255.255.1?use_udp=1', 'noreply'], + ]; + } + + #[DataProvider('refusedMemcachedOptionProvider')] + #[RequiresPhpExtension('memcached')] + public function testRefusesMemcachedDsnWhichAnswersBeforeTheServerDecides(string $dsn, string $option): void + { + $this->expectException(ConfigurationError::class); + $this->expectExceptionMessage($option); + + $this->sut()->validate($dsn); + } + + public static function refusedMemcachedClientOptionProvider(): array + { + return [ + 'buffer_writes' => ['OPT_BUFFER_WRITES', 'buffer_writes'], + 'noreply' => ['OPT_NOREPLY', 'noreply'], + // libmemcached turns "noreply" on with UDP, and that option is checked first. + 'use_udp' => ['OPT_USE_UDP', 'noreply'], + ]; + } + + #[DataProvider('refusedMemcachedClientOptionProvider')] + #[RequiresPhpExtension('memcached')] + public function testRefusesMemcachedClientWhichAnswersBeforeTheServerDecides(string $option, string $name): void + { + $client = new \Memcached(); + $client->addServer('10.255.255.1', 11211); + $optionValue = constant(\Memcached::class . '::' . $option); + $this->assertIsInt($optionValue); + $this->assertTrue($client->setOption($optionValue, true)); + + $this->expectException(ConfigurationError::class); + $this->expectExceptionMessage($name); + + $this->sut()->validate($client); + } + + #[RequiresPhpExtension('memcached')] + public function testRefusesMemcachedClientWithoutServers(): void + { + $this->expectException(ConfigurationError::class); + $this->expectExceptionMessage('no servers'); + + $this->sut()->validate(new \Memcached()); + } + + #[RequiresPhpExtension('memcached')] + public function testAcceptsMemcachedClientWithTheTradeOffOptions(): void + { + $client = new \Memcached(); + $client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true); + $client->setOption(\Memcached::OPT_REMOVE_FAILED_SERVERS, true); + $client->addServer('10.255.255.1', 11211); + + $this->sut()->validate($client); + $this->addToAssertionCount(1); + } + + public static function acceptedRedisClientClassProvider(): array + { + return [['Redis'], ['RedisCluster'], ['RedisArray']]; + } + + #[DataProvider('acceptedRedisClientClassProvider')] + #[RequiresPhpExtension('redis')] + public function testAcceptsRedisClientObject(string $class): void + { + /** @var class-string $class */ + $this->sut()->validate($this->createStub($class)); + $this->addToAssertionCount(1); + } + + public static function refusedValueProvider(): array + { + return [ + 'null' => [null], + 'empty string' => [''], + 'integer' => [6379], + 'array' => [['memcached://10.255.255.1']], + 'unknown scheme' => ['mysql://10.255.255.1'], + 'no scheme' => ['10.255.255.1:11211'], + 'scheme in capitals' => ['REDIS://10.255.255.1'], + 'unsupported object' => [new stdClass()], + ]; + } + + #[DataProvider('refusedValueProvider')] + public function testRefusesAnythingElse(mixed $lockStore): void + { + $this->expectException(ConfigurationError::class); + + $this->sut()->validate($lockStore); + } + + public static function unbuildableRedisDsnProvider(): array + { + return [ + 'no host' => ['redis://'], + 'cluster and sentinel' => ['redis://10.255.255.1?redis_cluster=1&redis_sentinel=mymaster'], + 'unsupported client class' => ['redis://10.255.255.1?class=stdClass'], + 'database not a number' => ['redis://10.255.255.1/abc'], + 'host not an array' => ['redis://10.255.255.1?host=10.255.255.2'], + 'password with "?", unsupported class' => ['redis://p?ss@10.255.255.1:6379?class=stdClass'], + 'password with "?", database not a number' => ['redis://p?ss@10.255.255.1:6379/abc'], + // Read only when the client connects: a lazy client would not reveal it. + 'cluster failover misspelt' => ['redis:?host[10.255.255.1:7000]&redis_cluster=1&failover=typo&lazy=0'], + ]; + } + + #[DataProvider('unbuildableRedisDsnProvider')] + #[RequiresPhpExtension('redis')] + public function testRefusesRedisDsnFromWhichNoClientCanBeBuilt(string $dsn): void + { + $this->expectException(ConfigurationError::class); + + $this->sut()->validate($dsn); + } + + /** + * The DSN rebuilt for the check must be split the way the cache component splits it. + */ + #[RequiresPhpExtension('redis')] + public function testChecksEveryRedisOptionWhateverTheOutputSeparator(): void + { + $outputSeparator = ini_get('arg_separator.output'); + ini_set('arg_separator.output', '&'); + + try { + $this->sut()->validate('redis://10.255.255.1?timeout=2&class=stdClass'); + $this->fail('An unsupported client class after another option was accepted.'); + } catch (ConfigurationError) { + $this->addToAssertionCount(1); + } finally { + ini_set('arg_separator.output', (string)$outputSeparator); + } + } + + public function testRefusesMemcachedDsnWithoutTheExtension(): void + { + $this->expectException(ConfigurationError::class); + $this->expectExceptionMessage('memcached extension'); + + $this->sutWith(['redis'])->validate('memcached://10.255.255.1'); + } + + public function testRefusesRedisDsnWithoutAnyClient(): void + { + $this->expectException(ConfigurationError::class); + $this->expectExceptionMessage('predis'); + + $this->sutWith(['memcached'])->validate('redis://10.255.255.1'); + } + + public function testRefusesAPredis1ClusterClientObject(): void + { + $connection = new class implements Predis1ClusterDouble { + }; + $client = $this->createStub(PredisClientDouble::class); + $client->method('getConnection')->willReturn($connection); + + $this->expectException(ConfigurationError::class); + $this->expectExceptionMessage('Predis 1'); + + $this->sutWith()->validate($client); + } + + public function testAcceptsPredisClientObjectsOtherThanAPredis1Cluster(): void + { + $predis2Cluster = new class implements Predis1ClusterDouble, Predis2ClusterDouble { + }; + $single = new stdClass(); + + foreach ([$predis2Cluster, $single] as $connection) { + $client = $this->createStub(PredisClientDouble::class); + $client->method('getConnection')->willReturn($connection); + + $this->sutWith()->validate($client); + } + + $this->addToAssertionCount(2); + } + + public static function dsnWithPasswordProvider(): array + { + return [ + 'Memcached, refused option' => ['memcached://user:s3cr3t-pa55@10.255.255.1?noreply=1', 'memcached'], + 'Memcached, unbuildable' => ['memcached://user:s3cr3t-pa55@', 'memcached'], + 'Redis, unbuildable' => ['redis://user:s3cr3t-pa55@10.255.255.1?class=s3cr3t-pa55', 'redis'], + ]; + } + + #[DataProvider('dsnWithPasswordProvider')] + public function testMessagesDoNotDiscloseTheDsn(string $dsn, string $extension): void + { + if (!extension_loaded($extension)) { + $this->markTestSkipped("The $extension extension is not installed."); + } + + try { + $this->sut()->validate($dsn); + $this->fail('The lock store was accepted.'); + } catch (ConfigurationError $error) { + $this->assertStringNotContainsString('s3cr3t-pa55', $error->getMessage()); + } + } + + #[RequiresPhpExtension('memcached')] + public function testBuildsAMemcachedClientFromADsnWithoutConnecting(): void + { + $client = $this->sut()->buildClient('memcached://10.255.255.1:11211'); + + $this->assertInstanceOf(\Memcached::class, $client); + $this->assertTrue((bool)$client->getOption(\Memcached::OPT_BINARY_PROTOCOL)); + } + + #[RequiresPhpExtension('redis')] + public function testBuildsALazyRedisClientFromADsnWithoutConnecting(): void + { + $client = $this->sut()->buildClient('redis://127.0.0.1:1'); + + $this->assertInstanceOf(\Redis::class, $client); + } + + public function testAnswersAClientObjectAsGiven(): void + { + $client = new stdClass(); + + $this->assertSame($client, $this->sut()->buildClient($client)); + } + + public function testRefusesToBuildFromAnythingElse(): void + { + $this->expectException(InvalidArgumentException::class); + + $this->sut()->buildClient(null); + } + + public function testRefusesToBuildFromAnUnsupportedScheme(): void + { + $this->expectException(InvalidArgumentException::class); + + $this->sut()->buildClient('mysql://10.255.255.1'); + } +} diff --git a/tests/unit/src/Utils/ProtocolCacheTest.php b/tests/unit/src/Utils/ProtocolCacheTest.php new file mode 100644 index 000000000..4af769542 --- /dev/null +++ b/tests/unit/src/Utils/ProtocolCacheTest.php @@ -0,0 +1,167 @@ +adapter = new FaultyArrayAdapter(); + } + + protected function sut(): ProtocolCache + { + return new ProtocolCache(new Psr16Cache($this->adapter)); + } + + public static function valueProvider(): array + { + return [ + 'string' => ['clean'], + 'array' => [['id' => 'abc', 'is_revoked' => false, 'cache_only' => true, 'scopes' => '["openid"]']], + ]; + } + + #[DataProvider('valueProvider')] + public function testSetCheckedStoresAndConfirmsTheValue(mixed $value): void + { + $sut = $this->sut(); + + $sut->setChecked($value, 60, 'key', 'element'); + + $this->assertSame($value, $sut->get(null, 'key', 'element')); + $this->assertSame([ProtocolCache::keyFor('key', 'element')], $this->adapter->savedKeys); + } + + public function testSetCheckedThrowsWhenTheWriteIsRefused(): void + { + $this->adapter->refuseWrites = true; + + try { + $this->sut()->setChecked('clean', 60, 'key'); + $this->fail('A refused write was confirmed.'); + } catch (OidcServerException $exception) { + $this->assertSame('server_error', $exception->getErrorType()); + } + } + + public function testSetCheckedThrowsWhenTheWriteAnswersTrueWithoutLanding(): void + { + $this->adapter->dropWrites = true; + + $this->expectException(OidcServerException::class); + + $this->sut()->setChecked('clean', 60, 'key'); + } + + public function testSetCheckedThrowsWhenTheReadBackMisses(): void + { + $this->adapter->missReads = true; + + $this->expectException(OidcServerException::class); + + $this->sut()->setChecked('clean', 60, 'key'); + } + + public function testSetCheckedThrowsWhenTheReadBackDiffers(): void + { + $this->adapter->readFilter = fn(string $key, mixed $value): string => 'replayed'; + + $this->expectException(OidcServerException::class); + + $this->sut()->setChecked('clean', 60, 'key'); + } + + public function testSetCheckedThrowsWhenTheReadBackDiffersInType(): void + { + $this->adapter->readFilter = fn(string $key, mixed $value): array => ['is_revoked' => 0]; + + $this->expectException(OidcServerException::class); + + $this->sut()->setChecked(['is_revoked' => false], 60, 'key'); + } + + public function testSetCheckedThrowsWhenTheWriteLandsAndTheReadBackFails(): void + { + $this->adapter->afterSave = function (): void { + $this->adapter->missReads = true; + }; + + try { + $this->sut()->setChecked('clean', 60, 'key'); + $this->fail('A write which could not be read back was confirmed.'); + } catch (OidcServerException) { + // The write landed, and the outcome is unknown to the caller. + } + + $this->adapter->missReads = false; + $this->assertSame('clean', $this->sut()->get(null, 'key')); + } + + public function testSetCheckedWrapsACacheException(): void + { + $this->adapter->afterSave = function (): void { + throw new RuntimeException('backend failure'); + }; + + $this->expectException(OidcServerException::class); + + $this->sut()->setChecked('clean', 60, 'key'); + } + + public static function nonPositiveTtlProvider(): array + { + return [[0], [-1], [-3600]]; + } + + #[DataProvider('nonPositiveTtlProvider')] + public function testSetCheckedRefusesATtlNotAboveZeroBeforeWriting(int $ttl): void + { + try { + $this->sut()->setChecked('clean', $ttl, 'key'); + $this->fail('A write with a TTL not above zero was accepted.'); + } catch (OidcServerException) { + // Expected. + } + + $this->assertSame([], $this->adapter->savedKeys); + } + + public function testGetManyAnswersEachEntryUnderItsName(): void + { + $sut = $this->sut(); + $sut->set(['a' => 1], 60, 'entry', 'one'); + $sut->set('clean', 60, 'guard', 'one'); + + $this->assertSame( + ['entry' => ['a' => 1], 'guard' => 'clean', 'other' => null], + $sut->getMany([ + 'entry' => ['entry', 'one'], + 'guard' => ['guard', 'one'], + 'other' => ['other'], + ]), + ); + } + + public function testGetManyAnswersNullForEveryEntryWhenReadsFail(): void + { + $sut = $this->sut(); + $sut->set('clean', 60, 'guard'); + $this->adapter->missReads = true; + + $this->assertSame(['guard' => null], $sut->getMany(['guard' => ['guard']])); + } +}