Similarityoung commented on code in PR #948:
URL: https://github.com/apache/dubbo-go-pixiu/pull/948#discussion_r3367026652


##########
pkg/filter/http/openapi/openapi.go:
##########
@@ -0,0 +1,415 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package openapi
+
+import (
+       "bytes"
+       "io"
+       "net/http"
+       "os"
+       "path/filepath"
+       "strings"
+)
+
+import (
+       "github.com/pb33f/libopenapi"
+       openapiValidator "github.com/pb33f/libopenapi-validator"
+       validatorConfig "github.com/pb33f/libopenapi-validator/config"
+       validatorErrors "github.com/pb33f/libopenapi-validator/errors"
+       validatorPaths "github.com/pb33f/libopenapi-validator/paths"
+       validatorRadix "github.com/pb33f/libopenapi-validator/radix"
+       "github.com/pb33f/libopenapi/datamodel"
+       v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
+
+       "github.com/pkg/errors"
+)
+
+import (
+       "github.com/apache/dubbo-go-pixiu/pkg/common/constant"
+       "github.com/apache/dubbo-go-pixiu/pkg/common/extension/filter"
+       contexthttp "github.com/apache/dubbo-go-pixiu/pkg/context/http"
+       "github.com/apache/dubbo-go-pixiu/pkg/logger"
+)
+
+const (
+       // Kind is the kind of OpenAPI validation filter.
+       Kind = constant.HTTPOpenAPIFilter
+
+       defaultMaxRequestBodyBytes = 1 << 20
+)
+
+var errOpenAPIRequestBodyTooLarge = errors.New("openapi request body too 
large")
+
+func init() {
+       filter.RegisterHttpFilter(&Plugin{})
+}
+
+type (
+       Plugin struct {
+       }
+
+       FilterFactory struct {
+               cfg               *Config
+               validator         openapiValidator.Validator
+               model             *v3.Document
+               validationOptions *validatorConfig.ValidationOptions
+               maxRequestBody    int64
+       }
+
+       Filter struct {
+               validator         openapiValidator.Validator
+               model             *v3.Document
+               validationOptions *validatorConfig.ValidationOptions
+               maxRequestBody    int64
+       }
+
+       Config struct {
+               Path string `yaml:"path" json:"path,omitempty"`
+               // MaxRequestBodyBytes limits how much request body data 
OpenAPI validation may read.
+               // Zero uses the default limit.
+               MaxRequestBodyBytes int64 `yaml:"max_request_body_bytes" 
json:"max_request_body_bytes,omitempty"`
+       }
+)
+
+func (p *Plugin) Kind() string {
+       return Kind
+}
+
+func (p *Plugin) CreateFilterFactory() (filter.HttpFilterFactory, error) {
+       return &FilterFactory{cfg: &Config{}}, nil
+}
+
+func (factory *FilterFactory) Config() any {
+       return factory.cfg
+}
+
+func (factory *FilterFactory) Apply() error {
+       path, err := cleanOpenAPIPath(factory.cfg.Path)
+       if err != nil {
+               return err
+       }
+       factory.cfg.Path = path
+
+       maxRequestBody, err := factory.cfg.effectiveMaxRequestBodyBytes()
+       if err != nil {
+               return err
+       }
+
+       validator, model, validationOptions, err := loadValidatorFromFile(path)

Review Comment:
   [P1] 这里返回加载错误本身没问题,但当前集成链路不会真正让启动失败。`FilterManager.ReLoad()` 只记录 `Apply()` 
的错误,随后仍会把返回的 nil factory 放进 `filtersArray`;后续创建 filter chain 时会对这个 nil factory 
调 `PrepareFilterChain`,请求路径上可能直接 panic。建议让 HTTP filter 初始化错误向上返回,或者至少不要安装失败的 
factory,并补一个非法 OpenAPI 配置的集成测试。



##########
pkg/filter/http/openapi/openapi.go:
##########
@@ -0,0 +1,415 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package openapi
+
+import (
+       "bytes"
+       "io"
+       "net/http"
+       "os"
+       "path/filepath"
+       "strings"
+)
+
+import (
+       "github.com/pb33f/libopenapi"
+       openapiValidator "github.com/pb33f/libopenapi-validator"
+       validatorConfig "github.com/pb33f/libopenapi-validator/config"
+       validatorErrors "github.com/pb33f/libopenapi-validator/errors"
+       validatorPaths "github.com/pb33f/libopenapi-validator/paths"
+       validatorRadix "github.com/pb33f/libopenapi-validator/radix"
+       "github.com/pb33f/libopenapi/datamodel"
+       v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
+
+       "github.com/pkg/errors"
+)
+
+import (
+       "github.com/apache/dubbo-go-pixiu/pkg/common/constant"
+       "github.com/apache/dubbo-go-pixiu/pkg/common/extension/filter"
+       contexthttp "github.com/apache/dubbo-go-pixiu/pkg/context/http"
+       "github.com/apache/dubbo-go-pixiu/pkg/logger"
+)
+
+const (
+       // Kind is the kind of OpenAPI validation filter.
+       Kind = constant.HTTPOpenAPIFilter
+
+       defaultMaxRequestBodyBytes = 1 << 20
+)
+
+var errOpenAPIRequestBodyTooLarge = errors.New("openapi request body too 
large")
+
+func init() {
+       filter.RegisterHttpFilter(&Plugin{})
+}
+
+type (
+       Plugin struct {
+       }
+
+       FilterFactory struct {
+               cfg               *Config
+               validator         openapiValidator.Validator
+               model             *v3.Document
+               validationOptions *validatorConfig.ValidationOptions
+               maxRequestBody    int64
+       }
+
+       Filter struct {
+               validator         openapiValidator.Validator
+               model             *v3.Document
+               validationOptions *validatorConfig.ValidationOptions
+               maxRequestBody    int64
+       }
+
+       Config struct {
+               Path string `yaml:"path" json:"path,omitempty"`
+               // MaxRequestBodyBytes limits how much request body data 
OpenAPI validation may read.
+               // Zero uses the default limit.
+               MaxRequestBodyBytes int64 `yaml:"max_request_body_bytes" 
json:"max_request_body_bytes,omitempty"`
+       }
+)
+
+func (p *Plugin) Kind() string {
+       return Kind
+}
+
+func (p *Plugin) CreateFilterFactory() (filter.HttpFilterFactory, error) {
+       return &FilterFactory{cfg: &Config{}}, nil
+}
+
+func (factory *FilterFactory) Config() any {
+       return factory.cfg
+}
+
+func (factory *FilterFactory) Apply() error {
+       path, err := cleanOpenAPIPath(factory.cfg.Path)
+       if err != nil {
+               return err
+       }
+       factory.cfg.Path = path
+
+       maxRequestBody, err := factory.cfg.effectiveMaxRequestBodyBytes()
+       if err != nil {
+               return err
+       }
+
+       validator, model, validationOptions, err := loadValidatorFromFile(path)
+       if err != nil {
+               return err
+       }
+       factory.validator = validator
+       factory.model = model
+       factory.validationOptions = validationOptions
+       factory.maxRequestBody = maxRequestBody
+       return nil
+}
+
+func (factory *FilterFactory) PrepareFilterChain(ctx *contexthttp.HttpContext, 
chain filter.FilterChain) error {
+       f := &Filter{
+               validator:         factory.validator,
+               model:             factory.model,
+               validationOptions: factory.validationOptions,
+               maxRequestBody:    factory.maxRequestBody,
+       }
+       chain.AppendDecodeFilters(f)
+       return nil
+}
+
+func (f *Filter) Decode(ctx *contexthttp.HttpContext) filter.FilterStatus {
+       if f.validator == nil || f.model == nil {
+               return filter.Continue
+       }
+
+       req := ctx.Request
+       pathItem, foundPath, ok := f.findRequestOperation(req)
+       if !ok {
+               return filter.Continue
+       }
+
+       if err := f.prepareRequestBodyForValidation(req); err != nil {
+               if err == errOpenAPIRequestBodyTooLarge {
+                       errResp := contexthttp.PayloadTooLarge.WithError(err)
+                       ctx.SendLocalReply(errResp.Status, errResp.ToJSON())
+                       logger.Debug(errResp.Error())
+                       return filter.Stop
+               }
+               errResp := contexthttp.BadRequest.WithError(errors.New("openapi 
request body read failed"))
+               ctx.SendLocalReply(errResp.Status, errResp.ToJSON())
+               logger.Debugf("openapi request body read failed: %v", err)
+               return filter.Stop
+       }
+
+       if valid, validationErrs := 
f.validator.ValidateHttpRequestSyncWithPathItem(req, pathItem, foundPath); 
!valid {
+               validationDetails := formatValidationErrors(validationErrs)
+               errResp := contexthttp.BadRequest.WithError(errors.New("openapi 
request validation failed"))
+               ctx.SendLocalReply(errResp.Status, errResp.ToJSON())
+               logger.Debugf("openapi request validation failed: %s", 
validationDetails)
+               return filter.Stop
+       }
+       return filter.Continue
+}
+
+func (f *Filter) findRequestOperation(req *http.Request) (*v3.PathItem, 
string, bool) {
+       pathItem, validationErrs, foundPath := validatorPaths.FindPath(req, 
f.model, f.validationOptions)
+       if len(validationErrs) > 0 {
+               logger.Debugf("openapi path lookup errors for %s %s: %s", 
req.Method, req.URL.Path, formatValidationErrors(validationErrs))
+               return nil, "", false
+       }
+       if pathItem == nil {
+               return nil, "", false
+       }
+       if !hasRequestOperation(req, pathItem) {
+               return nil, "", false
+       }
+       return pathItem, foundPath, true
+}
+
+func hasRequestOperation(req *http.Request, pathItem *v3.PathItem) bool {
+       switch req.Method {
+       case http.MethodGet:
+               return pathItem.Get != nil
+       case http.MethodPost:
+               return pathItem.Post != nil
+       case http.MethodPut:
+               return pathItem.Put != nil
+       case http.MethodDelete:
+               return pathItem.Delete != nil
+       case http.MethodOptions:
+               return pathItem.Options != nil
+       case http.MethodHead:
+               return pathItem.Head != nil || pathItem.Get != nil
+       case http.MethodPatch:
+               return pathItem.Patch != nil
+       case http.MethodTrace:
+               return pathItem.Trace != nil
+       default:
+               operations := pathItem.GetOperations()
+               return operations != nil && 
operations.GetOrZero(strings.ToLower(req.Method)) != nil
+       }
+}
+
+func (f *Filter) prepareRequestBodyForValidation(req *http.Request) error {
+       if req.Body == nil || req.Body == http.NoBody {
+               return nil
+       }
+       if f.maxRequestBody <= 0 {
+               return nil
+       }
+       if req.ContentLength > f.maxRequestBody {
+               return errOpenAPIRequestBodyTooLarge
+       }
+
+       body, err := readRequestBodyWithinLimit(req.Body, f.maxRequestBody)
+       if err != nil {
+               return err
+       }
+       req.Body = io.NopCloser(bytes.NewReader(body))
+       req.ContentLength = int64(len(body))
+       return nil
+}
+
+func readRequestBodyWithinLimit(body io.ReadCloser, limit int64) ([]byte, 
error) {
+       // The original body is replaced by the caller after this bounded read.
+       defer body.Close()
+
+       data, err := io.ReadAll(io.LimitReader(body, limit+1))
+       if err != nil {
+               return nil, err
+       }
+       if int64(len(data)) > limit {
+               return nil, errOpenAPIRequestBodyTooLarge
+       }
+       return data, nil
+}
+
+func loadValidatorFromFile(path string) (openapiValidator.Validator, 
*v3.Document, *validatorConfig.ValidationOptions, error) {
+       spec, err := os.ReadFile(path)
+       if err != nil {
+               return nil, nil, nil, errors.Wrap(err, "read openapi file")
+       }
+
+       doc, err := libopenapi.NewDocumentWithConfiguration(spec, 
&datamodel.DocumentConfiguration{

Review Comment:
   [P1] 这里设置 `BasePath` 后,libopenapi 会解析本地外部 `$ref`,并会从 base path 递归索引文件。入口 
`path` 已经做了相对路径、`..`、敏感目录和 symlink 检查,但 spec 内部的外部 `$ref` 还没有同等限制。建议用受限的 
`LocalFS` / `FileFilter`,或者在构建模型前校验所有本地外部 `$ref`,避免绝对路径、`..` 或 symlink 跳出允许目录。



##########
pkg/filter/http/openapi/openapi.go:
##########
@@ -0,0 +1,415 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package openapi
+
+import (
+       "bytes"
+       "io"
+       "net/http"
+       "os"
+       "path/filepath"
+       "strings"
+)
+
+import (
+       "github.com/pb33f/libopenapi"
+       openapiValidator "github.com/pb33f/libopenapi-validator"
+       validatorConfig "github.com/pb33f/libopenapi-validator/config"
+       validatorErrors "github.com/pb33f/libopenapi-validator/errors"
+       validatorPaths "github.com/pb33f/libopenapi-validator/paths"
+       validatorRadix "github.com/pb33f/libopenapi-validator/radix"
+       "github.com/pb33f/libopenapi/datamodel"
+       v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
+
+       "github.com/pkg/errors"
+)
+
+import (
+       "github.com/apache/dubbo-go-pixiu/pkg/common/constant"
+       "github.com/apache/dubbo-go-pixiu/pkg/common/extension/filter"
+       contexthttp "github.com/apache/dubbo-go-pixiu/pkg/context/http"
+       "github.com/apache/dubbo-go-pixiu/pkg/logger"
+)
+
+const (
+       // Kind is the kind of OpenAPI validation filter.
+       Kind = constant.HTTPOpenAPIFilter
+
+       defaultMaxRequestBodyBytes = 1 << 20
+)
+
+var errOpenAPIRequestBodyTooLarge = errors.New("openapi request body too 
large")
+
+func init() {
+       filter.RegisterHttpFilter(&Plugin{})
+}
+
+type (
+       Plugin struct {
+       }
+
+       FilterFactory struct {
+               cfg               *Config
+               validator         openapiValidator.Validator
+               model             *v3.Document
+               validationOptions *validatorConfig.ValidationOptions
+               maxRequestBody    int64
+       }
+
+       Filter struct {
+               validator         openapiValidator.Validator
+               model             *v3.Document
+               validationOptions *validatorConfig.ValidationOptions
+               maxRequestBody    int64
+       }
+
+       Config struct {
+               Path string `yaml:"path" json:"path,omitempty"`
+               // MaxRequestBodyBytes limits how much request body data 
OpenAPI validation may read.
+               // Zero uses the default limit.
+               MaxRequestBodyBytes int64 `yaml:"max_request_body_bytes" 
json:"max_request_body_bytes,omitempty"`
+       }
+)
+
+func (p *Plugin) Kind() string {
+       return Kind
+}
+
+func (p *Plugin) CreateFilterFactory() (filter.HttpFilterFactory, error) {
+       return &FilterFactory{cfg: &Config{}}, nil
+}
+
+func (factory *FilterFactory) Config() any {
+       return factory.cfg
+}
+
+func (factory *FilterFactory) Apply() error {
+       path, err := cleanOpenAPIPath(factory.cfg.Path)
+       if err != nil {
+               return err
+       }
+       factory.cfg.Path = path
+
+       maxRequestBody, err := factory.cfg.effectiveMaxRequestBodyBytes()
+       if err != nil {
+               return err
+       }
+
+       validator, model, validationOptions, err := loadValidatorFromFile(path)
+       if err != nil {
+               return err
+       }
+       factory.validator = validator
+       factory.model = model
+       factory.validationOptions = validationOptions
+       factory.maxRequestBody = maxRequestBody
+       return nil
+}
+
+func (factory *FilterFactory) PrepareFilterChain(ctx *contexthttp.HttpContext, 
chain filter.FilterChain) error {
+       f := &Filter{
+               validator:         factory.validator,
+               model:             factory.model,
+               validationOptions: factory.validationOptions,
+               maxRequestBody:    factory.maxRequestBody,
+       }
+       chain.AppendDecodeFilters(f)
+       return nil
+}
+
+func (f *Filter) Decode(ctx *contexthttp.HttpContext) filter.FilterStatus {
+       if f.validator == nil || f.model == nil {
+               return filter.Continue
+       }
+
+       req := ctx.Request
+       pathItem, foundPath, ok := f.findRequestOperation(req)
+       if !ok {
+               return filter.Continue
+       }
+
+       if err := f.prepareRequestBodyForValidation(req); err != nil {
+               if err == errOpenAPIRequestBodyTooLarge {
+                       errResp := contexthttp.PayloadTooLarge.WithError(err)
+                       ctx.SendLocalReply(errResp.Status, errResp.ToJSON())
+                       logger.Debug(errResp.Error())
+                       return filter.Stop
+               }
+               errResp := contexthttp.BadRequest.WithError(errors.New("openapi 
request body read failed"))
+               ctx.SendLocalReply(errResp.Status, errResp.ToJSON())
+               logger.Debugf("openapi request body read failed: %v", err)
+               return filter.Stop
+       }
+
+       if valid, validationErrs := 
f.validator.ValidateHttpRequestSyncWithPathItem(req, pathItem, foundPath); 
!valid {
+               validationDetails := formatValidationErrors(validationErrs)
+               errResp := contexthttp.BadRequest.WithError(errors.New("openapi 
request validation failed"))
+               ctx.SendLocalReply(errResp.Status, errResp.ToJSON())
+               logger.Debugf("openapi request validation failed: %s", 
validationDetails)
+               return filter.Stop
+       }
+       return filter.Continue
+}
+
+func (f *Filter) findRequestOperation(req *http.Request) (*v3.PathItem, 
string, bool) {
+       pathItem, validationErrs, foundPath := validatorPaths.FindPath(req, 
f.model, f.validationOptions)
+       if len(validationErrs) > 0 {
+               logger.Debugf("openapi path lookup errors for %s %s: %s", 
req.Method, req.URL.Path, formatValidationErrors(validationErrs))
+               return nil, "", false
+       }
+       if pathItem == nil {
+               return nil, "", false
+       }
+       if !hasRequestOperation(req, pathItem) {
+               return nil, "", false
+       }
+       return pathItem, foundPath, true
+}
+
+func hasRequestOperation(req *http.Request, pathItem *v3.PathItem) bool {
+       switch req.Method {
+       case http.MethodGet:
+               return pathItem.Get != nil
+       case http.MethodPost:
+               return pathItem.Post != nil
+       case http.MethodPut:
+               return pathItem.Put != nil
+       case http.MethodDelete:
+               return pathItem.Delete != nil
+       case http.MethodOptions:
+               return pathItem.Options != nil
+       case http.MethodHead:
+               return pathItem.Head != nil || pathItem.Get != nil

Review Comment:
   [P2] 这里会把只声明了 GET 的 HEAD 请求当成命中的 operation 继续交给 validator。现有 query/header 
参数路径不会 fallback 到 GET,所以当前测试能通过;但 request body 提取会 fallback 到 GET,带 
`requestBody` 的 GET operation 仍可能影响 HEAD。文档说 GET-only HEAD 应跳过校验,建议这里按文档只接受显式 
`head` operation,或者补充 GET requestBody 场景并更新文档契约。



##########
pkg/filter/http/openapi/openapi.go:
##########
@@ -0,0 +1,415 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package openapi
+
+import (
+       "bytes"
+       "io"
+       "net/http"
+       "os"
+       "path/filepath"
+       "strings"
+)
+
+import (
+       "github.com/pb33f/libopenapi"
+       openapiValidator "github.com/pb33f/libopenapi-validator"
+       validatorConfig "github.com/pb33f/libopenapi-validator/config"
+       validatorErrors "github.com/pb33f/libopenapi-validator/errors"
+       validatorPaths "github.com/pb33f/libopenapi-validator/paths"
+       validatorRadix "github.com/pb33f/libopenapi-validator/radix"
+       "github.com/pb33f/libopenapi/datamodel"
+       v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
+
+       "github.com/pkg/errors"
+)
+
+import (
+       "github.com/apache/dubbo-go-pixiu/pkg/common/constant"
+       "github.com/apache/dubbo-go-pixiu/pkg/common/extension/filter"
+       contexthttp "github.com/apache/dubbo-go-pixiu/pkg/context/http"
+       "github.com/apache/dubbo-go-pixiu/pkg/logger"
+)
+
+const (
+       // Kind is the kind of OpenAPI validation filter.
+       Kind = constant.HTTPOpenAPIFilter
+
+       defaultMaxRequestBodyBytes = 1 << 20
+)
+
+var errOpenAPIRequestBodyTooLarge = errors.New("openapi request body too 
large")
+
+func init() {
+       filter.RegisterHttpFilter(&Plugin{})
+}
+
+type (
+       Plugin struct {
+       }
+
+       FilterFactory struct {
+               cfg               *Config
+               validator         openapiValidator.Validator
+               model             *v3.Document
+               validationOptions *validatorConfig.ValidationOptions
+               maxRequestBody    int64
+       }
+
+       Filter struct {
+               validator         openapiValidator.Validator
+               model             *v3.Document
+               validationOptions *validatorConfig.ValidationOptions
+               maxRequestBody    int64
+       }
+
+       Config struct {
+               Path string `yaml:"path" json:"path,omitempty"`
+               // MaxRequestBodyBytes limits how much request body data 
OpenAPI validation may read.
+               // Zero uses the default limit.
+               MaxRequestBodyBytes int64 `yaml:"max_request_body_bytes" 
json:"max_request_body_bytes,omitempty"`
+       }
+)
+
+func (p *Plugin) Kind() string {
+       return Kind
+}
+
+func (p *Plugin) CreateFilterFactory() (filter.HttpFilterFactory, error) {
+       return &FilterFactory{cfg: &Config{}}, nil
+}
+
+func (factory *FilterFactory) Config() any {
+       return factory.cfg
+}
+
+func (factory *FilterFactory) Apply() error {
+       path, err := cleanOpenAPIPath(factory.cfg.Path)
+       if err != nil {
+               return err
+       }
+       factory.cfg.Path = path
+
+       maxRequestBody, err := factory.cfg.effectiveMaxRequestBodyBytes()
+       if err != nil {
+               return err
+       }
+
+       validator, model, validationOptions, err := loadValidatorFromFile(path)
+       if err != nil {
+               return err
+       }
+       factory.validator = validator
+       factory.model = model
+       factory.validationOptions = validationOptions
+       factory.maxRequestBody = maxRequestBody
+       return nil
+}
+
+func (factory *FilterFactory) PrepareFilterChain(ctx *contexthttp.HttpContext, 
chain filter.FilterChain) error {
+       f := &Filter{
+               validator:         factory.validator,
+               model:             factory.model,
+               validationOptions: factory.validationOptions,
+               maxRequestBody:    factory.maxRequestBody,
+       }
+       chain.AppendDecodeFilters(f)
+       return nil
+}
+
+func (f *Filter) Decode(ctx *contexthttp.HttpContext) filter.FilterStatus {
+       if f.validator == nil || f.model == nil {
+               return filter.Continue
+       }
+
+       req := ctx.Request
+       pathItem, foundPath, ok := f.findRequestOperation(req)
+       if !ok {
+               return filter.Continue
+       }
+
+       if err := f.prepareRequestBodyForValidation(req); err != nil {
+               if err == errOpenAPIRequestBodyTooLarge {
+                       errResp := contexthttp.PayloadTooLarge.WithError(err)
+                       ctx.SendLocalReply(errResp.Status, errResp.ToJSON())
+                       logger.Debug(errResp.Error())
+                       return filter.Stop
+               }
+               errResp := contexthttp.BadRequest.WithError(errors.New("openapi 
request body read failed"))
+               ctx.SendLocalReply(errResp.Status, errResp.ToJSON())
+               logger.Debugf("openapi request body read failed: %v", err)
+               return filter.Stop
+       }
+
+       if valid, validationErrs := 
f.validator.ValidateHttpRequestSyncWithPathItem(req, pathItem, foundPath); 
!valid {
+               validationDetails := formatValidationErrors(validationErrs)
+               errResp := contexthttp.BadRequest.WithError(errors.New("openapi 
request validation failed"))
+               ctx.SendLocalReply(errResp.Status, errResp.ToJSON())
+               logger.Debugf("openapi request validation failed: %s", 
validationDetails)
+               return filter.Stop
+       }
+       return filter.Continue
+}
+
+func (f *Filter) findRequestOperation(req *http.Request) (*v3.PathItem, 
string, bool) {
+       pathItem, validationErrs, foundPath := validatorPaths.FindPath(req, 
f.model, f.validationOptions)
+       if len(validationErrs) > 0 {

Review Comment:
   [P2] 这里一旦 `FindPath()` 返回 missing operation error 就直接跳过,下面 
`hasRequestOperation()` 里基于 `GetOperations()` 的兜底基本走不到。对 OpenAPI 3.2 的 
additional operations,比如 `query`,libopenapi 可以建模,但当前 `FindPath` / path tree 的 
method 判断不会把它当作已声明方法,最后会被当成未声明 method 放行。若要宣称支持 OpenAPI 3.2 
operation,建议调整这个分支并补 `QUERY /path` 这类测试;否则文档里需要收窄 3.2 支持范围。



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to