api.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package client
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/gorilla/schema"
  13. "github.com/porter-dev/porter/api/types"
  14. "k8s.io/client-go/util/homedir"
  15. )
  16. // Client represents the client for the Porter API
  17. type Client struct {
  18. BaseURL string
  19. HTTPClient *http.Client
  20. Cookie *http.Cookie
  21. CookieFilePath string
  22. Token string
  23. }
  24. // NewClient constructs a new client based on a set of options
  25. func NewClient(baseURL string, cookieFileName string) *Client {
  26. home := homedir.HomeDir()
  27. cookieFilePath := filepath.Join(home, ".porter", cookieFileName)
  28. client := &Client{
  29. BaseURL: baseURL,
  30. CookieFilePath: cookieFilePath,
  31. HTTPClient: &http.Client{
  32. Timeout: time.Minute,
  33. },
  34. }
  35. cookie, _ := client.getCookie()
  36. if cookie != nil {
  37. client.Cookie = cookie
  38. }
  39. return client
  40. }
  41. func NewClientWithToken(baseURL, token string) *Client {
  42. client := &Client{
  43. BaseURL: baseURL,
  44. Token: token,
  45. HTTPClient: &http.Client{
  46. Timeout: time.Minute,
  47. },
  48. }
  49. return client
  50. }
  51. func (c *Client) getRequest(relPath string, data interface{}, response interface{}) error {
  52. vals := make(map[string][]string)
  53. err := schema.NewEncoder().Encode(data, vals)
  54. urlVals := url.Values(vals)
  55. req, err := http.NewRequest(
  56. "GET",
  57. fmt.Sprintf("%s/%s?%s", c.BaseURL, relPath, urlVals.Encode()),
  58. nil,
  59. )
  60. if err != nil {
  61. return err
  62. }
  63. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  64. if httpErr != nil {
  65. return fmt.Errorf("%v", httpErr.Error)
  66. }
  67. return err
  68. }
  69. return nil
  70. }
  71. func (c *Client) postRequest(relPath string, data interface{}, response interface{}) error {
  72. strData, err := json.Marshal(data)
  73. if err != nil {
  74. return nil
  75. }
  76. req, err := http.NewRequest(
  77. "POST",
  78. fmt.Sprintf("%s/%s", c.BaseURL, relPath),
  79. strings.NewReader(string(strData)),
  80. )
  81. if err != nil {
  82. return err
  83. }
  84. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  85. if httpErr != nil {
  86. return fmt.Errorf("%v", httpErr.Error)
  87. }
  88. return err
  89. }
  90. return nil
  91. }
  92. func (c *Client) deleteRequest(relPath string, data interface{}, response interface{}) error {
  93. strData, err := json.Marshal(data)
  94. if err != nil {
  95. return nil
  96. }
  97. req, err := http.NewRequest(
  98. "DELETE",
  99. fmt.Sprintf("%s/%s", c.BaseURL, relPath),
  100. strings.NewReader(string(strData)),
  101. )
  102. if err != nil {
  103. return err
  104. }
  105. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  106. if httpErr != nil {
  107. return fmt.Errorf("%v", httpErr.Error)
  108. }
  109. return err
  110. }
  111. return nil
  112. }
  113. func (c *Client) sendRequest(req *http.Request, v interface{}, useCookie bool) (*types.ExternalError, error) {
  114. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  115. req.Header.Set("Accept", "application/json; charset=utf-8")
  116. if c.Token != "" {
  117. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
  118. } else if cookie, _ := c.getCookie(); useCookie && cookie != nil {
  119. c.Cookie = cookie
  120. req.AddCookie(c.Cookie)
  121. }
  122. res, err := c.HTTPClient.Do(req)
  123. if err != nil {
  124. return nil, err
  125. }
  126. defer res.Body.Close()
  127. if cookies := res.Cookies(); len(cookies) == 1 {
  128. c.saveCookie(cookies[0])
  129. }
  130. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  131. var errRes types.ExternalError
  132. if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
  133. return &errRes, nil
  134. }
  135. return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
  136. }
  137. if v != nil {
  138. debugBytes, _ := ioutil.ReadAll(res.Body)
  139. fmt.Println(string(debugBytes))
  140. copyBody := strings.NewReader(string(debugBytes))
  141. if err = json.NewDecoder(copyBody).Decode(v); err != nil {
  142. return nil, err
  143. }
  144. }
  145. return nil, nil
  146. }
  147. // CookieStorage for temporary fs-based cookie storage before jwt tokens
  148. type CookieStorage struct {
  149. Cookie *http.Cookie `json:"cookie"`
  150. }
  151. // saves single cookie to file
  152. func (c *Client) saveCookie(cookie *http.Cookie) error {
  153. data, err := json.Marshal(&CookieStorage{
  154. Cookie: cookie,
  155. })
  156. if err != nil {
  157. return err
  158. }
  159. return ioutil.WriteFile(c.CookieFilePath, data, 0644)
  160. }
  161. // retrieves single cookie from file
  162. func (c *Client) getCookie() (*http.Cookie, error) {
  163. data, err := ioutil.ReadFile(c.CookieFilePath)
  164. if err != nil {
  165. return nil, err
  166. }
  167. cookie := &CookieStorage{}
  168. err = json.Unmarshal(data, cookie)
  169. if err != nil {
  170. return nil, err
  171. }
  172. return cookie.Cookie, nil
  173. }
  174. type TokenProjectID struct {
  175. ProjectID uint `json:"project_id"`
  176. }
  177. func GetProjectIDFromToken(token string) (uint, bool, error) {
  178. var encoded string
  179. if tokenSplit := strings.Split(token, "."); len(tokenSplit) != 3 {
  180. return 0, false, fmt.Errorf("invalid jwt token format")
  181. } else {
  182. encoded = tokenSplit[1]
  183. }
  184. decodedBytes, err := base64.RawStdEncoding.DecodeString(encoded)
  185. if err != nil {
  186. return 0, false, fmt.Errorf("could not decode jwt token from base64: %v", err)
  187. }
  188. res := &TokenProjectID{}
  189. err = json.Unmarshal(decodedBytes, res)
  190. if err != nil {
  191. return 0, false, fmt.Errorf("could not get token project id: %v", err)
  192. }
  193. // if the project ID is 0, this is a token signed for a user, not a specific project
  194. if res.ProjectID == 0 {
  195. return 0, false, nil
  196. }
  197. return res.ProjectID, true, nil
  198. }