forked from Intrinsec/protoc-gen-sanitize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sanitizer.go
333 lines (283 loc) · 8.07 KB
/
sanitizer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright 2021 Intrinsec. All rights reserved.
package main
import (
"fmt"
"os"
"regexp"
"strings"
"text/template"
"github.com/intrinsec/protoc-gen-sanitize/sanitize"
pgs "github.com/lyft/protoc-gen-star"
pgsgo "github.com/lyft/protoc-gen-star/lang/go"
)
// SanitizeModule adds Sanitize methods on PB
type SanitizeModule struct {
*pgs.ModuleBase
ctx pgsgo.Context
tpl *template.Template
importBluemonday map[pgs.File]bool
strict bool
hasErrors bool
}
// Sanitize returns an initialized SanitizePlugin
func Sanitize() *SanitizeModule {
return &SanitizeModule{
ModuleBase: &pgs.ModuleBase{},
importBluemonday: make(map[pgs.File]bool),
hasErrors: false,
}
}
// InitContext populates the module with needed context and fields
func (p *SanitizeModule) InitContext(c pgs.BuildContext) {
c.Debug("InitContext")
p.ModuleBase.InitContext(c)
p.ctx = pgsgo.InitContext(c.Parameters())
tpl := template.New("Sanitize").Funcs(map[string]interface{}{
"package": p.ctx.PackageName,
"name": p.ctx.Name,
"sanitizer": p.sanitizer,
"initializer": p.initializer,
"leadingCommenter": p.leadingCommenter,
"doImportBluemonday": p.doImportBluemonday,
"isDisabledMessage": p.isDisabledMessage,
"checkNoSanitize": p.checkNoSanitize,
})
p.tpl = template.Must(tpl.Parse(sanitizeTpl))
}
// Name satisfies the generator.Plugin interface.
func (p *SanitizeModule) Name() string { return "Sanitize" }
// Execute generates sanitization code for files
func (p *SanitizeModule) Execute(targets map[string]pgs.File, pkgs map[string]pgs.Package) []pgs.Artifact {
p.Debug("Execute")
if ok, _ := p.Parameters().Bool("strict"); ok {
p.strict = true
}
for _, t := range targets {
if !p.doSanitize(t) {
continue
}
p.generateFile(t)
}
return p.Artifacts()
}
func (p *SanitizeModule) ExitCheck() {
if p.hasErrors && p.strict {
p.Log("Sanitization strict mode enabled. Cannot generate with missing sanitize option fields or with sanitize option defined on fields of disabled message, check above errors")
os.Exit(1)
}
}
func (p *SanitizeModule) doSanitize(f pgs.File) bool {
var disableFile bool
p.importBluemonday[f] = false
if ok, err := f.Extension(sanitize.E_DisableFile, &disableFile); ok && err == nil && disableFile {
p.Debug("Skipping: ", f.InputPath())
return false
}
for _, m := range f.AllMessages() {
var disableMessage bool
if ok, err := m.Extension(sanitize.E_DisableMessage, &disableMessage); ok && err == nil && disableMessage {
p.Debug("Skipping: ", m.Name())
continue
}
for _, field := range m.Fields() {
var kind sanitize.Sanitization
if ok, err := field.Extension(sanitize.E_Kind, &kind); ok && err == nil {
// Only case where we will use bluemonday in the generated code
p.importBluemonday[f] = true
return true
}
}
}
p.Debug("No sanitization options encountered for:", f.InputPath())
// Nonetheless we generate sanitization function to enable calling sanitization function of nested messages
return true
}
func (p *SanitizeModule) doImportBluemonday(f pgs.File) bool {
p.Debug("doImportBluemonday")
if value, ok := p.importBluemonday[f]; ok {
p.Debug(value)
return value
}
return false
}
func (p *SanitizeModule) generateFile(f pgs.File) {
if len(f.Messages()) == 0 {
return
}
p.Push(f.Name().String())
defer p.Pop()
p.Debug("File:", f.InputPath())
name := f.InputPath().BaseName() + ".pb.sanitize.go"
p.Debug("generate:", name)
p.AddGeneratorTemplateFile(name, p.tpl, f)
}
func (p *SanitizeModule) leadingCommenter(f pgs.File) string {
p.Debug("Comments:", f.SourceCodeInfo().LeadingDetachedComments())
var comments []string
re := regexp.MustCompile("(\r?\n)+")
// Add default comment
comments = append(comments, " Code generated by protoc-gen-sanitize. DO NOT EDIT.")
for _, comment := range f.SourceCodeInfo().LeadingDetachedComments() {
tmpCmt := re.Split(comment, -1)
comments = append(comments, tmpCmt[:len(tmpCmt)-1]...)
}
return "//" + strings.Join(comments, "\n//")
}
func (p *SanitizeModule) initializer(m pgs.Message) string {
html := false
text := false
var disableMessage bool
if ok, err := m.Extension(sanitize.E_DisableMessage, &disableMessage); ok && err == nil && disableMessage {
p.Debug("Skipping: ", m.Name())
return ""
}
for _, f := range m.Fields() {
var kind sanitize.Sanitization
if ok, err := f.Extension(sanitize.E_Kind, &kind); ok && err == nil {
switch kind {
case sanitize.Sanitization_NONE:
break
case sanitize.Sanitization_HTML:
html = true
break
case sanitize.Sanitization_TEXT:
text = true
break
}
}
}
out := make([]string, 0)
if html {
out = append(out, "htmlSanitize := bluemonday.UGCPolicy()")
}
if text {
out = append(out, "textSanitize := bluemonday.StrictPolicy()")
}
return strings.Join(out, "\n ")
}
func (p *SanitizeModule) buildSanitizeCall(f pgs.Field, name string, sanitizeKind string) string {
prefix := ""
suffix := ""
indent := ""
sanitizeCall := ""
iter := "i"
elementName := name
if f.Type().IsRepeated() {
indent = " "
suffix = "\n}"
elementName = strings.ToLower(string(name[0:2]))
if sanitizeKind == "" {
iter = "_"
}
prefix = fmt.Sprintf("for %s, %s := range m.%s {\n",
iter,
elementName,
name,
)
}
var format string
if sanitizeKind == "" {
// building call for message
if f.Type().IsRepeated() {
format = "%s.Sanitize()"
} else {
format = "m.%s.Sanitize()"
}
sanitizeCall = fmt.Sprintf(format, elementName)
} else {
// building call for string
if f.Type().IsRepeated() {
format = "m.%s[i] = %sSanitize.Sanitize(%s)"
} else {
format = "m.%s = %sSanitize.Sanitize(m.%s)"
}
sanitizeCall = fmt.Sprintf(format, name, strings.ToLower(sanitizeKind), elementName)
}
return fmt.Sprintf("%s%s%s%s", prefix, indent, sanitizeCall, suffix)
}
func (p *SanitizeModule) isDisabledMessage(m pgs.Message) bool {
disableMessage := false
_, _ = m.Extension(sanitize.E_DisableMessage, &disableMessage)
return disableMessage
}
func (p *SanitizeModule) checkNoSanitize(f pgs.Field) string {
var kind sanitize.Sanitization
name := p.ctx.Name(f)
ok, err := f.Extension(sanitize.E_Kind, &kind)
if err == nil && ok {
fmt.Fprintf(
os.Stderr,
"%v:%d: sanitize option defined on %v for disabled message %v\n",
f.File().Name(),
f.SourceCodeInfo().Location().Span[0]+1,
name,
f.Message().Name())
p.hasErrors = true
return fmt.Sprintf("// sanitize option defined on %v for disabled message", name)
}
return ""
}
func (p *SanitizeModule) sanitizer(f pgs.Field) string {
name := p.ctx.Name(f)
var disableField bool
if ok, err := f.Extension(sanitize.E_DisableField, &disableField); ok && err == nil && disableField {
p.Debug("Skipping disabled field:", name)
return "// sanitize is disabled on field " + name.String()
}
switch f.Type().ProtoType() {
case pgs.StringT:
var kind sanitize.Sanitization
ok, err := f.Extension(sanitize.E_Kind, &kind)
if err == nil {
if ok {
switch kind {
case sanitize.Sanitization_NONE:
return ""
case sanitize.Sanitization_HTML:
return p.buildSanitizeCall(f, string(name), "html")
case sanitize.Sanitization_TEXT:
return p.buildSanitizeCall(f, string(name), "text")
}
} else {
if f.Type().ProtoType() == pgs.StringT {
fmt.Fprintf(
os.Stderr,
"%v:%d: no sanitize option on %v\n",
f.File().Name(),
f.SourceCodeInfo().Location().Span[0]+1,
f.FullyQualifiedName())
p.hasErrors = true
}
}
}
case pgs.MessageT:
return p.buildSanitizeCall(f, string(name), "")
}
return ""
}
const sanitizeTpl = `{{ leadingCommenter . }}
package {{ package . }}
{{ if doImportBluemonday . }}
import (
"github.com/microcosm-cc/bluemonday"
)
{{ end }}
{{ range .AllMessages }}
func (m *{{ name . }}) Sanitize() {
{{ if isDisabledMessage . }}
// sanitize is disabled for this message
{{ range .Fields }}
{{ checkNoSanitize . }}
{{ end }}
{{ else }}
if m == nil {
return
}
{{ initializer . }}
{{ range .Fields }}
{{ sanitizer . }}
{{ end }}
{{ end }}
}
{{ end }}
`