fix: implement LRU eviction for SSL context cache and unify OAuth error handling#4241
Open
bogdanmariusc10 wants to merge 2 commits intomainfrom
Conversation
…or handling Issue 1 - SSL Context Cache Thrash (HIGH): - Replace full cache wipe with LRU eviction using OrderedDict - Move cache entries to end on access to mark as recently used - Remove only oldest entry when cache reaches capacity (100 entries) - Prevents cache thrash in deployments with >100 gateways using custom CA certs - Gracefully handle empty timestamps dict during eviction Issue 2 - OAuth Error Handling Consistency (MEDIUM): - Standardize refresh_token to use raise_for_status() like other OAuth flows - Preserve special handling for 400/401 errors (invalid refresh tokens) - Maintain retry logic with exponential backoff for transient errors - Improves code maintainability and predictability Test Updates: - Update SSL cache tests to expect LRU behavior (100 entries maintained) - Update OAuth tests to mock raise_for_status() with HTTPStatusError - Add Mock import to test_oauth_manager_pkce.py - Adjust error message regex patterns for new error handling Fixes cache thrash under high traffic and unifies OAuth error patterns. Signed-off-by: Bogdan-Marius-Catanus <bogdan-marius.catanus@ibm.com>
7 tasks
- Remove unused typing.Any and typing.Dict imports (ruff F401) - Fix mypy type errors for _SSL_CONTEXT_CACHE_TTL variable - Add type annotation for ca_certificate parameter to accept str | bytes - Remove trailing whitespace from test file (pre-commit hook) Resolves mypy assignment and arg-type errors while maintaining backward compatibility. Signed-off-by: Bogdan-Marius-Catanus <bogdan-marius.catanus@ibm.com>
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.
🔗 Related Issue
Closes #4239
📝 Summary
This PR fixes two critical bugs affecting production deployments:
SSL Context Cache Thrash (HIGH): The SSL context cache was performing a full wipe when reaching capacity (100 entries), causing severe performance degradation in deployments with >100 gateways using custom CA certificates. Now implements proper LRU (Least Recently Used) eviction.
OAuth Error Handling Inconsistency (MEDIUM): The
refresh_tokenmethod used manual status code checking while other OAuth flows (_client_credentials_flow,_password_flow) usedraise_for_status(). This inconsistency has been unified for better maintainability.🏷️ Type of Change
🔧 Changes Made
Issue 1: SSL Context Cache LRU Eviction
File:
mcpgateway/utils/ssl_context_cache.pyOrderedDictfromcollectionsfor LRU trackingdicttoOrderedDictmove_to_end()calls on cache hits to mark entries as recently usedpopitem(last=False)to remove only the oldest entryBefore (Cache Thrash):
After (LRU Eviction):
Issue 2: OAuth Error Handling Consistency
File:
mcpgateway/services/oauth_manager.pyrefresh_tokento useresponse.raise_for_status()like other OAuth flowsHTTPStatusErrorexception handlingBefore (Manual Status Check):
After (Consistent raise_for_status):
Test Updates
Files:
tests/unit/mcpgateway/utils/test_ssl_context_cache.py,tests/unit/mcpgateway/services/test_oauth_manager.py,tests/unit/mcpgateway/services/test_oauth_manager_pkce.pyraise_for_status()withHTTPStatusErrorexceptionsMockimport totest_oauth_manager_pkce.py🧪 Verification
make lintmake testmake coverage✅ Checklist
make black isort pre-commit)📓 Notes
Impact Assessment
Issue 1 - SSL Cache (HIGH SEVERITY):
Issue 2 - OAuth Consistency (MEDIUM SEVERITY):
raise_for_status()pattern with specialized exception handlingTesting Strategy
All existing tests updated to reflect new behavior:
HTTPStatusErrorexceptions for status code validationBackward Compatibility
✅ Fully backward compatible - No breaking changes to public APIs or behavior, only internal implementation improvements.