api.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. encodedURLVals := urlVals.Encode()
  57. var req *http.Request
  58. if encodedURLVals != "" {
  59. req, err = http.NewRequest(
  60. "GET",
  61. fmt.Sprintf("%s%s?%s", c.BaseURL, relPath, encodedURLVals),
  62. nil,
  63. )
  64. } else {
  65. req, err = http.NewRequest(
  66. "GET",
  67. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  68. nil,
  69. )
  70. }
  71. if err != nil {
  72. return err
  73. }
  74. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  75. if httpErr != nil {
  76. return fmt.Errorf("%v", httpErr.Error)
  77. }
  78. return err
  79. }
  80. return nil
  81. }
  82. type postRequestOpts struct {
  83. retryCount uint
  84. }
  85. func (c *Client) postRequest(relPath string, data interface{}, response interface{}, opts ...postRequestOpts) error {
  86. var retryCount uint = 1
  87. if len(opts) > 0 {
  88. for _, opt := range opts {
  89. retryCount = opt.retryCount
  90. }
  91. }
  92. var httpErr *types.ExternalError
  93. var err error
  94. for i := 0; i < int(retryCount); i++ {
  95. strData, err := json.Marshal(data)
  96. if err != nil {
  97. return nil
  98. }
  99. req, err := http.NewRequest(
  100. "POST",
  101. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  102. strings.NewReader(string(strData)),
  103. )
  104. if err != nil {
  105. return err
  106. }
  107. httpErr, err = c.sendRequest(req, response, true)
  108. if httpErr == nil && err == nil {
  109. return nil
  110. }
  111. if i != int(retryCount)-1 {
  112. if httpErr != nil {
  113. fmt.Printf("Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  114. } else {
  115. fmt.Printf("Error: %v, retrying request...\n", err)
  116. }
  117. }
  118. }
  119. if httpErr != nil {
  120. return fmt.Errorf("%v", httpErr.Error)
  121. }
  122. return err
  123. }
  124. func (c *Client) deleteRequest(relPath string, data interface{}, response interface{}) error {
  125. strData, err := json.Marshal(data)
  126. if err != nil {
  127. return nil
  128. }
  129. req, err := http.NewRequest(
  130. "DELETE",
  131. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  132. strings.NewReader(string(strData)),
  133. )
  134. if err != nil {
  135. return err
  136. }
  137. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  138. if httpErr != nil {
  139. return fmt.Errorf("%v", httpErr.Error)
  140. }
  141. return err
  142. }
  143. return nil
  144. }
  145. func (c *Client) sendRequest(req *http.Request, v interface{}, useCookie bool) (*types.ExternalError, error) {
  146. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  147. req.Header.Set("Accept", "application/json; charset=utf-8")
  148. if c.Token != "" {
  149. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
  150. } else if cookie, _ := c.getCookie(); useCookie && cookie != nil {
  151. c.Cookie = cookie
  152. req.AddCookie(c.Cookie)
  153. }
  154. res, err := c.HTTPClient.Do(req)
  155. if err != nil {
  156. return nil, err
  157. }
  158. defer res.Body.Close()
  159. if cookies := res.Cookies(); len(cookies) == 1 {
  160. c.saveCookie(cookies[0])
  161. }
  162. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  163. var errRes types.ExternalError
  164. if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
  165. return &errRes, nil
  166. }
  167. return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
  168. }
  169. if v != nil {
  170. if err = json.NewDecoder(res.Body).Decode(v); err != nil {
  171. return nil, err
  172. }
  173. }
  174. return nil, nil
  175. }
  176. // CookieStorage for temporary fs-based cookie storage before jwt tokens
  177. type CookieStorage struct {
  178. Cookie *http.Cookie `json:"cookie"`
  179. }
  180. // saves single cookie to file
  181. func (c *Client) saveCookie(cookie *http.Cookie) error {
  182. data, err := json.Marshal(&CookieStorage{
  183. Cookie: cookie,
  184. })
  185. if err != nil {
  186. return err
  187. }
  188. return ioutil.WriteFile(c.CookieFilePath, data, 0644)
  189. }
  190. // retrieves single cookie from file
  191. func (c *Client) getCookie() (*http.Cookie, error) {
  192. data, err := ioutil.ReadFile(c.CookieFilePath)
  193. if err != nil {
  194. return nil, err
  195. }
  196. cookie := &CookieStorage{}
  197. err = json.Unmarshal(data, cookie)
  198. if err != nil {
  199. return nil, err
  200. }
  201. return cookie.Cookie, nil
  202. }
  203. // retrieves single cookie from file
  204. func (c *Client) deleteCookie() error {
  205. // if file does not exist, return no error
  206. if _, err := os.Stat(c.CookieFilePath); os.IsNotExist(err) {
  207. return nil
  208. }
  209. return os.Remove(c.CookieFilePath)
  210. }
  211. type TokenProjectID struct {
  212. ProjectID uint `json:"project_id"`
  213. }
  214. func GetProjectIDFromToken(token string) (uint, bool, error) {
  215. var encoded string
  216. if tokenSplit := strings.Split(token, "."); len(tokenSplit) != 3 {
  217. return 0, false, fmt.Errorf("invalid jwt token format")
  218. } else {
  219. encoded = tokenSplit[1]
  220. }
  221. decodedBytes, err := base64.RawStdEncoding.DecodeString(encoded)
  222. if err != nil {
  223. return 0, false, fmt.Errorf("could not decode jwt token from base64: %v", err)
  224. }
  225. res := &TokenProjectID{}
  226. err = json.Unmarshal(decodedBytes, res)
  227. if err != nil {
  228. return 0, false, fmt.Errorf("could not get token project id: %v", err)
  229. }
  230. // if the project ID is 0, this is a token signed for a user, not a specific project
  231. if res.ProjectID == 0 {
  232. return 0, false, nil
  233. }
  234. return res.ProjectID, true, nil
  235. }