validation.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package storageos
  2. import (
  3. "errors"
  4. "regexp"
  5. )
  6. const (
  7. // IDFormat are the characters allowed to represent an ID.
  8. IDFormat = `[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`
  9. // NameFormat are the characters allowed to represent a name.
  10. NameFormat = `[a-zA-Z0-9][a-zA-Z0-9~_.-]+`
  11. )
  12. var (
  13. // IDPattern is a regular expression to validate a unique id against the
  14. // collection of restricted characters.
  15. IDPattern = regexp.MustCompile(`^` + IDFormat + `$`)
  16. // NamePattern is a regular expression to validate names against the
  17. // collection of restricted characters.
  18. NamePattern = regexp.MustCompile(`^` + NameFormat + `$`)
  19. // ErrNoRef is given when the reference given is invalid.
  20. ErrNoRef = errors.New("no ref provided or incorrect format")
  21. // ErrNoNamespace is given when the namespace given is invalid.
  22. ErrNoNamespace = errors.New("no namespace provided or incorrect format")
  23. )
  24. // ValidateNamespaceAndRef returns true if both the namespace and ref are valid.
  25. func ValidateNamespaceAndRef(namespace, ref string) error {
  26. if !IsUUID(ref) && !IsName(ref) {
  27. return ErrNoRef
  28. }
  29. if !IsName(namespace) {
  30. return ErrNoNamespace
  31. }
  32. return nil
  33. }
  34. // ValidateNamespace returns true if the namespace uses a valid name.
  35. func ValidateNamespace(namespace string) error {
  36. if !IsName(namespace) {
  37. return ErrNoNamespace
  38. }
  39. return nil
  40. }
  41. // IsUUID returns true if the string input is a valid UUID string.
  42. func IsUUID(s string) bool {
  43. return IDPattern.MatchString(s)
  44. }
  45. // IsName returns true if the string input is a valid Name string.
  46. func IsName(s string) bool {
  47. return NamePattern.MatchString(s)
  48. }
  49. // namespacedPath checks for valid input and returns api path for a namespaced
  50. // objectType. Use namespacedRefPath for objects.
  51. func namespacedPath(namespace, objectType string) (string, error) {
  52. if err := ValidateNamespace(namespace); err != nil {
  53. return "", err
  54. }
  55. return "/namespaces/" + namespace + "/" + objectType, nil
  56. }
  57. // namespacedRefPath checks for valid input and returns api path for a single
  58. // namespaced object. Use namespacedPath for objects type path.
  59. func namespacedRefPath(namespace, objectType, ref string) (string, error) {
  60. if err := ValidateNamespaceAndRef(namespace, ref); err != nil {
  61. return "", err
  62. }
  63. return "/namespaces/" + namespace + "/" + objectType + "/" + ref, nil
  64. }