types.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. // CertTypeFromString returns the CertType for the string "user" and "host".
  35. func CertTypeFromString(s string) (CertType, error) {
  36. switch strings.ToLower(s) {
  37. case userString:
  38. return UserCert, nil
  39. case hostString:
  40. return HostCert, nil
  41. default:
  42. return 0, errors.Errorf("unknown certificate type '%s'", s)
  43. }
  44. }
  45. // String returns "user" for user certificates and "host" for host certificates.
  46. // It will return the empty string for any other value.
  47. func (c CertType) String() string {
  48. switch c {
  49. case UserCert:
  50. return userString
  51. case HostCert:
  52. return hostString
  53. default:
  54. return ""
  55. }
  56. }
  57. // MarshalJSON implements the json.Marshaler interface for CertType. UserCert
  58. // will be marshaled as the string "user" and HostCert as "host".
  59. func (c CertType) MarshalJSON() ([]byte, error) {
  60. if s := c.String(); s != "" {
  61. return []byte(`"` + s + `"`), nil
  62. }
  63. return nil, errors.Errorf("unknown certificate type %d", c)
  64. }
  65. // UnmarshalJSON implements the json.Unmarshaler interface for CertType.
  66. func (c *CertType) UnmarshalJSON(data []byte) error {
  67. var s string
  68. if err := json.Unmarshal(data, &s); err != nil {
  69. return errors.Wrap(err, "error unmarshaling certificate type")
  70. }
  71. certType, err := CertTypeFromString(s)
  72. if err != nil {
  73. return errors.Errorf("error unmarshaling '%s' as a certificate type", s)
  74. }
  75. *c = certType
  76. return nil
  77. }