|
| 1 | +"""OIDC token cache. |
| 2 | +
|
| 3 | +Caches Cloudsmith API tokens obtained via OIDC exchange to avoid unnecessary |
| 4 | +re-exchanges. Uses system keyring when available (respecting CLOUDSMITH_NO_KEYRING), |
| 5 | +with automatic fallback to filesystem storage when keyring is unavailable. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import hashlib |
| 11 | +import json |
| 12 | +import logging |
| 13 | +import os |
| 14 | +import time |
| 15 | +from base64 import urlsafe_b64decode |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | +EXPIRY_MARGIN_SECONDS = 60 |
| 20 | + |
| 21 | +_CACHE_DIR_NAME = "oidc_token_cache" |
| 22 | + |
| 23 | + |
| 24 | +def _get_cache_dir() -> str: |
| 25 | + """Return the cache directory path, creating it if needed.""" |
| 26 | + from ....cli.config import get_default_config_path |
| 27 | + |
| 28 | + base = get_default_config_path() |
| 29 | + cache_dir = os.path.join(base, _CACHE_DIR_NAME) |
| 30 | + if not os.path.isdir(cache_dir): |
| 31 | + os.makedirs(cache_dir, mode=0o700, exist_ok=True) |
| 32 | + return cache_dir |
| 33 | + |
| 34 | + |
| 35 | +def _cache_key(api_host: str, org: str, service_slug: str) -> str: |
| 36 | + """Compute a deterministic cache filename from the exchange parameters.""" |
| 37 | + raw = f"{api_host}|{org}|{service_slug}" |
| 38 | + digest = hashlib.sha256(raw.encode()).hexdigest()[:32] |
| 39 | + return f"oidc_{digest}.json" |
| 40 | + |
| 41 | + |
| 42 | +def _decode_jwt_exp(token: str) -> float | None: |
| 43 | + """Decode the exp claim from a JWT without verification.""" |
| 44 | + try: |
| 45 | + parts = token.split(".") |
| 46 | + if len(parts) != 3: |
| 47 | + return None |
| 48 | + payload_b64 = parts[1] |
| 49 | + padding = 4 - len(payload_b64) % 4 |
| 50 | + if padding != 4: |
| 51 | + payload_b64 += "=" * padding |
| 52 | + payload = json.loads(urlsafe_b64decode(payload_b64)) |
| 53 | + exp = payload.get("exp") |
| 54 | + if exp is not None: |
| 55 | + return float(exp) |
| 56 | + except Exception: # pylint: disable=broad-exception-caught |
| 57 | + logger.debug("Failed to decode JWT expiry", exc_info=True) |
| 58 | + return None |
| 59 | + |
| 60 | + |
| 61 | +def get_cached_token(api_host: str, org: str, service_slug: str) -> str | None: |
| 62 | + """Return a cached token if it exists and is not expired.""" |
| 63 | + token = _get_from_keyring(api_host, org, service_slug) |
| 64 | + if token: |
| 65 | + return token |
| 66 | + return _get_from_disk(api_host, org, service_slug) |
| 67 | + |
| 68 | + |
| 69 | +def _get_from_keyring(api_host: str, org: str, service_slug: str) -> str | None: |
| 70 | + """Try to get token from keyring.""" |
| 71 | + try: |
| 72 | + from ...keyring import get_oidc_token |
| 73 | + |
| 74 | + token_data = get_oidc_token(api_host, org, service_slug) |
| 75 | + if not token_data: |
| 76 | + return None |
| 77 | + |
| 78 | + data = json.loads(token_data) |
| 79 | + token = data.get("token") |
| 80 | + expires_at = data.get("expires_at") |
| 81 | + |
| 82 | + if not token: |
| 83 | + return None |
| 84 | + |
| 85 | + if expires_at is not None: |
| 86 | + remaining = expires_at - time.time() |
| 87 | + if remaining < EXPIRY_MARGIN_SECONDS: |
| 88 | + logger.debug( |
| 89 | + "Keyring OIDC token expired or expiring soon " |
| 90 | + "(%.0fs remaining, margin=%ds)", |
| 91 | + remaining, |
| 92 | + EXPIRY_MARGIN_SECONDS, |
| 93 | + ) |
| 94 | + from ...keyring import delete_oidc_token |
| 95 | + |
| 96 | + delete_oidc_token(api_host, org, service_slug) |
| 97 | + return None |
| 98 | + logger.debug("Using keyring OIDC token (expires in %.0fs)", remaining) |
| 99 | + else: |
| 100 | + logger.debug("Using keyring OIDC token (no expiry information)") |
| 101 | + |
| 102 | + return token |
| 103 | + |
| 104 | + except Exception: # pylint: disable=broad-exception-caught |
| 105 | + logger.debug("Failed to read OIDC token from keyring", exc_info=True) |
| 106 | + return None |
| 107 | + |
| 108 | + |
| 109 | +def _get_from_disk(api_host: str, org: str, service_slug: str) -> str | None: |
| 110 | + """Try to get token from disk cache.""" |
| 111 | + cache_dir = _get_cache_dir() |
| 112 | + cache_file = os.path.join(cache_dir, _cache_key(api_host, org, service_slug)) |
| 113 | + |
| 114 | + if not os.path.isfile(cache_file): |
| 115 | + return None |
| 116 | + |
| 117 | + try: |
| 118 | + with open(cache_file) as f: |
| 119 | + data = json.load(f) |
| 120 | + |
| 121 | + token = data.get("token") |
| 122 | + expires_at = data.get("expires_at") |
| 123 | + |
| 124 | + if not token: |
| 125 | + return None |
| 126 | + |
| 127 | + if expires_at is not None: |
| 128 | + remaining = expires_at - time.time() |
| 129 | + if remaining < EXPIRY_MARGIN_SECONDS: |
| 130 | + logger.debug( |
| 131 | + "Disk cached OIDC token expired or expiring soon " |
| 132 | + "(%.0fs remaining, margin=%ds)", |
| 133 | + remaining, |
| 134 | + EXPIRY_MARGIN_SECONDS, |
| 135 | + ) |
| 136 | + _remove_cache_file(cache_file) |
| 137 | + return None |
| 138 | + logger.debug("Using disk cached OIDC token (expires in %.0fs)", remaining) |
| 139 | + else: |
| 140 | + logger.debug("Using disk cached OIDC token (no expiry information)") |
| 141 | + |
| 142 | + return token |
| 143 | + |
| 144 | + except (json.JSONDecodeError, OSError, KeyError): |
| 145 | + logger.debug("Failed to read OIDC token from disk cache", exc_info=True) |
| 146 | + _remove_cache_file(cache_file) |
| 147 | + return None |
| 148 | + |
| 149 | + |
| 150 | +def store_cached_token(api_host: str, org: str, service_slug: str, token: str) -> None: |
| 151 | + """Cache a token in keyring (if available) or filesystem.""" |
| 152 | + expires_at = _decode_jwt_exp(token) |
| 153 | + |
| 154 | + data = { |
| 155 | + "token": token, |
| 156 | + "expires_at": expires_at, |
| 157 | + "api_host": api_host, |
| 158 | + "org": org, |
| 159 | + "service_slug": service_slug, |
| 160 | + "cached_at": time.time(), |
| 161 | + } |
| 162 | + |
| 163 | + if _store_in_keyring(api_host, org, service_slug, data): |
| 164 | + return |
| 165 | + |
| 166 | + _store_on_disk(api_host, org, service_slug, data) |
| 167 | + |
| 168 | + |
| 169 | +def _store_in_keyring(api_host: str, org: str, service_slug: str, data: dict) -> bool: |
| 170 | + """Try to store token in keyring.""" |
| 171 | + try: |
| 172 | + from ...keyring import store_oidc_token |
| 173 | + |
| 174 | + token_data = json.dumps(data) |
| 175 | + success = store_oidc_token(api_host, org, service_slug, token_data) |
| 176 | + if success: |
| 177 | + logger.debug( |
| 178 | + "Stored OIDC token in keyring (expires_at=%s)", data.get("expires_at") |
| 179 | + ) |
| 180 | + return success |
| 181 | + except Exception: # pylint: disable=broad-exception-caught |
| 182 | + logger.debug("Failed to store OIDC token in keyring", exc_info=True) |
| 183 | + return False |
| 184 | + |
| 185 | + |
| 186 | +def _store_on_disk(api_host: str, org: str, service_slug: str, data: dict) -> None: |
| 187 | + """Store token on disk.""" |
| 188 | + cache_dir = _get_cache_dir() |
| 189 | + cache_file = os.path.join(cache_dir, _cache_key(api_host, org, service_slug)) |
| 190 | + |
| 191 | + try: |
| 192 | + fd = os.open(cache_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) |
| 193 | + with os.fdopen(fd, "w") as f: |
| 194 | + json.dump(data, f) |
| 195 | + logger.debug( |
| 196 | + "Stored OIDC token on disk (expires_at=%s)", data.get("expires_at") |
| 197 | + ) |
| 198 | + except OSError: |
| 199 | + logger.debug("Failed to write OIDC token to disk cache", exc_info=True) |
| 200 | + |
| 201 | + |
| 202 | +def invalidate_cached_token(api_host: str, org: str, service_slug: str) -> None: |
| 203 | + """Remove a cached token from both keyring and disk.""" |
| 204 | + try: |
| 205 | + from ...keyring import delete_oidc_token |
| 206 | + |
| 207 | + delete_oidc_token(api_host, org, service_slug) |
| 208 | + except Exception: # pylint: disable=broad-exception-caught |
| 209 | + logger.debug("Failed to delete OIDC token from keyring", exc_info=True) |
| 210 | + |
| 211 | + cache_dir = _get_cache_dir() |
| 212 | + cache_file = os.path.join(cache_dir, _cache_key(api_host, org, service_slug)) |
| 213 | + _remove_cache_file(cache_file) |
| 214 | + |
| 215 | + |
| 216 | +def _remove_cache_file(path: str) -> None: |
| 217 | + """Safely remove a cache file.""" |
| 218 | + try: |
| 219 | + os.unlink(path) |
| 220 | + except (OSError, TypeError): |
| 221 | + pass |
0 commit comments