2
0

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