api.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 cookie 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 uint
  131. }
  132. func (c *Client) postRequest(relPath string, data interface{}, response interface{}, opts ...postRequestOpts) error {
  133. var retryCount uint = 1
  134. if len(opts) > 0 {
  135. for _, opt := range opts {
  136. retryCount = opt.retryCount
  137. }
  138. }
  139. var httpErr *types.ExternalError
  140. var err error
  141. for i := 0; i < int(retryCount); i++ {
  142. strData, err := json.Marshal(data)
  143. if err != nil {
  144. return err
  145. }
  146. req, err := http.NewRequest(
  147. "POST",
  148. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  149. strings.NewReader(string(strData)),
  150. )
  151. if err != nil {
  152. return err
  153. }
  154. httpErr, err = c.sendRequest(req, response, true)
  155. if httpErr == nil && err == nil {
  156. return nil
  157. }
  158. if i != int(retryCount)-1 {
  159. if httpErr != nil {
  160. fmt.Fprintf(os.Stderr, "Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  161. } else {
  162. fmt.Fprintf(os.Stderr, "Error: %v, retrying request...\n", err)
  163. }
  164. }
  165. }
  166. if httpErr != nil {
  167. return fmt.Errorf("%v", httpErr.Error)
  168. }
  169. return err
  170. }
  171. type patchRequestOpts struct {
  172. retryCount uint
  173. }
  174. func (c *Client) patchRequest(relPath string, data interface{}, response interface{}, opts ...patchRequestOpts) error {
  175. var retryCount uint = 1
  176. if len(opts) > 0 {
  177. for _, opt := range opts {
  178. retryCount = opt.retryCount
  179. }
  180. }
  181. var httpErr *types.ExternalError
  182. var err error
  183. for i := 0; i < int(retryCount); i++ {
  184. strData, err := json.Marshal(data)
  185. if err != nil {
  186. return nil
  187. }
  188. req, err := http.NewRequest(
  189. "PATCH",
  190. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  191. strings.NewReader(string(strData)),
  192. )
  193. if err != nil {
  194. return err
  195. }
  196. httpErr, err = c.sendRequest(req, response, true)
  197. if httpErr == nil && err == nil {
  198. return nil
  199. }
  200. if i != int(retryCount)-1 {
  201. if httpErr != nil {
  202. fmt.Fprintf(os.Stderr, "Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  203. } else {
  204. fmt.Fprintf(os.Stderr, "Error: %v, retrying request...\n", err)
  205. }
  206. }
  207. }
  208. if httpErr != nil {
  209. return fmt.Errorf("%v", httpErr.Error)
  210. }
  211. return err
  212. }
  213. func (c *Client) deleteRequest(relPath string, data interface{}, response interface{}) error {
  214. strData, err := json.Marshal(data)
  215. if err != nil {
  216. return nil
  217. }
  218. req, err := http.NewRequest(
  219. "DELETE",
  220. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  221. strings.NewReader(string(strData)),
  222. )
  223. if err != nil {
  224. return err
  225. }
  226. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  227. if httpErr != nil {
  228. return fmt.Errorf("%v", httpErr.Error)
  229. }
  230. return err
  231. }
  232. return nil
  233. }
  234. func (c *Client) sendRequest(req *http.Request, v interface{}, useCookie bool) (*types.ExternalError, error) {
  235. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  236. req.Header.Set("Accept", "application/json; charset=utf-8")
  237. if c.Token != "" {
  238. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
  239. } else if cookie, _ := c.getCookie(); useCookie && cookie != nil {
  240. c.Cookie = cookie
  241. req.AddCookie(c.Cookie)
  242. }
  243. if c.cfToken != "" {
  244. req.Header.Set("cf-access-token", c.cfToken)
  245. }
  246. res, err := c.HTTPClient.Do(req)
  247. if err != nil {
  248. return nil, err
  249. }
  250. defer res.Body.Close()
  251. if cookies := res.Cookies(); len(cookies) == 1 {
  252. c.saveCookie(cookies[0])
  253. }
  254. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  255. var errRes types.ExternalError
  256. if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
  257. return &errRes, nil
  258. }
  259. return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
  260. }
  261. if v != nil {
  262. if err = json.NewDecoder(res.Body).Decode(v); err != nil {
  263. return nil, err
  264. }
  265. }
  266. return nil, nil
  267. }
  268. // CookieStorage for temporary fs-based cookie storage before jwt tokens
  269. type CookieStorage struct {
  270. Cookie *http.Cookie `json:"cookie"`
  271. }
  272. // saves single cookie to file
  273. func (c *Client) saveCookie(cookie *http.Cookie) error {
  274. data, err := json.Marshal(&CookieStorage{
  275. Cookie: cookie,
  276. })
  277. if err != nil {
  278. return err
  279. }
  280. return ioutil.WriteFile(c.CookieFilePath, data, 0o644)
  281. }
  282. // retrieves single cookie from file
  283. func (c *Client) getCookie() (*http.Cookie, error) {
  284. data, err := ioutil.ReadFile(c.CookieFilePath)
  285. if err != nil {
  286. return nil, err
  287. }
  288. cookie := &CookieStorage{}
  289. err = json.Unmarshal(data, cookie)
  290. if err != nil {
  291. return nil, err
  292. }
  293. return cookie.Cookie, nil
  294. }
  295. // retrieves single cookie from file
  296. func (c *Client) deleteCookie() error {
  297. // if file does not exist, return no error
  298. if _, err := os.Stat(c.CookieFilePath); os.IsNotExist(err) {
  299. return nil
  300. }
  301. return os.Remove(c.CookieFilePath)
  302. }
  303. type TokenProjectID struct {
  304. ProjectID uint `json:"project_id"`
  305. }
  306. func GetProjectIDFromToken(token string) (uint, bool, error) {
  307. var encoded string
  308. if tokenSplit := strings.Split(token, "."); len(tokenSplit) != 3 {
  309. return 0, false, fmt.Errorf("invalid jwt token format")
  310. } else {
  311. encoded = tokenSplit[1]
  312. }
  313. decodedBytes, err := base64.RawStdEncoding.DecodeString(encoded)
  314. if err != nil {
  315. return 0, false, fmt.Errorf("could not decode jwt token from base64: %v", err)
  316. }
  317. res := &TokenProjectID{}
  318. err = json.Unmarshal(decodedBytes, res)
  319. if err != nil {
  320. return 0, false, fmt.Errorf("could not get token project id: %v", err)
  321. }
  322. // if the project ID is 0, this is a token signed for a user, not a specific project
  323. if res.ProjectID == 0 {
  324. return 0, false, nil
  325. }
  326. return res.ProjectID, true, nil
  327. }