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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/tangle-cli/src/tangle_cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@
try:
__version__ = metadata_version("tangle-cli")
except PackageNotFoundError:
__version__ = "0.1.39"
__version__ = "0.1.40"

__all__ = ["TangleDynamicDiscoveryClient", "__version__"]
25 changes: 21 additions & 4 deletions packages/tangle-cli/src/tangle_cli/pipeline_hydrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand All @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -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 = [
Expand All @@ -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",
Expand Down
3 changes: 2 additions & 1 deletion tests/test_packaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions tests/test_pipeline_decompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down
193 changes: 193 additions & 0 deletions tests/test_template_hydration_trust.py
Original file line number Diff line number Diff line change
@@ -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"
4 changes: 2 additions & 2 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading