Extend Jinja Environment to allow Haystack data classes in ConditionalRouter #8691
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Related Issues
Proposed Changes:
Currently, to use Haystack data classes as an output type in
ConditionalRouter
, users must setunsafe=True
. This limitation arises becauseSandboxedEnvironment
does not support the safe evaluation of Python objects, and extendingast.literal_eval
to handle custom data classes is neither practical nor secure.As a solution, this PR introduces
NativeSandboxedEnvironment
, a custom Jinja2 environment that tries to combine the sandboxing capabilities ofSandboxedEnvironment
with the native type rendering ofNativeEnvironment
. I tried to whitelist Haystack data classes in theis_safe_attribute
method, allowing them to be safely rendered as native Python objects. Everything else should pass through default sandbox security rules.❌ However, currently everything is being rendered as a
NativeTemplate
which possibly causes a security vulnerability.Highlights:
Subclass both SandboxedEnvironment and NativeEnvironment → NativeSandboxedEnvironment.
Override
from_string
andtemplate_class
so the environment uses a “native” template but still enforces the sandbox.Use
is_safe_attribute
to whitelist Haystack data classes.How did you test it?
Ran the tests
Notes for the reviewer
As I am still evaluating the vulnerabilities of the above approach, an alternative solution could be to check the
output_type
. If it corresponds to a Haystack data class, theNativeSandboxedEnvironment
could be used specifically for rendering Haystack data classes, while theSandboxedEnvironment
is retained for all other cases to enhance overall safety.Checklist
fix:
,feat:
,build:
,chore:
,ci:
,docs:
,style:
,refactor:
,perf:
,test:
and added!
in case the PR includes breaking changes.