Fix cache-key asymmetry, cache TOCTOU, response decode robustness, encoding leak#4
Closed
fabcocco wants to merge 1 commit into
Closed
Fix cache-key asymmetry, cache TOCTOU, response decode robustness, encoding leak#4fabcocco wants to merge 1 commit into
fabcocco wants to merge 1 commit into
Conversation
…coding leak Four robustness fixes in BaseApi, found during an audit of a consuming application (data-hub ERPlus gateway): 1. Cache-key asymmetry: getCacheKey() built the key from the raw endpoint (with ":param" placeholders) plus the request data. getEndpoint() consumes ":param" entries from the request data while resolving the URL, so the lookup key (computed before resolution) and the store key (computed after) never matched for keyed endpoints - their cache could never hit. The key is now built from the resolved endpoint. 2. Cache TOCTOU: loadResponseFromCache() used Cache::has() followed by Cache::get(); an entry expiring between the two calls assigned null to the typed array|object $response property and crashed with a TypeError. Now a single get() with a sentinel default. 3. Response decode robustness: setResponse() assigned json_decode() output directly to the typed property. Invalid JSON or empty bodies (null) and JSON scalar bodies (e.g. a bare string from an RPC-style action) crashed with an opaque TypeError. Invalid JSON now throws a descriptive exception, empty bodies become an empty object, and scalars are wrapped as (object)['value' => ...]. 4. Temporary request-encoding leak: setTemporaryRequestEncoding() was only restored inside setResponse(), so a transport failure (connection timeout) before a response leaked the temporary encoding into the next call. executeCall() now restores it on any throw. Also casts $requestEncoding for strtolower() to avoid the PHP 8.4 "passing null to non-nullable" deprecation (the property is nullable). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
There was a problem hiding this comment.
Pull request overview
This PR improves BaseApi robustness around caching, request encoding handling, and JSON response decoding to prevent cache misses, TOCTOU-related type errors, and response-body decoding crashes.
Changes:
- Makes cache keys symmetric by basing them on the resolved endpoint (so keyed endpoints can actually hit the cache).
- Eliminates cache
has()/get()TOCTOU by using a singleCache::get()with a sentinel and validating cached types. - Adds resilient response decoding (
decodeResponseBody) to handle empty bodies, invalid JSON (with a descriptive exception), and JSON scalars (wrapped to preserve thearray|objectcontract), and ensures temporary request encoding is restored even when the transport throws.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Four robustness fixes in
BaseApi, found during an adversarial audit of a consuming application (the data-hub ERPlus gateway). All are backwards compatible — no signature changes, suggested as a patch release (v2.0.1).1. Cache-key asymmetry — keyed-endpoint cache could never hit
getCacheKey()built the key from the raw endpoint (with:paramplaceholders) plus the request data.getEndpoint()consumes:paramentries from$this->requestDatawhile resolving the URL, so:loadResponseFromCache(), before resolution) contained the placeholder endpoint + the param in the data, whilecacheResponse(), after resolution) contained the same raw endpoint but without the consumed param.The two keys never match for keyed endpoints (
modelFind-styleentity/:idcalls), so their responses were written to the cache but never read back. The key is now built from the resolved endpoint (getEndpoint()is idempotent via$endpointCache), making lookup and store symmetric.2. Cache TOCTOU → TypeError
loadResponseFromCache()usedCache::has()followed byCache::get(). An entry expiring between the two calls assignsnullto the typedarray|object $responseproperty → uncaughtTypeError. Now a singleget()with a sentinel default (plus a type guard on the cached value).3. Response decode robustness — scalar/invalid/empty bodies crashed
setResponse()assignedjson_decode($response->body())directly to the typedarray|objectproperty:null→ opaqueTypeError;getnxtposnr/getnextworkordernumberdeclare200 → {"type": "string"}) →TypeErroron every successful call.Now: invalid JSON throws a descriptive
Exception, an empty body becomes an emptystdClass(e.g. 204 on DELETE), and scalars are wrapped as(object) ['value' => …]so thearray|objectcontract keeps holding.4. Temporary request-encoding leak on transport failure
setTemporaryRequestEncoding()is only restored insidesetResponse(). If the request itself throws before a response exists (connection refused/timeout), the temporary encoding leaked into the subsequent call on the same instance — relevant for singletons.executeCall()now restores it on any throw (restoreRequestEncoding()is a no-op when nothing is pending).Also casts
$requestEncodingforstrtolower()to avoid the PHP 8.4 passing null to non-nullable deprecation (the property is?stringand defaults tonull).🤖 Generated with Claude Code