Skip to content
Merged
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
64 changes: 59 additions & 5 deletions rsconnect/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,39 @@ def _resolved_config_dir() -> Path:
return Path(metadata.config_dirname()).expanduser().resolve()


def _path_identity(path: Path) -> tuple[int, int]:
stat = path.stat()
return stat.st_dev, stat.st_ino


def _path_is_within(path: Path, directory: Path) -> bool:
return path == directory or directory in path.parents
if path == directory or directory in path.parents:
return True
try:
directory_identity = _path_identity(directory)
except (FileNotFoundError, NotADirectoryError):
return False
for ancestor in (path, *path.parents):
try:
if _path_identity(ancestor) == directory_identity:
return True
except (FileNotFoundError, NotADirectoryError):
continue
return False


def _has_reserved_config_directory(path: Path) -> bool:
if _config_dir_names.intersection(path.parts):
return True
for ancestor in (path, *path.parents):
name = ancestor.name.casefold()
if name in _config_dir_names:
try:
if ancestor.samefile(ancestor.with_name(name)):
return True
except (FileNotFoundError, NotADirectoryError):
continue
return False


def _is_config_path(
Expand All @@ -104,14 +135,14 @@ def _is_config_path(
candidate = Path(path)
if base_dir is not None and not candidate.is_absolute():
candidate = Path(base_dir) / candidate
if _config_dir_names.intersection(candidate.parts):
if _has_reserved_config_directory(candidate):
return True
if config_dir is None:
if base_dir is None and not candidate.is_absolute():
return False
config_dir = _resolved_config_dir()
resolved = candidate.resolve()
return bool(_config_dir_names.intersection(resolved.parts)) or _path_is_within(resolved, config_dir)
return _has_reserved_config_directory(resolved) or _path_is_within(resolved, config_dir)


def _ensure_content_root_is_safe(path: str | Path, config_dir: Path) -> None:
Expand Down Expand Up @@ -436,7 +467,7 @@ def discard_file(self, filepath: str) -> None:

def to_file(self, deploy_dir: str) -> typing.IO[bytes]:
bundle_file = tempfile.TemporaryFile(prefix="rsc_bundle")
with tarfile.open(mode="w:gz", fileobj=bundle_file) as bundle:
with tarfile.open(mode="w:gz", fileobj=bundle_file, dereference=True) as bundle:
for fp in self.file_paths:
if Path(fp).name in self.buffer:
continue
Expand Down Expand Up @@ -557,6 +588,7 @@ def bundle_add_file(bundle: tarfile.TarFile, rel_path: str, base_dir: str) -> No
"""
path = join(base_dir, rel_path) if os.path.isdir(base_dir) else rel_path
logger.log(VERBOSE, "Adding file: %s", path)
bundle.dereference = True
bundle.add(path, arcname=rel_path)


Expand Down Expand Up @@ -1358,9 +1390,31 @@ def _iter_directory_files(
) -> Iterator[str]:
glob_set = create_glob_set(path, excludes)
exclude_paths = {Path(p) for p in excludes}
for cur_dir, sub_dirs, files in os.walk(path):
for cur_dir, sub_dirs, files in os.walk(path, followlinks=True):
if _should_skip_walk_directory(cur_dir, sub_dirs, exclude_paths, config_dir):
sub_dirs[:] = []
continue
ancestors: set[tuple[int, int]] = set()
current = Path(cur_dir)
root = Path(path)
while True:
ancestors.add(_path_identity(current))
if current == root:
break
current = current.parent
for sub_dir in sub_dirs[:]:
sub_path = Path(cur_dir) / sub_dir
relative_sub_path = Path(relpath(sub_path, path))
if glob_set.matches(str(sub_path)) or not keep_manifest_specified_file(
str(relative_sub_path),
exclude_paths | directories_to_ignore,
base_dir=path,
config_dir=config_dir,
):
sub_dirs.remove(sub_dir)
elif _path_identity(sub_path) in ancestors:
logger.warning("Skipping directory symlink loop: %s", sub_path)
sub_dirs.remove(sub_dir)
for file in files:
cur_path = os.path.join(cur_dir, file)
rel_path = relpath(cur_path, path)
Expand Down
176 changes: 174 additions & 2 deletions tests/test_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def test_api_bundle_reports_dangling_symlink(tmp_path, link_name):
def test_api_bundle_keeps_valid_symlink(tmp_path):
(tmp_path / "app.py").write_text("app = object()\n")
(tmp_path / "requirements.txt").write_text("flask\n")
(tmp_path / "data.csv").write_text("data\n")
(tmp_path / "data.csv").write_bytes(b"data\n")
try:
(tmp_path / "data-link.csv").symlink_to("data.csv")
except OSError:
Expand All @@ -107,7 +107,179 @@ def test_api_bundle_keeps_valid_symlink(tmp_path):
with tarfile.open(mode="r:gz", fileobj=bundle) as tar:
manifest = json.loads(tar.extractfile("manifest.json").read())
assert manifest["files"]["data-link.csv"]["checksum"] == file_checksum(tmp_path / "data.csv")
assert tar.getmember("data-link.csv").issym()
assert tar.getmember("data-link.csv").isfile()
assert tar.extractfile("data-link.csv").read() == b"data\n"


def make_symlink(link, target, *, directory=False):
try:
link.symlink_to(target, target_is_directory=directory)
except (OSError, NotImplementedError):
pytest.skip("symlinks are unavailable")


def assert_regular_archive(tar):
assert all(not member.issym() and not member.islnk() for member in tar.getmembers())


def test_linked_content_in_shiny_manifest_and_bundles(tmp_path):
from click.testing import CliRunner

from rsconnect.main import cli

app = tmp_path / "app"
app.mkdir()
source = tmp_path / "source.py"
source.write_bytes(b"app = object()\n")
data = tmp_path / "shared"
data.mkdir()
(data / "foo.csv").write_bytes(b"hello\n")
make_symlink(app / "app.py", source)
make_symlink(app / "data", data, directory=True)
make_symlink(data / "nested.csv", data / "foo.csv")
(app / "requirements.txt").write_text("shiny\n")
environment = Environment.create_python_environment(str(app))

result = CliRunner().invoke(cli, ["write-manifest", "shiny", str(app)])
assert result.exit_code == 0, result.output
manifest = json.loads((app / "manifest.json").read_text())
for name, contents in {
"app.py": b"app = object()\n",
"data/foo.csv": b"hello\n",
"data/nested.csv": b"hello\n",
}.items():
assert manifest["files"][name]["checksum"] == rsconnect.bundle.buffer_checksum(contents)

bundles = [
make_api_bundle(str(app), "app:app", AppModes.PYTHON_SHINY, environment, [], []),
make_manifest_bundle(app / "manifest.json"),
]
for bundle in bundles:
with bundle, tarfile.open(mode="r:gz", fileobj=bundle) as tar:
assert_regular_archive(tar)
for name, contents in {
"app.py": b"app = object()\n",
"data/foo.csv": b"hello\n",
"data/nested.csv": b"hello\n",
}.items():
assert tar.getmember(name).isfile()
assert tar.extractfile(name).read() == contents
bundled_manifest = json.loads(tar.extractfile("manifest.json").read())
assert bundled_manifest["files"][name]["checksum"] == rsconnect.bundle.buffer_checksum(contents)


def test_linked_directory_loops_excludes_and_config(tmp_path, monkeypatch, caplog):
app = tmp_path / "app"
app.mkdir()
shared = tmp_path / "shared"
shared.mkdir()
(shared / "foo.csv").write_text("data")
make_symlink(shared / "loop", app, directory=True)
make_symlink(app / "data", shared, directory=True)
make_symlink(app / "other", shared, directory=True)
make_symlink(app / "ignored.csv", shared / "foo.csv")
config = tmp_path / "config"
config.mkdir()
(config / "credentials").write_text("secret")
make_symlink(app / "secret", config, directory=True)
make_symlink(app / "secret-file", config / "credentials")
monkeypatch.setattr(rsconnect.bundle.metadata, "config_dirname", lambda: str(config))

files = rsconnect.bundle.create_file_list(str(app), [], ["data", "ignored.csv"])
assert files == [os.path.join("other", "foo.csv")]
assert "other/loop" in caplog.text.replace("\\", "/")
assert rsconnect.bundle.create_file_list(str(app), ["data/foo.csv"], ["data", "ignored.csv"]) == [
"data/foo.csv",
os.path.join("other", "foo.csv"),
]
assert rsconnect.bundle.create_file_list(str(app), [], ["d*", "ignored.csv"]) == [os.path.join("other", "foo.csv")]


def test_linked_directory_loop_with_case_alias(tmp_path, caplog):
app = tmp_path / "app"
app.mkdir()
case_alias = tmp_path / "APP"
if not case_alias.exists():
pytest.skip("requires a case-insensitive filesystem")
(app / "payload.txt").write_text("payload")
make_symlink(app / "loop", case_alias, directory=True)

assert rsconnect.bundle.create_file_list(str(app), [], []) == ["payload.txt"]
warnings = [record.getMessage() for record in caplog.records if "symlink loop" in record.getMessage()]
assert warnings == [f"Skipping directory symlink loop: {app / 'loop'}"]


@pytest.mark.parametrize("config_name", ["custom-config", ".rsconnect-python"])
def test_bundle_filters_config_case_aliases(tmp_path, monkeypatch, config_name):
app = tmp_path / "app"
app.mkdir()
config = tmp_path / config_name
config.mkdir()
case_alias = tmp_path / config_name.upper()
if not case_alias.exists():
pytest.skip("requires a case-insensitive filesystem")
(config / "nested").mkdir()
(config / "nested" / "credentials").write_text("SECRET")
make_symlink(app / "secret", case_alias, directory=True)
make_symlink(app / "secret-file", case_alias / "nested" / "credentials")
active_config = config if config_name == "custom-config" else tmp_path / "active-config"
monkeypatch.setattr(rsconnect.bundle.metadata, "config_dirname", lambda: str(active_config))

(app / "app.py").write_text("app = object()")
(app / "requirements.txt").write_text("flask\n")
environment = _make_test_environment()
extras = ["secret/nested/credentials", "secret-file"]
with make_api_bundle(str(app), "app:app", AppModes.PYTHON_API, environment, extras, []) as bundle:
members, manifest = _bundle_snapshot(bundle)

assert set(manifest["files"]) == {"app.py", "requirements.txt"}
assert set(members) == {"app.py", "requirements.txt", "manifest.json"}
assert b"SECRET" not in b"".join(members.values())
with pytest.raises(RSConnectException, match="inside the rsconnect-python configuration directory"):
rsconnect.bundle.create_file_list(str(case_alias / "nested"), [], [])


def test_uppercase_reserved_name_on_case_sensitive_filesystem(tmp_path, monkeypatch):
app = tmp_path / "app"
app.mkdir()
uppercase_directory = app / ".RSCONNECT-PYTHON"
uppercase_directory.mkdir()
if (app / ".rsconnect-python").exists():
pytest.skip("requires a case-sensitive filesystem")
(uppercase_directory / "data.txt").write_text("safe")
monkeypatch.setattr(rsconnect.bundle.metadata, "config_dirname", lambda: str(tmp_path / "config"))

assert rsconnect.bundle.create_file_list(str(app), [], []) == [os.path.join(".RSCONNECT-PYTHON", "data.txt")]


def test_notebook_and_bundle_class_dereference_links(tmp_path):
app = tmp_path / "app"
app.mkdir()
notebook = tmp_path / "source.ipynb"
notebook.write_text('{"cells": []}')
data = tmp_path / "data.csv"
data.write_text("data")
make_symlink(app / "notebook.ipynb", notebook)
make_symlink(app / "data.csv", data)
make_symlink(app / "data-again.csv", data)
(app / "requirements.txt").write_text("notebook\n")
environment = Environment.create_python_environment(str(app))
bundle = rsconnect.bundle.Bundle()
bundle.add_file(str(app / "data.csv"))
bundle.add_file(str(app / "data-again.csv"))
bundle.add_file(str(app / "notebook.ipynb"))
bundles = [
make_notebook_source_bundle(
str(app / "notebook.ipynb"), environment, ["data.csv", "data-again.csv"], False, False
),
bundle.to_file(str(app)),
]
for archive in bundles:
with archive, tarfile.open(mode="r:gz", fileobj=archive) as tar:
assert_regular_archive(tar)
assert tar.extractfile("data.csv").read() == b"data"
assert tar.extractfile("data-again.csv").read() == b"data"
assert tar.extractfile("notebook.ipynb").read() == b'{"cells": []}'


class TestBundle(TestCase):
Expand Down
Loading