"""Configuration for the code intelligence service.""" from __future__ import annotations import datetime import ipaddress import json import os import stat from dataclasses import dataclass, field from pathlib import Path, PurePosixPath, PureWindowsPath def is_loopback(host: str) -> bool: """True for a host that only this computer can reach.""" if host == "localhost": return True try: return ipaddress.ip_address(host).is_loopback except ValueError: return False @dataclass(slots=True) class CodeIntelConfig: """Configuration for the CodeIntelService.""" # Core settings (Phase 1) project_dir: str = "" host: str = "127.0.0.1" port: int = 8080 api_key: str = "" # No other web origin can call the API unless ATTOCODE_CORS_ORIGINS names it. cors_origins: list[str] = field(default_factory=list) log_level: str = "info" # Indexing settings file_cap: int = 5000 # Max files to index; higher = better coverage, slower bootstrap # Service mode (multi-user) database_url: str = "" secret_key: str = "" redis_url: str = "" # Git clone settings git_clone_dir: str = "/var/lib/code-intel/repos" git_clone_max_gb: float = 50.0 git_ssh_key_path: str = "" # Embedding settings embedding_model: str = "" # auto-detect or explicit: all-MiniLM-L6-v2 | nomic-embed-text | openai embedding_dimension: int = 0 # 0 = auto from model embedding_nl_mode: str = "none" # "none" = embed raw code, "heuristic" = code-to-NL before embedding # Optional local-only reranker. Both values must be supplied; a model is # never downloaded or loaded synchronously by a search request. local_reranker_path: str = "" local_reranker_sha256: str = "" # Optional shortlist ranking. Empty provider keeps the legacy local # cross-encoder opt-in; "off" disables every model-based ranker. ranking_provider: str = "" ranking_endpoint: str = "" ranking_model: str = "" ranking_auth_env: str = "" ranking_allow_remote: bool = False ranking_remote_workspace: str = "" ranking_timeout_ms: int = 0 # auto: 5s loopback, 800ms remote ranking_max_candidates: int = 24 # Remote connection (CLI → server bridge) remote_url: str = "" # e.g. "https://code.example.com" remote_token: str = "" # JWT or API key for remote server remote_repo_id: str = "" # UUID of the repo on the remote server # GC settings gc_merged_branch_retention_days: int = 7 gc_inactive_branch_retention_days: int = 30 gc_content_min_age_minutes: int = 60 # Auth settings jwt_expiry_minutes: int = 60 refresh_expiry_days: int = 30 github_client_id: str = "" github_client_secret: str = "" google_client_id: str = "" google_client_secret: str = "" base_url: str = "" # e.g. "https://code.example.com" — for OAuth redirect_uri registration_key: str = "" # When set, required in register request to prevent open signup @property def is_service_mode(self) -> bool: """True when DATABASE_URL is set — enables multi-user service features.""" return bool(self.database_url) @property def effective_base_url(self) -> str: """Base URL for OAuth redirect URIs. Falls back to http://host:port.""" if self.base_url: return self.base_url.rstrip("/") return f"http://{self.host}:{self.port}" @classmethod def from_env(cls) -> CodeIntelConfig: """Build config from environment variables.""" return cls( project_dir=os.environ.get("ATTOCODE_PROJECT_DIR", ""), host=os.environ.get("ATTOCODE_HOST", "127.0.0.1"), port=int(os.environ.get("ATTOCODE_PORT", "8080")), api_key=os.environ.get("ATTOCODE_API_KEY", ""), cors_origins=[o for o in os.environ.get("ATTOCODE_CORS_ORIGINS", "").split(",") if o], log_level=os.environ.get("ATTOCODE_LOG_LEVEL", "info"), file_cap=int(os.environ.get("ATTOCODE_FILE_CAP", "5000")), database_url=os.environ.get("DATABASE_URL", ""), secret_key=os.environ.get("SECRET_KEY", ""), redis_url=os.environ.get("REDIS_URL", ""), git_clone_dir=os.environ.get("GIT_CLONE_DIR", "/var/lib/code-intel/repos"), git_clone_max_gb=float(os.environ.get("GIT_CLONE_MAX_GB", "50")), git_ssh_key_path=os.environ.get("GIT_SSH_KEY_PATH", ""), embedding_model=os.environ.get("ATTOCODE_EMBEDDING_MODEL", ""), embedding_dimension=int(os.environ.get("ATTOCODE_EMBEDDING_DIMENSION", "0")), embedding_nl_mode=os.environ.get("ATTOCODE_NL_EMBEDDING_MODE", "none"), local_reranker_path=os.environ.get("ATTOCODE_INTEL_RERANKER_PATH", ""), local_reranker_sha256=os.environ.get("ATTOCODE_INTEL_RERANKER_SHA256", ""), ranking_provider=os.environ.get("ATTOCODE_INTEL_RANKING_PROVIDER", ""), ranking_endpoint=os.environ.get("ATTOCODE_INTEL_RANKING_ENDPOINT", ""), ranking_model=os.environ.get("ATTOCODE_INTEL_RANKING_MODEL", ""), ranking_auth_env=os.environ.get("ATTOCODE_INTEL_RANKING_AUTH_ENV", ""), ranking_allow_remote=os.environ.get("ATTOCODE_INTEL_RANKING_ALLOW_REMOTE", "").lower() in {"1", "true", "yes", "on"}, ranking_remote_workspace=os.environ.get("ATTOCODE_INTEL_RANKING_REMOTE_WORKSPACE", ""), ranking_timeout_ms=int(os.environ.get("ATTOCODE_INTEL_RANKING_TIMEOUT_MS", "0")), ranking_max_candidates=int(os.environ.get("ATTOCODE_INTEL_RANKING_MAX_CANDIDATES", "24")), gc_merged_branch_retention_days=int(os.environ.get("GC_MERGED_BRANCH_RETENTION_DAYS", "7")), gc_inactive_branch_retention_days=int(os.environ.get("GC_INACTIVE_BRANCH_RETENTION_DAYS", "30")), gc_content_min_age_minutes=int(os.environ.get("GC_CONTENT_MIN_AGE_MINUTES", "60")), jwt_expiry_minutes=int(os.environ.get("JWT_EXPIRY_MINUTES", "60")), refresh_expiry_days=int(os.environ.get("REFRESH_EXPIRY_DAYS", "30")), github_client_id=os.environ.get("GITHUB_CLIENT_ID", ""), github_client_secret=os.environ.get("GITHUB_CLIENT_SECRET", ""), google_client_id=os.environ.get("GOOGLE_CLIENT_ID", ""), google_client_secret=os.environ.get("GOOGLE_CLIENT_SECRET", ""), base_url=os.environ.get("ATTOCODE_BASE_URL", ""), registration_key=os.environ.get("REGISTRATION_KEY", ""), remote_url=os.environ.get("ATTOCODE_REMOTE_URL", ""), remote_token=os.environ.get("ATTOCODE_REMOTE_TOKEN", ""), remote_repo_id=os.environ.get("ATTOCODE_REMOTE_REPO_ID", ""), ) @dataclass(slots=True) class RemoteConfig: """Remote server connection configuration, persisted to .attocode/config.toml.""" server: str = "" token: str = "" repo_id: str = "" branch_auto_detect: bool = True @property def is_configured(self) -> bool: return bool(self.server and self.token) def token_is_expired(token: str, *, leeway_seconds: int = 30) -> bool: """Best-effort check whether a JWT's ``exp`` claim is in the past. Decodes the token payload WITHOUT verifying the signature — we don't hold the remote server's signing key, we only need the expiry. Returns ``False`` when the token has no ``exp`` claim or can't be parsed (we can't prove it's expired, so let the reachability probe decide). ``leeway_seconds`` treats a token as expired slightly early so we don't start a session on a token about to lapse. """ import base64 import json import time parts = token.split(".") if len(parts) != 3: return False try: payload_b64 = parts[1] + "=" * (-len(parts[1]) % 4) payload = json.loads(base64.urlsafe_b64decode(payload_b64)) except Exception: return False exp = payload.get("exp") if not isinstance(exp, (int, float)): return False return time.time() >= (float(exp) - leeway_seconds) def load_perl_module_roots(project_dir: str) -> list[str]: """Read contained static Perl roots; absent/invalid config keeps root/lib. Explicit lists replace defaults. Entries grant no file-discovery permission and never cause Perl, shell, environment or host-global path evaluation. """ defaults = ['.', 'lib'] try: import tomllib root = Path(project_dir).resolve() path = (root / '.attocode/config.toml').resolve(strict=True) if not path.is_relative_to(root) or not path.is_file(): return defaults with path.open('rb') as stream: raw = stream.read(1_000_001) if len(raw) > 1_000_000: return defaults data = tomllib.loads(raw.decode('utf-8')) except (OSError, UnicodeError, ValueError, RuntimeError): return defaults perl = data.get('perl') if not isinstance(perl, dict) or 'module_roots' not in perl: return defaults entries = perl['module_roots'] if not isinstance(entries, list): return defaults result = [] for entry in entries: if (not isinstance(entry, str) or not entry or any(ord(c) < 32 or ord(c) == 127 for c in entry)): continue relative = entry.replace('\\', '/') if (PurePosixPath(relative).is_absolute() or PureWindowsPath(entry).drive or '..' in PurePosixPath(relative).parts): continue try: path = (root / relative).resolve() if not path.is_relative_to(root) or (path.exists() and not path.is_dir()): continue name = path.relative_to(root).as_posix() except (OSError, ValueError, RuntimeError): continue if name not in result: result.append(name) return result def load_remote_config(project_dir: str) -> RemoteConfig: """Load remote config from .attocode/config.toml, falling back to env vars.""" config_path = Path(project_dir) / ".attocode" / "config.toml" rc = RemoteConfig() if config_path.exists(): try: import tomllib data = tomllib.loads(config_path.read_text(encoding="utf-8")) remote = data.get("remote", {}) rc.server = remote.get("server", "") rc.token = remote.get("token", "") rc.repo_id = remote.get("repo_id", "") rc.branch_auto_detect = remote.get("branch_auto_detect", True) except Exception: pass # Env vars override file config if os.environ.get("ATTOCODE_REMOTE_URL"): rc.server = os.environ["ATTOCODE_REMOTE_URL"] if os.environ.get("ATTOCODE_REMOTE_TOKEN"): rc.token = os.environ["ATTOCODE_REMOTE_TOKEN"] if os.environ.get("ATTOCODE_REMOTE_REPO_ID"): rc.repo_id = os.environ["ATTOCODE_REMOTE_REPO_ID"] return rc def _toml_string(value: str) -> str: # TOML additionally forbids raw DEL. Keep scalar Unicode instead of JSON's # ASCII surrogate pairs, which are not valid TOML Unicode escapes. return json.dumps(value, ensure_ascii=False).replace('\x7f', '\\u007f') def _toml_key(value: str) -> str: if value and all(c.isascii() and (c.isalnum() or c in '-_') for c in value): return value return _toml_string(value) def _toml_value(value: object) -> str: """Serialize tomllib values without Python repr changing TOML semantics.""" if isinstance(value, bool): return 'true' if value else 'false' if isinstance(value, str): return _toml_string(value) if isinstance(value, (int, float)): return repr(value) if isinstance(value, (datetime.datetime, datetime.date, datetime.time)): return value.isoformat() if isinstance(value, list): return '[' + ', '.join(_toml_value(item) for item in value) + ']' if isinstance(value, dict): return '{' + ', '.join(_toml_key(k) + ' = ' + _toml_value(v) for k, v in value.items()) + '}' raise TypeError('Unsupported TOML value type: ' + type(value).__name__) def _read_remote_config_data(directory: int) -> dict: """Read an anchored regular file without following links or blocking on FIFOs.""" import tomllib try: descriptor = os.open('config.toml', os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) except FileNotFoundError: return {} with os.fdopen(descriptor, 'rb') as stream: if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): raise ValueError('Remote settings require a regular config file') raw = stream.read(1_000_001) if len(raw) > 1_000_000: raise ValueError('Existing config exceeds the 1,000,000-byte limit') try: return tomllib.loads(raw.decode('utf-8')) except (ValueError, UnicodeError): # Parser diagnostics can include credential-bearing source lines. raise ValueError('Existing config is not valid UTF-8 TOML; repair it before saving') from None def _publish_remote_config(directory: int, raw: bytes) -> None: """Flush a private owned file before atomically replacing the live name.""" if len(raw) > 1_000_000: raise ValueError('Serialized config exceeds the 1,000,000-byte limit') import secrets temporary = '.config-' + secrets.token_hex(12) + '.tmp' descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory) try: try: os.fchmod(descriptor, 0o600) remaining = memoryview(raw) while remaining: count = os.write(descriptor, remaining) if count <= 0: raise OSError('Remote settings write made no progress') remaining = remaining[count:] os.fsync(descriptor) finally: os.close(descriptor) os.replace(temporary, 'config.toml', src_dir_fd=directory, dst_dir_fd=directory) finally: try: os.unlink(temporary, dir_fd=directory) except FileNotFoundError: pass def save_remote_config(project_dir: str, rc: RemoteConfig) -> Path: """Atomically save private settings; refuse linked or unreadable destinations.""" config_path = Path(project_dir) / '.attocode/config.toml' root = Path(project_dir).resolve() root.mkdir(parents=True, exist_ok=True) flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW project = os.open(root, flags) try: try: os.mkdir('.attocode', 0o700, dir_fd=project) except FileExistsError: pass directory = os.open('.attocode', flags, dir_fd=project) finally: os.close(project) try: existing = _read_remote_config_data(directory) existing['remote'] = { 'server': rc.server, 'token': rc.token, 'repo_id': rc.repo_id, 'branch_auto_detect': rc.branch_auto_detect, } # Root scalars precede tables; inline nested tables preserve their data. lines = [_toml_key(k) + ' = ' + _toml_value(v) for k, v in existing.items() if not isinstance(v, dict)] for section, values in existing.items(): if isinstance(values, dict): if lines: lines.append('') lines.append('[' + _toml_key(section) + ']') for k, v in values.items(): lines.append(_toml_key(k) + ' = ' + _toml_value(v)) _publish_remote_config(directory, ('\n'.join(lines) + '\n').encode('utf-8')) return config_path finally: os.close(directory)