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