polish: env_for hardening per code review (M1-M3)

- env_for validates theme against THEMES whitelist (defense in depth)
- degraded single-path envs are no longer cached
- tests: unknown-theme rejection, real macro shadowing semantics,
  degraded branch path + no-cache

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
浅念
2026-10-22 17:45:40 +08:00
parent 67b469d56d
commit 712ccac058
2 changed files with 43 additions and 2 deletions
+6 -2
View File
@@ -23,13 +23,17 @@ def env_for(theme):
Lets a theme override shared macros (_professional_components.html) while
inheriting everything else. Cached: one env per theme across large builds.
Only built-in theme names are accepted; callers are expected to enforce the
THEMES whitelist too (render does), this is defense in depth.
"""
if theme not in THEMES:raise ValueError('未知主题')
env=_ENVS.get(theme)
if env is None:
theme_dir=ROOT/'themes'/theme
search=[str(theme_dir),str(ROOT/'themes')] if theme_dir.is_dir() else [str(ROOT/'themes')]
canonical=theme_dir.is_dir()
search=[str(theme_dir),str(ROOT/'themes')] if canonical else [str(ROOT/'themes')]
env=Environment(loader=FileSystemLoader(search),autoescape=select_autoescape(['html','xml']))
_ENVS[theme]=env
if canonical:_ENVS[theme]=env # degraded envs are not cached
return env
TITLES={'product':'产品中心','vehicle':'车型中心','post':'新闻资讯','case':'项目案例','brand':'品牌中心','service':'服务与解决方案'}