# Error Handling Strategy: Security-Focused
## Error Types
The security-focused repository manager handles a simplified set of errors:
1. **Not a Directory**: CWD is not a directory (rare edge case)
2. **No Access**: CWD cannot be read (permission issue)
3. **Not a Git Repository**: CWD is valid but not a git repository
4. **Git Operation Failed**: Git command execution errors
## Error Handling Approach
The security-focused approach simplifies error handling significantly:
### 1. CWD Validation
The manager validates only the current working directory:
```python
def _validate_cwd(self):
"""Validate current working directory."""
cwd = os.getcwd()
# Basic validation (should rarely fail)
if not os.path.isdir(cwd):
self._context.is_valid_directory = False
self._context.validation_error = "Current working directory is not a directory"
return
if not os.access(cwd, os.R_OK):
self._context.is_valid_directory = False
self._context.validation_error = "No read access to current working directory"
return
self._context.is_valid_directory = True
# Check if it's a git repository
git_dir = os.path.join(cwd, ".git")
self._context.is_git_repository = os.path.exists(git_dir)
```
### 2. Operation Validation
Simple validation before operations:
```python
def validate_cwd_for_operation() -> Tuple[bool, Optional[Dict[str, Any]]]:
"""Validate current working directory is suitable for operations."""
manager = SecureRepositoryManager()
if not manager._context.is_valid_directory:
return False, create_error_response(
RepositoryError(
message=manager._context.validation_error or "Invalid directory",
repo_path=os.getcwd()
)
)
return True, None
```
### 3. Git-Specific Validation
Additional validation for git operations:
```python
def validate_cwd_for_git_operation() -> Tuple[bool, Optional[Dict[str, Any]]]:
"""Validate current working directory is a git repository."""
# First check basic validity
is_valid, error = validate_cwd_for_operation()
if not is_valid:
return False, error
manager = SecureRepositoryManager()
if not manager._context.is_git_repository:
return False, create_error_response(
RepositoryError(
message="Current directory is not a git repository",
repo_path=os.getcwd(),
suggestions=[
"Run 'git init' to initialize a repository",
"Change to a directory containing a git repository"
]
)
)
return True, None
```
### 4. Tool Integration
Tools have simplified error handling:
```python
@mcp.tool()
def get_enhanced_git_status() -> Dict[str, Any]:
"""Get enhanced git repository status for current directory."""
# Simple validation - no path parameters to check
is_valid, error_response = validate_cwd_for_git_operation()
if not is_valid:
return error_response
# Always use CWD
service = GitPythonCore(repo_path=os.getcwd())
return service.get_enhanced_status()
```
## Error Response Format
Simplified error responses focused on CWD:
```json
{
"success": false,
"error": "Current directory is not a git repository",
"error_type": "RepositoryError",
"details": {
"current_directory": "/current/working/directory",
"is_git_repository": false
},
"suggestions": [
"Run 'git init' to initialize a repository",
"Change to a directory containing a git repository"
]
}
```
## No Path-Related Errors
The security-focused design eliminates entire categories of errors:
1. **No "Repository Not Found"**: Always uses CWD which exists
2. **No Path Traversal Errors**: Cannot specify other paths
3. **No Environment Variable Errors**: No environment variables used
4. **No Path Resolution Errors**: No complex path logic
## Simplified Error Messages
Error messages are clearer and more actionable:
```python
# Before (with path parameters)
"Repository path does not exist: /some/complex/path"
"No access to repository: /another/path"
"Invalid repository path provided"
# After (CWD only)
"Current directory is not a git repository"
"No read access to current directory"
"Git operations require a git repository"
```
## Error Logging
Simplified logging focused on CWD:
```python
logger.warning(f"Current directory is not a git repository: {os.getcwd()}")
logger.error(f"Git operation failed in: {os.getcwd()}")
```
## Testing Error Handling
Simplified testing approach:
### 1. Unit Tests
```python
def test_not_git_repository():
"""Test error when CWD is not a git repository."""
with temporary_directory() as temp_dir:
os.chdir(temp_dir)
# Should fail - not a git repo
is_valid, error = validate_cwd_for_git_operation()
assert not is_valid
assert "not a git repository" in error["error"]
```
### 2. Permission Tests
```python
@patch("os.access")
def test_no_read_access(mock_access):
"""Test error when CWD has no read access."""
mock_access.return_value = False
is_valid, error = validate_cwd_for_operation()
assert not is_valid
assert "No read access" in error["error"]
```
### 3. Edge Case Tests
```python
def test_git_operations_in_git_repo():
"""Test successful validation in git repository."""
with temporary_git_repo() as repo:
os.chdir(repo.working_dir)
# Should succeed
is_valid, error = validate_cwd_for_git_operation()
assert is_valid
assert error is None
```
## Benefits of Simplified Error Handling
1. **Fewer Error Cases**: Eliminates path-related errors entirely
2. **Clearer Messages**: Always about current directory
3. **Easier Testing**: No complex path scenarios to test
4. **Better Security**: No information leakage about filesystem
5. **Simpler Code**: Less error handling logic needed