Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: expire token on logout (#8413)
Danny Xu0a1120535092
diff --git a/backend/api/auth/auth.go b/backend/api/auth/auth.goindex 3ffbdc5c95..a32776e659 100644--- a/backend/api/auth/auth.go+++ b/backend/api/auth/auth.go@@ -19,6 +19,7 @@ import (errs "github.com/pkg/errors""github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/component/state"enterpriseAPI "github.com/bytebase/bytebase/backend/enterprise/api""github.com/bytebase/bytebase/backend/store")@@ -53,16 +54,18 @@ type APIAuthInterceptor struct {secret stringtokenDuration time.DurationlicenseService enterpriseAPI.LicenseService+ stateCfg *state.Statemode common.ReleaseMode}// New returns a new API auth interceptor.-func New(store *store.Store, secret string, tokenDuration time.Duration, licenseService enterpriseAPI.LicenseService, mode common.ReleaseMode) *APIAuthInterceptor {+func New(store *store.Store, secret string, tokenDuration time.Duration, licenseService enterpriseAPI.LicenseService, stateCfg *state.State, mode common.ReleaseMode) *APIAuthInterceptor {return &APIAuthInterceptor{store: store,secret: secret,tokenDuration: tokenDuration,licenseService: licenseService,+ stateCfg: stateCfg,mode: mode,}}@@ -73,7 +76,7 @@ func (in *APIAuthInterceptor) AuthenticationInterceptor(ctx context.Context, reqif !ok {return nil, status.Errorf(codes.Unauthenticated, "failed to parse metadata from incoming context")}- accessTokenStr, err := getTokenFromMetadata(md)+ accessTokenStr, err := GetTokenFromMetadata(md)if err != nil {return nil, status.Errorf(codes.Unauthenticated, err.Error())}@@ -98,7 +101,7 @@ func (in *APIAuthInterceptor) AuthenticationStreamInterceptor(request any, ss grif !ok {return status.Errorf(codes.Unauthenticated, "failed to parse metadata from incoming context")}- accessTokenStr, err := getTokenFromMetadata(md)+ accessTokenStr, err := GetTokenFromMetadata(md)if err != nil {return status.Errorf(codes.Unauthenticated, err.Error())}@@ -130,6 +133,9 @@ func (in *APIAuthInterceptor) authenticate(ctx context.Context, accessTokenStr sif accessTokenStr == "" {return 0, status.Errorf(codes.Unauthenticated, "access token not found")}+ if _, ok := in.stateCfg.ExpireCache.Get(accessTokenStr); ok {+ return 0, status.Errorf(codes.Unauthenticated, "access token expired")+ }claims := &claimsMessage{}if _, err := jwt.ParseWithClaims(accessTokenStr, claims, func(t *jwt.Token) (any, error) {if t.Method.Alg() != jwt.SigningMethodHS256.Name {@@ -201,7 +207,7 @@ func GetUserIDFromMFATempToken(token string, mode common.ReleaseMode, secret strreturn userID, nil}-func getTokenFromMetadata(md metadata.MD) (string, error) {+func GetTokenFromMetadata(md metadata.MD) (string, error) {authorizationHeaders := md.Get("Authorization")if len(md.Get("Authorization")) > 0 {authHeaderParts := strings.Fields(authorizationHeaders[0])diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.goindex 8be6fff1a8..0bc423ec5d 100644--- a/backend/api/v1/auth_service.go+++ b/backend/api/v1/auth_service.go@@ -3,13 +3,14 @@ package v1import ("context""encoding/json"- "errors""fmt""net/mail""regexp""strings""time"+ "github.com/pkg/errors"+"github.com/pquerna/otp/totp""golang.org/x/crypto/bcrypt""golang.org/x/exp/slices"@@ -22,6 +23,7 @@ import ("github.com/bytebase/bytebase/backend/api/auth""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/component/config"+ "github.com/bytebase/bytebase/backend/component/state"enterpriseAPI "github.com/bytebase/bytebase/backend/enterprise/api"api "github.com/bytebase/bytebase/backend/legacyapi"metricAPI "github.com/bytebase/bytebase/backend/metric"@@ -46,11 +48,12 @@ type AuthService struct {licenseService enterpriseAPI.LicenseServicemetricReporter *metricreport.Reporterprofile *config.Profile+ stateCfg *state.StatepostCreateUser func(ctx context.Context, user *store.UserMessage, firstEndUser bool) error}// NewAuthService creates a new AuthService.-func NewAuthService(store *store.Store, secret string, tokenDuration time.Duration, licenseService enterpriseAPI.LicenseService, metricReporter *metricreport.Reporter, profile *config.Profile, postCreateUser func(ctx context.Context, user *store.UserMessage, firstEndUser bool) error) *AuthService {+func NewAuthService(store *store.Store, secret string, tokenDuration time.Duration, licenseService enterpriseAPI.LicenseService, metricReporter *metricreport.Reporter, profile *config.Profile, stateCfg *state.State, postCreateUser func(ctx context.Context, user *store.UserMessage, firstEndUser bool) error) (*AuthService, error) {return &AuthService{store: store,secret: secret,@@ -58,8 +61,9 @@ func NewAuthService(store *store.Store, secret string, tokenDuration time.DuratilicenseService: licenseService,metricReporter: metricReporter,profile: profile,+ stateCfg: stateCfg,postCreateUser: postCreateUser,- }+ }, nil}// GetUser gets a user.@@ -633,7 +637,17 @@ func (s *AuthService) Login(ctx context.Context, request *v1pb.LoginRequest) (*v}// Logout is the auth logout method.-func (*AuthService) Logout(ctx context.Context, _ *v1pb.LogoutRequest) (*emptypb.Empty, error) {+func (s *AuthService) Logout(ctx context.Context, _ *v1pb.LogoutRequest) (*emptypb.Empty, error) {+ md, ok := metadata.FromIncomingContext(ctx)+ if !ok {+ return nil, status.Errorf(codes.Unauthenticated, "failed to parse metadata from incoming context")+ }+ accessTokenStr, err := auth.GetTokenFromMetadata(md)+ if err != nil {+ return nil, status.Errorf(codes.Unauthenticated, err.Error())+ }+ s.stateCfg.ExpireCache.Set(accessTokenStr, true, 1)+if err := grpc.SetHeader(ctx, metadata.New(map[string]string{auth.GatewayMetadataAccessTokenKey: "",auth.GatewayMetadataUserIDKey: "",diff --git a/backend/component/state/state.go b/backend/component/state/state.goindex 1bdb9d8ed6..d4d090df41 100644--- a/backend/component/state/state.go+++ b/backend/component/state/state.go@@ -4,6 +4,9 @@ package stateimport ("sync"+ "github.com/dgraph-io/ristretto"+ "github.com/pkg/errors"+"github.com/bytebase/bytebase/backend/store")@@ -59,9 +62,32 @@ type State struct {// TaskRunTickleChan is the tickler for task run scheduler.TaskRunTickleChan chan int+ ExpireCache *ristretto.Cache+sync.Mutex}+func New() (*State, error) {+ expireCache, err := ristretto.NewCache(&ristretto.Config{+ NumCounters: 1_000,+ MaxCost: 1_000, // ~1KB+ BufferItems: 64,+ })+ if err != nil {+ return nil, errors.Wrapf(err, "failed to create auth expire cache")+ }+ return &State{+ InstanceDatabaseSyncChan: make(chan *store.InstanceMessage, 100),+ InstanceSlowQuerySyncChan: make(chan *InstanceSlowQuerySyncMessage, 100),+ InstanceOutstandingConnections: make(map[int]int),+ IssueExternalApprovalRelayCancelChan: make(chan int, 1),+ TaskSkippedOrDoneChan: make(chan int, 1000),+ PlanCheckTickleChan: make(chan int, 1000),+ TaskRunTickleChan: make(chan int, 1000),+ ExpireCache: expireCache,+ }, nil+}+// InstanceSlowQuerySyncMessage is the message for synchronizing slow query logs for instances.type InstanceSlowQuerySyncMessage struct {InstanceID stringdiff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.goindex 8a682447a0..74edbeb2c7 100644--- a/backend/server/grpc_routes.go+++ b/backend/server/grpc_routes.go@@ -46,7 +46,11 @@ func configureGrpcRouters(errorRecordRing *api.ErrorRecordRing,tokenDuration time.Duration) (*v1.RolloutService, *v1.IssueService, error) {// Register services.- v1pb.RegisterAuthServiceServer(grpcServer, v1.NewAuthService(stores, secret, tokenDuration, licenseService, metricReporter, profile, postCreateUser))+ authService, err := v1.NewAuthService(stores, secret, tokenDuration, licenseService, metricReporter, profile, stateCfg, postCreateUser)+ if err != nil {+ return nil, nil, err+ }+ v1pb.RegisterAuthServiceServer(grpcServer, authService)v1pb.RegisterActuatorServiceServer(grpcServer, v1.NewActuatorService(stores, profile, errorRecordRing))v1pb.RegisterSubscriptionServiceServer(grpcServer, v1.NewSubscriptionService(stores,diff --git a/backend/server/server.go b/backend/server/server.goindex 888098df32..95a4a7e087 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -266,14 +266,9 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {}s.store = storeInstance- s.stateCfg = &state.State{- InstanceDatabaseSyncChan: make(chan *store.InstanceMessage, 100),- InstanceSlowQuerySyncChan: make(chan *state.InstanceSlowQuerySyncMessage, 100),- InstanceOutstandingConnections: make(map[int]int),- IssueExternalApprovalRelayCancelChan: make(chan int, 1),- TaskSkippedOrDoneChan: make(chan int, 1000),- PlanCheckTickleChan: make(chan int, 1000),- TaskRunTickleChan: make(chan int, 1000),+ s.stateCfg, err = state.New()+ if err != nil {+ return nil, err}if err := s.store.BackfillIssueTsVector(ctx); err != nil {@@ -357,7 +352,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {}// Setup the gRPC and grpc-gateway.- authProvider := auth.New(s.store, s.secret, tokenDuration, s.licenseService, profile.Mode)+ authProvider := auth.New(s.store, s.secret, tokenDuration, s.licenseService, s.stateCfg, profile.Mode)aclProvider := v1.NewACLInterceptor(s.store, s.secret, s.licenseService, profile.Mode)debugProvider := v1.NewDebugInterceptor(&s.errorRecordRing, &profile, s.metricReporter)onPanic := func(p any) error {