|
| 1 | +"""Platform guardrail config cache. |
| 2 | +
|
| 3 | +session-start fetches the tenant's resolved guardrail config from the platform and writes it |
| 4 | +here; scans only read. Per-agent modes and sensitive-path globs are platform-owned - local |
| 5 | +policy files never carry them. An absent or corrupt cache means built-in defaults (Report |
| 6 | +everywhere + the default globs), always synchronous. |
| 7 | +""" |
| 8 | + |
| 9 | +import json |
| 10 | +import time |
| 11 | +from dataclasses import dataclass, field |
| 12 | +from pathlib import Path |
| 13 | +from typing import Optional |
| 14 | + |
| 15 | +from cycode.cli.apps.ai_guardrails.consts import GuardrailCellMode, PolicyMode |
| 16 | +from cycode.cli.apps.ai_guardrails.scan.consts import DEFAULT_SENSITIVE_PATH_GLOBS |
| 17 | +from cycode.cli.apps.ai_guardrails.scan.types import BlockReason |
| 18 | +from cycode.cli.consts import CYCODE_CONFIGURATION_DIRECTORY |
| 19 | +from cycode.cli.utils.path_utils import atomic_write_text, quarantine_corrupt_file |
| 20 | +from cycode.logger import get_logger |
| 21 | + |
| 22 | +logger = get_logger('AI Guardrails') |
| 23 | + |
| 24 | +GUARDRAILS_CONFIG_FILE_NAME = 'ai-guardrails-config.json' |
| 25 | + |
| 26 | +_DEFAULT_TTL_SECONDS = 900 |
| 27 | + |
| 28 | +# Guardrail keys are the CLI's block-reason vocabulary. Anything else in the payload (a future |
| 29 | +# guardrail this CLI doesn't implement) is ignored - unknown config must never fail closed. |
| 30 | +_KNOWN_GUARDRAIL_KEYS = frozenset( |
| 31 | + reason.value |
| 32 | + for reason in ( |
| 33 | + BlockReason.SECRETS_IN_PROMPT, |
| 34 | + BlockReason.SECRETS_IN_FILE, |
| 35 | + BlockReason.SENSITIVE_PATH, |
| 36 | + BlockReason.SECRETS_IN_MCP_ARGS, |
| 37 | + ) |
| 38 | +) |
| 39 | + |
| 40 | +# CLI --ide names to matrix column names; identity for names not listed. |
| 41 | +_AGENT_BY_IDE_NAME = {'claude-code': 'claude'} |
| 42 | + |
| 43 | + |
| 44 | +def get_config_cache_path() -> Path: |
| 45 | + return Path.home() / CYCODE_CONFIGURATION_DIRECTORY / GUARDRAILS_CONFIG_FILE_NAME |
| 46 | + |
| 47 | + |
| 48 | +def agent_for_ide(ide_name: Optional[str]) -> str: |
| 49 | + ide_name = (ide_name or '').lower() |
| 50 | + return _AGENT_BY_IDE_NAME.get(ide_name, ide_name) |
| 51 | + |
| 52 | + |
| 53 | +def _default_sensitive_globs() -> list: |
| 54 | + return list(DEFAULT_SENSITIVE_PATH_GLOBS) |
| 55 | + |
| 56 | + |
| 57 | +@dataclass |
| 58 | +class GuardrailConfig: |
| 59 | + payload: dict |
| 60 | + fetched_at: float |
| 61 | + tenant_id: Optional[str] = None |
| 62 | + _guardrails: dict = field(init=False, repr=False) |
| 63 | + |
| 64 | + def __post_init__(self) -> None: |
| 65 | + self._guardrails = { |
| 66 | + guardrail.get('key'): guardrail |
| 67 | + for guardrail in self.payload.get('guardrails') or [] |
| 68 | + if guardrail.get('key') in _KNOWN_GUARDRAIL_KEYS |
| 69 | + } |
| 70 | + |
| 71 | + def mode_for(self, guardrail_key: str, ide_name: Optional[str]) -> str: |
| 72 | + agents = (self._guardrails.get(guardrail_key) or {}).get('agents') or {} |
| 73 | + return str(agents.get(agent_for_ide(ide_name), GuardrailCellMode.REPORT.value)).lower() |
| 74 | + |
| 75 | + def _modes_for_event(self, event_name: str, ide_name: Optional[str]) -> list: |
| 76 | + return [ |
| 77 | + self.mode_for(key, ide_name) |
| 78 | + for key, guardrail in self._guardrails.items() |
| 79 | + if str(guardrail.get('event_type', '')).lower() == str(event_name).lower() |
| 80 | + ] |
| 81 | + |
| 82 | + def is_event_off(self, event_name: str, ide_name: Optional[str]) -> bool: |
| 83 | + """Every guardrail for this event is Off - skip the scan entirely.""" |
| 84 | + modes = self._modes_for_event(event_name, ide_name) |
| 85 | + return bool(modes) and all(mode == GuardrailCellMode.OFF for mode in modes) |
| 86 | + |
| 87 | + def can_event_block(self, event_name: str, ide_name: Optional[str]) -> bool: |
| 88 | + """At least one guardrail for this event is in Block mode - the scan must stay synchronous.""" |
| 89 | + return GuardrailCellMode.BLOCK in self._modes_for_event(event_name, ide_name) |
| 90 | + |
| 91 | + def sensitive_globs(self) -> list: |
| 92 | + settings = (self._guardrails.get(BlockReason.SENSITIVE_PATH) or {}).get('settings') or {} |
| 93 | + globs = settings.get('globs') |
| 94 | + return globs if isinstance(globs, list) and globs else _default_sensitive_globs() |
| 95 | + |
| 96 | + def is_expired(self) -> bool: |
| 97 | + ttl = self.payload.get('ttl_seconds') or _DEFAULT_TTL_SECONDS |
| 98 | + return time.time() - self.fetched_at > ttl |
| 99 | + |
| 100 | + def needs_refresh(self, tenant_id: Optional[str]) -> bool: |
| 101 | + """Expired, or fetched for another tenant (the user switched tenants since).""" |
| 102 | + return self.is_expired() or self.tenant_id != tenant_id |
| 103 | + |
| 104 | + |
| 105 | +def apply_platform_config(policy: dict, config: Optional[GuardrailConfig], ide_name: Optional[str]) -> None: |
| 106 | + """Overlay the platform-owned enforcement config onto the local knobs-only policy. |
| 107 | +
|
| 108 | + The platform is the only mode source: no cache (cold start) means the built-in defaults - |
| 109 | + Report everywhere with the default globs - which equal an unconfigured tenant's platform |
| 110 | + config, so behaviour is uniform either way. Each matrix cell lands on its own per-feature |
| 111 | + action, so the two FileRead guardrails (content scan vs. sensitive path) keep independent modes. |
| 112 | + An all-Off event never reaches here at all: scan_command skips it. |
| 113 | + """ |
| 114 | + |
| 115 | + def cell(guardrail_key: str) -> str: |
| 116 | + return config.mode_for(guardrail_key, ide_name) if config is not None else GuardrailCellMode.REPORT.value |
| 117 | + |
| 118 | + def action(guardrail_key: str) -> str: |
| 119 | + return PolicyMode.BLOCK.value if cell(guardrail_key) == GuardrailCellMode.BLOCK else PolicyMode.WARN.value |
| 120 | + |
| 121 | + policy.setdefault('prompt', {})['action'] = action(BlockReason.SECRETS_IN_PROMPT) |
| 122 | + |
| 123 | + file_read = policy.setdefault('file_read', {}) |
| 124 | + file_read['scan_content'] = cell(BlockReason.SECRETS_IN_FILE) != GuardrailCellMode.OFF |
| 125 | + file_read['action'] = action(BlockReason.SECRETS_IN_FILE) |
| 126 | + file_read['deny_globs'] = ( |
| 127 | + (config.sensitive_globs() if config is not None else _default_sensitive_globs()) |
| 128 | + if cell(BlockReason.SENSITIVE_PATH) != GuardrailCellMode.OFF |
| 129 | + else [] |
| 130 | + ) |
| 131 | + file_read['path_action'] = action(BlockReason.SENSITIVE_PATH) |
| 132 | + |
| 133 | + policy.setdefault('mcp', {})['action'] = action(BlockReason.SECRETS_IN_MCP_ARGS) |
| 134 | + |
| 135 | + |
| 136 | +def save_guardrail_config(payload: dict, tenant_id: Optional[str]) -> None: |
| 137 | + """Persist a fetched resolved config; a failed write just leaves the previous cache in place.""" |
| 138 | + path = get_config_cache_path() |
| 139 | + content = {'fetched_at': time.time(), 'tenant_id': tenant_id, 'payload': payload} |
| 140 | + try: |
| 141 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 142 | + atomic_write_text(str(path), json.dumps(content)) |
| 143 | + except Exception as e: |
| 144 | + logger.debug('Failed to save guardrail config cache', exc_info=e) |
| 145 | + |
| 146 | + |
| 147 | +def load_guardrail_config() -> Optional[GuardrailConfig]: |
| 148 | + """The cached platform config, or None when it is absent or corrupt (quarantined).""" |
| 149 | + path = get_config_cache_path() |
| 150 | + if not path.exists(): |
| 151 | + return None |
| 152 | + |
| 153 | + try: |
| 154 | + with open(path, encoding='UTF-8') as file: |
| 155 | + content = json.load(file) |
| 156 | + payload = content['payload'] |
| 157 | + if not isinstance(payload, dict): |
| 158 | + raise ValueError('payload is not an object') |
| 159 | + return GuardrailConfig( |
| 160 | + payload=payload, fetched_at=float(content['fetched_at']), tenant_id=content.get('tenant_id') |
| 161 | + ) |
| 162 | + except Exception as e: |
| 163 | + logger.warning('Guardrail config cache is corrupt and will be moved aside', exc_info=e) |
| 164 | + quarantine_corrupt_file(str(path)) |
| 165 | + return None |
0 commit comments