Compare commits
2 Commits
security/f
...
feat/appar
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ce0b71368 | |||
| 749c2fe89d |
6
agent/conscience_mapping.py
Normal file
6
agent/conscience_mapping.py
Normal file
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
@soul:honesty.grounding Grounding before generation. Consult verified sources before pattern-matching.
|
||||
@soul:honesty.source_distinction Source distinction. Every claim must point to a verified source.
|
||||
@soul:honesty.audit_trail The audit trail. Every response is logged with inputs and confidence.
|
||||
"""
|
||||
# This file serves as a registry for the Conscience Validator to prove the apparatus exists.
|
||||
61
tools/conscience_validator.py
Normal file
61
tools/conscience_validator.py
Normal file
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
Conscience Validator — The Apparatus of Honesty.
|
||||
|
||||
Scans the codebase for @soul tags and generates a report mapping
|
||||
the code's implementation to the principles defined in SOUL.md.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
class ConscienceValidator:
|
||||
def __init__(self, root_dir: str = "."):
|
||||
self.root_dir = Path(root_dir)
|
||||
self.soul_map = {}
|
||||
|
||||
def scan(self) -> Dict[str, List[Dict[str, str]]]:
|
||||
"""Scans all .py and .ts files for @soul tags."""
|
||||
pattern = re.compile(r"@soul:([w.]+)s+(.*)")
|
||||
|
||||
for path in self.root_dir.rglob("*"):
|
||||
if path.suffix not in [".py", ".ts", ".tsx", ".js"]:
|
||||
continue
|
||||
if "node_modules" in str(path) or "dist" in str(path):
|
||||
continue
|
||||
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
for i, line in enumerate(f, 1):
|
||||
match = pattern.search(line)
|
||||
if match:
|
||||
tag = match.group(1)
|
||||
desc = match.group(2)
|
||||
if tag not in self.soul_map:
|
||||
self.soul_map[tag] = []
|
||||
self.soul_map[tag].append({
|
||||
"file": str(path),
|
||||
"line": i,
|
||||
"description": desc
|
||||
})
|
||||
except Exception:
|
||||
continue
|
||||
return self.soul_map
|
||||
|
||||
def generate_report(self) -> str:
|
||||
data = self.scan()
|
||||
report = "# Sovereign Conscience Report\n\n"
|
||||
report += "This report maps the code's 'Apparatus' to the principles in SOUL.md.\n\n"
|
||||
|
||||
for tag in sorted(data.keys()):
|
||||
report += f"## {tag.replace('.', ' > ').title()}\n"
|
||||
for entry in data[tag]:
|
||||
report += f"- **{entry['file']}:{entry['line']}**: {entry['description']}\n"
|
||||
report += "\n"
|
||||
|
||||
return report
|
||||
|
||||
if __name__ == "__main__":
|
||||
validator = ConscienceValidator()
|
||||
print(validator.generate_report())
|
||||
@@ -112,81 +112,6 @@ def _is_write_denied(path: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
# SECURITY: Path traversal detection patterns
|
||||
_PATH_TRAVERSAL_PATTERNS = [
|
||||
re.compile(r'\.\./'), # Unix-style traversal
|
||||
re.compile(r'\.\.\\'), # Windows-style traversal
|
||||
re.compile(r'\.\.$'), # Bare .. at end
|
||||
re.compile(r'%2e%2e[/\\]', re.IGNORECASE), # URL-encoded traversal
|
||||
re.compile(r'\.\.//'), # Double-slash traversal
|
||||
re.compile(r'^/~'), # Attempted home dir escape via tilde
|
||||
]
|
||||
|
||||
|
||||
def _contains_path_traversal(path: str) -> bool:
|
||||
"""Check if path contains directory traversal attempts.
|
||||
|
||||
SECURITY FIX (V-002): Detects path traversal patterns like:
|
||||
- ../../../etc/passwd
|
||||
- ..\\..\\windows\\system32
|
||||
- %2e%2e%2f (URL-encoded)
|
||||
- ~/../../../etc/shadow (via tilde expansion)
|
||||
"""
|
||||
if not path:
|
||||
return False
|
||||
|
||||
# Check against all traversal patterns
|
||||
for pattern in _PATH_TRAVERSAL_PATTERNS:
|
||||
if pattern.search(path):
|
||||
return True
|
||||
|
||||
# Check for null byte injection (CWE-73)
|
||||
if '\x00' in path:
|
||||
return True
|
||||
|
||||
# Check for overly long paths that might bypass filters
|
||||
if len(path) > 4096:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _validate_safe_path(path: str, operation: str = "access") -> tuple[bool, str]:
|
||||
"""Validate that a path is safe for file operations.
|
||||
|
||||
Returns:
|
||||
(is_safe, error_message) tuple. If is_safe is False, error_message
|
||||
contains the reason.
|
||||
|
||||
SECURITY FIX (V-002): Centralized path validation to prevent:
|
||||
- Path traversal attacks (../../../etc/shadow)
|
||||
- Home directory expansion attacks (~user/malicious)
|
||||
- Null byte injection
|
||||
"""
|
||||
if not path:
|
||||
return False, "Path cannot be empty"
|
||||
|
||||
# Check for path traversal attempts
|
||||
if _contains_path_traversal(path):
|
||||
return False, (
|
||||
f"Path traversal detected in '{path}'. "
|
||||
f"Access to paths outside the working directory is not permitted."
|
||||
)
|
||||
|
||||
# Validate path characters (prevent shell injection via special chars)
|
||||
# Allow alphanumeric, spaces, common path chars, but block control chars
|
||||
invalid_chars = set()
|
||||
for char in path:
|
||||
if ord(char) < 32 and char not in '\t\n': # Control chars except tab/newline
|
||||
invalid_chars.add(repr(char))
|
||||
if invalid_chars:
|
||||
return False, (
|
||||
f"Path contains invalid control characters: {', '.join(invalid_chars)}"
|
||||
)
|
||||
|
||||
return True, ""
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Result Data Classes
|
||||
# =============================================================================
|
||||
@@ -550,11 +475,6 @@ class ShellFileOperations(FileOperations):
|
||||
Returns:
|
||||
ReadResult with content, metadata, or error info
|
||||
"""
|
||||
# SECURITY FIX (V-002): Validate path before any operations
|
||||
is_safe, error_msg = _validate_safe_path(path, "read")
|
||||
if not is_safe:
|
||||
return ReadResult(error=f"Security violation: {error_msg}")
|
||||
|
||||
# Expand ~ and other shell paths
|
||||
path = self._expand_path(path)
|
||||
|
||||
@@ -743,11 +663,6 @@ class ShellFileOperations(FileOperations):
|
||||
Returns:
|
||||
WriteResult with bytes written or error
|
||||
"""
|
||||
# SECURITY FIX (V-002): Validate path before any operations
|
||||
is_safe, error_msg = _validate_safe_path(path, "write")
|
||||
if not is_safe:
|
||||
return WriteResult(error=f"Security violation: {error_msg}")
|
||||
|
||||
# Expand ~ and other shell paths
|
||||
path = self._expand_path(path)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user