schema_loader.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package spec
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "log"
  19. "net/url"
  20. "reflect"
  21. "strings"
  22. "github.com/go-openapi/swag"
  23. )
  24. // PathLoader function to use when loading remote refs
  25. var PathLoader func(string) (json.RawMessage, error)
  26. func init() {
  27. PathLoader = func(path string) (json.RawMessage, error) {
  28. data, err := swag.LoadFromFileOrHTTP(path)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return json.RawMessage(data), nil
  33. }
  34. }
  35. // resolverContext allows to share a context during spec processing.
  36. // At the moment, it just holds the index of circular references found.
  37. type resolverContext struct {
  38. // circulars holds all visited circular references, which allows shortcuts.
  39. // NOTE: this is not just a performance improvement: it is required to figure out
  40. // circular references which participate several cycles.
  41. // This structure is privately instantiated and needs not be locked against
  42. // concurrent access, unless we chose to implement a parallel spec walking.
  43. circulars map[string]bool
  44. basePath string
  45. }
  46. func newResolverContext(originalBasePath string) *resolverContext {
  47. return &resolverContext{
  48. circulars: make(map[string]bool),
  49. basePath: originalBasePath, // keep the root base path in context
  50. }
  51. }
  52. type schemaLoader struct {
  53. root interface{}
  54. options *ExpandOptions
  55. cache ResolutionCache
  56. context *resolverContext
  57. loadDoc func(string) (json.RawMessage, error)
  58. }
  59. func (r *schemaLoader) transitiveResolver(basePath string, ref Ref) (*schemaLoader, error) {
  60. if ref.IsRoot() || ref.HasFragmentOnly {
  61. return r, nil
  62. }
  63. baseRef, _ := NewRef(basePath)
  64. currentRef := normalizeFileRef(&ref, basePath)
  65. if strings.HasPrefix(currentRef.String(), baseRef.String()) {
  66. return r, nil
  67. }
  68. // Set a new root to resolve against
  69. rootURL := currentRef.GetURL()
  70. rootURL.Fragment = ""
  71. root, _ := r.cache.Get(rootURL.String())
  72. // shallow copy of resolver options to set a new RelativeBase when
  73. // traversing multiple documents
  74. newOptions := r.options
  75. newOptions.RelativeBase = rootURL.String()
  76. debugLog("setting new root: %s", newOptions.RelativeBase)
  77. resolver, err := defaultSchemaLoader(root, newOptions, r.cache, r.context)
  78. if err != nil {
  79. return nil, err
  80. }
  81. return resolver, nil
  82. }
  83. func (r *schemaLoader) updateBasePath(transitive *schemaLoader, basePath string) string {
  84. if transitive != r {
  85. debugLog("got a new resolver")
  86. if transitive.options != nil && transitive.options.RelativeBase != "" {
  87. basePath, _ = absPath(transitive.options.RelativeBase)
  88. debugLog("new basePath = %s", basePath)
  89. }
  90. }
  91. return basePath
  92. }
  93. func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string) error {
  94. tgt := reflect.ValueOf(target)
  95. if tgt.Kind() != reflect.Ptr {
  96. return fmt.Errorf("resolve ref: target needs to be a pointer")
  97. }
  98. refURL := ref.GetURL()
  99. if refURL == nil {
  100. return nil
  101. }
  102. var res interface{}
  103. var data interface{}
  104. var err error
  105. // Resolve against the root if it isn't nil, and if ref is pointing at the root, or has a fragment only which means
  106. // it is pointing somewhere in the root.
  107. root := r.root
  108. if (ref.IsRoot() || ref.HasFragmentOnly) && root == nil && basePath != "" {
  109. if baseRef, erb := NewRef(basePath); erb == nil {
  110. root, _, _, _ = r.load(baseRef.GetURL())
  111. }
  112. }
  113. if (ref.IsRoot() || ref.HasFragmentOnly) && root != nil {
  114. data = root
  115. } else {
  116. baseRef := normalizeFileRef(ref, basePath)
  117. debugLog("current ref is: %s", ref.String())
  118. debugLog("current ref normalized file: %s", baseRef.String())
  119. data, _, _, err = r.load(baseRef.GetURL())
  120. if err != nil {
  121. return err
  122. }
  123. }
  124. res = data
  125. if ref.String() != "" {
  126. res, _, err = ref.GetPointer().Get(data)
  127. if err != nil {
  128. return err
  129. }
  130. }
  131. return swag.DynamicJSONToStruct(res, target)
  132. }
  133. func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) {
  134. debugLog("loading schema from url: %s", refURL)
  135. toFetch := *refURL
  136. toFetch.Fragment = ""
  137. normalized := normalizeAbsPath(toFetch.String())
  138. data, fromCache := r.cache.Get(normalized)
  139. if !fromCache {
  140. b, err := r.loadDoc(normalized)
  141. if err != nil {
  142. return nil, url.URL{}, false, err
  143. }
  144. if err := json.Unmarshal(b, &data); err != nil {
  145. return nil, url.URL{}, false, err
  146. }
  147. r.cache.Set(normalized, data)
  148. }
  149. return data, toFetch, fromCache, nil
  150. }
  151. // isCircular detects cycles in sequences of $ref.
  152. // It relies on a private context (which needs not be locked).
  153. func (r *schemaLoader) isCircular(ref *Ref, basePath string, parentRefs ...string) (foundCycle bool) {
  154. normalizedRef := normalizePaths(ref.String(), basePath)
  155. if _, ok := r.context.circulars[normalizedRef]; ok {
  156. // circular $ref has been already detected in another explored cycle
  157. foundCycle = true
  158. return
  159. }
  160. foundCycle = swag.ContainsStringsCI(parentRefs, normalizedRef)
  161. if foundCycle {
  162. r.context.circulars[normalizedRef] = true
  163. }
  164. return
  165. }
  166. // Resolve resolves a reference against basePath and stores the result in target
  167. // Resolve is not in charge of following references, it only resolves ref by following its URL
  168. // if the schema that ref is referring to has more refs in it. Resolve doesn't resolve them
  169. // if basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct
  170. func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error {
  171. return r.resolveRef(ref, target, basePath)
  172. }
  173. func (r *schemaLoader) deref(input interface{}, parentRefs []string, basePath string) error {
  174. var ref *Ref
  175. switch refable := input.(type) {
  176. case *Schema:
  177. ref = &refable.Ref
  178. case *Parameter:
  179. ref = &refable.Ref
  180. case *Response:
  181. ref = &refable.Ref
  182. case *PathItem:
  183. ref = &refable.Ref
  184. default:
  185. return fmt.Errorf("deref: unsupported type %T", input)
  186. }
  187. curRef := ref.String()
  188. if curRef != "" {
  189. normalizedRef := normalizeFileRef(ref, basePath)
  190. normalizedBasePath := normalizedRef.RemoteURI()
  191. if r.isCircular(normalizedRef, basePath, parentRefs...) {
  192. return nil
  193. }
  194. if err := r.resolveRef(ref, input, basePath); r.shouldStopOnError(err) {
  195. return err
  196. }
  197. // NOTE(fredbi): removed basePath check => needs more testing
  198. if ref.String() != "" && ref.String() != curRef {
  199. parentRefs = append(parentRefs, normalizedRef.String())
  200. return r.deref(input, parentRefs, normalizedBasePath)
  201. }
  202. }
  203. return nil
  204. }
  205. func (r *schemaLoader) shouldStopOnError(err error) bool {
  206. if err != nil && !r.options.ContinueOnError {
  207. return true
  208. }
  209. if err != nil {
  210. log.Println(err)
  211. }
  212. return false
  213. }
  214. func defaultSchemaLoader(
  215. root interface{},
  216. expandOptions *ExpandOptions,
  217. cache ResolutionCache,
  218. context *resolverContext) (*schemaLoader, error) {
  219. if cache == nil {
  220. cache = resCache
  221. }
  222. if expandOptions == nil {
  223. expandOptions = &ExpandOptions{}
  224. }
  225. absBase, _ := absPath(expandOptions.RelativeBase)
  226. if context == nil {
  227. context = newResolverContext(absBase)
  228. }
  229. return &schemaLoader{
  230. root: root,
  231. options: expandOptions,
  232. cache: cache,
  233. context: context,
  234. loadDoc: func(path string) (json.RawMessage, error) {
  235. debugLog("fetching document at %q", path)
  236. return PathLoader(path)
  237. },
  238. }, nil
  239. }