mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-29 11:26:25 -05:00
Map downloads are checked against the hash in the signed manifest (#934)
* Map downloads are checked against the hash in the signed manifest A meta4 signs only a bare hash, so any genuinely signed meta4 (an older version of a region, another region) passed its own check. The manifest now lists each file's sha256; it is signed as a whole, so the hash is tied to the URL. The catalog copies each hash into its download's settings, and aria2c checks the file against it. Downloads from a manifest without hashes still require the file's signed meta4. build_map_regions.py writes the hashes, and hash_map_manifest.py adds them to the published manifest from the verified meta4s without rebuilding any maps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * hash_map_manifest.py hashes each file's bytes instead of trusting its meta4's name Only the bare hash in a meta4 is signed, so an older version's meta4 with its name rewritten (or terrain's, whose name never changes) passed the name and duplicate-hash checks. Each file is now hashed from a local copy of the published files (--files) or downloaded from the CDN, and must match its signed meta4. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ee6c384dc6
commit
e6b7b9e5dd
5 changed files with 341 additions and 55 deletions
|
|
@ -330,18 +330,18 @@ def test_extract_finalize_builds_search_index(test_session, test_directory, has_
|
|||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _prepared_extract(map_dir):
|
||||
def _prepared_extract(map_dir, sha256: str = None):
|
||||
return map_extract_downloader.prepare_download(None, Download(
|
||||
url='https://x/us-2024-01.pmtiles', downloader='map_extract',
|
||||
settings={'region': 'us', 'version': '2024-01'},
|
||||
settings={'region': 'us', 'version': '2024-01', 'sha256': sha256},
|
||||
))
|
||||
|
||||
|
||||
def _prepared_search_index(map_dir):
|
||||
def _prepared_search_index(map_dir, sha256: str = None):
|
||||
(map_dir / 'us-2024-01.pmtiles').write_bytes(b'pretend pmtiles')
|
||||
return map_search_index_downloader.prepare_download(None, Download(
|
||||
url='https://x/us-2024-01.search.db', downloader='map_search_index',
|
||||
settings={'region': 'us', 'pmtiles_name': 'us-2024-01.pmtiles'},
|
||||
settings={'region': 'us', 'pmtiles_name': 'us-2024-01.pmtiles', 'sha256': sha256},
|
||||
))
|
||||
|
||||
|
||||
|
|
@ -521,3 +521,75 @@ async def test_map_download_refuses_unusable_file_name(test_directory, monkeypat
|
|||
|
||||
assert executed.error
|
||||
download_file.assert_not_called()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Hashes from the signed manifest
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
MANIFEST_SHA256 = hashlib.sha256(b'manifest contents').hexdigest()
|
||||
|
||||
|
||||
def test_catalog_finalize_copies_manifest_hashes(test_session, test_directory, test_download_manager, monkeypatch):
|
||||
"""Each child download gets its file's hash from the signed manifest."""
|
||||
map_dir = test_directory / 'maps'
|
||||
monkeypatch.setattr('modules.map.lib.get_map_directory', lambda: map_dir)
|
||||
pmtiles_url, search_url = 'https://x/us-2024-02.pmtiles', 'https://x/us-2024-02.search.db'
|
||||
executed = ExecutedMapCatalog(
|
||||
manifest={'regions': {'us': pmtiles_url}, 'search_indexes': {'us': search_url}, 'version': '2024-02',
|
||||
'sha256': {pmtiles_url: MANIFEST_SHA256, search_url: GENUINE_SHA256}},
|
||||
subscribed_regions=[{'region': 'us'}],
|
||||
)
|
||||
download = Download(url='https://x/manifest.json', downloader='map_catalog')
|
||||
result = map_catalog_downloader.finalize_download(test_session, download, executed)
|
||||
assert result.success is True, result.error
|
||||
|
||||
hashes = {i.downloader: i.settings.get('sha256') for i in test_session.query(Download)}
|
||||
assert hashes == {'map_extract': MANIFEST_SHA256, 'map_search_index': GENUINE_SHA256}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize('downloader,prepare', [
|
||||
(map_extract_downloader, _prepared_extract),
|
||||
(map_search_index_downloader, _prepared_search_index),
|
||||
], ids=['extract', 'search_index'])
|
||||
async def test_map_download_uses_the_manifest_hash(test_directory, monkeypatch, downloader, prepare):
|
||||
"""A hash from the signed manifest is the one aria2c checks. A meta4 signs only a bare hash, so any genuine
|
||||
meta4 (an older version, another region) would pass its own signature check."""
|
||||
map_dir = test_directory / 'maps'
|
||||
map_dir.mkdir()
|
||||
monkeypatch.setattr('modules.map.lib.get_map_directory', lambda: map_dir)
|
||||
prepared = prepare(map_dir, sha256=MANIFEST_SHA256)
|
||||
url = 'https://x/us-2024-01.pmtiles'
|
||||
# A genuinely signed meta4, but of some other file.
|
||||
meta4 = INJECTED_META4.format(url=url).encode()
|
||||
|
||||
with mock.patch.object(downloader, 'get_meta4_contents', mock.AsyncMock(return_value=meta4)) as get_meta4, \
|
||||
mock.patch('modules.map.downloader.verify_gpg_signature', mock.AsyncMock(return_value=True)), \
|
||||
mock.patch.object(downloader, 'download_file', mock.AsyncMock(side_effect=RuntimeError('stop'))) as df:
|
||||
await downloader.execute_download(prepared, make_test_ctx(), Download(url=url))
|
||||
|
||||
get_meta4.assert_not_called()
|
||||
passed = ElementTree.fromstring(df.call_args.kwargs['meta4_xml'])
|
||||
assert [i.text for i in passed.iter('{urn:ietf:params:xml:ns:metalink}hash')] == [MANIFEST_SHA256]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize('downloader,prepare', [
|
||||
(map_extract_downloader, _prepared_extract),
|
||||
(map_search_index_downloader, _prepared_search_index),
|
||||
], ids=['extract', 'search_index'])
|
||||
async def test_map_download_refuses_a_malformed_manifest_hash(test_directory, monkeypatch, downloader, prepare):
|
||||
map_dir = test_directory / 'maps'
|
||||
map_dir.mkdir()
|
||||
monkeypatch.setattr('modules.map.lib.get_map_directory', lambda: map_dir)
|
||||
prepared = prepare(map_dir, sha256='not-a-hash')
|
||||
meta4 = INJECTED_META4.format(url='https://x/a.pmtiles').encode()
|
||||
|
||||
with mock.patch.object(downloader, 'get_meta4_contents', mock.AsyncMock(return_value=meta4)), \
|
||||
mock.patch('modules.map.downloader.verify_gpg_signature', mock.AsyncMock(return_value=True)), \
|
||||
mock.patch.object(downloader, 'download_file', mock.AsyncMock()) as download_file:
|
||||
executed = await downloader.execute_download(prepared, make_test_ctx(), Download(url='https://x/a.pmtiles'))
|
||||
|
||||
assert executed.error
|
||||
download_file.assert_not_called()
|
||||
|
|
|
|||
108
modules/map/test/test_hash_map_manifest.py
Normal file
108
modules/map/test/test_hash_map_manifest.py
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import hashlib
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from wrolpi.scripts.hash_map_manifest import manifest_hashes
|
||||
|
||||
META4 = '''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<metalink xmlns="urn:ietf:params:xml:ns:metalink">
|
||||
<file name="{name}">
|
||||
<hash type="sha-256">{sha256}</hash>
|
||||
<signature mediatype="application/pgp-signature">pretend signature</signature>
|
||||
</file>
|
||||
</metalink>
|
||||
'''
|
||||
FILES = {'us-1.pmtiles': b'pmtiles', 'us-1.search.db': b'search', 'terrain-z0-8.pmtiles': b'terrain'}
|
||||
|
||||
|
||||
def _sha256(contents: bytes) -> str:
|
||||
return hashlib.sha256(contents).hexdigest()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def served(test_directory, simple_file_server):
|
||||
"""The published files, served over HTTP, and their manifest."""
|
||||
host, port = simple_file_server.server_address
|
||||
base = f'http://{host}:{port}' # noqa
|
||||
for name, contents in FILES.items():
|
||||
(test_directory / name).write_bytes(contents)
|
||||
manifest = {
|
||||
'regions': {'us': f'{base}/us-1.pmtiles', 'terrain-z0-8': f'{base}/terrain-z0-8.pmtiles'},
|
||||
'search_indexes': {'us': f'{base}/us-1.search.db'},
|
||||
}
|
||||
# Each file's genuine, signed meta4.
|
||||
meta4s = {f'{base}/{name}': META4.format(name=name, sha256=_sha256(contents)) for name, contents in FILES.items()}
|
||||
return base, manifest, meta4s
|
||||
|
||||
|
||||
async def _hashes(manifest: dict, meta4s: dict, files_directory=None, signature_valid: bool = True):
|
||||
async def get_meta4_contents(url):
|
||||
return meta4s[url].encode() if url in meta4s else None
|
||||
|
||||
with mock.patch('wrolpi.scripts.hash_map_manifest.Downloader.get_meta4_contents', get_meta4_contents), \
|
||||
mock.patch('modules.map.downloader.verify_gpg_signature', mock.AsyncMock(return_value=signature_valid)):
|
||||
return await manifest_hashes(manifest, files_directory)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize('local', [False, True], ids=['downloaded', 'local'])
|
||||
async def test_manifest_hashes(served, tmp_path, local):
|
||||
"""Each hash is of the file's bytes (a local copy of the published files, or downloaded), and matches its signed
|
||||
meta4."""
|
||||
base, manifest, meta4s = served
|
||||
files_directory = None
|
||||
if local:
|
||||
files_directory = tmp_path / 'published'
|
||||
files_directory.mkdir()
|
||||
for name, contents in FILES.items():
|
||||
(files_directory / name).write_bytes(contents)
|
||||
# The local copy is read; the server's file is not.
|
||||
manifest['regions']['us'] = 'http://127.0.0.1:9/us-1.pmtiles'
|
||||
meta4s[manifest['regions']['us']] = meta4s.pop(f'{base}/us-1.pmtiles')
|
||||
|
||||
assert await _hashes(manifest, meta4s, files_directory) == {
|
||||
manifest['regions']['us']: _sha256(b'pmtiles'),
|
||||
f'{base}/terrain-z0-8.pmtiles': _sha256(b'terrain'),
|
||||
f'{base}/us-1.search.db': _sha256(b'search'),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manifest_hashes_refuses_a_missing_meta4(served):
|
||||
base, manifest, meta4s = served
|
||||
del meta4s[f'{base}/us-1.search.db']
|
||||
with pytest.raises(RuntimeError):
|
||||
await _hashes(manifest, meta4s)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manifest_hashes_refuses_an_unsigned_meta4(served):
|
||||
_, manifest, meta4s = served
|
||||
with pytest.raises(RuntimeError):
|
||||
await _hashes(manifest, meta4s, signature_valid=False)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize('name,old_meta4_name', [
|
||||
# An older version's signed meta4, its unsigned name rewritten to the current file's.
|
||||
('us-1.search.db', 'us-1.search.db'),
|
||||
# Terrain is unversioned, so an older signed meta4 already has the current name.
|
||||
('terrain-z0-8.pmtiles', 'terrain-z0-8.pmtiles'),
|
||||
])
|
||||
async def test_manifest_hashes_refuses_an_older_signed_meta4(served, name, old_meta4_name):
|
||||
"""Only a bare hash is signed in a meta4, so only the file's bytes show which file a signed hash belongs to."""
|
||||
base, manifest, meta4s = served
|
||||
meta4s[f'{base}/{name}'] = META4.format(name=old_meta4_name, sha256=_sha256(b'older version'))
|
||||
with pytest.raises(RuntimeError):
|
||||
await _hashes(manifest, meta4s)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manifest_hashes_refuses_a_local_copy_that_differs(served, tmp_path):
|
||||
_, manifest, meta4s = served
|
||||
files_directory = tmp_path / 'published'
|
||||
files_directory.mkdir()
|
||||
(files_directory / 'us-1.pmtiles').write_bytes(b'something else')
|
||||
with pytest.raises(RuntimeError):
|
||||
await _hashes(manifest, meta4s, files_directory)
|
||||
Loading…
Add table
Add a link
Reference in a new issue