diff options
author | wxiaoguang <wxiaoguang@gmail.com> | 2025-01-08 11:44:32 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2025-01-08 03:44:32 +0000 |
commit | 386c1ed908dd7291a19fa0185d325f7810ca0b57 (patch) | |
tree | c2b4095c230e2dbeccfbc57815f68e31129afa9c /modules/templates | |
parent | 67aeb1f8961194a6f84ce1cca0cbb55d100a8cd2 (diff) | |
download | gitea-386c1ed908dd7291a19fa0185d325f7810ca0b57.tar.gz gitea-386c1ed908dd7291a19fa0185d325f7810ca0b57.zip |
Refactor HTMLFormat, update chroma render, fix js error (#33136)
A small refactor to improve HTMLFormat, to help to prevent low-level
mistakes.
And fix #33141, fix #33139
Diffstat (limited to 'modules/templates')
-rw-r--r-- | modules/templates/helper.go | 16 | ||||
-rw-r--r-- | modules/templates/helper_test.go | 3 |
2 files changed, 16 insertions, 3 deletions
diff --git a/modules/templates/helper.go b/modules/templates/helper.go index 48d3a8ff89..609407d36b 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -38,7 +38,7 @@ func NewFuncMap() template.FuncMap { "Iif": iif, "Eval": evalTokens, "SafeHTML": safeHTML, - "HTMLFormat": htmlutil.HTMLFormat, + "HTMLFormat": htmlFormat, "HTMLEscape": htmlEscape, "QueryEscape": queryEscape, "QueryBuild": QueryBuild, @@ -207,6 +207,20 @@ func htmlEscape(s any) template.HTML { panic(fmt.Sprintf("unexpected type %T", s)) } +func htmlFormat(s any, args ...any) template.HTML { + if len(args) == 0 { + // to prevent developers from calling "HTMLFormat $userInput" by mistake which will lead to XSS + panic("missing arguments for HTMLFormat") + } + switch v := s.(type) { + case string: + return htmlutil.HTMLFormat(template.HTML(v), args...) + case template.HTML: + return htmlutil.HTMLFormat(v, args...) + } + panic(fmt.Sprintf("unexpected type %T", s)) +} + func jsEscapeSafe(s string) template.HTML { return template.HTML(template.JSEscapeString(s)) } diff --git a/modules/templates/helper_test.go b/modules/templates/helper_test.go index e35e8a28f8..5d7bc93622 100644 --- a/modules/templates/helper_test.go +++ b/modules/templates/helper_test.go @@ -8,7 +8,6 @@ import ( "strings" "testing" - "code.gitea.io/gitea/modules/htmlutil" "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" @@ -88,7 +87,7 @@ func TestTemplateIif(t *testing.T) { func TestTemplateEscape(t *testing.T) { execTmpl := func(code string) string { tmpl := template.New("test") - tmpl.Funcs(template.FuncMap{"QueryBuild": QueryBuild, "HTMLFormat": htmlutil.HTMLFormat}) + tmpl.Funcs(template.FuncMap{"QueryBuild": QueryBuild, "HTMLFormat": htmlFormat}) template.Must(tmpl.Parse(code)) w := &strings.Builder{} assert.NoError(t, tmpl.Execute(w, nil)) |