api.go 5.5 KB

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