22import platform
33import re
44import typing
5- from typing import Dict
6- from jinja2 import Template
5+ import uuid
6+ from typing import Dict , List , Tuple
7+ from jinja2 import Environment , Template , meta
8+ from jinja2 .exceptions import TemplateSyntaxError
79from ..directory import runner_directory
810
911if typing .TYPE_CHECKING :
1921# $INPUT_<NAME> env vars instead.
2022_INPUT_REF_IN_TEMPLATE = re .compile (r"\$\{[{%][^}]*?(?<![.\w])(?:input|variable)(?!\w)" )
2123
24+ # One `${{ ... }}` expression, as written. Used to find the expressions in
25+ # a string before rendering so that the ones the runner does not own can
26+ # be kept exactly as they are (see `Variables.render`).
27+ _EXPRESSION = re .compile (r"\$\{\{.*?\}\}" , re .DOTALL )
28+
29+ _environment = Environment (
30+ block_start_string = "${%" ,
31+ variable_start_string = "${{" ,
32+ comment_start_string = "${#" ,
33+ )
34+
2235
2336class InputInjectionError (Exception ):
2437 """Raised when a shell command/script interpolates ${{ input.* }} /
@@ -72,6 +85,17 @@ def _env_key(key: str) -> str:
7285 },
7386}
7487
88+ # The namespaces the runner renders (`run` since 0.8.1: the step's place
89+ # in the record). `${{ ... }}` text rooted anywhere else (`steps.*`,
90+ # `inputs.*`, `jobs.*`, `secrets.*`, unknown names) is not a reference
91+ # the runner can resolve: the server resolves its own namespaces before
92+ # dispatch, and whatever still reads like one in a step input is DATA (a
93+ # log line, a fetched body, an older error message) that must reach the
94+ # action untouched.
95+ RUNNER_NAMESPACES = frozenset (
96+ {* global_variables .keys (), "input" , "variable" , "step" , "action" , "run" }
97+ )
98+
7599
76100class Variables (object ):
77101 """
@@ -92,6 +116,12 @@ class Variables(object):
92116 for use inside the action's own templates (``runs.command`` etc.).
93117 ``variable`` is a legacy alias of ``input``; both are scoped to the
94118 one step. The old job-wide accumulating namespace is gone.
119+
120+ Everything else is inert. A ``${{ ... }}`` whose root names are not all
121+ in ``RUNNER_NAMESPACES`` (or that does not parse) is left exactly as
122+ written, never raising and never rewritten: the runner does not author
123+ that text, so it must not interpret it. Only string inputs are rendered;
124+ objects and arrays pass through as they arrive.
95125 """
96126
97127 def __init__ (self ):
@@ -140,8 +170,54 @@ def merge(self, section: str, variables: dict):
140170 self .variables [section ] = {** self .variables [section ], ** variables }
141171
142172 def render (self , string : str ):
143- tp = self ._template (string )
144- return tp .render ({** global_variables , ** self .variables })
173+ """Render the runner's own namespaces in ``string``; keep every
174+ other ``${{ ... }}`` exactly as written (see the class docstring).
175+ """
176+ if string is None or "${" not in string :
177+ return string
178+ protected , kept = self ._protect_foreign_expressions (string )
179+ try :
180+ rendered = self ._template (protected ).render (
181+ {** global_variables , ** self .variables }
182+ )
183+ except TemplateSyntaxError :
184+ # Not a template the runner can read (an unclosed `${{`, a
185+ # stray `${%` in data): it is text, hand it back as it came.
186+ return string
187+ for token , text in kept :
188+ rendered = rendered .replace (token , text )
189+ return rendered
190+
191+ @classmethod
192+ def _protect_foreign_expressions (
193+ cls , string : str
194+ ) -> Tuple [str , List [Tuple [str , str ]]]:
195+ """Swap each ``${{ ... }}`` the runner does not own for an opaque
196+ token so Jinja never sees it; the caller restores them after
197+ rendering. Returns the protected string and the (token, original
198+ text) pairs."""
199+ nonce = uuid .uuid4 ().hex
200+ kept : List [Tuple [str , str ]] = []
201+
202+ def swap (match : "re.Match[str]" ) -> str :
203+ text = match .group (0 )
204+ if cls ._owns (text ):
205+ return text
206+ token = f"\x00 { nonce } :{ len (kept )} \x00 "
207+ kept .append ((token , text ))
208+ return token
209+
210+ return _EXPRESSION .sub (swap , string ), kept
211+
212+ @staticmethod
213+ def _owns (expression : str ) -> bool :
214+ """True when ``expression`` (one ``${{ ... }}``) parses and every
215+ name it reads is one of the runner's namespaces."""
216+ try :
217+ ast = _environment .parse (expression )
218+ except TemplateSyntaxError :
219+ return False
220+ return meta .find_undeclared_variables (ast ) <= RUNNER_NAMESPACES
145221
146222 def render_command (self , string : str ):
147223 """Render a shell command/script template.
@@ -177,12 +253,7 @@ def env_inputs(self) -> Dict[str, str]:
177253
178254 @staticmethod
179255 def _template (string : str ) -> Template :
180- return Template (
181- string ,
182- block_start_string = "${%" ,
183- variable_start_string = "${{" ,
184- comment_start_string = "${#" ,
185- )
256+ return _environment .from_string (string )
186257
187258 @property
188259 def inputs (self ) -> dict :
0 commit comments