|
| 1 | +""" |
| 2 | +Helper for discovering Cloudsmith custom domains. |
| 3 | +
|
| 4 | +This module provides functions to fetch custom domains from the Cloudsmith API |
| 5 | +for use in credential helpers. Results are cached on the filesystem. |
| 6 | +""" |
| 7 | + |
| 8 | +import json |
| 9 | +import logging |
| 10 | +import os |
| 11 | +import time |
| 12 | +from pathlib import Path |
| 13 | +from typing import List, Optional |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +# Cache custom domains for 1 hour |
| 18 | +CACHE_TTL_SECONDS = 3600 |
| 19 | + |
| 20 | + |
| 21 | +def get_cache_dir() -> Path: |
| 22 | + """ |
| 23 | + Get the cache directory for custom domains. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + Path to cache directory (e.g., ~/.cloudsmith/cache/custom_domains/) |
| 27 | + """ |
| 28 | + home = Path.home() |
| 29 | + cache_dir = home / ".cloudsmith" / "cache" / "custom_domains" |
| 30 | + cache_dir.mkdir(parents=True, exist_ok=True) |
| 31 | + return cache_dir |
| 32 | + |
| 33 | + |
| 34 | +def get_cache_path(org: str) -> Path: |
| 35 | + """ |
| 36 | + Get the cache file path for an organization's custom domains. |
| 37 | +
|
| 38 | + Args: |
| 39 | + org: Organization slug |
| 40 | +
|
| 41 | + Returns: |
| 42 | + Path to cache file |
| 43 | + """ |
| 44 | + cache_dir = get_cache_dir() |
| 45 | + # Use org slug as filename (sanitized) |
| 46 | + safe_org = "".join(c if c.isalnum() or c in "-_" else "_" for c in org) |
| 47 | + return cache_dir / f"{safe_org}.json" |
| 48 | + |
| 49 | + |
| 50 | +def is_cache_valid(cache_path: Path) -> bool: |
| 51 | + """ |
| 52 | + Check if a cache file exists and is still valid. |
| 53 | +
|
| 54 | + Args: |
| 55 | + cache_path: Path to cache file |
| 56 | +
|
| 57 | + Returns: |
| 58 | + bool: True if cache exists and hasn't expired |
| 59 | + """ |
| 60 | + if not cache_path.exists(): |
| 61 | + return False |
| 62 | + |
| 63 | + try: |
| 64 | + mtime = cache_path.stat().st_mtime |
| 65 | + age = time.time() - mtime |
| 66 | + return age < CACHE_TTL_SECONDS |
| 67 | + except OSError: |
| 68 | + return False |
| 69 | + |
| 70 | + |
| 71 | +def read_cache(cache_path: Path) -> Optional[List[str]]: |
| 72 | + """ |
| 73 | + Read custom domains from cache file. |
| 74 | +
|
| 75 | + Args: |
| 76 | + cache_path: Path to cache file |
| 77 | +
|
| 78 | + Returns: |
| 79 | + List of domain strings or None if cache invalid/missing |
| 80 | + """ |
| 81 | + if not is_cache_valid(cache_path): |
| 82 | + return None |
| 83 | + |
| 84 | + try: |
| 85 | + with open(cache_path, encoding="utf-8") as f: |
| 86 | + data = json.load(f) |
| 87 | + if isinstance(data, dict) and "domains" in data: |
| 88 | + domains = data["domains"] |
| 89 | + if isinstance(domains, list): |
| 90 | + logger.debug( |
| 91 | + "Read %d domains from cache: %s", len(domains), cache_path |
| 92 | + ) |
| 93 | + return domains |
| 94 | + except (OSError, json.JSONDecodeError) as exc: |
| 95 | + logger.debug("Failed to read cache %s: %s", cache_path, exc) |
| 96 | + |
| 97 | + return None |
| 98 | + |
| 99 | + |
| 100 | +def write_cache(cache_path: Path, domains: List[str]) -> None: |
| 101 | + """ |
| 102 | + Write custom domains to cache file. |
| 103 | +
|
| 104 | + Args: |
| 105 | + cache_path: Path to cache file |
| 106 | + domains: List of domain strings to cache |
| 107 | + """ |
| 108 | + try: |
| 109 | + data = { |
| 110 | + "domains": domains, |
| 111 | + "cached_at": time.time(), |
| 112 | + } |
| 113 | + with open(cache_path, "w", encoding="utf-8") as f: |
| 114 | + json.dump(data, f) |
| 115 | + logger.debug("Wrote %d domains to cache: %s", len(domains), cache_path) |
| 116 | + except OSError as exc: |
| 117 | + logger.debug("Failed to write cache %s: %s", cache_path, exc) |
| 118 | + |
| 119 | + |
| 120 | +def get_custom_domains_for_org( |
| 121 | + org: str, api_host: str = "https://api.cloudsmith.io" |
| 122 | +) -> List[str]: |
| 123 | + """ |
| 124 | + Fetch custom domains for a Cloudsmith organization. |
| 125 | +
|
| 126 | + Results are cached on the filesystem for 1 hour to avoid excessive API calls. |
| 127 | +
|
| 128 | + Args: |
| 129 | + org: Organization slug |
| 130 | + api_host: Cloudsmith API host |
| 131 | +
|
| 132 | + Returns: |
| 133 | + List of custom domain strings (e.g., ['docker.customer.com', 'dl.customer.com']) |
| 134 | + Empty list if API call fails or org has no custom domains |
| 135 | +
|
| 136 | + Example: |
| 137 | + >>> domains = get_custom_domains_for_org('my-org') |
| 138 | + >>> print(domains) |
| 139 | + ['docker.acme.com', 'dl.acme.com'] |
| 140 | + """ |
| 141 | + # Check cache first |
| 142 | + cache_path = get_cache_path(org) |
| 143 | + cached_domains = read_cache(cache_path) |
| 144 | + if cached_domains is not None: |
| 145 | + logger.debug("Using cached custom domains for %s", org) |
| 146 | + return cached_domains |
| 147 | + |
| 148 | + # Cache miss - fetch from API |
| 149 | + logger.debug("Fetching custom domains from API for %s", org) |
| 150 | + |
| 151 | + try: |
| 152 | + import requests |
| 153 | + |
| 154 | + # Construct API URL |
| 155 | + url = f"{api_host}/orgs/{org}/custom-domains/" |
| 156 | + |
| 157 | + # Make API request (no auth needed for custom domains endpoint) |
| 158 | + response = requests.get(url, timeout=5) |
| 159 | + |
| 160 | + if response.status_code == 404: |
| 161 | + logger.debug("Organization %s not found or has no custom domains", org) |
| 162 | + # Cache empty result to avoid repeated 404s |
| 163 | + write_cache(cache_path, []) |
| 164 | + return [] |
| 165 | + |
| 166 | + if response.status_code != 200: |
| 167 | + logger.debug( |
| 168 | + "Failed to fetch custom domains for %s: HTTP %d", |
| 169 | + org, |
| 170 | + response.status_code, |
| 171 | + ) |
| 172 | + return [] |
| 173 | + |
| 174 | + data = response.json() |
| 175 | + |
| 176 | + # Extract domain names from response |
| 177 | + # Expected format: [{"domain": "docker.customer.com", ...}, ...] |
| 178 | + domains = [] |
| 179 | + if isinstance(data, list): |
| 180 | + for item in data: |
| 181 | + if isinstance(item, dict) and "domain" in item: |
| 182 | + domains.append(item["domain"]) |
| 183 | + |
| 184 | + logger.debug("Fetched %d custom domains for %s", len(domains), org) |
| 185 | + |
| 186 | + # Cache the result |
| 187 | + write_cache(cache_path, domains) |
| 188 | + |
| 189 | + return domains |
| 190 | + |
| 191 | + except ImportError: |
| 192 | + logger.debug("requests library not available, cannot fetch custom domains") |
| 193 | + return [] |
| 194 | + except Exception as exc: # pylint: disable=broad-exception-caught |
| 195 | + logger.debug("Error fetching custom domains: %s", exc) |
| 196 | + return [] |
| 197 | + |
| 198 | + |
| 199 | +def get_custom_domains_from_env() -> List[str]: |
| 200 | + """ |
| 201 | + Get custom domains by fetching from API if CLOUDSMITH_ORG is set. |
| 202 | +
|
| 203 | + Returns: |
| 204 | + List of custom domain strings |
| 205 | + Empty list if CLOUDSMITH_ORG not set or API call fails |
| 206 | +
|
| 207 | + Example: |
| 208 | + >>> os.environ['CLOUDSMITH_ORG'] = 'my-org' |
| 209 | + >>> domains = get_custom_domains_from_env() |
| 210 | + >>> print(domains) |
| 211 | + ['docker.acme.com', 'dl.acme.com'] |
| 212 | + """ |
| 213 | + # Check for org and fetch custom domains from API |
| 214 | + org = os.environ.get("CLOUDSMITH_ORG", "").strip() |
| 215 | + if not org: |
| 216 | + return [] |
| 217 | + |
| 218 | + api_host = os.environ.get("CLOUDSMITH_API_HOST", "https://api.cloudsmith.io") |
| 219 | + return get_custom_domains_for_org(org, api_host) |
| 220 | + |
| 221 | + |
| 222 | +def is_custom_cloudsmith_domain(server_url: str, org: Optional[str] = None) -> bool: |
| 223 | + """ |
| 224 | + Check if a server URL matches a custom Cloudsmith domain. |
| 225 | +
|
| 226 | + Args: |
| 227 | + server_url: The server URL to check |
| 228 | + org: Optional organization slug (if not provided, uses CLOUDSMITH_ORG from env) |
| 229 | +
|
| 230 | + Returns: |
| 231 | + bool: True if this is a custom Cloudsmith domain, False otherwise |
| 232 | +
|
| 233 | + Example: |
| 234 | + >>> os.environ['CLOUDSMITH_ORG'] = 'my-org' |
| 235 | + >>> is_custom_cloudsmith_domain('docker.acme.com') |
| 236 | + True |
| 237 | + >>> is_custom_cloudsmith_domain('docker.hub.io') |
| 238 | + False |
| 239 | + """ |
| 240 | + if not server_url: |
| 241 | + return False |
| 242 | + |
| 243 | + # Normalize URL |
| 244 | + normalized = server_url.lower() |
| 245 | + if "://" in normalized: |
| 246 | + normalized = normalized.split("://", 1)[1] |
| 247 | + normalized = normalized.split(":")[0] # Remove port |
| 248 | + |
| 249 | + # Get custom domains |
| 250 | + custom_domains = get_custom_domains_from_env() |
| 251 | + |
| 252 | + # Check if normalized URL matches any custom domain |
| 253 | + return normalized in custom_domains |
0 commit comments