diff --git a/index/path_resolution.go b/index/path_resolution.go index d33d1e5f..278a9b99 100644 --- a/index/path_resolution.go +++ b/index/path_resolution.go @@ -44,6 +44,15 @@ func (index *SpecIndex) resolveRelativeFilePath(defRoot, ref string) string { } } + // 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 + } + } + // Prefer the configured BasePath if present and it yields an existing file. if index.config.BasePath != "" { baseAbs, _ := filepath.Abs(index.config.BasePath) @@ -73,6 +82,33 @@ func (index *SpecIndex) resolveRelativeFilePath(defRoot, ref string) string { return fallback } +// 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 { + rel, err := filepath.Rel(base, absPath) + if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { + return false + } + found = true + } + } + 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. 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 d8e695b1..2978f68a 100644 --- a/index/path_resolution_test.go +++ b/index/path_resolution_test.go @@ -232,3 +232,64 @@ 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) +} + +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 new file mode 100644 index 00000000..c9e749f5 --- /dev/null +++ b/issue735_test.go @@ -0,0 +1,130 @@ +// 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")) +} + +// 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) + }) + } +}