api.go 8.4 KB

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