schema_loader.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. return defaultSchemaLoader(root, newOptions, r.cache, r.context)
  78. }
  79. func (r *schemaLoader) updateBasePath(transitive *schemaLoader, basePath string) string {
  80. if transitive != r {
  81. debugLog("got a new resolver")
  82. if transitive.options != nil && transitive.options.RelativeBase != "" {
  83. basePath, _ = absPath(transitive.options.RelativeBase)
  84. debugLog("new basePath = %s", basePath)
  85. }
  86. }
  87. return basePath
  88. }
  89. func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string) error {
  90. tgt := reflect.ValueOf(target)
  91. if tgt.Kind() != reflect.Ptr {
  92. return fmt.Errorf("resolve ref: target needs to be a pointer")
  93. }
  94. refURL := ref.GetURL()
  95. if refURL == nil {
  96. return nil
  97. }
  98. var res interface{}
  99. var data interface{}
  100. var err error
  101. // Resolve against the root if it isn't nil, and if ref is pointing at the root, or has a fragment only which means
  102. // it is pointing somewhere in the root.
  103. root := r.root
  104. if (ref.IsRoot() || ref.HasFragmentOnly) && root == nil && basePath != "" {
  105. if baseRef, erb := NewRef(basePath); erb == nil {
  106. root, _, _, _ = r.load(baseRef.GetURL())
  107. }
  108. }
  109. if (ref.IsRoot() || ref.HasFragmentOnly) && root != nil {
  110. data = root
  111. } else {
  112. baseRef := normalizeFileRef(ref, basePath)
  113. debugLog("current ref is: %s", ref.String())
  114. debugLog("current ref normalized file: %s", baseRef.String())
  115. data, _, _, err = r.load(baseRef.GetURL())
  116. if err != nil {
  117. return err
  118. }
  119. }
  120. res = data
  121. if ref.String() != "" {
  122. res, _, err = ref.GetPointer().Get(data)
  123. if err != nil {
  124. return err
  125. }
  126. }
  127. return swag.DynamicJSONToStruct(res, target)
  128. }
  129. func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) {
  130. debugLog("loading schema from url: %s", refURL)
  131. toFetch := *refURL
  132. toFetch.Fragment = ""
  133. normalized := normalizeAbsPath(toFetch.String())
  134. data, fromCache := r.cache.Get(normalized)
  135. if !fromCache {
  136. b, err := r.loadDoc(normalized)
  137. if err != nil {
  138. debugLog("unable to load the document: %v", err)
  139. return nil, url.URL{}, false, err
  140. }
  141. if err := json.Unmarshal(b, &data); err != nil {
  142. return nil, url.URL{}, false, err
  143. }
  144. r.cache.Set(normalized, data)
  145. }
  146. return data, toFetch, fromCache, nil
  147. }
  148. // isCircular detects cycles in sequences of $ref.
  149. // It relies on a private context (which needs not be locked).
  150. func (r *schemaLoader) isCircular(ref *Ref, basePath string, parentRefs ...string) (foundCycle bool) {
  151. normalizedRef := normalizePaths(ref.String(), basePath)
  152. if _, ok := r.context.circulars[normalizedRef]; ok {
  153. // circular $ref has been already detected in another explored cycle
  154. foundCycle = true
  155. return
  156. }
  157. foundCycle = swag.ContainsStringsCI(parentRefs, normalizedRef)
  158. if foundCycle {
  159. r.context.circulars[normalizedRef] = true
  160. }
  161. return
  162. }
  163. // Resolve resolves a reference against basePath and stores the result in target
  164. // Resolve is not in charge of following references, it only resolves ref by following its URL
  165. // if the schema that ref is referring to has more refs in it. Resolve doesn't resolve them
  166. // if basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct
  167. func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error {
  168. return r.resolveRef(ref, target, basePath)
  169. }
  170. func (r *schemaLoader) deref(input interface{}, parentRefs []string, basePath string) error {
  171. var ref *Ref
  172. switch refable := input.(type) {
  173. case *Schema:
  174. ref = &refable.Ref
  175. case *Parameter:
  176. ref = &refable.Ref
  177. case *Response:
  178. ref = &refable.Ref
  179. case *PathItem:
  180. ref = &refable.Ref
  181. default:
  182. return fmt.Errorf("deref: unsupported type %T", input)
  183. }
  184. curRef := ref.String()
  185. if curRef != "" {
  186. normalizedRef := normalizeFileRef(ref, basePath)
  187. normalizedBasePath := normalizedRef.RemoteURI()
  188. if r.isCircular(normalizedRef, basePath, parentRefs...) {
  189. return nil
  190. }
  191. if err := r.resolveRef(ref, input, basePath); r.shouldStopOnError(err) {
  192. return err
  193. }
  194. // NOTE(fredbi): removed basePath check => needs more testing
  195. if ref.String() != "" && ref.String() != curRef {
  196. parentRefs = append(parentRefs, normalizedRef.String())
  197. return r.deref(input, parentRefs, normalizedBasePath)
  198. }
  199. }
  200. return nil
  201. }
  202. func (r *schemaLoader) shouldStopOnError(err error) bool {
  203. if err != nil && !r.options.ContinueOnError {
  204. return true
  205. }
  206. if err != nil {
  207. log.Println(err)
  208. }
  209. return false
  210. }
  211. func defaultSchemaLoader(
  212. root interface{},
  213. expandOptions *ExpandOptions,
  214. cache ResolutionCache,
  215. context *resolverContext) (*schemaLoader, error) {
  216. if cache == nil {
  217. cache = resCache
  218. }
  219. if expandOptions == nil {
  220. expandOptions = &ExpandOptions{}
  221. }
  222. absBase, _ := absPath(expandOptions.RelativeBase)
  223. if context == nil {
  224. context = newResolverContext(absBase)
  225. }
  226. return &schemaLoader{
  227. root: root,
  228. options: expandOptions,
  229. cache: cache,
  230. context: context,
  231. loadDoc: func(path string) (json.RawMessage, error) {
  232. debugLog("fetching document at %q", path)
  233. return PathLoader(path)
  234. },
  235. }, nil
  236. }