api.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. Name string `json:"name"`
  48. Namespace string `json:"namespace"`
  49. }
  50. // NewClient constructs a new client based on a set of options
  51. func NewClient(baseURL string, cookieFileName string) *Client {
  52. home := homedir.HomeDir()
  53. cookieFilePath := filepath.Join(home, ".porter", cookieFileName)
  54. client := &Client{
  55. BaseURL: baseURL,
  56. CookieFilePath: cookieFilePath,
  57. HTTPClient: &http.Client{
  58. Timeout: time.Minute,
  59. },
  60. }
  61. cookie, _ := client.getCookie()
  62. if cookie != nil {
  63. client.Cookie = cookie
  64. }
  65. return client
  66. }
  67. func NewClientWithToken(baseURL, token string) *Client {
  68. client := &Client{
  69. BaseURL: baseURL,
  70. Token: token,
  71. HTTPClient: &http.Client{
  72. Timeout: time.Minute,
  73. },
  74. }
  75. return client
  76. }
  77. func (c *Client) sendRequest(req *http.Request, v interface{}, useCookie bool) (*HTTPError, error) {
  78. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  79. req.Header.Set("Accept", "application/json; charset=utf-8")
  80. if c.Token != "" {
  81. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
  82. } else if cookie, _ := c.getCookie(); useCookie && cookie != nil {
  83. c.Cookie = cookie
  84. req.AddCookie(c.Cookie)
  85. }
  86. res, err := c.HTTPClient.Do(req)
  87. if err != nil {
  88. return nil, err
  89. }
  90. defer res.Body.Close()
  91. if cookies := res.Cookies(); len(cookies) == 1 {
  92. c.saveCookie(cookies[0])
  93. }
  94. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  95. var errRes HTTPError
  96. if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
  97. return &errRes, nil
  98. }
  99. return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
  100. }
  101. if v != nil {
  102. if err = json.NewDecoder(res.Body).Decode(v); err != nil {
  103. return nil, err
  104. }
  105. }
  106. return nil, nil
  107. }
  108. // CookieStorage for temporary fs-based cookie storage before jwt tokens
  109. type CookieStorage struct {
  110. Cookie *http.Cookie `json:"cookie"`
  111. }
  112. // saves single cookie to file
  113. func (c *Client) saveCookie(cookie *http.Cookie) error {
  114. data, err := json.Marshal(&CookieStorage{
  115. Cookie: cookie,
  116. })
  117. if err != nil {
  118. return err
  119. }
  120. return ioutil.WriteFile(c.CookieFilePath, data, 0644)
  121. }
  122. // StreamEvent sends an event from deployment to the api
  123. func (c *Client) StreamEvent(event Event, projID uint, clusterID uint, name string, namespace string) error {
  124. form := StreamEventForm{
  125. Event: event,
  126. ClusterID: clusterID,
  127. Name: name,
  128. Namespace: namespace,
  129. }
  130. body := new(bytes.Buffer)
  131. err := json.NewEncoder(body).Encode(form)
  132. if err != nil {
  133. return err
  134. }
  135. req, err := http.NewRequest(
  136. "POST",
  137. fmt.Sprintf("%s/projects/%d/releases/%s/steps", c.BaseURL, projID, name),
  138. body,
  139. )
  140. if err != nil {
  141. return err
  142. }
  143. req = req.WithContext(context.Background())
  144. if httpErr, err := c.sendRequest(req, nil, true); httpErr != nil || err != nil {
  145. if httpErr != nil {
  146. return fmt.Errorf("code %d, errors %v", httpErr.Code, httpErr.Errors)
  147. }
  148. return err
  149. }
  150. return nil
  151. }
  152. // retrieves single cookie from file
  153. func (c *Client) getCookie() (*http.Cookie, error) {
  154. data, err := ioutil.ReadFile(c.CookieFilePath)
  155. if err != nil {
  156. return nil, err
  157. }
  158. cookie := &CookieStorage{}
  159. err = json.Unmarshal(data, cookie)
  160. if err != nil {
  161. return nil, err
  162. }
  163. return cookie.Cookie, nil
  164. }
  165. type TokenProjectID struct {
  166. ProjectID uint `json:"project_id"`
  167. }
  168. func GetProjectIDFromToken(token string) (uint, bool, error) {
  169. var encoded string
  170. if tokenSplit := strings.Split(token, "."); len(tokenSplit) != 3 {
  171. return 0, false, fmt.Errorf("invalid jwt token format")
  172. } else {
  173. encoded = tokenSplit[1]
  174. }
  175. decodedBytes, err := base64.RawStdEncoding.DecodeString(encoded)
  176. if err != nil {
  177. return 0, false, fmt.Errorf("could not decode jwt token from base64: %v", err)
  178. }
  179. res := &TokenProjectID{}
  180. err = json.Unmarshal(decodedBytes, res)
  181. if err != nil {
  182. return 0, false, fmt.Errorf("could not get token project id: %v", err)
  183. }
  184. // if the project ID is 0, this is a token signed for a user, not a specific project
  185. if res.ProjectID == 0 {
  186. return 0, false, nil
  187. }
  188. return res.ProjectID, true, nil
  189. }