-
Notifications
You must be signed in to change notification settings - Fork 1
/
secureform.go
271 lines (229 loc) · 5.83 KB
/
secureform.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
package secureform
import (
"mime"
"mime/multipart"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
)
// Goal: Validate for
// - Type
// - Length
// - Format
// - Range
// Parser defines the security parameters for form parsing.
type Parser struct {
maxMemory int64
maxBytes int64
maxStringLen int64
}
type parserTag struct {
Name string
Min, Max string
}
func (t *parserTag) Parse(tag string) error {
if index := strings.IndexByte(tag, '?'); index >= 0 {
t.Name = tag[:index]
values, err := url.ParseQuery(tag[index+1:])
if err != nil {
return err
}
t.Min = values.Get("min")
t.Max = values.Get("max")
return nil
}
t.Name = tag
return nil
}
// NewParser allocates and returns a new Parser with the specified properties.
//
// The memory paramater is the maximum memory used before writing extra to the disk
// with multipart form data. The bytes parameter is the maximum size request body
// before sending an error back to the client. The stringLen parameter is the maximum
// size string allowed in a string form field.
func NewParser(memory, bytes, stringLen int64) *Parser {
return &Parser{
maxMemory: memory,
maxBytes: bytes,
maxStringLen: stringLen,
}
}
// Parse parses the form with the options of the parser and loads the results
// into the fields struct.
func (parser *Parser) Parse(w http.ResponseWriter, r *http.Request, fields interface{}) (err error) {
if parser.maxBytes > 0 {
r.Body = http.MaxBytesReader(w, r.Body, parser.maxBytes)
}
if parser.maxMemory <= 0 {
parser.maxMemory = 32 << 20 // 32 MB
}
if parser.maxStringLen <= 0 {
parser.maxStringLen = parser.maxMemory
}
multipart := false
contentType := r.Header.Get("Content-Type")
if contentType != "" {
contentType, _, err := mime.ParseMediaType(contentType)
if err == nil && contentType == "multipart/form-data" {
multipart = true
}
}
if multipart {
err = r.ParseMultipartForm(parser.maxMemory)
} else {
err = r.ParseForm()
}
if err != nil {
return
}
err = parser.loadForm(fields, r)
if err != nil {
return
}
return
}
func (parser *Parser) loadForm(fields interface{}, r *http.Request) error {
value := reflect.ValueOf(fields)
if value.Kind() != reflect.Ptr {
return ErrExpectedStructPtr
}
for value.Kind() == reflect.Ptr {
value = value.Elem()
}
if value.Kind() != reflect.Struct {
return ErrExpectedStructPtr
}
valueType := value.Type()
valueTypeLen := valueType.NumField()
for i := 0; i < valueTypeLen; i++ {
field := value.Field(i)
if !field.CanSet() || !field.CanAddr() || !field.CanInterface() {
continue
}
fieldInfo := valueType.Field(i)
tag := parserTag{Name: fieldInfo.Name}
if value, ok := fieldInfo.Tag.Lookup("form"); ok {
err := tag.Parse(value)
if err != nil {
return &FieldError{Name: fieldInfo.Name, Err: err}
}
}
err := parser.loadFormValueList(field, &tag, r)
if err != nil {
return &FieldError{Name: tag.Name, Err: err}
}
}
return nil
}
func (parser *Parser) loadFormValueList(field reflect.Value, tag *parserTag, r *http.Request) error {
size := 0
if isFileField(field) {
size = len(r.MultipartForm.File[tag.Name])
} else {
size = len(r.Form[tag.Name])
}
if field.Kind() == reflect.Slice {
field.Set(reflect.MakeSlice(field.Type(), size, size))
for i := 0; i < size; i++ {
err := parser.loadFormValue(field.Index(i), tag, r, i)
if err != nil {
return nil
}
}
return nil
}
if size == 0 {
field.Set(reflect.Zero(field.Type()))
return nil
}
return parser.loadFormValue(field, tag, r, 0)
}
func (parser *Parser) loadFormValue(field reflect.Value, tag *parserTag, r *http.Request, index int) error {
// Generic value validator interface.
if fieldType, ok := field.Addr().Interface().(Type); ok {
value := formValueByIndex(r.Form, tag.Name, index)
err := fieldType.Set(value)
if err != nil {
return err
}
return nil
}
// secureform.File struct
if file, ok := field.Addr().Interface().(*File); ok {
header := formFileByIndex(r.MultipartForm, tag.Name, index)
if header == nil {
return http.ErrMissingFile
}
file.FileHeader = header
return nil
}
switch field.Kind() {
case reflect.Bool:
field.SetBool(true)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
value := formValueByIndex(r.Form, tag.Name, index)
i, err := strconv.ParseInt(value, 10, field.Type().Bits())
if err != nil {
return err
}
if err := validateInt(i, tag); err != nil {
return err
}
field.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
value := formValueByIndex(r.Form, tag.Name, index)
u, err := strconv.ParseUint(value, 10, field.Type().Bits())
if err != nil {
return err
}
if err := validateUint(u, tag); err != nil {
return err
}
field.SetUint(u)
case reflect.Float32, reflect.Float64:
value := formValueByIndex(r.Form, tag.Name, index)
f, err := strconv.ParseFloat(value, field.Type().Bits())
if err != nil {
return err
}
if err := validateFloat(f, tag); err != nil {
return err
}
field.SetFloat(f)
case reflect.String:
// Validate string
value := formValueByIndex(r.Form, tag.Name, index)
if err := validateString(value, tag, parser.maxStringLen); err != nil {
return err
}
field.SetString(value)
default:
return ErrInvalidKind
}
return nil
}
func isFileField(field reflect.Value) bool {
if _, ok := field.Addr().Interface().(*File); ok {
return true
}
if _, ok := field.Addr().Interface().(*[]File); ok {
return true
}
return false
}
func formValueByIndex(form url.Values, name string, index int) string {
field := form[name]
if index < len(field) {
return field[index]
}
return ""
}
func formFileByIndex(form *multipart.Form, name string, index int) *multipart.FileHeader {
field := form.File[name]
if index < len(field) {
return field[index]
}
return nil
}