Files
omar aca8e5da1a
CI / Python 3.13 (push) Successful in 43s
CI / Python 3.12 (push) Successful in 46s
CI / Build and smoke-test image (push) Successful in 12s
Follow two upstream catalogue shifts: release rows and bare branch bounds
2026-11-29 08:39:57 +03:00

265 lines
13 KiB
Python

from __future__ import annotations
from collections import defaultdict, deque
from collections.abc import Mapping
from pathlib import Path
import pytest
from vuln_mcp.models import Doc
from vuln_mcp.sources.feed_android import allowed, android_scope_matches, lookup_android, refresh_android
from vuln_mcp.sources.feeds_common import FeedState
from vuln_mcp.sources.parsers import InvalidData
from vuln_mcp.store import Store
from vuln_mcp.transport import HttpError
pytestmark = pytest.mark.anyio
ROOT = "https://source.android.com/docs/security/bulletin/"
ARCHIVE = ROOT + "asb-overview"
JANUARY = ROOT + "2025-01-01"
FEBRUARY = ROOT + "2025-02-01"
JULY = ROOT + "2026/2026-07-01"
FRAMEWORK_CVE = "CVE-2024-49724"
MEDIATEK_CVE = "CVE-2024-20154"
# Public January 2025 bulletin, limited to the table fields the adapter consumes.
JAN_BODY = f"""
<h2>2025-01-01 security patch level vulnerability details</h2>
<h3>Framework</h3>
<table><thead><tr><th>CVE</th><th>References</th><th>Type</th><th>Severity</th>
<th>Updated AOSP versions</th></tr></thead>
<tbody><tr><td>{FRAMEWORK_CVE}</td><td><a href="https://example.invalid/untrusted">A-369351375</a></td>
<td>EoP</td><td>High</td><td>12, 12L, 13, 14, 15</td></tr></tbody></table>
<h3>Google Play system updates</h3>
<table><tr><th>Subcomponent</th><th>CVE</th></tr>
<tr><td>Documents UI</td><td>CVE-2024-43765</td></tr></table>
<h2>2025-01-05 security patch level vulnerability details</h2>
<h3>MediaTek components</h3>
<table><tr><th>CVE</th><th>References</th><th>Severity</th><th>Subcomponent</th></tr>
<tr><td>{MEDIATEK_CVE}</td><td>A-376809176 M-MOLY00720348</td><td>Critical</td><td>Modem</td></tr></table>
"""
def page(title: str, article: str) -> bytes:
return (f"<!doctype html><html><head><title>{title} &nbsp;|&nbsp; Android Open Source Project</title></head>"
f"<body><article>{article}</article></body></html>").encode()
def january(body: str = JAN_BODY) -> bytes:
return page("Android Security Bulletin&#8212;January 2025",
"<p><em>Published January 6, 2025 | Updated February 6, 2025</em></p>" + body)
def archive(*months: tuple[str, str, str, str]) -> bytes:
rows = "".join(f'<tr><td><a href="/docs/security/bulletin/{path}">{month}</a></td><td>English</td>'
f'<td>{date}</td><td>{levels}</td></tr>' for path, month, date, levels in months)
return page("Android Security Bulletins", "<table><tr><th>Bulletin</th><th>Languages</th>"
"<th>Published date</th><th>Security patch level</th></tr>" + rows + "</table>")
JAN = ("2025-01-01", "January 2025", "January 6, 2025", "2025-01-01<br>2025-01-05")
FEB = ("2025-02-01", "February 2025", "February 3, 2025", "2025-02-01<br>2025-02-05")
class Wire:
def __init__(self) -> None:
self.replies: dict[str, deque[tuple[int, bytes, dict[str, str]]]] = defaultdict(deque)
self.requests: list[tuple[str, Mapping[str, str]]] = []
def put(self, url: str, body: bytes = b"", *, etag: str = '"v1"', status: int = 200) -> None:
self.replies[url].append((status, body, {"etag": etag}))
async def download(
self, source: str, url: str, path: Path, *, headers: Mapping[str, str] | None = None, limit: int,
) -> tuple[int, Mapping[str, str]]:
assert source == "android"
self.requests.append((url, headers or {}))
status, body, response_headers = self.replies[url].popleft()
assert len(body) <= limit
if status == 200:
path.write_bytes(body)
return status, response_headers
async def bytes(self, source: str, url: str, *, deadline: float, limit: int) -> tuple[bytes, Mapping[str, str]]:
assert source == "android"
self.requests.append((url, {}))
status, body, headers = self.replies[url].popleft()
if status == 404:
raise HttpError("not_found")
assert status == 200 and len(body) <= limit
return body, headers
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
async def refresh(store: Store, wire: Wire) -> None:
state = await store.state("android")
async with store.staging("android") as staging:
result = await refresh_android(FeedState(state["checkpoint"], state["validators"]),
http=wire, staging=staging)
if result.layers:
await staging.publish(result.checkpoint, layers=result.layers, validators=result.validators,
artifacts=result.artifacts)
else:
await store.checked("android", checkpoint=result.checkpoint, validators=result.validators,
artifacts=result.artifacts)
def facts(doc: Doc, cve: str) -> list[dict]:
return next(issue for issue in doc.issues if issue.id == cve).facts["android_security_bulletin"]
async def test_archive_indexes_platform_branches_and_chipset_patch_tiers(tmp_path: Path) -> None:
wire = Wire()
wire.put(ARCHIVE, archive(JAN))
wire.put(JANUARY, january())
async with Store(tmp_path) as store:
await refresh(store, wire)
[doc] = await store.by_id(FRAMEWORK_CVE)
assert [match.native_id for match in await store.by_id("ASB-2025-01-01")] == ["ASB-2025-01-01"]
assert doc.url == JANUARY and doc.publisher == "Android Open Source Project"
assert doc.updated == "2025-02-06T00:00:00+00:00"
assert facts(doc, FRAMEWORK_CVE) == [{
"platform": "Android", "component": "Framework", "patch_level": "2025-01-01",
"version_relation": "updated", "platform_versions": ["12", "12L", "13", "14", "15"],
}]
assert facts(doc, MEDIATEK_CVE) == [{
"platform": "Android", "component_vendor": "MediaTek", "patch_level": "2025-01-05",
}]
assert await store.by_id("CVE-2024-43765") == [] # Mainline recap has no independent tier assignment.
platform, chipset = doc.issues
assert platform.products[0]["status"] == chipset.products[0]["status"] == "unknown"
assert chipset.products[0]["vendor"] == ["MediaTek"]
assert platform.fixes[0]["product_id"] == platform.products[0]["product_id"]
assert chipset.fixes[0]["product_id"] == chipset.products[0]["product_id"]
assert "version" not in platform.fixes[0] and "version" not in chipset.fixes[0]
assert "patch level alone does not verify OEM coverage" in platform.fixes[0]["details"]
assert android_scope_matches(platform.fixes[0], "12L")
assert not android_scope_matches(platform.fixes[0], "16")
assert [ref["url"] for issue in doc.issues for ref in issue.refs] == [JANUARY, JANUARY]
assert all(not issue.summary for issue in doc.issues)
assert doc.artifact is not None
assert store.artifact_path(doc.artifact).read_bytes() == january()
async def test_failed_bulletin_rolls_back_archive_validators_and_staged_documents(tmp_path: Path) -> None:
wire = Wire()
wire.put(ARCHIVE, archive(JAN), etag='"archive-original"')
wire.put(JANUARY, january(), etag='"january-original"')
wire.put(ARCHIVE, archive(FEB, JAN), etag='"archive-unpublished"')
wire.put(FEBRUARY, page("Android Security Bulletin&#8212;February 2025", """
<p><em>Published February 3, 2025</em></p>
<h2>2025-02-01 security patch level vulnerability details</h2>
<h3>System</h3><table><tr><th>CVE</th><th>References</th><th>Severity</th>
<th>Updated AOSP versions</th></tr><tr><td>CVE-2025-0110</td><td>A-1</td><td>High</td><td>13</td></tr></table>
"""))
wire.put(JANUARY, january(JAN_BODY.split("<h2>2025-01-05", 1)[0]), etag='"malformed-revision"')
wire.put(ARCHIVE, status=304)
wire.put(JANUARY, status=304)
async with Store(tmp_path) as store:
await refresh(store, wire)
published = await store.state("android")
generation = await store.generation()
with pytest.raises(InvalidData, match="previously indexed Android vulnerability row is missing"):
await refresh(store, wire)
assert await store.state("android") == published
assert await store.generation() == generation
assert await store.by_id("ASB-2025-02-01") == []
assert await store.by_id("CVE-2025-0110") == []
assert await store.by_id(MEDIATEK_CVE)
await refresh(store, wire)
assert wire.requests[-2][1]["If-None-Match"] == '"archive-original"'
assert wire.requests[-1][1]["If-None-Match"] == '"january-original"'
assert await store.generation() == generation
async def test_live_revalidates_exact_bulletin_and_honors_no_store() -> None:
wire = Wire()
wire.replies[JANUARY].append((200, january(), {"Cache-Control": "max-age=0, no-store"}))
wire.put(JANUARY, january())
first = await lookup_android("id", "ASB-2025-01-01", http=wire, deadline=1)
second = await lookup_android("id", "asb-2025-01-01", http=wire, deadline=1)
assert first.status.status == second.status.status == "ok"
assert not first.cacheable and second.cacheable
assert [url for url, _ in wire.requests] == [JANUARY, JANUARY]
assert facts(second.docs[0], FRAMEWORK_CVE)[0]["patch_level"] == "2025-01-01"
for unrouteable in (FRAMEWORK_CVE, JANUARY, "ASB-2025-02-30", "ASB-2025-01-01?hl=ja"):
result = await lookup_android("id", unrouteable, http=wire, deadline=1)
assert result.status.status == "invalid_data" and not result.docs
assert len(wire.requests) == 2
async def test_empty_current_bulletin_requires_publisher_notice() -> None:
wire = Wire()
title = "Android Security Bulletin&#8212;July 2026"
publication = "<em>Published July 6, 2026</em><h2>Announcements</h2>"
wire.put(JULY, page(title, publication + "<ul><li>There are no security vulnerabilities in this bulletin.</li></ul>"))
wire.put(JULY, page(title, publication))
good = await lookup_android("id", "ASB-2026-07-01", http=wire, deadline=1)
assert good.status.status == "ok" and good.docs[0].issues == []
malformed = await lookup_android("id", "ASB-2026-07-01", http=wire, deadline=1)
assert malformed.status.status == "invalid_data" and not malformed.docs
async def test_early_nexus_bulletin_preserves_range_without_inventing_a_patch_level() -> None:
url = ROOT + "2015-08-01"
wire = Wire()
wire.put(url, page("Nexus Security Bulletin&#8212;August 2015", """
<em>Published August 13, 2015</em><h3>Bulletin entry</h3>
<table><tr><th>CVE</th><th>Bug(s) with AOSP links</th><th>Severity</th><th>Affected versions</th></tr>
<tr><td>CVE-2015-1538</td><td>ANDROID-20139950</td><td>Critical</td><td>5.1 and below</td></tr></table>
"""))
result = await lookup_android("id", "ASB-2015-08-01", http=wire, deadline=1)
[doc] = result.docs
assert facts(doc, "CVE-2015-1538") == [{
"platform": "Nexus Android", "version_relation": "affected", "platform_versions_at_or_below": "5.1",
}]
assert not doc.issues[0].fixes
async def test_historical_google_devices_do_not_narrow_aosp_branch_evidence() -> None:
url = ROOT + "2016-07-01"
wire = Wire()
wire.put(url, page("Android Security Bulletin&#8212;July 2016", """
<em>Published July 06, 2016 | Updated April 1, 2019</em>
<h2>2016-07-01 security patch level&#8212;Security vulnerability details</h2>
<table><tr><th>CVE</th><th>References</th><th>Severity*</th><th>Updated Nexus devices</th>
<th>Updated AOSP versions</th><th>Date reported</th></tr>
<tr><td>CVE-2016-2506</td><td>ANDROID-27855172</td><td>Critical</td><td>All Nexus</td>
<td>4.4.4, 5.0.2, 5.1.1, 6.0, 6.0.1</td><td>March 23, 2016</td></tr></table>
"""))
result = await lookup_android("id", "ASB-2016-07-01", http=wire, deadline=1)
[doc] = result.docs
[aosp, google] = facts(doc, "CVE-2016-2506")
assert aosp["platform_versions"] == ["4.4.4", "5.0.2", "5.1.1", "6.0", "6.0.1"]
assert google["updated_google_devices"] == ["Nexus"] and "platform_versions" not in google
assert aosp["patch_level"] == google["patch_level"] == "2016-07-01"
platform, devices = doc.issues[0].products
assert platform["product_id"] != devices["product_id"]
assert devices["vendor"] == ["Google"] and devices["model"] == ["Nexus"]
@pytest.mark.parametrize(("host", "path", "live", "expected"), [
("source.android.com", "/docs/security/bulletin/asb-overview", False, True),
("source.android.com", "/docs/security/bulletin/asb-overview", True, False),
("source.android.com", "/docs/security/bulletin/2016-04-02", True, True),
("source.android.com", "/docs/security/bulletin/2026/2026-07-01.html", True, True),
("source.android.com", "/docs/security/bulletin/2026/2025-01-01", False, False),
("source.android.com", "/docs/security/bulletin/pixel/2025-01-01", False, False),
("source.android.com", "/docs/security/bulletin/2025-01-01/extra", True, False),
("source.android.com.attacker.invalid", "/docs/security/bulletin/2025-01-01", True, False),
])
def test_android_route_allowlist(host: str, path: str, live: bool, expected: bool) -> None:
assert allowed(host, path, live=live) is expected
def test_archive_skips_release_pages_that_carry_no_month() -> None:
from vuln_mcp.sources.feed_android import _archive
html = archive(("android-11", "Android 11", "January 6, 2025", "2025-01-01"), JAN)
entries = _archive(html.decode())
assert list(entries) == ["2025-01-01"]