|
| 1 | +import hashlib |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import tempfile |
| 5 | +import time |
| 6 | +from dataclasses import dataclass |
| 7 | +from pathlib import Path |
| 8 | +from typing import Optional |
| 9 | + |
| 10 | +import yaml |
| 11 | +from pygitguardian.models import RemediationMessages, SecretScanPreferences, TokenScope |
| 12 | + |
| 13 | +from ggshield.core.dirs import get_cache_dir |
| 14 | + |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | +# How long a successful auth check (metadata + token scopes) stays valid. |
| 19 | +# Short enough that revoked tokens and scope changes propagate quickly; |
| 20 | +# long enough that a burst of scans (e.g. IDE on-save) shares one check. |
| 21 | +TTL_SECONDS = 300 |
| 22 | + |
| 23 | + |
| 24 | +def _cache_file() -> Path: |
| 25 | + # Resolved lazily so GG_CACHE_DIR overrides (tests, sandboxed envs) are honored. |
| 26 | + return get_cache_dir() / "auth_check.yaml" |
| 27 | + |
| 28 | + |
| 29 | +@dataclass |
| 30 | +class CachedAuthCheck: |
| 31 | + # If not None, these are the scopes fetched from /v1/api_tokens/self. |
| 32 | + # None means we haven't fetched scopes yet (e.g. from an auth-login flow |
| 33 | + # where no specific scopes were required). |
| 34 | + scopes: Optional[set[TokenScope]] |
| 35 | + secrets_engine_version: Optional[str] |
| 36 | + maximum_payload_size: Optional[int] |
| 37 | + secret_scan_preferences: Optional[SecretScanPreferences] |
| 38 | + remediation_messages: Optional[RemediationMessages] |
| 39 | + |
| 40 | + |
| 41 | +def _key_hash(instance_url: str, api_key: str) -> str: |
| 42 | + return hashlib.sha256(f"{instance_url}\0{api_key}".encode("utf-8")).hexdigest() |
| 43 | + |
| 44 | + |
| 45 | +def load(instance_url: str, api_key: str) -> Optional[CachedAuthCheck]: |
| 46 | + """Return the cached auth check for this (instance, key) pair, or None on miss.""" |
| 47 | + path = _cache_file() |
| 48 | + try: |
| 49 | + with path.open("r") as f: |
| 50 | + data = yaml.safe_load(f) |
| 51 | + except FileNotFoundError: |
| 52 | + return None |
| 53 | + except (OSError, yaml.YAMLError) as e: |
| 54 | + logger.warning("Could not load auth check cache: %s", repr(e)) |
| 55 | + return None |
| 56 | + |
| 57 | + if not isinstance(data, dict): |
| 58 | + return None |
| 59 | + if data.get("key_hash") != _key_hash(instance_url, api_key): |
| 60 | + return None |
| 61 | + if data.get("expires_at", 0) < time.time(): |
| 62 | + return None |
| 63 | + |
| 64 | + raw_scopes = data.get("scopes") |
| 65 | + scopes: Optional[set[TokenScope]] |
| 66 | + if raw_scopes is None: |
| 67 | + scopes = None |
| 68 | + else: |
| 69 | + scopes = set() |
| 70 | + for scope_str in raw_scopes: |
| 71 | + try: |
| 72 | + scopes.add(TokenScope(scope_str)) |
| 73 | + except ValueError: |
| 74 | + logger.debug("Ignoring unknown cached scope: '%s'", scope_str) |
| 75 | + |
| 76 | + raw_version = data.get("secrets_engine_version") |
| 77 | + secrets_engine_version = raw_version if isinstance(raw_version, str) else None |
| 78 | + |
| 79 | + raw_max_payload = data.get("maximum_payload_size") |
| 80 | + maximum_payload_size = raw_max_payload if isinstance(raw_max_payload, int) else None |
| 81 | + |
| 82 | + raw_ssp = data.get("secret_scan_preferences") |
| 83 | + secret_scan_preferences: Optional[SecretScanPreferences] = None |
| 84 | + if isinstance(raw_ssp, dict): |
| 85 | + try: |
| 86 | + secret_scan_preferences = SecretScanPreferences(**raw_ssp) |
| 87 | + except TypeError as e: |
| 88 | + logger.debug("Ignoring malformed cached secret_scan_preferences: %s", e) |
| 89 | + |
| 90 | + raw_rm = data.get("remediation_messages") |
| 91 | + remediation_messages: Optional[RemediationMessages] = None |
| 92 | + if isinstance(raw_rm, dict): |
| 93 | + try: |
| 94 | + remediation_messages = RemediationMessages(**raw_rm) |
| 95 | + except TypeError as e: |
| 96 | + logger.debug("Ignoring malformed cached remediation_messages: %s", e) |
| 97 | + |
| 98 | + return CachedAuthCheck( |
| 99 | + scopes=scopes, |
| 100 | + secrets_engine_version=secrets_engine_version, |
| 101 | + maximum_payload_size=maximum_payload_size, |
| 102 | + secret_scan_preferences=secret_scan_preferences, |
| 103 | + remediation_messages=remediation_messages, |
| 104 | + ) |
| 105 | + |
| 106 | + |
| 107 | +def store( |
| 108 | + instance_url: str, |
| 109 | + api_key: str, |
| 110 | + scopes: Optional[set[TokenScope]], |
| 111 | + secrets_engine_version: Optional[str], |
| 112 | + maximum_payload_size: Optional[int], |
| 113 | + secret_scan_preferences: Optional[SecretScanPreferences], |
| 114 | + remediation_messages: Optional[RemediationMessages], |
| 115 | +) -> None: |
| 116 | + """Record a successful auth check. |
| 117 | +
|
| 118 | + Pass scopes=None if token scopes were not fetched (only metadata was checked). |
| 119 | + """ |
| 120 | + payload = { |
| 121 | + "key_hash": _key_hash(instance_url, api_key), |
| 122 | + "scopes": (None if scopes is None else sorted(s.value for s in scopes)), |
| 123 | + "secrets_engine_version": secrets_engine_version, |
| 124 | + "maximum_payload_size": maximum_payload_size, |
| 125 | + "secret_scan_preferences": ( |
| 126 | + None |
| 127 | + if secret_scan_preferences is None |
| 128 | + else { |
| 129 | + "maximum_document_size": secret_scan_preferences.maximum_document_size, |
| 130 | + "maximum_documents_per_scan": secret_scan_preferences.maximum_documents_per_scan, |
| 131 | + } |
| 132 | + ), |
| 133 | + "remediation_messages": ( |
| 134 | + None |
| 135 | + if remediation_messages is None |
| 136 | + else { |
| 137 | + "pre_commit": remediation_messages.pre_commit, |
| 138 | + "pre_push": remediation_messages.pre_push, |
| 139 | + "pre_receive": remediation_messages.pre_receive, |
| 140 | + } |
| 141 | + ), |
| 142 | + "expires_at": int(time.time()) + TTL_SECONDS, |
| 143 | + } |
| 144 | + |
| 145 | + path = _cache_file() |
| 146 | + try: |
| 147 | + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 148 | + # Re-apply on a pre-existing dir, since mkdir's mode is ignored when the |
| 149 | + # dir already exists. Keeps the auth-check file out of reach of other |
| 150 | + # local users on shared POSIX hosts. |
| 151 | + try: |
| 152 | + os.chmod(path.parent, 0o700) |
| 153 | + except OSError as e: |
| 154 | + logger.debug("Could not tighten cache dir permissions: %s", repr(e)) |
| 155 | + # Atomic write: a concurrent ggshield process would otherwise be able to |
| 156 | + # observe a truncated YAML file. tempfile in the same directory so |
| 157 | + # os.replace stays on one filesystem. |
| 158 | + fd, tmp_path = tempfile.mkstemp( |
| 159 | + prefix=".auth_check.", suffix=".tmp", dir=path.parent |
| 160 | + ) |
| 161 | + try: |
| 162 | + os.chmod(tmp_path, 0o600) |
| 163 | + with os.fdopen(fd, "w") as f: |
| 164 | + yaml.dump(payload, f, indent=2, default_flow_style=False) |
| 165 | + os.replace(tmp_path, path) |
| 166 | + except Exception: |
| 167 | + try: |
| 168 | + os.unlink(tmp_path) |
| 169 | + except OSError: |
| 170 | + pass |
| 171 | + raise |
| 172 | + except OSError as e: |
| 173 | + logger.warning("Could not save auth check cache: %s", repr(e)) |
| 174 | + |
| 175 | + |
| 176 | +def invalidate() -> None: |
| 177 | + """Drop the cached auth check, typically after a 401 from any API call.""" |
| 178 | + try: |
| 179 | + _cache_file().unlink(missing_ok=True) |
| 180 | + except OSError as e: |
| 181 | + logger.warning("Could not invalidate auth check cache: %s", repr(e)) |
0 commit comments