api.go 9.3 KB

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