Debian Codegraph @

cmd/libopenapi-validate/main.go

raw ◀ ▶
1 Debian patch touch this file
•1 // Patched for debian packaging to enforce diff generation
2 package main
3
4 import (
5 "errors"
6 "flag"
7 "fmt"
8 "log/slog"
9 "os"
10
11 "github.com/dlclark/regexp2"
12 "github.com/goccy/go-yaml"
13 "github.com/pb33f/libopenapi"
14 "github.com/santhosh-tekuri/jsonschema/v6"
15
16 validator "github.com/pb33f/libopenapi-validator"
17 "github.com/pb33f/libopenapi-validator/config"
18 )
19
20 type customRegexp regexp2.Regexp
21
22 func (re *customRegexp) MatchString(s string) bool {
23 matched, err := (*regexp2.Regexp)(re).MatchString(s)
24 return err == nil && matched
25 }
26
27 func (re *customRegexp) String() string {
28 return (*regexp2.Regexp)(re).String()
29 }
30
31 type regexEngine struct {
32 runtimeOption regexp2.RegexOptions
33 }
34
35 func (e *regexEngine) run(s string) (jsonschema.Regexp, error) {
36 re, err := regexp2.Compile(s, e.runtimeOption)
37 if err != nil {
38 return nil, err
39 }
40 return (*customRegexp)(re), nil
41 }
42
43 var regexParsingOptionsMap = map[string]regexp2.RegexOptions{
44 "none": regexp2.None,
45 "ignorecase": regexp2.IgnoreCase,
46 "multiline": regexp2.Multiline,
47 "explicitcapture": regexp2.ExplicitCapture,
48 "compiled": regexp2.Compiled,
49 "singleline": regexp2.Singleline,
50 "ignorepatternwhitespace": regexp2.IgnorePatternWhitespace,
51 "righttoleft": regexp2.RightToLeft,
52 "debug": regexp2.Debug,
53 "ecmascript": regexp2.ECMAScript,
54 "re2": regexp2.RE2,
55 "unicode": regexp2.Unicode,
56 }
57
58 var (
59 defaultRegexEngine = ""
60 regexParsingOptions = flag.String("regexengine", defaultRegexEngine, `Specify the regex parsing option to use.
61 Supported values are:
62 Engines: re2 (default), ecmascript
63 Flags: ignorecase, multiline, explicitcapture, compiled,
64 singleline, ignorepatternwhitespace, righttoleft,
65 debug, unicode
66 If not specified, the default libopenapi option is "re2".
67
68 If not specified, the default libopenapi regex engine is "re2"".`)
69 convertYAMLToJSON = flag.Bool("yaml2json", false, `Convert YAML files to JSON before validation.
70 libopenapi passes map[interface{}]interface{} structures for deeply nested objects
71 or complex mappings, which are not allowed in JSON and cannot be validated by jsonschema.
72 This flag allows pre-converting from YAML to JSON to bypass this limitation of the libopenapi.
73 Default is false.`)
74 )
75
76 // main is the entry point for validating an OpenAPI Specification (OAS) document.
77 // It uses the libopenapi-validator library to check if the provided OAS document
78 // conforms to the OpenAPI specification.
79 //
80 // This tool accepts a single input file (YAML or JSON) and provides optional flags:
81 //
82 // `--regexengine` flag to customize the regex engine used during validation.
83 // This is useful for cases where the spec uses regex patterns that require engines
84 // like ECMAScript or RE2.
85 //
86 // Supported regex options include:
87 // - Engines: re2 (default), ecmascript
88 // - Flags: ignorecase, multiline, explicitcapture, compiled, singleline,
89 // ignorepatternwhitespace, righttoleft, debug, unicode
90 //
91 // `--yaml2json` flag to convert YAML files to JSON before validation.
92 // libopenapi passes map[interface{}]interface{} structures for deeply nested
93 // objects or complex mappings, which are not allowed in JSON and cannot be
94 // validated by jsonschema. This flag allows pre-converting from YAML to JSON
95 // to bypass this limitation of the libopenapi. Default is false.
96 //
97 // Example usage:
98 //
99 // go run main.go --regexengine=ecmascript ./my-api-spec.yaml
100 // go run main.go --yaml2json ./my-api-spec.yaml
101 //
102 // If validation passes, the tool logs a success message.
103 // If the document is invalid or there is a processing error, it logs details and exits non-zero.
104 func main() {
105 flag.Usage = func() {
106 fmt.Fprintf(os.Stderr, `Usage: validate [OPTIONS] <file>
107
108 Validates an OpenAPI document using libopenapi-validator.
109
110 Options:
111 --regexengine string Specify the regex parsing option to use.
112 Supported values are:
113 Engines: re2 (default), ecmascript
114 Flags: ignorecase, multiline, explicitcapture, compiled,
115 singleline, ignorepatternwhitespace, righttoleft,
116 debug, unicode
117 If not specified, the default libopenapi option is "re2".
118
119 --yaml2json Convert YAML files to JSON before validation.
120 libopenapi passes map[interface{}]interface{}
121 structures for deeply nested objects or complex mappings, which
122 are not allowed in JSON and cannot be validated by jsonschema.
123 This flag allows pre-converting from YAML to JSON to bypass this
124 limitation of the libopenapi.
125 (default: false)
126
127 -h, --help Show this help message and exit.
128 `)
129 }
130
131 for _, arg := range os.Args[1:] {
132 if arg == "--help" || arg == "-h" {
133 flag.Usage()
134 os.Exit(0)
135 }
136 }
137
138 logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
139 flag.Parse()
140 filename := flag.Arg(0)
141 if len(flag.Args()) != 1 || filename == "" {
142 logger.Error("missing file argument", slog.Any("args", os.Args))
143 flag.Usage()
144 os.Exit(1)
145 }
146 validationOpts := []config.Option{}
147 if *regexParsingOptions != "" {
148 regexEngineOption, ok := regexParsingOptionsMap[*regexParsingOptions]
149 if !ok {
150 logger.Error("unsupported regex option provided",
151 slog.String("provided", *regexParsingOptions),
152 slog.Any("supported", []string{
153 "none",
154 "ignorecase",
155 "multiline",
156 "explicitcapture",
157 "compiled",
158 "singleline",
159 "ignorepatternwhitespace",
160 "righttoleft",
161 "debug",
162 "ecmascript",
163 "re2",
164 "unicode",
165 }),
166 )
167 os.Exit(1)
168 }
169 reEngine := &regexEngine{
170 runtimeOption: regexEngineOption,
171 }
172
173 validationOpts = append(validationOpts, config.WithRegexEngine(reEngine.run))
174 }
175
176 data, err := os.ReadFile(filename)
177 if err != nil {
178 logger.Error("error reading file", slog.String("provided", filename), slog.Any("error", err))
179 os.Exit(1)
180 }
181
182 if *convertYAMLToJSON {
183 var v interface{}
184 if err := yaml.Unmarshal(data, &v); err == nil {
185 data, err = yaml.YAMLToJSON(data)
186 if err != nil {
187 logger.Error("invalid api spec: error converting yaml to json", slog.Any("error", err))
188 os.Exit(1)
189 }
190 }
191 }
192
193 doc, err := libopenapi.NewDocument(data)
194 if err != nil {
195 logger.Error("error creating new libopenapi document", slog.Any("error", err))
196 os.Exit(1)
197 }
198
199 docValidator, validatorErrs := validator.NewValidator(doc, validationOpts...)
200 if len(validatorErrs) > 0 {
201 logger.Error("error creating a new validator", slog.Any("errors", errors.Join(validatorErrs...)))
202 os.Exit(1)
203 }
204
205 valid, validationErrs := docValidator.ValidateDocument()
206 if !valid {
207 logger.Error("validation errors", slog.Any("errors", validationErrs))
208 os.Exit(1)
209 }
210 logger.Info("document passes all validations", slog.String("filename", filename))
211 }