From 5873bd1d7e87e0686390d71a840a44e2e2c3e11d Mon Sep 17 00:00:00 2001 From: Roland Shoemaker Date: Thu, 5 Oct 2023 06:16:18 -0700 Subject: [PATCH] html/template: track brace depth for each nested expression We need to track the brace depth for each individual nested expression, since a string interpolation expression may be nested inside of an object. e.g. `${ {1:`${}`}}` has brace depths [1, 0] when inside of the inner ${} expression. When we exit the inner expression, we need to reset to the previous brace depth (1) so that we know that the following } closes the object, but not the outer expression. Note that if you write a broken expression (i.e. `${ { }`) escaping will clearly not work as expected (or depending on your interpretation, since it is broken, it will work as expected). Since the JS parser doesn't catch syntax errors, it's up to the user to write a valid template. Updates #61619 Change-Id: I4c33723d12aff49facdcb1134d9ca82b7a0dffc4 Reviewed-on: https://go-review.googlesource.com/c/go/+/532995 Reviewed-by: Damien Neil LUCI-TryBot-Result: Go LUCI --- src/html/template/context.go | 23 +++++++++++++---------- src/html/template/escape_test.go | 14 +++++++++++++- src/html/template/transition.go | 30 +++++++++++------------------- 3 files changed, 37 insertions(+), 30 deletions(-) diff --git a/src/html/template/context.go b/src/html/template/context.go index 63d5c31b018be3..b78f0f7325ed66 100644 --- a/src/html/template/context.go +++ b/src/html/template/context.go @@ -17,16 +17,19 @@ import ( // https://www.w3.org/TR/html5/syntax.html#the-end // where the context element is null. type context struct { - state state - delim delim - urlPart urlPart - jsCtx jsCtx - jsTmplExprDepth int - jsBraceDepth int - attr attr - element element - n parse.Node // for range break/continue - err *Error + state state + delim delim + urlPart urlPart + jsCtx jsCtx + // jsBraceDepth contains the current depth, for each JS template literal + // string interpolation expression, of braces we've seen. This is used to + // determine if the next } will close a JS template literal string + // interpolation expression or not. + jsBraceDepth []int + attr attr + element element + n parse.Node // for range break/continue + err *Error } func (c context) String() string { diff --git a/src/html/template/escape_test.go b/src/html/template/escape_test.go index 91fbfb9a3cdb6c..497ead8716ffed 100644 --- a/src/html/template/escape_test.go +++ b/src/html/template/escape_test.go @@ -1797,13 +1797,25 @@ func TestEscapeText(t *testing.T) { context{state: stateJS, element: elementScript, jsCtx: jsCtxDivOp}, }, { - "