api.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. cfToken string
  25. }
  26. // NewClient constructs a new client based on a set of options
  27. func NewClient(baseURL string, cookieFileName string) *Client {
  28. home := homedir.HomeDir()
  29. cookieFilePath := filepath.Join(home, ".porter", cookieFileName)
  30. client := &Client{
  31. BaseURL: baseURL,
  32. CookieFilePath: cookieFilePath,
  33. HTTPClient: &http.Client{
  34. Timeout: time.Minute,
  35. },
  36. }
  37. cookie, _ := client.getCookie()
  38. if cookie != nil {
  39. client.Cookie = cookie
  40. }
  41. // look for a cloudflare access token specifically for Porter
  42. if cfToken := os.Getenv("PORTER_CF_ACCESS_TOKEN"); cfToken != "" {
  43. client.cfToken = cfToken
  44. }
  45. return client
  46. }
  47. func NewClientWithToken(baseURL, token string) *Client {
  48. client := &Client{
  49. BaseURL: baseURL,
  50. Token: token,
  51. HTTPClient: &http.Client{
  52. Timeout: time.Minute,
  53. },
  54. }
  55. // look for a cloudflare access token specifically for Porter
  56. if cfToken := os.Getenv("PORTER_CF_ACCESS_TOKEN"); cfToken != "" {
  57. client.cfToken = cfToken
  58. }
  59. return client
  60. }
  61. func (c *Client) getRequest(relPath string, data interface{}, response interface{}) error {
  62. vals := make(map[string][]string)
  63. err := schema.NewEncoder().Encode(data, vals)
  64. urlVals := url.Values(vals)
  65. encodedURLVals := urlVals.Encode()
  66. var req *http.Request
  67. if encodedURLVals != "" {
  68. req, err = http.NewRequest(
  69. "GET",
  70. fmt.Sprintf("%s%s?%s", c.BaseURL, relPath, encodedURLVals),
  71. nil,
  72. )
  73. } else {
  74. req, err = http.NewRequest(
  75. "GET",
  76. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  77. nil,
  78. )
  79. }
  80. if err != nil {
  81. return err
  82. }
  83. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  84. if httpErr != nil {
  85. return fmt.Errorf("%v", httpErr.Error)
  86. }
  87. return err
  88. }
  89. return nil
  90. }
  91. type postRequestOpts struct {
  92. retryCount uint
  93. }
  94. func (c *Client) postRequest(relPath string, data interface{}, response interface{}, opts ...postRequestOpts) error {
  95. var retryCount uint = 1
  96. if len(opts) > 0 {
  97. for _, opt := range opts {
  98. retryCount = opt.retryCount
  99. }
  100. }
  101. var httpErr *types.ExternalError
  102. var err error
  103. for i := 0; i < int(retryCount); i++ {
  104. strData, err := json.Marshal(data)
  105. if err != nil {
  106. return nil
  107. }
  108. req, err := http.NewRequest(
  109. "POST",
  110. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  111. strings.NewReader(string(strData)),
  112. )
  113. if err != nil {
  114. return err
  115. }
  116. httpErr, err = c.sendRequest(req, response, true)
  117. if httpErr == nil && err == nil {
  118. return nil
  119. }
  120. if i != int(retryCount)-1 {
  121. if httpErr != nil {
  122. fmt.Fprintf(os.Stderr, "Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  123. } else {
  124. fmt.Fprintf(os.Stderr, "Error: %v, retrying request...\n", err)
  125. }
  126. }
  127. }
  128. if httpErr != nil {
  129. return fmt.Errorf("%v", httpErr.Error)
  130. }
  131. return err
  132. }
  133. type patchRequestOpts struct {
  134. retryCount uint
  135. }
  136. func (c *Client) patchRequest(relPath string, data interface{}, response interface{}, opts ...patchRequestOpts) error {
  137. var retryCount uint = 1
  138. if len(opts) > 0 {
  139. for _, opt := range opts {
  140. retryCount = opt.retryCount
  141. }
  142. }
  143. var httpErr *types.ExternalError
  144. var err error
  145. for i := 0; i < int(retryCount); i++ {
  146. strData, err := json.Marshal(data)
  147. if err != nil {
  148. return nil
  149. }
  150. req, err := http.NewRequest(
  151. "PATCH",
  152. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  153. strings.NewReader(string(strData)),
  154. )
  155. if err != nil {
  156. return err
  157. }
  158. httpErr, err = c.sendRequest(req, response, true)
  159. if httpErr == nil && err == nil {
  160. return nil
  161. }
  162. if i != int(retryCount)-1 {
  163. if httpErr != nil {
  164. fmt.Fprintf(os.Stderr, "Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  165. } else {
  166. fmt.Fprintf(os.Stderr, "Error: %v, retrying request...\n", err)
  167. }
  168. }
  169. }
  170. if httpErr != nil {
  171. return fmt.Errorf("%v", httpErr.Error)
  172. }
  173. return err
  174. }
  175. func (c *Client) deleteRequest(relPath string, data interface{}, response interface{}) error {
  176. strData, err := json.Marshal(data)
  177. if err != nil {
  178. return nil
  179. }
  180. req, err := http.NewRequest(
  181. "DELETE",
  182. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  183. strings.NewReader(string(strData)),
  184. )
  185. if err != nil {
  186. return err
  187. }
  188. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  189. if httpErr != nil {
  190. return fmt.Errorf("%v", httpErr.Error)
  191. }
  192. return err
  193. }
  194. return nil
  195. }
  196. func (c *Client) sendRequest(req *http.Request, v interface{}, useCookie bool) (*types.ExternalError, error) {
  197. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  198. req.Header.Set("Accept", "application/json; charset=utf-8")
  199. if c.Token != "" {
  200. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
  201. } else if cookie, _ := c.getCookie(); useCookie && cookie != nil {
  202. c.Cookie = cookie
  203. req.AddCookie(c.Cookie)
  204. }
  205. if c.cfToken != "" {
  206. req.Header.Set("cf-access-token", c.cfToken)
  207. }
  208. res, err := c.HTTPClient.Do(req)
  209. if err != nil {
  210. return nil, err
  211. }
  212. defer res.Body.Close()
  213. if cookies := res.Cookies(); len(cookies) == 1 {
  214. c.saveCookie(cookies[0])
  215. }
  216. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  217. var errRes types.ExternalError
  218. if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
  219. return &errRes, nil
  220. }
  221. return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
  222. }
  223. if v != nil {
  224. if err = json.NewDecoder(res.Body).Decode(v); err != nil {
  225. return nil, err
  226. }
  227. }
  228. return nil, nil
  229. }
  230. // CookieStorage for temporary fs-based cookie storage before jwt tokens
  231. type CookieStorage struct {
  232. Cookie *http.Cookie `json:"cookie"`
  233. }
  234. // saves single cookie to file
  235. func (c *Client) saveCookie(cookie *http.Cookie) error {
  236. data, err := json.Marshal(&CookieStorage{
  237. Cookie: cookie,
  238. })
  239. if err != nil {
  240. return err
  241. }
  242. return ioutil.WriteFile(c.CookieFilePath, data, 0644)
  243. }
  244. // retrieves single cookie from file
  245. func (c *Client) getCookie() (*http.Cookie, error) {
  246. data, err := ioutil.ReadFile(c.CookieFilePath)
  247. if err != nil {
  248. return nil, err
  249. }
  250. cookie := &CookieStorage{}
  251. err = json.Unmarshal(data, cookie)
  252. if err != nil {
  253. return nil, err
  254. }
  255. return cookie.Cookie, nil
  256. }
  257. // retrieves single cookie from file
  258. func (c *Client) deleteCookie() error {
  259. // if file does not exist, return no error
  260. if _, err := os.Stat(c.CookieFilePath); os.IsNotExist(err) {
  261. return nil
  262. }
  263. return os.Remove(c.CookieFilePath)
  264. }
  265. type TokenProjectID struct {
  266. ProjectID uint `json:"project_id"`
  267. }
  268. func GetProjectIDFromToken(token string) (uint, bool, error) {
  269. var encoded string
  270. if tokenSplit := strings.Split(token, "."); len(tokenSplit) != 3 {
  271. return 0, false, fmt.Errorf("invalid jwt token format")
  272. } else {
  273. encoded = tokenSplit[1]
  274. }
  275. decodedBytes, err := base64.RawStdEncoding.DecodeString(encoded)
  276. if err != nil {
  277. return 0, false, fmt.Errorf("could not decode jwt token from base64: %v", err)
  278. }
  279. res := &TokenProjectID{}
  280. err = json.Unmarshal(decodedBytes, res)
  281. if err != nil {
  282. return 0, false, fmt.Errorf("could not get token project id: %v", err)
  283. }
  284. // if the project ID is 0, this is a token signed for a user, not a specific project
  285. if res.ProjectID == 0 {
  286. return 0, false, nil
  287. }
  288. return res.ProjectID, true, nil
  289. }