enrollment_key.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package models
  2. import (
  3. "time"
  4. "github.com/google/uuid"
  5. )
  6. const (
  7. Undefined KeyType = iota
  8. TimeExpiration
  9. Uses
  10. Unlimited
  11. )
  12. // KeyType - the type of enrollment key
  13. type KeyType int
  14. // String - returns the string representation of a KeyType
  15. func (k KeyType) String() string {
  16. return [...]string{"Undefined", "TimeExpiration", "Uses", "Unlimited"}[k]
  17. }
  18. // EnrollmentToken - the tokenized version of an enrollmentkey;
  19. // to be used for host registration
  20. type EnrollmentToken struct {
  21. Server string `json:"server"`
  22. Value string `json:"value"`
  23. }
  24. // EnrollmentKeyLength - the length of an enrollment key - 62^16 unique possibilities
  25. const EnrollmentKeyLength = 32
  26. // EnrollmentKey - the key used to register hosts and join them to specific networks
  27. type EnrollmentKey struct {
  28. Expiration time.Time `json:"expiration"`
  29. UsesRemaining int `json:"uses_remaining"`
  30. Value string `json:"value"`
  31. Networks []string `json:"networks"`
  32. Unlimited bool `json:"unlimited"`
  33. Tags []string `json:"tags"`
  34. Token string `json:"token,omitempty"` // B64 value of EnrollmentToken
  35. Type KeyType `json:"type"`
  36. Relay uuid.UUID `json:"relay"`
  37. }
  38. // APIEnrollmentKey - used to create enrollment keys via API
  39. type APIEnrollmentKey struct {
  40. Expiration int64 `json:"expiration"`
  41. UsesRemaining int `json:"uses_remaining"`
  42. Networks []string `json:"networks"`
  43. Unlimited bool `json:"unlimited"`
  44. Tags []string `json:"tags"`
  45. Type KeyType `json:"type"`
  46. Relay string `json:"relay"`
  47. }
  48. // RegisterResponse - the response to a successful enrollment register
  49. type RegisterResponse struct {
  50. ServerConf ServerConfig `json:"server_config"`
  51. RequestedHost Host `json:"requested_host"`
  52. }
  53. // EnrollmentKey.IsValid - checks if the key is still valid to use
  54. func (k *EnrollmentKey) IsValid() bool {
  55. if k == nil {
  56. return false
  57. }
  58. if k.UsesRemaining > 0 {
  59. return true
  60. }
  61. if !k.Expiration.IsZero() && time.Now().Before(k.Expiration) {
  62. return true
  63. }
  64. if k.Type == Undefined {
  65. return false
  66. }
  67. return k.Unlimited
  68. }
  69. // EnrollmentKey.Validate - validate's an EnrollmentKey
  70. // should be used during creation
  71. func (k *EnrollmentKey) Validate() bool {
  72. return k.Networks != nil &&
  73. k.Tags != nil &&
  74. len(k.Value) == EnrollmentKeyLength &&
  75. k.IsValid()
  76. }