Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 92 additions & 1 deletion tests/test_updater_fetch_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,19 @@

from __future__ import annotations

import errno
import os
import sys
import tempfile
import unittest
from dataclasses import dataclass
from pathlib import Path
from unittest.mock import patch

from tests import utils
from tests.repository_simulator import RepositorySimulator
from tuf.api.exceptions import RepositoryError
from tuf.api.metadata import DelegatedRole, Delegations
from tuf.api.metadata import DelegatedRole, Delegations, TargetFile
from tuf.ngclient import Updater


Expand Down Expand Up @@ -119,6 +122,94 @@ def test_fetch_target(self, target: TestTarget) -> None:
self.assertEqual(path, updater.find_cached_target(info))
self.assertEqual(path, updater.find_cached_target(info, path))

def test_fetch_target_with_long_cache_filename(self) -> None:
os.rmdir(self.targets_dir)
# Encoding the nested path expands it from 247 to 307 bytes.
prefix = "segment/" * 30
first_target = prefix + "first00"
second_target = prefix + "second0"
content = b"shared content"
self.sim.add_target("targets", content, first_target)
self.sim.add_target("targets", content, second_target)
self.sim.update_snapshot()

updater = self._init_updater()
first_info = updater.get_targetinfo(first_target)
second_info = updater.get_targetinfo(second_target)
assert first_info is not None
assert second_info is not None
self.assertIsNone(updater.find_cached_target(first_info))
self.assertFalse(os.path.exists(self.targets_dir))

explicit_path = os.path.join(self.temp_dir.name, "explicit")
self.assertEqual(
updater.download_target(first_info, explicit_path), explicit_path
)
self.assertEqual(
updater.find_cached_target(first_info, explicit_path), explicit_path
)

first_path = updater.download_target(first_info)
self.assertTrue(Path(first_path).is_relative_to(self.targets_dir))
self.assertIsNone(updater.find_cached_target(second_info))
second_path = updater.download_target(second_info)
self.assertNotEqual(first_path, second_path)

updater = self._init_updater()
self.assertEqual(updater.find_cached_target(first_info), first_path)
self.assertEqual(updater.find_cached_target(second_info), second_path)

def test_generated_target_filename_at_filesystem_limit(self) -> None:
os.rmdir(self.targets_dir)
updater = self._init_updater()
target = TargetFile.from_data("a" * 100, b"content")
with patch.object(
os, "pathconf", side_effect=[FileNotFoundError, 100], create=True
) as pathconf:
self.assertEqual(
updater._generate_target_file_path(target),
os.path.join(self.targets_dir, target.path),
)
self.assertEqual(pathconf.call_count, 2)

target = TargetFile.from_data("a" * 101, b"content")
with patch.object(os, "pathconf", return_value=100, create=True):
path = updater._generate_target_file_path(target)
self.assertLess(len(os.path.basename(path)), 100)

def test_generated_target_path_exceeds_full_path_limit(self) -> None:
updater = self._init_updater()
target = TargetFile.from_data("nested/path/target", b"content")
encoded_path = os.path.join(self.targets_dir, "nested%2Fpath%2Ftarget")
with (
patch.object(os, "pathconf", return_value=255, create=True),
patch.object(
os, "lstat", side_effect=OSError(errno.ENAMETOOLONG, "too long")
) as probe,
):
path = updater._generate_target_file_path(target)

self.assertTrue(Path(path).name.startswith("@"))
probe.assert_called_once_with(encoded_path)

def test_fetch_target_with_low_filename_limit(self) -> None:
target_path = "nested/path/target"
self.sim.add_target("targets", b"content", target_path)
self.sim.update_snapshot()

updater = self._init_updater()
target = updater.get_targetinfo(target_path)
assert target is not None
with patch.object(os, "pathconf", return_value=14, create=True):
self.assertIsNone(updater.find_cached_target(target))
path = updater.download_target(target)
self.assertEqual(updater.find_cached_target(target), path)

components = Path(path).relative_to(self.targets_dir).parts
self.assertTrue(components[0].startswith("@"))
self.assertTrue(all(len(component) <= 14 for component in components))
self.assertEqual(len("".join(components)), 65)

def test_download_targets_with_succinct_roles(self) -> None:
self.sim.add_succinct_roles("targets", 8, "bin")
self.sim.update_snapshot()
Expand Down
48 changes: 47 additions & 1 deletion tuf/ngclient/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
from __future__ import annotations

import contextlib
import errno
import hashlib
import logging
import os
import shutil
Expand Down Expand Up @@ -188,7 +190,19 @@ def _generate_target_file_path(self, targetinfo: TargetFile) -> str:

# Use URL encoded target path as filename
filename = parse.quote(targetinfo.path, "")
return os.path.join(self.target_dir, filename)
filepath = os.path.join(self.target_dir, filename)
# The quoted filename is ASCII, so its byte and character lengths match.
limit = _target_filename_limit(self.target_dir)
if len(filename) > limit or _path_is_too_long(filepath):
digest = hashlib.sha256(targetinfo.path.encode("utf-8")).hexdigest()
# The leading @ is always escaped in regular cache filenames.
name = f"@{digest}"
components = [
name[start : start + limit]
for start in range(0, len(name), limit)
]
return os.path.join(self.target_dir, *components)
return filepath

def get_targetinfo(self, target_path: str) -> TargetFile | None:
"""Return ``TargetFile`` instance with information for ``target_path``.
Expand Down Expand Up @@ -581,6 +595,38 @@ def _preorder_depth_first_walk(
return None


def _target_filename_limit(directory: str) -> int:
"""Return the filesystem's filename limit for the target cache."""
if hasattr(os, "pathconf"):
path = Path(directory)
# The cache directory may not exist before the first download.
for candidate in (path, *path.parents):
try:
limit = os.pathconf(candidate, "PC_NAME_MAX")
except FileNotFoundError:
continue
except (OSError, ValueError):
break
if limit > 0:
return limit
break

# Use the common filesystem limit where pathconf is unavailable.
return 255


def _path_is_too_long(filepath: str) -> bool:
"""Check for a path length error from the operating system."""
try:
os.lstat(filepath)
except OSError as e:
# Windows can report ERROR_FILENAME_EXCED_RANGE as ENOENT.
return (
e.errno == errno.ENAMETOOLONG or getattr(e, "winerror", None) == 206
)
return False


def _ensure_trailing_slash(url: str) -> str:
"""Return url guaranteed to end in a slash."""
return url if url.endswith("/") else f"{url}/"