2
0

validation.go 18 KB

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