Skip to content

Commit

Permalink
Merge pull request #826 from manics/callable-env
Browse files Browse the repository at this point in the history
Don't attempt to expand callable environment variables
  • Loading branch information
consideRatio authored Mar 28, 2024
2 parents f99b98f + 17625e6 commit 7268a51
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
13 changes: 12 additions & 1 deletion kubespawner/spawner.py
Original file line number Diff line number Diff line change
Expand Up @@ -1841,6 +1841,17 @@ def _expand_user_properties(self, template):
rendered = rendered.rstrip("-")
return rendered

def _expand_env(self, env):
# environment expansion requires special handling because the parent class
# may have also modified it, e.g. by evaluating a callable
expanded_env = {}
for k, v in env.items():
if isinstance(v, (list, dict, str)):
expanded_env[k] = self._expand_all(v)
# else do nothing- this will be merged with the parent env
# by the caller so by omitting the key we keep the parent value
return expanded_env

def _expand_all(self, src):
if isinstance(src, list):
return [self._expand_all(i) for i in src]
Expand Down Expand Up @@ -2166,7 +2177,7 @@ def get_env(self):
# Explicitly expand *and* set all the admin specified variables only.
# This allows JSON-like strings set by JupyterHub itself to not be
# expanded. https://github.com/jupyterhub/kubespawner/issues/743
env.update(self._expand_all(self.environment))
env.update(self._expand_env(self.environment))

return env

Expand Down
16 changes: 16 additions & 0 deletions tests/test_spawner.py
Original file line number Diff line number Diff line change
Expand Up @@ -1342,6 +1342,22 @@ async def test_pod_name_no_named_servers():
assert spawner.pod_name == "jupyter-user"


async def test_spawner_env():
c = Config()
c.Spawner.environment = {
"STATIC": "static",
"EXPANDED": "{username} (expanded)",
"ESCAPED": "{{username}}",
"CALLABLE": lambda spawner: spawner.user.name + " (callable)",
}
spawner = KubeSpawner(config=c, _mock=True)
env = spawner.get_env()
assert env["STATIC"] == "static"
assert env["EXPANDED"] == "mock-5fname (expanded)"
assert env["ESCAPED"] == "{username}"
assert env["CALLABLE"] == "mock_name (callable)"


async def test_jupyterhub_supplied_env():
cookie_options = {"samesite": "None", "secure": True}
c = Config()
Expand Down

0 comments on commit 7268a51

Please sign in to comment.