|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import re |
| 4 | +from dataclasses import dataclass, field |
| 5 | +from datetime import datetime, timezone |
| 6 | + |
| 7 | +import requests |
| 8 | +import yaml |
| 9 | + |
| 10 | +import common |
| 11 | + |
| 12 | +GITHUB_API_BASE = "https://api.github.com/repos/mozilla/foundation-security-advisories" |
| 13 | +ADVISORIES_INDEX_URL = "https://www.mozilla.org/en-US/security/advisories/" |
| 14 | + |
| 15 | + |
| 16 | +class AdvisoryError(Exception): |
| 17 | + """Neither the structured YAML source nor the mozilla.org fallback could give a |
| 18 | + definitive answer. Never guessed at - the caller must halt, per Phase 6's whole reason |
| 19 | + for existing: an LLM must never be left to invent a CVE list.""" |
| 20 | + |
| 21 | + |
| 22 | +@dataclass |
| 23 | +class Advisory: |
| 24 | + mfsa_number: str | None |
| 25 | + mfsa_url: str | None |
| 26 | + announced_date: str | None |
| 27 | + cves: list = field(default_factory=list) # [{id, title, impact, url}] |
| 28 | + |
| 29 | + @classmethod |
| 30 | + def empty(cls) -> "Advisory": |
| 31 | + return cls(mfsa_number=None, mfsa_url=None, announced_date=None, cves=[]) |
| 32 | + |
| 33 | + |
| 34 | +def _fixed_in_candidates(version) -> list: |
| 35 | + """The strings Mozilla's own `fixed_in` uses for this release, most specific first. |
| 36 | +
|
| 37 | + Two-component versions ("153.0") are the first release of a new ESR line, and upstream |
| 38 | + labels those differently: the ESR ships the same code as the matching rapid release on |
| 39 | + that day, so the advisory's fixed_in tends to say "Firefox 153" rather than |
| 40 | + "Firefox ESR 153.0". Later releases on the line ("153.1.0") go back to the ordinary |
| 41 | + "Firefox ESR x.y.z" form. Only the two-component case gets the plain-Firefox |
| 42 | + candidates - offering them for a point release would let an unrelated rapid-release |
| 43 | + advisory match. |
| 44 | + """ |
| 45 | + parts = version.split(".") |
| 46 | + candidates = [f"Firefox ESR {version}"] |
| 47 | + if len(parts) == 3: |
| 48 | + candidates.append(f"Firefox ESR {parts[0]}.{parts[1]}") |
| 49 | + else: |
| 50 | + candidates.append(f"Firefox {version}") |
| 51 | + candidates.append(f"Firefox {parts[0]}") |
| 52 | + return candidates |
| 53 | + |
| 54 | + |
| 55 | +def _matches_version(fixed_in_list, version) -> bool: |
| 56 | + candidates = set(_fixed_in_candidates(version)) |
| 57 | + return any((entry or "").strip() in candidates for entry in (fixed_in_list or [])) |
| 58 | + |
| 59 | + |
| 60 | +def _list_advisory_files(year, timeout=30): |
| 61 | + """Returns [(filename, download_url), ...] for that year's mfsa*.yml files, or [] |
| 62 | + if the year directory doesn't exist yet (e.g. checking next year too early).""" |
| 63 | + url = f"{GITHUB_API_BASE}/contents/announce/{year}" |
| 64 | + r = requests.get(url, timeout=timeout) |
| 65 | + if r.status_code == 404: |
| 66 | + return [] |
| 67 | + r.raise_for_status() |
| 68 | + return [ |
| 69 | + (entry["name"], entry["download_url"]) |
| 70 | + for entry in r.json() |
| 71 | + if entry["name"].startswith("mfsa") and entry["name"].endswith(".yml") |
| 72 | + ] |
| 73 | + |
| 74 | + |
| 75 | +def _fetch_yaml(download_url, timeout=30): |
| 76 | + r = requests.get(download_url, timeout=timeout) |
| 77 | + r.raise_for_status() |
| 78 | + return yaml.safe_load(r.text) |
| 79 | + |
| 80 | + |
| 81 | +def _non_windows_marker(details, markers): |
| 82 | + """The marker that scopes this advisory to a platform we don't build for, or None. |
| 83 | +
|
| 84 | + Matches against title and description together, because upstream puts the scoping in |
| 85 | + whichever of the two it feels like on the day ("... in Firefox for Android" in a title, |
| 86 | + "Note: this bug only affects Android" in a description). Returns the matched marker |
| 87 | + rather than a bool so the caller can log WHY something was dropped. |
| 88 | + """ |
| 89 | + if not markers: |
| 90 | + return None |
| 91 | + haystack = " ".join([ |
| 92 | + (details or {}).get("title", "") or "", |
| 93 | + (details or {}).get("description", "") or "", |
| 94 | + ]).lower() |
| 95 | + for marker in markers: |
| 96 | + if marker.lower() in haystack: |
| 97 | + return marker |
| 98 | + return None |
| 99 | + |
| 100 | + |
| 101 | +def _advisory_from_yaml(filename, data, non_windows_markers=(), logger=None) -> Advisory: |
| 102 | + mfsa_number = filename.removeprefix("mfsa").removesuffix(".yml") # "mfsa2026-13.yml" -> "2026-13" |
| 103 | + cves = [] |
| 104 | + dropped = [] |
| 105 | + for cve_id, details in (data.get("advisories") or {}).items(): |
| 106 | + marker = _non_windows_marker(details, non_windows_markers) |
| 107 | + if marker: |
| 108 | + dropped.append((cve_id, marker)) |
| 109 | + continue |
| 110 | + cves.append({ |
| 111 | + "id": cve_id, |
| 112 | + "title": common.strip_em_dashes((details or {}).get("title", "")), |
| 113 | + "impact": (details or {}).get("impact", "").lower(), |
| 114 | + "url": f"https://www.cve.org/CVERecord?id={cve_id}", |
| 115 | + }) |
| 116 | + if dropped and logger: |
| 117 | + # Logged individually and by name: a reader of this log has to be able to |
| 118 | + # reconstruct exactly which upstream CVEs were left out of a shipped release. |
| 119 | + logger.info("advisory %s: keeping %d of %d CVEs, dropped %d as non-Windows", |
| 120 | + mfsa_number, len(cves), len(cves) + len(dropped), len(dropped)) |
| 121 | + for cve_id, marker in dropped: |
| 122 | + logger.info(" dropped %s (matched %r)", cve_id, marker) |
| 123 | + return Advisory( |
| 124 | + mfsa_number=mfsa_number, |
| 125 | + mfsa_url=f"https://www.mozilla.org/en-US/security/advisories/mfsa{mfsa_number}/", |
| 126 | + announced_date=data.get("announced"), |
| 127 | + cves=cves, |
| 128 | + ) |
| 129 | + |
| 130 | + |
| 131 | +def _candidate_years(): |
| 132 | + now = datetime.now(timezone.utc) |
| 133 | + return [now.year, now.year - 1] |
| 134 | + |
| 135 | + |
| 136 | +def _try_yaml_search(version, non_windows_markers=(), logger=None): |
| 137 | + """Returns (Advisory_or_None, error_or_None). None/None means the source was reachable |
| 138 | + and searched completely but genuinely has nothing for this version.""" |
| 139 | + try: |
| 140 | + for year in _candidate_years(): |
| 141 | + for name, download_url in _list_advisory_files(year): |
| 142 | + data = _fetch_yaml(download_url) |
| 143 | + if data and _matches_version(data.get("fixed_in", []), version): |
| 144 | + if logger: |
| 145 | + logger.info("found %s for %s via structured YAML", name, version) |
| 146 | + return _advisory_from_yaml(name, data, non_windows_markers, logger), None |
| 147 | + return None, None |
| 148 | + except (requests.RequestException, yaml.YAMLError) as exc: |
| 149 | + if logger: |
| 150 | + logger.warning("YAML advisory search failed: %s", exc) |
| 151 | + return None, exc |
| 152 | + |
| 153 | + |
| 154 | +def _try_scrape_search(version, logger=None): |
| 155 | + """Fallback: confirms an MFSA exists and its number/URL, nothing more - the index page |
| 156 | + doesn't carry CVE-level detail, so this can never be used to build a full CVE list.""" |
| 157 | + try: |
| 158 | + r = requests.get(ADVISORIES_INDEX_URL, timeout=30) |
| 159 | + r.raise_for_status() |
| 160 | + except requests.RequestException as exc: |
| 161 | + if logger: |
| 162 | + logger.warning("advisories index scrape failed: %s", exc) |
| 163 | + return None, exc |
| 164 | + |
| 165 | + candidates = _fixed_in_candidates(version) |
| 166 | + for line in r.text.splitlines(): |
| 167 | + if any(c in line for c in candidates): |
| 168 | + match = re.search(r"mfsa(\d{4}-\d+)", line, re.IGNORECASE) |
| 169 | + if match: |
| 170 | + mfsa_number = match.group(1) |
| 171 | + if logger: |
| 172 | + logger.info("found MFSA %s for %s via mozilla.org fallback scrape", mfsa_number, version) |
| 173 | + return { |
| 174 | + "mfsa_number": mfsa_number, |
| 175 | + "mfsa_url": f"https://www.mozilla.org/en-US/security/advisories/mfsa{mfsa_number}/", |
| 176 | + }, None |
| 177 | + return None, None |
| 178 | + |
| 179 | + |
| 180 | +def resolve_advisory(version, non_windows_markers=(), logger=None) -> Advisory: |
| 181 | + """Resolves the MFSA/CVE data for `version` (e.g. "140.14.0"). Returns Advisory.empty() |
| 182 | + for the legitimate "no security content this release" case - only raises AdvisoryError |
| 183 | + when neither source could give a definitive answer, or when they disagree. |
| 184 | +
|
| 185 | + non_windows_markers drops CVEs upstream scopes to platforms ducksteps doesn't build |
| 186 | + for (see [advisory] in config.toml). It only ever filters the CVE list; it never |
| 187 | + affects whether an MFSA is considered found, so an advisory whose every CVE is |
| 188 | + Android-only still resolves and still reports its MFSA number rather than |
| 189 | + masquerading as "no security content". |
| 190 | + """ |
| 191 | + yaml_advisory, yaml_error = _try_yaml_search(version, non_windows_markers, logger=logger) |
| 192 | + if yaml_advisory is not None: |
| 193 | + return yaml_advisory |
| 194 | + |
| 195 | + scrape_hit, scrape_error = _try_scrape_search(version, logger=logger) |
| 196 | + |
| 197 | + if yaml_error is None and scrape_error is None: |
| 198 | + if scrape_hit is None: |
| 199 | + return Advisory.empty() |
| 200 | + raise AdvisoryError( |
| 201 | + f"mozilla.org shows {scrape_hit['mfsa_number']} for {version} but the structured " |
| 202 | + f"YAML repo doesn't - sources disagree, halting rather than guessing CVE details." |
| 203 | + ) |
| 204 | + |
| 205 | + if scrape_hit is not None: |
| 206 | + raise AdvisoryError( |
| 207 | + f"MFSA {scrape_hit['mfsa_number']} confirmed for {version} via the mozilla.org " |
| 208 | + f"fallback, but the structured YAML source errored ({yaml_error}) - cannot build " |
| 209 | + f"a reliable CVE list from a scrape alone." |
| 210 | + ) |
| 211 | + |
| 212 | + if yaml_error is not None and scrape_error is not None: |
| 213 | + raise AdvisoryError( |
| 214 | + f"neither advisory source could be reached for {version}: YAML={yaml_error}, scrape={scrape_error}" |
| 215 | + ) |
| 216 | + |
| 217 | + if logger: |
| 218 | + logger.warning( |
| 219 | + "one advisory source errored (yaml=%s, scrape=%s) but the other found nothing for " |
| 220 | + "%s and was fully reachable; proceeding as no security content", |
| 221 | + yaml_error, scrape_error, version, |
| 222 | + ) |
| 223 | + return Advisory.empty() |
0 commit comments