Skip to content

lib doesn't resolve multi file spec #219

Closed

Description

@bitomaxsp

Hej. I tried to update from v0.12.x to latest and spotted that library can't properly resolve multifile spec.
I managed to debug it and found why, but i don't quite get how to fix it.

So the dir/file layout that will reproduce the issue is the following (I'll only cover relevant parts, not all spec):

./lib/openapi.yaml <- main spec 
./lib/resources/actions/endpoint.yaml <- endpoint description
./lib/shared/parameters.yaml  <- parameters that endpoint refers to using relative $ref

openapi.yaml:

....
paths:
  /actions:
    $ref: "resources/actions/endpoint.yaml"

endpoint.yaml:

post:
  operationId: post/actions
  summary: Action

...

  parameters:
    - $ref: "../../shared/parameters.yaml#/X-Sender-FBS"

parameters.yaml:

X-Sender-FBS:
  name: X-Sender-FBS
  in: header
  description: FBS ID of the unit sending the request.
  required: true
  schema:
    type: string
    nullable: true

So here is the line that is triggered: https://github.com/pb33f/libopenapi/blob/main/datamodel/low/extraction_functions.go#L118

abs, _ = filepath.Abs(filepath.Join(filepath.Dir(specPath), explodedRefValue[0]))

explodedRefValue[0] will hold file path component of the $ref, in our case relative path component. And it is relative to the current file.
But resolution happens relative specPath which is always openapi.yaml. So it actually can't find what it is looking for. :(

Activity

  1. daveshanley commented on Dec 14, 2023

    @daveshanley
    Member

    Hmm, ok, yeah this whole system was overhauled a month ago and it looks like there are still some small glitches here and there. We did slam this code through thousands of multi-file tests, some that were beyond nuts, but there are multiple places where this logic is built out.

    I will look into this ASAP, all the parts are there, something is just mis-aligned somewhere and this use case exposes it.

  2. added
    bug
    requires investigation
    on Dec 14, 2023
  3. yozel commented on Dec 18, 2023

    @yozel

    I'm not sure if this is the same issue, but I have encountered something similar.

    spec.yaml:

    openapi: 3.0.2
    info:
      title: "test"
      version: "0.0.1"
    paths: {}
    components:
      schemas:
        ExternalRef:
          $ref: "spec-ext.yaml#/components/schemas/Foo"

    spec-ext.yaml:

    openapi: 3.0.2
    info:
      title: "test"
      version: "0.0.1"
    paths: {}
    components:
      schemas:
        Foo:
          type: object
          properties:
            internalAttr:
              type: string
            externalAttr:
              $ref: "#/components/schemas/Bar"
        Bar:
          type: object
          properties:
            id:
              type: string
    

    With these two files, the following code returns an error:

    sp := model.Components.Schemas.Value("ExternalRef")
    schema, err := sp.BuildSchema()
    // err: schema properties build failed: cannot find reference #/components/schemas/Bar, line 14, col 17

    While this creates the schema without any errors:

    sp := model.Paths.PathItems.Value("/hello").Post.Responses.Codes.Value("200").Content.Value("application/json").Schema
    schema, err := sp.BuildSchema()

    I did some investigation and found out that lowbase.SchemaProxy.ctx doesn't have key value pair of index.CurrentPathKey, "<basedir>/spec-ext.yaml" when it's acquired from model.Components.Schemas.Value("ExternalRef").GoLow(), and extraction_functions.go uses this value to decide where to look for the file. Strangely enough, if Schema Proxy is acquired via model.Parameters...GoLow(), it has correct context value.

  4. yozel commented on Dec 18, 2023

    @yozel

    If it helps, here is the go tests I wrote yozel@4b9eb63

  5. daveshanley commented on Dec 18, 2023

    @daveshanley
    Member

    Hi @bitomaxsp,

    So I loaded this exact test into my testrig to locate the issue and I cannot re-create the problem.

    Screenshot 2023-12-18 at 9 02 48 AM

    openapi.yaml

    openapi: 3.1.0
    paths:
      /actions:
        $ref: "resources/actions/endpoint.yaml"

    resources/actions/endpoint.yaml

    post:
      operationId: post/actions
      summary: Action
    parameters:
      - $ref: "../../shared/parameters.yaml#/X-Sender-FBS"

    shared/parameters.yaml

    X-Sender-FBS:
      name: X-Sender-FBS
      in: header
      description: FBS ID of the unit sending the request.
      required: true
      schema:
        type: string
        nullable: true

    Then, I wrote the following code.

    package main
    
    import (
        "fmt"
        "log/slog"
        "os"
        "time"
    
        "github.com/pb33f/libopenapi"
        "github.com/pb33f/libopenapi/datamodel"
    )
    
    func readExploded() []byte {
        data, err := os.ReadFile("resolve_components_updated/openapi.yaml")
        if err != nil {
            panic(err)
        }
        return data
    }
    
    func main() {
        check()
    }
    
    func check() {
    
        start := time.Now()
        config := datamodel.DocumentConfiguration{
            IgnorePolymorphicCircularReferences: true,
            IgnoreArrayCircularReferences:       true,
            Logger: slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
                Level: slog.LevelDebug,
            })),
            BasePath: "resolve_components_updated/",
        }
    
        doc, err := libopenapi.NewDocumentWithConfiguration(readExploded(), &config)
        if err != nil {
            panic(err)
        }
    
        m, dErr := doc.BuildV3Model()
        if dErr != nil {
            panic(dErr)
        }
        if m != nil {
            fmt.Printf("model built\n")
        }
        end := time.Now()
        elapsed := end.Sub(start)
        fmt.Printf("done in %v\n", elapsed)
    
        // let's pull out the description of the parameters, this can only be done if the model
        // has correctly resolved.
    
        wanted := "FBS ID of the unit sending the request."
        got := m.Model.Paths.PathItems.GetOrZero("/actions").Parameters[0].Description
    
        if wanted != got {
            panic("wanted: " + wanted + " got: " + got)
        } else {
            fmt.Println("everything is good")
        }
    
    }

    What is the output?

    {"time":"2023-12-18T09:02:32.04447-05:00","level":"DEBUG","msg":"[rolodex file loader]: extracting file from OS","file":"/Users/daveshanley/pb33f/libopenapi-testrig/resolve_components/resources/actions/endpoint.yaml"}
    {"time":"2023-12-18T09:02:32.044642-05:00","level":"DEBUG","msg":"[rolodex file loader]: reading local file from OS","file":"/Users/daveshanley/pb33f/libopenapi-testrig/resolve_components/resources/actions/endpoint.yaml"}
    {"time":"2023-12-18T09:02:32.044799-05:00","level":"DEBUG","msg":"[rolodex file loader]: extracting file from OS","file":"/Users/daveshanley/pb33f/libopenapi-testrig/resolve_components/shared/parameters.yaml"}
    {"time":"2023-12-18T09:02:32.044804-05:00","level":"DEBUG","msg":"[rolodex file loader]: reading local file from OS","file":"/Users/daveshanley/pb33f/libopenapi-testrig/resolve_components/shared/parameters.yaml"}
    {"time":"2023-12-18T09:02:32.044972-05:00","level":"DEBUG","msg":"[rolodex file loader]: successfully loaded and indexed file","file":"/Users/daveshanley/pb33f/libopenapi-testrig/resolve_components/shared/parameters.yaml"}
    {"time":"2023-12-18T09:02:32.072306-05:00","level":"DEBUG","msg":"[rolodex file loader]: successfully loaded and indexed file","file":"/Users/daveshanley/pb33f/libopenapi-testrig/resolve_components/resources/actions/endpoint.yaml"}
    {"time":"2023-12-18T09:02:32.072393-05:00","level":"DEBUG","msg":"[rolodex] starting root index build"}
    {"time":"2023-12-18T09:02:32.072396-05:00","level":"DEBUG","msg":"[rolodex] root index build completed"}
    model built
    done in 29.210542ms
    everything is good

    This all resolves exactly as it should, you can see the rolodex under the covers is locating everything without issue and the
    resolved description matches exactly.

  6. daveshanley commented on Dec 18, 2023

    @daveshanley
    Member

    I'm not sure if this is the same issue, but I have encountered something similar.

    spec.yaml:

    openapi: 3.0.2
    info:
      title: "test"
      version: "0.0.1"
    paths: {}
    components:
      schemas:
        ExternalRef:
          $ref: "spec-ext.yaml#/components/schemas/Foo"

    spec-ext.yaml:

    openapi: 3.0.2
    info:
      title: "test"
      version: "0.0.1"
    paths: {}
    components:
      schemas:
        Foo:
          type: object
          properties:
            internalAttr:
              type: string
            externalAttr:
              $ref: "#/components/schemas/Bar"
        Bar:
          type: object
          properties:
            id:
              type: string

    With these two files, the following code returns an error:

    sp := model.Components.Schemas.Value("ExternalRef")
    schema, err := sp.BuildSchema()
    // err: schema properties build failed: cannot find reference #/components/schemas/Bar, line 14, col 17

    While this creates the schema without any errors:

    sp := model.Paths.PathItems.Value("/hello").Post.Responses.Codes.Value("200").Content.Value("application/json").Schema
    schema, err := sp.BuildSchema()

    I did some investigation and found out that lowbase.SchemaProxy.ctx doesn't have key value pair of index.CurrentPathKey, "<basedir>/spec-ext.yaml" when it's acquired from model.Components.Schemas.Value("ExternalRef").GoLow(), and extraction_functions.go uses this value to decide where to look for the file. Strangely enough, if Schema Proxy is acquired via model.Parameters...GoLow(), it has correct context value.

    This is actually a bug, you discovered a small edge case where schema builds were not carrying down context. I was able to replicate this issue, and located the problem.

  7. daveshanley commented on Dec 18, 2023

    @daveshanley
    Member

    @yozel If you try v0.14.1 you should see the result you're expecting now. This is my result when running against your specs

        start := time.Now()
        config := datamodel.DocumentConfiguration{
            Logger: slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
                Level: slog.LevelDebug,
            })),
            BasePath: "resolve_components_updated/",
        }
    
        doc, err := libopenapi.NewDocumentWithConfiguration(readExplodedAlt(), &config)
        if err != nil {
            panic(err)
        }
    
        m, dErr := doc.BuildV3Model()
        if dErr != nil {
            panic(dErr)
        }
        if m != nil {
            fmt.Printf("model built\n")
        }
        end := time.Now()
        elapsed := end.Sub(start)
        fmt.Printf("done in %v\n", elapsed)
    
        // let's pull out the property 'id' from 'Bar' which can only be reached unless everything
        // is fully resolved.
    
        wanted := "string"
        got := m.Model.Components.Schemas.GetOrZero("ExternalRef").
            Schema().Properties.GetOrZero("externalAttr").
            Schema().Properties.GetOrZero("id").
            Schema().Type[0]
    
        fmt.Printf("wanted: %v\n", wanted)
        fmt.Printf("got: %v\n", got)
    {"time":"2023-12-18T09:55:02.518305-05:00","level":"DEBUG","msg":"[rolodex file loader]: extracting file from OS","file":"/Users/daveshanley/pb33f/libopenapi-testrig/resolve_components_updated/spec-ext.yaml"}
    {"time":"2023-12-18T09:55:02.518468-05:00","level":"DEBUG","msg":"[rolodex file loader]: reading local file from OS","file":"/Users/daveshanley/pb33f/libopenapi-testrig/resolve_components_updated/spec-ext.yaml"}
    {"time":"2023-12-18T09:55:02.518799-05:00","level":"DEBUG","msg":"[rolodex file loader]: successfully loaded and indexed file","file":"/Users/daveshanley/pb33f/libopenapi-testrig/resolve_components_updated/spec-ext.yaml"}
    {"time":"2023-12-18T09:55:02.51886-05:00","level":"DEBUG","msg":"[rolodex] starting root index build"}
    {"time":"2023-12-18T09:55:02.518866-05:00","level":"DEBUG","msg":"[rolodex] root index build completed"}
    model built
    done in 1.863ms
    wanted: string
    got: string
    
  8. removed
    requires investigation
    on Dec 18, 2023
  9. yozel commented on Dec 18, 2023

    @yozel

    @daveshanley the issue is resolved. Thanks for the quick fix! I discovered it while I was trying to migrate https://github.com/deepmap/oapi-codegen into libopenapi, and now I the pull request there is complete without any failed tests

  10. added a commit that references this issue on Mar 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions