forked from chukmunnlee/caddy-openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openapi.go
247 lines (200 loc) · 5.7 KB
/
openapi.go
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
package openapi
import (
"fmt"
"net/url"
"os"
"strconv"
"strings"
"go.uber.org/zap"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/open-policy-agent/opa/rego"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/routers"
"github.com/getkin/kin-openapi/routers/gorillamux"
)
const (
MODULE_ID = "http.handlers.openapi"
X_POLICY = "x-policy"
OPENAPI_ERROR = "openapi.error"
OPENAPI_STATUS_CODE = "openapi.status_code"
OPENAPI_RESPONSE_ERROR = "openapi.response_error"
TOKEN_OPENAPI = "openapi"
TOKEN_POLICY_BUNDLE = "policy_bundle"
TOKEN_SPEC = "spec"
TOKEN_FALL_THROUGH = "fall_through"
TOKEN_LOG_ERROR = "log_error"
TOKEN_VALIDATE_SERVERS = "validate_servers"
TOKEN_CHECK = "check"
VALUE_REQ_PARAMS = "req_params"
VALUE_REQ_BODY = "req_body"
VALUE_RESP_BODY = "resp_body"
)
// This middleware validates request against an OpenAPI V3 specification. No conforming request can be rejected
type OpenAPI struct {
// The location of the OASv3 file
Spec string `json:"spec"`
PolicyBundle string `json:"policy_bundle"`
// Should the request proceed if it fails validation. Default is `false`
FallThrough bool `json:"fall_through,omitempty"`
// Should the non compliant request be logged? Default is `false`
LogError bool `json:"log_error,omitempty"`
// Enable request and response validation
Check *CheckOptions `json:"check,omitempty"`
// Enable server validation
ValidateServers bool `json:"valid_servers,omitempty"`
oas *openapi3.T
router routers.Router
logger *zap.Logger
contentMap map[string]string
policy func(*rego.Rego)
}
type CheckOptions struct {
// Enable request query validation. Default is `false`
RequestParams bool `json:"req_params,omitempty"`
// Enable request payload validation. Default is `false`
RequestBody bool `json:"req_body,omitempty"`
// Enable response body validation with an optional list of
// `Content-Type` to examine. Default `application/json`. If you set
// your content type, the default will be removed
ResponseBody []string `json:"resp_body,omitempty"`
}
var (
_ caddy.Provisioner = (*OpenAPI)(nil)
_ caddy.Validator = (*OpenAPI)(nil)
_ caddyfile.Unmarshaler = (*OpenAPI)(nil)
_ caddyhttp.MiddlewareHandler = (*OpenAPI)(nil)
)
func init() {
caddy.RegisterModule(OpenAPI{})
httpcaddyfile.RegisterHandlerDirective(TOKEN_OPENAPI, parseCaddyFile)
}
func (oapi OpenAPI) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: MODULE_ID,
New: func() caddy.Module { return new(OpenAPI) },
}
}
func (oapi *OpenAPI) Provision(ctx caddy.Context) error {
var oas *openapi3.T
var err error
oapi.logger = ctx.Logger(oapi)
defer oapi.logger.Sync()
oapi.log(fmt.Sprintf("Using OpenAPI spec: %s", oapi.Spec))
if strings.HasPrefix("http", oapi.Spec) {
var u *url.URL
if u, err = url.Parse(oapi.Spec); nil != err {
return err
}
if oas, err = openapi3.NewLoader().LoadFromURI(u); nil != err {
return err
}
} else if _, err = os.Stat(oapi.Spec); !(nil == err || os.IsExist(err)) {
return err
} else if oas, err = openapi3.NewLoader().LoadFromFile(oapi.Spec); nil != err {
return err
}
if oapi.ValidateServers {
oapi.log("List of servers")
for _, s := range oas.Servers {
oapi.log(fmt.Sprintf("- %s #%s", s.URL, s.Description))
}
} else {
// clear all servers
oapi.log("Disabling server validation")
oas.Servers = make([]*openapi3.Server, 0)
}
router, err := gorillamux.NewRouter(oas)
if nil != err {
return err
}
oapi.oas = oas
oapi.router = router
if (nil != oapi.Check) && (nil != oapi.Check.ResponseBody) {
oapi.contentMap = make(map[string]string)
for _, content := range oapi.Check.ResponseBody {
oapi.contentMap[content] = ""
}
}
if len(oapi.PolicyBundle) > 0 {
oapi.log(fmt.Sprintf("Loaded policy bundle: %s", oapi.PolicyBundle))
oapi.policy = rego.LoadBundle(oapi.PolicyBundle)
}
return nil
}
func (oapi OpenAPI) Validate() error {
return nil
}
func (oapi *OpenAPI) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
oapi.Spec = ""
oapi.PolicyBundle = ""
oapi.FallThrough = false
oapi.LogError = false
oapi.ValidateServers = true
oapi.Check = nil
// Skip the openapi directive
d.Next()
args := d.RemainingArgs()
if 1 == len(args) {
d.NextArg()
oapi.Spec = d.Val()
}
for nest := d.Nesting(); d.NextBlock(nest); {
token := d.Val()
switch token {
case TOKEN_SPEC:
if !d.NextArg() {
return d.Err("Missing OpenAPI spec file")
} else {
oapi.Spec = d.Val()
}
if d.NextArg() {
return d.ArgErr()
}
case TOKEN_POLICY_BUNDLE:
if !d.NextArg() {
return d.Err("Missing policy bundle")
} else {
oapi.PolicyBundle = d.Val()
}
if d.NextArg() {
return d.ArgErr()
}
case TOKEN_VALIDATE_SERVERS:
if d.NextArg() {
b, err := strconv.ParseBool(d.Val())
if nil == err {
oapi.ValidateServers = b
}
}
case TOKEN_FALL_THROUGH:
if d.NextArg() {
return d.ArgErr()
}
oapi.FallThrough = true
case TOKEN_LOG_ERROR:
if d.NextArg() {
return d.ArgErr()
}
oapi.LogError = true
case TOKEN_CHECK:
err := parseCheckDirective(oapi, d)
if nil != err {
return err
}
default:
return d.Errf("unrecognized subdirective: '%s'", token)
}
}
if "" == oapi.Spec {
return d.Err("missing OpenAPI spec file")
}
return nil
}
func parseCaddyFile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var oapi OpenAPI
err := oapi.UnmarshalCaddyfile(h.Dispenser)
return oapi, err
}