api.go 9.1 KB

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