client.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package hashicorp
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "git.aetherial.dev/aeth/yosai/pkg/daemon"
  10. "git.aetherial.dev/aeth/yosai/pkg/keytags"
  11. )
  12. const (
  13. SecretsApiPath = "v1/kv/data"
  14. )
  15. type VaultAdd struct {
  16. Data map[string]string `json:"data"`
  17. }
  18. type VaultResponse struct {
  19. Data VaultResponseInner `json:"data"`
  20. }
  21. type VaultResponseInner struct {
  22. Data VaultItem `json:"data"`
  23. }
  24. type VaultItem struct {
  25. Name string `json:"name"`
  26. Public string `json:"public"`
  27. Secret string `json:"secret"`
  28. Type string `json:"type"`
  29. }
  30. type VaultConnection struct {
  31. VaultUrl string
  32. HttpProto string
  33. KeyRing daemon.DaemonKeyRing
  34. Client *http.Client
  35. }
  36. func (v VaultItem) GetPublic() string { return v.Public }
  37. func (v VaultItem) GetSecret() string { return v.Secret }
  38. func (v VaultItem) GetType() string { return v.Type }
  39. func (v VaultItem) Prepare() string {
  40. return "Unimplemented method"
  41. }
  42. // Returns the 'public' field of the credential, i.e. a username or something
  43. func (v VaultResponse) GetPublic() string {
  44. return v.Data.Data.Public
  45. }
  46. // returns the 'private' field of the credential, like the API key or password
  47. func (v VaultResponse) GetSecret() string {
  48. return v.Data.Data.Secret
  49. }
  50. // this is an extra implementation so VaultResponse can implement the daemon.Key interface
  51. func (v VaultResponse) Prepare() string {
  52. if v.Data.Data.Type == "bearer" {
  53. return fmt.Sprintf("Bearer %s", v.GetSecret())
  54. }
  55. if v.Data.Data.Type == "basic" {
  56. encodedcreds := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", v.GetPublic(), v.GetSecret())))
  57. return fmt.Sprintf("Basic %s", encodedcreds)
  58. }
  59. return "CREDENTIAL TYPE INVALID"
  60. }
  61. /*
  62. Implementing the daemon.Key interface and returning the keys 'type'
  63. */
  64. func (v VaultResponse) GetType() string {
  65. return v.Data.Data.Type
  66. }
  67. /*
  68. Retrieve a key from hashicorp. the 2nd argument, 'name' is the path of the secret in hashicorp
  69. :param keyring: a daemon.DaemonKeyRing interface that will have the hashicorp API key
  70. :param name: the name of the secret in hashicorp. It will be injected as the 'path' in the API call,
  71. See the Hashicorp Vault documentation for details
  72. */
  73. func (v VaultConnection) GetKey(name string) (daemon.Key, error) {
  74. vaultBase := fmt.Sprintf("%s://%s/%s/%s", v.HttpProto, v.VaultUrl, SecretsApiPath, name)
  75. var vaultResp VaultResponse
  76. req, err := http.NewRequest("GET", vaultBase, nil)
  77. if err != nil {
  78. return vaultResp, err
  79. }
  80. req.Header.Add("Content-Type", "application/json")
  81. vaultApiKey, err := v.KeyRing.GetKey(keytags.HASHICORP_VAULT_KEYNAME)
  82. if err != nil {
  83. return vaultResp, err
  84. }
  85. req.Header.Add("Authorization", vaultApiKey.Prepare())
  86. resp, err := v.Client.Do(req)
  87. if err != nil {
  88. return vaultResp, err
  89. }
  90. defer resp.Body.Close()
  91. if resp.StatusCode != 200 {
  92. return vaultResp, daemon.KeyNotFound
  93. }
  94. b, err := io.ReadAll(resp.Body)
  95. if err != nil {
  96. return vaultResp, err
  97. }
  98. err = json.Unmarshal(b, &vaultResp)
  99. if err != nil {
  100. return vaultResp, err
  101. }
  102. return vaultResp, nil
  103. }
  104. /*
  105. Add the root users for your VPS to Hashicorp vault
  106. :param pass: the password to store in vault
  107. */
  108. func (v VaultConnection) AddKey(name string, key daemon.Key) error {
  109. body := VaultAdd{
  110. Data: map[string]string{"public": key.GetPublic(), "secret": key.GetSecret(), "type": key.GetType()},
  111. }
  112. b, err := json.Marshal(&body)
  113. if err != nil {
  114. return err
  115. }
  116. vaultBase := fmt.Sprintf("%s://%s/%s/%s", v.HttpProto, v.VaultUrl, SecretsApiPath, name)
  117. req, err := http.NewRequest("POST", vaultBase, bytes.NewReader(b))
  118. if err != nil {
  119. return err
  120. }
  121. req.Header.Add("Content-Type", "application/json")
  122. vaultApiKey, err := v.KeyRing.GetKey(keytags.HASHICORP_VAULT_KEYNAME)
  123. if err != nil {
  124. return err
  125. }
  126. req.Header.Add("Authorization", vaultApiKey.Prepare())
  127. resp, err := v.Client.Do(req)
  128. if err != nil {
  129. return err
  130. }
  131. defer resp.Body.Close()
  132. if resp.StatusCode != 200 {
  133. return &HashicorpClientError{Msg: resp.Status}
  134. }
  135. return nil
  136. }
  137. /*
  138. Removes a key from the vault
  139. :param name: the 'path' of the key as Hashicorp knows it
  140. */
  141. func (v VaultConnection) RemoveKey(name string) error {
  142. vaultBase := fmt.Sprintf("%s://%s/%s/%s", v.HttpProto, v.VaultUrl, SecretsApiPath, name)
  143. req, err := http.NewRequest("DELETE", vaultBase, nil)
  144. if err != nil {
  145. return err
  146. }
  147. vaultApiKey, err := v.KeyRing.GetKey(keytags.HASHICORP_VAULT_KEYNAME)
  148. if err != nil {
  149. return err
  150. }
  151. req.Header.Add("Authorization", vaultApiKey.Prepare())
  152. req.Header.Add("Content-Type", "application/json")
  153. resp, err := v.Client.Do(req)
  154. if err != nil {
  155. return err
  156. }
  157. defer resp.Body.Close()
  158. if resp.StatusCode != 200 {
  159. return &HashicorpClientError{Msg: resp.Status}
  160. }
  161. return nil
  162. }
  163. // Return the resource name for logging purposes
  164. func (v VaultConnection) Source() string {
  165. return "Hashicorp Vault"
  166. }
  167. /*
  168. Handles the routing for the hashicorp keyring routes
  169. :param msg: a daemon.SockMessage that contains request data
  170. */
  171. func (v VaultConnection) VaultRouter(msg daemon.SockMessage) daemon.SockMessage {
  172. switch msg.Method {
  173. case "add":
  174. var req VaultItem
  175. err := json.Unmarshal(msg.Body, &req)
  176. if err != nil {
  177. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  178. }
  179. err = v.AddKey(req.Name, req)
  180. if err != nil {
  181. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  182. }
  183. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, []byte("Key successfully added."))
  184. default:
  185. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_UNRESOLVED, []byte("Unresolvable method"))
  186. }
  187. }
  188. /*
  189. #####################
  190. ###### ERRORS #######
  191. #####################
  192. */
  193. type HashicorpClientError struct {
  194. Msg string
  195. }
  196. func (h *HashicorpClientError) Error() string {
  197. return fmt.Sprintf("There was an error with the client call: %s", h.Msg)
  198. }