validation.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. Copyright 2014 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 validation
  14. import (
  15. "fmt"
  16. "math"
  17. "regexp"
  18. "strings"
  19. "unicode"
  20. "k8s.io/apimachinery/pkg/api/validate/content"
  21. "k8s.io/apimachinery/pkg/util/validation/field"
  22. )
  23. // IsQualifiedName tests whether the value passed is what Kubernetes calls a
  24. // "qualified name". This is a format used in various places throughout the
  25. // system. If the value is not valid, a list of error strings is returned.
  26. // Otherwise an empty list (or nil) is returned.
  27. // Deprecated: Use k8s.io/apimachinery/pkg/api/validate/content.IsQualifiedName instead.
  28. var IsQualifiedName = content.IsLabelKey
  29. // IsFullyQualifiedName checks if the name is fully qualified. This is similar
  30. // to IsFullyQualifiedDomainName but requires a minimum of 3 segments instead of
  31. // 2 and does not accept a trailing . as valid.
  32. // TODO: This function is deprecated and preserved until all callers migrate to
  33. // IsFullyQualifiedDomainName; please don't add new callers.
  34. func IsFullyQualifiedName(fldPath *field.Path, name string) field.ErrorList {
  35. var allErrors field.ErrorList
  36. if len(name) == 0 {
  37. return append(allErrors, field.Required(fldPath, ""))
  38. }
  39. if errs := IsDNS1123Subdomain(name); len(errs) > 0 {
  40. return append(allErrors, field.Invalid(fldPath, name, strings.Join(errs, ",")))
  41. }
  42. if len(strings.Split(name, ".")) < 3 {
  43. return append(allErrors, field.Invalid(fldPath, name, "should be a domain with at least three segments separated by dots"))
  44. }
  45. return allErrors
  46. }
  47. // IsFullyQualifiedDomainName checks if the domain name is fully qualified. This
  48. // is similar to IsFullyQualifiedName but only requires a minimum of 2 segments
  49. // instead of 3 and accepts a trailing . as valid.
  50. func IsFullyQualifiedDomainName(fldPath *field.Path, name string) field.ErrorList {
  51. var allErrors field.ErrorList
  52. if len(name) == 0 {
  53. return append(allErrors, field.Required(fldPath, ""))
  54. }
  55. if strings.HasSuffix(name, ".") {
  56. name = name[:len(name)-1]
  57. }
  58. if errs := IsDNS1123Subdomain(name); len(errs) > 0 {
  59. return append(allErrors, field.Invalid(fldPath, name, strings.Join(errs, ",")))
  60. }
  61. if len(strings.Split(name, ".")) < 2 {
  62. return append(allErrors, field.Invalid(fldPath, name, "should be a domain with at least two segments separated by dots"))
  63. }
  64. for _, label := range strings.Split(name, ".") {
  65. if errs := IsDNS1123Label(label); len(errs) > 0 {
  66. return append(allErrors, field.Invalid(fldPath, label, strings.Join(errs, ",")))
  67. }
  68. }
  69. return allErrors
  70. }
  71. // Allowed characters in an HTTP Path as defined by RFC 3986. A HTTP path may
  72. // contain:
  73. // * unreserved characters (alphanumeric, '-', '.', '_', '~')
  74. // * percent-encoded octets
  75. // * sub-delims ("!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=")
  76. // * a colon character (":")
  77. const httpPathFmt string = `[A-Za-z0-9/\-._~%!$&'()*+,;=:]+`
  78. var httpPathRegexp = regexp.MustCompile("^" + httpPathFmt + "$")
  79. // IsDomainPrefixedPath checks if the given string is a domain-prefixed path
  80. // (e.g. acme.io/foo). All characters before the first "/" must be a valid
  81. // subdomain as defined by RFC 1123. All characters trailing the first "/" must
  82. // be valid HTTP Path characters as defined by RFC 3986.
  83. func IsDomainPrefixedPath(fldPath *field.Path, dpPath string) field.ErrorList {
  84. var allErrs field.ErrorList
  85. if len(dpPath) == 0 {
  86. return append(allErrs, field.Required(fldPath, ""))
  87. }
  88. segments := strings.SplitN(dpPath, "/", 2)
  89. if len(segments) != 2 || len(segments[0]) == 0 || len(segments[1]) == 0 {
  90. return append(allErrs, field.Invalid(fldPath, dpPath, "must be a domain-prefixed path (such as \"acme.io/foo\")"))
  91. }
  92. host := segments[0]
  93. for _, err := range IsDNS1123Subdomain(host) {
  94. allErrs = append(allErrs, field.Invalid(fldPath, host, err))
  95. }
  96. path := segments[1]
  97. if !httpPathRegexp.MatchString(path) {
  98. return append(allErrs, field.Invalid(fldPath, path, RegexError("Invalid path", httpPathFmt)))
  99. }
  100. return allErrs
  101. }
  102. // IsDomainPrefixedKey checks if the given key string is a domain-prefixed key
  103. // (e.g. acme.io/foo). All characters before the first "/" must be a valid
  104. // subdomain as defined by RFC 1123. All characters trailing the first "/" must
  105. // be non-empty and match the regex ^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$.
  106. func IsDomainPrefixedKey(fldPath *field.Path, key string) field.ErrorList {
  107. var allErrs field.ErrorList
  108. if len(key) == 0 {
  109. return append(allErrs, field.Required(fldPath, ""))
  110. }
  111. for _, errMessages := range content.IsLabelKey(key) {
  112. allErrs = append(allErrs, field.Invalid(fldPath, key, errMessages))
  113. }
  114. if len(allErrs) > 0 {
  115. return allErrs
  116. }
  117. segments := strings.Split(key, "/")
  118. if len(segments) != 2 {
  119. return append(allErrs, field.Invalid(fldPath, key, "must be a domain-prefixed key (such as \"acme.io/foo\")"))
  120. }
  121. return allErrs
  122. }
  123. // LabelValueMaxLength is a label's max length
  124. // Deprecated: Use k8s.io/apimachinery/pkg/api/validate/content.LabelValueMaxLength instead.
  125. const LabelValueMaxLength int = content.LabelValueMaxLength
  126. // IsValidLabelValue tests whether the value passed is a valid label value. If
  127. // the value is not valid, a list of error strings is returned. Otherwise an
  128. // empty list (or nil) is returned.
  129. // Deprecated: Use k8s.io/apimachinery/pkg/api/validate/content.IsLabelValue instead.
  130. var IsValidLabelValue = content.IsLabelValue
  131. const dns1123LabelFmt string = "[a-z0-9]([-a-z0-9]*[a-z0-9])?"
  132. const dns1123LabelFmtWithUnderscore string = "_?[a-z0-9]([-_a-z0-9]*[a-z0-9])?"
  133. const dns1123LabelErrMsg string = "a lowercase RFC 1123 label must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character"
  134. // DNS1123LabelMaxLength is a label's max length in DNS (RFC 1123)
  135. const DNS1123LabelMaxLength int = 63
  136. var dns1123LabelRegexp = regexp.MustCompile("^" + dns1123LabelFmt + "$")
  137. // IsDNS1123Label tests for a string that conforms to the definition of a label in
  138. // DNS (RFC 1123).
  139. func IsDNS1123Label(value string) []string {
  140. var errs []string
  141. if len(value) > DNS1123LabelMaxLength {
  142. errs = append(errs, MaxLenError(DNS1123LabelMaxLength))
  143. }
  144. if !dns1123LabelRegexp.MatchString(value) {
  145. if dns1123SubdomainRegexp.MatchString(value) {
  146. // It was a valid subdomain and not a valid label. Since we
  147. // already checked length, it must be dots.
  148. errs = append(errs, "must not contain dots")
  149. } else {
  150. errs = append(errs, RegexError(dns1123LabelErrMsg, dns1123LabelFmt, "my-name", "123-abc"))
  151. }
  152. }
  153. return errs
  154. }
  155. const dns1123SubdomainFmt string = dns1123LabelFmt + "(\\." + dns1123LabelFmt + ")*"
  156. const dns1123SubdomainErrorMsg string = "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character"
  157. const dns1123SubdomainFmtWithUnderscore string = dns1123LabelFmtWithUnderscore + "(\\." + dns1123LabelFmtWithUnderscore + ")*"
  158. const dns1123SubdomainErrorMsgFG string = "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '_', '-' or '.', and must start and end with an alphanumeric character"
  159. // DNS1123SubdomainMaxLength is a subdomain's max length in DNS (RFC 1123)
  160. const DNS1123SubdomainMaxLength int = 253
  161. var dns1123SubdomainRegexp = regexp.MustCompile("^" + dns1123SubdomainFmt + "$")
  162. var dns1123SubdomainRegexpWithUnderscore = regexp.MustCompile("^" + dns1123SubdomainFmtWithUnderscore + "$")
  163. // IsDNS1123Subdomain tests for a string that conforms to the definition of a
  164. // subdomain in DNS (RFC 1123).
  165. func IsDNS1123Subdomain(value string) []string {
  166. var errs []string
  167. if len(value) > DNS1123SubdomainMaxLength {
  168. errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))
  169. }
  170. if !dns1123SubdomainRegexp.MatchString(value) {
  171. errs = append(errs, RegexError(dns1123SubdomainErrorMsg, dns1123SubdomainFmt, "example.com"))
  172. }
  173. return errs
  174. }
  175. // IsDNS1123SubdomainWithUnderscore tests for a string that conforms to the definition of a
  176. // subdomain in DNS (RFC 1123), but allows the use of an underscore in the string
  177. func IsDNS1123SubdomainWithUnderscore(value string) []string {
  178. var errs []string
  179. if len(value) > DNS1123SubdomainMaxLength {
  180. errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))
  181. }
  182. if !dns1123SubdomainRegexpWithUnderscore.MatchString(value) {
  183. errs = append(errs, RegexError(dns1123SubdomainErrorMsgFG, dns1123SubdomainFmtWithUnderscore, "example.com"))
  184. }
  185. return errs
  186. }
  187. const dns1035LabelFmt string = "[a-z]([-a-z0-9]*[a-z0-9])?"
  188. const dns1035LabelErrMsg string = "a DNS-1035 label must consist of lower case alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character"
  189. // DNS1035LabelMaxLength is a label's max length in DNS (RFC 1035)
  190. const DNS1035LabelMaxLength int = 63
  191. var dns1035LabelRegexp = regexp.MustCompile("^" + dns1035LabelFmt + "$")
  192. // IsDNS1035Label tests for a string that conforms to the definition of a label in
  193. // DNS (RFC 1035).
  194. func IsDNS1035Label(value string) []string {
  195. var errs []string
  196. if len(value) > DNS1035LabelMaxLength {
  197. errs = append(errs, MaxLenError(DNS1035LabelMaxLength))
  198. }
  199. if !dns1035LabelRegexp.MatchString(value) {
  200. errs = append(errs, RegexError(dns1035LabelErrMsg, dns1035LabelFmt, "my-name", "abc-123"))
  201. }
  202. return errs
  203. }
  204. // wildcard definition - RFC 1034 section 4.3.3.
  205. // examples:
  206. // - valid: *.bar.com, *.foo.bar.com
  207. // - invalid: *.*.bar.com, *.foo.*.com, *bar.com, f*.bar.com, *
  208. const wildcardDNS1123SubdomainFmt = "\\*\\." + dns1123SubdomainFmt
  209. const wildcardDNS1123SubdomainErrMsg = "a wildcard DNS-1123 subdomain must start with '*.', followed by a valid DNS subdomain, which must consist of lower case alphanumeric characters, '-' or '.' and end with an alphanumeric character"
  210. // IsWildcardDNS1123Subdomain tests for a string that conforms to the definition of a
  211. // wildcard subdomain in DNS (RFC 1034 section 4.3.3).
  212. func IsWildcardDNS1123Subdomain(value string) []string {
  213. wildcardDNS1123SubdomainRegexp := regexp.MustCompile("^" + wildcardDNS1123SubdomainFmt + "$")
  214. var errs []string
  215. if len(value) > DNS1123SubdomainMaxLength {
  216. errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))
  217. }
  218. if !wildcardDNS1123SubdomainRegexp.MatchString(value) {
  219. errs = append(errs, RegexError(wildcardDNS1123SubdomainErrMsg, wildcardDNS1123SubdomainFmt, "*.example.com"))
  220. }
  221. return errs
  222. }
  223. // IsCIdentifier tests for a string that conforms the definition of an identifier
  224. // in C. This checks the format, but not the length.
  225. // Deprecated: Use k8s.io/apimachinery/pkg/api/validate/content.IsCIdentifier instead.
  226. var IsCIdentifier = content.IsCIdentifier
  227. // IsValidPortNum tests that the argument is a valid, non-zero port number.
  228. func IsValidPortNum(port int) []string {
  229. if 1 <= port && port <= 65535 {
  230. return nil
  231. }
  232. return []string{InclusiveRangeError(1, 65535)}
  233. }
  234. // IsInRange tests that the argument is in an inclusive range.
  235. func IsInRange(value int, min int, max int) []string {
  236. if value >= min && value <= max {
  237. return nil
  238. }
  239. return []string{InclusiveRangeError(min, max)}
  240. }
  241. // Now in libcontainer UID/GID limits is 0 ~ 1<<31 - 1
  242. // TODO: once we have a type for UID/GID we should make these that type.
  243. const (
  244. minUserID = 0
  245. maxUserID = math.MaxInt32
  246. minGroupID = 0
  247. maxGroupID = math.MaxInt32
  248. )
  249. // IsValidGroupID tests that the argument is a valid Unix GID.
  250. func IsValidGroupID(gid int64) []string {
  251. if minGroupID <= gid && gid <= maxGroupID {
  252. return nil
  253. }
  254. return []string{InclusiveRangeError(minGroupID, maxGroupID)}
  255. }
  256. // IsValidUserID tests that the argument is a valid Unix UID.
  257. func IsValidUserID(uid int64) []string {
  258. if minUserID <= uid && uid <= maxUserID {
  259. return nil
  260. }
  261. return []string{InclusiveRangeError(minUserID, maxUserID)}
  262. }
  263. var portNameCharsetRegex = regexp.MustCompile("^[-a-z0-9]+$")
  264. var portNameOneLetterRegexp = regexp.MustCompile("[a-z]")
  265. // IsValidPortName check that the argument is valid syntax. It must be
  266. // non-empty and no more than 15 characters long. It may contain only [-a-z0-9]
  267. // and must contain at least one letter [a-z]. It must not start or end with a
  268. // hyphen, nor contain adjacent hyphens.
  269. //
  270. // Note: We only allow lower-case characters, even though RFC 6335 is case
  271. // insensitive.
  272. func IsValidPortName(port string) []string {
  273. var errs []string
  274. if len(port) > 15 {
  275. errs = append(errs, MaxLenError(15))
  276. }
  277. if !portNameCharsetRegex.MatchString(port) {
  278. errs = append(errs, "must contain only alpha-numeric characters (a-z, 0-9), and hyphens (-)")
  279. }
  280. if !portNameOneLetterRegexp.MatchString(port) {
  281. errs = append(errs, "must contain at least one letter (a-z)")
  282. }
  283. if strings.Contains(port, "--") {
  284. errs = append(errs, "must not contain consecutive hyphens")
  285. }
  286. if len(port) > 0 && (port[0] == '-' || port[len(port)-1] == '-') {
  287. errs = append(errs, "must not begin or end with a hyphen")
  288. }
  289. return errs
  290. }
  291. const percentFmt string = "[0-9]+%"
  292. const percentErrMsg string = "a valid percent string must be a numeric string followed by an ending '%'"
  293. var percentRegexp = regexp.MustCompile("^" + percentFmt + "$")
  294. // IsValidPercent checks that string is in the form of a percentage
  295. func IsValidPercent(percent string) []string {
  296. if !percentRegexp.MatchString(percent) {
  297. return []string{RegexError(percentErrMsg, percentFmt, "1%", "93%")}
  298. }
  299. return nil
  300. }
  301. const httpHeaderNameFmt string = "[-A-Za-z0-9]+"
  302. const httpHeaderNameErrMsg string = "a valid HTTP header must consist of alphanumeric characters or '-'"
  303. var httpHeaderNameRegexp = regexp.MustCompile("^" + httpHeaderNameFmt + "$")
  304. // IsHTTPHeaderName checks that a string conforms to the Go HTTP library's
  305. // definition of a valid header field name (a stricter subset than RFC7230).
  306. func IsHTTPHeaderName(value string) []string {
  307. if !httpHeaderNameRegexp.MatchString(value) {
  308. return []string{RegexError(httpHeaderNameErrMsg, httpHeaderNameFmt, "X-Header-Name")}
  309. }
  310. return nil
  311. }
  312. const envVarNameFmt = "[-._a-zA-Z][-._a-zA-Z0-9]*"
  313. const envVarNameFmtErrMsg string = "a valid environment variable name must consist of alphabetic characters, digits, '_', '-', or '.', and must not start with a digit"
  314. // TODO(hirazawaui): Rename this when the RelaxedEnvironmentVariableValidation gate is removed.
  315. const relaxedEnvVarNameFmtErrMsg string = "a valid environment variable name must consist only of printable ASCII characters other than '='"
  316. var envVarNameRegexp = regexp.MustCompile("^" + envVarNameFmt + "$")
  317. // IsEnvVarName tests if a string is a valid environment variable name.
  318. func IsEnvVarName(value string) []string {
  319. var errs []string
  320. if !envVarNameRegexp.MatchString(value) {
  321. errs = append(errs, RegexError(envVarNameFmtErrMsg, envVarNameFmt, "my.env-name", "MY_ENV.NAME", "MyEnvName1"))
  322. }
  323. errs = append(errs, hasChDirPrefix(value)...)
  324. return errs
  325. }
  326. // IsRelaxedEnvVarName tests if a string is a valid environment variable name.
  327. func IsRelaxedEnvVarName(value string) []string {
  328. var errs []string
  329. if len(value) == 0 {
  330. errs = append(errs, "environment variable name "+EmptyError())
  331. }
  332. for _, r := range value {
  333. if r > unicode.MaxASCII || !unicode.IsPrint(r) || r == '=' {
  334. errs = append(errs, relaxedEnvVarNameFmtErrMsg)
  335. break
  336. }
  337. }
  338. return errs
  339. }
  340. const configMapKeyFmt = `[-._a-zA-Z0-9]+`
  341. const configMapKeyErrMsg string = "a valid config key must consist of alphanumeric characters, '-', '_' or '.'"
  342. var configMapKeyRegexp = regexp.MustCompile("^" + configMapKeyFmt + "$")
  343. // IsConfigMapKey tests for a string that is a valid key for a ConfigMap or Secret
  344. func IsConfigMapKey(value string) []string {
  345. var errs []string
  346. if len(value) > DNS1123SubdomainMaxLength {
  347. errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))
  348. }
  349. if !configMapKeyRegexp.MatchString(value) {
  350. errs = append(errs, RegexError(configMapKeyErrMsg, configMapKeyFmt, "key.name", "KEY_NAME", "key-name"))
  351. }
  352. errs = append(errs, hasChDirPrefix(value)...)
  353. return errs
  354. }
  355. // MaxLenError returns a string explanation of a "string too long" validation
  356. // failure.
  357. func MaxLenError(length int) string {
  358. return fmt.Sprintf("must be no more than %d characters", length)
  359. }
  360. // RegexError returns a string explanation of a regex validation failure.
  361. func RegexError(msg string, fmt string, examples ...string) string {
  362. if len(examples) == 0 {
  363. return msg + " (regex used for validation is '" + fmt + "')"
  364. }
  365. msg += " (e.g. "
  366. for i := range examples {
  367. if i > 0 {
  368. msg += " or "
  369. }
  370. msg += "'" + examples[i] + "', "
  371. }
  372. msg += "regex used for validation is '" + fmt + "')"
  373. return msg
  374. }
  375. // EmptyError returns a string explanation of a "must not be empty" validation
  376. // failure.
  377. func EmptyError() string {
  378. return "must be non-empty"
  379. }
  380. // InclusiveRangeError returns a string explanation of a numeric "must be
  381. // between" validation failure.
  382. func InclusiveRangeError(lo, hi int) string {
  383. return fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi)
  384. }
  385. func hasChDirPrefix(value string) []string {
  386. var errs []string
  387. switch {
  388. case value == ".":
  389. errs = append(errs, `must not be '.'`)
  390. case value == "..":
  391. errs = append(errs, `must not be '..'`)
  392. case strings.HasPrefix(value, ".."):
  393. errs = append(errs, `must not start with '..'`)
  394. }
  395. return errs
  396. }