validation.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 markers
  14. import (
  15. "fmt"
  16. "encoding/json"
  17. apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  18. "sigs.k8s.io/controller-tools/pkg/markers"
  19. )
  20. const (
  21. SchemalessName = "kubebuilder:validation:Schemaless"
  22. )
  23. // ValidationMarkers lists all available markers that affect CRD schema generation,
  24. // except for the few that don't make sense as type-level markers (see FieldOnlyMarkers).
  25. // All markers start with `+kubebuilder:validation:`, and continue with their type name.
  26. // A copy is produced of all markers that describes types as well, for making types
  27. // reusable and writing complex validations on slice items.
  28. var ValidationMarkers = mustMakeAllWithPrefix("kubebuilder:validation", markers.DescribesField,
  29. // integer markers
  30. Maximum(0),
  31. Minimum(0),
  32. ExclusiveMaximum(false),
  33. ExclusiveMinimum(false),
  34. MultipleOf(0),
  35. MinProperties(0),
  36. MaxProperties(0),
  37. // string markers
  38. MaxLength(0),
  39. MinLength(0),
  40. Pattern(""),
  41. // slice markers
  42. MaxItems(0),
  43. MinItems(0),
  44. UniqueItems(false),
  45. // general markers
  46. Enum(nil),
  47. Format(""),
  48. Type(""),
  49. XPreserveUnknownFields{},
  50. XEmbeddedResource{},
  51. )
  52. // FieldOnlyMarkers list field-specific validation markers (i.e. those markers that don't make
  53. // sense on a type, and thus aren't in ValidationMarkers).
  54. var FieldOnlyMarkers = []*definitionWithHelp{
  55. must(markers.MakeDefinition("kubebuilder:validation:Required", markers.DescribesField, struct{}{})).
  56. WithHelp(markers.SimpleHelp("CRD validation", "specifies that this field is required, if fields are optional by default.")),
  57. must(markers.MakeDefinition("kubebuilder:validation:Optional", markers.DescribesField, struct{}{})).
  58. WithHelp(markers.SimpleHelp("CRD validation", "specifies that this field is optional, if fields are required by default.")),
  59. must(markers.MakeDefinition("optional", markers.DescribesField, struct{}{})).
  60. WithHelp(markers.SimpleHelp("CRD validation", "specifies that this field is optional, if fields are required by default.")),
  61. must(markers.MakeDefinition("nullable", markers.DescribesField, Nullable{})).
  62. WithHelp(Nullable{}.Help()),
  63. must(markers.MakeAnyTypeDefinition("kubebuilder:default", markers.DescribesField, Default{})).
  64. WithHelp(Default{}.Help()),
  65. must(markers.MakeDefinition("kubebuilder:validation:EmbeddedResource", markers.DescribesField, XEmbeddedResource{})).
  66. WithHelp(XEmbeddedResource{}.Help()),
  67. must(markers.MakeDefinition(SchemalessName, markers.DescribesField, Schemaless{})).
  68. WithHelp(Schemaless{}.Help()),
  69. }
  70. // ValidationIshMarkers are field-and-type markers that don't fall under the
  71. // :validation: prefix, and/or don't have a name that directly matches their
  72. // type.
  73. var ValidationIshMarkers = []*definitionWithHelp{
  74. must(markers.MakeDefinition("kubebuilder:pruning:PreserveUnknownFields", markers.DescribesField, XPreserveUnknownFields{})).
  75. WithHelp(XPreserveUnknownFields{}.Help()),
  76. must(markers.MakeDefinition("kubebuilder:pruning:PreserveUnknownFields", markers.DescribesType, XPreserveUnknownFields{})).
  77. WithHelp(XPreserveUnknownFields{}.Help()),
  78. }
  79. func init() {
  80. AllDefinitions = append(AllDefinitions, ValidationMarkers...)
  81. for _, def := range ValidationMarkers {
  82. newDef := *def.Definition
  83. // copy both parts so we don't change the definition
  84. typDef := definitionWithHelp{
  85. Definition: &newDef,
  86. Help: def.Help,
  87. }
  88. typDef.Target = markers.DescribesType
  89. AllDefinitions = append(AllDefinitions, &typDef)
  90. }
  91. AllDefinitions = append(AllDefinitions, FieldOnlyMarkers...)
  92. AllDefinitions = append(AllDefinitions, ValidationIshMarkers...)
  93. }
  94. // +controllertools:marker:generateHelp:category="CRD validation"
  95. // Maximum specifies the maximum numeric value that this field can have.
  96. type Maximum int
  97. // +controllertools:marker:generateHelp:category="CRD validation"
  98. // Minimum specifies the minimum numeric value that this field can have. Negative integers are supported.
  99. type Minimum int
  100. // +controllertools:marker:generateHelp:category="CRD validation"
  101. // ExclusiveMinimum indicates that the minimum is "up to" but not including that value.
  102. type ExclusiveMinimum bool
  103. // +controllertools:marker:generateHelp:category="CRD validation"
  104. // ExclusiveMaximum indicates that the maximum is "up to" but not including that value.
  105. type ExclusiveMaximum bool
  106. // +controllertools:marker:generateHelp:category="CRD validation"
  107. // MultipleOf specifies that this field must have a numeric value that's a multiple of this one.
  108. type MultipleOf int
  109. // +controllertools:marker:generateHelp:category="CRD validation"
  110. // MaxLength specifies the maximum length for this string.
  111. type MaxLength int
  112. // +controllertools:marker:generateHelp:category="CRD validation"
  113. // MinLength specifies the minimum length for this string.
  114. type MinLength int
  115. // +controllertools:marker:generateHelp:category="CRD validation"
  116. // Pattern specifies that this string must match the given regular expression.
  117. type Pattern string
  118. // +controllertools:marker:generateHelp:category="CRD validation"
  119. // MaxItems specifies the maximum length for this list.
  120. type MaxItems int
  121. // +controllertools:marker:generateHelp:category="CRD validation"
  122. // MinItems specifies the minimun length for this list.
  123. type MinItems int
  124. // +controllertools:marker:generateHelp:category="CRD validation"
  125. // UniqueItems specifies that all items in this list must be unique.
  126. type UniqueItems bool
  127. // +controllertools:marker:generateHelp:category="CRD validation"
  128. // MaxProperties restricts the number of keys in an object
  129. type MaxProperties int
  130. // +controllertools:marker:generateHelp:category="CRD validation"
  131. // MinProperties restricts the number of keys in an object
  132. type MinProperties int
  133. // +controllertools:marker:generateHelp:category="CRD validation"
  134. // Enum specifies that this (scalar) field is restricted to the *exact* values specified here.
  135. type Enum []interface{}
  136. // +controllertools:marker:generateHelp:category="CRD validation"
  137. // Format specifies additional "complex" formatting for this field.
  138. //
  139. // For example, a date-time field would be marked as "type: string" and
  140. // "format: date-time".
  141. type Format string
  142. // +controllertools:marker:generateHelp:category="CRD validation"
  143. // Type overrides the type for this field (which defaults to the equivalent of the Go type).
  144. //
  145. // This generally must be paired with custom serialization. For example, the
  146. // metav1.Time field would be marked as "type: string" and "format: date-time".
  147. type Type string
  148. // +controllertools:marker:generateHelp:category="CRD validation"
  149. // Nullable marks this field as allowing the "null" value.
  150. //
  151. // This is often not necessary, but may be helpful with custom serialization.
  152. type Nullable struct{}
  153. // +controllertools:marker:generateHelp:category="CRD validation"
  154. // Default sets the default value for this field.
  155. //
  156. // A default value will be accepted as any value valid for the
  157. // field. Formatting for common types include: boolean: `true`, string:
  158. // `Cluster`, numerical: `1.24`, array: `{1,2}`, object: `{policy:
  159. // "delete"}`). Defaults should be defined in pruned form, and only best-effort
  160. // validation will be performed. Full validation of a default requires
  161. // submission of the containing CRD to an apiserver.
  162. type Default struct {
  163. Value interface{}
  164. }
  165. // +controllertools:marker:generateHelp:category="CRD processing"
  166. // PreserveUnknownFields stops the apiserver from pruning fields which are not specified.
  167. //
  168. // By default the apiserver drops unknown fields from the request payload
  169. // during the decoding step. This marker stops the API server from doing so.
  170. // It affects fields recursively, but switches back to normal pruning behaviour
  171. // if nested properties or additionalProperties are specified in the schema.
  172. // This can either be true or undefined. False
  173. // is forbidden.
  174. //
  175. // NB: The kubebuilder:validation:XPreserveUnknownFields variant is deprecated
  176. // in favor of the kubebuilder:pruning:PreserveUnknownFields variant. They function
  177. // identically.
  178. type XPreserveUnknownFields struct{}
  179. // +controllertools:marker:generateHelp:category="CRD validation"
  180. // EmbeddedResource marks a fields as an embedded resource with apiVersion, kind and metadata fields.
  181. //
  182. // An embedded resource is a value that has apiVersion, kind and metadata fields.
  183. // They are validated implicitly according to the semantics of the currently
  184. // running apiserver. It is not necessary to add any additional schema for these
  185. // field, yet it is possible. This can be combined with PreserveUnknownFields.
  186. type XEmbeddedResource struct{}
  187. // +controllertools:marker:generateHelp:category="CRD validation"
  188. // Schemaless marks a field as being a schemaless object.
  189. //
  190. // Schemaless objects are not introspected, so you must provide
  191. // any type and validation information yourself. One use for this
  192. // tag is for embedding fields that hold JSONSchema typed objects.
  193. // Because this field disables all type checking, it is recommended
  194. // to be used only as a last resort.
  195. type Schemaless struct{}
  196. func (m Maximum) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  197. if schema.Type != "integer" {
  198. return fmt.Errorf("must apply maximum to an integer")
  199. }
  200. val := float64(m)
  201. schema.Maximum = &val
  202. return nil
  203. }
  204. func (m Minimum) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  205. if schema.Type != "integer" {
  206. return fmt.Errorf("must apply minimum to an integer")
  207. }
  208. val := float64(m)
  209. schema.Minimum = &val
  210. return nil
  211. }
  212. func (m ExclusiveMaximum) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  213. if schema.Type != "integer" {
  214. return fmt.Errorf("must apply exclusivemaximum to an integer")
  215. }
  216. schema.ExclusiveMaximum = bool(m)
  217. return nil
  218. }
  219. func (m ExclusiveMinimum) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  220. if schema.Type != "integer" {
  221. return fmt.Errorf("must apply exclusiveminimum to an integer")
  222. }
  223. schema.ExclusiveMinimum = bool(m)
  224. return nil
  225. }
  226. func (m MultipleOf) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  227. if schema.Type != "integer" {
  228. return fmt.Errorf("must apply multipleof to an integer")
  229. }
  230. val := float64(m)
  231. schema.MultipleOf = &val
  232. return nil
  233. }
  234. func (m MaxLength) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  235. if schema.Type != "string" {
  236. return fmt.Errorf("must apply maxlength to a string")
  237. }
  238. val := int64(m)
  239. schema.MaxLength = &val
  240. return nil
  241. }
  242. func (m MinLength) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  243. if schema.Type != "string" {
  244. return fmt.Errorf("must apply minlength to a string")
  245. }
  246. val := int64(m)
  247. schema.MinLength = &val
  248. return nil
  249. }
  250. func (m Pattern) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  251. if schema.Type != "string" {
  252. return fmt.Errorf("must apply pattern to a string")
  253. }
  254. schema.Pattern = string(m)
  255. return nil
  256. }
  257. func (m MaxItems) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  258. if schema.Type != "array" {
  259. return fmt.Errorf("must apply maxitem to an array")
  260. }
  261. val := int64(m)
  262. schema.MaxItems = &val
  263. return nil
  264. }
  265. func (m MinItems) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  266. if schema.Type != "array" {
  267. return fmt.Errorf("must apply minitems to an array")
  268. }
  269. val := int64(m)
  270. schema.MinItems = &val
  271. return nil
  272. }
  273. func (m UniqueItems) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  274. if schema.Type != "array" {
  275. return fmt.Errorf("must apply uniqueitems to an array")
  276. }
  277. schema.UniqueItems = bool(m)
  278. return nil
  279. }
  280. func (m MinProperties) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  281. if schema.Type != "object" {
  282. return fmt.Errorf("must apply minproperties to an object")
  283. }
  284. val := int64(m)
  285. schema.MinProperties = &val
  286. return nil
  287. }
  288. func (m MaxProperties) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  289. if schema.Type != "object" {
  290. return fmt.Errorf("must apply maxproperties to an object")
  291. }
  292. val := int64(m)
  293. schema.MaxProperties = &val
  294. return nil
  295. }
  296. func (m Enum) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  297. // TODO(directxman12): this is a bit hacky -- we should
  298. // probably support AnyType better + using the schema structure
  299. vals := make([]apiext.JSON, len(m))
  300. for i, val := range m {
  301. // TODO(directxman12): check actual type with schema type?
  302. // if we're expecting a string, marshal the string properly...
  303. // NB(directxman12): we use json.Marshal to ensure we handle JSON escaping properly
  304. valMarshalled, err := json.Marshal(val)
  305. if err != nil {
  306. return err
  307. }
  308. vals[i] = apiext.JSON{Raw: valMarshalled}
  309. }
  310. schema.Enum = vals
  311. return nil
  312. }
  313. func (m Format) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  314. schema.Format = string(m)
  315. return nil
  316. }
  317. // NB(directxman12): we "typecheck" on target schema properties here,
  318. // which means the "Type" marker *must* be applied first.
  319. // TODO(directxman12): find a less hacky way to do this
  320. // (we could preserve ordering of markers, but that feels bad in its own right).
  321. func (m Type) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  322. schema.Type = string(m)
  323. return nil
  324. }
  325. func (m Type) ApplyFirst() {}
  326. func (m Nullable) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  327. schema.Nullable = true
  328. return nil
  329. }
  330. // Defaults are only valid CRDs created with the v1 API
  331. func (m Default) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  332. marshalledDefault, err := json.Marshal(m.Value)
  333. if err != nil {
  334. return err
  335. }
  336. schema.Default = &apiext.JSON{Raw: marshalledDefault}
  337. return nil
  338. }
  339. func (m XPreserveUnknownFields) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  340. defTrue := true
  341. schema.XPreserveUnknownFields = &defTrue
  342. return nil
  343. }
  344. func (m XEmbeddedResource) ApplyToSchema(schema *apiext.JSONSchemaProps) error {
  345. schema.XEmbeddedResource = true
  346. return nil
  347. }