|
| 1 | +import json |
| 2 | +import os |
| 3 | +import shlex |
| 4 | +import shutil |
| 5 | +import subprocess |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from libkernelbot.consts import SubmissionMode |
| 9 | +from libkernelbot.utils import KernelBotError, limit_length, setup_logging |
| 10 | + |
| 11 | +logger = setup_logging(__name__) |
| 12 | + |
| 13 | +_TRUE_VALUES = {"1", "true", "yes", "on"} |
| 14 | +_DEFAULT_TIMEOUT_SEC = 30 |
| 15 | +_GUARDED_MODES = frozenset( |
| 16 | + { |
| 17 | + SubmissionMode.BENCHMARK, |
| 18 | + SubmissionMode.PROFILE, |
| 19 | + SubmissionMode.LEADERBOARD, |
| 20 | + SubmissionMode.PRIVATE, |
| 21 | + } |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +class KernelGuardRejected(KernelBotError): |
| 26 | + def __init__(self, message: str, result: dict[str, Any]): |
| 27 | + super().__init__(message) |
| 28 | + self.result = result |
| 29 | + |
| 30 | + |
| 31 | +def _env_enabled(name: str, default: bool = False) -> bool: |
| 32 | + raw = os.getenv(name) |
| 33 | + if raw is None: |
| 34 | + return default |
| 35 | + return raw.strip().lower() in _TRUE_VALUES |
| 36 | + |
| 37 | + |
| 38 | +def should_precheck_submission(mode: SubmissionMode) -> bool: |
| 39 | + return _env_enabled("KERNELGUARD_ENABLED") and mode in _GUARDED_MODES |
| 40 | + |
| 41 | + |
| 42 | +def _timeout_sec() -> int: |
| 43 | + raw = os.getenv("KERNELGUARD_TIMEOUT_SEC", str(_DEFAULT_TIMEOUT_SEC)).strip() |
| 44 | + try: |
| 45 | + return max(1, int(raw)) |
| 46 | + except ValueError: |
| 47 | + logger.warning("Invalid KERNELGUARD_TIMEOUT_SEC=%r, using %d", raw, _DEFAULT_TIMEOUT_SEC) |
| 48 | + return _DEFAULT_TIMEOUT_SEC |
| 49 | + |
| 50 | + |
| 51 | +def _profile() -> str | None: |
| 52 | + raw = os.getenv("KERNELGUARD_PROFILE", "").strip() |
| 53 | + return raw or None |
| 54 | + |
| 55 | + |
| 56 | +def _config_path() -> str | None: |
| 57 | + raw = os.getenv("KERNELGUARD_CONFIG", "").strip() |
| 58 | + return raw or None |
| 59 | + |
| 60 | + |
| 61 | +def _fail_open_enabled() -> bool: |
| 62 | + return _env_enabled("KERNELGUARD_FAIL_OPEN") |
| 63 | + |
| 64 | + |
| 65 | +def _default_command() -> list[str]: |
| 66 | + for candidate in ("kernelguard", "kguard"): |
| 67 | + if shutil.which(candidate): |
| 68 | + return [candidate] |
| 69 | + if shutil.which("uvx"): |
| 70 | + return ["uvx", "kernelguard"] |
| 71 | + raise FileNotFoundError("Could not find `kernelguard`, `kguard`, or `uvx` in PATH") |
| 72 | + |
| 73 | + |
| 74 | +def _command() -> list[str]: |
| 75 | + raw = os.getenv("KERNELGUARD_COMMAND", "").strip() |
| 76 | + if raw: |
| 77 | + return shlex.split(raw) |
| 78 | + return _default_command() |
| 79 | + |
| 80 | + |
| 81 | +def _analyze_with_cli(code: str) -> dict[str, Any]: |
| 82 | + cmd = [*_command()] |
| 83 | + profile = _profile() |
| 84 | + config_path = _config_path() |
| 85 | + if profile is not None: |
| 86 | + cmd.extend(["--profile", profile]) |
| 87 | + if config_path is not None: |
| 88 | + cmd.extend(["--config", config_path]) |
| 89 | + cmd.append("--api-mode") |
| 90 | + |
| 91 | + proc = subprocess.run( |
| 92 | + cmd, |
| 93 | + input=code, |
| 94 | + text=True, |
| 95 | + capture_output=True, |
| 96 | + timeout=_timeout_sec(), |
| 97 | + check=False, |
| 98 | + ) |
| 99 | + if proc.returncode != 0: |
| 100 | + stderr = limit_length(proc.stderr.strip(), 300) if proc.stderr else "" |
| 101 | + stdout = limit_length(proc.stdout.strip(), 300) if proc.stdout else "" |
| 102 | + raise RuntimeError( |
| 103 | + "KernelGuard command failed " |
| 104 | + f"(exit={proc.returncode}, stdout={stdout!r}, stderr={stderr!r})" |
| 105 | + ) |
| 106 | + |
| 107 | + lines = [line for line in proc.stdout.splitlines() if line.strip()] |
| 108 | + if not lines: |
| 109 | + raise RuntimeError("KernelGuard returned no JSON result") |
| 110 | + |
| 111 | + try: |
| 112 | + result = json.loads(lines[-1]) |
| 113 | + except json.JSONDecodeError as exc: |
| 114 | + raise RuntimeError(f"KernelGuard returned invalid JSON: {lines[-1]!r}") from exc |
| 115 | + |
| 116 | + if not isinstance(result, dict): |
| 117 | + raise RuntimeError("KernelGuard returned a non-object JSON payload") |
| 118 | + return result |
| 119 | + |
| 120 | + |
| 121 | +def analyze_submission(code: str) -> dict[str, Any]: |
| 122 | + # Always use the single-shot CLI path so KERNELGUARD_TIMEOUT_SEC is enforced. |
| 123 | + return _analyze_with_cli(code) |
| 124 | + |
| 125 | + |
| 126 | +def enforce_submission_precheck(code: str, file_name: str) -> dict[str, Any] | None: |
| 127 | + if not _env_enabled("KERNELGUARD_ENABLED"): |
| 128 | + return None |
| 129 | + |
| 130 | + try: |
| 131 | + result = analyze_submission(code) |
| 132 | + except Exception as exc: |
| 133 | + logger.warning("KernelGuard pre-check failed for %s", file_name, exc_info=exc) |
| 134 | + if _fail_open_enabled(): |
| 135 | + return None |
| 136 | + raise KernelBotError( |
| 137 | + "KernelGuard pre-check is unavailable right now. Please try again later.", |
| 138 | + code=503, |
| 139 | + ) from exc |
| 140 | + |
| 141 | + classification = str(result.get("classification", "unknown")) |
| 142 | + if result.get("should_filter"): |
| 143 | + patterns = sorted( |
| 144 | + { |
| 145 | + str(item.get("pattern", "unknown")) |
| 146 | + for item in result.get("matched_patterns", []) |
| 147 | + if isinstance(item, dict) |
| 148 | + } |
| 149 | + ) |
| 150 | + reason = str(result.get("filter_reason") or classification) |
| 151 | + details = f"Submission rejected by KernelGuard pre-check ({reason})" |
| 152 | + if patterns: |
| 153 | + details += f". Matched rules: {', '.join(patterns)}" |
| 154 | + raise KernelGuardRejected(details + ".", result=result) |
| 155 | + |
| 156 | + if classification != "valid": |
| 157 | + logger.info("KernelGuard classified %s as %s", file_name, classification) |
| 158 | + |
| 159 | + return result |
0 commit comments