From e649ce4508059c4a6a68eae8cd4febdbb728aff2 Mon Sep 17 00:00:00 2001 From: Volv G Date: Fri, 20 Nov 2026 15:45:43 -0800 Subject: [PATCH] Sandbox pipeline template hydration (v0.1.40) --- README.md | 4 +- .../tangle-cli/src/tangle_cli/__init__.py | 2 +- .../src/tangle_cli/pipeline_hydrator.py | 25 ++- pyproject.toml | 4 +- tests/test_packaging.py | 3 +- tests/test_pipeline_decompiler.py | 6 +- tests/test_template_hydration_trust.py | 193 ++++++++++++++++++ uv.lock | 4 +- 8 files changed, 227 insertions(+), 14 deletions(-) create mode 100644 tests/test_template_hydration_trust.py diff --git a/README.md b/README.md index f2f811a..4d44178 100644 --- a/README.md +++ b/README.md @@ -496,6 +496,8 @@ uv run tangle sdk pipelines diagram pipeline.yaml uv run tangle sdk pipelines layout pipeline.yaml --recursive ``` +`hydrate` renders a `template_file` config in Jinja2's sandbox: a template that reaches for Python internals fails the hydration. `--trusted-hydration` and `--trusted-source` apply to `local_from_python` and do not lift the sandbox. `{% include %}`, `{% import %}` and `include_raw` read files from the template's directory. + `pipelines dehydrate` is the inverse of `hydrate`. It replaces inline component specs with references, using the same noninteractive dehydrator as `pipeline-runs export --dehydrate`, and a single `--mode` applies to every component: | `--mode` | Each inline component becomes | @@ -652,7 +654,7 @@ Python: a dehydrated input whose components resolve through trust. So is any other resolver kind that may build or run code — `local_from_docker` and the other docker/container spellings, or any kind a downstream package registers — with `unsupported-executable-component-source`, -and a `template_file` component config, whose Jinja could reach Python, with +and a `template_file` component config, which only hydration renders, with `unsupported-template-component-source`: decompile resolves only digests, names, http(s) URLs and plain files, through the built-in resolvers and URI readers; a URI scheme only a downstream reader handles is refused the same way. Run `tangle sdk pipelines hydrate` on such a pipeline first — that is diff --git a/packages/tangle-cli/src/tangle_cli/__init__.py b/packages/tangle-cli/src/tangle_cli/__init__.py index e0b18be..7361905 100644 --- a/packages/tangle-cli/src/tangle_cli/__init__.py +++ b/packages/tangle-cli/src/tangle_cli/__init__.py @@ -14,6 +14,6 @@ try: __version__ = metadata_version("tangle-cli") except PackageNotFoundError: - __version__ = "0.1.39" + __version__ = "0.1.40" __all__ = ["TangleDynamicDiscoveryClient", "__version__"] diff --git a/packages/tangle-cli/src/tangle_cli/pipeline_hydrator.py b/packages/tangle-cli/src/tangle_cli/pipeline_hydrator.py index e3aa411..735551c 100644 --- a/packages/tangle-cli/src/tangle_cli/pipeline_hydrator.py +++ b/packages/tangle-cli/src/tangle_cli/pipeline_hydrator.py @@ -167,14 +167,25 @@ def render_template( ) -> str: """Render a Jinja2 template with the given context. - Ported from TD's ``render_template`` helper, including ``include_raw``. + A template is pipeline input, so it renders in Jinja2's + ``SandboxedEnvironment``: access to Python internals fails the render. + ``include_raw`` includes a file from the template's directory without + Jinja2 processing, through the same loader as ``{% include %}``. """ - from jinja2 import Environment, FileSystemLoader + from jinja2 import FileSystemLoader + from jinja2.exceptions import SecurityError + from jinja2.sandbox import SandboxedEnvironment + + class _TemplateSandbox(SandboxedEnvironment): + def unsafe_undefined(self, obj: Any, attribute: str) -> Any: + raise SecurityError( + f"access to attribute {attribute!r} of a {type(obj).__name__!r} object is unsafe" + ) template_dir = template_path.parent template_name = template_path.name - env = Environment( + env = _TemplateSandbox( loader=FileSystemLoader(str(template_dir)), keep_trailing_newline=True, ) @@ -191,7 +202,13 @@ def include_raw(path: str) -> str: if overrides: merged_context.update(overrides) - return template.render(**merged_context) + try: + return template.render(**merged_context) + except SecurityError as exc: + raise UntrustedHydrationSourceError( + f"Refusing to render template {template_path}: it uses a feature " + f"that the template sandbox blocks ({exc})." + ) from exc class PipelineHydrator(TangleCliHandler): diff --git a/pyproject.toml b/pyproject.toml index e5f85f4..2aa671e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "tangle-cli" -version = "0.1.39" +version = "0.1.40" description = "CLI for Tangle, the open-source ML pipeline orchestration platform" readme = "README.md" authors = [ @@ -14,7 +14,7 @@ dependencies = [ "cyclopts>=4.16.1", "docstring-parser>=0.16", "httpx>=0.28.1", - "jinja2>=3.1", + "jinja2>=3.1.6", "jsonschema>=4.25.0", "platformdirs>=4.10.0", "pydantic>=2.0", diff --git a/tests/test_packaging.py b/tests/test_packaging.py index cbf523c..558a6d1 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -183,7 +183,8 @@ def test_tangle_cli_wheel_supports_expert_no_deps_import_path_without_tangle_api requires_dist = [line for line in metadata.splitlines() if line.startswith("Requires-Dist: ")] assert not any(name.startswith("tangle_api/") for name in names) assert "tangle_cli/openapi/openapi.json" not in names - assert "Version: 0.1.39" in metadata + assert "Version: 0.1.40" in metadata + assert "Requires-Dist: jinja2>=3.1.6" in requires_dist assert "Requires-Dist: tangle-api==0.1.1" in requires_dist assert not any("extra == 'native'" in line for line in requires_dist) assert "Provides-Extra: native" in metadata diff --git a/tests/test_pipeline_decompiler.py b/tests/test_pipeline_decompiler.py index abde892..70e49ed 100644 --- a/tests/test_pipeline_decompiler.py +++ b/tests/test_pipeline_decompiler.py @@ -1892,14 +1892,14 @@ def test_a_template_component_is_refused_without_rendering(tmp_path: Path, route def test_hydrating_a_template_first_then_decompiling_succeeds(tmp_path: Path) -> None: """The explicit hydrate renders it; decompile then reads plain YAML.""" - _template_leaf(tmp_path) + (tmp_path / "leaf.j2").write_text("# {{ note }}\n" + dump_yaml(_leaf("templated")), encoding="utf-8") + _write(tmp_path / "leaf.yaml", {"template_file": "leaf.j2", "note": "rendered by hydrate"}) source = _write(tmp_path / "in.yaml", _graph_spec("Root", {"a": _ref(url="file://./leaf.yaml")})) hydrated = PipelineHydrator(client=_UnreachableLibrary()).hydrate_file(source).data - (tmp_path / "SENTINEL").unlink() result = decompile_pipeline_file(_write(tmp_path / "hydrated.yaml", hydrated), tmp_path / "gen.py", client=_UnreachableLibrary()) - assert result.verified and not (tmp_path / "SENTINEL").exists() + assert result.verified @pytest.mark.parametrize("fallback", [False, True], ids=["primary", "behind-fallback"]) diff --git a/tests/test_template_hydration_trust.py b/tests/test_template_hydration_trust.py new file mode 100644 index 0000000..9beb54f --- /dev/null +++ b/tests/test_template_hydration_trust.py @@ -0,0 +1,193 @@ +"""A ``template_file`` is pipeline input: rendering it must not reach Python internals.""" + +from __future__ import annotations + +import textwrap +from pathlib import Path + +import pytest +import yaml + +from tangle_cli.pipeline_hydrator import ( + PipelineHydrator, + UntrustedHydrationSourceError, + render_template, +) + +PIPELINE_TEMPLATE = textwrap.dedent( + """ + name: "{{ pipeline_name }}" + implementation: + graph: + tasks: {} + """ +) + + +def _write_config(path: Path, template_file: str, **params: str) -> Path: + path.write_text(yaml.safe_dump({"template_file": template_file, **params}), encoding="utf-8") + return path + + +def test_render_template_blocks_python_internals(tmp_path: Path): + template = tmp_path / "pipeline.yaml.j2" + template.write_text('name: "{{ pipeline_name.__class__ }}"\n', encoding="utf-8") + + with pytest.raises(UntrustedHydrationSourceError, match="template sandbox"): + render_template(template, {"pipeline_name": "P"}) + + +def test_hydrate_file_template_cannot_reach_python_internals(tmp_path: Path): + (tmp_path / "pipeline.yaml.j2").write_text( + 'name: "{{ pipeline_name.__class__.__mro__ }}"\nimplementation:\n graph:\n tasks: {}\n', + encoding="utf-8", + ) + config = _write_config(tmp_path / "pipeline.yaml", "pipeline.yaml.j2", pipeline_name="P") + + with pytest.raises(UntrustedHydrationSourceError, match="template sandbox"): + PipelineHydrator().hydrate_file(config) + + +def test_component_template_cannot_reach_python_internals(tmp_path: Path): + (tmp_path / "component.yaml.j2").write_text( + 'name: "{{ component_name.__class__ }}"\nimplementation:\n container:\n image: python:3.12\n', + encoding="utf-8", + ) + _write_config(tmp_path / "component.yaml", "component.yaml.j2", component_name="C") + pipeline = tmp_path / "pipeline.yaml" + pipeline.write_text( + yaml.safe_dump({ + "name": "P", + "implementation": {"graph": {"tasks": { + "task": {"componentRef": {"url": "file://./component.yaml"}}, + }}}, + }), + encoding="utf-8", + ) + + with pytest.raises(UntrustedHydrationSourceError, match="template sandbox"): + PipelineHydrator().hydrate_file(pipeline) + + +@pytest.mark.parametrize("trust", ["all", "source"]) +def test_trusted_hydration_does_not_lift_the_template_sandbox(tmp_path: Path, trust: str): + (tmp_path / "pipeline.yaml.j2").write_text( + 'name: "{{ pipeline_name.__class__ }}"\nimplementation:\n graph:\n tasks: {}\n', + encoding="utf-8", + ) + config = _write_config(tmp_path / "pipeline.yaml", "pipeline.yaml.j2", pipeline_name="P") + + with pytest.raises(UntrustedHydrationSourceError, match="template sandbox"): + PipelineHydrator( + allow_all_hydration=trust == "all", + trusted_python_sources=[str(tmp_path)] if trust == "source" else [], + ).hydrate_file(config) + + +@pytest.mark.parametrize("directive", ["{{ include_raw(%s) }}", "{%% include %s %%}", "{%% import %s as m %%}"]) +@pytest.mark.parametrize("absolute", [False, True], ids=["parent-traversal", "absolute-path"]) +def test_includes_read_only_inside_the_template_directory(tmp_path: Path, directive: str, absolute: bool): + from jinja2.exceptions import TemplateNotFound + + templates = tmp_path / "templates" + templates.mkdir() + (tmp_path / "outside.txt").write_text("outside the template directory\n", encoding="utf-8") + template = templates / "pipeline.yaml.j2" + include_path = str(tmp_path / "outside.txt") if absolute else "../outside.txt" + template.write_text(directive % repr(include_path), encoding="utf-8") + + with pytest.raises(TemplateNotFound): + render_template(template, {}) + + +def test_symlinked_shared_macros_still_render(tmp_path: Path): + shared = tmp_path / "shared" + pipeline_dir = tmp_path / "pipelines" / "daily" + shared.mkdir() + pipeline_dir.mkdir(parents=True) + (shared / "macros.j2").write_text( + "{% macro describe(team) %}Owned by {{ team | upper }}{% endmacro %}\n", + encoding="utf-8", + ) + (pipeline_dir / "macros.j2").symlink_to(Path("..") / ".." / "shared" / "macros.j2") + (pipeline_dir / "pipeline.yaml.j2").write_text( + textwrap.dedent( + """\ + {%- import 'macros.j2' as m %} + name: "{{ pipeline_name }}" + description: "{{ m.describe(team) }}" + implementation: + graph: + tasks: {} + """ + ), + encoding="utf-8", + ) + config = _write_config(pipeline_dir / "pipeline.yaml", "pipeline.yaml.j2", pipeline_name="Daily", team="ml") + + hydrated = PipelineHydrator().hydrate_file(config) + + assert hydrated.data["name"] == "Daily" + assert hydrated.data["description"] == "Owned by ML" + + +def test_shared_template_in_a_parent_directory_still_renders(tmp_path: Path, monkeypatch): + configs = tmp_path / "configs" / "prod" + configs.mkdir(parents=True) + (tmp_path / "pipeline.yaml.j2").write_text(PIPELINE_TEMPLATE, encoding="utf-8") + config = _write_config(configs / "pipeline.yaml", "../../pipeline.yaml.j2", pipeline_name="Prod") + monkeypatch.chdir(configs) + + hydrated = PipelineHydrator().hydrate_file(config) + + assert hydrated.data["name"] == "Prod" + + +def test_ordinary_template_features_render_in_the_sandbox(tmp_path: Path): + templates = tmp_path / "templates" + (templates / "sql").mkdir(parents=True) + (templates / "sql" / "query.sql").write_text("SELECT * FROM {{ table }}\n", encoding="utf-8") + (templates / "labels.yaml.j2").write_text( + "labels: {{ labels | join(',') }} {{ '%s-%d' | format(env, 3) }} {{ labels[0].replace('-', '_') }}\n", + encoding="utf-8", + ) + template = templates / "pipeline.yaml.j2" + template.write_text( + textwrap.dedent( + """\ + {%- set suffix = env | upper %} + name: "{{ pipeline_name }} {{ suffix }}" + query: {{ include_raw('sql/query.sql') | tojson }} + implementation: + graph: + tasks: + {%- for name, digest in tasks.items() | sort %} + {{ name }}: + componentRef: + digest: {{ digest }} + {%- endfor %} + {% include 'labels.yaml.j2' %} + """ + ), + encoding="utf-8", + ) + + rendered = yaml.safe_load( + render_template( + template, + { + "pipeline_name": "Daily", + "env": "prod", + "tasks": {"train": "sha-train", "eval": "sha-eval"}, + "labels": ["team-a", "nightly"], + }, + ) + ) + + assert rendered["name"] == "Daily PROD" + assert rendered["query"] == "SELECT * FROM {{ table }}\n" + assert rendered["implementation"]["graph"]["tasks"] == { + "eval": {"componentRef": {"digest": "sha-eval"}}, + "train": {"componentRef": {"digest": "sha-train"}}, + } + assert rendered["labels"] == "team-a,nightly prod-3 team_a" diff --git a/uv.lock b/uv.lock index 0a7707b..328b965 100644 --- a/uv.lock +++ b/uv.lock @@ -2083,7 +2083,7 @@ requires-dist = [{ name = "pydantic", specifier = ">=2.0" }] [[package]] name = "tangle-cli" -version = "0.1.39" +version = "0.1.40" source = { editable = "." } dependencies = [ { name = "cloud-pipelines" }, @@ -2126,7 +2126,7 @@ requires-dist = [ { name = "cyclopts", specifier = ">=4.16.1" }, { name = "docstring-parser", specifier = ">=0.16" }, { name = "httpx", specifier = ">=0.28.1" }, - { name = "jinja2", specifier = ">=3.1" }, + { name = "jinja2", specifier = ">=3.1.6" }, { name = "jsonschema", specifier = ">=4.25.0" }, { name = "platformdirs", specifier = ">=4.10.0" }, { name = "pydantic", specifier = ">=2.0" },