You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

279 lines
7.7 KiB

  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. var err error
  134. path := toFetch.String()
  135. if path == rootBase {
  136. path, err = absPath(rootBase)
  137. if err != nil {
  138. return nil, url.URL{}, false, err
  139. }
  140. }
  141. normalized := normalizeAbsPath(path)
  142. data, fromCache := r.cache.Get(normalized)
  143. if !fromCache {
  144. b, err := r.loadDoc(normalized)
  145. if err != nil {
  146. debugLog("unable to load the document: %v", err)
  147. return nil, url.URL{}, false, err
  148. }
  149. if err := json.Unmarshal(b, &data); err != nil {
  150. return nil, url.URL{}, false, err
  151. }
  152. r.cache.Set(normalized, data)
  153. }
  154. return data, toFetch, fromCache, nil
  155. }
  156. // isCircular detects cycles in sequences of $ref.
  157. // It relies on a private context (which needs not be locked).
  158. func (r *schemaLoader) isCircular(ref *Ref, basePath string, parentRefs ...string) (foundCycle bool) {
  159. normalizedRef := normalizePaths(ref.String(), basePath)
  160. if _, ok := r.context.circulars[normalizedRef]; ok {
  161. // circular $ref has been already detected in another explored cycle
  162. foundCycle = true
  163. return
  164. }
  165. foundCycle = swag.ContainsStringsCI(parentRefs, normalizedRef)
  166. if foundCycle {
  167. r.context.circulars[normalizedRef] = true
  168. }
  169. return
  170. }
  171. // Resolve resolves a reference against basePath and stores the result in target
  172. // Resolve is not in charge of following references, it only resolves ref by following its URL
  173. // if the schema that ref is referring to has more refs in it. Resolve doesn't resolve them
  174. // if basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct
  175. func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error {
  176. return r.resolveRef(ref, target, basePath)
  177. }
  178. func (r *schemaLoader) deref(input interface{}, parentRefs []string, basePath string) error {
  179. var ref *Ref
  180. switch refable := input.(type) {
  181. case *Schema:
  182. ref = &refable.Ref
  183. case *Parameter:
  184. ref = &refable.Ref
  185. case *Response:
  186. ref = &refable.Ref
  187. case *PathItem:
  188. ref = &refable.Ref
  189. default:
  190. return fmt.Errorf("deref: unsupported type %T", input)
  191. }
  192. curRef := ref.String()
  193. if curRef != "" {
  194. normalizedRef := normalizeFileRef(ref, basePath)
  195. normalizedBasePath := normalizedRef.RemoteURI()
  196. if r.isCircular(normalizedRef, basePath, parentRefs...) {
  197. return nil
  198. }
  199. if err := r.resolveRef(ref, input, basePath); r.shouldStopOnError(err) {
  200. return err
  201. }
  202. // NOTE(fredbi): removed basePath check => needs more testing
  203. if ref.String() != "" && ref.String() != curRef {
  204. parentRefs = append(parentRefs, normalizedRef.String())
  205. return r.deref(input, parentRefs, normalizedBasePath)
  206. }
  207. }
  208. return nil
  209. }
  210. func (r *schemaLoader) shouldStopOnError(err error) bool {
  211. if err != nil && !r.options.ContinueOnError {
  212. return true
  213. }
  214. if err != nil {
  215. log.Println(err)
  216. }
  217. return false
  218. }
  219. func defaultSchemaLoader(
  220. root interface{},
  221. expandOptions *ExpandOptions,
  222. cache ResolutionCache,
  223. context *resolverContext) (*schemaLoader, error) {
  224. if cache == nil {
  225. cache = resCache
  226. }
  227. if expandOptions == nil {
  228. expandOptions = &ExpandOptions{}
  229. }
  230. absBase, _ := absPath(expandOptions.RelativeBase)
  231. if context == nil {
  232. context = newResolverContext(absBase)
  233. }
  234. return &schemaLoader{
  235. root: root,
  236. options: expandOptions,
  237. cache: cache,
  238. context: context,
  239. loadDoc: func(path string) (json.RawMessage, error) {
  240. debugLog("fetching document at %q", path)
  241. return PathLoader(path)
  242. },
  243. }, nil
  244. }