Debian Codegraph @

cmd/libopenapi-validate/main.go

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