diff --git a/agent/main.go b/agent/main.go index 7feea5dbb..e9444a790 100644 --- a/agent/main.go +++ b/agent/main.go @@ -24,7 +24,6 @@ import ( "github.com/up9inc/mizu/agent/pkg/oas" "github.com/up9inc/mizu/agent/pkg/routes" "github.com/up9inc/mizu/agent/pkg/servicemap" - "github.com/up9inc/mizu/agent/pkg/up9" "github.com/up9inc/mizu/agent/pkg/utils" "github.com/up9inc/mizu/agent/pkg/api" @@ -72,13 +71,13 @@ func main() { } else if *tapperMode { runInTapperMode() } else if *apiServerMode { - app := runInApiServerMode(*namespace) + ginApp := runInApiServerMode(*namespace) if *profiler { - pprof.Register(app) + pprof.Register(ginApp) } - utils.StartServer(app) + utils.StartServer(ginApp) } else if *harsReaderMode { runInHarReaderMode() @@ -92,9 +91,9 @@ func main() { } func hostApi(socketHarOutputChannel chan<- *tapApi.OutputChannelItem) *gin.Engine { - app := gin.Default() + ginApp := gin.Default() - app.GET("/echo", func(c *gin.Context) { + ginApp.GET("/echo", func(c *gin.Context) { c.JSON(http.StatusOK, "Here is Mizu agent") }) @@ -102,7 +101,7 @@ func hostApi(socketHarOutputChannel chan<- *tapApi.OutputChannelItem) *gin.Engin SocketOutChannel: socketHarOutputChannel, } - app.Use(disableRootStaticCache()) + ginApp.Use(disableRootStaticCache()) staticFolder := "./site" indexStaticFile := staticFolder + "/index.html" @@ -110,30 +109,30 @@ func hostApi(socketHarOutputChannel chan<- *tapApi.OutputChannelItem) *gin.Engin logger.Log.Errorf("Error setting ui flags, err: %v", err) } - app.Use(static.ServeRoot("/", staticFolder)) - app.NoRoute(func(c *gin.Context) { + ginApp.Use(static.ServeRoot("/", staticFolder)) + ginApp.NoRoute(func(c *gin.Context) { c.File(indexStaticFile) }) - app.Use(middlewares.CORSMiddleware()) // This has to be called after the static middleware, does not work if its called before + ginApp.Use(middlewares.CORSMiddleware()) // This has to be called after the static middleware, does not work if it's called before - api.WebSocketRoutes(app, &eventHandlers) + api.WebSocketRoutes(ginApp, &eventHandlers) if config.Config.OAS { - routes.OASRoutes(app) + routes.OASRoutes(ginApp) } if config.Config.ServiceMap { - routes.ServiceMapRoutes(app) + routes.ServiceMapRoutes(ginApp) } - routes.QueryRoutes(app) - routes.EntriesRoutes(app) - routes.MetadataRoutes(app) - routes.StatusRoutes(app) - routes.DbRoutes(app) + routes.QueryRoutes(ginApp) + routes.EntriesRoutes(ginApp) + routes.MetadataRoutes(ginApp) + routes.StatusRoutes(ginApp) + routes.DbRoutes(ginApp) - return app + return ginApp } func runInApiServerMode(namespace string) *gin.Engine { @@ -145,13 +144,6 @@ func runInApiServerMode(namespace string) *gin.Engine { enableExpFeatureIfNeeded() - syncEntriesConfig := getSyncEntriesConfig() - if syncEntriesConfig != nil { - if err := up9.SyncEntries(syncEntriesConfig); err != nil { - logger.Log.Error("Error syncing entries, err: %v", err) - } - } - return hostApi(app.GetEntryInputChannel()) } @@ -218,21 +210,6 @@ func enableExpFeatureIfNeeded() { } } -func getSyncEntriesConfig() *shared.SyncEntriesConfig { - syncEntriesConfigJson := os.Getenv(shared.SyncEntriesConfigEnvVar) - if syncEntriesConfigJson == "" { - return nil - } - - var syncEntriesConfig = &shared.SyncEntriesConfig{} - err := json.Unmarshal([]byte(syncEntriesConfigJson), syncEntriesConfig) - if err != nil { - panic(fmt.Sprintf("env var %s's value of %s is invalid! json must match the shared.SyncEntriesConfig struct, err: %v", shared.SyncEntriesConfigEnvVar, syncEntriesConfigJson, err)) - } - - return syncEntriesConfig -} - func disableRootStaticCache() gin.HandlerFunc { return func(c *gin.Context) { if c.Request.RequestURI == "/" { diff --git a/agent/pkg/api/socket_server_handlers.go b/agent/pkg/api/socket_server_handlers.go index 4fc82d8fe..72288e5ca 100644 --- a/agent/pkg/api/socket_server_handlers.go +++ b/agent/pkg/api/socket_server_handlers.go @@ -10,7 +10,6 @@ import ( "github.com/up9inc/mizu/agent/pkg/models" "github.com/up9inc/mizu/agent/pkg/providers/tappedPods" "github.com/up9inc/mizu/agent/pkg/providers/tappers" - "github.com/up9inc/mizu/agent/pkg/up9" tapApi "github.com/up9inc/mizu/tap/api" @@ -31,10 +30,6 @@ type RoutesEventHandlers struct { SocketOutChannel chan<- *tapApi.OutputChannelItem } -func init() { - go up9.UpdateAnalyzeStatus(BroadcastToBrowserClients) -} - func (h *RoutesEventHandlers) WebSocketConnect(_ *gin.Context, socketId int, isTapper bool) { if isTapper { logger.Log.Infof("Websocket event - Tapper connected, socket ID: %d", socketId) diff --git a/agent/pkg/controllers/status_controller.go b/agent/pkg/controllers/status_controller.go index 215b9a9cf..817ac006a 100644 --- a/agent/pkg/controllers/status_controller.go +++ b/agent/pkg/controllers/status_controller.go @@ -11,7 +11,6 @@ import ( "github.com/up9inc/mizu/agent/pkg/providers" "github.com/up9inc/mizu/agent/pkg/providers/tappedPods" "github.com/up9inc/mizu/agent/pkg/providers/tappers" - "github.com/up9inc/mizu/agent/pkg/up9" "github.com/up9inc/mizu/agent/pkg/validation" "github.com/up9inc/mizu/logger" "github.com/up9inc/mizu/shared" @@ -71,25 +70,11 @@ func GetConnectedTappersCount(c *gin.Context) { c.JSON(http.StatusOK, tappers.GetConnectedCount()) } -func GetAuthStatus(c *gin.Context) { - authStatus, err := providers.GetAuthStatus() - if err != nil { - c.JSON(http.StatusInternalServerError, err) - return - } - - c.JSON(http.StatusOK, authStatus) -} - func GetTappingStatus(c *gin.Context) { tappedPodsStatus := tappedPods.GetTappedPodsStatus() c.JSON(http.StatusOK, tappedPodsStatus) } -func AnalyzeInformation(c *gin.Context) { - c.JSON(http.StatusOK, up9.GetAnalyzeInfo()) -} - func GetGeneralStats(c *gin.Context) { c.JSON(http.StatusOK, providers.GetGeneralStats()) } diff --git a/agent/pkg/models/models.go b/agent/pkg/models/models.go index 2fa113357..a145fdc90 100644 --- a/agent/pkg/models/models.go +++ b/agent/pkg/models/models.go @@ -43,11 +43,6 @@ type WebSocketTappedEntryMessage struct { Data *tapApi.OutputChannelItem } -type AuthStatus struct { - Email string `json:"email"` - Model string `json:"model"` -} - type ToastMessage struct { Type string `json:"type"` AutoClose uint `json:"autoClose"` diff --git a/agent/pkg/providers/status_provider.go b/agent/pkg/providers/status_provider.go deleted file mode 100644 index dbd1d3ac9..000000000 --- a/agent/pkg/providers/status_provider.go +++ /dev/null @@ -1,47 +0,0 @@ -package providers - -import ( - "encoding/json" - "fmt" - "os" - - "github.com/up9inc/mizu/agent/pkg/models" - "github.com/up9inc/mizu/shared" -) - -var ( - authStatus *models.AuthStatus -) - -func GetAuthStatus() (*models.AuthStatus, error) { - if authStatus == nil { - syncEntriesConfigJson := os.Getenv(shared.SyncEntriesConfigEnvVar) - if syncEntriesConfigJson == "" { - authStatus = &models.AuthStatus{} - return authStatus, nil - } - - syncEntriesConfig := &shared.SyncEntriesConfig{} - err := json.Unmarshal([]byte(syncEntriesConfigJson), syncEntriesConfig) - if err != nil { - return nil, fmt.Errorf("failed to marshal sync entries config, err: %v", err) - } - - if syncEntriesConfig.Token == "" { - authStatus = &models.AuthStatus{} - return authStatus, nil - } - - tokenEmail, err := shared.GetTokenEmail(syncEntriesConfig.Token) - if err != nil { - return nil, fmt.Errorf("failed to get token email, err: %v", err) - } - - authStatus = &models.AuthStatus{ - Email: tokenEmail, - Model: syncEntriesConfig.Workspace, - } - } - - return authStatus, nil -} diff --git a/agent/pkg/routes/status_routes.go b/agent/pkg/routes/status_routes.go index e83dfa911..7914df2b1 100644 --- a/agent/pkg/routes/status_routes.go +++ b/agent/pkg/routes/status_routes.go @@ -15,10 +15,6 @@ func StatusRoutes(ginApp *gin.Engine) { routeGroup.GET("/connectedTappersCount", controllers.GetConnectedTappersCount) routeGroup.GET("/tap", controllers.GetTappingStatus) - routeGroup.GET("/auth", controllers.GetAuthStatus) - - routeGroup.GET("/analyze", controllers.AnalyzeInformation) - routeGroup.GET("/general", controllers.GetGeneralStats) // get general stats about entries in DB routeGroup.GET("/resolving", controllers.GetCurrentResolvingInformation) diff --git a/agent/pkg/up9/main.go b/agent/pkg/up9/main.go deleted file mode 100644 index 0a9ff13ee..000000000 --- a/agent/pkg/up9/main.go +++ /dev/null @@ -1,353 +0,0 @@ -package up9 - -import ( - "bytes" - "compress/zlib" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "regexp" - "strings" - "sync" - "time" - - "github.com/up9inc/mizu/agent/pkg/har" - "github.com/up9inc/mizu/agent/pkg/utils" - - basenine "github.com/up9inc/basenine/client/go" - "github.com/up9inc/mizu/logger" - "github.com/up9inc/mizu/shared" - tapApi "github.com/up9inc/mizu/tap/api" -) - -const ( - AnalyzeCheckSleepTime = 5 * time.Second - SentCountLogInterval = 100 -) - -type GuestToken struct { - Token string `json:"token"` - Model string `json:"model"` -} - -type ModelStatus struct { - LastMajorGeneration float64 `json:"lastMajorGeneration"` -} - -func GetRemoteUrl(analyzeDestination string, analyzeModel string, analyzeToken string, guestMode bool) string { - if guestMode { - return fmt.Sprintf("https://%s/share/%s", analyzeDestination, analyzeToken) - } - - return fmt.Sprintf("https://%s/app/workspaces/%s", analyzeDestination, analyzeModel) -} - -func CheckIfModelReady(analyzeDestination string, analyzeModel string, analyzeToken string, guestMode bool) bool { - statusUrl, _ := url.Parse(fmt.Sprintf("https://trcc.%s/models/%s/status", analyzeDestination, analyzeModel)) - - authHeader := getAuthHeader(guestMode) - req := &http.Request{ - Method: http.MethodGet, - URL: statusUrl, - Header: map[string][]string{ - "Content-Type": {"application/json"}, - authHeader: {analyzeToken}, - }, - } - statusResp, err := http.DefaultClient.Do(req) - if err != nil { - return false - } - defer statusResp.Body.Close() - - target := &ModelStatus{} - _ = json.NewDecoder(statusResp.Body).Decode(&target) - - return target.LastMajorGeneration > 0 -} - -func getAuthHeader(guestMode bool) string { - if guestMode { - return "Guest-Auth" - } - - return "Authorization" -} - -func GetTrafficDumpUrl(analyzeDestination string, analyzeModel string) *url.URL { - strUrl := fmt.Sprintf("https://traffic.%s/dumpTrafficBulk/%s", analyzeDestination, analyzeModel) - postUrl, _ := url.Parse(strUrl) - return postUrl -} - -type AnalyzeInformation struct { - IsAnalyzing bool - GuestMode bool - SentCount int - AnalyzedModel string - AnalyzeToken string - AnalyzeDestination string -} - -func (info *AnalyzeInformation) Reset() { - info.IsAnalyzing = false - info.GuestMode = true - info.AnalyzedModel = "" - info.AnalyzeToken = "" - info.AnalyzeDestination = "" - info.SentCount = 0 -} - -var analyzeInformation = &AnalyzeInformation{} - -func GetAnalyzeInfo() *shared.AnalyzeStatus { - return &shared.AnalyzeStatus{ - IsAnalyzing: analyzeInformation.IsAnalyzing, - RemoteUrl: GetRemoteUrl(analyzeInformation.AnalyzeDestination, analyzeInformation.AnalyzedModel, analyzeInformation.AnalyzeToken, analyzeInformation.GuestMode), - IsRemoteReady: CheckIfModelReady(analyzeInformation.AnalyzeDestination, analyzeInformation.AnalyzedModel, analyzeInformation.AnalyzeToken, analyzeInformation.GuestMode), - SentCount: analyzeInformation.SentCount, - } -} - -func SyncEntries(syncEntriesConfig *shared.SyncEntriesConfig) error { - logger.Log.Infof("Sync entries - started") - - var ( - token, model string - guestMode bool - ) - if syncEntriesConfig.Token == "" { - logger.Log.Infof("Sync entries - creating anonymous token. env %s", syncEntriesConfig.Env) - guestToken, err := createAnonymousToken(syncEntriesConfig.Env) - if err != nil { - return fmt.Errorf("failed creating anonymous token, err: %v", err) - } - - token = guestToken.Token - model = guestToken.Model - guestMode = true - } else { - token = fmt.Sprintf("bearer %s", syncEntriesConfig.Token) - model = syncEntriesConfig.Workspace - guestMode = false - - logger.Log.Infof("Sync entries - upserting model. env %s, model %s", syncEntriesConfig.Env, model) - if err := upsertModel(token, model, syncEntriesConfig.Env); err != nil { - return fmt.Errorf("failed upserting model, err: %v", err) - } - } - - modelRegex, _ := regexp.Compile("[A-Za-z0-9][-A-Za-z0-9_.]*[A-Za-z0-9]+$") - if len(model) > 63 || !modelRegex.MatchString(model) { - return fmt.Errorf("invalid model name, model name: %s", model) - } - - logger.Log.Infof("Sync entries - syncing. token: %s, model: %s, guest mode: %v", token, model, guestMode) - go syncEntriesImpl(token, model, syncEntriesConfig.Env, syncEntriesConfig.UploadIntervalSec, guestMode) - - return nil -} - -func upsertModel(token string, model string, envPrefix string) error { - upsertModelUrl, _ := url.Parse(fmt.Sprintf("https://trcc.%s/models/%s", envPrefix, model)) - - authHeader := getAuthHeader(false) - req := &http.Request{ - Method: http.MethodPost, - URL: upsertModelUrl, - Header: map[string][]string{ - authHeader: {token}, - }, - } - - response, err := http.DefaultClient.Do(req) - if err != nil { - return fmt.Errorf("failed request to upsert model, err: %v", err) - } - - // In case the model is not created (not 201) and doesn't exists (not 409) - if response.StatusCode != 201 && response.StatusCode != 409 { - return fmt.Errorf("failed request to upsert model, status code: %v", response.StatusCode) - } - - return nil -} - -func createAnonymousToken(envPrefix string) (*GuestToken, error) { - tokenUrl := fmt.Sprintf("https://trcc.%s/anonymous/token", envPrefix) - if strings.HasPrefix(envPrefix, "http") { - tokenUrl = fmt.Sprintf("%s/api/token", envPrefix) - } - token := &GuestToken{} - if err := getGuestToken(tokenUrl, token); err != nil { - logger.Log.Infof("Failed to get token, %s", err) - return nil, err - } - return token, nil -} - -func getGuestToken(url string, target *GuestToken) error { - resp, err := http.Get(url) - if err != nil { - return err - } - defer resp.Body.Close() - logger.Log.Infof("Got token from the server, starting to json decode... status code: %v", resp.StatusCode) - return json.NewDecoder(resp.Body).Decode(target) -} - -func syncEntriesImpl(token string, model string, envPrefix string, uploadIntervalSec int, guestMode bool) { - analyzeInformation.IsAnalyzing = true - analyzeInformation.GuestMode = guestMode - analyzeInformation.AnalyzedModel = model - analyzeInformation.AnalyzeToken = token - analyzeInformation.AnalyzeDestination = envPrefix - analyzeInformation.SentCount = 0 - - // "http or grpc" filter indicates that we're only interested in HTTP and gRPC entries - query := "http or grpc" - - logger.Log.Infof("Getting entries from the database") - -BasenineReconnect: - var connection *basenine.Connection - var err error - connection, err = basenine.NewConnection(shared.BasenineHost, shared.BaseninePort) - if err != nil { - logger.Log.Errorf("Can't establish a new connection to Basenine server: %v", err) - connection.Close() - time.Sleep(shared.BasenineReconnectInterval * time.Second) - goto BasenineReconnect - } - - data := make(chan []byte) - meta := make(chan []byte) - - defer func() { - data <- []byte(basenine.CloseChannel) - meta <- []byte(basenine.CloseChannel) - connection.Close() - }() - - lastTimeSynced := time.Time{} - - batch := make([]har.Entry, 0) - - handleDataChannel := func(wg *sync.WaitGroup, connection *basenine.Connection, data chan []byte) { - defer wg.Done() - for { - dataBytes := <-data - - if string(dataBytes) == basenine.CloseChannel { - return - } - - var dataMap map[string]interface{} - err = json.Unmarshal(dataBytes, &dataMap) - - var entry tapApi.Entry - if err := json.Unmarshal([]byte(dataBytes), &entry); err != nil { - continue - } - harEntry, err := har.NewEntry(entry.Request, entry.Response, entry.StartTime, entry.ElapsedTime) - if err != nil { - continue - } - if entry.Source.Name != "" { - harEntry.Request.Headers = append(harEntry.Request.Headers, har.Header{Name: "x-mizu-source", Value: entry.Source.Name}) - } - if entry.Destination.Name != "" { - harEntry.Request.Headers = append(harEntry.Request.Headers, har.Header{Name: "x-mizu-destination", Value: entry.Destination.Name}) - harEntry.Request.URL = utils.SetHostname(harEntry.Request.URL, entry.Destination.Name) - } - - batch = append(batch, *harEntry) - - now := time.Now() - if lastTimeSynced.Add(time.Duration(uploadIntervalSec) * time.Second).After(now) { - continue - } - lastTimeSynced = now - - body, jMarshalErr := json.Marshal(batch) - batchSize := len(batch) - if jMarshalErr != nil { - analyzeInformation.Reset() - logger.Log.Infof("Stopping sync entries") - logger.Log.Fatal(jMarshalErr) - } - batch = make([]har.Entry, 0) - - var in bytes.Buffer - w := zlib.NewWriter(&in) - _, _ = w.Write(body) - _ = w.Close() - reqBody := ioutil.NopCloser(bytes.NewReader(in.Bytes())) - - authHeader := getAuthHeader(guestMode) - req := &http.Request{ - Method: http.MethodPost, - URL: GetTrafficDumpUrl(envPrefix, model), - Header: map[string][]string{ - "Content-Encoding": {"deflate"}, - "Content-Type": {"application/octet-stream"}, - authHeader: {token}, - }, - Body: reqBody, - } - - if _, postErr := http.DefaultClient.Do(req); postErr != nil { - analyzeInformation.Reset() - logger.Log.Info("Stopping sync entries") - logger.Log.Fatal(postErr) - } - analyzeInformation.SentCount += batchSize - - if analyzeInformation.SentCount%SentCountLogInterval == 0 { - logger.Log.Infof("Uploaded %v entries until now", analyzeInformation.SentCount) - } - } - } - - handleMetaChannel := func(wg *sync.WaitGroup, connection *basenine.Connection, meta chan []byte) { - defer wg.Done() - for { - metaBytes := <-meta - - if string(metaBytes) == basenine.CloseChannel { - return - } - } - } - - var wg sync.WaitGroup - go handleDataChannel(&wg, connection, data) - go handleMetaChannel(&wg, connection, meta) - wg.Add(2) - - if err = connection.Query("latest", query, data, meta); err != nil { - logger.Log.Errorf("Query mode call failed: %v", err) - connection.Close() - time.Sleep(shared.BasenineReconnectInterval * time.Second) - goto BasenineReconnect - } - - wg.Wait() -} - -func UpdateAnalyzeStatus(callback func(data []byte)) { - for { - if !analyzeInformation.IsAnalyzing { - time.Sleep(AnalyzeCheckSleepTime) - continue - } - analyzeStatus := GetAnalyzeInfo() - socketMessage := shared.CreateWebSocketMessageTypeAnalyzeStatus(*analyzeStatus) - - jsonMessage, _ := json.Marshal(socketMessage) - callback(jsonMessage) - time.Sleep(AnalyzeCheckSleepTime) - } -} diff --git a/cli/auth/authProvider.go b/cli/auth/authProvider.go deleted file mode 100644 index 92f1eda30..000000000 --- a/cli/auth/authProvider.go +++ /dev/null @@ -1,147 +0,0 @@ -package auth - -import ( - "context" - "errors" - "fmt" - "net" - "net/http" - "time" - - "github.com/google/uuid" - "github.com/up9inc/mizu/cli/config" - "github.com/up9inc/mizu/cli/config/configStructs" - "github.com/up9inc/mizu/cli/uiUtils" - "github.com/up9inc/mizu/logger" - "golang.org/x/oauth2" -) - -const loginTimeoutInMin = 2 - -// Ports are configured in keycloak "cli" client as valid redirect URIs. A change here must be reflected there as well. -var listenPorts = []int{3141, 4001, 5002, 6003, 7004, 8005, 9006, 10007} - -func Login() error { - token, loginErr := loginInteractively() - if loginErr != nil { - return fmt.Errorf("failed login interactively, err: %v", loginErr) - } - - authConfig := configStructs.AuthConfig{ - EnvName: config.Config.Auth.EnvName, - Token: token.AccessToken, - } - - if err := config.UpdateConfig(func(configStruct *config.ConfigStruct) { configStruct.Auth = authConfig }); err != nil { - return fmt.Errorf("failed updating config with auth, err: %v", err) - } - - config.Config.Auth = authConfig - - logger.Log.Infof("Login successfully, token stored in config path: %s", fmt.Sprintf(uiUtils.Purple, config.Config.ConfigFilePath)) - return nil -} - -func loginInteractively() (*oauth2.Token, error) { - tokenChannel := make(chan *oauth2.Token) - errorChannel := make(chan error) - - server := http.Server{} - go startLoginServer(tokenChannel, errorChannel, &server) - - defer func() { - if err := server.Shutdown(context.Background()); err != nil { - logger.Log.Debugf("Error shutting down server, err: %v", err) - } - }() - - select { - case <-time.After(loginTimeoutInMin * time.Minute): - return nil, errors.New("auth timed out") - case err := <-errorChannel: - return nil, err - case token := <-tokenChannel: - return token, nil - } -} - -func startLoginServer(tokenChannel chan *oauth2.Token, errorChannel chan error, server *http.Server) { - for _, port := range listenPorts { - var authConfig = &oauth2.Config{ - ClientID: "cli", - RedirectURL: fmt.Sprintf("http://localhost:%v/callback", port), - Endpoint: oauth2.Endpoint{ - AuthURL: fmt.Sprintf("https://auth.%s/auth/realms/testr/protocol/openid-connect/auth", config.Config.Auth.EnvName), - TokenURL: fmt.Sprintf("https://auth.%s/auth/realms/testr/protocol/openid-connect/token", config.Config.Auth.EnvName), - }, - } - - state := uuid.New() - - mux := http.NewServeMux() - server.Handler = mux - mux.Handle("/callback", loginCallbackHandler(tokenChannel, errorChannel, authConfig, state)) - - listener, listenErr := net.Listen("tcp", fmt.Sprintf("%s:%d", "127.0.0.1", port)) - if listenErr != nil { - logger.Log.Debugf("failed to start listening on port %v, err: %v", port, listenErr) - continue - } - - authorizationUrl := authConfig.AuthCodeURL(state.String()) - uiUtils.OpenBrowser(authorizationUrl) - - serveErr := server.Serve(listener) - if serveErr == http.ErrServerClosed { - logger.Log.Debugf("received server shutdown, server on port %v is closed", port) - return - } else if serveErr != nil { - logger.Log.Debugf("failed to start serving on port %v, err: %v", port, serveErr) - continue - } - - logger.Log.Debugf("didn't receive server closed on port %v", port) - return - } - - errorChannel <- fmt.Errorf("failed to start serving on all listen ports, ports: %v", listenPorts) -} - -func loginCallbackHandler(tokenChannel chan *oauth2.Token, errorChannel chan error, authConfig *oauth2.Config, state uuid.UUID) http.Handler { - return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { - if err := request.ParseForm(); err != nil { - errorMsg := fmt.Sprintf("failed to parse form, err: %v", err) - http.Error(writer, errorMsg, http.StatusBadRequest) - errorChannel <- fmt.Errorf(errorMsg) - return - } - - requestState := request.Form.Get("state") - if requestState != state.String() { - errorMsg := fmt.Sprintf("state invalid, requestState: %v, authState:%v", requestState, state.String()) - http.Error(writer, errorMsg, http.StatusBadRequest) - errorChannel <- fmt.Errorf(errorMsg) - return - } - - code := request.Form.Get("code") - if code == "" { - errorMsg := "code not found" - http.Error(writer, errorMsg, http.StatusBadRequest) - errorChannel <- fmt.Errorf(errorMsg) - return - } - - token, err := authConfig.Exchange(context.Background(), code) - if err != nil { - errorMsg := fmt.Sprintf("failed to create token, err: %v", err) - http.Error(writer, errorMsg, http.StatusInternalServerError) - errorChannel <- fmt.Errorf(errorMsg) - return - } - - tokenChannel <- token - - http.Redirect(writer, request, fmt.Sprintf("https://%s/CliLogin", config.Config.Auth.EnvName), http.StatusFound) - }) -} diff --git a/cli/cmd/tap.go b/cli/cmd/tap.go index 2867923ea..ba2d3cbb5 100644 --- a/cli/cmd/tap.go +++ b/cli/cmd/tap.go @@ -2,24 +2,15 @@ package cmd import ( "errors" - "fmt" - "os" - - "github.com/up9inc/mizu/cli/up9" "github.com/creasty/defaults" "github.com/spf13/cobra" - "github.com/up9inc/mizu/cli/auth" "github.com/up9inc/mizu/cli/config" "github.com/up9inc/mizu/cli/config/configStructs" "github.com/up9inc/mizu/cli/errormessage" - "github.com/up9inc/mizu/cli/uiUtils" "github.com/up9inc/mizu/logger" - "github.com/up9inc/mizu/shared" ) -const uploadTrafficMessageToConfirm = `NOTE: running mizu with --%s flag will upload recorded traffic for further analysis and enriched presentation options.` - var tapCmd = &cobra.Command{ Use: "tap [POD REGEX]", Short: "Record ingoing traffic of a kubernetes pod", @@ -40,67 +31,12 @@ Supported protocols are HTTP and gRPC.`, return errormessage.FormatError(err) } - if config.Config.Tap.Workspace != "" { - askConfirmation(configStructs.WorkspaceTapName) - - if config.Config.Auth.Token == "" { - logger.Log.Infof("This action requires authentication, please log in to continue") - if err := auth.Login(); err != nil { - logger.Log.Errorf("failed to log in, err: %v", err) - return nil - } - } else { - tokenExpired, err := shared.IsTokenExpired(config.Config.Auth.Token) - if err != nil { - logger.Log.Errorf("failed to check if token is expired, err: %v", err) - return nil - } - - if tokenExpired { - logger.Log.Infof("Token expired, please log in again to continue") - if err := auth.Login(); err != nil { - logger.Log.Errorf("failed to log in, err: %v", err) - return nil - } - } else if isValidToken := up9.IsTokenValid(config.Config.Auth.Token, config.Config.Auth.EnvName); !isValidToken { - logger.Log.Errorf("Token is not valid, please log in again to continue") - if err := auth.Login(); err != nil { - logger.Log.Errorf("failed to log in, err: %v", err) - return nil - } - } - } - } - - if config.Config.Tap.Analysis { - askConfirmation(configStructs.AnalysisTapName) - - config.Config.Auth.Token = "" - } - logger.Log.Infof("Mizu will store up to %s of traffic, old traffic will be cleared once the limit is reached.", config.Config.Tap.HumanMaxEntriesDBSize) return nil }, } -func askConfirmation(flagName string) { - logger.Log.Infof(fmt.Sprintf(uploadTrafficMessageToConfirm, flagName)) - - if !config.Config.Tap.AskUploadConfirmation { - return - } - - if !uiUtils.AskForConfirmation("Would you like to proceed [Y/n]: ") { - logger.Log.Infof("You can always run mizu without %s, aborting", flagName) - os.Exit(0) - } - - if err := config.UpdateConfig(func(configStruct *config.ConfigStruct) { configStruct.Tap.AskUploadConfirmation = false }); err != nil { - logger.Log.Debugf("failed updating config with upload confirmation, err: %v", err) - } -} - func init() { rootCmd.AddCommand(tapCmd) @@ -111,14 +47,12 @@ func init() { tapCmd.Flags().Uint16P(configStructs.GuiPortTapName, "p", defaultTapConfig.GuiPort, "Provide a custom port for the web interface webserver") tapCmd.Flags().StringSliceP(configStructs.NamespacesTapName, "n", defaultTapConfig.Namespaces, "Namespaces selector") - tapCmd.Flags().Bool(configStructs.AnalysisTapName, defaultTapConfig.Analysis, "Uploads traffic to UP9 for further analysis (Beta)") tapCmd.Flags().BoolP(configStructs.AllNamespacesTapName, "A", defaultTapConfig.AllNamespaces, "Tap all namespaces") tapCmd.Flags().StringSliceP(configStructs.PlainTextFilterRegexesTapName, "r", defaultTapConfig.PlainTextFilterRegexes, "List of regex expressions that are used to filter matching values from text/plain http bodies") tapCmd.Flags().Bool(configStructs.EnableRedactionTapName, defaultTapConfig.EnableRedaction, "Enables redaction of potentially sensitive request/response headers and body values") tapCmd.Flags().String(configStructs.HumanMaxEntriesDBSizeTapName, defaultTapConfig.HumanMaxEntriesDBSize, "Override the default max entries db size") tapCmd.Flags().String(configStructs.InsertionFilterName, defaultTapConfig.InsertionFilter, "Set the insertion filter. Accepts string or a file path.") tapCmd.Flags().Bool(configStructs.DryRunTapName, defaultTapConfig.DryRun, "Preview of all pods matching the regex, without tapping them") - tapCmd.Flags().StringP(configStructs.WorkspaceTapName, "w", defaultTapConfig.Workspace, "Uploads traffic to your UP9 workspace for further analysis (requires auth)") tapCmd.Flags().String(configStructs.EnforcePolicyFile, defaultTapConfig.EnforcePolicyFile, "Yaml file path with policy rules") tapCmd.Flags().String(configStructs.ContractFile, defaultTapConfig.ContractFile, "OAS/Swagger file to validate to monitor the contracts") tapCmd.Flags().Bool(configStructs.ServiceMeshName, defaultTapConfig.ServiceMesh, "Record decrypted traffic if the cluster is configured with a service mesh and with mtls") diff --git a/cli/cmd/tapRunner.go b/cli/cmd/tapRunner.go index a01adaa30..f5cd55484 100644 --- a/cli/cmd/tapRunner.go +++ b/cli/cmd/tapRunner.go @@ -124,7 +124,7 @@ func RunMizuTap() { } logger.Log.Infof("Waiting for Mizu Agent to start...") - if state.mizuServiceAccountExists, err = resources.CreateTapMizuResources(ctx, kubernetesProvider, serializedValidationRules, serializedContract, serializedMizuConfig, config.Config.IsNsRestrictedMode(), config.Config.MizuResourcesNamespace, config.Config.AgentImage, getSyncEntriesConfig(), config.Config.Tap.MaxEntriesDBSizeBytes(), config.Config.Tap.ApiServerResources, config.Config.ImagePullPolicy(), config.Config.LogLevel(), config.Config.Tap.Profiler); err != nil { + if state.mizuServiceAccountExists, err = resources.CreateTapMizuResources(ctx, kubernetesProvider, serializedValidationRules, serializedContract, serializedMizuConfig, config.Config.IsNsRestrictedMode(), config.Config.MizuResourcesNamespace, config.Config.AgentImage, config.Config.Tap.MaxEntriesDBSizeBytes(), config.Config.Tap.ApiServerResources, config.Config.ImagePullPolicy(), config.Config.LogLevel(), config.Config.Tap.Profiler); err != nil { var statusError *k8serrors.StatusError if errors.As(err, &statusError) && (statusError.ErrStatus.Reason == metav1.StatusReasonAlreadyExists) { logger.Log.Info("Mizu is already running in this namespace, change the `mizu-resources-namespace` configuration or run `mizu clean` to remove the currently running Mizu instance") @@ -295,19 +295,6 @@ func getMizuApiFilteringOptions() (*api.TrafficFilteringOptions, error) { }, nil } -func getSyncEntriesConfig() *shared.SyncEntriesConfig { - if !config.Config.Tap.Analysis && config.Config.Tap.Workspace == "" { - return nil - } - - return &shared.SyncEntriesConfig{ - Token: config.Config.Auth.Token, - Env: config.Config.Auth.EnvName, - Workspace: config.Config.Tap.Workspace, - UploadIntervalSec: config.Config.Tap.UploadIntervalSec, - } -} - func watchApiServerPod(ctx context.Context, kubernetesProvider *kubernetes.Provider, cancel context.CancelFunc) { podExactRegex := regexp.MustCompile(fmt.Sprintf("^%s$", kubernetes.ApiServerPodName)) podWatchHelper := kubernetes.NewPodWatchHelper(kubernetesProvider, podExactRegex) diff --git a/cli/config/config.go b/cli/config/config.go index 6e33485d8..dc7c65165 100644 --- a/cli/config/config.go +++ b/cli/config/config.go @@ -85,27 +85,6 @@ func WriteConfig(config *ConfigStruct) error { return nil } -type updateConfigStruct func(*ConfigStruct) - -func UpdateConfig(updateConfigStruct updateConfigStruct) error { - configFile, err := GetConfigWithDefaults() - if err != nil { - return fmt.Errorf("failed getting config with defaults, err: %v", err) - } - - if err := loadConfigFile(Config.ConfigFilePath, configFile); err != nil && !os.IsNotExist(err) { - return fmt.Errorf("failed getting config file, err: %v", err) - } - - updateConfigStruct(configFile) - - if err := WriteConfig(configFile); err != nil { - return fmt.Errorf("failed writing config, err: %v", err) - } - - return nil -} - func loadConfigFile(configFilePath string, config *ConfigStruct) error { reader, openErr := os.Open(configFilePath) if openErr != nil { diff --git a/cli/config/configStruct.go b/cli/config/configStruct.go index e809d3aec..3606a3071 100644 --- a/cli/config/configStruct.go +++ b/cli/config/configStruct.go @@ -27,7 +27,6 @@ type ConfigStruct struct { Version configStructs.VersionConfig `yaml:"version"` View configStructs.ViewConfig `yaml:"view"` Logs configStructs.LogsConfig `yaml:"logs"` - Auth configStructs.AuthConfig `yaml:"auth"` Config configStructs.ConfigConfig `yaml:"config,omitempty"` AgentImage string `yaml:"agent-image,omitempty" readonly:""` ImagePullPolicyStr string `yaml:"image-pull-policy" default:"Always"` diff --git a/cli/config/configStructs/authConfig.go b/cli/config/configStructs/authConfig.go deleted file mode 100644 index 550364528..000000000 --- a/cli/config/configStructs/authConfig.go +++ /dev/null @@ -1,6 +0,0 @@ -package configStructs - -type AuthConfig struct { - EnvName string `yaml:"env-name" default:"up9.app"` - Token string `yaml:"token"` -} diff --git a/cli/config/configStructs/tapConfig.go b/cli/config/configStructs/tapConfig.go index b012baee5..6f59d3848 100644 --- a/cli/config/configStructs/tapConfig.go +++ b/cli/config/configStructs/tapConfig.go @@ -1,7 +1,6 @@ package configStructs import ( - "errors" "fmt" "io/fs" "io/ioutil" @@ -18,14 +17,12 @@ import ( const ( GuiPortTapName = "gui-port" NamespacesTapName = "namespaces" - AnalysisTapName = "analysis" AllNamespacesTapName = "all-namespaces" PlainTextFilterRegexesTapName = "regex-masking" EnableRedactionTapName = "redact" HumanMaxEntriesDBSizeTapName = "max-entries-db-size" InsertionFilterName = "insertion-filter" DryRunTapName = "dry-run" - WorkspaceTapName = "workspace" EnforcePolicyFile = "traffic-validation-file" ContractFile = "contract" ServiceMeshName = "service-mesh" @@ -34,12 +31,10 @@ const ( ) type TapConfig struct { - UploadIntervalSec int `yaml:"upload-interval" default:"10"` PodRegexStr string `yaml:"regex" default:".*"` GuiPort uint16 `yaml:"gui-port" default:"8899"` ProxyHost string `yaml:"proxy-host" default:"127.0.0.1"` Namespaces []string `yaml:"namespaces"` - Analysis bool `yaml:"analysis" default:"false"` AllNamespaces bool `yaml:"all-namespaces" default:"false"` PlainTextFilterRegexes []string `yaml:"regex-masking"` IgnoredUserAgents []string `yaml:"ignored-user-agents"` @@ -47,10 +42,8 @@ type TapConfig struct { HumanMaxEntriesDBSize string `yaml:"max-entries-db-size" default:"200MB"` InsertionFilter string `yaml:"insertion-filter" default:""` DryRun bool `yaml:"dry-run" default:"false"` - Workspace string `yaml:"workspace"` EnforcePolicyFile string `yaml:"traffic-validation-file"` ContractFile string `yaml:"contract"` - AskUploadConfirmation bool `yaml:"ask-upload-confirmation" default:"true"` ApiServerResources shared.Resources `yaml:"api-server-resources"` TapperResources shared.Resources `yaml:"tapper-resources"` ServiceMesh bool `yaml:"service-mesh" default:"false"` @@ -94,16 +87,5 @@ func (config *TapConfig) Validate() error { return fmt.Errorf("Could not parse --%s value %s", HumanMaxEntriesDBSizeTapName, config.HumanMaxEntriesDBSize) } - if config.Workspace != "" { - workspaceRegex, _ := regexp.Compile("[A-Za-z0-9][-A-Za-z0-9_.]*[A-Za-z0-9]+$") - if len(config.Workspace) > 63 || !workspaceRegex.MatchString(config.Workspace) { - return errors.New("invalid workspace name") - } - } - - if config.Analysis && config.Workspace != "" { - return fmt.Errorf("Can't run with both --%s and --%s flags", AnalysisTapName, WorkspaceTapName) - } - return nil } diff --git a/cli/mizu/consts.go b/cli/mizu/consts.go index 11fd3d690..0a107f391 100644 --- a/cli/mizu/consts.go +++ b/cli/mizu/consts.go @@ -12,7 +12,6 @@ var ( BuildTimestamp = "" // this var is overridden using ldflags in makefile when building RBACVersion = "v1" Platform = "" - InstallModePersistentVolumeSizeBufferBytes = int64(500 * 1000 * 1000) //500mb ) const DEVENVVAR = "MIZU_DISABLE_TELEMTRY" diff --git a/cli/resources/createResources.go b/cli/resources/createResources.go index 9d359cb7d..aaaa6912c 100644 --- a/cli/resources/createResources.go +++ b/cli/resources/createResources.go @@ -14,7 +14,7 @@ import ( core "k8s.io/api/core/v1" ) -func CreateTapMizuResources(ctx context.Context, kubernetesProvider *kubernetes.Provider, serializedValidationRules string, serializedContract string, serializedMizuConfig string, isNsRestrictedMode bool, mizuResourcesNamespace string, agentImage string, syncEntriesConfig *shared.SyncEntriesConfig, maxEntriesDBSizeBytes int64, apiServerResources shared.Resources, imagePullPolicy core.PullPolicy, logLevel logging.Level, profiler bool) (bool, error) { +func CreateTapMizuResources(ctx context.Context, kubernetesProvider *kubernetes.Provider, serializedValidationRules string, serializedContract string, serializedMizuConfig string, isNsRestrictedMode bool, mizuResourcesNamespace string, agentImage string, maxEntriesDBSizeBytes int64, apiServerResources shared.Resources, imagePullPolicy core.PullPolicy, logLevel logging.Level, profiler bool) (bool, error) { if !isNsRestrictedMode { if err := createMizuNamespace(ctx, kubernetesProvider, mizuResourcesNamespace); err != nil { return false, err @@ -45,7 +45,6 @@ func CreateTapMizuResources(ctx context.Context, kubernetesProvider *kubernetes. KetoImage: "", ServiceAccountName: serviceAccountName, IsNamespaceRestricted: isNsRestrictedMode, - SyncEntriesConfig: syncEntriesConfig, MaxEntriesDBSizeBytes: maxEntriesDBSizeBytes, Resources: apiServerResources, ImagePullPolicy: imagePullPolicy, diff --git a/cli/uiUtils/confirmation.go b/cli/uiUtils/confirmation.go deleted file mode 100644 index 313183132..000000000 --- a/cli/uiUtils/confirmation.go +++ /dev/null @@ -1,26 +0,0 @@ -package uiUtils - -import ( - "bufio" - "fmt" - "os" - "strings" - - "github.com/up9inc/mizu/logger" -) - -func AskForConfirmation(s string) bool { - reader := bufio.NewReader(os.Stdin) - - fmt.Printf(Magenta, s) - - response, err := reader.ReadString('\n') - if err != nil { - logger.Log.Fatalf("Error while reading confirmation string, err: %v", err) - } - response = strings.ToLower(strings.TrimSpace(response)) - if response == "" || response == "y" || response == "yes" { - return true - } - return false -} diff --git a/cli/up9/provider.go b/cli/up9/provider.go deleted file mode 100644 index 7363a0bc2..000000000 --- a/cli/up9/provider.go +++ /dev/null @@ -1,27 +0,0 @@ -package up9 - -import ( - "fmt" - "net/http" - "net/url" -) - -func IsTokenValid(tokenString string, envName string) bool { - whoAmIUrl, _ := url.Parse(fmt.Sprintf("https://trcc.%s/admin/whoami", envName)) - - req := &http.Request{ - Method: http.MethodGet, - URL: whoAmIUrl, - Header: map[string][]string{ - "Authorization": {fmt.Sprintf("bearer %s", tokenString)}, - }, - } - - response, err := http.DefaultClient.Do(req) - if err != nil { - return false - } - defer response.Body.Close() - - return response.StatusCode == http.StatusOK -} diff --git a/shared/consts.go b/shared/consts.go index f285aa935..abd65fc1f 100644 --- a/shared/consts.go +++ b/shared/consts.go @@ -2,7 +2,6 @@ package shared const ( MizuFilteringOptionsEnvVar = "SENSITIVE_DATA_FILTERING_OPTIONS" - SyncEntriesConfigEnvVar = "SYNC_ENTRIES_CONFIG" HostModeEnvVar = "HOST_MODE" NodeNameEnvVar = "NODE_NAME" ConfigDirPath = "/app/config/" diff --git a/shared/kubernetes/provider.go b/shared/kubernetes/provider.go index 7c0119953..5d54778b7 100644 --- a/shared/kubernetes/provider.go +++ b/shared/kubernetes/provider.go @@ -32,7 +32,6 @@ import ( "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/client-go/rest" - restclient "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/clientcmd" watchtools "k8s.io/client-go/tools/watch" @@ -41,7 +40,7 @@ import ( type Provider struct { clientSet *kubernetes.Clientset kubernetesConfig clientcmd.ClientConfig - clientConfig restclient.Config + clientConfig rest.Config managedBy string createdBy string } @@ -88,6 +87,7 @@ func NewProvider(kubeConfigPath string, contextName string) (*Provider, error) { }, nil } +//NewProviderInCluster Used in another repo that calls this function func NewProviderInCluster() (*Provider, error) { restClientConfig, err := rest.InClusterConfig() if err != nil { @@ -176,7 +176,6 @@ type ApiServerOptions struct { KetoImage string ServiceAccountName string IsNamespaceRestricted bool - SyncEntriesConfig *shared.SyncEntriesConfig MaxEntriesDBSizeBytes int64 Resources shared.Resources ImagePullPolicy core.PullPolicy @@ -185,14 +184,6 @@ type ApiServerOptions struct { } func (provider *Provider) GetMizuApiServerPodObject(opts *ApiServerOptions, mountVolumeClaim bool, volumeClaimName string, createAuthContainer bool) (*core.Pod, error) { - var marshaledSyncEntriesConfig []byte - if opts.SyncEntriesConfig != nil { - var err error - if marshaledSyncEntriesConfig, err = json.Marshal(opts.SyncEntriesConfig); err != nil { - return nil, err - } - } - configMapVolume := &core.ConfigMapVolumeSource{} configMapVolume.Name = ConfigMapName @@ -264,10 +255,6 @@ func (provider *Provider) GetMizuApiServerPodObject(opts *ApiServerOptions, moun VolumeMounts: volumeMounts, Command: command, Env: []core.EnvVar{ - { - Name: shared.SyncEntriesConfigEnvVar, - Value: string(marshaledSyncEntriesConfig), - }, { Name: shared.LogLevelEnvVar, Value: opts.LogLevel.String(), @@ -1113,7 +1100,7 @@ func (provider *Provider) GetKubernetesVersion() (*semver.SemVersion, error) { return &serverVersionSemVer, nil } -func getClientSet(config *restclient.Config) (*kubernetes.Clientset, error) { +func getClientSet(config *rest.Config) (*kubernetes.Clientset, error) { clientSet, err := kubernetes.NewForConfig(config) if err != nil { return nil, err diff --git a/shared/models.go b/shared/models.go index 3e7d47272..5d6c28ae4 100644 --- a/shared/models.go +++ b/shared/models.go @@ -19,7 +19,6 @@ const ( WebSocketMessageTypeTappedEntry WebSocketMessageType = "tappedEntry" WebSocketMessageTypeUpdateStatus WebSocketMessageType = "status" WebSocketMessageTypeUpdateTappedPods WebSocketMessageType = "tappedPods" - WebSocketMessageTypeAnalyzeStatus WebSocketMessageType = "analyzeStatus" WebSocketMessageTypeToast WebSocketMessageType = "toast" WebSocketMessageTypeQueryMetadata WebSocketMessageType = "queryMetadata" WebSocketMessageTypeStartTime WebSocketMessageType = "startTime" @@ -51,17 +50,6 @@ type WebSocketMessageMetadata struct { MessageType WebSocketMessageType `json:"messageType,omitempty"` } -type WebSocketAnalyzeStatusMessage struct { - *WebSocketMessageMetadata - AnalyzeStatus AnalyzeStatus `json:"analyzeStatus"` -} - -type AnalyzeStatus struct { - IsAnalyzing bool `json:"isAnalyzing"` - RemoteUrl string `json:"remoteUrl"` - IsRemoteReady bool `json:"isRemoteReady"` - SentCount int `json:"sentCount"` -} type WebSocketStatusMessage struct { *WebSocketMessageMetadata @@ -116,13 +104,6 @@ type TLSLinkInfo struct { ResolvedSourceName string `json:"resolvedSourceName"` } -type SyncEntriesConfig struct { - Token string `json:"token"` - Env string `json:"env"` - Workspace string `json:"workspace"` - UploadIntervalSec int `json:"interval"` -} - func CreateWebSocketStatusMessage(tappedPodsStatus []TappedPodStatus) WebSocketStatusMessage { return WebSocketStatusMessage{ WebSocketMessageMetadata: &WebSocketMessageMetadata{ @@ -141,15 +122,6 @@ func CreateWebSocketTappedPodsMessage(nodeToTappedPodMap NodeToPodsMap) WebSocke } } -func CreateWebSocketMessageTypeAnalyzeStatus(analyzeStatus AnalyzeStatus) WebSocketAnalyzeStatusMessage { - return WebSocketAnalyzeStatusMessage{ - WebSocketMessageMetadata: &WebSocketMessageMetadata{ - MessageType: WebSocketMessageTypeAnalyzeStatus, - }, - AnalyzeStatus: analyzeStatus, - } -} - type HealthResponse struct { TappedPods []*PodInfo `json:"tappedPods"` ConnectedTappersCount int `json:"connectedTappersCount"` diff --git a/shared/tokenUtils.go b/shared/tokenUtils.go deleted file mode 100644 index 0bd212a3a..000000000 --- a/shared/tokenUtils.go +++ /dev/null @@ -1,41 +0,0 @@ -package shared - -import ( - "fmt" - "github.com/golang-jwt/jwt/v4" - "time" -) - -func IsTokenExpired(tokenString string) (bool, error) { - claims, err := getTokenClaims(tokenString) - if err != nil { - return true, err - } - - expiry := time.Unix(int64(claims["exp"].(float64)), 0) - - return time.Now().After(expiry), nil -} - -func GetTokenEmail(tokenString string) (string, error) { - claims, err := getTokenClaims(tokenString) - if err != nil { - return "", err - } - - return claims["email"].(string), nil -} - -func getTokenClaims(tokenString string) (jwt.MapClaims, error) { - token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{}) - if err != nil { - return nil, fmt.Errorf("failed to parse token, err: %v", err) - } - - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - return nil, fmt.Errorf("can't convert token's claims to standard claims") - } - - return claims, nil -} diff --git a/ui-common/src/components/AnalyzeButton/AnalyzeButton.tsx b/ui-common/src/components/AnalyzeButton/AnalyzeButton.tsx deleted file mode 100644 index 261056c24..000000000 --- a/ui-common/src/components/AnalyzeButton/AnalyzeButton.tsx +++ /dev/null @@ -1,86 +0,0 @@ -import {Button} from "@material-ui/core"; -import React from "react"; -import logo_up9 from "logo_up9.svg"; -import {makeStyles} from "@material-ui/core/styles"; -import { Tooltip } from "../UI"; - -const useStyles = makeStyles(() => ({ - tooltip: { - backgroundColor: "#3868dc", - color: "white", - fontSize: 13, - }, -})); - -interface AnalyseButtonProps { - analyzeStatus: any -} - -export const AnalyzeButton: React.FC = ({analyzeStatus}) => { - - const classes = useStyles(); - - const analysisMessage = analyzeStatus?.isRemoteReady ? - - - - - - - - - - -
StatusAvailable
Messages{analyzeStatus?.sentCount}
-
: - analyzeStatus?.sentCount > 0 ? - - - - - - - - - - - - - -
StatusProcessing
Messages{analyzeStatus?.sentCount}
Please allow a few minutes for the analysis to complete
-
: - - - - - - - - - - -
StatusWaiting for traffic
Messages{analyzeStatus?.sentCount}
-
- - return (
- -
- -
-
-
); -} diff --git a/ui-common/src/components/AnalyzeButton/logo_up9.svg b/ui-common/src/components/AnalyzeButton/logo_up9.svg deleted file mode 100644 index 4446859b5..000000000 --- a/ui-common/src/components/AnalyzeButton/logo_up9.svg +++ /dev/null @@ -1,39 +0,0 @@ - diff --git a/ui-common/src/components/TrafficViewer/TrafficViewer.tsx b/ui-common/src/components/TrafficViewer/TrafficViewer.tsx index 0506c62a6..af385a51e 100644 --- a/ui-common/src/components/TrafficViewer/TrafficViewer.tsx +++ b/ui-common/src/components/TrafficViewer/TrafficViewer.tsx @@ -43,7 +43,6 @@ const useLayoutStyles = makeStyles(() => ({ })); interface TrafficViewerProps { - setAnalyzeStatus?: (status: any) => void; api?: any trafficViewerApiProp: TrafficViewerApi, actionButtons?: JSX.Element, @@ -55,7 +54,7 @@ interface TrafficViewerProps { } export const TrafficViewer: React.FC = ({ - setAnalyzeStatus, trafficViewerApiProp, + trafficViewerApiProp, actionButtons, isShowStatusBar, webSocketUrl, shouldCloseWebSocket, setShouldCloseWebSocket, isDemoBannerView }) => { @@ -176,10 +175,6 @@ export const TrafficViewer: React.FC = ({ try { const tapStatusResponse = await trafficViewerApiProp.tapStatus(); setTappingStatus(tapStatusResponse); - if (setAnalyzeStatus) { - const analyzeStatusResponse = await trafficViewerApiProp.analyzeStatus(); - setAnalyzeStatus(analyzeStatusResponse); - } } catch (error) { console.error(error); } @@ -292,16 +287,16 @@ export const TrafficViewer: React.FC = ({ ); }; -const MemoiedTrafficViewer = React.memo(TrafficViewer) +const MemorizedTrafficViewer = React.memo(TrafficViewer) const TrafficViewerContainer: React.FC = ({ - setAnalyzeStatus, trafficViewerApiProp, + trafficViewerApiProp, actionButtons, isShowStatusBar = true, webSocketUrl, shouldCloseWebSocket, setShouldCloseWebSocket, isDemoBannerView }) => { return - + isDemoBannerView={isDemoBannerView}/> any tapStatus: () => any - analyzeStatus: () => any fetchEntries: (leftOff: any, direction: number, query: any, limit: number, timeoutMs: number) => any getEntry: (entryId: any, query: string) => any webSocket: { diff --git a/ui-common/src/index.tsx b/ui-common/src/index.tsx index d0b4eb13e..ac1252d49 100644 --- a/ui-common/src/index.tsx +++ b/ui-common/src/index.tsx @@ -2,10 +2,9 @@ import TrafficViewer from './components/TrafficViewer/TrafficViewer'; import * as UI from "./components/UI" import { StatusBar } from './components/UI'; import useWS, { DEFAULT_LEFTOFF } from './hooks/useWS'; -import { AnalyzeButton } from "./components/AnalyzeButton/AnalyzeButton" import OasModal from './components/OasModal/OasModal'; import { ServiceMapModal } from './components/ServiceMapModal/ServiceMapModal'; -export { UI, AnalyzeButton, StatusBar, OasModal, ServiceMapModal } +export { UI, StatusBar, OasModal, ServiceMapModal } export { useWS, DEFAULT_LEFTOFF } export default TrafficViewer; diff --git a/ui/src/App.tsx b/ui/src/App.tsx index bdf203c1a..484f352ca 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -1,4 +1,3 @@ -import { useState } from 'react'; import './App.sass'; import { Header } from "./components/Header/Header"; import { TrafficPage } from "./components/Pages/TrafficPage/TrafficPage"; @@ -13,14 +12,13 @@ const api = Api.getInstance() const App = () => { - const [analyzeStatus, setAnalyzeStatus] = useState(null); const [serviceMapModalOpen, setServiceMapModalOpen] = useRecoilState(serviceMapModalOpenAtom); const [oasModalOpen, setOasModalOpen] = useRecoilState(oasModalOpenAtom) return (
-
- +
+ {window["isServiceMapEnabled"] && setServiceMapModalOpen(true)} diff --git a/ui/src/components/Header/Header.tsx b/ui/src/components/Header/Header.tsx index 369916c0c..041527809 100644 --- a/ui/src/components/Header/Header.tsx +++ b/ui/src/components/Header/Header.tsx @@ -1,21 +1,17 @@ import React from "react"; import {AuthPresentation} from "../AuthPresentation/AuthPresentation"; -import {AnalyzeButton} from "@up9/mizu-common" import logo from '../assets/Mizu-logo.svg'; import './Header.sass'; import {UI} from "@up9/mizu-common" -interface HeaderProps { - analyzeStatus: any -} -export const Header: React.FC = ({analyzeStatus}) => { + +export const Header: React.FC = () => { return
logo
Traffic viewer for Kubernetes
- {analyzeStatus?.isAnalyzing && }
diff --git a/ui/src/components/Pages/TrafficPage/TrafficPage.tsx b/ui/src/components/Pages/TrafficPage/TrafficPage.tsx index 96c54469a..efc827ba8 100644 --- a/ui/src/components/Pages/TrafficPage/TrafficPage.tsx +++ b/ui/src/components/Pages/TrafficPage/TrafficPage.tsx @@ -11,13 +11,9 @@ import oasModalOpenAtom from "../../../recoil/oasModalOpen/atom"; import serviceMap from "../../assets/serviceMap.svg"; import services from "../../assets/services.svg"; -interface TrafficPageProps { - setAnalyzeStatus?: (status: any) => void; -} - const api = Api.getInstance(); -export const TrafficPage: React.FC = ({ setAnalyzeStatus }) => { +export const TrafficPage: React.FC = () => { const commonClasses = useCommonStyles(); const [serviceMapModalOpen, setServiceMapModalOpen] = useRecoilState(serviceMapModalOpenAtom); const [openOasModal, setOpenOasModal] = useRecoilState(oasModalOpenAtom); @@ -38,7 +34,7 @@ export const TrafficPage: React.FC = ({ setAnalyzeStatus }) => const actionButtons = (window["isOasEnabled"] || window["isServiceMapEnabled"]) &&
{window["isOasEnabled"] && } {window["isServiceMapEnabled"] &&