validation.go 14 KB

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