github.com/avenga/couper@v1.12.2/handler/validation/openapi_options.go (about)

     1  package validation
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/getkin/kin-openapi/openapi3"
     9  	"github.com/getkin/kin-openapi/openapi3filter"
    10  
    11  	"github.com/avenga/couper/config"
    12  	"github.com/avenga/couper/eval/buffer"
    13  )
    14  
    15  type OpenAPIOptions struct {
    16  	buffer                   buffer.Option
    17  	ignoreRequestViolations  bool
    18  	ignoreResponseViolations bool
    19  	filterOptions            *openapi3filter.Options
    20  	doc                      *openapi3.T
    21  }
    22  
    23  // NewOpenAPIOptions takes a list of openAPI configuration due to merging configurations.
    24  // The last item will be set and no attributes gets merged.
    25  func NewOpenAPIOptions(openapi *config.OpenAPI) (*OpenAPIOptions, error) {
    26  	if openapi == nil {
    27  		return nil, nil
    28  	}
    29  
    30  	p, err := filepath.Abs(openapi.File)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  
    35  	b, err := os.ReadFile(p)
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  
    40  	return NewOpenAPIOptionsFromBytes(openapi, b)
    41  }
    42  
    43  func NewOpenAPIOptionsFromBytes(openapi *config.OpenAPI, bytes []byte) (*OpenAPIOptions, error) {
    44  	if openapi == nil || bytes == nil {
    45  		return nil, nil
    46  	}
    47  
    48  	doc, err := openapi3.NewLoader().LoadFromData(bytes)
    49  	if err != nil {
    50  		return nil, fmt.Errorf("error loading openapi file: %w", err)
    51  	}
    52  
    53  	// Always buffer if openAPI is active. Request buffering is handled by openapifilter too.
    54  	// Anyway adding request buffer option to let Couper check the body limits.
    55  	bufferBodies := buffer.Request | buffer.Response
    56  
    57  	return &OpenAPIOptions{
    58  		buffer: bufferBodies,
    59  		filterOptions: &openapi3filter.Options{
    60  			ExcludeRequestBody:    false,
    61  			ExcludeResponseBody:   false,
    62  			IncludeResponseStatus: true,
    63  		},
    64  		ignoreRequestViolations:  openapi.IgnoreRequestViolations,
    65  		ignoreResponseViolations: openapi.IgnoreResponseViolations,
    66  		doc:                      doc,
    67  	}, nil
    68  }