fix(backend): validate inputs and add resilience guards in database mcp api key ( proposed)

Closed
AL
8h ago
+180-12

Summary

Hardens backend/database/mcp_api_key.py against path traversal, empty input allocations, and unexpected type crashes:

• Input Sanitization & Path Traversal Guard:
• Adds _clean_user_id(user_id) rejecting empty strings, non-string types, and path traversal characters (/, \\, ..), protecting Firestore user document collections.
• Adds _clean_key_name(name) validating non-empty names, normalizing whitespace, capping length at 255 characters, and guarding against raw token leakage.
• Early Validation & Fast Fail-Safe:
• In get_mcp_keys_for_user_with_repair_info(), malformed or empty user IDs return fast ([], frozenset()) without issuing unnecessary remote Firestore stream queries.
• In delete_mcp_key(), invalid or malformed user IDs and key IDs no-op cleanly rather than provoking Firestore document path traversal errors.
• In get_api_key_auth_result(), validates that api_key is a string before calling .startswith(), preventing AttributeError crashes on non-string inputs.
• Hermetic Unit Tests:
• Added 43 comprehensive unit tests in backend/tests/unit/test_mcp_api_key_resilience.py covering valid paths, invalid types, traversal attacks, length boundaries, and mock database operations (100% pass in 0.78s).

Failure-Class: none

Proposed Bounty

• Suggested reward: $50
• Contributor payout: PayPal chenpaiteng@gmail.com

Verification

• pytest backend/tests/unit/test_mcp_api_key_resilience.py (43 passed in 0.78s)
• pytest backend/tests/unit/test_mcp_api_key_auth_context.py (6 passed in 1.15s)
• black --line-length 120 --skip-string-normalization backend/database/mcp_api_key.py backend/tests/unit/test_mcp_api_key_resilience.py (clean)