types.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package sshutil
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "github.com/pkg/errors"
  6. "golang.org/x/crypto/ssh"
  7. )
  8. // Hosts are tagged with k,v pairs. These tags are how a user is ultimately
  9. // associated with a host.
  10. type HostTag struct {
  11. ID string
  12. Name string
  13. Value string
  14. }
  15. // Host defines expected attributes for an ssh host.
  16. type Host struct {
  17. HostID string `json:"hid"`
  18. HostTags []HostTag `json:"host_tags"`
  19. Hostname string `json:"hostname"`
  20. }
  21. // CertType defines the certificate type, it can be a user or a host
  22. // certificate.
  23. type CertType uint32
  24. const (
  25. // UserCert defines a user certificate.
  26. UserCert CertType = ssh.UserCert
  27. // HostCert defines a host certificate.
  28. HostCert CertType = ssh.HostCert
  29. )
  30. const (
  31. userString = "user"
  32. hostString = "host"
  33. )
  34. // String returns "user" for user certificates and "host" for host certificates.
  35. // It will return the empty string for any other value.
  36. func (c CertType) String() string {
  37. switch c {
  38. case UserCert:
  39. return userString
  40. case HostCert:
  41. return hostString
  42. default:
  43. return ""
  44. }
  45. }
  46. // MarshalJSON implements the json.Marshaler interface for CertType. UserCert
  47. // will be marshaled as the string "user" and HostCert as "host".
  48. func (c CertType) MarshalJSON() ([]byte, error) {
  49. if s := c.String(); s != "" {
  50. return []byte(`"` + s + `"`), nil
  51. }
  52. return nil, errors.Errorf("unknown certificate type %d", c)
  53. }
  54. // UnmarshalJSON implements the json.Unmarshaler interface for CertType.
  55. func (c *CertType) UnmarshalJSON(data []byte) error {
  56. var s string
  57. if err := json.Unmarshal(data, &s); err != nil {
  58. return errors.Wrap(err, "error unmarshaling certificate type")
  59. }
  60. switch strings.ToLower(s) {
  61. case userString:
  62. *c = UserCert
  63. return nil
  64. case hostString:
  65. *c = HostCert
  66. return nil
  67. default:
  68. return errors.Errorf("error unmarshaling '%s' as a certificate type", s)
  69. }
  70. }