schema.go 16 KB

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