Commit e8f11fa735

e8f11fa7351d1371cc0f0c290df2c35a6178ecb6

parent: f64de6f693

Verified · cmc ci/build: success ci/quality: success ci/test: success ci/vuln: success

cmc <hello@cleberg.net> · 2026-11-09 22:32 UTC

Check unquoted-attribute hits against the template

opengrep's html-templates unquoted-attribute-var rule matches in generic
mode, where a quote inside {{ }} ends the attribute and an action that
only adds an attribute name counts as a value. Read the template at the
scanned commit and keep a hit only where an output expression is an
unquoted attribute value or stands in for attributes; the rest are set
aside as quoted and counted in the issue, status and settings page.

Layout: unified · split

.gitbay/wiki/Admin.org +6 −1
@@ -494,7 +494,12 @@ outside =node_modules=, =vendor= and =third_party=. The =yaml/semgrep=
494lints count only in a repository with a =.semgrep= config. Paths 494lints count only in a repository with a =.semgrep= config. Paths
495=.gitattributes= marks =linguist-vendored= or =linguist-generated= are 495=.gitattributes= marks =linguist-vendored= or =linguist-generated= are
496set aside, as are the repository's =security-ignore= paths and 496set aside, as are the repository's =security-ignore= paths and
497=security-exclude-rule= rules. The issue says how many were set aside 497=security-exclude-rule= rules. A hit of
498=html-templates/security/unquoted-attribute-var=, which matches in
499generic mode and takes a quote inside ={{ }}= for the end of the
500attribute, is checked against the template at the scanned commit: it
501counts only where an expression there is an unquoted attribute value
502or stands in for attributes. The issue says how many were set aside
498and why. A finding a writer dismisses (=repo security dismiss=, by the 503and why. A finding a writer dismisses (=repo security dismiss=, by the
499fingerprint the issue prints) stays out of the issue across scans until 504fingerprint the issue prints) stays out of the issue across scans until
500it is reopened; the issue closes when nothing is left open. 505it is reopened; the issue closes when nothing is left open.
internal/codescan/attrs.go added +169
@@ -0,0 +1,169 @@
1package codescan
2
3import "strings"
4
5// unquotedAttrRule flags a template expression inside a tag unless it sees
6// the expression within ="…" or ='…'. It matches in generic mode, where a
7// quoted string ends at the next quote, so href="{{ f("a") }}" is reported,
8// and so is an action that only adds an attribute name
9// ({{if .X}} selected{{end}}). unquotedLines reads the template as HTML to
10// tell those apart from the real thing.
11const unquotedAttrRule = "html-templates.security.unquoted-attribute-var"
12
13// rawText are elements whose content is not markup.
14var rawText = map[string]bool{"script": true, "style": true, "textarea": true, "title": true}
15
16// Tag states.
17const (
18 inText = iota
19 beforeAttr
20 attrName
21 afterName
22 beforeValue
23 unquotedValue
24 quotedValue
25)
26
27// unquotedLines returns the lines of an HTML template where an output
28// expression is an unquoted attribute value or stands in for attributes.
29// ok is false when the file does not read as HTML to the end, and then
30// nothing is known.
31func unquotedLines(src []byte) (lines map[int]bool, ok bool) {
32 s := string(src)
33 lines = map[int]bool{}
34 line := 1
35 state := inText
36 var quote byte
37 var tag string
38 advance := func(to int, from int) int {
39 line += strings.Count(s[from:to], "\n")
40 return to
41 }
42 for i := 0; i < len(s); {
43 if end, output, found := expression(s, i); found {
44 if end < 0 {
45 return nil, false
46 }
47 if output && state != inText && state != quotedValue {
48 lines[line] = true
49 if state == beforeValue {
50 state = unquotedValue
51 } else if state != unquotedValue {
52 state = attrName
53 }
54 }
55 i = advance(end, i)
56 continue
57 }
58 c, prev := s[i], state
59 switch state {
60 case inText:
61 switch {
62 case strings.HasPrefix(s[i:], "<!--"):
63 end := strings.Index(s[i+4:], "-->")
64 if end < 0 {
65 return nil, false
66 }
67 i = advance(i+4+end+3, i)
68 continue
69 case c == '<' && i+1 < len(s) && isLetter(s[i+1]):
70 j := i + 1
71 for j < len(s) && (isLetter(s[j]) || s[j] >= '0' && s[j] <= '9' || s[j] == '-' || s[j] == ':') {
72 j++
73 }
74 tag = strings.ToLower(s[i+1 : j])
75 state = beforeAttr
76 i = j
77 continue
78 }
79 case quotedValue:
80 if c == quote {
81 state = beforeAttr
82 }
83 case beforeValue:
84 switch {
85 case c == '"' || c == '\'':
86 quote, state = c, quotedValue
87 case c == '>':
88 state = inText
89 case !isSpace(c):
90 state = unquotedValue
91 }
92 case unquotedValue:
93 if isSpace(c) {
94 state = beforeAttr
95 } else if c == '>' {
96 state = inText
97 }
98 default: // beforeAttr, attrName, afterName
99 switch {
100 case c == '=':
101 state = beforeValue
102 case c == '>':
103 state = inText
104 case isSpace(c):
105 if state == attrName {
106 state = afterName
107 }
108 case c != '/':
109 state = attrName
110 }
111 }
112 i = advance(i+1, i)
113 if prev != inText && state == inText && rawText[tag] && s[i-2] != '/' {
114 end := strings.Index(strings.ToLower(s[i:]), "</"+tag)
115 if end < 0 {
116 return nil, false
117 }
118 i = advance(i+end, i)
119 }
120 }
121 return lines, state == inText
122}
123
124// expression reports whether a template expression opens at i: {{ }},
125// {{{ }}}, {% %} or {# #}. end is just past its close, or -1 when it is
126// not closed. output is whether it writes a value, rather than being a
127// control action or a comment.
128func expression(s string, i int) (end int, output, found bool) {
129 open, close := "", ""
130 switch {
131 case strings.HasPrefix(s[i:], "{{{"):
132 open, close = "{{{", "}}}"
133 case strings.HasPrefix(s[i:], "{{"):
134 open, close = "{{", "}}"
135 case strings.HasPrefix(s[i:], "{%"):
136 open, close = "{%", "%}"
137 case strings.HasPrefix(s[i:], "{#"):
138 open, close = "{#", "#}"
139 default:
140 return 0, false, false
141 }
142 n := strings.Index(s[i+len(open):], close)
143 if n < 0 {
144 return -1, false, true
145 }
146 if open[1] != '{' {
147 return i + len(open) + n + len(close), false, true
148 }
149 body := strings.TrimLeft(s[i+len(open):i+len(open)+n], "-~ \t\r\n")
150 return i + len(open) + n + len(close), !control(body), true
151}
152
153// control reports whether the body of a {{ }} is a Go template action or a
154// Handlebars block, comment or else, which write nothing themselves.
155func control(body string) bool {
156 if body == "" || strings.ContainsRune("#/^!", rune(body[0])) {
157 return true
158 }
159 word, _, _ := strings.Cut(strings.TrimSpace(body), " ")
160 switch word {
161 case "if", "else", "end", "range", "with", "block", "define", "break", "continue":
162 return true
163 }
164 return false
165}
166
167func isLetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' }
168
169func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' }
internal/codescan/attrs_test.go added +87
@@ -0,0 +1,87 @@
1package codescan
2
3import (
4 "errors"
5 "testing"
6
7 "gitbay.org/gitbay/internal/store"
8)
9
10func TestUnquotedLines(t *testing.T) {
11 for _, tc := range []struct {
12 name, src string
13 want bool
14 }{
15 {"quotes inside a quoted value", `<a href="/{{ page.url | replace("index.html", "") }}">x</a>`, false},
16 {"quoted literal in a quoted value", `<meta property="og:image" content="{{ "og.png" | absolute }}">`, false},
17 {"single quotes", `<a href='{{ x }}'>`, false},
18 {"action adding a name", `<option value="off"{{if eq $mode "off"}} selected{{end}}>Off</option>`, false},
19 {"handlebars block", `<input {{#if on}}checked{{/if}}>`, false},
20 {"comment", `<p {{/* note */}} class="a">`, false},
21 {"jinja statement", `<option {% if x %}selected{% endif %}>`, false},
22 {"expression in text", `<p>{{ title }}</p>`, false},
23 {"script body", "<script>if (a<b) { x = {{ y }} }</script>", false},
24 {"html comment", `<!-- <a href={{ x }}> -->`, false},
25 {"unquoted value", `<a href={{ x }}>`, true},
26 {"unquoted after text", `<a href=/p/{{ x }}>`, true},
27 {"standing in for attributes", `<div {{ attrs }}>`, true},
28 {"output inside an action", `<option {{if .A}}value={{.V}}{{end}}>`, true},
29 {"triple stash", `<a href={{{ x }}}>`, true},
30 } {
31 lines, ok := unquotedLines([]byte(tc.src))
32 if !ok {
33 t.Errorf("%s: not read", tc.name)
34 continue
35 }
36 if lines[1] != tc.want {
37 t.Errorf("%s: unquoted = %v, want %v", tc.name, lines[1], tc.want)
38 }
39 }
40}
41
42func TestUnquotedLinesAcrossLines(t *testing.T) {
43 src := "<ul>\n<li\n class=\"a\"\n data-x={{ x }}\n title=\"{{ \"t\" }}\">\n</ul>\n"
44 lines, ok := unquotedLines([]byte(src))
45 if !ok || !lines[4] || lines[5] || len(lines) != 1 {
46 t.Errorf("lines = %v ok %v", lines, ok)
47 }
48 for _, src := range []string{`<a href="{{ x }}`, `<a href={{ x`, `<!-- open`} {
49 if _, ok := unquotedLines([]byte(src)); ok {
50 t.Errorf("%q read", src)
51 }
52 }
53}
54
55func TestScopeChecksUnquotedAttributes(t *testing.T) {
56 rule := "opt.opengrep-rules.generic.html-templates.security.unquoted-attribute-var"
57 files := map[string]string{
58 "quoted.html": "<p>\n<a href=\"{{ f(\"a\") }}\">x</a>\n",
59 "unquoted.html": "<a href={{ x }}>\n",
60 "broken.html": "<a href=\"{{ x }}",
61 }
62 read := func(p string) ([]byte, error) {
63 if src, ok := files[p]; ok {
64 return []byte(src), nil
65 }
66 return nil, errors.New("missing")
67 }
68 findings := []store.SecurityFinding{
69 {Rule: rule, Path: "quoted.html", Line: 2},
70 {Rule: rule, Path: "unquoted.html", Line: 1},
71 {Rule: rule, Path: "broken.html", Line: 1},
72 {Rule: rule, Path: "gone.html", Line: 1},
73 {Rule: "other", Path: "quoted.html", Line: 2},
74 }
75 kept, aside, _ := Scope{Read: read}.Apply(findings)
76 if aside.Quoted != 1 || len(kept) != 4 {
77 t.Fatalf("kept %+v aside %+v", kept, aside)
78 }
79 for _, f := range kept {
80 if f.Path == "quoted.html" && f.Rule == rule {
81 t.Errorf("quoted hit kept")
82 }
83 }
84 if kept, aside, _ := (Scope{}).Apply(findings); aside.Quoted != 0 || len(kept) != 5 {
85 t.Errorf("without Read: kept %d aside %+v", len(kept), aside)
86 }
87}
internal/codescan/codescan.go +3
@@ -317,6 +317,9 @@ func Body(r Report) string {
317 if len(r.Aside.Unused) > 0 { 317 if len(r.Aside.Unused) > 0 {
318 notListed = append(notListed, fmt.Sprintf("%d from rules for libraries it does not use (%s)", total(r.Aside.Unused), counts(r.Aside.Unused))) 318 notListed = append(notListed, fmt.Sprintf("%d from rules for libraries it does not use (%s)", total(r.Aside.Unused), counts(r.Aside.Unused)))
319 } 319 }
320 if r.Aside.Quoted > 0 {
321 notListed = append(notListed, fmt.Sprintf("%d unquoted-attribute hits on attributes the template quotes", r.Aside.Quoted))
322 }
320 if len(notListed) > 0 { 323 if len(notListed) > 0 {
321 fmt.Fprintf(&b, "\nNot listed: %s. `repo security status %s` shows them.\n", strings.Join(notListed, "; "), r.Repo) 324 fmt.Fprintf(&b, "\nNot listed: %s. `repo security status %s` shows them.\n", strings.Join(notListed, "; "), r.Repo)
322 } 325 }
internal/codescan/scope.go +35 −1
@@ -21,13 +21,23 @@ type Scope struct {
21 // Uses reports whether the scanned commit depends on any of packages, 21 // Uses reports whether the scanned commit depends on any of packages,
22 // written as library lists them. Nil uses everything. 22 // written as library lists them. Nil uses everything.
23 Uses func(packages []string) bool 23 Uses func(packages []string) bool
24 // Read returns a file at the scanned commit, for rules whose hits are
25 // checked against the source. Nil checks nothing.
26 Read func(path string) ([]byte, error)
24} 27}
25 28
26// Aside counts the findings a scope set aside: Ignored by path or rule, 29// Aside counts the findings a scope set aside: Ignored by path or rule,
27// Unused by the library a rule is about. 30// Unused by the library a rule is about, Quoted by reading the template an
31// unquoted-attribute hit is in.
28type Aside struct { 32type Aside struct {
29 Ignored int `json:"ignored,omitempty"` 33 Ignored int `json:"ignored,omitempty"`
30 Unused map[string]int `json:"unused,omitempty"` 34 Unused map[string]int `json:"unused,omitempty"`
35 Quoted int `json:"quoted,omitempty"`
36}
37
38// Any reports whether anything was set aside.
39func (a Aside) Any() bool {
40 return a.Ignored > 0 || len(a.Unused) > 0 || a.Quoted > 0
31} 41}
32 42
33// Apply splits findings into those reported, at most MaxFindings of them, 43// Apply splits findings into those reported, at most MaxFindings of them,
@@ -37,6 +47,7 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
37 var kept []store.SecurityFinding 47 var kept []store.SecurityFinding
38 var aside Aside 48 var aside Aside
39 truncated := false 49 truncated := false
50 unquoted := map[string]map[int]bool{}
40 for _, f := range findings { 51 for _, f := range findings {
41 if s.ignored(f) { 52 if s.ignored(f) {
42 aside.Ignored++ 53 aside.Ignored++
@@ -49,6 +60,10 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
49 aside.Unused[l.name()]++ 60 aside.Unused[l.name()]++
50 continue 61 continue
51 } 62 }
63 if ruleIn(f.Rule, unquotedAttrRule) && !s.unquoted(f, unquoted) {
64 aside.Quoted++
65 continue
66 }
52 if len(kept) == MaxFindings { 67 if len(kept) == MaxFindings {
53 truncated = true 68 truncated = true
54 continue 69 continue
@@ -58,6 +73,25 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
58 return kept, aside, truncated 73 return kept, aside, truncated
59} 74}
60 75
76// unquoted reports whether an unquoted-attribute hit is on a line where the
77// template has an unquoted attribute expression, or the file cannot be
78// read to say. Files are read once, into seen.
79func (s Scope) unquoted(f store.SecurityFinding, seen map[string]map[int]bool) bool {
80 if s.Read == nil || f.Path == "" || f.Line == 0 {
81 return true
82 }
83 lines, read := seen[f.Path]
84 if !read {
85 if src, err := s.Read(f.Path); err == nil {
86 if l, ok := unquotedLines(src); ok {
87 lines = l
88 }
89 }
90 seen[f.Path] = lines
91 }
92 return lines == nil || lines[f.Line]
93}
94
61func (s Scope) ignored(f store.SecurityFinding) bool { 95func (s Scope) ignored(f store.SecurityFinding) bool {
62 for _, g := range s.Ignore { 96 for _, g := range s.Ignore {
63 if ci.Match(g, f.Path) { 97 if ci.Match(g, f.Path) {
internal/control/security.go +7 −2
@@ -341,7 +341,7 @@ func runRunnerResults(c *Ctx, args []string) int {
341 return c.fail(protocol.ExitFailure, "%v", err) 341 return c.fail(protocol.ExitFailure, "%v", err)
342 } 342 }
343 asideJSON := "" 343 asideJSON := ""
344 if aside.Ignored > 0 || len(aside.Unused) > 0 { 344 if aside.Any() {
345 j, _ := json.Marshal(aside) 345 j, _ := json.Marshal(aside)
346 asideJSON = string(j) 346 asideJSON = string(j)
347 } 347 }
@@ -400,12 +400,14 @@ const maxManifestDirs = 50
400// settings, what .gitattributes marks vendored or generated, and findings 400// settings, what .gitattributes marks vendored or generated, and findings
401// from rules about libraries no manifest at that commit names. Manifests are 401// from rules about libraries no manifest at that commit names. Manifests are
402// read in every directory that has one, outside dependency directories, so 402// read in every directory that has one, outside dependency directories, so
403// a monorepo's web/package.json counts. 403// a monorepo's web/package.json counts. Files at sha are read for rules
404// whose hits are checked against the source.
404func scanScope(dir string, repo store.Repo, sha string) codescan.Scope { 405func scanScope(dir string, repo store.Repo, sha string) codescan.Scope {
405 sc := codescan.Scope{Ignore: repo.Settings.SecurityIgnore, ExcludeRules: repo.Settings.SecurityExcludeRules} 406 sc := codescan.Scope{Ignore: repo.Settings.SecurityIgnore, ExcludeRules: repo.Settings.SecurityExcludeRules}
406 if raw, err := gitutil.ReadBlob(dir, sha, ".gitattributes", manifestLimit); err == nil { 407 if raw, err := gitutil.ReadBlob(dir, sha, ".gitattributes", manifestLimit); err == nil {
407 sc.Vendored = codescan.Vendored(raw) 408 sc.Vendored = codescan.Vendored(raw)
408 } 409 }
410 sc.Read = func(p string) ([]byte, error) { return gitutil.ReadBlob(dir, sha, p, manifestLimit) }
409 root := map[string]bool{} 411 root := map[string]bool{}
410 if entries, err := gitutil.ListTree(dir, sha, ""); err == nil { 412 if entries, err := gitutil.ListTree(dir, sha, ""); err == nil {
411 for _, e := range entries { 413 for _, e := range entries {
@@ -486,6 +488,9 @@ func asideText(a codescan.Aside) string {
486 for _, l := range libs { 488 for _, l := range libs {
487 parts = append(parts, fmt.Sprintf("%d %s (not used)", a.Unused[l], l)) 489 parts = append(parts, fmt.Sprintf("%d %s (not used)", a.Unused[l], l))
488 } 490 }
491 if a.Quoted > 0 {
492 parts = append(parts, fmt.Sprintf("%d quoted attributes", a.Quoted))
493 }
489 return strings.Join(parts, ", ") 494 return strings.Join(parts, ", ")
490} 495}
491 496
internal/web/templates/settings.html +1 −1
@@ -188,7 +188,7 @@
188</form>{{end}} 188</form>{{end}}
189{{if .Security.Enabled}} 189{{if .Security.Enabled}}
190<p class="meta">Next scan {{.Security.NextRun}} · last results {{if .Security.LastResults}}{{when .Security.LastResults}}{{else}}never{{end}}{{if .Security.IssueNumber}} · <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Security.IssueNumber}}">#{{.Security.IssueNumber}}</a>{{end}}</p> 190<p class="meta">Next scan {{.Security.NextRun}} · last results {{if .Security.LastResults}}{{when .Security.LastResults}}{{else}}never{{end}}{{if .Security.IssueNumber}} · <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Security.IssueNumber}}">#{{.Security.IssueNumber}}</a>{{end}}</p>
191{{with .Security.Aside}}{{if or .Ignored .Unused}}<p class="meta">Set aside by the last scan:{{if .Ignored}} {{.Ignored}} under the paths or rules below, or marked vendored or generated in <code>.gitattributes</code>.{{end}}{{range $lib, $n := .Unused}} {{$n}} from {{$lib}} rules, which no manifest names.{{end}}</p>{{end}}{{end}} 191{{with .Security.Aside}}{{if .Any}}<p class="meta">Set aside by the last scan:{{if .Ignored}} {{.Ignored}} under the paths or rules below, or marked vendored or generated in <code>.gitattributes</code>.{{end}}{{range $lib, $n := .Unused}} {{$n}} from {{$lib}} rules, which no manifest names.{{end}}{{if .Quoted}} {{.Quoted}} unquoted-attribute hits on attributes the template quotes.{{end}}</p>{{end}}{{end}}
192{{if .Security.Findings}}<div class="tablewrap"><table class="keys"> 192{{if .Security.Findings}}<div class="tablewrap"><table class="keys">
193<tr class="cols"><th scope="col">location</th><th scope="col">rule</th><th scope="col">level</th><th scope="col"><span class="vh">dismiss</span></th></tr> 193<tr class="cols"><th scope="col">location</th><th scope="col">rule</th><th scope="col">level</th><th scope="col"><span class="vh">dismiss</span></th></tr>
194{{range .Security.Findings}}<tr> 194{{range .Security.Findings}}<tr>