api.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "k8s.io/client-go/util/homedir"
  14. )
  15. // Client represents the client for the Porter API
  16. type Client struct {
  17. BaseURL string
  18. HTTPClient *http.Client
  19. Cookie *http.Cookie
  20. CookieFilePath string
  21. Token string
  22. }
  23. // HTTPError is the Porter error response returned if a request fails
  24. type HTTPError struct {
  25. Code uint `json:"code"`
  26. Errors []string `json:"errors"`
  27. }
  28. type EventStatus int64
  29. const (
  30. EventStatusSuccess EventStatus = 1
  31. EventStatusInProgress = 2
  32. EventStatusFailed = 3
  33. )
  34. // Event represents an event that happens during
  35. type Event struct {
  36. ID string `json:"event_id"` // events with the same id wil be treated the same, and the highest index one is retained
  37. Name string `json:"name"`
  38. Index int64 `json:"index"` // priority of the event, used for sorting
  39. Status EventStatus `json:"status"`
  40. Info string `json:"info"` // extra information (can be error or success)
  41. }
  42. // StreamEventForm is used to send event data to the api
  43. type StreamEventForm struct {
  44. Event `json:"event"`
  45. Token string `json:"token"`
  46. ClusterID uint `json:"cluster_id"`
  47. }
  48. // NewClient constructs a new client based on a set of options
  49. func NewClient(baseURL string, cookieFileName string) *Client {
  50. home := homedir.HomeDir()
  51. cookieFilePath := filepath.Join(home, ".porter", cookieFileName)
  52. client := &Client{
  53. BaseURL: baseURL,
  54. CookieFilePath: cookieFilePath,
  55. HTTPClient: &http.Client{
  56. Timeout: time.Minute,
  57. },
  58. }
  59. cookie, _ := client.getCookie()
  60. if cookie != nil {
  61. client.Cookie = cookie
  62. }
  63. return client
  64. }
  65. func NewClientWithToken(baseURL, token string) *Client {
  66. client := &Client{
  67. BaseURL: baseURL,
  68. Token: token,
  69. HTTPClient: &http.Client{
  70. Timeout: time.Minute,
  71. },
  72. }
  73. return client
  74. }
  75. func (c *Client) sendRequest(req *http.Request, v interface{}, useCookie bool) (*HTTPError, error) {
  76. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  77. req.Header.Set("Accept", "application/json; charset=utf-8")
  78. if c.Token != "" {
  79. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
  80. } else if cookie, _ := c.getCookie(); useCookie && cookie != nil {
  81. c.Cookie = cookie
  82. req.AddCookie(c.Cookie)
  83. }
  84. res, err := c.HTTPClient.Do(req)
  85. if err != nil {
  86. return nil, err
  87. }
  88. defer res.Body.Close()
  89. if cookies := res.Cookies(); len(cookies) == 1 {
  90. c.saveCookie(cookies[0])
  91. }
  92. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  93. var errRes HTTPError
  94. if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
  95. return &errRes, nil
  96. }
  97. return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
  98. }
  99. if v != nil {
  100. if err = json.NewDecoder(res.Body).Decode(v); err != nil {
  101. return nil, err
  102. }
  103. }
  104. return nil, nil
  105. }
  106. // CookieStorage for temporary fs-based cookie storage before jwt tokens
  107. type CookieStorage struct {
  108. Cookie *http.Cookie `json:"cookie"`
  109. }
  110. // saves single cookie to file
  111. func (c *Client) saveCookie(cookie *http.Cookie) error {
  112. data, err := json.Marshal(&CookieStorage{
  113. Cookie: cookie,
  114. })
  115. if err != nil {
  116. return err
  117. }
  118. return ioutil.WriteFile(c.CookieFilePath, data, 0644)
  119. }
  120. // StreamEvent sends an event from deployment to the api
  121. func (c *Client) StreamEvent(event Event, token string, projID uint, clusterID uint, name string) error {
  122. form := StreamEventForm{
  123. Event: event,
  124. Token: token,
  125. ClusterID: clusterID,
  126. }
  127. body := new(bytes.Buffer)
  128. err := json.NewEncoder(body).Encode(form)
  129. if err != nil {
  130. return err
  131. }
  132. req, err := http.NewRequest(
  133. "POST",
  134. fmt.Sprintf("%s/projects/%d/releases/%s/steps", c.BaseURL, projID, name),
  135. body,
  136. )
  137. if err != nil {
  138. return err
  139. }
  140. req = req.WithContext(context.Background())
  141. if httpErr, err := c.sendRequest(req, nil, true); httpErr != nil || err != nil {
  142. if httpErr != nil {
  143. return fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors)
  144. }
  145. return err
  146. }
  147. return nil
  148. }
  149. // retrieves single cookie from file
  150. func (c *Client) getCookie() (*http.Cookie, error) {
  151. data, err := ioutil.ReadFile(c.CookieFilePath)
  152. if err != nil {
  153. return nil, err
  154. }
  155. cookie := &CookieStorage{}
  156. err = json.Unmarshal(data, cookie)
  157. if err != nil {
  158. return nil, err
  159. }
  160. return cookie.Cookie, nil
  161. }
  162. type TokenProjectID struct {
  163. ProjectID uint `json:"project_id"`
  164. }
  165. func GetProjectIDFromToken(token string) (uint, bool, error) {
  166. var encoded string
  167. if tokenSplit := strings.Split(token, "."); len(tokenSplit) != 3 {
  168. return 0, false, fmt.Errorf("invalid jwt token format")
  169. } else {
  170. encoded = tokenSplit[1]
  171. }
  172. decodedBytes, err := base64.RawStdEncoding.DecodeString(encoded)
  173. if err != nil {
  174. return 0, false, fmt.Errorf("could not decode jwt token from base64: %v", err)
  175. }
  176. res := &TokenProjectID{}
  177. err = json.Unmarshal(decodedBytes, res)
  178. if err != nil {
  179. return 0, false, fmt.Errorf("could not get token project id: %v", err)
  180. }
  181. // if the project ID is 0, this is a token signed for a user, not a specific project
  182. if res.ProjectID == 0 {
  183. return 0, false, nil
  184. }
  185. return res.ProjectID, true, nil
  186. }