schema.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /*
  2. Copyright 2019 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 crd
  14. import (
  15. "fmt"
  16. "go/ast"
  17. "go/types"
  18. "strings"
  19. apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  20. crdmarkers "sigs.k8s.io/controller-tools/pkg/crd/markers"
  21. "sigs.k8s.io/controller-tools/pkg/loader"
  22. "sigs.k8s.io/controller-tools/pkg/markers"
  23. )
  24. // Schema flattening is done in a recursive mapping method.
  25. // Start reading at infoToSchema.
  26. const (
  27. // defPrefix is the prefix used to link to definitions in the OpenAPI schema.
  28. defPrefix = "#/definitions/"
  29. )
  30. var (
  31. // byteType is the types.Type for byte (see the types documention
  32. // for why we need to look this up in the Universe), saved
  33. // for quick comparison.
  34. byteType = types.Universe.Lookup("byte").Type()
  35. )
  36. // SchemaMarker is any marker that needs to modify the schema of the underlying type or field.
  37. type SchemaMarker interface {
  38. // ApplyToSchema is called after the rest of the schema for a given type
  39. // or field is generated, to modify the schema appropriately.
  40. ApplyToSchema(*apiext.JSONSchemaProps) error
  41. }
  42. // applyFirstMarker is applied before any other markers. It's a bit of a hack.
  43. type applyFirstMarker interface {
  44. ApplyFirst()
  45. }
  46. // schemaRequester knows how to marker that another schema (e.g. via an external reference) is necessary.
  47. type schemaRequester interface {
  48. NeedSchemaFor(typ TypeIdent)
  49. }
  50. // schemaContext stores and provides information across a hierarchy of schema generation.
  51. type schemaContext struct {
  52. pkg *loader.Package
  53. info *markers.TypeInfo
  54. schemaRequester schemaRequester
  55. PackageMarkers markers.MarkerValues
  56. allowDangerousTypes bool
  57. }
  58. // newSchemaContext constructs a new schemaContext for the given package and schema requester.
  59. // It must have type info added before use via ForInfo.
  60. func newSchemaContext(pkg *loader.Package, req schemaRequester, allowDangerousTypes bool) *schemaContext {
  61. pkg.NeedTypesInfo()
  62. return &schemaContext{
  63. pkg: pkg,
  64. schemaRequester: req,
  65. allowDangerousTypes: allowDangerousTypes,
  66. }
  67. }
  68. // ForInfo produces a new schemaContext with containing the same information
  69. // as this one, except with the given type information.
  70. func (c *schemaContext) ForInfo(info *markers.TypeInfo) *schemaContext {
  71. return &schemaContext{
  72. pkg: c.pkg,
  73. info: info,
  74. schemaRequester: c.schemaRequester,
  75. allowDangerousTypes: c.allowDangerousTypes,
  76. }
  77. }
  78. // requestSchema asks for the schema for a type in the package with the
  79. // given import path.
  80. func (c *schemaContext) requestSchema(pkgPath, typeName string) {
  81. pkg := c.pkg
  82. if pkgPath != "" {
  83. pkg = c.pkg.Imports()[pkgPath]
  84. }
  85. c.schemaRequester.NeedSchemaFor(TypeIdent{
  86. Package: pkg,
  87. Name: typeName,
  88. })
  89. }
  90. // infoToSchema creates a schema for the type in the given set of type information.
  91. func infoToSchema(ctx *schemaContext) *apiext.JSONSchemaProps {
  92. return typeToSchema(ctx, ctx.info.RawSpec.Type)
  93. }
  94. // applyMarkers applies schema markers to the given schema, respecting "apply first" markers.
  95. func applyMarkers(ctx *schemaContext, markerSet markers.MarkerValues, props *apiext.JSONSchemaProps, node ast.Node) {
  96. // apply "apply first" markers first...
  97. for _, markerValues := range markerSet {
  98. for _, markerValue := range markerValues {
  99. if _, isApplyFirst := markerValue.(applyFirstMarker); !isApplyFirst {
  100. continue
  101. }
  102. schemaMarker, isSchemaMarker := markerValue.(SchemaMarker)
  103. if !isSchemaMarker {
  104. continue
  105. }
  106. if err := schemaMarker.ApplyToSchema(props); err != nil {
  107. ctx.pkg.AddError(loader.ErrFromNode(err /* an okay guess */, node))
  108. }
  109. }
  110. }
  111. // ...then the rest of the markers
  112. for _, markerValues := range markerSet {
  113. for _, markerValue := range markerValues {
  114. if _, isApplyFirst := markerValue.(applyFirstMarker); isApplyFirst {
  115. // skip apply-first markers, which were already applied
  116. continue
  117. }
  118. schemaMarker, isSchemaMarker := markerValue.(SchemaMarker)
  119. if !isSchemaMarker {
  120. continue
  121. }
  122. if err := schemaMarker.ApplyToSchema(props); err != nil {
  123. ctx.pkg.AddError(loader.ErrFromNode(err /* an okay guess */, node))
  124. }
  125. }
  126. }
  127. }
  128. // typeToSchema creates a schema for the given AST type.
  129. func typeToSchema(ctx *schemaContext, rawType ast.Expr) *apiext.JSONSchemaProps {
  130. var props *apiext.JSONSchemaProps
  131. switch expr := rawType.(type) {
  132. case *ast.Ident:
  133. props = localNamedToSchema(ctx, expr)
  134. case *ast.SelectorExpr:
  135. props = namedToSchema(ctx, expr)
  136. case *ast.ArrayType:
  137. props = arrayToSchema(ctx, expr)
  138. case *ast.MapType:
  139. props = mapToSchema(ctx, expr)
  140. case *ast.StarExpr:
  141. props = typeToSchema(ctx, expr.X)
  142. case *ast.StructType:
  143. props = structToSchema(ctx, expr)
  144. default:
  145. ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("unsupported AST kind %T", expr), rawType))
  146. // NB(directxman12): we explicitly don't handle interfaces
  147. return &apiext.JSONSchemaProps{}
  148. }
  149. props.Description = ctx.info.Doc
  150. applyMarkers(ctx, ctx.info.Markers, props, rawType)
  151. return props
  152. }
  153. // qualifiedName constructs a JSONSchema-safe qualified name for a type
  154. // (`<typeName>` or `<safePkgPath>~0<typeName>`, where `<safePkgPath>`
  155. // is the package path with `/` replaced by `~1`, according to JSONPointer
  156. // escapes).
  157. func qualifiedName(pkgName, typeName string) string {
  158. if pkgName != "" {
  159. return strings.Replace(pkgName, "/", "~1", -1) + "~0" + typeName
  160. }
  161. return typeName
  162. }
  163. // TypeRefLink creates a definition link for the given type and package.
  164. func TypeRefLink(pkgName, typeName string) string {
  165. return defPrefix + qualifiedName(pkgName, typeName)
  166. }
  167. // localNamedToSchema creates a schema (ref) for a *potentially* local type reference
  168. // (could be external from a dot-import).
  169. func localNamedToSchema(ctx *schemaContext, ident *ast.Ident) *apiext.JSONSchemaProps {
  170. typeInfo := ctx.pkg.TypesInfo.TypeOf(ident)
  171. if typeInfo == types.Typ[types.Invalid] {
  172. ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("unknown type %s", ident.Name), ident))
  173. return &apiext.JSONSchemaProps{}
  174. }
  175. if basicInfo, isBasic := typeInfo.(*types.Basic); isBasic {
  176. typ, fmt, err := builtinToType(basicInfo, ctx.allowDangerousTypes)
  177. if err != nil {
  178. ctx.pkg.AddError(loader.ErrFromNode(err, ident))
  179. }
  180. return &apiext.JSONSchemaProps{
  181. Type: typ,
  182. Format: fmt,
  183. }
  184. }
  185. // NB(directxman12): if there are dot imports, this might be an external reference,
  186. // so use typechecking info to get the actual object
  187. typeNameInfo := typeInfo.(*types.Named).Obj()
  188. pkg := typeNameInfo.Pkg()
  189. pkgPath := loader.NonVendorPath(pkg.Path())
  190. if pkg == ctx.pkg.Types {
  191. pkgPath = ""
  192. }
  193. ctx.requestSchema(pkgPath, typeNameInfo.Name())
  194. link := TypeRefLink(pkgPath, typeNameInfo.Name())
  195. return &apiext.JSONSchemaProps{
  196. Ref: &link,
  197. }
  198. }
  199. // namedSchema creates a schema (ref) for an explicitly external type reference.
  200. func namedToSchema(ctx *schemaContext, named *ast.SelectorExpr) *apiext.JSONSchemaProps {
  201. typeInfoRaw := ctx.pkg.TypesInfo.TypeOf(named)
  202. if typeInfoRaw == types.Typ[types.Invalid] {
  203. ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("unknown type %v.%s", named.X, named.Sel.Name), named))
  204. return &apiext.JSONSchemaProps{}
  205. }
  206. typeInfo := typeInfoRaw.(*types.Named)
  207. typeNameInfo := typeInfo.Obj()
  208. nonVendorPath := loader.NonVendorPath(typeNameInfo.Pkg().Path())
  209. ctx.requestSchema(nonVendorPath, typeNameInfo.Name())
  210. link := TypeRefLink(nonVendorPath, typeNameInfo.Name())
  211. return &apiext.JSONSchemaProps{
  212. Ref: &link,
  213. }
  214. // NB(directxman12): we special-case things like resource.Quantity during the "collapse" phase.
  215. }
  216. // arrayToSchema creates a schema for the items of the given array, dealing appropriately
  217. // with the special `[]byte` type (according to OpenAPI standards).
  218. func arrayToSchema(ctx *schemaContext, array *ast.ArrayType) *apiext.JSONSchemaProps {
  219. eltType := ctx.pkg.TypesInfo.TypeOf(array.Elt)
  220. if eltType == byteType && array.Len == nil {
  221. // byte slices are represented as base64-encoded strings
  222. // (the format is defined in OpenAPI v3, but not JSON Schema)
  223. return &apiext.JSONSchemaProps{
  224. Type: "string",
  225. Format: "byte",
  226. }
  227. }
  228. // TODO(directxman12): backwards-compat would require access to markers from base info
  229. items := typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), array.Elt)
  230. return &apiext.JSONSchemaProps{
  231. Type: "array",
  232. Items: &apiext.JSONSchemaPropsOrArray{Schema: items},
  233. }
  234. }
  235. // mapToSchema creates a schema for items of the given map. Key types must eventually resolve
  236. // to string (other types aren't allowed by JSON, and thus the kubernetes API standards).
  237. func mapToSchema(ctx *schemaContext, mapType *ast.MapType) *apiext.JSONSchemaProps {
  238. keyInfo := ctx.pkg.TypesInfo.TypeOf(mapType.Key)
  239. // check that we've got a type that actually corresponds to a string
  240. for keyInfo != nil {
  241. switch typedKey := keyInfo.(type) {
  242. case *types.Basic:
  243. if typedKey.Info()&types.IsString == 0 {
  244. ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("map keys must be strings, not %s", keyInfo.String()), mapType.Key))
  245. return &apiext.JSONSchemaProps{}
  246. }
  247. keyInfo = nil // stop iterating
  248. case *types.Named:
  249. keyInfo = typedKey.Underlying()
  250. default:
  251. ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("map keys must be strings, not %s", keyInfo.String()), mapType.Key))
  252. return &apiext.JSONSchemaProps{}
  253. }
  254. }
  255. // TODO(directxman12): backwards-compat would require access to markers from base info
  256. var valSchema *apiext.JSONSchemaProps
  257. switch val := mapType.Value.(type) {
  258. case *ast.Ident:
  259. valSchema = localNamedToSchema(ctx.ForInfo(&markers.TypeInfo{}), val)
  260. case *ast.SelectorExpr:
  261. valSchema = namedToSchema(ctx.ForInfo(&markers.TypeInfo{}), val)
  262. case *ast.ArrayType:
  263. valSchema = arrayToSchema(ctx.ForInfo(&markers.TypeInfo{}), val)
  264. if valSchema.Type == "array" && valSchema.Items.Schema.Type != "string" {
  265. ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("map values must be a named type, not %T", mapType.Value), mapType.Value))
  266. return &apiext.JSONSchemaProps{}
  267. }
  268. case *ast.StarExpr:
  269. valSchema = typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), val)
  270. default:
  271. ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("map values must be a named type, not %T", mapType.Value), mapType.Value))
  272. return &apiext.JSONSchemaProps{}
  273. }
  274. return &apiext.JSONSchemaProps{
  275. Type: "object",
  276. AdditionalProperties: &apiext.JSONSchemaPropsOrBool{
  277. Schema: valSchema,
  278. Allows: true, /* set automatically by serialization, but useful for testing */
  279. },
  280. }
  281. }
  282. // structToSchema creates a schema for the given struct. Embedded fields are placed in AllOf,
  283. // and can be flattened later with a Flattener.
  284. func structToSchema(ctx *schemaContext, structType *ast.StructType) *apiext.JSONSchemaProps {
  285. props := &apiext.JSONSchemaProps{
  286. Type: "object",
  287. Properties: make(map[string]apiext.JSONSchemaProps),
  288. }
  289. if ctx.info.RawSpec.Type != structType {
  290. ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("encountered non-top-level struct (possibly embedded), those aren't allowed"), structType))
  291. return props
  292. }
  293. for _, field := range ctx.info.Fields {
  294. jsonTag, hasTag := field.Tag.Lookup("json")
  295. if !hasTag {
  296. // if the field doesn't have a JSON tag, it doesn't belong in output (and shouldn't exist in a serialized type)
  297. ctx.pkg.AddError(loader.ErrFromNode(fmt.Errorf("encountered struct field %q without JSON tag in type %q", field.Name, ctx.info.Name), field.RawField))
  298. continue
  299. }
  300. jsonOpts := strings.Split(jsonTag, ",")
  301. if len(jsonOpts) == 1 && jsonOpts[0] == "-" {
  302. // skipped fields have the tag "-" (note that "-," means the field is named "-")
  303. continue
  304. }
  305. inline := false
  306. omitEmpty := false
  307. for _, opt := range jsonOpts[1:] {
  308. switch opt {
  309. case "inline":
  310. inline = true
  311. case "omitempty":
  312. omitEmpty = true
  313. }
  314. }
  315. fieldName := jsonOpts[0]
  316. inline = inline || fieldName == "" // anonymous fields are inline fields in YAML/JSON
  317. // if no default required mode is set, default to required
  318. defaultMode := "required"
  319. if ctx.PackageMarkers.Get("kubebuilder:validation:Optional") != nil {
  320. defaultMode = "optional"
  321. }
  322. switch defaultMode {
  323. // if this package isn't set to optional default...
  324. case "required":
  325. // ...everything that's not inline, omitempty, or explicitly optional is required
  326. if !inline && !omitEmpty && field.Markers.Get("kubebuilder:validation:Optional") == nil && field.Markers.Get("optional") == nil {
  327. props.Required = append(props.Required, fieldName)
  328. }
  329. // if this package isn't set to required default...
  330. case "optional":
  331. // ...everything that isn't explicitly required is optional
  332. if field.Markers.Get("kubebuilder:validation:Required") != nil {
  333. props.Required = append(props.Required, fieldName)
  334. }
  335. }
  336. var propSchema *apiext.JSONSchemaProps
  337. if field.Markers.Get(crdmarkers.SchemalessName) != nil {
  338. propSchema = &apiext.JSONSchemaProps{}
  339. } else {
  340. propSchema = typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), field.RawField.Type)
  341. }
  342. propSchema.Description = field.Doc
  343. applyMarkers(ctx, field.Markers, propSchema, field.RawField)
  344. if inline {
  345. props.AllOf = append(props.AllOf, *propSchema)
  346. continue
  347. }
  348. props.Properties[fieldName] = *propSchema
  349. }
  350. return props
  351. }
  352. // builtinToType converts builtin basic types to their equivalent JSON schema form.
  353. // It *only* handles types allowed by the kubernetes API standards. Floats are not
  354. // allowed unless allowDangerousTypes is true
  355. func builtinToType(basic *types.Basic, allowDangerousTypes bool) (typ string, format string, err error) {
  356. // NB(directxman12): formats from OpenAPI v3 are slightly different than those defined
  357. // in JSONSchema. This'll use the OpenAPI v3 ones, since they're useful for bounding our
  358. // non-string types.
  359. basicInfo := basic.Info()
  360. switch {
  361. case basicInfo&types.IsBoolean != 0:
  362. typ = "boolean"
  363. case basicInfo&types.IsString != 0:
  364. typ = "string"
  365. case basicInfo&types.IsInteger != 0:
  366. typ = "integer"
  367. case basicInfo&types.IsFloat != 0 && allowDangerousTypes:
  368. typ = "number"
  369. default:
  370. // NB(directxman12): floats are *NOT* allowed in kubernetes APIs
  371. return "", "", fmt.Errorf("unsupported type %q", basic.String())
  372. }
  373. switch basic.Kind() {
  374. case types.Int32, types.Uint32:
  375. format = "int32"
  376. case types.Int64, types.Uint64:
  377. format = "int64"
  378. }
  379. return typ, format, nil
  380. }