validation.go 18 KB

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