api.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. package client
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/gorilla/schema"
  13. "github.com/porter-dev/porter/api/types"
  14. "k8s.io/client-go/util/homedir"
  15. )
  16. // Client represents the client for the Porter API
  17. type Client struct {
  18. BaseURL string
  19. HTTPClient *http.Client
  20. Cookie *http.Cookie
  21. CookieFilePath string
  22. Token string
  23. cfToken string
  24. }
  25. // NewClient constructs a new client based on a set of options
  26. func NewClient(baseURL string, cookieFileName string) *Client {
  27. home := homedir.HomeDir()
  28. cookieFilePath := filepath.Join(home, ".porter", cookieFileName)
  29. client := &Client{
  30. BaseURL: baseURL,
  31. CookieFilePath: cookieFilePath,
  32. HTTPClient: &http.Client{
  33. Timeout: time.Minute,
  34. },
  35. }
  36. cookie, _ := client.getCookie()
  37. if cookie != nil {
  38. client.Cookie = cookie
  39. }
  40. // look for a cloudflare access token specifically for Porter
  41. if cfToken := os.Getenv("PORTER_CF_ACCESS_TOKEN"); cfToken != "" {
  42. client.cfToken = cfToken
  43. }
  44. return client
  45. }
  46. func NewClientWithToken(baseURL, token string) *Client {
  47. client := &Client{
  48. BaseURL: baseURL,
  49. Token: token,
  50. HTTPClient: &http.Client{
  51. Timeout: time.Minute,
  52. },
  53. }
  54. // look for a cloudflare access token specifically for Porter
  55. if cfToken := os.Getenv("PORTER_CF_ACCESS_TOKEN"); cfToken != "" {
  56. client.cfToken = cfToken
  57. }
  58. return client
  59. }
  60. func (c *Client) getRequest(relPath string, data interface{}, response interface{}) error {
  61. vals := make(map[string][]string)
  62. err := schema.NewEncoder().Encode(data, vals)
  63. if err != nil {
  64. return fmt.Errorf("error encoding data for GET request: %w", err)
  65. }
  66. urlVals := url.Values(vals)
  67. encodedURLVals := urlVals.Encode()
  68. var req *http.Request
  69. if encodedURLVals != "" {
  70. req, err = http.NewRequest(
  71. "GET",
  72. fmt.Sprintf("%s%s?%s", c.BaseURL, relPath, encodedURLVals),
  73. nil,
  74. )
  75. } else {
  76. req, err = http.NewRequest(
  77. "GET",
  78. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  79. nil,
  80. )
  81. }
  82. if err != nil {
  83. return err
  84. }
  85. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  86. if httpErr != nil {
  87. return fmt.Errorf("%s", httpErr.Error)
  88. }
  89. return err
  90. }
  91. return nil
  92. }
  93. type postRequestOpts struct {
  94. retryCount uint
  95. }
  96. func (c *Client) postRequest(relPath string, data interface{}, response interface{}, opts ...postRequestOpts) error {
  97. var retryCount uint = 1
  98. if len(opts) > 0 {
  99. for _, opt := range opts {
  100. retryCount = opt.retryCount
  101. }
  102. }
  103. var httpErr *types.ExternalError
  104. var err error
  105. for i := 0; i < int(retryCount); i++ {
  106. strData, err := json.Marshal(data)
  107. if err != nil {
  108. return err
  109. }
  110. req, err := http.NewRequest(
  111. "POST",
  112. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  113. strings.NewReader(string(strData)),
  114. )
  115. if err != nil {
  116. return err
  117. }
  118. httpErr, err = c.sendRequest(req, response, true)
  119. if httpErr == nil && err == nil {
  120. return nil
  121. }
  122. if i != int(retryCount)-1 {
  123. if httpErr != nil {
  124. fmt.Fprintf(os.Stderr, "Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  125. } else {
  126. fmt.Fprintf(os.Stderr, "Error: %v, retrying request...\n", err)
  127. }
  128. }
  129. }
  130. if httpErr != nil {
  131. return fmt.Errorf("%s", httpErr.Error)
  132. }
  133. return err
  134. }
  135. type patchRequestOpts struct {
  136. retryCount uint
  137. }
  138. func (c *Client) patchRequest(relPath string, data interface{}, response interface{}, opts ...patchRequestOpts) error {
  139. var retryCount uint = 1
  140. if len(opts) > 0 {
  141. for _, opt := range opts {
  142. retryCount = opt.retryCount
  143. }
  144. }
  145. var httpErr *types.ExternalError
  146. var err error
  147. for i := 0; i < int(retryCount); i++ {
  148. strData, err := json.Marshal(data)
  149. if err != nil {
  150. return nil
  151. }
  152. req, err := http.NewRequest(
  153. "PATCH",
  154. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  155. strings.NewReader(string(strData)),
  156. )
  157. if err != nil {
  158. return err
  159. }
  160. httpErr, err = c.sendRequest(req, response, true)
  161. if httpErr == nil && err == nil {
  162. return nil
  163. }
  164. if i != int(retryCount)-1 {
  165. if httpErr != nil {
  166. fmt.Fprintf(os.Stderr, "Error: %s (status code %d), retrying request...\n", httpErr.Error, httpErr.Code)
  167. } else {
  168. fmt.Fprintf(os.Stderr, "Error: %v, retrying request...\n", err)
  169. }
  170. }
  171. }
  172. if httpErr != nil {
  173. return fmt.Errorf("%s", httpErr.Error)
  174. }
  175. return err
  176. }
  177. func (c *Client) deleteRequest(relPath string, data interface{}, response interface{}) error {
  178. strData, err := json.Marshal(data)
  179. if err != nil {
  180. return nil
  181. }
  182. req, err := http.NewRequest(
  183. "DELETE",
  184. fmt.Sprintf("%s%s", c.BaseURL, relPath),
  185. strings.NewReader(string(strData)),
  186. )
  187. if err != nil {
  188. return err
  189. }
  190. if httpErr, err := c.sendRequest(req, response, true); httpErr != nil || err != nil {
  191. if httpErr != nil {
  192. return fmt.Errorf("%s", httpErr.Error)
  193. }
  194. return err
  195. }
  196. return nil
  197. }
  198. func (c *Client) sendRequest(req *http.Request, v interface{}, useCookie bool) (*types.ExternalError, error) {
  199. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  200. req.Header.Set("Accept", "application/json; charset=utf-8")
  201. if c.Token != "" {
  202. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
  203. } else if cookie, _ := c.getCookie(); useCookie && cookie != nil {
  204. c.Cookie = cookie
  205. req.AddCookie(c.Cookie)
  206. }
  207. if c.cfToken != "" {
  208. req.Header.Set("cf-access-token", c.cfToken)
  209. }
  210. res, err := c.HTTPClient.Do(req)
  211. if err != nil {
  212. return nil, err
  213. }
  214. defer res.Body.Close()
  215. if cookies := res.Cookies(); len(cookies) == 1 {
  216. c.saveCookie(cookies[0])
  217. }
  218. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  219. var errRes types.ExternalError
  220. if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
  221. return &errRes, nil
  222. }
  223. return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
  224. }
  225. if v != nil {
  226. if err = json.NewDecoder(res.Body).Decode(v); err != nil {
  227. return nil, err
  228. }
  229. }
  230. return nil, nil
  231. }
  232. // CookieStorage for temporary fs-based cookie storage before jwt tokens
  233. type CookieStorage struct {
  234. Cookie *http.Cookie `json:"cookie"`
  235. }
  236. // saves single cookie to file
  237. func (c *Client) saveCookie(cookie *http.Cookie) error {
  238. data, err := json.Marshal(&CookieStorage{
  239. Cookie: cookie,
  240. })
  241. if err != nil {
  242. return err
  243. }
  244. return os.WriteFile(c.CookieFilePath, data, 0o644)
  245. }
  246. // retrieves single cookie from file
  247. func (c *Client) getCookie() (*http.Cookie, error) {
  248. data, err := os.ReadFile(c.CookieFilePath)
  249. if err != nil {
  250. return nil, err
  251. }
  252. cookie := &CookieStorage{}
  253. err = json.Unmarshal(data, cookie)
  254. if err != nil {
  255. return nil, err
  256. }
  257. return cookie.Cookie, nil
  258. }
  259. // retrieves single cookie from file
  260. func (c *Client) deleteCookie() error {
  261. // if file does not exist, return no error
  262. if _, err := os.Stat(c.CookieFilePath); os.IsNotExist(err) {
  263. return nil
  264. }
  265. return os.Remove(c.CookieFilePath)
  266. }
  267. type TokenProjectID struct {
  268. ProjectID uint `json:"project_id"`
  269. }
  270. func GetProjectIDFromToken(token string) (uint, bool, error) {
  271. var encoded string
  272. if tokenSplit := strings.Split(token, "."); len(tokenSplit) != 3 {
  273. return 0, false, fmt.Errorf("invalid jwt token format")
  274. } else {
  275. encoded = tokenSplit[1]
  276. }
  277. decodedBytes, err := base64.RawStdEncoding.DecodeString(encoded)
  278. if err != nil {
  279. return 0, false, fmt.Errorf("could not decode jwt token from base64: %v", err)
  280. }
  281. res := &TokenProjectID{}
  282. err = json.Unmarshal(decodedBytes, res)
  283. if err != nil {
  284. return 0, false, fmt.Errorf("could not get token project id: %v", err)
  285. }
  286. // if the project ID is 0, this is a token signed for a user, not a specific project
  287. if res.ProjectID == 0 {
  288. return 0, false, nil
  289. }
  290. return res.ProjectID, true, nil
  291. }