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
104 changes: 104 additions & 0 deletions tests/test_updater_fetch_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,15 @@

from __future__ import annotations

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

from tests import utils
from tests.repository_simulator import RepositorySimulator
Expand Down Expand Up @@ -207,6 +211,106 @@ def test_invalid_target_cache(self) -> None:
with open(path, "rb") as f:
self.assertEqual(f.read(), target.content)

def test_failed_target_write_preserves_existing_file(self) -> None:
self.sim.add_target("targets", b"new target", "targetpath")
self.sim.update_snapshot()

updater = self._init_updater()
info = updater.get_targetinfo("targetpath")
assert info is not None
path = Path(self.targets_dir, "targetpath")
path.write_bytes(b"old target")

def fail_copy(source: BinaryIO, destination: BinaryIO) -> None:
destination.write(source.read(3))
destination.flush()
raise OSError(errno.ENOSPC, "No space left on device")

with (
patch("tuf.ngclient.updater.shutil.copyfileobj", fail_copy),
self.assertRaises(OSError) as caught,
):
updater.download_target(info)

self.assertEqual(caught.exception.errno, errno.ENOSPC)
self.assertEqual(path.read_bytes(), b"old target")
self.assertEqual(list(path.parent.iterdir()), [path])

@unittest.skipUnless(os.name == "posix", "requires POSIX symlink semantics")
def test_download_target_through_symlinks(self) -> None:
self.sim.add_target("targets", b"new target", "targetpath")
self.sim.update_snapshot()
updater = self._init_updater()
info = updater.get_targetinfo("targetpath")
assert info is not None

destination = Path(self.targets_dir, "destination")
destination.write_bytes(b"old target")
link = Path(self.targets_dir, "link")
link.symlink_to(f"{destination.name}/")
with self.assertRaises(NotADirectoryError):
updater.download_target(info, str(link))
self.assertEqual(destination.read_bytes(), b"old target")
self.assertTrue(link.is_symlink())

link.unlink()
link.symlink_to(destination.name)
self.assertEqual(updater.download_target(info, str(link)), str(link))
self.assertEqual(destination.read_bytes(), b"new target")
self.assertTrue(link.is_symlink())

destination.unlink()
self.assertEqual(updater.download_target(info, str(link)), str(link))
self.assertEqual(destination.read_bytes(), b"new target")
self.assertTrue(link.is_symlink())

nested = Path(self.targets_dir, "nested")
(nested / "child").mkdir(parents=True)
directory_link = Path(self.targets_dir, "directory-link")
directory_link.symlink_to(
Path("nested", "child"), target_is_directory=True
)
link.unlink()
link.symlink_to("directory-link/../destination")
self.assertEqual(updater.download_target(info, str(link)), str(link))
self.assertEqual((nested / "destination").read_bytes(), b"new target")
self.assertCountEqual(os.listdir(nested), ["child", "destination"])

@unittest.skipUnless(
getattr(os, "geteuid", lambda: 0)() != 0,
"requires unprivileged POSIX permissions",
)
def test_download_target_preserves_read_only_file(self) -> None:
self.sim.add_target("targets", b"new target", "targetpath")
self.sim.update_snapshot()
updater = self._init_updater()
info = updater.get_targetinfo("targetpath")
assert info is not None

path = Path(self.targets_dir, "targetpath")
path.write_bytes(b"old target")
path.chmod(0o444)
with self.assertRaises(PermissionError):
updater.download_target(info)
self.assertEqual(path.read_bytes(), b"old target")
self.assertEqual(list(path.parent.iterdir()), [path])

@unittest.skipUnless(os.name == "posix", "requires a POSIX null device")
def test_download_target_to_nonregular_destinations(self) -> None:
self.sim.add_target("targets", b"new target", "targetpath")
self.sim.update_snapshot()
updater = self._init_updater()
info = updater.get_targetinfo("targetpath")
assert info is not None

self.assertEqual(updater.download_target(info, os.devnull), os.devnull)
with self.assertRaises(IsADirectoryError):
updater.download_target(info, self.targets_dir)

Path(self.targets_dir, "targetpath").mkdir()
with self.assertRaises(IsADirectoryError):
updater.download_target(info)

def test_meta_missing_delegated_role(self) -> None:
"""Test a delegation where the role is not part of the snapshot"""

Expand Down
53 changes: 48 additions & 5 deletions tuf/ngclient/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
import logging
import os
import shutil
import stat
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, cast
Expand All @@ -70,6 +71,8 @@
from tuf.ngclient.urllib3_fetcher import Urllib3Fetcher

if TYPE_CHECKING:
from typing import IO

from tuf.ngclient.fetcher import FetcherInterface

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -262,8 +265,9 @@ def download_target(
targetinfo: ``TargetFile`` from ``get_targetinfo()``.
filepath: Local path to download into. If ``None``, the file is
downloaded into directory defined by ``target_dir`` constructor
argument using a generated filename. If file already exists,
it is overwritten.
argument using a generated filename. An existing regular file
is replaced atomically after the download has been verified
and written successfully.
target_base_url: Base URL used to form the final target
download URL. Default is the value provided in ``Updater()``

Expand Down Expand Up @@ -304,14 +308,53 @@ def download_target(
full_url, targetinfo.length
) as target_file:
targetinfo.verify_length_and_hashes(target_file)

target_file.seek(0)
with open(filepath, "wb") as destination_file:
shutil.copyfileobj(target_file, destination_file)

mode = None
with contextlib.suppress(FileNotFoundError):
mode = os.stat(filepath).st_mode
if mode is not None and not stat.S_ISREG(mode):
# Keep the usual file I/O behavior for devices and pipes.
with open(filepath, "wb") as destination_file:
shutil.copyfileobj(target_file, destination_file)
else:
self._persist_target(filepath, target_file, mode)

logger.debug("Downloaded target %s", targetinfo.path)
return filepath

@staticmethod
def _persist_target(
filepath: str, target_file: IO[bytes], mode: int | None
) -> None:
"""Atomically replace a regular target file."""
if mode is not None:
# Preserve the write-access check without truncating the file.
flags = os.O_WRONLY | getattr(os, "O_NONBLOCK", 0)
os.close(os.open(filepath, flags))

# Follow final symlinks without normalizing their spelling. In
# particular, a trailing slash requires a directory at that path.
destination = filepath
while os.path.islink(destination):
destination = os.path.join(
os.path.dirname(destination), os.readlink(destination)
)

# Stage next to the destination so replacement is atomic. A private
# directory lets open() apply the usual umask for a new file.
parent = os.path.realpath(
os.path.dirname(destination) or ".", strict=True
)
with tempfile.TemporaryDirectory(dir=parent) as temporary_dir:
staged_target = os.path.join(temporary_dir, "target")
with open(staged_target, "wb") as destination_file:
shutil.copyfileobj(target_file, destination_file)

if mode is not None:
os.chmod(staged_target, mode & 0o777)
os.replace(staged_target, destination)

def _download_metadata(
self, rolename: str, length: int, version: int | None = None
) -> bytes:
Expand Down