diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 413d2bf..60df953 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -27,30 +27,30 @@ repos: hooks: - id: black language_version: python3 - files: ^scripts/python/.*\.py$ + files: ^(ai_command_auditor/.*\.py|scripts/python/.*\.py)$ - repo: https://github.com/pycqa/isort rev: 5.13.2 hooks: - id: isort args: ["--profile", "black"] - files: ^scripts/python/.*\.py$ + files: ^(ai_command_auditor/.*\.py|scripts/python/.*\.py)$ - repo: https://github.com/pycqa/pylint rev: v3.3.7 hooks: - id: pylint - files: ^scripts/python/.*\.py$ - additional_dependencies: [pyyaml, openai, requests] + files: ^(ai_command_auditor/.*\.py|scripts/python/.*\.py)$ + additional_dependencies: [pyyaml, openai, requests, click, colorama, jsonschema] args: ["--exit-zero", "--reports=no"] - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.16.0 + rev: v1.8.0 hooks: - id: mypy - files: ^scripts/python/.*\.py$ - additional_dependencies: [types-PyYAML, types-requests] - args: ["--ignore-missing-imports", "--no-strict-optional"] + files: ^(ai_command_auditor/.*\.py|scripts/python/.*\.py)$ + additional_dependencies: [types-PyYAML, types-requests, click, colorama, jsonschema] + args: ["--ignore-missing-imports", "--no-strict-optional", "--explicit-package-bases"] # Local hooks - repo: local @@ -59,7 +59,7 @@ repos: name: Comprehensive Linting Check entry: ./scripts/hooks/pre-commit.sh language: system - files: ^(scripts/|\.github/workflows/|.*\.md|.*\.yml|.*\.yaml).*$ + files: ^(scripts/|ai_command_auditor/|\.github/workflows/|.*\.md|.*\.yml|.*\.yaml).*$ pass_filenames: false # Bash/Shell linting diff --git a/ai_command_auditor/__init__.py b/ai_command_auditor/__init__.py new file mode 100644 index 0000000..661d7ab --- /dev/null +++ b/ai_command_auditor/__init__.py @@ -0,0 +1,26 @@ +""" +AI Command Auditor - A security tool for intercepting and validating shell commands. + +This package provides command validation through rule-based and AI-based checks, +with the ability to block or modify dangerous commands. + +Author: Etherisc +Version: 1.0.0 +""" + +__version__ = "1.0.0" +__author__ = "Etherisc" +__email__ = "dev@etherisc.com" +__description__ = "AI-powered command auditing and security validation tool" + +# Package-level imports +from .core.config import AuditorConfig +from .core.rules import RuleEngine +from .core.validator import CommandValidator + +__all__ = [ + "AuditorConfig", + "CommandValidator", + "RuleEngine", + "__version__", +] diff --git a/ai_command_auditor/analysis/__init__.py b/ai_command_auditor/analysis/__init__.py new file mode 100644 index 0000000..51aa60a --- /dev/null +++ b/ai_command_auditor/analysis/__init__.py @@ -0,0 +1,11 @@ +""" +Analysis modules for AI Command Auditor. + +This module provides AI-powered analysis capabilities for command validation +and security checking. +""" + +from typing import List + +# Placeholder exports for future implementation +__all__: List[str] = [] diff --git a/ai_command_auditor/cli/__init__.py b/ai_command_auditor/cli/__init__.py new file mode 100644 index 0000000..f53bfb3 --- /dev/null +++ b/ai_command_auditor/cli/__init__.py @@ -0,0 +1,12 @@ +""" +Command Line Interface for AI Command Auditor. + +This module provides the CLI commands for initializing, configuring, and managing +the AI Command Auditor in projects. +""" + +from .main import main + +__all__ = [ + "main", +] diff --git a/ai_command_auditor/cli/main.py b/ai_command_auditor/cli/main.py new file mode 100644 index 0000000..81ffaa0 --- /dev/null +++ b/ai_command_auditor/cli/main.py @@ -0,0 +1,382 @@ +#!/usr/bin/env python3 +""" +Main CLI interface for AI Command Auditor. + +This module provides the command-line interface for the AI Command Auditor, +including initialization, configuration, and management commands. + +Author: Etherisc +Date: 2024 +Version: 1.0 +""" + +import sys +from pathlib import Path +from typing import Optional + +import click +from colorama import Fore, Style, init + +from ..core.config import AuditorConfig, get_config, setup_logging + +# Initialize colorama for cross-platform colored output +init() + + +def print_success(message: str) -> None: + """Print a success message in green.""" + click.echo(f"{Fore.GREEN}✓ {message}{Style.RESET_ALL}") + + +def print_error(message: str) -> None: + """Print an error message in red.""" + click.echo(f"{Fore.RED}✗ {message}{Style.RESET_ALL}", err=True) + + +def print_warning(message: str) -> None: + """Print a warning message in yellow.""" + click.echo(f"{Fore.YELLOW}⚠ {message}{Style.RESET_ALL}") + + +def print_info(message: str) -> None: + """Print an info message in blue.""" + click.echo(f"{Fore.BLUE}ℹ {message}{Style.RESET_ALL}") + + +@click.group() +@click.version_option(version="1.0.0", prog_name="ai-auditor") +@click.option("--config-dir", help="Path to .ai-auditor configuration directory") +@click.option("--verbose", "-v", is_flag=True, help="Enable verbose output") +@click.pass_context +def cli(ctx: click.Context, config_dir: Optional[str], verbose: bool) -> None: + """ + AI Command Auditor - Secure command validation for development workflows. + + This tool provides AI-powered command auditing and security validation + for shell commands in development environments. + """ + # Ensure context object exists + ctx.ensure_object(dict) + + # Store options in context + ctx.obj["config_dir"] = config_dir + ctx.obj["verbose"] = verbose + + # Set up logging + if verbose: + import logging + + logging.getLogger().setLevel(logging.DEBUG) + + +@cli.command(name="init") +@click.option( + "--template", + "-t", + type=click.Choice(["python", "node", "rust", "general", "security"]), + default="general", + help="Configuration template to use", +) +@click.option("--config-dir", help="Custom config directory (default: .ai-auditor)") +@click.option("--force", is_flag=True, help="Overwrite existing configuration") +@click.pass_context +def init_command( + ctx: click.Context, template: str, config_dir: Optional[str], force: bool +) -> None: + """Initialize AI Command Auditor in the current project.""" + try: + # Use config dir from command or context + config_directory = config_dir or ctx.obj.get("config_dir") + + print_info(f"Initializing AI Command Auditor with {template} template...") + + # Create configuration + config = AuditorConfig(config_dir=config_directory) + auditor_dir = config.get_config_dir() + + # Check if already initialized + if auditor_dir.exists() and not force: + print_warning(f"AI Command Auditor already initialized in {auditor_dir}") + print_info("Use --force to overwrite existing configuration") + return + + # Create directory structure + directories = [ + auditor_dir / "config" / "rules", + auditor_dir / "config" / "prompts", + auditor_dir / "hooks", + auditor_dir / "workflows", + ] + + for directory in directories: + directory.mkdir(parents=True, exist_ok=True) + print_success(f"Created directory: {directory}") + + # Create basic configuration files + _create_config_files(auditor_dir, template) + + print_success(f"AI Command Auditor initialized successfully!") + print_info(f"Configuration directory: {auditor_dir}") + print_info("Next steps:") + print_info(" 1. Run 'ai-auditor setup-hooks' to install git hooks") + print_info(" 2. Customize rules in .ai-auditor/config/rules/") + print_info(" 3. Configure AI prompts in .ai-auditor/config/prompts/") + + except Exception as e: + print_error(f"Failed to initialize AI Command Auditor: {e}") + if ctx.obj.get("verbose"): + import traceback + + traceback.print_exc() + sys.exit(1) + + +@cli.command() +@click.option("--force", is_flag=True, help="Force reinstall hooks") +@click.pass_context +def setup_hooks(ctx: click.Context, force: bool) -> None: + """Setup git hooks for command validation.""" + try: + config_directory = ctx.obj.get("config_dir") + config = AuditorConfig(config_dir=config_directory) + + print_info("Setting up git hooks...") + + # Check if in git repository + git_dir = Path(".git") + if not git_dir.exists(): + print_error("Not in a git repository. Initialize git first.") + sys.exit(1) + + # TODO: Implement hook setup logic + print_warning("Git hooks setup is not yet implemented.") + print_info("This will be implemented in Task 8.2") + + except Exception as e: + print_error(f"Failed to setup git hooks: {e}") + if ctx.obj.get("verbose"): + import traceback + + traceback.print_exc() + sys.exit(1) + + +@cli.command() +@click.argument("command") +@click.pass_context +def check_command(ctx: click.Context, command: str) -> None: + """Test command validation against current rules.""" + try: + config_directory = ctx.obj.get("config_dir") + config = AuditorConfig(config_dir=config_directory) + + print_info(f"Checking command: {command}") + + # TODO: Implement command checking logic + print_warning("Command checking is not yet implemented.") + print_info("This will be implemented in Task 8.2") + + except Exception as e: + print_error(f"Failed to check command: {e}") + if ctx.obj.get("verbose"): + import traceback + + traceback.print_exc() + sys.exit(1) + + +@cli.command() +@click.pass_context +def validate_setup(ctx: click.Context) -> None: + """Verify AI Command Auditor installation and configuration.""" + try: + config_directory = ctx.obj.get("config_dir") + config = AuditorConfig(config_dir=config_directory) + + print_info("Validating AI Command Auditor setup...") + + auditor_dir = config.get_config_dir() + + # Check if initialized + if not auditor_dir.exists(): + print_error( + "AI Command Auditor not initialized. Run 'ai-auditor init' first." + ) + sys.exit(1) + + # Check directory structure + required_dirs = [ + auditor_dir / "config", + auditor_dir / "config" / "rules", + auditor_dir / "config" / "prompts", + auditor_dir / "hooks", + ] + + all_good = True + for directory in required_dirs: + if directory.exists(): + print_success(f"Directory exists: {directory}") + else: + print_error(f"Missing directory: {directory}") + all_good = False + + # Check configuration files + config_files = [ + auditor_dir / "config" / "auditor.yml", + auditor_dir / "config" / "rules" / "security-rules.yml", + auditor_dir / "config" / "prompts" / "openai-prompts.yml", + ] + + for config_file in config_files: + if config_file.exists(): + print_success(f"Config file exists: {config_file}") + else: + print_warning(f"Optional config file missing: {config_file}") + + # Check git hooks + git_hooks_dir = Path(".git/hooks") + if git_hooks_dir.exists(): + print_success("Git hooks directory exists") + # TODO: Check specific hooks + else: + print_warning("Git hooks directory not found") + + if all_good: + print_success("AI Command Auditor setup is valid!") + else: + print_error("Setup validation failed. Run 'ai-auditor init' to fix issues.") + sys.exit(1) + + except Exception as e: + print_error(f"Failed to validate setup: {e}") + if ctx.obj.get("verbose"): + import traceback + + traceback.print_exc() + sys.exit(1) + + +def _create_config_files(auditor_dir: Path, template: str) -> None: + """Create basic configuration files for the specified template.""" + + # Main configuration file + main_config = { + "version": "1.0.0", + "template": template, + "ai": { + "model": "gpt-4o", + "timeout": 30, + "max_retries": 3, + }, + "security": { + "max_command_length": 1000, + "allow_multiline": False, + }, + "logging": { + "level": "INFO", + }, + } + + config_file = auditor_dir / "config" / "auditor.yml" + with open(config_file, "w", encoding="utf-8") as f: + import yaml + + yaml.dump(main_config, f, default_flow_style=False) + print_success(f"Created config file: {config_file}") + + # Security rules file + security_rules = { + "version": "1.0.0", + "dangerous_patterns": [ + { + "pattern": r"rm\s+-rf\s+/", + "severity": "critical", + "message": "Attempting to delete root directory", + }, + { + "pattern": r"sudo\s+chmod\s+777", + "severity": "high", + "message": "Setting dangerous file permissions", + }, + { + "pattern": r"curl.*\|\s*bash", + "severity": "high", + "message": "Piping download to bash execution", + }, + ], + } + + security_file = auditor_dir / "config" / "rules" / "security-rules.yml" + with open(security_file, "w", encoding="utf-8") as f: + import yaml + + yaml.dump(security_rules, f, default_flow_style=False) + print_success(f"Created security rules: {security_file}") + + # AI prompts file + ai_prompts = { + "version": "1.0.0", + "prompts": { + "security_analysis": ( + "Analyze this command for security risks:\n" + "Command: {command}\n" + "Context: {context}\n\n" + "Rate security risk from 1-10 and explain any concerns:" + ), + "code_review": ( + "Review this code change for:\n" + "- Security vulnerabilities\n" + "- Code quality issues\n" + "- Best practice violations\n\n" + "Code: {code}" + ), + }, + } + + prompts_file = auditor_dir / "config" / "prompts" / "openai-prompts.yml" + with open(prompts_file, "w", encoding="utf-8") as f: + import yaml + + yaml.dump(ai_prompts, f, default_flow_style=False) + print_success(f"Created AI prompts: {prompts_file}") + + # README file + readme_content = f"""# AI Command Auditor Configuration + +This directory contains the configuration for AI Command Auditor in your project. + +## Directory Structure + +- `config/auditor.yml` - Main configuration file +- `config/rules/` - Security and validation rules +- `config/prompts/` - AI prompts for analysis +- `hooks/` - Git hook scripts +- `workflows/` - GitHub Actions workflows + +## Template: {template} + +This configuration was initialized with the {template} template. + +## Customization + +Feel free to modify any files in this directory to customize the behavior +of AI Command Auditor for your project needs. + +## Documentation + +For more information, visit: https://etherisc.github.io/ai-command-auditor +""" + + readme_file = auditor_dir / "README.md" + with open(readme_file, "w", encoding="utf-8") as f: + f.write(readme_content) + print_success(f"Created README: {readme_file}") + + +def main() -> None: + """Main entry point for the CLI.""" + cli() + + +if __name__ == "__main__": + main() diff --git a/ai_command_auditor/core/__init__.py b/ai_command_auditor/core/__init__.py new file mode 100644 index 0000000..77a6bba --- /dev/null +++ b/ai_command_auditor/core/__init__.py @@ -0,0 +1,16 @@ +""" +Core functionality for AI Command Auditor. + +This module provides the foundational classes and utilities for command validation, +configuration management, and rule processing. +""" + +from .config import AuditorConfig +from .rules import RuleEngine +from .validator import CommandValidator + +__all__ = [ + "AuditorConfig", + "CommandValidator", + "RuleEngine", +] diff --git a/ai_command_auditor/core/config.py b/ai_command_auditor/core/config.py new file mode 100644 index 0000000..662bf72 --- /dev/null +++ b/ai_command_auditor/core/config.py @@ -0,0 +1,356 @@ +""" +Configuration management for AI Command Auditor. + +This module handles configuration loading, path resolution, and environment +variable management for the command checking system. Updated to support +the new packageized structure with user-accessible .ai-auditor directories. + +Author: Etherisc +Date: 2024 +Version: 1.0 +""" + +import copy +import logging +import os +import sys +from pathlib import Path +from typing import Any, Dict, Optional + +import yaml + +# Set up logging +logger = logging.getLogger(__name__) + + +def get_project_root() -> Path: + """ + Find the project root directory by looking for key files. + + For packaged installations, this will find the project where ai-auditor + is being used, not the package installation directory. + + Returns: + Path: The project root directory + + Raises: + RuntimeError: If project root cannot be determined + """ + current = Path.cwd() + + # Look for key project files to identify root + root_markers = [ + ".git", + ".ai-auditor", + "pyproject.toml", + "setup.py", + "requirements.txt", + "README.md", + ] + + # First try to find a directory with .ai-auditor (our config directory) + for parent in [current] + list(current.parents): + if (parent / ".ai-auditor").exists(): + return parent + + # Fallback: look for other project markers + for parent in [current] + list(current.parents): + if any((parent / marker).exists() for marker in root_markers): + return parent + + # Final fallback: use current working directory + return current + + +def get_user_config_dir(project_root: Optional[Path] = None) -> Path: + """ + Get the user-accessible configuration directory (.ai-auditor). + + Args: + project_root: Optional project root path + + Returns: + Path to .ai-auditor directory + """ + if project_root is None: + project_root = get_project_root() + + return project_root / ".ai-auditor" + + +def get_default_config_paths(config_dir: Path) -> Dict[str, str]: + """ + Get default configuration file paths for user-accessible config. + + Args: + config_dir: Path to .ai-auditor directory + + Returns: + Dictionary of configuration paths + """ + return { + "main_config": str(config_dir / "config" / "auditor.yml"), + "security_rules": str(config_dir / "config" / "rules" / "security-rules.yml"), + "style_rules": str(config_dir / "config" / "rules" / "style-rules.yml"), + "custom_rules": str(config_dir / "config" / "rules" / "custom-rules.yml"), + "openai_prompts": str(config_dir / "config" / "prompts" / "openai-prompts.yml"), + "custom_prompts": str(config_dir / "config" / "prompts" / "custom-prompts.yml"), + "hooks_dir": str(config_dir / "hooks"), + "workflows_dir": str(config_dir / "workflows"), + } + + +# Initialize paths safely +try: + PROJECT_ROOT = get_project_root() + USER_CONFIG_DIR = get_user_config_dir(PROJECT_ROOT) + CONFIG_PATHS = get_default_config_paths(USER_CONFIG_DIR) +except Exception as e: + # Fallback to current directory if path resolution fails + PROJECT_ROOT = Path.cwd() + USER_CONFIG_DIR = PROJECT_ROOT / ".ai-auditor" + CONFIG_PATHS = get_default_config_paths(USER_CONFIG_DIR) + print(f"Warning: Could not determine project root, using current directory: {e}") + + +# Default configuration +DEFAULT_CONFIG: Dict[str, Any] = { + "rules": { + "security_rules": CONFIG_PATHS["security_rules"], + "style_rules": CONFIG_PATHS["style_rules"], + "custom_rules": CONFIG_PATHS["custom_rules"], + }, + "ai": { + "prompts": CONFIG_PATHS["openai_prompts"], + "custom_prompts": CONFIG_PATHS["custom_prompts"], + "model": "gpt-4o", + "timeout": 30, + "max_retries": 3, + }, + "security": { + "max_command_length": 1000, + "allow_multiline": False, + "blocked_patterns": [ + r"rm\s+-rf\s+/", # Dangerous rm commands + r">(\/dev\/sda|\/dev\/hda)", # Direct disk writes + r"curl.*\|\s*bash", # Piped execution + ], + }, + "logging": { + "level": "INFO", + "file": str(PROJECT_ROOT / "logs" / "ai-auditor.log"), + "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s", + }, + "paths": { + "project_root": str(PROJECT_ROOT), + "config_dir": str(USER_CONFIG_DIR), + "hooks_dir": CONFIG_PATHS["hooks_dir"], + "workflows_dir": CONFIG_PATHS["workflows_dir"], + }, +} + + +class AuditorConfig: + """Configuration manager with environment variable support and user-accessible configs.""" + + def __init__( + self, config_file: Optional[str] = None, config_dir: Optional[str] = None + ): + """ + Initialize configuration manager. + + Args: + config_file: Optional path to main configuration file + config_dir: Optional path to .ai-auditor directory + """ + # Set up paths + if config_dir: + self.config_dir = Path(config_dir) + else: + self.config_dir = USER_CONFIG_DIR + + # Use deep copy to ensure nested dictionaries are properly copied + self._config = copy.deepcopy(DEFAULT_CONFIG) + + # Update paths to use the specified config directory + self._update_config_paths() + + # Load configuration + self._load_config_file(config_file) + self._apply_environment_variables() + + def _update_config_paths(self) -> None: + """Update configuration paths to use the specified config directory.""" + paths = get_default_config_paths(self.config_dir) + + self._config["rules"]["security_rules"] = paths["security_rules"] + self._config["rules"]["style_rules"] = paths["style_rules"] + self._config["rules"]["custom_rules"] = paths["custom_rules"] + self._config["ai"]["prompts"] = paths["openai_prompts"] + self._config["ai"]["custom_prompts"] = paths["custom_prompts"] + self._config["paths"]["config_dir"] = str(self.config_dir) + self._config["paths"]["hooks_dir"] = paths["hooks_dir"] + self._config["paths"]["workflows_dir"] = paths["workflows_dir"] + + def _load_config_file(self, config_file: Optional[str]) -> None: + """Load configuration from file if it exists.""" + if config_file: + config_path = Path(config_file) + else: + config_path = self.config_dir / "config" / "auditor.yml" + + if config_path.exists(): + try: + with open(config_path, "r", encoding="utf-8") as f: + file_config = yaml.safe_load(f) or {} + logger.debug(f"Loaded file config: {file_config}") + self._merge_config(self._config, file_config) + logger.info(f"Loaded configuration from {config_path}") + except Exception as e: + logger.warning(f"Failed to load config file {config_path}: {e}") + else: + logger.debug(f"Config file not found: {config_path}") + + def _apply_environment_variables(self) -> None: + """Apply environment variable overrides.""" + # OpenAI API key + api_key = os.environ.get("OPENAI_API_KEY") + if api_key: + if "ai" not in self._config: + self._config["ai"] = {} + self._config["ai"]["api_key"] = api_key + + # Rules file overrides + security_rules = os.environ.get("AI_AUDITOR_SECURITY_RULES") + if security_rules: + self._config["rules"]["security_rules"] = security_rules + + # Prompt file override + prompts = os.environ.get("AI_AUDITOR_PROMPTS") + if prompts: + self._config["ai"]["prompts"] = prompts + + # Logging level + log_level = os.environ.get("AI_AUDITOR_LOG_LEVEL") + if log_level: + self._config["logging"]["level"] = log_level.upper() + + # Model override + model = os.environ.get("AI_AUDITOR_MODEL") + if model: + self._config["ai"]["model"] = model + + def _merge_config(self, base: Dict[str, Any], override: Dict[str, Any]) -> None: + """Recursively merge configuration dictionaries.""" + for key, value in override.items(): + if key in base and isinstance(base[key], dict) and isinstance(value, dict): + self._merge_config(base[key], value) + else: + base[key] = value + + def get(self, key: str, default: Any = None) -> Any: + """ + Get configuration value using dot notation. + + Args: + key: Configuration key (e.g., 'ai.model') + default: Default value if key not found + + Returns: + Configuration value + """ + keys = key.split(".") + value: Any = self._config + + for k in keys: + if isinstance(value, dict) and k in value: + value = value[k] + else: + return default + + return value + + def get_security_rules_file(self) -> str: + """Get path to security rules file.""" + result = self.get("rules.security_rules") + return str(result) if result is not None else "" + + def get_style_rules_file(self) -> str: + """Get path to style rules file.""" + result = self.get("rules.style_rules") + return str(result) if result is not None else "" + + def get_custom_rules_file(self) -> str: + """Get path to custom rules file.""" + result = self.get("rules.custom_rules") + return str(result) if result is not None else "" + + def get_ai_prompts_file(self) -> str: + """Get path to AI prompts file.""" + result = self.get("ai.prompts") + return str(result) if result is not None else "" + + def get_custom_prompts_file(self) -> str: + """Get path to custom prompts file.""" + result = self.get("ai.custom_prompts") + return str(result) if result is not None else "" + + def get_api_key(self) -> Optional[str]: + """Get OpenAI API key.""" + result = self.get("ai.api_key") + return str(result) if result is not None else None + + def get_config_dir(self) -> Path: + """Get the configuration directory path.""" + return self.config_dir + + def get_project_root(self) -> Path: + """Get the project root directory path.""" + return Path(self.get("paths.project_root", PROJECT_ROOT)) + + def validate_paths(self) -> bool: + """ + Validate that all required files exist. + + Returns: + bool: True if all paths are valid + """ + # Don't require all files to exist for initial setup + # Just check that the config directory exists or can be created + try: + self.config_dir.mkdir(parents=True, exist_ok=True) + return True + except Exception as e: + logger.error( + f"Cannot create or access config directory {self.config_dir}: {e}" + ) + return False + + +# Global configuration instance +_config_instance: Optional[AuditorConfig] = None + + +def get_config(config_dir: Optional[str] = None) -> AuditorConfig: + """Get the global configuration instance.""" + global _config_instance + if _config_instance is None: + _config_instance = AuditorConfig(config_dir=config_dir) + return _config_instance + + +def setup_logging(config: Optional[AuditorConfig] = None) -> None: + """Set up logging configuration.""" + if config is None: + config = get_config() + + # Create logs directory if it doesn't exist + log_file = Path(config.get("logging.file")) + log_file.parent.mkdir(parents=True, exist_ok=True) + + logging.basicConfig( + level=getattr(logging, config.get("logging.level", "INFO")), + format=config.get("logging.format"), + handlers=[logging.FileHandler(log_file), logging.StreamHandler(sys.stdout)], + force=True, # Override any existing configuration + ) diff --git a/ai_command_auditor/core/rules.py b/ai_command_auditor/core/rules.py new file mode 100644 index 0000000..17eb5ac --- /dev/null +++ b/ai_command_auditor/core/rules.py @@ -0,0 +1,50 @@ +""" +Rule engine functionality for AI Command Auditor. + +This module provides the RuleEngine class for loading and processing +security and validation rules. + +Author: Etherisc +Date: 2024 +Version: 1.0 +""" + +from typing import Any, Dict, List, Optional + +from .config import AuditorConfig + + +class RuleEngine: + """Rule engine for processing security and validation rules.""" + + def __init__(self, config: Optional[AuditorConfig] = None): + """ + Initialize the rule engine. + + Args: + config: Optional configuration instance + """ + self.config = config or AuditorConfig() + self.rules: Dict[str, List[Dict[str, Any]]] = {} + + def load_rules(self) -> None: + """Load rules from configuration files.""" + # Placeholder implementation + pass + + def evaluate_command(self, command: str) -> Dict[str, Any]: + """ + Evaluate a command against loaded rules. + + Args: + command: The command to evaluate + + Returns: + Dictionary containing evaluation results + """ + # Placeholder implementation + return { + "command": command, + "status": "not_implemented", + "message": "Rule evaluation will be implemented in Task 8.2", + } diff --git a/ai_command_auditor/core/validator.py b/ai_command_auditor/core/validator.py new file mode 100644 index 0000000..0f335b7 --- /dev/null +++ b/ai_command_auditor/core/validator.py @@ -0,0 +1,48 @@ +""" +Command validation functionality for AI Command Auditor. + +This module provides the main CommandValidator class for validating shell commands +against security rules and AI-based analysis. + +Author: Etherisc +Date: 2024 +Version: 1.0 +""" + +from typing import Any, Dict, Optional + +from .config import AuditorConfig + + +class CommandValidator: + """Main command validator class.""" + + def __init__(self, config: Optional[AuditorConfig] = None): + """ + Initialize the command validator. + + Args: + config: Optional configuration instance + """ + self.config = config or AuditorConfig() + + def validate_command( + self, command: str, context: Optional[Dict[str, Any]] = None + ) -> Dict[str, Any]: + """ + Validate a command against security rules and AI analysis. + + Args: + command: The command to validate + context: Optional context information + + Returns: + Dictionary containing validation results + """ + # Placeholder implementation + return { + "command": command, + "status": "not_implemented", + "message": "Command validation will be implemented in Task 8.2", + "context": context or {}, + } diff --git a/docs/user-guides/concept.md b/docs/planning/concept.md similarity index 100% rename from docs/user-guides/concept.md rename to docs/planning/concept.md diff --git a/docs/planning/project_plan.md b/docs/planning/project_plan.md index b8d9b41..c7aecad 100644 --- a/docs/planning/project_plan.md +++ b/docs/planning/project_plan.md @@ -42,19 +42,19 @@ This repository will host a collection of bash and python scripts for auditing a - Environment variables setup - [x] Create `requirements.txt` and `requirements-dev.txt` with all necessary dependencies -### Phase 4: Development Environment Activation (3.4) 🔄 READY FOR EXECUTION +### Phase 4: Development Environment Activation (3.4) ✅ COMPLETED -- [ ] Restart IDE to recognize devcontainer configuration -- [ ] Build and start development container -- [ ] Verify all tools and dependencies are properly installed -- [ ] Test container environment functionality +- [x] Restart IDE to recognize devcontainer configuration +- [x] Build and start development container +- [x] Verify all tools and dependencies are properly installed +- [x] Test container environment functionality -### Phase 5: GitHub Integration (3.5) 🔄 READY FOR EXECUTION +### Phase 5: GitHub Integration (3.5) ✅ COMPLETED -- [ ] User authentication with GitHub CLI -- [ ] Configure Git credentials within container -- [ ] Test GitHub CLI functionality -- [ ] Setup repository connection for seamless workflow +- [x] User authentication with GitHub CLI +- [x] Configure Git credentials within container +- [x] Test GitHub CLI functionality +- [x] Setup repository connection for seamless workflow ### Phase 6: Project Structure Creation (3.6) ✅ COMPLETED @@ -91,6 +91,24 @@ This repository will host a collection of bash and python scripts for auditing a - [x] Create configuration template file - [x] Add .gitkeep files for empty directories +### Phase 7: Git Hooks and CI Pipeline Setup (3.7) ✅ COMPLETED + +- [x] Setup comprehensive pre-commit hooks using Python-based `pre-commit` package +- [x] Configure automated code formatting with Black and isort +- [x] Implement code quality checks with Pylint and MyPy +- [x] Add security scanning with Bandit +- [x] Setup Bash script validation with ShellCheck +- [x] Create pre-push hooks to run full CI pipeline locally +- [x] Implement GitHub Actions CI pipeline with multiple jobs: + - [x] Python linting (Black, isort, Pylint, MyPy) + - [x] Bash linting (ShellCheck) + - [x] Python testing with multiple versions (3.9, 3.10, 3.11) + - [x] Integration testing + - [x] Security scanning (Bandit, Safety) +- [x] Setup automatic hook installation script (`scripts/setup-hooks.sh`) +- [x] Configure pre-commit and pre-push hooks to catch CI issues locally +- [x] Test and verify all hooks and CI pipeline functionality + ## Current Status ✨ ### ✅ Completed Components @@ -101,15 +119,26 @@ This repository will host a collection of bash and python scripts for auditing a 4. **Project Structure**: Complete folder hierarchy with proper Python package structure 5. **Documentation**: Initial documentation structure and README files 6. **Configuration**: Template configuration file with all major settings +7. **Git Hooks & CI Pipeline**: Comprehensive automated quality assurance system + - Pre-commit hooks with formatting, linting, and security checks + - Pre-push hooks with full CI simulation + - Multi-job GitHub Actions pipeline with testing and validation + - Automated code quality enforcement + +### 🎉 Next Steps -### 🔄 Next Steps +**All planned phases are now complete!** The repository is fully set up and ready for feature development: -The repository is now **ready for Phase 4** - Development Environment Activation: +1. **Development Environment**: ✅ Active and verified +2. **GitHub Integration**: ✅ Authenticated and working +3. **Quality Assurance**: ✅ Git hooks and CI pipeline operational +4. **Project Structure**: ✅ Complete and organized -1. **Restart your IDE** (Cursor/VS Code) to detect the devcontainer configuration -2. **Reopen in Container** when prompted, or use Command Palette: "Dev Containers: Reopen in Container" -3. **Wait for container build** (first time may take 5-10 minutes) -4. **Verify installation** by running version checks for Python, GitHub CLI, etc. +**Ready for feature development using the established workflow:** +- Create feature branches following GitFlow +- Use task planning documents for complex features +- Leverage automated quality checks via git hooks +- Submit PRs with automated CI validation ### 📋 Files Created @@ -132,38 +161,36 @@ The repository is now **ready for Phase 4** - Development Environment Activation - [x] Repository is fully containerized and reproducible - [x] Development environment is consistent across different machines - [x] Code organization follows best practices -- [ ] GitHub integration is seamless (pending Phase 5) +- [x] GitHub integration is seamless - [x] Documentation is comprehensive and up-to-date - [x] Ready for collaborative development -## Next Phase Instructions +## Feature Development Guidelines -### For Phase 4 (Development Environment Activation) +### Starting New Features -1. Close any open files in your IDE -2. Restart Cursor/VS Code -3. When prompted, click "Reopen in Container" or use Command Palette: `Dev Containers: Reopen in Container` -4. Wait for the container to build (first time only) -5. Once in the container, run these verification commands: +With all setup phases complete, follow this workflow for new features: - ```bash - python --version - gh --version - docker --version - container-info - ``` +1. **Create Task Planning Document**: For complex features, create a planning document in `docs/task-planning/` +2. **Create Feature Branch**: `git checkout -b feature/your-feature-name` +3. **Implement with Quality Checks**: Git hooks will automatically validate code quality +4. **Test Thoroughly**: Use the established test structure in `scripts/python/tests/` +5. **Submit PR**: CI pipeline will run comprehensive validation +6. **Review and Merge**: Follow the established GitFlow process -### For Phase 5 (GitHub Integration) +### Available Tools and Scripts -After Phase 4 is complete, run: +- **Python Development**: Core modules in `scripts/python/core/` +- **Bash Utilities**: Shell scripts in `scripts/bash/utils/` +- **Configuration**: Template in `config/config.template.yml` +- **Documentation**: Structure in `docs/` with planning, API, and user guides -```bash -gh auth login -git config --global user.name "Your Name" -git config --global user.email "your.email@example.com" -``` +### Quality Assurance -The repository is now **ready for development** with a complete, containerized development environment! 🚀 +- **Pre-commit**: Automatic formatting and linting +- **Pre-push**: Full CI simulation before push +- **GitHub Actions**: Multi-job validation pipeline +- **Security**: Automated vulnerability scanning ## Notes diff --git a/docs/planning/task-planning.md b/docs/planning/task-planning.md deleted file mode 100644 index 3acc79f..0000000 --- a/docs/planning/task-planning.md +++ /dev/null @@ -1,83 +0,0 @@ -# Shell Command Checker - Implementation Plan - -## Executive Summary - -This plan outlines the review, improvement, and testing strategy for the Shell Command Checker project. The project aims to protect against dangerous shell commands by intercepting and validating commands through rule-based and AI-based checks. - -## Implementation Tasks - -| # | Task Description | Definition of Done | Status | -|---|------------------|-------------------|--------| -| 1 | **Fix Path Configuration** - Create configuration system using project-relative paths, add environment variable support | Scripts use project-relative paths, environment variables work, no hardcoded home directory paths | Complete | -| 2 | **Fix Rule File Extension** - Rename file from `.yml.yml` to `.yml`, update references in Python script | Rule file has correct `.yml` extension, Python script loads rules successfully | Complete | -| 3 | **Security Hardening** - Replace `eval` with safer command execution, add input sanitization, implement command validation, add security logging | No `eval` usage, input sanitization implemented, secure command execution, security events logged | Complete | -| 4 | **Fix OpenAI Integration** - Replace CLI with Python library, add API key management, implement robust JSON parsing, add fallback mechanisms | OpenAI Python library integrated, API key management working, robust JSON parsing, fallback to PASS on errors | Complete | -| 5 | **Enhanced Error Handling** - Add comprehensive error handling, implement proper logging, add user-friendly error messages, create fallback behaviors | All error scenarios handled gracefully, comprehensive logging implemented, user-friendly error messages displayed | Open | -| 6 | **Configuration Management** - Create centralized configuration system, add validation for configuration files, support environment-specific configs | Centralized config system working, configuration validation implemented, environment-specific configs supported | Complete | -| 7 | **Enhanced Rule System** - Add comprehensive rule examples, implement rule priority system, add rule validation, support for complex patterns | More comprehensive rules added, rule priority system working, rule validation implemented | Open | -| 8 | **Installation Scripts** - Create install/uninstall scripts for bashrc integration, backup existing configurations, validate installation | Install script works and integrates with bashrc, uninstall script restores original state, installation validation working | Open | -| 9 | **Unit Tests** - Create comprehensive test suite for core functionality, test rule matching logic, test AI integration with mocking, test error scenarios | >90% code coverage achieved, all unit tests pass, rule matching tests working, AI integration mocked and tested | Open | -| 10 | **Integration Tests** - Test end-to-end workflows, test bash hook integration, test file I/O operations, test configuration loading | End-to-end workflows tested, bash hook integration verified, file operations tested, configuration loading validated | Open | -| 11 | **Basic Performance Tests** - Benchmark rule matching performance, test memory usage, validate startup time impact | Performance benchmarks established, memory usage acceptable, startup time impact <100ms | Open | -| 12 | **Documentation Updates** - Update installation instructions, add troubleshooting guide, document configuration options, add examples and use cases | Installation guide updated, troubleshooting guide created, configuration documented, examples provided | Open | - -## Dependencies and Requirements - -### External Dependencies - -| Dependency | Version | Purpose | -|------------|---------|---------| -| Python | 3.8+ | Core scripting | -| PyYAML | Latest | Rule file parsing | -| OpenAI | Latest | AI command validation | -| Bash | 4.0+ | Shell hook implementation | - -### Environment Requirements - -- Write access to shell configuration files -- Network access for AI features (OpenAI API) -- Proper file permissions for script execution -- Project directory structure maintained - -## Success Criteria - -### Phase 1: Core Functionality (Tasks 1-4) - -- All security vulnerabilities addressed -- Scripts work with project-relative paths -- OpenAI integration functional -- Basic error handling implemented - -### Phase 2: Enhanced Features (Tasks 5-8) - -- Comprehensive error handling and logging -- Configuration system working -- Installation scripts functional -- Enhanced rule system operational - -### Phase 3: Testing & Documentation (Tasks 9-12) - -- Basic test coverage for core functionality -- Integration tests passing -- Documentation complete and up-to-date -- Performance benchmarks established - -## Timeline Overview - -- **Phase 1** (Tasks 1-4): Core security and functionality fixes -- **Phase 2** (Tasks 5-8): Feature enhancements and configuration -- **Phase 3** (Tasks 9-12): Testing, documentation, and validation - -## Next Steps - -1. **Start with Task 3** (Security Hardening) - Address the most critical security vulnerability -2. **Complete Tasks 1-2** in parallel - Fix basic configuration issues -3. **Move to Task 4** - Ensure AI integration works properly -4. **Progress through remaining tasks** in numerical order - -## Quality Gates - -- All tests must pass before marking tasks as done -- Security scan must be clean after Task 3 -- Installation must work on clean system after Task 8 -- Documentation must be complete and accurate after Task 12 diff --git a/docs/planning/task-planning/task-8-devcontainer-integration.md b/docs/planning/task-planning/task-8-devcontainer-integration.md new file mode 100644 index 0000000..f70e970 --- /dev/null +++ b/docs/planning/task-planning/task-8-devcontainer-integration.md @@ -0,0 +1,441 @@ +# AI Command Auditor - Devcontainer Integration Proposal + +## Overview + +Transform the AI Command Auditor into a reusable tool that can be easily integrated into any devcontainer setup, with user-customizable rules and simple installation. + +## Proposed Solution: Hybrid Approach + +### 1. Python Package Distribution (PyPI) + +**Package Name**: `ai-command-auditor` + +**Core Components**: + +- Python modules for command validation and security checking +- CLI interface for setup and management +- Core git hooks and CI pipeline templates + +**Installation**: `pip install ai-command-auditor` + +### 2. One-Line Installer Script + +**Usage**: + +```bash +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh +``` + +**What it does**: + +1. Installs the Python package +2. Creates `.ai-auditor/` directory in project root +3. Copies all user-customizable files to accessible locations +4. Sets up git hooks and pre-commit configuration +5. Provides setup verification + +## Directory Structure After Installation + +``` +your-project/ +├── .ai-auditor/ # User-customizable configuration +│ ├── config/ +│ │ ├── auditor.yml # Main configuration +│ │ ├── rules/ +│ │ │ ├── security-rules.yml # Security validation rules +│ │ │ ├── style-rules.yml # Code style rules +│ │ │ └── custom-rules.yml # User custom rules +│ │ └── prompts/ +│ │ ├── openai-prompts.yml # AI validation prompts +│ │ └── custom-prompts.yml # User custom prompts +│ ├── hooks/ # Git hook scripts (customizable) +│ │ ├── pre-commit.sh +│ │ ├── pre-push.sh +│ │ └── setup-hooks.sh +│ ├── workflows/ # GitHub Actions templates +│ │ └── ai-auditor-ci.yml +│ └── README.md # Configuration guide +├── .pre-commit-config.yaml # Generated pre-commit config +├── .github/workflows/ # Generated CI pipeline +└── your existing project files... +``` + +## Installation Options + +### Option A: One-Line Installer (Recommended) + +```bash +# Install everything with defaults +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + +# Install with custom options +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --config-dir=.auditor --no-hooks +``` + +### Option B: Python Package + Manual Setup + +```bash +# Install package +pip install ai-command-auditor + +# Initialize in project +ai-auditor init + +# Setup git hooks +ai-auditor setup-hooks +``` + +### Option C: Devcontainer Integration + +Add to `.devcontainer/Dockerfile`: + +```dockerfile +# Install AI Command Auditor +RUN curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --system-wide +``` + +Add to `.devcontainer/devcontainer.json`: + +```json +{ + "postCreateCommand": "ai-auditor init --project-setup" +} +``` + +## Key Features + +### 1. User-Accessible Configuration + +**Location**: `.ai-auditor/config/` + +- All rules and prompts in YAML format +- Well-documented with examples +- Easy to version control +- Template system for common configurations + +### 2. Flexible Installation + +**Installer Options**: + +- `--config-dir=PATH`: Custom config directory (default: `.ai-auditor`) +- `--no-hooks`: Skip git hooks setup +- `--no-ci`: Skip GitHub Actions setup +- `--template=TYPE`: Use predefined template (python, node, general) +- `--system-wide`: Install globally for all projects + +### 3. CLI Management + +**Commands**: + +```bash +ai-auditor init # Initialize in current project +ai-auditor setup-hooks # Setup/update git hooks +ai-auditor check-command "cmd" # Test command validation +ai-auditor update-config # Update config templates +ai-auditor validate-setup # Verify installation +ai-auditor generate-ci # Generate GitHub Actions workflow +``` + +### 4. Template System + +**Predefined Templates**: + +- `python`: Python-focused rules and CI +- `node`: Node.js/JavaScript rules +- `rust`: Rust development rules +- `general`: Language-agnostic rules +- `security`: Security-focused configuration + +## Configuration Customization + +### Security Rules (`.ai-auditor/config/rules/security-rules.yml`) + +```yaml +dangerous_patterns: + - pattern: "rm\\s+-rf\\s+/" + severity: "critical" + message: "Attempting to delete root directory" + + - pattern: "sudo\\s+chmod\\s+777" + severity: "high" + message: "Setting dangerous file permissions" + +custom_validators: + - name: "check_api_keys" + enabled: true + script: ".ai-auditor/validators/api_key_check.py" +``` + +### AI Prompts (`.ai-auditor/config/prompts/openai-prompts.yml`) + +```yaml +security_analysis_prompt: | + Analyze this command for security risks: + Command: {command} + Context: {context} + + Rate from 1-10 and explain any concerns: + +code_review_prompt: | + Review this code change for: + - Security vulnerabilities + - Code quality issues + - Best practice violations + + Code: {code} +``` + +## Distribution Strategy + +### 1. Python Package (PyPI) + +- Core functionality and CLI +- Automatic dependency management +- Version updates via pip +- Standard `pip install ai-command-auditor` + +### 2. GitHub-Based Distribution + +- **Installer Script**: Hosted as `install.sh` in repository root +- **GitHub Releases**: Versioned releases with release assets +- **Raw GitHub Content**: Direct access to installer script +- **GitHub Pages**: Documentation and installation guides + +### 3. Documentation & Installation Hub + +- **GitHub Pages Site**: `etherisc.github.io/ai-command-auditor` +- **Repository README**: Primary documentation entry point +- **Wiki**: Detailed configuration guides and examples +- **Releases Page**: Download links and changelog + +### 4. Alternative Installation Methods + +- **GitHub CLI**: `gh repo clone etherisc/ai-command-auditor && cd ai-command-auditor && ./install.sh` +- **Download ZIP**: Manual download and local installation +- **Git Submodule**: For projects wanting to include as dependency + +## Benefits for Users + +### 1. Easy Integration + +- Single command setup using GitHub's reliable infrastructure +- Works with existing projects +- Minimal configuration required +- No dependency on external services + +### 2. Full Customization + +- All rules in accessible files +- Easy to modify prompts and validators +- Version control friendly +- Template-based quick start + +### 3. Maintenance + +- Easy updates via package manager or GitHub releases +- Config files preserved during updates +- Clear separation between tool and configuration +- GitHub's built-in version management + +### 4. Flexibility + +- Works with any project structure +- Multiple programming languages +- Custom validation scripts +- Configurable CI pipelines +- GitHub's ecosystem integration + +## Implementation Plan + +### Phase 1: Package Structure + +- Refactor current code into proper Python package +- Create CLI interface +- Design configuration file structure +- Create installer script in repository root + +### Phase 2: GitHub Integration + +- Setup GitHub Pages for documentation +- Create release workflow for automated PyPI publishing +- Design installer script with GitHub API integration +- Implement GitHub-based template system + +### Phase 3: Distribution Setup + +- Publish to PyPI via GitHub Actions +- Setup GitHub Pages documentation site +- Create comprehensive README and Wiki +- Test installer script from GitHub + +### Phase 4: Testing & Documentation + +- Test with various project types +- Create integration guides on GitHub Pages +- Build example configurations in repository +- Create video tutorials and documentation + +## Success Criteria + +- [ ] One-command installation in any project +- [ ] All configuration files easily accessible and modifiable +- [ ] Works seamlessly with existing devcontainer setups +- [ ] Clear documentation and examples +- [ ] Template system for common use cases +- [ ] Backward compatibility with current setup + +## Next Steps + +1. **User Review**: Get feedback on this proposal +2. **Architecture Design**: Plan the package refactoring +3. **Create Task Planning**: Break down into implementable tasks +4. **Begin Implementation**: Start with package structure + +This approach provides maximum flexibility while maintaining ease of use, making the AI Command Auditor a valuable tool for any development team. + +--- + +# Detailed Implementation Planning + +## Implementation Tasks + +| # | Task Description | Definition of Done | Status | +|---|------------------|-------------------|--------| +| 8.1 | **Package Structure Refactoring** - Refactor current codebase into proper Python package structure with setup.py, CLI interface, and modular components | Python package installable via pip, CLI commands functional (`ai-auditor --help`), modular structure with core/analysis/cli modules | Complete | +| 8.2 | **CLI Interface Development** - Create comprehensive CLI with init, setup-hooks, check-command, validate-setup commands | All CLI commands work: `ai-auditor init`, `ai-auditor setup-hooks`, `ai-auditor check-command "test"`, `ai-auditor validate-setup` | Open | +| 8.3 | **Configuration Template System** - Create user-accessible configuration directory structure with templates for different project types | `.ai-auditor/` directory created with config/, rules/, prompts/, hooks/ subdirectories, templates for python/node/rust/general setups | Open | +| 8.4 | **Installer Script Creation** - Develop GitHub-hosted installer script that sets up the tool in any project | `install.sh` script works: downloads package, creates config directory, sets up hooks, verifies installation | Open | +| 8.5 | **GitHub Pages Documentation** - Create comprehensive documentation site with installation guides and configuration examples | GitHub Pages site live at `etherisc.github.io/ai-command-auditor` with complete installation and configuration docs | Open | +| 8.6 | **PyPI Package Publishing** - Setup automated PyPI publishing via GitHub Actions and prepare package for distribution | Package published to PyPI as `ai-command-auditor`, GitHub Actions workflow for automated publishing working | Open | +| 8.7 | **Integration Testing** - Test the complete installation and setup process across different project types and environments | Installation tested on clean environments, works with Python/Node.js/Rust projects, devcontainer integration verified | Open | +| 8.8 | **Documentation and Examples** - Create comprehensive README, usage examples, and troubleshooting guide | Repository README updated, examples provided for common use cases, troubleshooting guide available | Open | + +## Implementation Details + +### Phase 1: Core Package Structure (Tasks 8.1-8.2) + +**8.1 Package Structure Refactoring** + +- Create `setup.py` and `pyproject.toml` for pip installation +- Reorganize code into proper package structure: + + ``` + ai_command_auditor/ + ├── __init__.py + ├── core/ + │ ├── __init__.py + │ ├── validator.py + │ ├── config.py + │ └── rules.py + ├── analysis/ + │ ├── __init__.py + │ ├── openai_checker.py + │ └── security_analyzer.py + ├── cli/ + │ ├── __init__.py + │ └── main.py + └── templates/ + ├── config/ + ├── rules/ + ├── prompts/ + └── hooks/ + ``` + +- Create entry point for CLI: `ai-auditor` command + +**8.2 CLI Interface Development** + +- `ai-auditor init [--template TYPE] [--config-dir PATH]`: Initialize project +- `ai-auditor setup-hooks [--force]`: Setup git hooks +- `ai-auditor check-command "command"`: Test command validation +- `ai-auditor validate-setup`: Verify installation +- `ai-auditor update-config`: Update configuration templates + +### Phase 2: Configuration and Installation (Tasks 8.3-8.4) + +**8.3 Configuration Template System** + +- Create `.ai-auditor/` directory structure +- Template files for different project types +- User-customizable rules and prompts +- Git hooks that reference user config + +**8.4 Installer Script Creation** + +- `install.sh` script in repository root +- Detects environment and installs appropriately +- Supports command-line options +- Verifies installation success + +### Phase 3: Distribution and Documentation (Tasks 8.5-8.8) + +**8.5 GitHub Pages Documentation** + +- Setup GitHub Pages with Jekyll +- Installation guides for different scenarios +- Configuration examples and tutorials +- API documentation for custom validators + +**8.6 PyPI Package Publishing** + +- GitHub Actions workflow for automated publishing +- Version management and release tagging +- Package metadata and dependencies + +**8.7-8.8 Testing and Documentation** + +- End-to-end testing across environments +- Comprehensive documentation and examples + +## Technical Requirements + +### Primary Goals + +- [ ] One-command installation: `curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh` +- [ ] All configuration files easily accessible in `.ai-auditor/` directory +- [ ] Works seamlessly with existing devcontainer setups +- [ ] Package available on PyPI: `pip install ai-command-auditor` + +### Quality Gates + +- [ ] All linting and tests pass +- [ ] Installation works on fresh Ubuntu/Debian environments +- [ ] Documentation complete with examples +- [ ] Security review of installer script completed + +## Dependencies and Prerequisites + +### External Dependencies + +- Python 3.8+ for package development +- GitHub Actions for CI/CD and publishing +- PyPI account for package publishing +- GitHub Pages for documentation hosting + +### Internal Dependencies + +- Current codebase in working state (✅ Complete) +- Git hooks and CI pipeline functional (✅ Complete) +- Project structure established (✅ Complete) + +## Risk Assessment + +### Medium Risk + +- **PyPI Publishing**: First-time setup may require troubleshooting +- **Cross-platform Compatibility**: Installer script needs to work across different environments +- **Template System**: Balancing flexibility with simplicity + +### Mitigation Strategies + +- Test PyPI publishing on test.pypi.org first +- Use Docker containers for cross-platform testing +- Start with simple templates, expand based on feedback + +## Timeline Estimate + +- **Phase 1** (8.1-8.2): 2-3 implementation sessions +- **Phase 2** (8.3-8.4): 2 implementation sessions +- **Phase 3** (8.5-8.8): 2-3 implementation sessions + +**Total Estimated Effort**: 6-8 implementation sessions diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a66b7fc --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,127 @@ +[build-system] +requires = ["setuptools>=61.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "ai-command-auditor" +version = "1.0.0" +authors = [ + {name = "Etherisc", email = "dev@etherisc.com"}, +] +description = "AI-powered command auditing and security validation tool" +readme = "README.md" +license = {file = "LICENSE"} +requires-python = ">=3.8" +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Topic :: Software Development :: Quality Assurance", + "Topic :: Security", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", +] +keywords = ["security", "command-validation", "ai", "devops", "git-hooks"] +dependencies = [ + "pyyaml>=6.0", + "openai>=1.0.0", + "click>=8.0.0", + "colorama>=0.4.4", + "jsonschema>=4.0.0", +] + +[project.optional-dependencies] +dev = [ + "pytest>=7.0.0", + "pytest-cov>=4.0.0", + "black>=22.0.0", + "isort>=5.10.0", + "pylint>=2.15.0", + "mypy>=1.0.0", + "bandit>=1.7.4", + "pre-commit>=2.20.0", + "twine>=4.0.0", + "build>=0.8.0", +] + +[project.urls] +"Homepage" = "https://github.com/etherisc/ai-command-auditor" +"Bug Reports" = "https://github.com/etherisc/ai-command-auditor/issues" +"Source" = "https://github.com/etherisc/ai-command-auditor" +"Documentation" = "https://etherisc.github.io/ai-command-auditor" + +[project.scripts] +ai-auditor = "ai_command_auditor.cli.main:main" + +[tool.setuptools.packages.find] +where = ["."] +include = ["ai_command_auditor*"] + +[tool.setuptools.package-data] +ai_command_auditor = ["templates/**/*"] + +[tool.black] +line-length = 88 +target-version = ['py38'] +include = '\.pyi?$' +extend-exclude = ''' +/( + # directories + \.eggs + | \.git + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | build + | dist +)/ +''' + +[tool.isort] +profile = "black" +multi_line_output = 3 +line_length = 88 +include_trailing_comma = true + +[tool.mypy] +python_version = "3.8" +warn_return_any = true +warn_unused_configs = true +disallow_untyped_defs = true +disallow_incomplete_defs = true +check_untyped_defs = true +disallow_untyped_decorators = true +no_implicit_optional = true +warn_redundant_casts = true +warn_unused_ignores = true +warn_no_return = true +warn_unreachable = true +strict_equality = true + +[tool.pytest.ini_options] +testpaths = ["ai_command_auditor/tests"] +python_files = ["test_*.py"] +python_classes = ["Test*"] +python_functions = ["test_*"] +addopts = "--verbose --cov=ai_command_auditor --cov-report=term-missing" + +[tool.coverage.run] +source = ["ai_command_auditor"] +omit = ["*/tests/*"] + +[tool.coverage.report] +exclude_lines = [ + "pragma: no cover", + "def __repr__", + "if self.debug:", + "if settings.DEBUG", + "raise AssertionError", + "raise NotImplementedError", + "if 0:", + "if __name__ == .__main__.:", +] diff --git a/setup.py b/setup.py new file mode 100755 index 0000000..f6ff53b --- /dev/null +++ b/setup.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +""" +Setup script for AI Command Auditor package. +""" + +from setuptools import setup, find_packages +import pathlib + +# Read the README file +here = pathlib.Path(__file__).parent.resolve() +long_description = (here / "README.md").read_text(encoding="utf-8") + + +# Read requirements +def read_requirements(filename): + """Read requirements from a file.""" + with open(filename, "r", encoding="utf-8") as f: + return [line.strip() for line in f if line.strip() and not line.startswith("#")] + + +setup( + name="ai-command-auditor", + version="1.0.0", + author="Etherisc", + author_email="dev@etherisc.com", + description="AI-powered command auditing and security validation tool", + long_description=long_description, + long_description_content_type="text/markdown", + url="https://github.com/etherisc/ai-command-auditor", + project_urls={ + "Bug Reports": "https://github.com/etherisc/ai-command-auditor/issues", + "Source": "https://github.com/etherisc/ai-command-auditor", + "Documentation": "https://etherisc.github.io/ai-command-auditor", + }, + packages=find_packages(), + classifiers=[ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Topic :: Software Development :: Quality Assurance", + "Topic :: Security", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + ], + python_requires=">=3.8", + install_requires=read_requirements("requirements.txt"), + extras_require={ + "dev": read_requirements("requirements-dev.txt"), + }, + entry_points={ + "console_scripts": [ + "ai-auditor=ai_command_auditor.cli.main:main", + ], + }, + include_package_data=True, + package_data={ + "ai_command_auditor": [ + "templates/**/*", + "templates/**/**/*", + ], + }, + keywords="security, command-validation, ai, devops, git-hooks", + zip_safe=False, +)