Repository navigation
Expand file tree
/
Copy pathparser.go
More file actions
1419 lines (1171 loc) · 40.8 KB
/
Copy pathparser.go
File metadata and controls
1419 lines (1171 loc) · 40.8 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package publiccode
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"slices"
"strings"
"time"
"unicode/utf8"
"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
en_translations "github.com/go-playground/validator/v10/translations/en"
yaml "github.com/goccy/go-yaml"
"github.com/goccy/go-yaml/ast"
"github.com/goccy/go-yaml/lexer"
"github.com/goccy/go-yaml/parser"
"github.com/goccy/go-yaml/token"
urlutil "github.com/publiccodeyml/libpubliccode/v5/internal"
"github.com/publiccodeyml/libpubliccode/v5/internal/httpclient"
publiccodeValidator "github.com/publiccodeyml/libpubliccode/v5/validators"
)
// Build Validator and Translator once at package init.
var (
sharedValidate *validator.Validate
sharedTrans ut.Translator
)
func init() {
sharedValidate = publiccodeValidator.New()
enLocale := en.New()
uni := ut.New(enLocale, enLocale)
sharedTrans, _ = uni.GetTranslator("en")
_ = en_translations.RegisterDefaultTranslations(sharedValidate, sharedTrans)
_ = publiccodeValidator.RegisterLocalErrorMessages(sharedValidate, sharedTrans)
}
var errHTTPStatus = errors.New("unexpected HTTP status")
var reMapKey = regexp.MustCompile(`\[([[:alpha:]]+)\]`)
// reMapKeyTag matches every map key in brackets, including language tags
// with a region such as en-GB, which reMapKey leaves in brackets.
var reMapKeyTag = regexp.MustCompile(`\[([[:alpha:]][[:alnum:]-]*)\]`)
// ParserConfig configures parsing and validation of publiccode.yml files.
type ParserConfig struct {
// DisableNetwork disables all network tests (eg. URL existence). This
// results in much faster parsing.
DisableNetwork bool
// DisableExternalChecks disables ALL the additional checks on external files
// and resources, local or remote (eg. existence, images actually being images, etc.).
//
// It implies DisableNetwork = true.
DisableExternalChecks bool
// Domain will have domain specific settings, including basic auth if provided
// this will avoid strong quota limit imposed by code hosting platform
Domain Domain
// Branch is the branch of the repository in the url key that relative
// files (eg. logo) are read from. It only applies to ParseStream with
// network checks on and no BaseURL, when the parser takes the base of
// relative files from url. If empty, the parser asks the code hosting
// platform for the default branch.
Branch string
// The URL used as base of relative files in publiccode.yml (eg. logo)
// It can also be a local directory path.
BaseURL string
// Timeout is the maximum duration for each HTTP request during external checks.
// Defaults to 30s if zero.
Timeout time.Duration
// UserAgent is sent in the User-Agent header of every request made during
// the external checks. It defaults to [UserAgent], which names this library
// and its version.
//
// Programs embedding the parser are encouraged to identify themselves here,
// so that the administrators of the sites being checked can tell their
// traffic apart and allow it.
UserAgent string
// AllowNetworkToPrivateHosts allows the external checks to connect to
// non-public addresses (loopback, private, link-local, ...).
//
// It is false by default so that URLs coming from an untrusted
// publiccode.yml cannot be abused to perform SSRF against internal services
// or cloud metadata endpoints. Enable it only when the input is trusted
// (or in tests targeting a local server). A proxy set in HTTP_PROXY or
// HTTPS_PROXY can have a private address. The parser still checks the
// addresses of each target host, but the proxy resolves the host again, so
// it needs its own filtering when its DNS answers can differ.
AllowNetworkToPrivateHosts bool
}
const defaultHTTPTimeout = 30 * time.Second
// Parser is a helper class for parsing publiccode.yml files.
type Parser struct {
disableNetwork bool
disableExternalChecks bool
domain Domain
branch string
baseURL *url.URL
client *http.Client
httpclient *httpclient.Client
// urlChecks keeps the outcome of each isReachable call by URL. It is nil
// on the Parser callers share and set on the copy that validates the
// fields of one document. See withURLChecks.
urlChecks map[string]error
}
// Domain is a single code hosting service.
type Domain struct {
// Domains.yml data
Host string `yaml:"host"`
// UseTokenFor lists the hosts that get one of BasicAuth in an
// Authorization header. Only https URLs of these hosts get it.
UseTokenFor []string `yaml:"use-token-for"`
BasicAuth []string `yaml:"basic-auth"`
}
// NewParser initializes and returns a new Parser object following the settings in
// ParserConfig.
func NewParser(config ParserConfig) (*Parser, error) {
if config.DisableExternalChecks {
config.DisableNetwork = true
}
timeout := config.Timeout
if timeout == 0 {
timeout = defaultHTTPTimeout
}
// Hardened HTTP client: refuses connections to non-public addresses (SSRF)
// and caps the size of each response (resource exhaustion). It also sets the
// User-Agent, which covers both the requests built here and the ones built
// by the internal httpclient and by go-vcsurl, since they all go through
// this client. See internal/safehttp.go.
httpClient := urlutil.SafeHTTPClient(
timeout,
config.AllowNetworkToPrivateHosts,
urlutil.WithUserAgent(config.UserAgent),
)
p := Parser{
disableNetwork: config.DisableNetwork,
disableExternalChecks: config.DisableExternalChecks,
domain: config.Domain,
branch: config.Branch,
client: httpClient,
httpclient: httpclient.New(httpClient),
}
if config.BaseURL != "" {
var err error
if p.baseURL, err = toURL(config.BaseURL); err != nil {
return nil, err
}
}
return &p, nil
}
// NewDefaultParser initializes and returns a new Parser object with default settings.
func NewDefaultParser() (*Parser, error) {
return NewParser(ParserConfig{})
}
// ParseStream reads and validates a publiccode.yml file from in.
// It returns a non-nil [ValidationResults] error when validation produces errors
// or warnings, including when there are only warnings. Call
// [ValidationResults.HasErrors] to tell whether the file is valid, or inspect
// each result for [ValidationError] or [ValidationWarning] to distinguish them.
//
// The returned [PublicCode] may be nil if parsing fails before decoding.
// A non-nil PublicCode does not imply that validation succeeded.
func (p *Parser) ParseStream(in io.Reader) (PublicCode, error) {
return p.ParseStreamWithContext(context.Background(), in)
}
// ParseStreamWithContext is [Parser.ParseStream] with a context. The external
// checks stop when ctx is cancelled or reaches its deadline, including the
// waits between retries when a host rate limits the requests.
//
// When ctx ends before the parser returns, the results can hold checks that
// were cut short, so it returns a nil [PublicCode] and an error wrapping
// ctx.Err() instead of [ValidationResults].
func (p *Parser) ParseStreamWithContext(ctx context.Context, in io.Reader) (PublicCode, error) {
return p.parseStream(ctx, in, nil, "")
}
// Parse reads and validates a publiccode.yml file from a local path or an HTTP(S) URL.
// Local paths may be absolute or relative to the current working directory.
// Remote files are fetched with GET. A response status outside 2xx returns an error.
// The URL must serve the raw file contents. Repository page URLs, such as GitHub
// blob URLs, are not converted to raw file URLs.
//
// Use [Parser.ParseStream] to parse data from an io.Reader.
//
// Like ParseStream, Parse returns a non-nil [ValidationResults] error for
// warnings as well as validation errors. Call [ValidationResults.HasErrors], or
// inspect each result for [ValidationError] or [ValidationWarning], before deciding
// whether to accept the returned [PublicCode].
// A non-nil PublicCode does not imply that validation succeeded. Errors opening
// or fetching the file return a nil PublicCode and an error outside ValidationResults.
func (p *Parser) Parse(uri string) (PublicCode, error) {
return p.ParseWithContext(context.Background(), uri)
}
// ParseWithContext is [Parser.Parse] with a context. The context stops the
// fetch of a remote file and the external checks, including the waits
// between retries when a host rate limits the requests.
//
// When ctx ends before the parser returns, it returns a nil [PublicCode] and
// an error wrapping ctx.Err(), as [Parser.ParseStreamWithContext] does.
func (p *Parser) ParseWithContext(ctx context.Context, uri string) (PublicCode, error) {
var stream io.ReadCloser
fileURL, err := toURL(uri)
if err != nil {
return nil, fmt.Errorf("invalid URL '%s': %w", uri, err)
}
if fileURL.Scheme == "file" {
stream, err = os.Open(fileURL.Path)
if err != nil {
return nil, fmt.Errorf("can't open file '%s': %w", fileURL.Path, err)
}
} else {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return nil, fmt.Errorf("can't build GET request for '%s': %w", uri, err)
}
resp, err := p.client.Do(req)
if err != nil {
return nil, fmt.Errorf("can't GET '%s': %w", uri, err)
}
// A server answering 404 or 500 can send a body that is valid YAML,
// and decoding it would validate a document that was never fetched.
if resp.StatusCode < 200 || resp.StatusCode > 299 {
_ = resp.Body.Close()
return nil, fmt.Errorf("can't GET '%s': %w %s", uri, errHTTPStatus, resp.Status)
}
stream = resp.Body
}
defer stream.Close()
return p.parseStream(ctx, stream, fileURL, diagnosticFileName(uri, fileURL))
}
func (p *Parser) parseStream(ctx context.Context, in io.Reader, fileURL *url.URL, fileName string) (PublicCode, error) {
publiccode, err := p.parseAndValidate(ctx, in, fileURL)
// A check stopped by ctx reports a reachability error that says nothing
// about the file, so none of the results can be trusted.
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, fmt.Errorf("validation stopped: %w", ctxErr)
}
if results, ok := errors.AsType[ValidationResults](err); ok {
setFileName(results, fileName)
}
return publiccode, err
}
// diagnosticFileName returns the name to report in the diagnostics for uri,
// which toURL resolved to fileURL. A local path is kept as passed, so that an
// editor following the errorformat output opens the validated file from the
// same working directory. A URL keeps only its last path segment, because the
// errorformat prefix ends at the first colon and a whole URL there would send
// an editor nowhere.
func diagnosticFileName(uri string, fileURL *url.URL) string {
if fileURL.Scheme == "file" {
return uri
}
name := path.Base(fileURL.Path)
// Base() answers "." for an empty path and "/" for the root, neither of
// which is a file name.
if name == "." || name == "/" {
return ""
}
return name
}
// setFileName records name on every diagnostic in results. Both diagnostic
// types are values, so each one has to be written back into the slice.
func setFileName(results ValidationResults, name string) {
if name == "" {
return
}
for i, result := range results {
var valErr ValidationError
var valWarn ValidationWarning
switch {
case errors.As(result, &valErr):
valErr.File = name
results[i] = valErr
case errors.As(result, &valWarn):
valWarn.File = name
results[i] = valWarn
}
}
}
func (p *Parser) parseAndValidate( //nolint:maintidx
ctx context.Context, in io.Reader, fileURL *url.URL,
) (PublicCode, error) {
b, err := io.ReadAll(in)
if err != nil {
return nil, ValidationResults{newValidationErrorf("", "Can't read the stream: %v", err)}
}
if !utf8.Valid(b) {
return nil, ValidationResults{newValidationError("", "Invalid UTF-8")}
}
// YAML 1.2 allows a leading byte order mark, but the AST parser
// rejects it as content.
b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf"))
// Parse the YAML into an AST so we can look up line/column positions and
// detect structural issues (multi-document, empty file, syntax errors).
tokens := lexer.Tokenize(string(b))
// The parser takes memory quadratic in the nesting depth, so check the
// depth on the tokens before parsing them. Parse reports invalid tokens
// before it builds anything.
if tokens.InvalidToken() == nil {
if tk := findNestingOverflow(tokens); tk != nil {
return nil, ValidationResults{ValidationError{
Key: "",
Description: fmt.Sprintf("YAML collections nest deeper than %d levels", maxNestingDepth),
Line: tk.Position.Line,
Column: tk.Position.Column,
}}
}
// The parser also takes time quadratic in the keys of a mapping.
if tk := findMappingOverflow(tokens); tk != nil {
return nil, ValidationResults{ValidationError{
Key: "",
Description: fmt.Sprintf("YAML mapping has more than %d keys", maxMappingKeys),
Line: tk.Position.Line,
Column: tk.Position.Column,
}}
}
}
file, err := parser.Parse(tokens, 0)
if err != nil {
// Point users who supplied an HTML page to the raw file URL
// instead of reporting a YAML syntax error.
if htmlErr := htmlPageError(b); htmlErr != nil {
return nil, ValidationResults{htmlErr}
}
if se, ok := errors.AsType[*yaml.SyntaxError](err); ok {
line, column := 0, 0
if tok := se.GetToken(); tok != nil && tok.Position != nil {
line, column = tok.Position.Line, tok.Position.Column
}
description := se.GetMessage()
if d := overIndentedDescription(description, se.GetToken()); d != "" {
description = d
}
return nil, ValidationResults{ValidationError{
Key: "",
Description: description,
Line: line,
Column: column,
}}
}
return nil, ValidationResults{newValidationError("", err.Error())}
}
if len(file.Docs) == 0 || file.Docs[0].Body == nil {
return nil, ValidationResults{newValidationError("publiccodeYmlVersion", "publiccodeYmlVersion is a required field")}
}
if len(file.Docs) > 1 {
return nil, ValidationResults{newValidationError("", "multiple YAML documents in one file are not supported")}
}
if err := notMappingError(file.Docs[0].Body, b); err != nil {
return nil, ValidationResults{err}
}
// Decoding copies the value at each alias, so check how much the
// aliases add before decoding anything.
if alias := findAliasOverflow(file.Docs[0].Body); alias != nil {
tok := alias.GetToken()
return nil, ValidationResults{ValidationError{
Key: findKeyAtLine(file.Docs[0].Body, tok.Position.Line, ""),
Description: alias.description,
Line: tok.Position.Line,
Column: tok.Position.Column,
}}
}
// Extract publiccodeYmlVersion from the AST.
versionPath, err := yaml.PathString("$.publiccodeYmlVersion")
if err != nil {
return nil, ValidationResults{newValidationError("", err.Error())}
}
versionNode, err := versionPath.FilterFile(file)
if err != nil || versionNode == nil {
return nil, ValidationResults{newValidationError("publiccodeYmlVersion", "publiccodeYmlVersion is a required field")}
}
strNode, ok := versionNode.(*ast.StringNode)
if !ok {
line, column := getPositionInFile("publiccodeYmlVersion", file)
return nil, ValidationResults{ValidationError{
Key: "publiccodeYmlVersion",
Description: mustBeString,
Line: line,
Column: column,
}}
}
version := strNode.Value
if !slices.Contains(SupportedVersions, version) {
line, column := getPositionInFile("publiccodeYmlVersion", file)
return nil, ValidationResults{ValidationError{
Key: "publiccodeYmlVersion",
Description: fmt.Sprintf(
"unsupported version: '%s'. Supported versions: %s",
version,
strings.Join(SupportedVersions, ", "),
),
Line: line,
Column: column,
}}
}
var ve ValidationResults
latestVersion := SupportedVersions[len(SupportedVersions)-1]
if version != "0" && version != latestVersion && !strings.HasPrefix(version, latestVersion+".") {
line, column := getPositionInFile("publiccodeYmlVersion", file)
ve = append(ve, ValidationWarning{
Key: "publiccodeYmlVersion",
Description: fmt.Sprintf(
"v%s is not the latest version, use '0'. Parsing this file as v%s.",
version,
latestVersion,
),
Line: line,
Column: column,
})
}
var publiccode PublicCode
var validateFields validateFn
var (
decodeResults ValidationResults
wrongTypes []string
)
if version[0] == '0' {
v0 := &PublicCodeV0{}
validateFields = validateFieldsV0
decodeResults, wrongTypes = decode(b, v0, file)
if isBasedOnIsString(file) {
line, column := getPositionInFile("isBasedOn", file)
ve = append(ve, ValidationWarning{
Key: "isBasedOn",
Description: "The single string form is DEPRECATED and will be removed in v1. " +
"Use a one element array instead",
Line: line,
Column: column,
})
}
publiccode = v0
} else {
v1 := &PublicCodeV1{}
validateFields = validateFieldsV1
decodeResults, wrongTypes = decode(b, v1, file)
publiccode = v1
}
if decodeResults != nil {
sortByPosition(decodeResults)
ve = append(ve, decodeResults...)
}
err = sharedValidate.Struct(publiccode)
if err != nil {
if validationErrs, ok := errors.AsType[validator.ValidationErrors](err); ok {
structResults := make(ValidationResults, 0, len(validationErrs))
for _, err := range validationErrs {
key := strings.SplitN(err.Namespace(), ".", 2)[1]
key = reMapKey.ReplaceAllString(key, ".$1")
// The wrong type error already names this value, or the rule
// compared against the placeholder that replaced it.
if isUnder(key, wrongTypes) || dependsOnWrongType(err, key, publiccode, wrongTypes) {
continue
}
line, column := getPositionInFile(key, file)
structResults = append(structResults, ValidationError{
Key: key,
Description: err.Translate(sharedTrans),
Line: line,
Column: column,
})
}
sortByPosition(structResults)
ve = append(ve, structResults...)
}
}
// Compute the base URL for this call without mutating p (goroutine-safety).
var currentBaseURL *url.URL
// baseURL was not set by the user (with ParserConfig{BaseURL: "..."})),
// We need a base URL to perform external checks on relative files (eg. logo).
if p.baseURL == nil {
// If we parsed from an actual local or remote file, use its dir
if fileURL != nil {
u := *fileURL
currentBaseURL = &u
currentBaseURL.Path = path.Dir(fileURL.Path)
}
} else {
u := *p.baseURL
currentBaseURL = &u
}
// Still no base URL: we parsed from a stream, try to use the publiccode.yml's `url` field.
// go-vcsurl only knows some forges, so the raw root may stay unknown. Only
// relative paths need it: they stay unchecked, with a warning, and every
// other key is still validated.
rawRootUnknown := false
if currentBaseURL == nil && !p.disableNetwork && publiccode.Url() != nil {
rawRoot, err := p.getRawRoot(ctx, (*url.URL)(publiccode.Url()))
if err != nil {
rawRootUnknown = true
} else {
currentBaseURL = rawRoot
}
}
// Still no base URL: DisableNetwork is true, use the current working directory as a fallback
if currentBaseURL == nil && !rawRootUnknown {
cwd, err := os.Getwd()
if err != nil {
ve = append(ve, newValidationErrorf("", "no baseURL set and failed to get working directory: %s", err))
return asPublicCode(publiccode), ve
}
currentBaseURL = &url.URL{Scheme: "file", Path: cwd}
}
if err = validateFields(ctx, publiccode, p, ve, !p.disableNetwork, currentBaseURL); err != nil {
if vr, ok := errors.AsType[ValidationResults](err); ok {
fieldResults := make(ValidationResults, 0, len(vr))
for _, result := range vr {
var valErr ValidationError
var valWarn ValidationWarning
switch {
case errors.As(result, &valErr):
// Recovery replaced the wrong value, so this check saw a placeholder.
if isUnder(valErr.Key, wrongTypes) {
continue
}
valErr.Line, valErr.Column = getPositionInFile(valErr.Key, file)
fieldResults = append(fieldResults, valErr)
case errors.As(result, &valWarn):
valWarn.Line, valWarn.Column = getPositionInFile(valWarn.Key, file)
fieldResults = append(fieldResults, valWarn)
}
}
sortByPosition(fieldResults)
ve = append(ve, fieldResults...)
}
}
// v0: Copy data from deprecated fields to the canonical ones, where possible
if v0, ok := publiccode.(*PublicCodeV0); ok {
// Auto-copy the deprecated field into the new one, so we can guarantee
// to the user that `IT` is always the field to check
if v0.It != nil && v0.IT == nil {
v0.IT = v0.It
}
it := v0.IT
// Auto-copy the deprecated field into the new one, so we can guarantee
// to the user that `organisation` is always the field to check
if it != nil && it.Riuso.CodiceIPA != "" && v0.Organisation == nil {
v0.Organisation = &OrganisationV0{}
v0.Organisation.URI = "urn:x-italian-pa:" + it.Riuso.CodiceIPA
v0.Organisation.Name = v0.Legal.RepoOwner
}
}
if len(ve) == 0 {
return asPublicCode(publiccode), nil
}
return asPublicCode(publiccode), ve
}
// Ensure the returned value implements PublicCode as a struct, not as a pointer.
func asPublicCode(pc PublicCode) PublicCode {
switch v := pc.(type) {
case *PublicCodeV0:
return *v
default:
return v
}
}
// getPositionInFile returns the line and column of the key in the YAML AST.
// Uses dot notation (e.g. "organisation.name") with optional array
// indices (e.g. "localisation.availableLanguages[0]").
func getPositionInFile(key string, file *ast.File) (int, int) {
if len(file.Docs) == 0 || file.Docs[0].Body == nil {
return 0, 0
}
parts := splitKeyParts(key)
if len(parts) == 0 {
return 0, 0
}
line, col := findKeyPos(file.Docs[0].Body, parts)
return line, col
}
// isBasedOnIsString reports whether the top level isBasedOn is a single
// string. It has to look at the AST because UrlOrUrlArray folds both forms
// into a slice, losing which one was used.
func isBasedOnIsString(file *ast.File) bool {
if len(file.Docs) == 0 {
return false
}
root, ok := file.Docs[0].Body.(*ast.MappingNode)
if !ok {
return false
}
for _, mv := range root.Values {
if tok := mv.Key.GetToken(); tok != nil && tok.Value == "isBasedOn" {
value := mv.Value
if tag, ok := value.(*ast.TagNode); ok {
value = tag.Value
}
_, isString := value.(*ast.StringNode)
return isString
}
}
return false
}
// splitKeyParts splits a dot-separated key path into parts, preserving array
// indices. Eg. "a.b[0].c" -> ["a", "b[0]", "c"].
func splitKeyParts(key string) []string {
return strings.Split(key, ".")
}
// findKeyPos traverses the AST and returns the position of the key node
// identified by parts. Returns 0,0 if not found.
func findKeyPos(node ast.Node, parts []string) (int, int) {
if node == nil || len(parts) == 0 {
return 0, 0
}
part := parts[0]
arrayIdx := -1
stringKey := ""
basePart := part
// Parse array index "foo[0]" or string map key "foo[en-US]".
if idx := strings.LastIndex(part, "["); idx >= 0 && strings.HasSuffix(part, "]") {
idxStr := part[idx+1 : len(part)-1]
n := 0
valid := len(idxStr) > 0
for _, c := range idxStr {
if c < '0' || c > '9' {
valid = false
break
}
n = n*10 + int(c-'0')
}
if valid {
arrayIdx = n
basePart = part[:idx]
} else if len(idxStr) > 0 {
stringKey = idxStr
basePart = part[:idx]
}
}
switch n := node.(type) {
case *ast.MappingNode:
for _, mv := range n.Values {
tok := mv.Key.GetToken()
if tok == nil {
continue
}
keyVal := tok.Value
if keyVal != basePart {
continue
}
if arrayIdx >= 0 {
// Navigate into the sequence at this index.
seq, ok := mv.Value.(*ast.SequenceNode)
if !ok || arrayIdx >= len(seq.Values) {
// Value is not a sequence or index out of bounds:
// fall back to the key's own position.
if tok := mv.Key.GetToken(); tok != nil {
return tok.Position.Line, tok.Position.Column
}
return 0, 0
}
elem := seq.Values[arrayIdx]
if len(parts) == 1 {
tok := elem.GetToken()
if mapping, ok := elem.(*ast.MappingNode); ok && !mapping.IsFlowStyle && len(mapping.Values) > 0 {
tok = mapping.Values[0].Key.GetToken()
}
if tok != nil {
return tok.Position.Line, tok.Position.Column
}
return 0, 0
}
//nolint:gosec // parts is nonempty at entry, and the single part case returns above.
return findKeyPos(elem, parts[1:])
}
if stringKey != "" {
// Non-numeric bracket key (eg. "description[en-US]"): navigate
// into the value treating the bracket content as the next key.
//nolint:gosec // parts is nonempty at entry.
return findKeyPos(mv.Value, append([]string{stringKey}, parts[1:]...))
}
if len(parts) == 1 {
tok := mv.Key.GetToken()
return tok.Position.Line, tok.Position.Column
}
//nolint:gosec // parts is nonempty at entry, and the single part case returns above.
return findKeyPos(mv.Value, parts[1:])
}
// Key not found.
// For flow mappings ({...}) return the '{' token (e.g. "legal: {}" when
// "legal.license" is missing).
if n.IsFlowStyle {
if tok := n.GetToken(); tok != nil {
return tok.Position.Line, tok.Position.Column
}
}
// For block mappings, only fall back to the first child key when this is
// the final key segment. Mid path misses (e.g. "legal" not found while
// looking for "legal.license") return 0,0 because we have no useful anchor.
if len(parts) == 1 && len(n.Values) > 0 {
if tok := n.Values[0].Key.GetToken(); tok != nil {
return tok.Position.Line, tok.Position.Column
}
}
case *ast.DocumentNode:
return findKeyPos(n.Body, parts)
case *ast.AnchorNode:
return findKeyPos(n.Value, parts)
default:
// Node is a scalar or unexpected type
// Return the node's own token so the position points to the
// mistyped value.
if tok := node.GetToken(); tok != nil {
return tok.Position.Line, tok.Position.Column
}
}
return 0, 0
}
// findKeyAtLine traverses the AST and returns the dot-separated YAML
// key path for the node whose key token is at the given line.
func findKeyAtLine(node ast.Node, targetLine int, prefix string) string {
if node == nil {
return ""
}
switch n := node.(type) {
case *ast.MappingNode:
for _, mv := range n.Values {
if result := findKeyAtLine(mv, targetLine, prefix); result != "" {
return result
}
}
case *ast.MappingValueNode:
keyTok := n.Key.GetToken()
if keyTok == nil {
return ""
}
var fullKey string
if prefix == "" {
fullKey = keyTok.Value
} else {
fullKey = prefix + "." + keyTok.Value
}
if keyTok.Position == nil || keyTok.Position.Line == targetLine {
return fullKey
}
if result := findKeyAtLine(n.Value, targetLine, fullKey); result != "" {
return result
}
case *ast.SequenceNode:
for i, entry := range n.Values {
seqKey := fmt.Sprintf("%s[%d]", prefix, i)
if tok := entry.GetToken(); tok != nil && tok.Position != nil && tok.Position.Line == targetLine {
return seqKey
}
if result := findKeyAtLine(entry, targetLine, seqKey); result != "" {
return result
}
}
case *ast.DocumentNode:
return findKeyAtLine(n.Body, targetLine, prefix)
case *ast.AnchorNode:
return findKeyAtLine(n.Value, targetLine, prefix)
}
return ""
}
// decode decodes the parsed file into publiccode and returns any decode errors
// (type mismatches, unknown fields, syntax errors) as ValidationResults.
//
// The decoder stops at its first error and leaves the enclosing mapping or
// list unset, so every later value would be lost and struct validation would
// report present keys as missing. After each error the offending value is
// dropped from a private copy of the AST and decoding starts again.
//
// The second return value holds the keys whose values had the wrong type.
func decode[T any](data []byte, publiccode *T, file *ast.File) (ValidationResults, []string) {
var (
ve ValidationResults
wrongTypes []string
)
// Positions in the copy match the ones in file, which is left untouched
// for later lookups.
work, err := parser.ParseBytes(data, 0)
if err != nil || len(work.Docs) == 0 {
return ValidationResults{newValidationError("", "YAML decoding failed")}, nil
}
unknownKeys := findUnknownKeys(work.Docs[0].Body, reflect.TypeFor[T]())
for _, key := range unknownKeys {
if key.entry != nil {
quoteKey(key)
}
ve = append(ve, ValidationError{
Key: key.path, Description: fmt.Sprintf("unknown field %q", key.name),
Line: key.token.Position.Line, Column: key.token.Position.Column,
})
}
// The decoder can point at an anchor's value when an alias has the
// wrong type. Check those uses before recovery can erase the anchor.
aliasErrors, aliasWrongTypes := dropWrongTypeAliases(
work.Docs[0].Body, reflect.TypeFor[T](), file, decodeRetryBytes/max(len(data), 1),
)
ve = append(ve, aliasErrors...)
wrongTypes = append(wrongTypes, aliasWrongTypes...)
mergeErrors := keysBeforeMergeErrors(work.Docs[0].Body)
var last T
for retry := false; ; retry = true {
var zero T
*publiccode = zero
err := decodeNode(work.Docs[0].Body, publiccode)
if err == nil {
return append(ve, mergeErrors...), wrongTypes
}
var (
unknownErr *yaml.UnknownFieldError
yamlErr yaml.Error
dropped bool
)
switch {
case errors.As(err, &unknownErr):
var key string
key, dropped = dropNode(work.Docs[0], unknownErr.Token, true)
if len(unknownKeys) == 0 {
ve = append(ve, decodeError(file, key, unknownErr.Token, unknownErr.Message))
}
case errors.As(err, &yamlErr):
var key string
description := wrongTypeGeneric
if !sharedValue(work.Docs[0], yamlErr.GetToken(), false) {
description = wrongTypeDescription(yamlErr)
}
key, dropped = dropNode(work.Docs[0], yamlErr.GetToken(), false)
ve = append(ve, decodeError(file, key, yamlErr.GetToken(), description))
if dropped {
wrongTypes = append(wrongTypes, key)
}