diff --git a/src/mvt/common/updates.py b/src/mvt/common/updates.py index 71e97cc4..b0bfc1b2 100644 --- a/src/mvt/common/updates.py +++ b/src/mvt/common/updates.py @@ -9,8 +9,10 @@ import logging import os import re import shlex +import stat import subprocess from datetime import datetime +from pathlib import Path from typing import Optional, Tuple import requests @@ -528,6 +530,20 @@ class IndicatorsUpdates: return yaml.safe_load(res.content) + @staticmethod + def _ioc_file_name(ioc_url: str) -> str: + return ioc_url.split("://", 1)[-1].replace("/", "_") + + @staticmethod + def _cached_file_id(path: Path) -> Optional[tuple[int, int]]: + try: + info = path.stat() + except FileNotFoundError: + return None + if stat.S_ISREG(info.st_mode): + return info.st_dev, info.st_ino + return None + def download_remote_ioc(self, ioc_url: str) -> Optional[str]: try: res = requests.get(ioc_url, timeout=15) @@ -543,8 +559,7 @@ class IndicatorsUpdates: ) return None - clean_file_name = ioc_url.lstrip("https://").replace("/", "_") - ioc_path = os.path.join(MVT_INDICATORS_FOLDER, clean_file_name) + ioc_path = os.path.join(MVT_INDICATORS_FOLDER, self._ioc_file_name(ioc_url)) with open(ioc_path, "w", encoding="utf-8") as handle: handle.write(res.text) @@ -561,6 +576,8 @@ class IndicatorsUpdates: if not index: return + legacy_names: set[str] = set() + protected_names: set[str] = set() for ioc in index.get("indicators", []): ioc_type = ioc.get("type", "") @@ -582,14 +599,36 @@ class IndicatorsUpdates: ) continue + # Keep every current name, including those of feeds that fail to refresh. + protected_names.add(self._ioc_file_name(ioc_url)) + # Reproduce the old spelling for files already in the cache. + legacy_name = ioc_url.lstrip("https://").replace("/", "_") ioc_local_path = self.download_remote_ioc(ioc_url) if not ioc_local_path: + protected_names.add(legacy_name) continue + legacy_names.add(legacy_name) log.info( 'Downloaded indicators "%s" to %s', ioc.get("name"), ioc_local_path ) + obsolete_names = legacy_names - protected_names + if obsolete_names: + cache = Path(MVT_INDICATORS_FOLDER) + # Different spellings can refer to the same file on this filesystem. + protected_ids = { + self._cached_file_id(cache / name) + for name in protected_names + if Path(name).name == name + } + for cached_file in cache.iterdir(): + if cached_file.name not in obsolete_names: + continue + file_id = self._cached_file_id(cached_file) + if file_id is not None and file_id not in protected_ids: + cached_file.unlink(missing_ok=True) + self.set_latest_update() def _get_remote_file_latest_commit( diff --git a/tests/common/test_indicators_updates.py b/tests/common/test_indicators_updates.py new file mode 100644 index 00000000..2b0994a1 --- /dev/null +++ b/tests/common/test_indicators_updates.py @@ -0,0 +1,144 @@ +import json +from types import SimpleNamespace + +import pytest + +from mvt.common import indicators, updates + + +@pytest.fixture +def updater_and_cache(tmp_path, monkeypatch): + cache = tmp_path / "indicators" + cache.mkdir() + monkeypatch.setattr(updates, "MVT_DATA_FOLDER", str(tmp_path)) + monkeypatch.setattr(updates, "MVT_INDICATORS_FOLDER", str(cache)) + monkeypatch.setattr(indicators, "MVT_INDICATORS_FOLDER", str(cache)) + monkeypatch.setattr(indicators.settings, "STIX2", None) + return updates.IndicatorsUpdates(), cache + + +def _mock_downloads(monkeypatch, updater, responses): + monkeypatch.setattr( + updater, + "get_remote_index", + lambda: {"indicators": [{"download_url": url} for url in responses]}, + ) + monkeypatch.setattr(updates.requests, "get", lambda url, *, timeout: responses[url]) + + +def _bundle(domain): + return json.dumps( + { + "objects": [ + { + "type": "indicator", + "id": "indicator--test", + "pattern": f"[domain-name:value = '{domain}']", + } + ] + } + ) + + +@pytest.mark.parametrize("scheme", ["http", "https"]) +def test_refresh_retires_legacy_download(scheme, updater_and_cache, monkeypatch): + updater, cache = updater_and_cache + legacy = cache / "ools.example_iocs.stix2" + legacy.write_text(_bundle("retired.example"), encoding="utf-8") + unrelated = cache / "other.stix2" + unrelated.write_text(_bundle("other.example"), encoding="utf-8") + _mock_downloads( + monkeypatch, + updater, + { + f"{scheme}://tools.example/iocs.stix2": SimpleNamespace( + status_code=200, text=_bundle("current.example") + ) + }, + ) + + updater.update() + updater.update() + + assert not legacy.exists() + assert (cache / "tools.example_iocs.stix2").is_file() + loaded = indicators.Indicators() + loaded.load_indicators_files([]) + assert {ioc.value for ioc in loaded.get_iocs("domains")} == { + "current.example", + "other.example", + } + + +@pytest.mark.parametrize( + ("other_host", "status_code", "expected_legacy"), + [ + ("ools.example", 200, "other feed"), + ("ools.example", 503, "cached feed"), + ("stools.example", 503, "cached feed"), + ("stools.example", 200, None), + ], +) +def test_refresh_handles_legacy_filename_collisions( + other_host, status_code, expected_legacy, updater_and_cache, monkeypatch +): + updater, cache = updater_and_cache + legacy = cache / "ools.example_iocs.stix2" + legacy.write_text("cached feed", encoding="utf-8") + _mock_downloads( + monkeypatch, + updater, + { + "https://tools.example/iocs.stix2": SimpleNamespace( + status_code=200, text="refreshed feed" + ), + f"https://{other_host}/iocs.stix2": SimpleNamespace( + status_code=status_code, text="other feed" + ), + }, + ) + + updater.update() + + assert (cache / "tools.example_iocs.stix2").read_text(encoding="utf-8") == ( + "refreshed feed" + ) + if expected_legacy is None: + assert not legacy.exists() + else: + assert legacy.read_text(encoding="utf-8") == expected_legacy + + +@pytest.mark.parametrize("other_status", [200, 503]) +def test_refresh_uses_filesystem_case_rules( + updater_and_cache, monkeypatch, other_status +): + updater, cache = updater_and_cache + # These are the two paths the previous version wrote, in index order. + legacy = cache / "ools.example_IOCs.stix2" + other = cache / "ools.example_iocs.stix2" + legacy.write_text(_bundle("retired.example"), encoding="utf-8") + other.write_text(_bundle("cached-other.example"), encoding="utf-8") + shared_file = legacy.samefile(other) + _mock_downloads( + monkeypatch, + updater, + { + "https://tools.example/IOCs.stix2": SimpleNamespace( + status_code=200, text=_bundle("current.example") + ), + "https://ools.example/iocs.stix2": SimpleNamespace( + status_code=other_status, text=_bundle("updated-other.example") + ), + }, + ) + + updater.update() + + assert legacy.exists() == shared_file + loaded = indicators.Indicators() + loaded.load_indicators_files([]) + assert {ioc.value for ioc in loaded.get_iocs("domains")} == { + "current.example", + "updated-other.example" if other_status == 200 else "cached-other.example", + }