common.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package common
  14. import (
  15. "net/http"
  16. "strings"
  17. "github.com/emicklei/go-restful/v3"
  18. "k8s.io/kube-openapi/pkg/spec3"
  19. "k8s.io/kube-openapi/pkg/validation/spec"
  20. )
  21. const (
  22. // TODO: Make this configurable.
  23. ExtensionPrefix = "x-kubernetes-"
  24. ExtensionV2Schema = ExtensionPrefix + "v2-schema"
  25. )
  26. // OpenAPIDefinition describes single type. Normally these definitions are auto-generated using gen-openapi.
  27. type OpenAPIDefinition struct {
  28. Schema spec.Schema
  29. Dependencies []string
  30. }
  31. type ReferenceCallback func(path string) spec.Ref
  32. // GetOpenAPIDefinitions is collection of all definitions.
  33. type GetOpenAPIDefinitions func(ReferenceCallback) map[string]OpenAPIDefinition
  34. // OpenAPIDefinitionGetter gets openAPI definitions for a given type. If a type implements this interface,
  35. // the definition returned by it will be used, otherwise the auto-generated definitions will be used. See
  36. // GetOpenAPITypeFormat for more information about trade-offs of using this interface or GetOpenAPITypeFormat method when
  37. // possible.
  38. type OpenAPIDefinitionGetter interface {
  39. OpenAPIDefinition() *OpenAPIDefinition
  40. }
  41. type OpenAPIV3DefinitionGetter interface {
  42. OpenAPIV3Definition() *OpenAPIDefinition
  43. }
  44. type PathHandler interface {
  45. Handle(path string, handler http.Handler)
  46. }
  47. type PathHandlerByGroupVersion interface {
  48. Handle(path string, handler http.Handler)
  49. HandlePrefix(path string, handler http.Handler)
  50. }
  51. // Config is set of configuration for openAPI spec generation.
  52. type Config struct {
  53. // List of supported protocols such as https, http, etc.
  54. ProtocolList []string
  55. // Info is general information about the API.
  56. Info *spec.Info
  57. // DefaultResponse will be used if an operation does not have any responses listed. It
  58. // will show up as ... "responses" : {"default" : $DefaultResponse} in the spec.
  59. DefaultResponse *spec.Response
  60. // ResponseDefinitions will be added to "responses" under the top-level swagger object. This is an object
  61. // that holds responses definitions that can be used across operations. This property does not define
  62. // global responses for all operations. For more info please refer:
  63. // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#fixed-fields
  64. ResponseDefinitions map[string]spec.Response
  65. // CommonResponses will be added as a response to all operation specs. This is a good place to add common
  66. // responses such as authorization failed.
  67. CommonResponses map[int]spec.Response
  68. // List of webservice's path prefixes to ignore
  69. IgnorePrefixes []string
  70. // OpenAPIDefinitions should provide definition for all models used by routes. Failure to provide this map
  71. // or any of the models will result in spec generation failure.
  72. GetDefinitions GetOpenAPIDefinitions
  73. // Provides the definition for all models used by routes. One of GetDefinitions or Definitions must be defined to generate a spec.
  74. // This takes precedent over the GetDefinitions function
  75. Definitions map[string]OpenAPIDefinition
  76. // GetOperationIDAndTags returns operation id and tags for a restful route. It is an optional function to customize operation IDs.
  77. //
  78. // Deprecated: GetOperationIDAndTagsFromRoute should be used instead. This cannot be specified if using the new Route
  79. // interface set of funcs.
  80. GetOperationIDAndTags func(r *restful.Route) (string, []string, error)
  81. // GetOperationIDAndTagsFromRoute returns operation id and tags for a Route. It is an optional function to customize operation IDs.
  82. GetOperationIDAndTagsFromRoute func(r Route) (string, []string, error)
  83. // GetDefinitionName returns a friendly name for a definition base on the serving path. parameter `name` is the full name of the definition.
  84. // It is an optional function to customize model names.
  85. GetDefinitionName func(name string) (string, spec.Extensions)
  86. // PostProcessSpec runs after the spec is ready to serve. It allows a final modification to the spec before serving.
  87. PostProcessSpec func(*spec.Swagger) (*spec.Swagger, error)
  88. // SecurityDefinitions is list of all security definitions for OpenAPI service. If this is not nil, the user of config
  89. // is responsible to provide DefaultSecurity and (maybe) add unauthorized response to CommonResponses.
  90. SecurityDefinitions *spec.SecurityDefinitions
  91. // DefaultSecurity for all operations. This will pass as spec.SwaggerProps.Security to OpenAPI.
  92. // For most cases, this will be list of acceptable definitions in SecurityDefinitions.
  93. DefaultSecurity []map[string][]string
  94. }
  95. // OpenAPIV3Config is set of configuration for OpenAPI V3 spec generation.
  96. type OpenAPIV3Config struct {
  97. // Info is general information about the API.
  98. Info *spec.Info
  99. // DefaultResponse will be used if an operation does not have any responses listed. It
  100. // will show up as ... "responses" : {"default" : $DefaultResponse} in the spec.
  101. DefaultResponse *spec3.Response
  102. // ResponseDefinitions will be added to responses component. This is an object
  103. // that holds responses that can be used across operations.
  104. ResponseDefinitions map[string]*spec3.Response
  105. // CommonResponses will be added as a response to all operation specs. This is a good place to add common
  106. // responses such as authorization failed.
  107. CommonResponses map[int]*spec3.Response
  108. // List of webservice's path prefixes to ignore
  109. IgnorePrefixes []string
  110. // OpenAPIDefinitions should provide definition for all models used by routes. Failure to provide this map
  111. // or any of the models will result in spec generation failure.
  112. // One of GetDefinitions or Definitions must be defined to generate a spec.
  113. GetDefinitions GetOpenAPIDefinitions
  114. // Provides the definition for all models used by routes. One of GetDefinitions or Definitions must be defined to generate a spec.
  115. // This takes precedent over the GetDefinitions function
  116. Definitions map[string]OpenAPIDefinition
  117. // GetOperationIDAndTags returns operation id and tags for a restful route. It is an optional function to customize operation IDs.
  118. //
  119. // Deprecated: GetOperationIDAndTagsFromRoute should be used instead. This cannot be specified if using the new Route
  120. // interface set of funcs.
  121. GetOperationIDAndTags func(r *restful.Route) (string, []string, error)
  122. // GetOperationIDAndTagsFromRoute returns operation id and tags for a Route. It is an optional function to customize operation IDs.
  123. GetOperationIDAndTagsFromRoute func(r Route) (string, []string, error)
  124. // GetDefinitionName returns a friendly name for a definition base on the serving path. parameter `name` is the full name of the definition.
  125. // It is an optional function to customize model names.
  126. GetDefinitionName func(name string) (string, spec.Extensions)
  127. // SecuritySchemes is list of all security schemes for OpenAPI service.
  128. SecuritySchemes spec3.SecuritySchemes
  129. // DefaultSecurity for all operations.
  130. DefaultSecurity []map[string][]string
  131. }
  132. type typeInfo struct {
  133. name string
  134. format string
  135. zero interface{}
  136. }
  137. var schemaTypeFormatMap = map[string]typeInfo{
  138. "uint": {"integer", "int32", 0.},
  139. "uint8": {"integer", "byte", 0.},
  140. "uint16": {"integer", "int32", 0.},
  141. "uint32": {"integer", "int64", 0.},
  142. "uint64": {"integer", "int64", 0.},
  143. "int": {"integer", "int32", 0.},
  144. "int8": {"integer", "byte", 0.},
  145. "int16": {"integer", "int32", 0.},
  146. "int32": {"integer", "int32", 0.},
  147. "int64": {"integer", "int64", 0.},
  148. "byte": {"integer", "byte", 0},
  149. "float64": {"number", "double", 0.},
  150. "float32": {"number", "float", 0.},
  151. "bool": {"boolean", "", false},
  152. "time.Time": {"string", "date-time", ""},
  153. "string": {"string", "", ""},
  154. "integer": {"integer", "", 0.},
  155. "number": {"number", "", 0.},
  156. "boolean": {"boolean", "", false},
  157. "[]byte": {"string", "byte", ""}, // base64 encoded characters
  158. "interface{}": {"object", "", interface{}(nil)},
  159. }
  160. // This function is a reference for converting go (or any custom type) to a simple open API type,format pair. There are
  161. // two ways to customize spec for a type. If you add it here, a type will be converted to a simple type and the type
  162. // comment (the comment that is added before type definition) will be lost. The spec will still have the property
  163. // comment. The second way is to implement OpenAPIDefinitionGetter interface. That function can customize the spec (so
  164. // the spec does not need to be simple type,format) or can even return a simple type,format (e.g. IntOrString). For simple
  165. // type formats, the benefit of adding OpenAPIDefinitionGetter interface is to keep both type and property documentation.
  166. // Example:
  167. //
  168. // type Sample struct {
  169. // ...
  170. // // port of the server
  171. // port IntOrString
  172. // ...
  173. // }
  174. //
  175. // // IntOrString documentation...
  176. // type IntOrString { ... }
  177. //
  178. // Adding IntOrString to this function:
  179. //
  180. // "port" : {
  181. // format: "string",
  182. // type: "int-or-string",
  183. // Description: "port of the server"
  184. // }
  185. //
  186. // Implement OpenAPIDefinitionGetter for IntOrString:
  187. //
  188. // "port" : {
  189. // $Ref: "#/definitions/IntOrString"
  190. // Description: "port of the server"
  191. // }
  192. //
  193. // ...
  194. // definitions:
  195. //
  196. // {
  197. // "IntOrString": {
  198. // format: "string",
  199. // type: "int-or-string",
  200. // Description: "IntOrString documentation..." // new
  201. // }
  202. // }
  203. func OpenAPITypeFormat(typeName string) (string, string) {
  204. mapped, ok := schemaTypeFormatMap[typeName]
  205. if !ok {
  206. return "", ""
  207. }
  208. return mapped.name, mapped.format
  209. }
  210. // Returns the zero-value for the given type along with true if the type
  211. // could be found.
  212. func OpenAPIZeroValue(typeName string) (interface{}, bool) {
  213. mapped, ok := schemaTypeFormatMap[typeName]
  214. if !ok {
  215. return nil, false
  216. }
  217. return mapped.zero, true
  218. }
  219. func EscapeJsonPointer(p string) string {
  220. // Escaping reference name using rfc6901
  221. p = strings.Replace(p, "~", "~0", -1)
  222. p = strings.Replace(p, "/", "~1", -1)
  223. return p
  224. }
  225. func EmbedOpenAPIDefinitionIntoV2Extension(main OpenAPIDefinition, embedded OpenAPIDefinition) OpenAPIDefinition {
  226. if main.Schema.Extensions == nil {
  227. main.Schema.Extensions = make(map[string]interface{})
  228. }
  229. main.Schema.Extensions[ExtensionV2Schema] = embedded.Schema
  230. return main
  231. }
  232. // GenerateOpenAPIV3OneOfSchema generate the set of schemas that MUST be assigned to SchemaProps.OneOf
  233. func GenerateOpenAPIV3OneOfSchema(types []string) (oneOf []spec.Schema) {
  234. for _, t := range types {
  235. oneOf = append(oneOf, spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{t}}})
  236. }
  237. return
  238. }