-
Notifications
You must be signed in to change notification settings - Fork 19
feat: Auto-detect API Keys from Common Locations (Issue #255) #279
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Implements Issue #255 - Auto-detect API keys from common locations This feature improves the onboarding experience by automatically finding API keys from common configuration locations. Features: - Searches environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY) - Scans shell configs (~/.bashrc, ~/.zshrc, ~/.bash_profile, etc.) - Checks .env files in current directory and home - Checks ~/.config/cortex/ and ~/.cortex/ directories - Supports both Anthropic and OpenAI key formats - Key masking for safe display - Deduplication of keys found in multiple locations - Validation of key format and length Search locations: - ~/.bashrc, ~/.bash_profile, ~/.zshrc, ~/.zprofile, ~/.profile - ~/.env, ./.env, ./.env.local - ~/.config/cortex/.env, ~/.config/cortex/config - ~/.cortex/.env, ~/.cortex/config Usage: from cortex.api_key_detector import auto_configure_api_key key = auto_configure_api_key() # Auto-sets env var if found 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
WalkthroughThis pull request introduces an API key auto-detection module that scans environment variables and common configuration file locations (e.g., Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
| import pytest | ||
| import tempfile | ||
| from pathlib import Path | ||
| from unittest.mock import patch, MagicMock |
| from cortex.api_key_detector import ( | ||
| Provider, | ||
| DetectedKey, | ||
| APIKeyDetector, | ||
| auto_configure_api_key, | ||
| get_detection_summary, | ||
| validate_detected_key, | ||
| KEY_PATTERNS, | ||
| ENV_VAR_NAMES, | ||
| ) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
cortex/api_key_detector.py (1)
154-158: Consider catching more specific exceptions.Per static analysis hint, catching bare
Exceptionis overly broad. While robust error handling is important here, narrowing the scope to expected file I/O exceptions improves clarity.except PermissionError: logger.debug(f"Permission denied reading {filepath}") - except Exception as e: + except (OSError, IOError) as e: logger.debug(f"Error reading {filepath}: {e}")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
cortex/api_key_detector.py(1 hunks)tests/test_api_key_detector.py(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/test_api_key_detector.py (1)
cortex/api_key_detector.py (11)
Provider(20-23)DetectedKey(27-46)APIKeyDetector(93-255)auto_configure_api_key(258-295)get_detection_summary(298-322)validate_detected_key(325-346)masked_key(42-46)detect_from_environment(161-187)_search_file(126-159)detect_all(203-227)get_best_key(229-255)
cortex/api_key_detector.py (1)
cortex/logging_system.py (3)
debug(207-209)warning(215-217)info(211-213)
🪛 Gitleaks (8.30.0)
tests/test_api_key_detector.py
[high] 80-80: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
[high] 404-404: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
[high] 416-416: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
🪛 Ruff (0.14.8)
cortex/api_key_detector.py
156-156: Do not catch blind exception: Exception
(BLE001)
🔇 Additional comments (15)
cortex/api_key_detector.py (9)
1-24: LGTM!Module docstring, imports, and
Providerenum are well-structured and appropriate for the functionality.
26-47: LGTM!The
DetectedKeydataclass withmasked_keyproperty provides good security practice for displaying keys in logs and UI without exposing the full sensitive value.
49-63: LGTM!The regex patterns correctly identify keys based on both variable name and key prefix. The patterns properly handle export statements, quoted values, and simple assignments.
71-90: Missing search locations from Issue #255 requirements.Per Issue #255, the detector should check
~/.config/anthropicand~/.config/openaidirectories. These locations are not included inSEARCH_LOCATIONS. Consider adding them to align with the requirements.SEARCH_LOCATIONS = [ # Shell configuration files "~/.bashrc", "~/.bash_profile", "~/.zshrc", "~/.zprofile", "~/.profile", # Environment files "~/.env", "./.env", "./.env.local", # Config directories "~/.config/cortex/.env", "~/.config/cortex/config", + "~/.config/anthropic/api_key", + "~/.config/anthropic/.env", + "~/.config/openai/api_key", + "~/.config/openai/.env", "~/.cortex/.env", "~/.cortex/config", # Project-specific "./cortex.env", ]
93-124: LGTM!The
__init__correctly handles path expansion and additional paths. The_extract_key_from_contentmethod properly iterates through patterns and returns the first match.
161-187: LGTM!The environment detection correctly validates key prefixes before accepting them. The separate checks for each provider ensure proper validation.
189-256: LGTM!The detection and selection logic is well-structured. Environment variables correctly take priority, deduplication works by key value, and the provider preference system with Anthropic as default is clearly documented.
258-295: LGTM!The
auto_configure_api_keyfunction provides a clean entry point with appropriate error handling for unknown providers and optional environment variable configuration.
325-346: LGTM!The validation function provides appropriate format checks for both providers with clear error messages.
tests/test_api_key_detector.py (6)
1-50: LGTM!Imports are appropriate and
TestDetectedKeycorrectly validates the masking behavior for both long and short keys.
52-98: LGTM!Pattern tests comprehensively cover export statements, simple assignments, and
.envfile formats. The Gitleaks warning on line 80 is a false positive—these are clearly test fixtures, not real API keys.
100-281: LGTM!Comprehensive test coverage for
APIKeyDetectorincluding environment detection, file-based detection, deduplication, and key preference logic. Proper use of temporary files with cleanup.
283-346: LGTM!Tests correctly verify
auto_configure_api_keybehavior including environment variable setting, theset_env=Falsecase, and preferred provider handling.
348-447: LGTM!Good coverage of
get_detection_summaryandvalidate_detected_keyfunctions. The Gitleaks warnings on lines 404 and 416 are false positives—these are test fixtures with intentionally invalid prefixes to verify validation logic.
449-510: LGTM!Integration tests with realistic
.bashrcand.envfile content provide excellent coverage for real-world scenarios. Proper cleanup withtry/finallyensures no leftover temp files.
| return key | ||
|
|
||
|
|
||
| def get_detection_summary() -> Dict[str, any]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix type hint: use Any instead of any.
The type hint uses lowercase any which is not the typing construct. Use Any from the typing module for proper type annotation.
-def get_detection_summary() -> Dict[str, any]:
+def get_detection_summary() -> Dict[str, Any]:Also add Any to the imports on line 13:
-from typing import Optional, Dict, List, Tuple
+from typing import Optional, Dict, List, Tuple, AnyCommittable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In cortex/api_key_detector.py around line 298, the return type annotation uses
the lowercase built-in name `any` instead of the typing construct `Any`; change
the signature to use `Any` (e.g., Dict[str, Any]) and add `Any` to the imports
on line 13 (from typing import Any, ...). Ensure the import list includes Any
and update the function annotation accordingly.



Summary
Implements Issue #255: Auto-detect API keys from common locations
This PR adds automatic API key detection to improve the onboarding experience. New users often have API keys already configured in their shell or .env files - Cortex can now find and use them automatically.
Features
sk-ant-a...mnop)Search Locations
$ANTHROPIC_API_KEY/$OPENAI_API_KEY~/.bashrc,~/.bash_profile~/.zshrc,~/.zprofile~/.profile~/.env,./.env,./.env.local~/.config/cortex/,~/.cortex/Usage
Test Plan
Files Changed
cortex/api_key_detector.py- New detection module (290 lines)tests/test_api_key_detector.py- Comprehensive test suite (430 lines)Closes #255
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests
✏️ Tip: You can customize this high-level summary in your review settings.