api.go 11 KB

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