validation.go 10 KB

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