Skip to content
Open
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
36 changes: 36 additions & 0 deletions index/path_resolution.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This os.Stat runs on every call that gets past the first loop, and it shows up in a benchmark of resolveRelativeFilePath (main vs this branch, darwin/arm64, 8 runs, benchstat):

Case main PR Change
Sibling exists in a root 1.95µs, 6 allocs 1.97µs, 6 allocs none
Sibling missing in root, found under BasePath 4.18µs, 13 allocs 5.09µs, 16 allocs +22%
File outside roots, found under BasePath 2.92µs, 11 allocs 3.97µs, 14 allocs +36%
Missing everywhere 5.48µs, 21 allocs 6.79µs, 24 allocs +24%

In rows 2 and 4 fallback is inside an OS-backed root, so pathExistsInFS has already stat'd the same path in the loop above and failed. The second stat is a pure duplicate.

Please skip the stat when fallback is already inside an OS-backed root. I tried that locally and rows 2 and 4 went back to baseline. Row 3 keeps its one extra stat, which the fix needs.

return fallback
}
}

// Prefer the configured BasePath if present and it yields an existing file.
if index.config.BasePath != "" {
baseAbs, _ := filepath.Abs(index.config.BasePath)
Expand Down Expand Up @@ -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)
Expand Down
61 changes: 61 additions & 0 deletions index/path_resolution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
}
130 changes: 130 additions & 0 deletions issue735_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
}
Loading