Escaping Meta Tag Content? Help

This sounds awesome, unfortunately hugo --minify panics for me :frowning: https://github.com/gohugoio/hugo/issues/5261

@rdegges Please read Requesting Help and create a new post in #support. Your issue should be discussed separately, and before opening a ticket in the issue queue. Please include the information mentioned in Requesting Help so other may assist you.

Reviving for the sake of documenting a solution.

In order to disable escaping of HTML entities in a tag, use safeHTMLAttr, as previously suggested. However, the catch is that safeHTMLAttr should be used to mark the complete attribute (name + value), not just the value.

Original:

No escaping:

<meta name="description" {{ .Page.Description | printf "content=%q" | safeHTMLAttr }}>

Bear in mind that whenever you use the safe* functions (safeHTML, safeHTMLAttr, etc), it means you fully trust the input.

A malicious input could infect your website. Given a content file like this:

---
description: "Untrusted page's description. \"><script>alert('hello')</script>"
---

And a template:

<meta name="description" content="{{ .Description }}">
<meta name="description" {{ .Description | printf "content=%q" | safeHTMLAttr }}>

The output is:

<meta name="description" content="Untrusted page&#39;s description. &#34;&gt;&lt;script&gt;alert(&#39;hello&#39;)&lt;/script&gt;">
<meta name="description" content="Untrusted page's description. \"><script>alert('hello')</script>">

Notice that the original form escapes the script tag, and the form with safeHTMLAttr does not, thus outputting JavaScript that is executed on page load.

3 Likes

How would you get something like this to work for the <title>? This use case differs from the description because the description has the content= property.

For example:

{{ $title := print .Title " " .Site.Params.Site.titleSuffix }}
<title>{{ $title }}</title>

The above produces:

<title>Hello world&#39;s blog post &amp;mdash; Test suffix</title>

The expected output would be:

<title>Hello world's blog post — Test suffix</title>

I tried a whole bunch of combinations of using safeHTML and safeHTMLAttr unsuccessfully.