Commit Graph
27 Commits
Author SHA1 Message Date
Sammy Farida 90eb9bd128 Security: Fix command substitution bypass and implement version 2 policy schema (#76)
* Security: Fix command substitution bypass and implement version 2 policy schema

- Hard-ban all command substitution ($(), backticks, $((())) to prevent policy bypasses
- Implement version 2 policy schema with simple_binaries and structured rules
- Remove legacy commands fnmatch patterns (breaking change)
- Add shlex-based argument parsing for argument-aware rule matching
- Block path-based binaries by default for security
- Update config/policy.yml and examples/example-policy.yml to version 2 schema
- Add comprehensive tests for command substitution blocking and version 2 schema
- Update documentation to reflect version 2 schema only
- Update CHANGELOG with security fix and breaking changes

Fixes: Command substitution bypass vulnerabilities (15+ bypasses blocked)
Breaking: Legacy commands patterns removed, version 2 schema only

* Add comprehensive test coverage and improve policy validation

- Add new test files for comprehensive coverage:
  - test_ssh_coverage.py: SSH client edge cases and error handling
  - test_ssh_integration.py: SSH integration scenarios
  - test_utilities_coverage.py: Async task management and progress callbacks
  - test_mcp_server_coverage.py: MCP server coverage (notification handlers, context logging, resources)

- Expand test_ssh.py with extensive test cases (1000+ lines added)

- Improve policy.py structured rule matching:
  - Fix validation to require binary field for structured rules
  - Add validation to ensure structured rules have at least one restriction
  - Improve allow_extra_args logic with path_args support
  - Fix edge cases in argument matching
  - Add type annotations for mypy compliance

- Update documentation:
  - Update CHANGELOG.md with test coverage details
  - Update README.md, SECURITY.md, and wiki documentation
  - Update example-policy.yml with version 2 schema
  - Update CONTRIBUTING.md with script documentation
  - Fix markdownlint issues in SECURITY.md

- Script maintenance:
  - Add scripts/README.md documenting all scripts
  - Add scripts/test-mcp-automated.py for automated testing
  - Remove obsolete scripts (fix-markdownlint.py, fix-markdownlint.sh, test-annotations.sh)
  - Enhance scripts/validate-mcp-schema.py with improved type checking

- Update pyproject.toml configuration

- Clean up .cursor/commands/issues.md (no longer needed)

- Fix code quality issues:
  - Fix ruff UP038: Use X | Y instead of (X, Y) in isinstance
  - Add missing type annotations for mypy compliance
  - Fix unreachable code warnings

* Add .cursor/ to .gitignore and remove from tracking

* fix: Add pytest-asyncio dependency to fix async test failures

- Add pytest-asyncio>=0.21.0,<1.0.0 to test dependencies
- Configure asyncio_mode = 'auto' in pytest settings
- Fixes 10 failing async tests in test_mcp_server_coverage.py

* fix: Fix all broken code blocks and formatting issues in markdown files

- Fix unclosed code blocks in docs/CONTRIBUTING.md
- Fix broken code blocks in docs/wiki/12-Troubleshooting.md
- Fix broken code blocks in docs/wiki/13-Contributing.md
- Fix broken code blocks in docs/wiki/06-Configuration.md
- Fix broken code blocks in docs/wiki/11-Observability-Audit.md
- Wrap JSON examples in proper code blocks with json language specifier
- Fix code block language specifiers
- Ensure all code blocks are properly closed

Addresses PR review feedback from CodeBotD
2025-11-20 23:24:07 -05:00
Sammy Farida 9bd5cc7e9a feat: Add .env file support for consolidated secrets management (#72)
- Add support for consolidated .env file in secrets directory
- Maintain backward compatibility with individual secret files
- Implement caching with proper cache invalidation on missing files
- Add comprehensive security validations (permissions, size, symlinks)
- Support comments, quoted values, and values with = characters
- Update all documentation with .env file usage and examples
- Add 20 comprehensive tests covering all edge cases

Resolution order: env vars → .env file → individual files

Fixes cache initialization bug where missing files were cached as empty
2025-11-18 20:34:05 -05:00
Sammy Farida ff57b466c4 fix: address code review issues #1, #2, #3, #7, #11 (#69)
- Fix SSH client exception handling to catch only KeyError/AttributeError (Issue #1)
- Fix DNS cache race condition with 1-second grace period (Issue #2)
- Fix cleanup thread to support graceful shutdown and log exceptions (Issue #3)
- Improve type hints for _ctx_log payload parameter (Issue #7)
- Increase command hash length from 12 to 16 characters for better collision resistance (Issue #11)

BREAKING CHANGE: Command hash length increased from 12 to 16 characters.
External tools parsing command hashes may need updates.

Added comprehensive unit tests for all fixes (11 new tests).
All 280 tests pass.
2025-11-18 11:41:57 -05:00
Sammy Farida f874b13d34 Security/fix command chaining bypass (#68)
* fix: Remove unused variable in fix-markdownlint.py

* fix: Remove unused code_block_lang variable

* chore: Update documentation, workflows, and examples

- Updated all wiki documentation files (markdownlint fixes)
- Updated GitHub workflows and issue templates
- Updated example configuration files
- Updated metadata.json and pyproject.toml
- Updated Dockerfile and compose files
- Updated validation scripts

Note: yamllint warnings are style-only (missing ---, line length) and don't affect functionality
2025-11-18 07:00:42 -05:00
Sammy Farida efa6e19099 feat: Improve SSH error handling with specific messages and per-host … (#67)
* feat: Improve SSH error handling with specific messages and per-host exception handling

- Enhanced SSH error messages with specific failure reasons:
  * Authentication failures, timeouts, connection refused
  * DNS resolution failures, host key verification errors
  * Key file errors (not found, permission denied, format invalid, passphrase required)
  * Network unreachable errors
- Added per-host exception handling in ssh_run_on_tag:
  * Individual host failures no longer stop entire operation
  * Each host's result included in results array with exit_code: -1 for failures
  * Proper task cleanup on failure
- Improved async task error handling with sanitized error messages
- Comprehensive test coverage:
  * 12 new unit tests for SSH error scenarios
  * 5 new integration tests for per-host handling
  * 7 new MCP compliance tests
- Added MCP Inspector test script for error handling validation
- Updated documentation:
  * Troubleshooting guide with detailed error message explanations
  * Tools reference with error handling documentation
  * CHANGELOG with all improvements

All error messages are sanitized for security (no IPs, hostnames, or file paths exposed).
Follows MCP specification requirements for error handling patterns.

* fix: Replace socket.timeout with TimeoutError per ruff UP041 rule

- Changed socket.timeout to TimeoutError in test_ssh_client_connection_timeout
- Fixes ruff linting error UP041
- Test still passes (TimeoutError is handled by existing exception handler)
2025-11-17 17:29:59 -05:00
Sammy Farida e6dbeffd52 feat: Add Docker MCP Gateway secret injection support (#66)
- Support direct environment variable secret resolution (Docker MCP Gateway pattern)
- Maintain backward compatibility with prefixed env vars (MCP_SSH_SECRET_*)
- Update secret resolution priority: direct env > prefixed env > file
- Add comprehensive test coverage (9 unit tests, 4 integration tests)
- Update documentation with Docker MCP Gateway integration details
- Support all 10 secrets (5 passphrase, 5 password) from Docker MCP Registry

Resolves compatibility with Docker MCP Gateway while preserving existing
standalone deployment behavior.
2025-11-17 15:32:40 -05:00
Sammy Farida 28392722a1 feat: add MCP resources, context logging, and denial hints (#63)
* feat: add MCP resources, context logging, and denial hints

* fix: resolve merge markers in mcp server

* chore: apply black formatting
2025-11-14 22:08:44 -05:00
Sammy Farida de29acc0f5 feat: Add MCP prompts and structured JSON denial responses (#58)
- Add 6 MCP prompts for LLM guidance:
  - ssh_orchestrator_usage: General usage guidance for SSH orchestrator tools
  - ssh_policy_denied_guidance: How to handle policy denials
  - ssh_network_denied_guidance: How to handle network policy denials
  - ssh_missing_host_guidance: How to handle missing host aliases
  - ssh_missing_credentials_guidance: How to handle missing/incomplete credentials
  - ssh_config_change_workflow: Global rules for config change suggestions

- Convert denial responses to structured JSON format:
  - Policy denials return JSON with status, reason, alias, hash, command
  - Network denials return JSON with status, reason, alias, hostname, detail
  - Improves LLM understanding and enables better prompt-based guidance
  - Per MCP recommendation for better structured outputs
  - Updated ssh_run(), ssh_run_async(), and post-connect network denials

- Add comprehensive tests:
  - tests/test_prompts.py: 7 tests for prompt registration and content
  - tests/test_server_tools.py: 4 tests for JSON denial responses
  - All 186 tests passing

- Update documentation:
  - CHANGELOG.md: Added v0.4.0 entry with detailed changes
  - docs/CONTRIBUTING.md: Updated prompts section
  - docs/wiki/07-Tools-Reference.md: Added Prompts section and updated Error Handling section

- Bump version to 0.4.0 in pyproject.toml
2025-11-13 19:24:29 -05:00
Sammy Farida 6a08a13f0b Feature/structured output (#56)
* feat: convert MCP tools to structured output

- Convert all 13 tools to return dicts instead of json.dumps() strings
- Update return type annotations to ToolResult (dict | str)
- FastMCP now automatically generates JSON schemas for clients
- Update all tests to expect structured responses
- Update CONTRIBUTING.md to reflect structured output pattern
- Add MCP Inspector testing documentation
- Update wiki docs with structured output examples
- All tests passing, verified with MCP Inspector

This makes the server more MCP-native and provides better client
experience with automatic schema generation and validation.

Breaking change: Tools now return structured dicts. Clients using
FastMCP will automatically get schemas. Error cases still return
strings for backward compatibility.

* docs: remove emojis and update MCP rules for future prompt support

- Remove emojis from MCP rules section
- Remove 'NO prompts' restrictions
- Add note that prompts will be supported in the future per MCP spec

* docs: remove redundant policy-engine-flowchart.md

Policy engine flowcharts are already covered in the wiki:
- Simplified Policy Evaluation Flow in 04-Architecture.md
- Rule Evaluation Order and Override Hierarchy in 06.3-policy.yml.md
- Network Policy documentation in 06.3-policy.yml.md

The detailed flowcharts were redundant with existing wiki documentation.

* docs: remove unused diagram .mmd files

The diagram files in assets/diagrams/ were not being referenced.
Diagrams are embedded directly in markdown files using mermaid code blocks.
Updated README.md to reflect that diagrams should be embedded, not referenced.

* fix: resolve linting issues

- Move ToolResult type alias after all imports to fix E402
- Remove unused json import from test_server_tools.py
- Apply black formatting to fix line length issues
2025-11-13 13:25:10 -05:00
Sammy Farida ed75e1b7f2 Refactor notification logging in mcp_server.py to simplify debug and … (#42)
* Refactor notification logging in mcp_server.py to simplify debug and info message handling by removing unnecessary parameters.

* docs: record notification handler fix
2025-11-08 21:03:58 -05:00
Sammy Farida 0e8a71020f Adopt MCP context notifications for async tasks (#40) 2025-11-07 17:31:13 -05:00
Sammy Farida 46a8919d95 Security: Fix SSH host key validation (CWE-295) (#35)
* Security: Fix SSH host key validation (CWE-295)

Fix CodeQL security alert by removing unsafe Paramiko host key policies.

Changes:
- Remove AcceptPolicy class and AutoAddPolicy() usage
- Always use RejectPolicy() for strict host key verification
- Deprecate host_key_auto_add and require_known_host=False options
- Add deprecation warnings when unsafe configurations are detected
- Update all SSH connections to require known_hosts entry
- Update documentation and examples to reflect security requirements

Fixes CodeQL alert: py/paramiko-missing-host-key-validation
References: CWE-295

Breaking Change: Configurations using host_key_auto_add: true or
require_known_host: false will now fail with clear error messages.
Users must populate known_hosts file before connecting.

* Fix: Apply black formatting and remove unused import
2025-11-04 13:01:43 -05:00
Sammy Farida e65d4106ed feat: Add security audit logging for path traversal attempts (PR10) (#34)
**Security Enhancement:** Comprehensive security audit logging for security-relevant events.

**Implementation:**
- Created _log_security_event() function with structured JSON format
- Unified all security event logging to use audit format (replaced _log_err calls)
- Includes both Unix timestamp (ts) and ISO 8601 timestamp (timestamp)
- Logs attempted_path and resolved_path for path-related events
- Logs additional context via additional_data parameter

**Security Event Types Logged:**
- path_traversal_attempt: Path traversal detected in secret/key resolution
- file_validation_failed: Directory/symlink/non-file paths rejected
- file_size_limit_exceeded: Oversized YAML files rejected
- input_length_limit_exceeded: Oversized string inputs rejected
- invalid_secret_name: Invalid characters in secret names
- dns_rate_limit_exceeded: DNS resolution rate limit violations
- command_bypass_attempt: Command denial bypass attempts detected

**Audit Log Format:**
{
  "level": "error",
  "kind": "security_audit",
  "type": "security_event",
  "event_type": "path_traversal_attempt",
  "ts": 1762112167.394149,
  "timestamp": "2025-11-02T14:36:07-0500",
  "attempted_path": "../etc/passwd",
  "resolved_path": "/app/secrets/../etc/passwd",
  "reason": "path_outside_allowed_directory",
  "base_dir": "/app/secrets"
}

**Tests Added:**
- 7 comprehensive tests for audit logging
- Tests for log format validation (JSON structure, required fields)
- Tests for path traversal attempt logging
- Tests for invalid file access logging
- Tests for oversized file logging
- Tests for timestamp inclusion (Unix + ISO format)
- Tests that logging failures don't break functionality

**Documentation:**
- Updated SECURITY.md with security audit logging section
- Updated Observability-Audit.md with security audit log format and event types
- Updated CHANGELOG.md with PR10 entry

**Security Impact:** Enables security monitoring and incident response via
structured audit trail. All security-relevant events are logged with full
context for SIEM integration and forensic analysis.

Fixes security vulnerability from CodeQL analysis.
2025-11-02 14:53:36 -05:00
Sammy Farida 615335a2bf feat: Add input length limits for configuration parameters (PR9) (#33)
**Security Enhancement:** Prevent resource exhaustion via oversized string inputs.

**Implementation:**
- Added MAX_SECRET_NAME_LENGTH (100 chars) and MAX_KEY_PATH_LENGTH (500 chars) constants
- Added length validation in _resolve_secret() for secret names
- Added length validation in _resolve_key_path() for SSH key paths
- Length validation occurs before other validations (character checks, path traversal)
- Security event logging for length limit violations

**Length Limits:**
- Secret names: 100 characters max
- SSH key paths: 500 characters max
- MCP tool parameters (from PR6):
  - Alias: 100 characters
  - Command: 10,000 characters
  - Tag: 50 characters
  - Task ID: 200 characters

**Tests Added:**
- 8 comprehensive tests for length limit validation
- Tests for secret names: at limit, exceeds limit, under limit
- Tests for key paths: at limit, exceeds limit, under limit
- Tests for validation order (length before character/traversal checks)

**Documentation:**
- Updated SECURITY.md with input length limits section
- Updated credentials.yml.md with length limit details
- Updated CHANGELOG.md with PR9 entry

**Security Impact:** Prevents resource exhaustion attacks via oversized
string inputs in configuration files and user-controlled parameters.
Complements PR6 input validation for MCP tool parameters.

Fixes security vulnerability from CodeQL analysis.
2025-11-02 14:29:20 -05:00
Sammy Farida 59cf8c4c63 feat: Add rate limiting for DNS resolution (PR8) (#32)
**Security Enhancement:** Prevent DNS-based DoS attacks and reduce load.

**Implementation:**
- Added in-memory rate limiter: max 10 resolutions/second per hostname
- Added DNS result caching with 60-second TTL
- Added 5-second timeout for DNS resolution
- Thread-safe implementation for concurrent access
- Rate limit violations logged as security events

**Rate Limiting Features:**
- Per-hostname tracking (separate limits for different hostnames)
- Time-window based (sliding 1-second window)
- Returns empty list when rate limited (fails closed)

**Caching Features:**
- Caches successful and failed resolutions
- Prevents repeated lookups for invalid hostnames
- Reduces load on DNS servers

**Tests Added:**
- 9 comprehensive tests for DNS rate limiting and caching
- Tests for normal resolution, rate limiting, caching, time windows
- Tests for per-hostname isolation and cache expiration
- Tests for empty hostname and timeout handling

**Documentation:**
- Updated SECURITY.md with DNS rate limiting section
- Updated Security-Model.md with DNS rate limiting details
- Updated CHANGELOG.md with PR8 entry

**Security Impact:** Prevents DNS-based DoS attacks by limiting
resolution frequency and caching results, reducing load on DNS
infrastructure.

Fixes security vulnerability from CodeQL analysis.
2025-11-02 14:11:04 -05:00
Sammy Farida 4937a77917 feat: Improve command denial logic to prevent bypasses (PR7) (#31)
* feat: Improve command denial logic to prevent bypasses (PR7)

**Security Enhancement:** Prevent command denial bypasses via obfuscation.

**Implementation:**
- Added _normalize_command() function for bypass detection
- Removes quotes (single and double) from commands
- Handles escaped characters (normalizes \ to space)
- Normalizes whitespace (collapses multiple spaces/tabs)
- Enhanced is_allowed() with dual checking (original + normalized)
- Added token-based matching for exact pattern matches
- Added _log_bypass_attempt() for security event logging

**Bypass Techniques Prevented:**
- Quote obfuscation: 'rm -rf /', "rm -rf /"
- Escaped characters: rm\ -rf\ /
- Whitespace variations: rm    -rf    /, rm\t-rf\t/
- Mixed techniques: echo "rm\\ -rf\\ /"

**Tests Added:**
- 12 comprehensive tests for bypass prevention
- Tests for quotes, escaping, whitespace variations
- Tests for command normalization function
- Tests that legitimate commands still work

**Documentation:**
- Updated SECURITY.md with bypass prevention section
- Updated policy.yml.md with bypass prevention details
- Documented limitations (complex obfuscation may still bypass)

**Security Impact:** Significantly reduces risk of command denial
bypasses through common obfuscation techniques. Perfect prevention
would require full command parsing.

Fixes security vulnerability from CodeQL analysis.

* fix: Format _log_bypass_attempt method signature to pass Black linting

- Split method parameters across multiple lines to comply with Black formatting
- Fixes linting failure in PR #31 for 'Improve command denial logic to prevent bypasses (PR7)'
2025-11-02 13:43:12 -05:00
Sammy Farida 6a53e551c1 feat: Add input validation for user-controlled parameters (PR6) (#30)
**Security Enhancement:** Prevent injection attacks and resource exhaustion.

**Implementation:**
- Added validation helper functions: _validate_alias(), _validate_command(),
  _validate_tag(), _validate_task_id()
- Alias validation: 100 char limit, alphanumeric/dash/underscore/dot only
- Command validation: 10,000 char limit, rejects null bytes and control chars
- Tag validation: 50 char limit, alphanumeric/dash/underscore/dot only
- Task ID validation: 200 char limit, format validation
- Applied validation to all MCP tools that accept user input
- Security event logging for injection attempts (null bytes, control chars)

**Tests Added:**
- 21 comprehensive tests for all validation functions
- Tests for valid inputs, empty inputs, length limits, invalid characters
- Tests for null byte and control character injection prevention

**Documentation:**
- Updated SECURITY.md with input validation section
- Updated Tools-Reference.md with input validation requirements
- Updated CHANGELOG.md with PR6 entry

**Security Impact:** Prevents injection attacks (null bytes, control characters)
and resource exhaustion (length limits) via malformed user inputs.

Fixes security vulnerability from CodeQL analysis.
2025-11-02 12:34:16 -05:00
Sammy Farida a9e5d61b51 feat: Sanitize error messages to prevent information disclosure (PR5) (#29)
**Security Enhancement:** Prevent information disclosure via error messages.

**Implementation:**
- Added sanitize_error() function in utilities.py with comprehensive pattern matching
- Removes sensitive information: file paths, IPs, hostnames, credentials, ports
- All exception handlers in mcp_server.py sanitize user-facing errors
- Detailed errors logged to stderr (JSON structured logs) for debugging
- Updated ssh_client.py to provide generic error messages
- Original detailed errors preserved in exception chains for logging

**Sanitization Patterns:**
- File paths (absolute, relative, Windows paths)
- IP addresses (IPv4)
- Hostnames and domain names
- User@host patterns
- Credential references (passwords, keys, secrets)
- Port numbers
- System-specific directory paths

**Tests Added:**
- 13 comprehensive tests for all sanitization patterns
- Tests for edge cases and complex error messages
- Tests for generic fallback messages

**Documentation:**
- Updated SECURITY.md with error sanitization section
- Updated Configuration.md with sanitization details
- Added examples of sanitized vs. detailed error messages

**Security Impact:** Prevents information disclosure vulnerabilities where
error messages could reveal system architecture, file paths, network
topology, or credential locations.

Fixes security vulnerability from CodeQL analysis.
2025-11-02 12:00:59 -05:00
Sammy Farida 2182b00a1c feat: Add file size limits for YAML loading (PR4) (#28)
**Security Enhancement:** Prevent resource exhaustion attacks via oversized YAML files.

**Implementation:**
- Added MAX_YAML_FILE_SIZE constant (10MB) for configuration files
- Updated _load_yaml() to check file size before parsing
- Returns empty dict and logs security event if file exceeds limit
- Size validation prevents loading files into memory if too large

**Tests Added:**
- test_load_yaml_normal_size - Normal files load correctly
- test_load_yaml_oversized_file - Oversized files are rejected
- test_load_yaml_at_size_limit - Files at limit still load
- test_load_yaml_missing_file - Missing files return empty dict
- test_load_yaml_invalid_yaml - Invalid YAML handled gracefully
- test_load_yaml_empty_file - Empty files return empty dict

**Documentation:**
- Updated SECURITY.md with YAML file size limits section
- Updated Configuration.md with file size limit details
- Added security event logging examples

**Security Impact:** Prevents resource exhaustion attacks via maliciously
large YAML configuration files while allowing legitimate large configurations.

Fixes security vulnerability from CodeQL analysis.
2025-11-02 11:49:43 -05:00
Sammy FaridaandDimitrius Farida 60aba31901 Security/pr3 file validation (#27)
* docs: Add path traversal protection documentation for PR1 & PR2

Document security enhancements from PR1 and PR2:

- Add comprehensive path traversal protection section to SECURITY.md
  * Secret path protection details
  * SSH key path protection details
  * Security event logging examples

- Document secret name validation in credentials.yml.md
  * Allowed characters (alphanumeric, dash, underscore)
  * Path resolution security measures
  * Examples of valid/invalid secret names

- Add key path validation section to credentials.yml.md
  * Relative and absolute path validation rules
  * Traversal pattern detection
  * Examples of valid/invalid key paths

- Update Configuration.md with path traversal protection overview
  * Secret path security
  * SSH key path security
  * Security event logging

This documentation accompanies the security fixes in PR1 and PR2.

* docs: Update CHANGELOG.md for path traversal documentation

Add entry for documentation updates (PR #23)

* feat: Add file path validation (PR3) - Validate paths are regular files

Add comprehensive file type validation to prevent security vulnerabilities:

**Security Enhancement:**
- Added _validate_file_path() helper function
- Rejects directories (must be files, not directories)
- Rejects symbolic links (symlinks can be security risks)
- Validates paths stay within allowed directories
- Only regular files are accepted

**Implementation:**
- Integrated validation into _resolve_secret() (requires file existence)
- Integrated validation into _resolve_key_path() (allows non-existent for later validation)
- Added require_exists parameter to handle different use cases

**Tests Added:**
- test_validate_file_path_directory_rejection
- test_validate_file_path_symlink_rejection
- test_validate_file_path_non_existent
- test_validate_file_path_outside_directory
- test_validate_file_path_regular_file_allowed
- test_resolve_secret_directory_rejection
- test_resolve_secret_symlink_rejection
- test_resolve_key_path_directory_rejection
- test_resolve_key_path_symlink_rejection
- Updated test_resolve_key_path_absolute_same_as_keys_dir (now rejects directories)

**Documentation:**
- Updated SECURITY.md with file type validation section
- Updated credentials.yml.md with file type requirements
- Updated Configuration.md with file validation details

**Security Impact:** Prevents accessing directories or symlinks that could lead
to security vulnerabilities or unauthorized access.

Fixes security vulnerability from CodeQL analysis.

* fix: Apply Black formatting to _validate_file_path function

- Split function signature across multiple lines for better readability
- Remove duplicate .gitignore entries for plan.plan.md

Fixes CI formatting check failure.

* fix: Remove duplicate .gitignore entries for plan.plan.md

---------

Co-authored-by: Dimitrius Farida <135074036+CodeBotD@users.noreply.github.com>
2025-11-02 10:18:41 -05:00
Sammy Farida c390282b04 security: Add path traversal protection to _resolve_key_path (#22)
PR 2: Fixes path traversal vulnerability in SSH key path resolution

- Add path normalization and validation to prevent directory traversal
- Validate absolute paths are within keys_dir (reject if outside)
- Reject relative paths containing traversal patterns (../, ..\)
- Add security event logging for path traversal attempts
- Update existing test to reflect new security behavior
- Add comprehensive test coverage for path traversal scenarios

Security Impact:
- Prevents accessing SSH keys outside /app/keys directory
- Blocks path traversal attacks (../, ..\, encoded patterns)
- Validates absolute paths must be within keys_dir
- Maintains backward compatibility for legitimate key access

Test Coverage:
- 9 new security-focused tests added (7 for key paths + 2 updated)
- All 28 tests pass (19 existing + 9 new/updated)
- No regressions in existing functionality
2025-11-02 08:46:49 -05:00
Sammy Farida 3c8686388c security: Add path traversal protection to _resolve_secret (#21)
PR 1: Fixes path traversal vulnerability in secret resolution

- Add path normalization and validation to prevent directory traversal
- Reject absolute paths (enforce relative paths only)
- Validate secret names contain only safe characters (alphanumeric, dash, underscore)
- Add security event logging for path traversal attempts
- Add comprehensive test coverage for path traversal scenarios

Security Impact:
- Prevents reading files outside /app/secrets directory
- Blocks path traversal attacks (../, ..\, absolute paths)
- Maintains backward compatibility for legitimate secret access

Test Coverage:
- 9 new security-focused tests added
- All 22 tests pass (13 existing + 9 new)
- No regressions in existing functionality
2025-11-02 08:15:43 -05:00
Sammy Farida 7a31c5f266 style: Apply Black code formatting
- Format utilities.py, mcp_server.py, and test_async_task_manager.py
- Ensure compliance with Black's 88-character line limit
- Improve code readability with proper line breaks
- Fix multi-line function calls and parameter formatting
- Consistent string quote usage

All Black formatting checks now pass
2025-10-25 23:45:48 -04:00
Sammy Farida 34b3243328 fix: Resolve test failures and linting issues
- Fix AsyncTaskManager tests to expect dictionaries instead of JSON strings
- Fix error message assertions in server tool tests
- Remove unused variables and fix whitespace issues
- All 74 tests now pass with 55% code coverage
- All linting issues resolved
2025-10-25 17:47:27 -04:00
Sammy Farida 9908f00009 feat: Add SEP-1686 compliant async task support
- Add AsyncTaskManager with thread-safe task execution
- Implement 5 new MCP tools: ssh_run_async, ssh_get_task_status, ssh_get_task_result, ssh_get_task_output, ssh_cancel_async_task
- Add MCP notifications for task events (created, progress, completed, failed, cancelled)
- Add policy configuration for task TTL and progress intervals
- Update documentation with async task examples and benefits
- Add comprehensive test coverage for async functionality
- Bump version to 0.2.0

This resolves the issue of repeated SSH connections during long-running operations
by providing non-blocking execution with real-time progress monitoring.
2025-10-25 17:36:11 -04:00
Sammy Farida 0b86327c73 Fix linting and formatting issues for CI/CD 2025-10-21 14:37:10 -04:00
Sammy Farida a6960e5625 Initial commit: MCP SSH Orchestrator v0.1.0 2025-10-21 13:55:05 -04:00