api.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. package client
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "strings"
  13. "time"
  14. "github.com/gorilla/schema"
  15. "github.com/porter-dev/porter/api/types"
  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 is a cloudflare token for accessing the API
  25. cfToken string
  26. }
  27. // NewClientInput contains all information required to create a new API Client
  28. type NewClientInput struct {
  29. // BaseURL is the url for the API. This usually ends with /api, and should not end with a /
  30. BaseURL string
  31. // CookieFileName allows you to authenticate with a cookie file, if one is present in the porter directory.
  32. // If both CookieFileName and BearerToken are specified, BearerToken will be preferred
  33. CookieFileName string
  34. // BearerToken uses a JWT to authenticate with the Porter API. If both BearerToken and CookieFileName are specified, BearerToken will be used
  35. BearerToken string
  36. // CloudflareToken allows for authenticating with a Porter API behind Cloudflare Zero Trust. If not specified, we will check PORTER_CF_ACCESS_TOKEN for a token.
  37. // If one is found, it will be added to all API calls.
  38. CloudflareToken string
  39. }
  40. // NewClientWithConfig creates a new API client with the provided config
  41. func NewClientWithConfig(ctx context.Context, input NewClientInput) (Client, error) {
  42. client := Client{
  43. BaseURL: input.BaseURL,
  44. HTTPClient: &http.Client{
  45. Timeout: time.Minute,
  46. },
  47. }
  48. if cfToken := os.Getenv("PORTER_CF_ACCESS_TOKEN"); cfToken != "" {
  49. client.cfToken = cfToken
  50. }
  51. if input.BearerToken != "" {
  52. client.Token = input.BearerToken
  53. return client, nil
  54. }
  55. if input.CookieFileName != "" {
  56. client.CookieFilePath = input.CookieFileName
  57. cookie, err := client.getCookie()
  58. if err != nil {
  59. return client, fmt.Errorf("error getting cooking from path: %w", err)
  60. }
  61. if cookie == nil {
  62. return client, errors.New("no cookie found at location")
  63. }
  64. return client, nil
  65. }
  66. return client, ErrNoAuthCredential
  67. }
  68. // ErrNoAuthCredential returns an error when no auth credentials have been provided such as cookies or tokens
  69. var ErrNoAuthCredential = errors.New("unable to create an API session with cookie nor token")
  70. // getRequestConfig defines configuration for a GET request
  71. type getRequestConfig struct {
  72. retryCount uint
  73. }
  74. // withRetryCount is a convenience function for setting the retry count
  75. func withRetryCount(retryCount uint) func(*getRequestConfig) {
  76. return func(o *getRequestConfig) {
  77. o.retryCount = retryCount
  78. }
  79. }
  80. // getRequest makes a GET request to the API
  81. func (c *Client) getRequest(relPath string, data interface{}, response interface{}, opts ...func(*getRequestConfig)) error {
  82. vals := make(map[string][]string)
  83. _ = schema.NewEncoder().Encode(data, vals)
  84. var err error
  85. urlVals := url.Values(vals)
  86. encodedURLVals := urlVals.Encode()
  87. var req *http.Request
  88. if encodedURLVals != "" {
  89. req, err = http.NewRequest(
  90. "GET",
  91. fmt.Sprintf("%s%s?%s", c.BaseURL, relPath, encodedURLVals),
  92. nil,
  93. )
  94. } else {
  95. req, err = http.NewRequest(
  96. "GET",
  97. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  98. nil,
  99. )
  100. }
  101. if err != nil {
  102. return err
  103. }
  104. config := &getRequestConfig{
  105. retryCount: 1,
  106. }
  107. for _, opt := range opts {
  108. opt(config)
  109. }
  110. var httpErr *types.ExternalError
  111. for i := 0; i < int(config.retryCount); i++ {
  112. httpErr, err = c.sendRequest(req, response, true)
  113. if httpErr == nil && err == nil {
  114. return nil
  115. }
  116. if i != int(config.retryCount)-1 {
  117. if httpErr != nil {
  118. fmt.Fprintf(os.Stderr, "Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  119. } else {
  120. fmt.Fprintf(os.Stderr, "Error: %v, retrying request...\n", err)
  121. }
  122. }
  123. }
  124. if httpErr != nil {
  125. return fmt.Errorf("%v", httpErr.Error)
  126. }
  127. return err
  128. }
  129. type postRequestOpts struct {
  130. // retryCount is the number of times to retry the request
  131. retryCount uint
  132. // onlyRetry500 will only retry the request if the status code is in the 500-range
  133. onlyRetry500 bool
  134. }
  135. func (c *Client) postRequest(relPath string, data interface{}, response interface{}, opts ...postRequestOpts) error {
  136. var retryCount uint = 1
  137. var onlyRetry500 bool = false
  138. if len(opts) > 0 {
  139. for _, opt := range opts {
  140. retryCount = opt.retryCount
  141. onlyRetry500 = opt.onlyRetry500
  142. }
  143. }
  144. var httpErr *types.ExternalError
  145. var sendErr error
  146. for i := 0; i < int(retryCount); i++ {
  147. strData, err := json.Marshal(data)
  148. if err != nil {
  149. return err
  150. }
  151. req, err := http.NewRequest(
  152. "POST",
  153. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  154. strings.NewReader(string(strData)),
  155. )
  156. if err != nil {
  157. return err
  158. }
  159. httpErr, err = c.sendRequest(req, response, true)
  160. if httpErr == nil && err == nil {
  161. return nil
  162. }
  163. sendErr = err
  164. if i != int(retryCount)-1 {
  165. if httpErr != nil {
  166. if onlyRetry500 && httpErr.Code < 500 {
  167. // if we only retry 500-range responses and this is not a 500-range response, do not retry, instead return the error
  168. return fmt.Errorf("%v", httpErr.Error)
  169. }
  170. fmt.Fprintf(os.Stderr, "Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  171. } else {
  172. fmt.Fprintf(os.Stderr, "Error: %v, retrying request...\n", err)
  173. }
  174. }
  175. }
  176. if httpErr != nil {
  177. return fmt.Errorf("%v", httpErr.Error)
  178. }
  179. return sendErr
  180. }
  181. type patchRequestOpts struct {
  182. retryCount uint
  183. }
  184. func (c *Client) patchRequest(relPath string, data interface{}, response interface{}, opts ...patchRequestOpts) error {
  185. var retryCount uint = 1
  186. if len(opts) > 0 {
  187. for _, opt := range opts {
  188. retryCount = opt.retryCount
  189. }
  190. }
  191. var httpErr *types.ExternalError
  192. var err error
  193. for i := 0; i < int(retryCount); i++ {
  194. strData, err := json.Marshal(data)
  195. if err != nil {
  196. return nil
  197. }
  198. req, err := http.NewRequest(
  199. "PATCH",
  200. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  201. strings.NewReader(string(strData)),
  202. )
  203. if err != nil {
  204. return err
  205. }
  206. httpErr, err = c.sendRequest(req, response, true)
  207. if httpErr == nil && err == nil {
  208. return nil
  209. }
  210. if i != int(retryCount)-1 {
  211. if httpErr != nil {
  212. fmt.Fprintf(os.Stderr, "Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  213. } else {
  214. fmt.Fprintf(os.Stderr, "Error: %v, retrying request...\n", err)
  215. }
  216. }
  217. }
  218. if httpErr != nil {
  219. return fmt.Errorf("%v", httpErr.Error)
  220. }
  221. return err
  222. }
  223. func (c *Client) deleteRequest(relPath string, data interface{}, response interface{}) error {
  224. strData, err := json.Marshal(data)
  225. if err != nil {
  226. return nil
  227. }
  228. req, err := http.NewRequest(
  229. "DELETE",
  230. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  231. strings.NewReader(string(strData)),
  232. )
  233. if err != nil {
  234. return err
  235. }
  236. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  237. if httpErr != nil {
  238. return fmt.Errorf("%v", httpErr.Error)
  239. }
  240. return err
  241. }
  242. return nil
  243. }
  244. func (c *Client) sendRequest(req *http.Request, v interface{}, useCookie bool) (*types.ExternalError, error) {
  245. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  246. req.Header.Set("Accept", "application/json; charset=utf-8")
  247. if c.Token != "" {
  248. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
  249. } else if cookie, _ := c.getCookie(); useCookie && cookie != nil {
  250. c.Cookie = cookie
  251. req.AddCookie(c.Cookie)
  252. }
  253. if c.cfToken != "" {
  254. req.Header.Set("cf-access-token", c.cfToken)
  255. }
  256. res, err := c.HTTPClient.Do(req)
  257. if err != nil {
  258. return nil, err
  259. }
  260. defer res.Body.Close()
  261. if cookies := res.Cookies(); len(cookies) == 1 {
  262. c.saveCookie(cookies[0])
  263. }
  264. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  265. var errRes types.ExternalError
  266. if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
  267. return &errRes, nil
  268. }
  269. return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
  270. }
  271. if v != nil {
  272. if err = json.NewDecoder(res.Body).Decode(v); err != nil {
  273. return nil, err
  274. }
  275. }
  276. return nil, nil
  277. }
  278. // CookieStorage for temporary fs-based cookie storage before jwt tokens
  279. type CookieStorage struct {
  280. Cookie *http.Cookie `json:"cookie"`
  281. }
  282. // saves single cookie to file
  283. func (c *Client) saveCookie(cookie *http.Cookie) error {
  284. data, err := json.Marshal(&CookieStorage{
  285. Cookie: cookie,
  286. })
  287. if err != nil {
  288. return err
  289. }
  290. return ioutil.WriteFile(c.CookieFilePath, data, 0o644)
  291. }
  292. // retrieves single cookie from file
  293. func (c *Client) getCookie() (*http.Cookie, error) {
  294. data, err := ioutil.ReadFile(c.CookieFilePath)
  295. if err != nil {
  296. return nil, err
  297. }
  298. cookie := &CookieStorage{}
  299. err = json.Unmarshal(data, cookie)
  300. if err != nil {
  301. return nil, err
  302. }
  303. return cookie.Cookie, nil
  304. }
  305. // retrieves single cookie from file
  306. func (c *Client) deleteCookie() error {
  307. // if file does not exist, return no error
  308. if _, err := os.Stat(c.CookieFilePath); os.IsNotExist(err) {
  309. return nil
  310. }
  311. return os.Remove(c.CookieFilePath)
  312. }
  313. type TokenProjectID struct {
  314. ProjectID uint `json:"project_id"`
  315. }
  316. func GetProjectIDFromToken(token string) (uint, bool, error) {
  317. var encoded string
  318. if tokenSplit := strings.Split(token, "."); len(tokenSplit) != 3 {
  319. return 0, false, fmt.Errorf("invalid jwt token format")
  320. } else {
  321. encoded = tokenSplit[1]
  322. }
  323. decodedBytes, err := base64.RawStdEncoding.DecodeString(encoded)
  324. if err != nil {
  325. return 0, false, fmt.Errorf("could not decode jwt token from base64: %v", err)
  326. }
  327. res := &TokenProjectID{}
  328. err = json.Unmarshal(decodedBytes, res)
  329. if err != nil {
  330. return 0, false, fmt.Errorf("could not get token project id: %v", err)
  331. }
  332. // if the project ID is 0, this is a token signed for a user, not a specific project
  333. if res.ProjectID == 0 {
  334. return 0, false, nil
  335. }
  336. return res.ProjectID, true, nil
  337. }