From 7851b5e17a9e3041d42f6ea4206d8b7d2c5a3374 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 26 Nov 2026 23:29:20 -0400 Subject: [PATCH 1/2] fix(index): resolve sibling refs of files outside BasePath A relative ref in a file outside every local file system root was rejected by pathExistsInFS even though the file exists next to it, so resolution fell back to BasePath and could pick a different document with the same name. Co-Authored-By: Claude Sonnet 5.5 --- index/path_resolution.go | 19 +++++++++ index/path_resolution_test.go | 37 +++++++++++++++++ issue735_test.go | 76 +++++++++++++++++++++++++++++++++++ 3 files changed, 132 insertions(+) create mode 100644 issue735_test.go diff --git a/index/path_resolution.go b/index/path_resolution.go index d33d1e5fc..6a50b524c 100644 --- a/index/path_resolution.go +++ b/index/path_resolution.go @@ -44,6 +44,14 @@ func (index *SpecIndex) resolveRelativeFilePath(defRoot, ref string) string { } } + // The current file may live outside every configured root. A file that exists next to it still + // wins over a file with the same relative name under BasePath or another root. + if filepath.IsAbs(defRoot) && index.hasOSFileSystem() { + if info, err := os.Stat(fallback); err == nil && !info.IsDir() { + return fallback + } + } + // Prefer the configured BasePath if present and it yields an existing file. if index.config.BasePath != "" { baseAbs, _ := filepath.Abs(index.config.BasePath) @@ -73,6 +81,17 @@ func (index *SpecIndex) resolveRelativeFilePath(defRoot, ref string) string { return fallback } +// hasOSFileSystem reports whether any local file system reads straight from the operating system, +// and can therefore open absolute paths outside its base directory. +func (index *SpecIndex) hasOSFileSystem() bool { + for _, fsys := range index.rolodex.localFS { + if lfs, ok := fsys.(*LocalFS); ok && lfs.fsConfig != nil && lfs.fsConfig.DirFS == nil { + return true + } + } + return false +} + // ResolveRelativeFilePath is a public wrapper for resolving local file references. func (index *SpecIndex) ResolveRelativeFilePath(defRoot, ref string) string { return index.resolveRelativeFilePath(defRoot, ref) diff --git a/index/path_resolution_test.go b/index/path_resolution_test.go index d8e695b15..d41dab93f 100644 --- a/index/path_resolution_test.go +++ b/index/path_resolution_test.go @@ -232,3 +232,40 @@ func TestResolverResolveLocalRefPath(t *testing.T) { wantFallback, _ := filepath.Abs(utils.CheckPathOverlap("/base", "file.yaml", string(os.PathSeparator))) assert.Equal(t, wantFallback, gotFallback) } + +func TestResolveRelativeFilePath_SiblingOutsideRoots(t *testing.T) { + dir := t.TempDir() + base := filepath.Join(dir, "api") + other := filepath.Join(dir, "other") + for _, d := range []string{base, other} { + require.NoError(t, os.MkdirAll(d, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(d, "openapi.yaml"), []byte("type: object"), 0o600)) + } + + resolve := func(fsConfig *LocalFSConfig, defRoot string) string { + localFS, err := NewLocalFSWithConfig(fsConfig) + require.NoError(t, err) + + rolo := NewRolodex(CreateOpenAPIIndexConfig()) + rolo.AddLocalFS(base, localFS) + + cfg := CreateOpenAPIIndexConfig() + cfg.BasePath = base + idx := &SpecIndex{config: cfg, rolodex: rolo} + return idx.ResolveRelativeFilePath(defRoot, "openapi.yaml") + } + + // the OS file system can read the sibling, so it wins over BasePath. + got := resolve(&LocalFSConfig{BaseDirectory: base}, other) + assert.Equal(t, filepath.Join(other, "openapi.yaml"), got) + + // a virtual file system can't, so BasePath is still preferred. + virtual := fstest.MapFS{"openapi.yaml": {Data: []byte("type: object")}} + got = resolve(&LocalFSConfig{BaseDirectory: base, DirFS: virtual}, other) + assert.Equal(t, filepath.Join(base, "openapi.yaml"), got) + + // a relative defRoot says nothing about the current file, so the working directory doesn't win. + t.Chdir(other) + got = resolve(&LocalFSConfig{BaseDirectory: base}, ".") + assert.Equal(t, filepath.Join(base, "openapi.yaml"), got) +} diff --git a/issue735_test.go b/issue735_test.go new file mode 100644 index 000000000..0b2365951 --- /dev/null +++ b/issue735_test.go @@ -0,0 +1,76 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package libopenapi + +import ( + "os" + "path/filepath" + "testing" + + "github.com/pb33f/libopenapi/datamodel" + "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" +) + +// https://github.com/pb33f/libopenapi/issues/735 +func TestIssue735_RelativeRefOutsideBasePath(t *testing.T) { + dir := t.TempDir() + files := map[string]string{ + "api/openapi.yaml": `openapi: 3.0.3 +info: {title: root, version: '1'} +paths: + /events: + get: + responses: + '200': + description: ok + content: + application/json: + schema: + $ref: '../other/events.yaml#/components/schemas/Event' +`, + "other/events.yaml": `components: + schemas: + Event: + type: object + properties: + pet: + $ref: './openapi.yaml#/components/schemas/Pet' +`, + "other/openapi.yaml": `openapi: 3.0.3 +info: {title: other, version: '1'} +paths: {} +components: + schemas: + Pet: + type: object + properties: + name: {type: string} +`, + } + for name, content := range files { + path := filepath.Join(dir, filepath.FromSlash(name)) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) + } + + specPath := filepath.Join(dir, "api", "openapi.yaml") + spec, err := os.ReadFile(specPath) + require.NoError(t, err) + + doc, err := NewDocumentWithConfiguration(spec, &datamodel.DocumentConfiguration{ + SpecFilePath: specPath, + BasePath: filepath.Join(dir, "api"), + }) + require.NoError(t, err) + + model, err := doc.BuildV3Model() + require.NoError(t, err) + + media := model.Model.Paths.PathItems.GetOrZero("/events").Get.Responses.Codes. + GetOrZero("200").Content.GetOrZero("application/json") + pet := media.Schema.Schema().Properties.GetOrZero("pet").Schema() + require.NotNil(t, pet) + assert.NotNil(t, pet.Properties.GetOrZero("name")) +} From 6a71b8330bc1f95bb4b98ca8dd1fa410da305e13 Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 28 Nov 2026 16:44:28 -0400 Subject: [PATCH 2/2] fix(index): keep root refs on BasePath and skip duplicate stat The sibling check now applies only outside the root document's directory, and only stats paths that no OS file system root has already checked. Co-Authored-By: Claude Sonnet 5.5 --- index/path_resolution.go | 35 +++++++++++++++++------ index/path_resolution_test.go | 24 ++++++++++++++++ issue735_test.go | 54 +++++++++++++++++++++++++++++++++++ 3 files changed, 104 insertions(+), 9 deletions(-) diff --git a/index/path_resolution.go b/index/path_resolution.go index 6a50b524c..278a9b99c 100644 --- a/index/path_resolution.go +++ b/index/path_resolution.go @@ -44,9 +44,10 @@ func (index *SpecIndex) resolveRelativeFilePath(defRoot, ref string) string { } } - // The current file may live outside every configured root. A file that exists next to it still - // wins over a file with the same relative name under BasePath or another root. - if filepath.IsAbs(defRoot) && index.hasOSFileSystem() { + // A referenced file may live outside every configured root. A file that exists next to it still + // wins over a file with the same relative name under BasePath or another root. The root + // document's directory keeps preferring BasePath. + if filepath.IsAbs(defRoot) && index.canReadOutsideRoots(fallback) && !index.isRootDocumentDir(defRoot) { if info, err := os.Stat(fallback); err == nil && !info.IsDir() { return fallback } @@ -81,15 +82,31 @@ func (index *SpecIndex) resolveRelativeFilePath(defRoot, ref string) string { return fallback } -// hasOSFileSystem reports whether any local file system reads straight from the operating system, -// and can therefore open absolute paths outside its base directory. -func (index *SpecIndex) hasOSFileSystem() bool { - for _, fsys := range index.rolodex.localFS { +// canReadOutsideRoots reports whether absPath lies outside every local file system that reads +// straight from the operating system, while at least one such file system exists to open it. +// Paths inside one of those roots have already been checked by pathExistsInFS. +func (index *SpecIndex) canReadOutsideRoots(absPath string) bool { + found := false + for base, fsys := range index.rolodex.localFS { if lfs, ok := fsys.(*LocalFS); ok && lfs.fsConfig != nil && lfs.fsConfig.DirFS == nil { - return true + rel, err := filepath.Rel(base, absPath) + if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { + return false + } + found = true } } - return false + return found +} + +// isRootDocumentDir reports whether dir is the directory of the root specification. +func (index *SpecIndex) isRootDocumentDir(dir string) bool { + cfg := index.rolodex.indexConfig + if cfg == nil || cfg.SpecAbsolutePath == "" { + return false + } + root, _ := filepath.Abs(cfg.SpecAbsolutePath) + return filepath.Dir(root) == filepath.Clean(dir) } // ResolveRelativeFilePath is a public wrapper for resolving local file references. diff --git a/index/path_resolution_test.go b/index/path_resolution_test.go index d41dab93f..2978f68a9 100644 --- a/index/path_resolution_test.go +++ b/index/path_resolution_test.go @@ -269,3 +269,27 @@ func TestResolveRelativeFilePath_SiblingOutsideRoots(t *testing.T) { got = resolve(&LocalFSConfig{BaseDirectory: base}, ".") assert.Equal(t, filepath.Join(base, "openapi.yaml"), got) } + +func TestResolveRelativeFilePath_RootDocumentDir(t *testing.T) { + dir := t.TempDir() + base := filepath.Join(dir, "schemas") + require.NoError(t, os.MkdirAll(base, 0o755)) + for _, d := range []string{dir, base} { + require.NoError(t, os.WriteFile(filepath.Join(d, "common.yaml"), []byte("type: object"), 0o600)) + } + + localFS, err := NewLocalFSWithConfig(&LocalFSConfig{BaseDirectory: base}) + require.NoError(t, err) + + rootConfig := CreateOpenAPIIndexConfig() + rootConfig.SpecAbsolutePath = filepath.Join(dir, "spec.yaml") + rolo := NewRolodex(rootConfig) + rolo.AddLocalFS(base, localFS) + + cfg := CreateOpenAPIIndexConfig() + cfg.BasePath = base + idx := &SpecIndex{config: cfg, rolodex: rolo} + + // the root document's directory keeps preferring BasePath. + assert.Equal(t, filepath.Join(base, "common.yaml"), idx.ResolveRelativeFilePath(dir, "common.yaml")) +} diff --git a/issue735_test.go b/issue735_test.go index 0b2365951..c9e749f5e 100644 --- a/issue735_test.go +++ b/issue735_test.go @@ -74,3 +74,57 @@ components: require.NotNil(t, pet) assert.NotNil(t, pet.Properties.GetOrZero("name")) } + +// the root document's own refs keep preferring BasePath, however SpecFilePath is spelled. +func TestIssue735_RootDocumentPrefersBasePath(t *testing.T) { + dir := t.TempDir() + files := map[string]string{ + "spec.yaml": `openapi: 3.0.3 +info: {title: root, version: '1'} +paths: + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: + $ref: './common.yaml#/components/schemas/Pet' +`, + "common.yaml": `components: + schemas: + Pet: {type: object, description: next to the root spec} +`, + "schemas/common.yaml": `components: + schemas: + Pet: {type: object, description: under BasePath} +`, + } + for name, content := range files { + path := filepath.Join(dir, filepath.FromSlash(name)) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) + } + spec, err := os.ReadFile(filepath.Join(dir, "spec.yaml")) + require.NoError(t, err) + t.Chdir(dir) + + for name, config := range map[string]datamodel.DocumentConfiguration{ + "absolute": {SpecFilePath: filepath.Join(dir, "spec.yaml"), BasePath: filepath.Join(dir, "schemas")}, + "relative": {SpecFilePath: "spec.yaml", BasePath: "schemas"}, + } { + t.Run(name, func(t *testing.T) { + doc, err := NewDocumentWithConfiguration(spec, &config) + require.NoError(t, err) + + model, err := doc.BuildV3Model() + require.NoError(t, err) + + media := model.Model.Paths.PathItems.GetOrZero("/pets").Get.Responses.Codes. + GetOrZero("200").Content.GetOrZero("application/json") + require.NotNil(t, media.Schema.Schema()) + assert.Equal(t, "under BasePath", media.Schema.Schema().Description) + }) + } +}