hades / tests /data /test_sources.py
Kolgrim's picture
HADES pipeline code, tokenizer, tests, docs
5f02c05 verified
Raw History Blame Contribute Delete
9.35 kB
import gzip
import json
import shutil
import zipfile
import pytest
from hades.data.sources import SOURCES
def _check(source, raw_dir, n_min=2, fixed_license=True):
mod = SOURCES[source]
recs = list(mod.iter_records(raw_dir))
assert len(recs) >= n_min
assert len({r.id for r in recs}) == len(recs)
for r in recs:
assert r.source == mod.NAME == source and r.group == mod.GROUP and r.text.strip()
assert r.license == mod.LICENSE if fixed_license else r.license
return recs
def test_registry_order():
assert list(SOURCES) == ["cve", "cisa_kev", "mitre", "rfc", "manpages", "owasp", "wikipedia_security",
"fineweb_edu", "wikipedia_general", "synth_logs"]
groups = {k: m.GROUP for k, m in SOURCES.items()}
assert groups["fineweb_edu"] == groups["wikipedia_general"] == "general" and groups["synth_logs"] == "logs"
def _cve(cid, state="PUBLISHED"):
return {"cveMetadata": {"cveId": cid, "state": state}, "containers": {"cna": {
"title": f"Overflow in {cid}", "descriptions": [{"lang": "en", "value": f"A buffer overflow in {cid} allows RCE."}],
"problemTypes": [{"descriptions": [{"cweId": "CWE-787", "description": "OOB write"}]}],
"affected": [{"vendor": "acme", "product": "widget"}]}}}
def test_cve(tmp_path):
d = tmp_path / "cve"
d.mkdir()
with zipfile.ZipFile(d / "cvelistV5-main.zip", "w") as z:
z.writestr("cvelistV5-main/cves/2024/1xxx/CVE-2024-1000.json", json.dumps(_cve("CVE-2024-1000")))
z.writestr("cvelistV5-main/cves/2024/1xxx/CVE-2024-1001.json", json.dumps(_cve("CVE-2024-1001")))
z.writestr("cvelistV5-main/cves/2024/1xxx/CVE-2024-1002.json", json.dumps(_cve("CVE-2024-1002", "REJECTED")))
z.writestr("cvelistV5-main/cves/delta.json", "{}")
recs = _check("cve", tmp_path)
assert len(recs) == 2 and "CWE-787" in recs[0].text and "acme" in recs[0].text
def test_cisa_kev(tmp_path):
(tmp_path / "cisa_kev").mkdir()
vulns = [{"cveID": f"CVE-2023-{i}", "vendorProject": "acme", "product": "vpn", "vulnerabilityName": "Auth bypass",
"shortDescription": "Allows bypass.", "requiredAction": "Apply updates."} for i in range(3)]
(tmp_path / "cisa_kev" / "known_exploited_vulnerabilities.json").write_text(json.dumps({"vulnerabilities": vulns}))
assert "Apply updates." in _check("cisa_kev", tmp_path)[0].text
def test_mitre(tmp_path):
d = tmp_path / "mitre"
d.mkdir()
objs = [{"type": "attack-pattern", "id": "attack-pattern--1", "name": "Brute Force", "description": "Adversaries guess passwords.",
"x_mitre_detection": "Monitor failed logins.", "external_references": [{"source_name": "mitre-attack", "external_id": "T1110"}]},
{"type": "attack-pattern", "id": "attack-pattern--2", "name": "Old", "description": "x", "revoked": True,
"external_references": [{"source_name": "mitre-attack", "external_id": "T9999"}]}]
(d / "enterprise-attack.json").write_text(json.dumps({"type": "bundle", "objects": objs}))
cwe = ('<Weakness_Catalog xmlns="http://cwe.mitre.org/cwe-7"><Weaknesses><Weakness ID="79" Name="XSS">'
'<Description>Improper neutralization of input.</Description><Potential_Mitigations><Mitigation>'
'<Description>Encode output.</Description></Mitigation></Potential_Mitigations></Weakness></Weaknesses></Weakness_Catalog>')
with zipfile.ZipFile(d / "cwec_latest.xml.zip", "w") as z:
z.writestr("cwec_v4.15.xml", cwe)
(d / "capec_latest.xml").write_text(
'<Attack_Pattern_Catalog xmlns="http://capec.mitre.org/capec-3"><Attack_Patterns><Attack_Pattern ID="112" Name="Brute Force">'
'<Description>Guess secrets.</Description><Mitigations><Mitigation>Use strong secrets.</Mitigation></Mitigations>'
'</Attack_Pattern></Attack_Patterns></Attack_Pattern_Catalog>')
recs = _check("mitre", tmp_path, 3)
ids = {r.id for r in recs}
assert ids == {"attack:T1110", "cwe:79", "capec:112"}
texts = " ".join(r.text for r in recs)
assert "Monitor failed logins." in texts and "Encode output." in texts and "Use strong secrets." in texts
def test_rfc(tmp_path):
d = tmp_path / "rfc"
d.mkdir()
index = ('<rfc-index xmlns="https://www.rfc-editor.org/rfc-index">'
'<rfc-entry><doc-id>RFC4253</doc-id><title>The Secure Shell (SSH) Transport Layer Protocol</title></rfc-entry>'
'<rfc-entry><doc-id>RFC8446</doc-id><title>The Transport Layer Security (TLS) Protocol Version 1.3</title></rfc-entry>'
'<rfc-entry><doc-id>RFC2324</doc-id><title>Hyper Text Coffee Pot Control Protocol</title><keywords><kw>coffee</kw></keywords></rfc-entry>'
'</rfc-index>')
(d / "rfc-index.xml").write_text(index)
body = "Body text about the protocol.\n\nYlonen & Lonvick Standards Track [Page 1]\n\x0c\nRFC 4253 SSH Transport Layer Protocol January 2006\n\nMore text."
(d / "txt").mkdir()
for name in ("rfc4253.txt", "rfc8446.txt", "rfc2324.txt"):
(d / "txt" / name).write_text(body)
recs = _check("rfc", tmp_path)
assert {r.id for r in recs} == {"RFC4253", "RFC8446"}
assert "[Page 1]" not in recs[0].text and "January 2006" not in recs[0].text and "More text." in recs[0].text
def test_manpages(tmp_path):
d = tmp_path / "manpages" / "man8"
d.mkdir(parents=True)
(d / "sshd.txt").write_text("SSHD(8)\n\nNAME\n sshd - OpenSSH daemon\n")
(d / "iptables.txt").write_text("IPTABLES(8)\n\nNAME\n iptables - packet filter\n")
(tmp_path / "manpages" / "licenses.json").write_text(json.dumps({"man8/sshd.txt": "BSD", "man8/iptables.txt": "GPL-2.0"}))
recs = _check("manpages", tmp_path, fixed_license=False)
assert {r.id for r in recs} == {"man8/sshd", "man8/iptables"}
assert {r.id: r.license for r in recs} == {"man8/sshd": "BSD", "man8/iptables": "GPL-2.0"}
def test_owasp(tmp_path):
(tmp_path / "owasp").mkdir()
with zipfile.ZipFile(tmp_path / "owasp" / "CheatSheetSeries-master.zip", "w") as z:
z.writestr("CheatSheetSeries-master/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.md", "# SQLi\nUse parameterized queries.")
z.writestr("CheatSheetSeries-master/cheatsheets/Password_Storage_Cheat_Sheet.md", "# Passwords\nUse Argon2id.")
z.writestr("CheatSheetSeries-master/README.md", "readme")
assert len(_check("owasp", tmp_path)) == 2
def test_wikipedia_security(tmp_path):
(tmp_path / "wikipedia_security").mkdir()
rows = [{"title": "Firewall (computing)", "text": "A firewall is..."}, {"title": "Phishing", "text": "Phishing is..."}]
(tmp_path / "wikipedia_security" / "articles.jsonl").write_text("\n".join(json.dumps(r) for r in rows))
assert {r.id for r in _check("wikipedia_security", tmp_path)} == {"Firewall (computing)", "Phishing"}
def test_fineweb_edu(tmp_path):
(tmp_path / "fineweb_edu").mkdir()
rows = [{"id": "<urn:1>", "text": "Photosynthesis converts light."}, {"id": "<urn:2>", "text": "Rivers erode valleys."}]
(tmp_path / "fineweb_edu" / "part-000.jsonl").write_text("\n".join(json.dumps(r) for r in rows))
_check("fineweb_edu", tmp_path)
def test_wikipedia_general_excludes_security_titles(tmp_path):
(tmp_path / "wikipedia_general").mkdir()
(tmp_path / "wikipedia_security").mkdir()
(tmp_path / "wikipedia_security" / "articles.jsonl").write_text(json.dumps({"title": "Phishing", "text": "x"}))
rows = [{"id": "1", "title": "Rome", "text": "Rome is a city."}, {"id": "2", "title": "Phishing", "text": "dup"},
{"id": "3", "title": "Lion", "text": "Lions are cats."}]
(tmp_path / "wikipedia_general" / "part-000.jsonl").write_text("\n".join(json.dumps(r) for r in rows))
assert {r.id for r in _check("wikipedia_general", tmp_path)} == {"1", "3"}
def test_synth_logs(tmp_path):
mod = SOURCES["synth_logs"]
recs = list(mod.iter_records(tmp_path, target_bytes=50_000))
assert sum(len(r.text) for r in recs) >= 50_000 and all(r.group == "logs" for r in recs)
def test_rfc_selection_from_index(tmp_path):
from hades.data.sources import rfc
(tmp_path / "rfc-index.xml").write_text(
'<rfc-index xmlns="https://www.rfc-editor.org/rfc-index">'
'<rfc-entry><doc-id>RFC4253</doc-id><title>The Secure Shell (SSH) Transport Layer Protocol</title></rfc-entry>'
'<rfc-entry><doc-id>RFC2324</doc-id><title>Hyper Text Coffee Pot Control Protocol</title></rfc-entry>'
'</rfc-index>')
assert rfc.selected_ids(tmp_path / "rfc-index.xml") == ["RFC4253"]
assert rfc.txt_url("RFC4253") == "https://www.rfc-editor.org/rfc/rfc4253.txt"
@pytest.mark.skipif(shutil.which("groff") is None, reason="groff not installed")
def test_manpage_render_with_groff(tmp_path):
from hades.data.sources.manpages import render
page = tmp_path / "demo.8.gz"
page.write_bytes(gzip.compress(b'.TH DEMO 8\n.SH NAME\ndemo \\- a demo daemon\n.SH DESCRIPTION\n.B demo\nlistens on port 22.\n'))
text = render(page)
assert "NAME" in text and "a demo daemon" in text and "listens on port 22" in text
assert "\x1b" not in text and "\b" not in text
so = tmp_path / "alias.8.gz"
so.write_bytes(gzip.compress(b".so man8/demo.8\n"))
assert render(so) == ""