Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support refs outside #/components - Resolves Issue 24 #207

Merged
merged 2 commits into from
Apr 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 92 additions & 74 deletions openapi3/swagger_loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"net/url"
"path"
"reflect"
"strings"

"github.com/ghodss/yaml"
Expand Down Expand Up @@ -247,24 +248,72 @@ func isSingleRefElement(ref string) bool {
return !strings.Contains(ref, "#")
}

func (swaggerLoader *SwaggerLoader) resolveComponent(swagger *Swagger, ref string, prefix string, path *url.URL) (
components *Components,
id string,
func (swaggerLoader *SwaggerLoader) resolveComponent(swagger *Swagger, ref string, path *url.URL) (
cursor interface{},
componentPath *url.URL,
err error,
) {
if swagger, ref, componentPath, err = swaggerLoader.resolveRefSwagger(swagger, ref, path); err != nil {
return nil, "", nil, err
return nil, nil, err
}
if !strings.HasPrefix(ref, prefix) {
err := fmt.Errorf("expected prefix '%s' in URI '%s'", prefix, ref)
return nil, "", nil, err

parsedURL, err := url.Parse(ref)
if err != nil {
return nil, nil, fmt.Errorf("Can't parse reference: '%s': %v", ref, parsedURL)
}
id = ref[len(prefix):]
if strings.IndexByte(id, '/') >= 0 {
return nil, "", nil, failedToResolveRefFragmentPart(ref, id)
fragment := parsedURL.Fragment
if !strings.HasPrefix(fragment, "/") {
err := fmt.Errorf("expected fragment prefix '#/' in URI '%s'", ref)
return nil, nil, err
}

cursor = swagger
for _, pathPart := range strings.Split(fragment[1:], "/") {

pathPart = strings.Replace(pathPart, "~1", "/", -1)
pathPart = strings.Replace(pathPart, "~0", "~", -1)

cursor, err = drillIntoSwaggerField(cursor, pathPart)
if err != nil {
return nil, nil, fmt.Errorf("Failed to resolve '%s' in fragment in URI: '%s': %v", ref, pathPart, err.Error())
}
if cursor == nil {
return nil, nil, failedToResolveRefFragmentPart(ref, pathPart)
}
}

return cursor, componentPath, nil
}

func drillIntoSwaggerField(cursor interface{}, fieldName string) (interface{}, error) {
val := reflect.Indirect(reflect.ValueOf(cursor))

switch val.Kind() {
case reflect.Map:
elementValue := val.MapIndex(reflect.ValueOf(fieldName))
if !elementValue.IsValid() {
return nil, fmt.Errorf("Map key not found: %v", fieldName)
}
return elementValue.Interface(), nil

case reflect.Struct:
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
tagValue := field.Tag.Get("yaml")
yamlKey := strings.Split(tagValue, ",")[0]
if yamlKey == fieldName {
return val.Field(i).Interface(), nil
}
}
// if cursor if a "ref wrapper" struct (e.g. RequestBodyRef), try digging into its Value field
_, ok := val.Type().FieldByName("Value")
if ok {
return drillIntoSwaggerField(val.FieldByName("Value").Interface(), fieldName) // recurse into .Value
}
// give up
return nil, fmt.Errorf("Struct field not found: %v", fieldName)
}
return &swagger.Components, id, componentPath, nil
return nil, fmt.Errorf("Not a map or struct")
}

func (swaggerLoader *SwaggerLoader) resolveRefSwagger(swagger *Swagger, ref string, path *url.URL) (*Swagger, string, *url.URL, error) {
Expand Down Expand Up @@ -313,16 +362,12 @@ func (swaggerLoader *SwaggerLoader) resolveHeaderRef(swagger *Swagger, component

component.Value = &header
} else {
components, id, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, prefix, path)
untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)
if err != nil {
return err
}
definitions := components.Headers
if definitions == nil {
return failedToResolveRefFragment(ref)
}
resolved := definitions[id]
if resolved == nil {
resolved, ok := untypedResolved.(*HeaderRef)
if !ok {
return failedToResolveRefFragment(ref)
}
if err := swaggerLoader.resolveHeaderRef(swagger, resolved, componentPath); err != nil {
Expand Down Expand Up @@ -362,17 +407,13 @@ func (swaggerLoader *SwaggerLoader) resolveParameterRef(swagger *Swagger, compon
}
component.Value = &param
} else {
components, id, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, prefix, documentPath)
untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, documentPath)
if err != nil {
return err
}
definitions := components.Parameters
if definitions == nil {
return failedToResolveRefFragmentPart(ref, "parameters")
}
resolved := definitions[id]
if resolved == nil {
return failedToResolveRefFragmentPart(ref, id)
resolved, ok := untypedResolved.(*ParameterRef)
if !ok {
return failedToResolveRefFragment(ref)
}
if err := swaggerLoader.resolveParameterRef(swagger, resolved, componentPath); err != nil {
return err
Expand Down Expand Up @@ -427,17 +468,13 @@ func (swaggerLoader *SwaggerLoader) resolveRequestBodyRef(swagger *Swagger, comp

component.Value = &requestBody
} else {
components, id, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, prefix, path)
untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)
if err != nil {
return err
}
definitions := components.RequestBodies
if definitions == nil {
return failedToResolveRefFragmentPart(ref, "requestBodies")
}
resolved := definitions[id]
if resolved == nil {
return failedToResolveRefFragmentPart(ref, id)
resolved, ok := untypedResolved.(*RequestBodyRef)
if !ok {
return failedToResolveRefFragment(ref)
}
if err = swaggerLoader.resolveRequestBodyRef(swagger, resolved, componentPath); err != nil {
return err
Expand Down Expand Up @@ -486,17 +523,13 @@ func (swaggerLoader *SwaggerLoader) resolveResponseRef(swagger *Swagger, compone

component.Value = &resp
} else {
components, id, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, prefix, documentPath)
untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, documentPath)
if err != nil {
return err
}
definitions := components.Responses
if definitions == nil {
return failedToResolveRefFragmentPart(ref, "responses")
}
resolved := definitions[id]
if resolved == nil {
return failedToResolveRefFragmentPart(ref, id)
resolved, ok := untypedResolved.(*ResponseRef)
if !ok {
return failedToResolveRefFragment(ref)
}
if err := swaggerLoader.resolveResponseRef(swagger, resolved, componentPath); err != nil {
return err
Expand Down Expand Up @@ -562,17 +595,14 @@ func (swaggerLoader *SwaggerLoader) resolveSchemaRef(swagger *Swagger, component
}
component.Value = &schema
} else {
components, id, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, prefix, documentPath)
untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, documentPath)
if err != nil {
return err
}
definitions := components.Schemas
if definitions == nil {
return failedToResolveRefFragmentPart(ref, "schemas")
}
resolved := definitions[id]
if resolved == nil {
return failedToResolveRefFragmentPart(ref, id)

resolved, ok := untypedResolved.(*SchemaRef)
if !ok {
return failedToResolveRefFragment(ref)
}
if err := swaggerLoader.resolveSchemaRef(swagger, resolved, componentPath); err != nil {
return err
Expand Down Expand Up @@ -650,17 +680,13 @@ func (swaggerLoader *SwaggerLoader) resolveSecuritySchemeRef(swagger *Swagger, c

component.Value = &scheme
} else {
components, id, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, prefix, path)
untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)
if err != nil {
return err
}
definitions := components.SecuritySchemes
if definitions == nil {
return failedToResolveRefFragmentPart(ref, "securitySchemes")
}
resolved := definitions[id]
if resolved == nil {
return failedToResolveRefFragmentPart(ref, id)
resolved, ok := untypedResolved.(*SecuritySchemeRef)
if !ok {
return failedToResolveRefFragment(ref)
}
if err := swaggerLoader.resolveSecuritySchemeRef(swagger, resolved, componentPath); err != nil {
return err
Expand Down Expand Up @@ -689,17 +715,13 @@ func (swaggerLoader *SwaggerLoader) resolveExampleRef(swagger *Swagger, componen

component.Value = &example
} else {
components, id, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, prefix, path)
untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)
if err != nil {
return err
}
definitions := components.Examples
if definitions == nil {
return failedToResolveRefFragmentPart(ref, "examples")
}
resolved := definitions[id]
if resolved == nil {
return failedToResolveRefFragmentPart(ref, id)
resolved, ok := untypedResolved.(*ExampleRef)
if !ok {
return failedToResolveRefFragment(ref)
}
if err := swaggerLoader.resolveExampleRef(swagger, resolved, componentPath); err != nil {
return err
Expand Down Expand Up @@ -728,17 +750,13 @@ func (swaggerLoader *SwaggerLoader) resolveLinkRef(swagger *Swagger, component *

component.Value = &link
} else {
components, id, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, prefix, path)
untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)
if err != nil {
return err
}
definitions := components.Links
if definitions == nil {
return failedToResolveRefFragmentPart(ref, "links")
}
resolved := definitions[id]
if resolved == nil {
return failedToResolveRefFragmentPart(ref, id)
resolved, ok := untypedResolved.(*LinkRef)
if !ok {
return failedToResolveRefFragment(ref)
}
if err := swaggerLoader.resolveLinkRef(swagger, resolved, componentPath); err != nil {
return err
Expand Down
61 changes: 61 additions & 0 deletions openapi3/swagger_loader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -490,3 +490,64 @@ paths:
require.Equal(t, "getUserById", link.OperationID)
require.Equal(t, "link to to the father", link.Description)
}
func TestResolveNonComponentsRef(t *testing.T) {
spec := []byte(`
openapi: 3.0.0
info:
title: An API
version: v1

components:
schemas:
NewItem:
required: [name]
properties:
name: {type: string}
tag: {type: string}
ErrorModel:
type: object
required: [code, message]
properties:
code: {type: integer}
message: {type: string}

paths:
/items:
put:
description: ''
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewItem'
responses:
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorModel'
post:
description: ''
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/paths/~1items/put/requestBody/content/application~1json/schema'
responses:
default:
description: unexpected error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorModel'
`)

loader := openapi3.NewSwaggerLoader()
doc, err := loader.LoadSwaggerFromData(spec)
require.NoError(t, err)
err = doc.Validate(loader.Context)
require.NoError(t, err)
}