validation.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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.
  63. func IsFullyQualifiedName(fldPath *field.Path, name string) field.ErrorList {
  64. var allErrors field.ErrorList
  65. if len(name) == 0 {
  66. return append(allErrors, field.Required(fldPath, ""))
  67. }
  68. if errs := IsDNS1123Subdomain(name); len(errs) > 0 {
  69. return append(allErrors, field.Invalid(fldPath, name, strings.Join(errs, ",")))
  70. }
  71. if len(strings.Split(name, ".")) < 3 {
  72. return append(allErrors, field.Invalid(fldPath, name, "should be a domain with at least three segments separated by dots"))
  73. }
  74. return allErrors
  75. }
  76. const labelValueFmt string = "(" + qualifiedNameFmt + ")?"
  77. 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"
  78. // LabelValueMaxLength is a label's max length
  79. const LabelValueMaxLength int = 63
  80. var labelValueRegexp = regexp.MustCompile("^" + labelValueFmt + "$")
  81. // IsValidLabelValue tests whether the value passed is a valid label value. If
  82. // the value is not valid, a list of error strings is returned. Otherwise an
  83. // empty list (or nil) is returned.
  84. func IsValidLabelValue(value string) []string {
  85. var errs []string
  86. if len(value) > LabelValueMaxLength {
  87. errs = append(errs, MaxLenError(LabelValueMaxLength))
  88. }
  89. if !labelValueRegexp.MatchString(value) {
  90. errs = append(errs, RegexError(labelValueErrMsg, labelValueFmt, "MyValue", "my_value", "12345"))
  91. }
  92. return errs
  93. }
  94. const dns1123LabelFmt string = "[a-z0-9]([-a-z0-9]*[a-z0-9])?"
  95. const dns1123LabelErrMsg string = "a DNS-1123 label must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character"
  96. // DNS1123LabelMaxLength is a label's max length in DNS (RFC 1123)
  97. const DNS1123LabelMaxLength int = 63
  98. var dns1123LabelRegexp = regexp.MustCompile("^" + dns1123LabelFmt + "$")
  99. // IsDNS1123Label tests for a string that conforms to the definition of a label in
  100. // DNS (RFC 1123).
  101. func IsDNS1123Label(value string) []string {
  102. var errs []string
  103. if len(value) > DNS1123LabelMaxLength {
  104. errs = append(errs, MaxLenError(DNS1123LabelMaxLength))
  105. }
  106. if !dns1123LabelRegexp.MatchString(value) {
  107. errs = append(errs, RegexError(dns1123LabelErrMsg, dns1123LabelFmt, "my-name", "123-abc"))
  108. }
  109. return errs
  110. }
  111. const dns1123SubdomainFmt string = dns1123LabelFmt + "(\\." + dns1123LabelFmt + ")*"
  112. const dns1123SubdomainErrorMsg string = "a DNS-1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character"
  113. // DNS1123SubdomainMaxLength is a subdomain's max length in DNS (RFC 1123)
  114. const DNS1123SubdomainMaxLength int = 253
  115. var dns1123SubdomainRegexp = regexp.MustCompile("^" + dns1123SubdomainFmt + "$")
  116. // IsDNS1123Subdomain tests for a string that conforms to the definition of a
  117. // subdomain in DNS (RFC 1123).
  118. func IsDNS1123Subdomain(value string) []string {
  119. var errs []string
  120. if len(value) > DNS1123SubdomainMaxLength {
  121. errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))
  122. }
  123. if !dns1123SubdomainRegexp.MatchString(value) {
  124. errs = append(errs, RegexError(dns1123SubdomainErrorMsg, dns1123SubdomainFmt, "example.com"))
  125. }
  126. return errs
  127. }
  128. const dns1035LabelFmt string = "[a-z]([-a-z0-9]*[a-z0-9])?"
  129. 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"
  130. // DNS1035LabelMaxLength is a label's max length in DNS (RFC 1035)
  131. const DNS1035LabelMaxLength int = 63
  132. var dns1035LabelRegexp = regexp.MustCompile("^" + dns1035LabelFmt + "$")
  133. // IsDNS1035Label tests for a string that conforms to the definition of a label in
  134. // DNS (RFC 1035).
  135. func IsDNS1035Label(value string) []string {
  136. var errs []string
  137. if len(value) > DNS1035LabelMaxLength {
  138. errs = append(errs, MaxLenError(DNS1035LabelMaxLength))
  139. }
  140. if !dns1035LabelRegexp.MatchString(value) {
  141. errs = append(errs, RegexError(dns1035LabelErrMsg, dns1035LabelFmt, "my-name", "abc-123"))
  142. }
  143. return errs
  144. }
  145. // wildcard definition - RFC 1034 section 4.3.3.
  146. // examples:
  147. // - valid: *.bar.com, *.foo.bar.com
  148. // - invalid: *.*.bar.com, *.foo.*.com, *bar.com, f*.bar.com, *
  149. const wildcardDNS1123SubdomainFmt = "\\*\\." + dns1123SubdomainFmt
  150. 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"
  151. // IsWildcardDNS1123Subdomain tests for a string that conforms to the definition of a
  152. // wildcard subdomain in DNS (RFC 1034 section 4.3.3).
  153. func IsWildcardDNS1123Subdomain(value string) []string {
  154. wildcardDNS1123SubdomainRegexp := regexp.MustCompile("^" + wildcardDNS1123SubdomainFmt + "$")
  155. var errs []string
  156. if len(value) > DNS1123SubdomainMaxLength {
  157. errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))
  158. }
  159. if !wildcardDNS1123SubdomainRegexp.MatchString(value) {
  160. errs = append(errs, RegexError(wildcardDNS1123SubdomainErrMsg, wildcardDNS1123SubdomainFmt, "*.example.com"))
  161. }
  162. return errs
  163. }
  164. const cIdentifierFmt string = "[A-Za-z_][A-Za-z0-9_]*"
  165. const identifierErrMsg string = "a valid C identifier must start with alphabetic character or '_', followed by a string of alphanumeric characters or '_'"
  166. var cIdentifierRegexp = regexp.MustCompile("^" + cIdentifierFmt + "$")
  167. // IsCIdentifier tests for a string that conforms the definition of an identifier
  168. // in C. This checks the format, but not the length.
  169. func IsCIdentifier(value string) []string {
  170. if !cIdentifierRegexp.MatchString(value) {
  171. return []string{RegexError(identifierErrMsg, cIdentifierFmt, "my_name", "MY_NAME", "MyName")}
  172. }
  173. return nil
  174. }
  175. // IsValidPortNum tests that the argument is a valid, non-zero port number.
  176. func IsValidPortNum(port int) []string {
  177. if 1 <= port && port <= 65535 {
  178. return nil
  179. }
  180. return []string{InclusiveRangeError(1, 65535)}
  181. }
  182. // IsInRange tests that the argument is in an inclusive range.
  183. func IsInRange(value int, min int, max int) []string {
  184. if value >= min && value <= max {
  185. return nil
  186. }
  187. return []string{InclusiveRangeError(min, max)}
  188. }
  189. // Now in libcontainer UID/GID limits is 0 ~ 1<<31 - 1
  190. // TODO: once we have a type for UID/GID we should make these that type.
  191. const (
  192. minUserID = 0
  193. maxUserID = math.MaxInt32
  194. minGroupID = 0
  195. maxGroupID = math.MaxInt32
  196. )
  197. // IsValidGroupID tests that the argument is a valid Unix GID.
  198. func IsValidGroupID(gid int64) []string {
  199. if minGroupID <= gid && gid <= maxGroupID {
  200. return nil
  201. }
  202. return []string{InclusiveRangeError(minGroupID, maxGroupID)}
  203. }
  204. // IsValidUserID tests that the argument is a valid Unix UID.
  205. func IsValidUserID(uid int64) []string {
  206. if minUserID <= uid && uid <= maxUserID {
  207. return nil
  208. }
  209. return []string{InclusiveRangeError(minUserID, maxUserID)}
  210. }
  211. var portNameCharsetRegex = regexp.MustCompile("^[-a-z0-9]+$")
  212. var portNameOneLetterRegexp = regexp.MustCompile("[a-z]")
  213. // IsValidPortName check that the argument is valid syntax. It must be
  214. // non-empty and no more than 15 characters long. It may contain only [-a-z0-9]
  215. // and must contain at least one letter [a-z]. It must not start or end with a
  216. // hyphen, nor contain adjacent hyphens.
  217. //
  218. // Note: We only allow lower-case characters, even though RFC 6335 is case
  219. // insensitive.
  220. func IsValidPortName(port string) []string {
  221. var errs []string
  222. if len(port) > 15 {
  223. errs = append(errs, MaxLenError(15))
  224. }
  225. if !portNameCharsetRegex.MatchString(port) {
  226. errs = append(errs, "must contain only alpha-numeric characters (a-z, 0-9), and hyphens (-)")
  227. }
  228. if !portNameOneLetterRegexp.MatchString(port) {
  229. errs = append(errs, "must contain at least one letter or number (a-z, 0-9)")
  230. }
  231. if strings.Contains(port, "--") {
  232. errs = append(errs, "must not contain consecutive hyphens")
  233. }
  234. if len(port) > 0 && (port[0] == '-' || port[len(port)-1] == '-') {
  235. errs = append(errs, "must not begin or end with a hyphen")
  236. }
  237. return errs
  238. }
  239. // IsValidIP tests that the argument is a valid IP address.
  240. func IsValidIP(value string) []string {
  241. if net.ParseIP(value) == nil {
  242. return []string{"must be a valid IP address, (e.g. 10.9.8.7)"}
  243. }
  244. return nil
  245. }
  246. const percentFmt string = "[0-9]+%"
  247. const percentErrMsg string = "a valid percent string must be a numeric string followed by an ending '%'"
  248. var percentRegexp = regexp.MustCompile("^" + percentFmt + "$")
  249. // IsValidPercent checks that string is in the form of a percentage
  250. func IsValidPercent(percent string) []string {
  251. if !percentRegexp.MatchString(percent) {
  252. return []string{RegexError(percentErrMsg, percentFmt, "1%", "93%")}
  253. }
  254. return nil
  255. }
  256. const httpHeaderNameFmt string = "[-A-Za-z0-9]+"
  257. const httpHeaderNameErrMsg string = "a valid HTTP header must consist of alphanumeric characters or '-'"
  258. var httpHeaderNameRegexp = regexp.MustCompile("^" + httpHeaderNameFmt + "$")
  259. // IsHTTPHeaderName checks that a string conforms to the Go HTTP library's
  260. // definition of a valid header field name (a stricter subset than RFC7230).
  261. func IsHTTPHeaderName(value string) []string {
  262. if !httpHeaderNameRegexp.MatchString(value) {
  263. return []string{RegexError(httpHeaderNameErrMsg, httpHeaderNameFmt, "X-Header-Name")}
  264. }
  265. return nil
  266. }
  267. const envVarNameFmt = "[-._a-zA-Z][-._a-zA-Z0-9]*"
  268. const envVarNameFmtErrMsg string = "a valid environment variable name must consist of alphabetic characters, digits, '_', '-', or '.', and must not start with a digit"
  269. var envVarNameRegexp = regexp.MustCompile("^" + envVarNameFmt + "$")
  270. // IsEnvVarName tests if a string is a valid environment variable name.
  271. func IsEnvVarName(value string) []string {
  272. var errs []string
  273. if !envVarNameRegexp.MatchString(value) {
  274. errs = append(errs, RegexError(envVarNameFmtErrMsg, envVarNameFmt, "my.env-name", "MY_ENV.NAME", "MyEnvName1"))
  275. }
  276. errs = append(errs, hasChDirPrefix(value)...)
  277. return errs
  278. }
  279. const configMapKeyFmt = `[-._a-zA-Z0-9]+`
  280. const configMapKeyErrMsg string = "a valid config key must consist of alphanumeric characters, '-', '_' or '.'"
  281. var configMapKeyRegexp = regexp.MustCompile("^" + configMapKeyFmt + "$")
  282. // IsConfigMapKey tests for a string that is a valid key for a ConfigMap or Secret
  283. func IsConfigMapKey(value string) []string {
  284. var errs []string
  285. if len(value) > DNS1123SubdomainMaxLength {
  286. errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))
  287. }
  288. if !configMapKeyRegexp.MatchString(value) {
  289. errs = append(errs, RegexError(configMapKeyErrMsg, configMapKeyFmt, "key.name", "KEY_NAME", "key-name"))
  290. }
  291. errs = append(errs, hasChDirPrefix(value)...)
  292. return errs
  293. }
  294. // MaxLenError returns a string explanation of a "string too long" validation
  295. // failure.
  296. func MaxLenError(length int) string {
  297. return fmt.Sprintf("must be no more than %d characters", length)
  298. }
  299. // RegexError returns a string explanation of a regex validation failure.
  300. func RegexError(msg string, fmt string, examples ...string) string {
  301. if len(examples) == 0 {
  302. return msg + " (regex used for validation is '" + fmt + "')"
  303. }
  304. msg += " (e.g. "
  305. for i := range examples {
  306. if i > 0 {
  307. msg += " or "
  308. }
  309. msg += "'" + examples[i] + "', "
  310. }
  311. msg += "regex used for validation is '" + fmt + "')"
  312. return msg
  313. }
  314. // EmptyError returns a string explanation of a "must not be empty" validation
  315. // failure.
  316. func EmptyError() string {
  317. return "must be non-empty"
  318. }
  319. func prefixEach(msgs []string, prefix string) []string {
  320. for i := range msgs {
  321. msgs[i] = prefix + msgs[i]
  322. }
  323. return msgs
  324. }
  325. // InclusiveRangeError returns a string explanation of a numeric "must be
  326. // between" validation failure.
  327. func InclusiveRangeError(lo, hi int) string {
  328. return fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi)
  329. }
  330. func hasChDirPrefix(value string) []string {
  331. var errs []string
  332. switch {
  333. case value == ".":
  334. errs = append(errs, `must not be '.'`)
  335. case value == "..":
  336. errs = append(errs, `must not be '..'`)
  337. case strings.HasPrefix(value, ".."):
  338. errs = append(errs, `must not start with '..'`)
  339. }
  340. return errs
  341. }
  342. // IsValidSocketAddr checks that string represents a valid socket address
  343. // as defined in RFC 789. (e.g 0.0.0.0:10254 or [::]:10254))
  344. func IsValidSocketAddr(value string) []string {
  345. var errs []string
  346. ip, port, err := net.SplitHostPort(value)
  347. if err != nil {
  348. errs = append(errs, "must be a valid socket address format, (e.g. 0.0.0.0:10254 or [::]:10254)")
  349. return errs
  350. }
  351. portInt, _ := strconv.Atoi(port)
  352. errs = append(errs, IsValidPortNum(portInt)...)
  353. errs = append(errs, IsValidIP(ip)...)
  354. return errs
  355. }