Debian Codegraph @

parser/metadecoders/decoder.go

raw
1 // Copyright 2025 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package metadecoders
15
16 import (
17 "bytes"
18 "encoding/csv"
19 "encoding/json"
20 "fmt"
21 "log"
22 "regexp"
23 "strconv"
24 "strings"
25 "unsafe"
26
27 "github.com/gohugoio/hugo/common/herrors"
28 "github.com/gohugoio/hugo/common/hmaps"
29 "github.com/gohugoio/hugo/common/hugio"
30 "github.com/niklasfasching/go-org/org"
31
32 xml "github.com/clbanning/mxj/v2"
33 yaml "github.com/goccy/go-yaml"
34 toml "github.com/pelletier/go-toml/v2"
35 "github.com/spf13/afero"
36 "github.com/spf13/cast"
37 )
38
39 // Decoder provides some configuration options for the decoders.
40 type Decoder struct {
41 // Format specifies a specific format to decode from. If empty or
42 // unspecified, it's inferred from the contents or the filename.
43 Format string
44
45 // Delimiter is the field delimiter. Used in the CSV decoder. Default is
46 // ','.
47 Delimiter rune
48
49 // Comment, if not 0, is the comment character. Lines beginning with the
50 // Comment character without preceding whitespace are ignored. Used in the
51 // CSV decoder.
52 Comment rune
53
54 // If true, a quote may appear in an unquoted field and a non-doubled quote
55 // may appear in a quoted field. Used in the CSV decoder. Default is false.
56 LazyQuotes bool
57
58 // The target data type, either slice or map. Used in the CSV decoder.
59 // Default is slice.
60 TargetType string
61 }
62
63 // OptionsKey is used in cache keys.
64 func (d Decoder) OptionsKey() string {
65 var sb strings.Builder
66 sb.WriteString(d.Format)
67 sb.WriteRune(d.Delimiter)
68 sb.WriteRune(d.Comment)
69 sb.WriteString(strconv.FormatBool(d.LazyQuotes))
70 sb.WriteString(d.TargetType)
71 return sb.String()
72 }
73
74 // Default is a Decoder in its default configuration.
75 var Default = Decoder{
76 Delimiter: ',',
77 TargetType: "slice",
78 }
79
80 // UnmarshalToMap will unmarshall data in format f into a new map. This is
81 // what's needed for Hugo's front matter decoding.
82 func (d Decoder) UnmarshalToMap(data []byte, f Format) (map[string]any, error) {
83 m := make(map[string]any)
84 if data == nil {
85 return m, nil
86 }
87
88 err := d.UnmarshalTo(data, f, &m)
89
90 if m == nil {
91 // We migrated to github.com/goccy/go-yaml in v0.152.0,
92 // which produces nil maps for empty YAML files (and empty map nodes), unlike gopkg.in/yaml.v2.
93 //
94 // To prevent crashes when trying to handle empty config files etc., we ensure we always return a non-nil map here.
95 // See issue 14074.
96 m = make(map[string]any)
97 }
98
99 return m, err
100 }
101
102 // UnmarshalFileToMap is the same as UnmarshalToMap, but reads the data from
103 // the given filename.
104 func (d Decoder) UnmarshalFileToMap(fs afero.Fs, filename string) (map[string]any, error) {
105 format := FormatFromString(filename)
106 if format == "" {
107 return nil, fmt.Errorf("%q is not a valid configuration format", filename)
108 }
109
110 data, err := hugio.ReadFile(fs, filename)
111 if err != nil {
112 return nil, err
113 }
114 return d.UnmarshalToMap(data, format)
115 }
116
117 // UnmarshalStringTo tries to unmarshal data to a new instance of type typ.
118 func (d Decoder) UnmarshalStringTo(data string, typ any) (any, error) {
119 data = strings.TrimSpace(data)
120 // We only check for the possible types in YAML, JSON and TOML.
121 switch typ.(type) {
122 case string:
123 return data, nil
124 case map[string]any, hmaps.Params:
125 format := d.FormatFromContentString(data)
126 return d.UnmarshalToMap([]byte(data), format)
127 case []any:
128 // A standalone slice. Let YAML handle it.
129 return d.Unmarshal([]byte(data), YAML)
130 case bool:
131 return cast.ToBoolE(data)
132 case int:
133 return cast.ToIntE(data)
134 case int64:
135 return cast.ToInt64E(data)
136 case float64:
137 return cast.ToFloat64E(data)
138 default:
139 return nil, fmt.Errorf("unmarshal: %T not supported", typ)
140 }
141 }
142
143 // Unmarshal will unmarshall data in format f into an interface{}.
144 // This is what's needed for Hugo's /data handling.
145 func (d Decoder) Unmarshal(data []byte, f Format) (any, error) {
146 if len(data) == 0 {
147 switch f {
148 case CSV:
149 switch d.TargetType {
150 case "map":
151 return make(map[string]any), nil
152 case "slice":
153 return make([][]string, 0), nil
154 default:
155 return nil, fmt.Errorf("invalid targetType: expected either slice or map, received %s", d.TargetType)
156 }
157 default:
158 return make(map[string]any), nil
159 }
160 }
161 var v any
162 err := d.UnmarshalTo(data, f, &v)
163
164 return v, err
165 }
166
167 // UnmarshalYaml unmarshals data in YAML format into v.
168 func UnmarshalYaml(data []byte, v any) error {
169 if err := yaml.Unmarshal(data, v); err != nil {
170 return err
171 }
172 if err := validateAliasLimitForCollections(v, calculateCollectionAliasLimit(len(data))); err != nil {
173 return err
174 }
175
176 return nil
177 }
178
179 // The Billion Laughs YAML example is about 500 bytes in size,
180 // but even halving that when converted to JSON would produce a file of about 4 MB in size,
181 // which, when repeated enough times, could be disruptive.
182 // For large data files where every row shares a common map via aliases,
183 // a large number of aliases could make sense.
184 // The primary goal here is to catch the small but malicious files.
185 func calculateCollectionAliasLimit(sizeInBytes int) int {
186 sizeInKB := sizeInBytes / 1024
187 if sizeInKB == 0 {
188 sizeInKB = 1
189 }
190 if sizeInKB < 2 {
191 // This should allow at most "thousand laughs",
192 // which should be plenty of room for legitimate uses.
193 return 100
194 }
195
196 // The numbers below are somewhat arbitrary, but should provide
197 // a reasonable trade-off between safety and usability.
198 if sizeInKB < 10 {
199 return 5000
200 }
201 return 10000
202 }
203
204 // Used in benchmarks.
205 func unmarshalYamlNoValidation(data []byte, v any) error {
206 if err := yaml.Unmarshal(data, v); err != nil {
207 return err
208 }
209 return nil
210 }
211
212 // See https://github.com/goccy/go-yaml/issues/461
213 // While it's true that yaml.Unmarshal isn't vulnerable to the Billion Laughs attack,
214 // we can easily get a delayed laughter when we try to render this very big structure later,
215 // e.g. via RenderString.
216 func validateAliasLimitForCollections(v any, limit int) error {
217 if limit <= 0 {
218 limit = 1000
219 }
220
221 collectionRefCounts := make(map[uintptr]int)
222
223 checkCollectionRef := func(v *any) error {
224 // Conversion of a Pointer to a uintptr (but not back to Pointer) is considered safe.
225 // See https://pkg.go.dev/unsafe#pkg-functions
226 ptr := uintptr(unsafe.Pointer(v))
227 if ptr == 0 {
228 return nil
229 }
230 collectionRefCounts[ptr]++
231 if collectionRefCounts[ptr] > limit {
232 return fmt.Errorf("too many YAML aliases for non-scalar nodes")
233 }
234 return nil
235 }
236
237 var validate func(v any) error
238 validate = func(v any) error {
239 switch vv := v.(type) {
240 case *map[string]any:
241 if err := checkCollectionRef(&v); err != nil {
242 return err
243 }
244 for _, vvv := range *vv {
245 if err := validate(vvv); err != nil {
246 return err
247 }
248 }
249 case map[string]any:
250 if err := checkCollectionRef(&v); err != nil {
251 return err
252 }
253 for _, vvv := range vv {
254 if err := validate(vvv); err != nil {
255 return err
256 }
257 }
258 case []any:
259 if err := checkCollectionRef(&v); err != nil {
260 return err
261 }
262 for _, vvv := range vv {
263 if err := validate(vvv); err != nil {
264 return err
265 }
266 }
267 case *any:
268 return validate(*vv)
269 default:
270 // ok
271 }
272 return nil
273 }
274
275 return validate(v)
276 }
277
278 // UnmarshalTo unmarshals data in format f into v.
279 func (d Decoder) UnmarshalTo(data []byte, f Format, v any) error {
280 var err error
281
282 switch f {
283 case ORG:
284 err = d.unmarshalORG(data, v)
285 case JSON:
286 err = json.Unmarshal(data, v)
287 case XML:
288 var xmlRoot xml.Map
289 xmlRoot, err = xml.NewMapXml(data)
290
291 var xmlValue map[string]any
292 if err == nil {
293 xmlRootName, err := xmlRoot.Root()
294 if err != nil {
295 return toFileError(f, data, fmt.Errorf("failed to unmarshal XML: %w", err))
296 }
297
298 // Get the root value and verify it's a map
299 rootValue := xmlRoot[xmlRootName]
300 if rootValue == nil {
301 return toFileError(f, data, fmt.Errorf("XML root element '%s' has no value", xmlRootName))
302 }
303
304 // Type check before conversion
305 mapValue, ok := rootValue.(map[string]any)
306 if !ok {
307 return toFileError(f, data, fmt.Errorf("XML root element '%s' must be a map/object, got %T", xmlRootName, rootValue))
308 }
309 xmlValue = mapValue
310 }
311
312 switch v := v.(type) {
313 case *map[string]any:
314 *v = xmlValue
315 case *any:
316 *v = xmlValue
317 }
318 case TOML:
319 err = toml.Unmarshal(data, v)
320 case YAML:
321 return UnmarshalYaml(data, v)
322 case CSV:
323 return d.unmarshalCSV(data, v)
324
325 default:
326 return fmt.Errorf("unmarshal of format %q is not supported", f)
327 }
328
329 if err == nil {
330 return nil
331 }
332
333 return toFileError(f, data, fmt.Errorf("unmarshal failed: %w", err))
334 }
335
336 func (d Decoder) unmarshalCSV(data []byte, v any) error {
337 r := csv.NewReader(bytes.NewReader(data))
338 r.Comma = d.Delimiter
339 r.Comment = d.Comment
340 r.LazyQuotes = d.LazyQuotes
341
342 records, err := r.ReadAll()
343 if err != nil {
344 return err
345 }
346
347 switch vv := v.(type) {
348 case *any:
349 switch d.TargetType {
350 case "map":
351 if len(records) < 2 {
352 return fmt.Errorf("cannot unmarshal CSV into %T: expected at least a header row and one data row", v)
353 }
354
355 seen := make(map[string]bool, len(records[0]))
356 for _, fieldName := range records[0] {
357 if seen[fieldName] {
358 return fmt.Errorf("cannot unmarshal CSV into %T: header row contains duplicate field names", v)
359 }
360 seen[fieldName] = true
361 }
362
363 sm := make([]map[string]string, len(records)-1)
364 for i, record := range records[1:] {
365 m := make(map[string]string, len(records[0]))
366 for j, col := range record {
367 m[records[0][j]] = col
368 }
369 sm[i] = m
370 }
371 *vv = sm
372 case "slice":
373 *vv = records
374 default:
375 return fmt.Errorf("cannot unmarshal CSV into %T: invalid targetType: expected either slice or map, received %s", v, d.TargetType)
376 }
377 default:
378 return fmt.Errorf("cannot unmarshal CSV into %T", v)
379 }
380
381 return nil
382 }
383
384 func parseORGDate(s string) string {
385 r := regexp.MustCompile(`[<\[](\d{4}-\d{2}-\d{2}) .*[>\]]`)
386 if m := r.FindStringSubmatch(s); m != nil {
387 return m[1]
388 }
389 return s
390 }
391
392 func (d Decoder) unmarshalORG(data []byte, v any) error {
393 config := org.New()
394 config.Log = log.Default() // TODO(bep)
395 document := config.Parse(bytes.NewReader(data), "")
396 if document.Error != nil {
397 return document.Error
398 }
399 frontMatter := make(map[string]any, len(document.BufferSettings))
400 for k, v := range document.BufferSettings {
401 k = strings.ToLower(k)
402 if strings.HasSuffix(k, "[]") {
403 frontMatter[k[:len(k)-2]] = strings.Fields(v)
404 } else if strings.Contains(v, "\n") {
405 frontMatter[k] = strings.Split(v, "\n")
406 } else if k == "filetags" {
407 trimmed := strings.TrimPrefix(v, ":")
408 trimmed = strings.TrimSuffix(trimmed, ":")
409 frontMatter[k] = strings.Split(trimmed, ":")
410 } else if k == "date" || k == "lastmod" || k == "publishdate" || k == "expirydate" {
411 frontMatter[k] = parseORGDate(v)
412 } else {
413 frontMatter[k] = v
414 }
415 }
416 switch vv := v.(type) {
417 case *map[string]any:
418 *vv = frontMatter
419 case *any:
420 *vv = frontMatter
421 }
422 return nil
423 }
424
425 func toFileError(f Format, data []byte, err error) error {
426 return herrors.NewFileErrorFromName(err, fmt.Sprintf("_stream.%s", f)).UpdateContent(bytes.NewReader(data), nil)
427 }