Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(auth): implement web refresh token support (#18646)
p0ny3d5de7f43b17
diff --git a/backend/api/auth/header.go b/backend/api/auth/header.goindex 8a113a7290..403af71954 100644--- a/backend/api/auth/header.go+++ b/backend/api/auth/header.go@@ -72,3 +72,43 @@ func GetTokenDuration(ctx context.Context, store *store.Store, licenseService *ereturn tokenDuration}++const RefreshTokenCookieName = "refresh-token"++// GetRefreshTokenCookie creates a cookie for the refresh token.+// token="" => unset (clears cookie)+// Path is "/" to allow logout to delete the token from database.+// Security is maintained via HttpOnly, Secure, and SameSite=Strict.+func GetRefreshTokenCookie(origin, token string, duration time.Duration) *http.Cookie {+ if token == "" {+ return &http.Cookie{+ Name: RefreshTokenCookieName,+ Value: "",+ Expires: time.Unix(0, 0),+ Path: "/",+ }+ }+ isHTTPS := strings.HasPrefix(origin, "https")+ return &http.Cookie{+ Name: RefreshTokenCookieName,+ Value: token,+ MaxAge: int(duration.Seconds()),+ Path: "/",+ HttpOnly: true,+ Secure: isHTTPS,+ SameSite: http.SameSiteStrictMode,+ }+}++// GetRefreshTokenFromCookie extracts the refresh token from request headers.+func GetRefreshTokenFromCookie(header http.Header) string {+ for _, cookie := range header.Values("Cookie") {+ for _, part := range strings.Split(cookie, ";") {+ part = strings.TrimSpace(part)+ if strings.HasPrefix(part, RefreshTokenCookieName+"=") {+ return strings.TrimPrefix(part, RefreshTokenCookieName+"=")+ }+ }+ }+ return ""+}diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 40d5fd18d9..b3be3afb3f 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -382,6 +382,44 @@ paths:application/json:schema:$ref: '#/components/schemas/google.protobuf.Empty'+ /bytebase.v1.AuthService/Refresh:+ post:+ tags:+ - bytebase.v1.AuthService+ summary: 'Refreshes the access token using the refresh token cookie. Permissions required: None (validates via refresh token cookie)'+ description: |-+ Refreshes the access token using the refresh token cookie.+ Permissions required: None (validates via refresh token cookie)+ operationId: bytebase.v1.AuthService.Refresh+ parameters:+ - name: Connect-Protocol-Version+ in: header+ required: true+ schema:+ $ref: '#/components/schemas/connect-protocol-version'+ - name: Connect-Timeout-Ms+ in: header+ schema:+ $ref: '#/components/schemas/connect-timeout-header'+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.RefreshRequest'+ required: true+ responses:+ default:+ description: Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/connect.error'+ "200":+ description: Success+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.RefreshResponse'/bytebase.v1.CelService/BatchDeparse:post:tags:@@ -13738,6 +13776,16 @@ components:Range represents a span within a text or sequence.Whether the indices are byte offsets or character indices depends on the context.Check the documentation of the field using Range for specific semantics.+ bytebase.v1.RefreshRequest:+ type: object+ title: RefreshRequest+ additionalProperties: false+ description: Request to refresh the access token.+ bytebase.v1.RefreshResponse:+ type: object+ title: RefreshResponse+ additionalProperties: false+ description: Response from refreshing the access token.bytebase.v1.RejectIssueRequest:type: objectproperties:diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.goindex ad7802a25c..98fbd4a6ff 100644--- a/backend/api/v1/auth_service.go+++ b/backend/api/v1/auth_service.go@@ -56,6 +56,8 @@ const (errMsgInvalidRecoveryCode = "invalid recovery code"errMsgTooManyPassword = "too many failed login attempts, please try again later" // Will be used for password rate limitingerrMsgTooManyMFA = "too many failed MFA attempts, please try again later"++ refreshTokenGracePeriod = 30 * time.Second)var (@@ -85,6 +87,14 @@ func NewAuthService(store *store.Store, secret string, licenseService *enterpris}}+// GetRefreshTokenDuration returns the configured refresh token duration or default.+func GetRefreshTokenDuration(_ context.Context, _ *store.Store, _ *enterprise.LicenseService) time.Duration {+ // TODO: Add refresh_token_duration field to WorkspaceProfileSetting proto+ // and implement workspace setting-based configuration similar to GetTokenDuration.+ // For now, use a fixed 30-day duration.+ return 30 * 24 * time.Hour+}+// Login is the auth login method including SSO.func (s *AuthService) Login(ctx context.Context, req *connect.Request[v1pb.LoginRequest]) (*connect.Response[v1pb.LoginResponse], error) {request := req.Msg@@ -168,11 +178,110 @@ func (s *AuthService) Logout(ctx context.Context, req *connect.Request[v1pb.Logo}s.stateCfg.ExpireCache.Add(accessTokenStr, true)+ // Delete refresh token from database if present+ if refreshToken := auth.GetRefreshTokenFromCookie(req.Header()); refreshToken != "" {+ if err := s.store.DeleteWebRefreshToken(ctx, auth.HashToken(refreshToken)); err != nil {+ slog.Error("failed to delete refresh token on logout", log.BBError(err))+ }+ }+resp := connect.NewResponse(&emptypb.Empty{})origin := req.Header().Get("Origin")+ // Clear access token cookiecookie := auth.GetTokenCookie(ctx, s.store, s.licenseService, origin, "")resp.Header().Add("Set-Cookie", cookie.String())+ // Clear refresh token cookie+ resp.Header().Add("Set-Cookie", auth.GetRefreshTokenCookie(origin, "", 0).String())+ return resp, nil+}++// Refresh exchanges a refresh token for new access and refresh tokens.+func (s *AuthService) Refresh(ctx context.Context, req *connect.Request[v1pb.RefreshRequest]) (*connect.Response[v1pb.RefreshResponse], error) {+ // 1. Extract refresh token from cookie+ refreshToken := auth.GetRefreshTokenFromCookie(req.Header())+ if refreshToken == "" {+ return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("refresh token not found"))+ }++ // 2. Look up in database+ tokenHash := auth.HashToken(refreshToken)+ stored, err := s.store.GetWebRefreshToken(ctx, tokenHash)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get refresh token"))+ }+ if stored == nil {+ return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("invalid refresh token"))+ }++ // 3. Check expiration+ if time.Now().After(stored.ExpiresAt) {+ if err := s.store.DeleteWebRefreshToken(ctx, tokenHash); err != nil {+ slog.Error("failed to delete expired refresh token", log.BBError(err))+ }+ return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("refresh token expired"))+ }++ // 4. Check if already rotated (grace period)+ if stored.RotatedAt != nil {+ if time.Since(*stored.RotatedAt) > refreshTokenGracePeriod {+ if err := s.store.DeleteWebRefreshToken(ctx, tokenHash); err != nil {+ slog.Error("failed to delete rotated refresh token", log.BBError(err))+ }+ return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("refresh token already used"))+ }+ // Within grace period - return success but don't issue new tokens+ return connect.NewResponse(&v1pb.RefreshResponse{}), nil+ }++ // 5. Get user+ user, err := s.store.GetUserByEmail(ctx, stored.UserEmail)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get user"))+ }+ if user == nil || user.MemberDeleted {+ return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("user not found"))+ }++ // 6. Atomically mark old token as rotated (grace period starts)+ // If another request already rotated it, we're in a race - return success without new tokens+ rotated, err := s.store.MarkWebRefreshTokenRotated(ctx, tokenHash)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to rotate refresh token"))+ }+ if !rotated {+ // Another request already rotated this token - we're within grace period+ // Return success but don't issue new tokens (the other request already did)+ return connect.NewResponse(&v1pb.RefreshResponse{}), nil+ }++ // 7. Issue new tokens+ accessTokenDuration := auth.GetTokenDuration(ctx, s.store, s.licenseService)+ accessToken, err := auth.GenerateAccessToken(user.Email, s.profile.Mode, s.secret, accessTokenDuration)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate access token"))+ }++ refreshTokenDuration := GetRefreshTokenDuration(ctx, s.store, s.licenseService)+ newRefreshToken, err := auth.GenerateOpaqueToken()+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate refresh token"))+ }++ if err := s.store.CreateWebRefreshToken(ctx, &store.WebRefreshTokenMessage{+ TokenHash: auth.HashToken(newRefreshToken),+ UserEmail: user.Email,+ ExpiresAt: time.Now().Add(refreshTokenDuration),+ }); err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create refresh token"))+ }++ // 8. Set cookies and return+ resp := connect.NewResponse(&v1pb.RefreshResponse{})+ origin := req.Header().Get("Origin")+ resp.Header().Add("Set-Cookie", auth.GetTokenCookie(ctx, s.store, s.licenseService, origin, accessToken).String())+ resp.Header().Add("Set-Cookie", auth.GetRefreshTokenCookie(origin, newRefreshToken, refreshTokenDuration).String())+return resp, nil}@@ -696,6 +805,22 @@ func (s *AuthService) finalizeLogin(ctx context.Context, req *connect.Request[v1origin := req.Header().Get("Origin")cookie := auth.GetTokenCookie(ctx, s.store, s.licenseService, origin, token)resp.Header().Add("Set-Cookie", cookie.String())++ // Issue refresh token for web login+ refreshToken, err := auth.GenerateOpaqueToken()+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to generate refresh token"))+ }+ refreshTokenDuration := GetRefreshTokenDuration(ctx, s.store, s.licenseService)+ if err := s.store.CreateWebRefreshToken(ctx, &store.WebRefreshTokenMessage{+ TokenHash: auth.HashToken(refreshToken),+ UserEmail: user.Email,+ ExpiresAt: time.Now().Add(refreshTokenDuration),+ }); err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to create refresh token"))+ }+ refreshCookie := auth.GetRefreshTokenCookie(origin, refreshToken, refreshTokenDuration)+ resp.Header().Add("Set-Cookie", refreshCookie.String())}if _, err := s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{diff --git a/backend/api/v1/user_service.go b/backend/api/v1/user_service.goindex 6e7aed4e47..a768a0e2a3 100644--- a/backend/api/v1/user_service.go+++ b/backend/api/v1/user_service.go@@ -3,6 +3,7 @@ package v1import ("context""fmt"+ "log/slog""net/mail""regexp""strings"@@ -17,6 +18,7 @@ import ("google.golang.org/protobuf/types/known/timestamppb""github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/component/iam""github.com/bytebase/bytebase/backend/component/state"@@ -468,6 +470,12 @@ func (s *UserService) UpdateUser(ctx context.Context, request *connect.Request[v}passwordHashStr := string(passwordHash)patch.PasswordHash = &passwordHashStr++ // Revoke all refresh tokens for this user (including current session)+ // User must re-login after password change for security+ if err := s.store.DeleteWebRefreshTokensByUser(ctx, user.Email); err != nil {+ slog.Error("failed to revoke refresh tokens on password change", log.BBError(err), slog.String("user", user.Email))+ }}// This flag is mainly used for validating OTP code when user setup MFA.// We only validate OTP code but not update user.diff --git a/backend/generated-go/v1/auth_service.pb.go b/backend/generated-go/v1/auth_service.pb.goindex e87454d560..99635ac5a8 100644--- a/backend/generated-go/v1/auth_service.pb.go+++ b/backend/generated-go/v1/auth_service.pb.go@@ -518,6 +518,80 @@ func (x *ExchangeTokenResponse) GetAccessToken() string {return ""}+// Request to refresh the access token.+type RefreshRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *RefreshRequest) Reset() {+ *x = RefreshRequest{}+ mi := &file_v1_auth_service_proto_msgTypes[8]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *RefreshRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RefreshRequest) ProtoMessage() {}++func (x *RefreshRequest) ProtoReflect() protoreflect.Message {+ mi := &file_v1_auth_service_proto_msgTypes[8]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RefreshRequest.ProtoReflect.Descriptor instead.+func (*RefreshRequest) Descriptor() ([]byte, []int) {+ return file_v1_auth_service_proto_rawDescGZIP(), []int{8}+}++// Response from refreshing the access token.+type RefreshResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *RefreshResponse) Reset() {+ *x = RefreshResponse{}+ mi := &file_v1_auth_service_proto_msgTypes[9]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *RefreshResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RefreshResponse) ProtoMessage() {}++func (x *RefreshResponse) ProtoReflect() protoreflect.Message {+ mi := &file_v1_auth_service_proto_msgTypes[9]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RefreshResponse.ProtoReflect.Descriptor instead.+func (*RefreshResponse) Descriptor() ([]byte, []int) {+ return file_v1_auth_service_proto_rawDescGZIP(), []int{9}+}+var File_v1_auth_service_proto protoreflect.FileDescriptorconst file_v1_auth_service_proto_rawDesc = "" +@@ -555,11 +629,14 @@ const file_v1_auth_service_proto_rawDesc = "" +"\x05token\x18\x01 \x01(\tR\x05token\x12\x14\n" +"\x05email\x18\x02 \x01(\tR\x05email\":\n" +"\x15ExchangeTokenResponse\x12!\n" +- "\faccess_token\x18\x01 \x01(\tR\vaccessToken2\xd6\x02\n" ++ "\faccess_token\x18\x01 \x01(\tR\vaccessToken\"\x10\n" ++ "\x0eRefreshRequest\"\x11\n" ++ "\x0fRefreshResponse2\xbd\x03\n" +"\vAuthService\x12a\n" +"\x05Login\x12\x19.bytebase.v1.LoginRequest\x1a\x1a.bytebase.v1.LoginResponse\"!\x80\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02\x13:\x01*\"\x0e/v1/auth/login\x12`\n" +"\x06Logout\x12\x1a.bytebase.v1.LogoutRequest\x1a\x16.google.protobuf.Empty\"\"\x80\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02\x14:\x01*\"\x0f/v1/auth/logout\x12\x81\x01\n" +- "\rExchangeToken\x12!.bytebase.v1.ExchangeTokenRequest\x1a\".bytebase.v1.ExchangeTokenResponse\")\x80\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02\x1b:\x01*\"\x16/v1/auth:exchangeTokenB\xa6\x01\n" ++ "\rExchangeToken\x12!.bytebase.v1.ExchangeTokenRequest\x1a\".bytebase.v1.ExchangeTokenResponse\")\x80\xea0\x01\x98\xea0\x01\x82\xd3\xe4\x93\x02\x1b:\x01*\"\x16/v1/auth:exchangeToken\x12e\n" ++ "\aRefresh\x12\x1b.bytebase.v1.RefreshRequest\x1a\x1c.bytebase.v1.RefreshResponse\"\x1f\x80\xea0\x01\x82\xd3\xe4\x93\x02\x15:\x01*\"\x10/v1/auth/refreshB\xa6\x01\n" +"\x0fcom.bytebase.v1B\x10AuthServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"var (@@ -574,7 +651,7 @@ func file_v1_auth_service_proto_rawDescGZIP() []byte {return file_v1_auth_service_proto_rawDescData}-var file_v1_auth_service_proto_msgTypes = make([]protoimpl.MessageInfo, 8)+var file_v1_auth_service_proto_msgTypes = make([]protoimpl.MessageInfo, 10)var file_v1_auth_service_proto_goTypes = []any{(*LoginRequest)(nil), // 0: bytebase.v1.LoginRequest(*IdentityProviderContext)(nil), // 1: bytebase.v1.IdentityProviderContext@@ -584,25 +661,29 @@ var file_v1_auth_service_proto_goTypes = []any{(*LogoutRequest)(nil), // 5: bytebase.v1.LogoutRequest(*ExchangeTokenRequest)(nil), // 6: bytebase.v1.ExchangeTokenRequest(*ExchangeTokenResponse)(nil), // 7: bytebase.v1.ExchangeTokenResponse- (*User)(nil), // 8: bytebase.v1.User- (*emptypb.Empty)(nil), // 9: google.protobuf.Empty+ (*RefreshRequest)(nil), // 8: bytebase.v1.RefreshRequest+ (*RefreshResponse)(nil), // 9: bytebase.v1.RefreshResponse+ (*User)(nil), // 10: bytebase.v1.User+ (*emptypb.Empty)(nil), // 11: google.protobuf.Empty}var file_v1_auth_service_proto_depIdxs = []int32{- 1, // 0: bytebase.v1.LoginRequest.idp_context:type_name -> bytebase.v1.IdentityProviderContext- 2, // 1: bytebase.v1.IdentityProviderContext.oauth2_context:type_name -> bytebase.v1.OAuth2IdentityProviderContext- 3, // 2: bytebase.v1.IdentityProviderContext.oidc_context:type_name -> bytebase.v1.OIDCIdentityProviderContext- 8, // 3: bytebase.v1.LoginResponse.user:type_name -> bytebase.v1.User- 0, // 4: bytebase.v1.AuthService.Login:input_type -> bytebase.v1.LoginRequest- 5, // 5: bytebase.v1.AuthService.Logout:input_type -> bytebase.v1.LogoutRequest- 6, // 6: bytebase.v1.AuthService.ExchangeToken:input_type -> bytebase.v1.ExchangeTokenRequest- 4, // 7: bytebase.v1.AuthService.Login:output_type -> bytebase.v1.LoginResponse- 9, // 8: bytebase.v1.AuthService.Logout:output_type -> google.protobuf.Empty- 7, // 9: bytebase.v1.AuthService.ExchangeToken:output_type -> bytebase.v1.ExchangeTokenResponse- 7, // [7:10] is the sub-list for method output_type- 4, // [4:7] is the sub-list for method input_type- 4, // [4:4] is the sub-list for extension type_name- 4, // [4:4] is the sub-list for extension extendee- 0, // [0:4] is the sub-list for field type_name+ 1, // 0: bytebase.v1.LoginRequest.idp_context:type_name -> bytebase.v1.IdentityProviderContext+ 2, // 1: bytebase.v1.IdentityProviderContext.oauth2_context:type_name -> bytebase.v1.OAuth2IdentityProviderContext+ 3, // 2: bytebase.v1.IdentityProviderContext.oidc_context:type_name -> bytebase.v1.OIDCIdentityProviderContext+ 10, // 3: bytebase.v1.LoginResponse.user:type_name -> bytebase.v1.User+ 0, // 4: bytebase.v1.AuthService.Login:input_type -> bytebase.v1.LoginRequest+ 5, // 5: bytebase.v1.AuthService.Logout:input_type -> bytebase.v1.LogoutRequest+ 6, // 6: bytebase.v1.AuthService.ExchangeToken:input_type -> bytebase.v1.ExchangeTokenRequest+ 8, // 7: bytebase.v1.AuthService.Refresh:input_type -> bytebase.v1.RefreshRequest+ 4, // 8: bytebase.v1.AuthService.Login:output_type -> bytebase.v1.LoginResponse+ 11, // 9: bytebase.v1.AuthService.Logout:output_type -> google.protobuf.Empty+ 7, // 10: bytebase.v1.AuthService.ExchangeToken:output_type -> bytebase.v1.ExchangeTokenResponse+ 9, // 11: bytebase.v1.AuthService.Refresh:output_type -> bytebase.v1.RefreshResponse+ 8, // [8:12] is the sub-list for method output_type+ 4, // [4:8] is the sub-list for method input_type+ 4, // [4:4] is the sub-list for extension type_name+ 4, // [4:4] is the sub-list for extension extendee+ 0, // [0:4] is the sub-list for field type_name}func init() { file_v1_auth_service_proto_init() }@@ -624,7 +705,7 @@ func file_v1_auth_service_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_auth_service_proto_rawDesc), len(file_v1_auth_service_proto_rawDesc)),NumEnums: 0,- NumMessages: 8,+ NumMessages: 10,NumExtensions: 0,NumServices: 1,},diff --git a/backend/generated-go/v1/auth_service.pb.gw.go b/backend/generated-go/v1/auth_service.pb.gw.goindex 3bd70391a3..b9d7185440 100644--- a/backend/generated-go/v1/auth_service.pb.gw.go+++ b/backend/generated-go/v1/auth_service.pb.gw.go@@ -116,6 +116,33 @@ func local_request_AuthService_ExchangeToken_0(ctx context.Context, marshaler rureturn msg, metadata, err}+func request_AuthService_Refresh_0(ctx context.Context, marshaler runtime.Marshaler, client AuthServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq RefreshRequest+ metadata runtime.ServerMetadata+ )+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)+ }+ if req.Body != nil {+ _, _ = io.Copy(io.Discard, req.Body)+ }+ msg, err := client.Refresh(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))+ return msg, metadata, err+}++func local_request_AuthService_Refresh_0(ctx context.Context, marshaler runtime.Marshaler, server AuthServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq RefreshRequest+ metadata runtime.ServerMetadata+ )+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)+ }+ msg, err := server.Refresh(ctx, &protoReq)+ return msg, metadata, err+}+// RegisterAuthServiceHandlerServer registers the http handlers for service AuthService to "mux".// UnaryRPC :call AuthServiceServer directly.// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.@@ -182,6 +209,26 @@ func RegisterAuthServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux}forward_AuthService_ExchangeToken_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})+ mux.Handle(http.MethodPost, pattern_AuthService_Refresh_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ var stream runtime.ServerTransportStream+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.AuthService/Refresh", runtime.WithHTTPPathPattern("/v1/auth/refresh"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := local_request_AuthService_Refresh_0(annotatedContext, inboundMarshaler, server, req, pathParams)+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_AuthService_Refresh_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })return nil}@@ -273,6 +320,23 @@ func RegisterAuthServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux}forward_AuthService_ExchangeToken_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})+ mux.Handle(http.MethodPost, pattern_AuthService_Refresh_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.AuthService/Refresh", runtime.WithHTTPPathPattern("/v1/auth/refresh"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := request_AuthService_Refresh_0(annotatedContext, inboundMarshaler, client, req, pathParams)+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_AuthService_Refresh_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })return nil}@@ -280,10 +344,12 @@ var (pattern_AuthService_Login_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "auth", "login"}, ""))pattern_AuthService_Logout_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "auth", "logout"}, ""))pattern_AuthService_ExchangeToken_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "auth"}, "exchangeToken"))+ pattern_AuthService_Refresh_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "auth", "refresh"}, "")))var (forward_AuthService_Login_0 = runtime.ForwardResponseMessageforward_AuthService_Logout_0 = runtime.ForwardResponseMessageforward_AuthService_ExchangeToken_0 = runtime.ForwardResponseMessage+ forward_AuthService_Refresh_0 = runtime.ForwardResponseMessage)diff --git a/backend/generated-go/v1/auth_service_equal.pb.go b/backend/generated-go/v1/auth_service_equal.pb.goindex 59bc5c3608..dcd20dcb23 100644--- a/backend/generated-go/v1/auth_service_equal.pb.go+++ b/backend/generated-go/v1/auth_service_equal.pb.go@@ -139,3 +139,23 @@ func (x *ExchangeTokenResponse) Equal(y *ExchangeTokenResponse) bool {}return true}++func (x *RefreshRequest) Equal(y *RefreshRequest) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ return true+}++func (x *RefreshResponse) Equal(y *RefreshResponse) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ return true+}diff --git a/backend/generated-go/v1/auth_service_grpc.pb.go b/backend/generated-go/v1/auth_service_grpc.pb.goindex 037a6e02ff..2785f2e79f 100644--- a/backend/generated-go/v1/auth_service_grpc.pb.go+++ b/backend/generated-go/v1/auth_service_grpc.pb.go@@ -23,6 +23,7 @@ const (AuthService_Login_FullMethodName = "/bytebase.v1.AuthService/Login"AuthService_Logout_FullMethodName = "/bytebase.v1.AuthService/Logout"AuthService_ExchangeToken_FullMethodName = "/bytebase.v1.AuthService/ExchangeToken"+ AuthService_Refresh_FullMethodName = "/bytebase.v1.AuthService/Refresh")// AuthServiceClient is the client API for AuthService service.@@ -41,6 +42,9 @@ type AuthServiceClient interface {// Used by CI/CD pipelines with Workload Identity Federation.// Permissions required: None (validates via OIDC token)ExchangeToken(ctx context.Context, in *ExchangeTokenRequest, opts ...grpc.CallOption) (*ExchangeTokenResponse, error)+ // Refreshes the access token using the refresh token cookie.+ // Permissions required: None (validates via refresh token cookie)+ Refresh(ctx context.Context, in *RefreshRequest, opts ...grpc.CallOption) (*RefreshResponse, error)}type authServiceClient struct {@@ -81,6 +85,16 @@ func (c *authServiceClient) ExchangeToken(ctx context.Context, in *ExchangeTokenreturn out, nil}+func (c *authServiceClient) Refresh(ctx context.Context, in *RefreshRequest, opts ...grpc.CallOption) (*RefreshResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(RefreshResponse)+ err := c.cc.Invoke(ctx, AuthService_Refresh_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+// AuthServiceServer is the server API for AuthService service.// All implementations must embed UnimplementedAuthServiceServer// for forward compatibility.@@ -97,6 +111,9 @@ type AuthServiceServer interface {// Used by CI/CD pipelines with Workload Identity Federation.// Permissions required: None (validates via OIDC token)ExchangeToken(context.Context, *ExchangeTokenRequest) (*ExchangeTokenResponse, error)+ // Refreshes the access token using the refresh token cookie.+ // Permissions required: None (validates via refresh token cookie)+ Refresh(context.Context, *RefreshRequest) (*RefreshResponse, error)mustEmbedUnimplementedAuthServiceServer()}@@ -116,6 +133,9 @@ func (UnimplementedAuthServiceServer) Logout(context.Context, *LogoutRequest) (*func (UnimplementedAuthServiceServer) ExchangeToken(context.Context, *ExchangeTokenRequest) (*ExchangeTokenResponse, error) {return nil, status.Error(codes.Unimplemented, "method ExchangeToken not implemented")}+func (UnimplementedAuthServiceServer) Refresh(context.Context, *RefreshRequest) (*RefreshResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method Refresh not implemented")+}func (UnimplementedAuthServiceServer) mustEmbedUnimplementedAuthServiceServer() {}func (UnimplementedAuthServiceServer) testEmbeddedByValue() {}@@ -191,6 +211,24 @@ func _AuthService_ExchangeToken_Handler(srv interface{}, ctx context.Context, dereturn interceptor(ctx, in, info, handler)}+func _AuthService_Refresh_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(RefreshRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AuthServiceServer).Refresh(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AuthService_Refresh_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AuthServiceServer).Refresh(ctx, req.(*RefreshRequest))+ }+ return interceptor(ctx, in, info, handler)+}+// AuthService_ServiceDesc is the grpc.ServiceDesc for AuthService service.// It's only intended for direct use with grpc.RegisterService,// and not to be introspected or modified (even as a copy)@@ -210,6 +248,10 @@ var AuthService_ServiceDesc = grpc.ServiceDesc{MethodName: "ExchangeToken",Handler: _AuthService_ExchangeToken_Handler,},+ {+ MethodName: "Refresh",+ Handler: _AuthService_Refresh_Handler,+ },},Streams: []grpc.StreamDesc{},Metadata: "v1/auth_service.proto",diff --git a/backend/generated-go/v1/v1connect/auth_service.connect.go b/backend/generated-go/v1/v1connect/auth_service.connect.goindex 6a8b7ec582..0a60628baf 100644--- a/backend/generated-go/v1/v1connect/auth_service.connect.go+++ b/backend/generated-go/v1/v1connect/auth_service.connect.go@@ -41,6 +41,8 @@ const (// AuthServiceExchangeTokenProcedure is the fully-qualified name of the AuthService's ExchangeToken// RPC.AuthServiceExchangeTokenProcedure = "/bytebase.v1.AuthService/ExchangeToken"+ // AuthServiceRefreshProcedure is the fully-qualified name of the AuthService's Refresh RPC.+ AuthServiceRefreshProcedure = "/bytebase.v1.AuthService/Refresh")// AuthServiceClient is a client for the bytebase.v1.AuthService service.@@ -55,6 +57,9 @@ type AuthServiceClient interface {// Used by CI/CD pipelines with Workload Identity Federation.// Permissions required: None (validates via OIDC token)ExchangeToken(context.Context, *connect.Request[v1.ExchangeTokenRequest]) (*connect.Response[v1.ExchangeTokenResponse], error)+ // Refreshes the access token using the refresh token cookie.+ // Permissions required: None (validates via refresh token cookie)+ Refresh(context.Context, *connect.Request[v1.RefreshRequest]) (*connect.Response[v1.RefreshResponse], error)}// NewAuthServiceClient constructs a client for the bytebase.v1.AuthService service. By default, it@@ -86,6 +91,12 @@ func NewAuthServiceClient(httpClient connect.HTTPClient, baseURL string, opts ..connect.WithSchema(authServiceMethods.ByName("ExchangeToken")),connect.WithClientOptions(opts...),),+ refresh: connect.NewClient[v1.RefreshRequest, v1.RefreshResponse](+ httpClient,+ baseURL+AuthServiceRefreshProcedure,+ connect.WithSchema(authServiceMethods.ByName("Refresh")),+ connect.WithClientOptions(opts...),+ ),}}@@ -94,6 +105,7 @@ type authServiceClient struct {login *connect.Client[v1.LoginRequest, v1.LoginResponse]logout *connect.Client[v1.LogoutRequest, emptypb.Empty]exchangeToken *connect.Client[v1.ExchangeTokenRequest, v1.ExchangeTokenResponse]+ refresh *connect.Client[v1.RefreshRequest, v1.RefreshResponse]}// Login calls bytebase.v1.AuthService.Login.@@ -111,6 +123,11 @@ func (c *authServiceClient) ExchangeToken(ctx context.Context, req *connect.Requreturn c.exchangeToken.CallUnary(ctx, req)}+// Refresh calls bytebase.v1.AuthService.Refresh.+func (c *authServiceClient) Refresh(ctx context.Context, req *connect.Request[v1.RefreshRequest]) (*connect.Response[v1.RefreshResponse], error) {+ return c.refresh.CallUnary(ctx, req)+}+// AuthServiceHandler is an implementation of the bytebase.v1.AuthService service.type AuthServiceHandler interface {// Authenticates a user and returns access tokens.@@ -123,6 +140,9 @@ type AuthServiceHandler interface {// Used by CI/CD pipelines with Workload Identity Federation.// Permissions required: None (validates via OIDC token)ExchangeToken(context.Context, *connect.Request[v1.ExchangeTokenRequest]) (*connect.Response[v1.ExchangeTokenResponse], error)+ // Refreshes the access token using the refresh token cookie.+ // Permissions required: None (validates via refresh token cookie)+ Refresh(context.Context, *connect.Request[v1.RefreshRequest]) (*connect.Response[v1.RefreshResponse], error)}// NewAuthServiceHandler builds an HTTP handler from the service implementation. It returns the path@@ -150,6 +170,12 @@ func NewAuthServiceHandler(svc AuthServiceHandler, opts ...connect.HandlerOptionconnect.WithSchema(authServiceMethods.ByName("ExchangeToken")),connect.WithHandlerOptions(opts...),)+ authServiceRefreshHandler := connect.NewUnaryHandler(+ AuthServiceRefreshProcedure,+ svc.Refresh,+ connect.WithSchema(authServiceMethods.ByName("Refresh")),+ connect.WithHandlerOptions(opts...),+ )return "/bytebase.v1.AuthService/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {case AuthServiceLoginProcedure:@@ -158,6 +184,8 @@ func NewAuthServiceHandler(svc AuthServiceHandler, opts ...connect.HandlerOptionauthServiceLogoutHandler.ServeHTTP(w, r)case AuthServiceExchangeTokenProcedure:authServiceExchangeTokenHandler.ServeHTTP(w, r)+ case AuthServiceRefreshProcedure:+ authServiceRefreshHandler.ServeHTTP(w, r)default:http.NotFound(w, r)}@@ -178,3 +206,7 @@ func (UnimplementedAuthServiceHandler) Logout(context.Context, *connect.Request[func (UnimplementedAuthServiceHandler) ExchangeToken(context.Context, *connect.Request[v1.ExchangeTokenRequest]) (*connect.Response[v1.ExchangeTokenResponse], error) {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.AuthService.ExchangeToken is not implemented"))}++func (UnimplementedAuthServiceHandler) Refresh(context.Context, *connect.Request[v1.RefreshRequest]) (*connect.Response[v1.RefreshResponse], error) {+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.AuthService.Refresh is not implemented"))+}diff --git a/backend/migrator/migration/3.14/0011##web_refresh_token.sql b/backend/migrator/migration/3.14/0011##web_refresh_token.sqlnew file mode 100644index 0000000000..322e79eabc--- /dev/null+++ b/backend/migrator/migration/3.14/0011##web_refresh_token.sql@@ -0,0 +1,10 @@+CREATE TABLE web_refresh_token (+ token_hash TEXT PRIMARY KEY,+ user_email TEXT NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,+ expires_at TIMESTAMPTZ NOT NULL,+ rotated_at TIMESTAMPTZ+);++CREATE INDEX idx_web_refresh_token_user_email ON web_refresh_token(user_email);+CREATE INDEX idx_web_refresh_token_expires_at ON web_refresh_token(expires_at);+CREATE INDEX idx_web_refresh_token_rotated_at ON web_refresh_token(rotated_at) WHERE rotated_at IS NOT NULL;diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sqlindex 83f11ba923..79bd07a86a 100644--- a/backend/migrator/migration/LATEST.sql+++ b/backend/migrator/migration/LATEST.sql@@ -550,6 +550,18 @@ CREATE INDEX idx_oauth2_authorization_code_expires_at ON oauth2_authorization_coCREATE INDEX idx_oauth2_refresh_token_expires_at ON oauth2_refresh_token(expires_at);CREATE INDEX idx_oauth2_client_last_active_at ON oauth2_client(last_active_at);+-- Web refresh tokens for session management+CREATE TABLE web_refresh_token (+ token_hash TEXT PRIMARY KEY,+ user_email TEXT NOT NULL REFERENCES principal(email) ON UPDATE CASCADE,+ expires_at TIMESTAMPTZ NOT NULL,+ rotated_at TIMESTAMPTZ+);++CREATE INDEX idx_web_refresh_token_user_email ON web_refresh_token(user_email);+CREATE INDEX idx_web_refresh_token_expires_at ON web_refresh_token(expires_at);+CREATE INDEX idx_web_refresh_token_rotated_at ON web_refresh_token(rotated_at) WHERE rotated_at IS NOT NULL;+-- Default bytebase system account id is 1.INSERT INTO principal (id, type, name, email, password_hash) VALUES (1, 'SYSTEM_BOT', 'Bytebase', '[email protected]', '');diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex 0bc227b822..4dc4abacd0 100644--- a/backend/migrator/migrator_test.go+++ b/backend/migrator/migrator_test.go@@ -12,7 +12,7 @@ import (func TestLatestVersion(t *testing.T) {files, err := getSortedVersionedFiles()require.NoError(t, err)- require.Equal(t, semver.MustParse("3.14.10"), *files[len(files)-1].version)+ require.Equal(t, semver.MustParse("3.14.11"), *files[len(files)-1].version)}func TestVersionUnique(t *testing.T) {diff --git a/backend/runner/cleaner/data_cleaner.go b/backend/runner/cleaner/data_cleaner.goindex d193853d8a..070b814fb1 100644--- a/backend/runner/cleaner/data_cleaner.go+++ b/backend/runner/cleaner/data_cleaner.go@@ -15,6 +15,7 @@ const (cleanupInterval = 1 * time.HourexportArchiveRetentionPeriod = 24 * time.Houroauth2ClientRetentionPeriod = 30 * 24 * time.Hour // 30 days of inactivity+ refreshTokenGracePeriod = 30 * time.Second // Grace period for rotated refresh tokens)// DataCleaner periodically cleans up expired data from the database.@@ -52,6 +53,7 @@ func (c *DataCleaner) Run(ctx context.Context, wg *sync.WaitGroup) {func (c *DataCleaner) cleanup(ctx context.Context) {c.cleanupExportArchives(ctx)c.cleanupOAuth2Data(ctx)+ c.cleanupWebRefreshTokens(ctx)}func (c *DataCleaner) cleanupExportArchives(ctx context.Context) {@@ -88,3 +90,19 @@ func (c *DataCleaner) cleanupOAuth2Data(ctx context.Context) {slog.Info("Cleaned up inactive OAuth2 clients", slog.Int64("count", rowsAffected))}}++func (c *DataCleaner) cleanupWebRefreshTokens(ctx context.Context) {+ // Clean up expired web refresh tokens+ if rowsAffected, err := c.store.DeleteExpiredWebRefreshTokens(ctx); err != nil {+ slog.Error("Failed to clean up expired web refresh tokens", log.BBError(err))+ } else if rowsAffected > 0 {+ slog.Info("Cleaned up expired web refresh tokens", slog.Int64("count", rowsAffected))+ }++ // Clean up rotated tokens past grace period+ if rowsAffected, err := c.store.DeleteRotatedWebRefreshTokens(ctx, refreshTokenGracePeriod); err != nil {+ slog.Error("Failed to clean up rotated web refresh tokens", log.BBError(err))+ } else if rowsAffected > 0 {+ slog.Info("Cleaned up rotated web refresh tokens", slog.Int64("count", rowsAffected))+ }+}diff --git a/backend/store/web_refresh_token.go b/backend/store/web_refresh_token.gonew file mode 100644index 0000000000..2ba8027278--- /dev/null+++ b/backend/store/web_refresh_token.go@@ -0,0 +1,161 @@+package store++import (+ "context"+ "database/sql"+ "time"++ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/common/qb"+)++type WebRefreshTokenMessage struct {+ TokenHash string+ UserEmail string+ ExpiresAt time.Time+ RotatedAt *time.Time+}++func (s *Store) CreateWebRefreshToken(ctx context.Context, create *WebRefreshTokenMessage) error {+ q := qb.Q().Space(`+ INSERT INTO web_refresh_token (token_hash, user_email, expires_at)+ VALUES (?, ?, ?)+ `, create.TokenHash, create.UserEmail, create.ExpiresAt)++ query, args, err := q.ToSQL()+ if err != nil {+ return err+ }++ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {+ return errors.Wrap(err, "failed to create web refresh token")+ }+ return nil+}++func (s *Store) GetWebRefreshToken(ctx context.Context, tokenHash string) (*WebRefreshTokenMessage, error) {+ q := qb.Q().Space(`+ SELECT token_hash, user_email, expires_at, rotated_at+ FROM web_refresh_token+ WHERE token_hash = ?+ `, tokenHash)++ query, args, err := q.ToSQL()+ if err != nil {+ return nil, err+ }++ msg := &WebRefreshTokenMessage{}+ var rotatedAt sql.NullTime+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(+ &msg.TokenHash, &msg.UserEmail, &msg.ExpiresAt, &rotatedAt,+ ); err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ return nil, errors.Wrap(err, "failed to get web refresh token")+ }+ if rotatedAt.Valid {+ msg.RotatedAt = &rotatedAt.Time+ }+ return msg, nil+}++// MarkWebRefreshTokenRotated atomically marks a token as rotated.+// Returns true if the token was rotated (rotated_at was null), false if already rotated.+// This prevents race conditions when multiple requests try to rotate the same token.+func (s *Store) MarkWebRefreshTokenRotated(ctx context.Context, tokenHash string) (bool, error) {+ q := qb.Q().Space(`+ UPDATE web_refresh_token+ SET rotated_at = NOW()+ WHERE token_hash = ? AND rotated_at IS NULL+ `, tokenHash)++ query, args, err := q.ToSQL()+ if err != nil {+ return false, err+ }++ result, err := s.GetDB().ExecContext(ctx, query, args...)+ if err != nil {+ return false, errors.Wrap(err, "failed to mark web refresh token as rotated")+ }++ rowsAffected, err := result.RowsAffected()+ if err != nil {+ return false, errors.Wrap(err, "failed to get rows affected")+ }++ return rowsAffected > 0, nil+}++func (s *Store) DeleteWebRefreshToken(ctx context.Context, tokenHash string) error {+ q := qb.Q().Space(`+ DELETE FROM web_refresh_token+ WHERE token_hash = ?+ `, tokenHash)++ query, args, err := q.ToSQL()+ if err != nil {+ return err+ }++ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {+ return errors.Wrap(err, "failed to delete web refresh token")+ }+ return nil+}++func (s *Store) DeleteWebRefreshTokensByUser(ctx context.Context, userEmail string) error {+ q := qb.Q().Space(`+ DELETE FROM web_refresh_token+ WHERE user_email = ?+ `, userEmail)++ query, args, err := q.ToSQL()+ if err != nil {+ return err+ }++ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {+ return errors.Wrap(err, "failed to delete web refresh tokens for user")+ }+ return nil+}++func (s *Store) DeleteExpiredWebRefreshTokens(ctx context.Context) (int64, error) {+ q := qb.Q().Space(`+ DELETE FROM web_refresh_token+ WHERE expires_at < NOW()+ `)++ query, args, err := q.ToSQL()+ if err != nil {+ return 0, err+ }++ result, err := s.GetDB().ExecContext(ctx, query, args...)+ if err != nil {+ return 0, errors.Wrap(err, "failed to delete expired web refresh tokens")+ }+ return result.RowsAffected()+}++func (s *Store) DeleteRotatedWebRefreshTokens(ctx context.Context, gracePeriod time.Duration) (int64, error) {+ q := qb.Q().Space(`+ DELETE FROM web_refresh_token+ WHERE rotated_at IS NOT NULL AND rotated_at < ?+ `, time.Now().Add(-gracePeriod))++ query, args, err := q.ToSQL()+ if err != nil {+ return 0, err+ }++ result, err := s.GetDB().ExecContext(ctx, query, args...)+ if err != nil {+ return 0, errors.Wrap(err, "failed to delete rotated web refresh tokens")+ }+ return result.RowsAffected()+}diff --git a/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts b/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.tsindex 0afac43ed2..5ae38b9327 100644--- a/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts+++ b/frontend/src/grpcweb/middlewares/authInterceptorMiddleware.ts@@ -3,6 +3,7 @@ import { t } from "@/plugins/i18n";import { router } from "@/router";import { pushNotification, useAuthStore } from "@/store";import { ignoredCodesContextKey, silentContextKey } from "../context-key";+import { refreshTokens } from "../refreshToken";export type IgnoreErrorsOptions = {/**@@ -22,7 +23,6 @@ export const authInterceptor: Interceptor = (next) => async (req) => {return resp;} catch (error) {const authStore = useAuthStore();- // If silent is set to true, will NOT show redirect to other pages(e.g., 403, sign in page).const silent = req.contextValues.get(silentContextKey);const ignoredCodes = req.contextValues.get(ignoredCodesContextKey);@@ -32,20 +32,53 @@ export const authInterceptor: Interceptor = (next) => async (req) => {// omit specified errors} else {if (code === Code.Unauthenticated && req.method.name !== "Login") {- // Skip show login modal when the request is to get current user.- // When receiving 401 and is returned by our server, it means the current- // login user's token becomes invalid. Thus we force the user to login again.- authStore.unauthenticatedOccurred = true;- if (authStore.isLoggedIn) {- pushNotification({- module: "bytebase",- style: "WARN",- title: t("auth.token-expired-title"),- description: t("auth.token-expired-description"),- });+ // Don't retry refresh endpoint failures - just propagate error+ // The caller (refreshTokens catch block) will handle the notification+ if (req.method.name === "Refresh") {+ throw error;+ }++ // Try to refresh - catch ONLY refresh failures+ try {+ await refreshTokens();+ } catch {+ // Refresh itself failed - auth is broken+ authStore.unauthenticatedOccurred = true;+ if (authStore.isLoggedIn) {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: t("auth.token-expired-title"),+ description: t("auth.token-expired-description"),+ });+ }+ throw error;+ }++ // Refresh succeeded - retry the original request+ try {+ return await next(req);+ } catch (retryError) {+ // Retry failed - check if it's also an auth error+ if (+ retryError instanceof ConnectError &&+ retryError.code === Code.Unauthenticated+ ) {+ // New token also invalid (edge case) - auth is broken+ authStore.unauthenticatedOccurred = true;+ if (authStore.isLoggedIn) {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: t("auth.token-expired-title"),+ description: t("auth.token-expired-description"),+ });+ }+ }+ // Throw retry error (not original) - let other handlers deal with it+ throw retryError;}} else if (code === Code.PermissionDenied) {- // Jump to 403 pagerouter.push({ name: "error.403" });}}diff --git a/frontend/src/grpcweb/refreshToken.ts b/frontend/src/grpcweb/refreshToken.tsnew file mode 100644index 0000000000..d24e29bebd--- /dev/null+++ b/frontend/src/grpcweb/refreshToken.ts@@ -0,0 +1,23 @@+import { authServiceClientConnect } from "@/grpcweb";++let refreshPromise: Promise<void> | null = null;++/**+ * Refresh the access token using the refresh token cookie.+ * Uses singleton pattern to prevent concurrent refresh calls within the same tab.+ * Cross-tab races are handled by server-side grace period (30 seconds).+ */+export async function refreshTokens(): Promise<void> {+ if (refreshPromise) {+ return refreshPromise;+ }++ refreshPromise = authServiceClientConnect+ .refresh({})+ .then(() => {})+ .finally(() => {+ refreshPromise = null;+ });++ return refreshPromise;+}diff --git a/frontend/src/types/proto-es/v1/auth_service_pb.d.ts b/frontend/src/types/proto-es/v1/auth_service_pb.d.tsindex fb226964eb..dfce33d5d3 100644--- a/frontend/src/types/proto-es/v1/auth_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/auth_service_pb.d.ts@@ -251,6 +251,34 @@ export declare type ExchangeTokenResponse = Message<"bytebase.v1.ExchangeTokenRe*/export declare const ExchangeTokenResponseSchema: GenMessage<ExchangeTokenResponse>;+/**+ * Request to refresh the access token.+ *+ * @generated from message bytebase.v1.RefreshRequest+ */+export declare type RefreshRequest = Message<"bytebase.v1.RefreshRequest"> & {+};++/**+ * Describes the message bytebase.v1.RefreshRequest.+ * Use `create(RefreshRequestSchema)` to create a new message.+ */+export declare const RefreshRequestSchema: GenMessage<RefreshRequest>;++/**+ * Response from refreshing the access token.+ *+ * @generated from message bytebase.v1.RefreshResponse+ */+export declare type RefreshResponse = Message<"bytebase.v1.RefreshResponse"> & {+};++/**+ * Describes the message bytebase.v1.RefreshResponse.+ * Use `create(RefreshResponseSchema)` to create a new message.+ */+export declare const RefreshResponseSchema: GenMessage<RefreshResponse>;+/*** AuthService handles user authentication operations.*@@ -291,5 +319,16 @@ export declare const AuthService: GenService<{input: typeof ExchangeTokenRequestSchema;output: typeof ExchangeTokenResponseSchema;},+ /**+ * Refreshes the access token using the refresh token cookie.+ * Permissions required: None (validates via refresh token cookie)+ *+ * @generated from rpc bytebase.v1.AuthService.Refresh+ */+ refresh: {+ methodKind: "unary";+ input: typeof RefreshRequestSchema;+ output: typeof RefreshResponseSchema;+ },}>;diff --git a/frontend/src/types/proto-es/v1/auth_service_pb.js b/frontend/src/types/proto-es/v1/auth_service_pb.jsindex 99866a9057..5cc3a79b99 100644--- a/frontend/src/types/proto-es/v1/auth_service_pb.js+++ b/frontend/src/types/proto-es/v1/auth_service_pb.js@@ -12,7 +12,7 @@ import { file_v1_user_service } from "./user_service_pb";* Describes the file v1/auth_service.proto.*/export const file_v1_auth_service = /*@__PURE__*/- fileDesc("ChV2MS9hdXRoX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIosCCgxMb2dpblJlcXVlc3QSDQoFZW1haWwYASABKAkSEAoIcGFzc3dvcmQYAiABKAkSCwoDd2ViGAMgASgIEhAKCGlkcF9uYW1lGAQgASgJEjkKC2lkcF9jb250ZXh0GAUgASgLMiQuYnl0ZWJhc2UudjEuSWRlbnRpdHlQcm92aWRlckNvbnRleHQSFQoIb3RwX2NvZGUYBiABKAlIAIgBARIaCg1yZWNvdmVyeV9jb2RlGAcgASgJSAGIAQESGwoObWZhX3RlbXBfdG9rZW4YCCABKAlIAogBAUILCglfb3RwX2NvZGVCEAoOX3JlY292ZXJ5X2NvZGVCEQoPX21mYV90ZW1wX3Rva2VuIqwBChdJZGVudGl0eVByb3ZpZGVyQ29udGV4dBJECg5vYXV0aDJfY29udGV4dBgBIAEoCzIqLmJ5dGViYXNlLnYxLk9BdXRoMklkZW50aXR5UHJvdmlkZXJDb250ZXh0SAASQAoMb2lkY19jb250ZXh0GAIgASgLMiguYnl0ZWJhc2UudjEuT0lEQ0lkZW50aXR5UHJvdmlkZXJDb250ZXh0SABCCQoHY29udGV4dCItCh1PQXV0aDJJZGVudGl0eVByb3ZpZGVyQ29udGV4dBIMCgRjb2RlGAEgASgJIisKG09JRENJZGVudGl0eVByb3ZpZGVyQ29udGV4dBIMCgRjb2RlGAEgASgJIo8BCg1Mb2dpblJlc3BvbnNlEg0KBXRva2VuGAEgASgJEhsKDm1mYV90ZW1wX3Rva2VuGAIgASgJSACIAQESHgoWcmVxdWlyZV9yZXNldF9wYXNzd29yZBgDIAEoCBIfCgR1c2VyGAQgASgLMhEuYnl0ZWJhc2UudjEuVXNlckIRCg9fbWZhX3RlbXBfdG9rZW4iDwoNTG9nb3V0UmVxdWVzdCI0ChRFeGNoYW5nZVRva2VuUmVxdWVzdBINCgV0b2tlbhgBIAEoCRINCgVlbWFpbBgCIAEoCSItChVFeGNoYW5nZVRva2VuUmVzcG9uc2USFAoMYWNjZXNzX3Rva2VuGAEgASgJMtYCCgtBdXRoU2VydmljZRJhCgVMb2dpbhIZLmJ5dGViYXNlLnYxLkxvZ2luUmVxdWVzdBoaLmJ5dGViYXNlLnYxLkxvZ2luUmVzcG9uc2UiIYDqMAGY6jABgtPkkwITOgEqIg4vdjEvYXV0aC9sb2dpbhJgCgZMb2dvdXQSGi5ieXRlYmFzZS52MS5Mb2dvdXRSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IiKA6jABmOowAYLT5JMCFDoBKiIPL3YxL2F1dGgvbG9nb3V0EoEBCg1FeGNoYW5nZVRva2VuEiEuYnl0ZWJhc2UudjEuRXhjaGFuZ2VUb2tlblJlcXVlc3QaIi5ieXRlYmFzZS52MS5FeGNoYW5nZVRva2VuUmVzcG9uc2UiKYDqMAGY6jABgtPkkwIbOgEqIhYvdjEvYXV0aDpleGNoYW5nZVRva2VuQqYBCg9jb20uYnl0ZWJhc2UudjFCEEF1dGhTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_protobuf_empty, file_v1_annotation, file_v1_user_service]);+ fileDesc("ChV2MS9hdXRoX3NlcnZpY2UucHJvdG8SC2J5dGViYXNlLnYxIosCCgxMb2dpblJlcXVlc3QSDQoFZW1haWwYASABKAkSEAoIcGFzc3dvcmQYAiABKAkSCwoDd2ViGAMgASgIEhAKCGlkcF9uYW1lGAQgASgJEjkKC2lkcF9jb250ZXh0GAUgASgLMiQuYnl0ZWJhc2UudjEuSWRlbnRpdHlQcm92aWRlckNvbnRleHQSFQoIb3RwX2NvZGUYBiABKAlIAIgBARIaCg1yZWNvdmVyeV9jb2RlGAcgASgJSAGIAQESGwoObWZhX3RlbXBfdG9rZW4YCCABKAlIAogBAUILCglfb3RwX2NvZGVCEAoOX3JlY292ZXJ5X2NvZGVCEQoPX21mYV90ZW1wX3Rva2VuIqwBChdJZGVudGl0eVByb3ZpZGVyQ29udGV4dBJECg5vYXV0aDJfY29udGV4dBgBIAEoCzIqLmJ5dGViYXNlLnYxLk9BdXRoMklkZW50aXR5UHJvdmlkZXJDb250ZXh0SAASQAoMb2lkY19jb250ZXh0GAIgASgLMiguYnl0ZWJhc2UudjEuT0lEQ0lkZW50aXR5UHJvdmlkZXJDb250ZXh0SABCCQoHY29udGV4dCItCh1PQXV0aDJJZGVudGl0eVByb3ZpZGVyQ29udGV4dBIMCgRjb2RlGAEgASgJIisKG09JRENJZGVudGl0eVByb3ZpZGVyQ29udGV4dBIMCgRjb2RlGAEgASgJIo8BCg1Mb2dpblJlc3BvbnNlEg0KBXRva2VuGAEgASgJEhsKDm1mYV90ZW1wX3Rva2VuGAIgASgJSACIAQESHgoWcmVxdWlyZV9yZXNldF9wYXNzd29yZBgDIAEoCBIfCgR1c2VyGAQgASgLMhEuYnl0ZWJhc2UudjEuVXNlckIRCg9fbWZhX3RlbXBfdG9rZW4iDwoNTG9nb3V0UmVxdWVzdCI0ChRFeGNoYW5nZVRva2VuUmVxdWVzdBINCgV0b2tlbhgBIAEoCRINCgVlbWFpbBgCIAEoCSItChVFeGNoYW5nZVRva2VuUmVzcG9uc2USFAoMYWNjZXNzX3Rva2VuGAEgASgJIhAKDlJlZnJlc2hSZXF1ZXN0IhEKD1JlZnJlc2hSZXNwb25zZTK9AwoLQXV0aFNlcnZpY2USYQoFTG9naW4SGS5ieXRlYmFzZS52MS5Mb2dpblJlcXVlc3QaGi5ieXRlYmFzZS52MS5Mb2dpblJlc3BvbnNlIiGA6jABmOowAYLT5JMCEzoBKiIOL3YxL2F1dGgvbG9naW4SYAoGTG9nb3V0EhouYnl0ZWJhc2UudjEuTG9nb3V0UmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSIigOowAZjqMAGC0+STAhQ6ASoiDy92MS9hdXRoL2xvZ291dBKBAQoNRXhjaGFuZ2VUb2tlbhIhLmJ5dGViYXNlLnYxLkV4Y2hhbmdlVG9rZW5SZXF1ZXN0GiIuYnl0ZWJhc2UudjEuRXhjaGFuZ2VUb2tlblJlc3BvbnNlIimA6jABmOowAYLT5JMCGzoBKiIWL3YxL2F1dGg6ZXhjaGFuZ2VUb2tlbhJlCgdSZWZyZXNoEhsuYnl0ZWJhc2UudjEuUmVmcmVzaFJlcXVlc3QaHC5ieXRlYmFzZS52MS5SZWZyZXNoUmVzcG9uc2UiH4DqMAGC0+STAhU6ASoiEC92MS9hdXRoL3JlZnJlc2hCpgEKD2NvbS5ieXRlYmFzZS52MUIQQXV0aFNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_protobuf_empty, file_v1_annotation, file_v1_user_service]);/*** Describes the message bytebase.v1.LoginRequest.@@ -70,6 +70,20 @@ export const ExchangeTokenRequestSchema = /*@__PURE__*/export const ExchangeTokenResponseSchema = /*@__PURE__*/messageDesc(file_v1_auth_service, 7);+/**+ * Describes the message bytebase.v1.RefreshRequest.+ * Use `create(RefreshRequestSchema)` to create a new message.+ */+export const RefreshRequestSchema = /*@__PURE__*/+ messageDesc(file_v1_auth_service, 8);++/**+ * Describes the message bytebase.v1.RefreshResponse.+ * Use `create(RefreshResponseSchema)` to create a new message.+ */+export const RefreshResponseSchema = /*@__PURE__*/+ messageDesc(file_v1_auth_service, 9);+/*** AuthService handles user authentication operations.*diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex dc5a901f23..301859188b 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -229,6 +229,33 @@ paths:application/json:schema:$ref: '#/components/schemas/Status'+ /v1/auth/refresh:+ post:+ tags:+ - AuthService+ description: |-+ Refreshes the access token using the refresh token cookie.+ Permissions required: None (validates via refresh token cookie)+ operationId: AuthService_Refresh+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RefreshRequest'+ required: true+ responses:+ "200":+ description: OK+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RefreshResponse'+ default:+ description: Default error response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/Status'/v1/auth:exchangeToken:post:tags:@@ -12510,6 +12537,14 @@ components:substitution:type: stringdescription: substitution is the string used to replace the OriginalValue[start:end).+ RefreshRequest:+ type: object+ properties: {}+ description: Request to refresh the access token.+ RefreshResponse:+ type: object+ properties: {}+ description: Response from refreshing the access token.RejectIssueRequest:required:- namediff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 1918a9bcff..6340bf270d 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -170,6 +170,8 @@- [LogoutRequest](#bytebase-v1-LogoutRequest)- [OAuth2IdentityProviderContext](#bytebase-v1-OAuth2IdentityProviderContext)- [OIDCIdentityProviderContext](#bytebase-v1-OIDCIdentityProviderContext)+ - [RefreshRequest](#bytebase-v1-RefreshRequest)+ - [RefreshResponse](#bytebase-v1-RefreshResponse)- [AuthService](#bytebase-v1-AuthService)@@ -3107,6 +3109,26 @@ OpenID Connect authentication context.++<a name="bytebase-v1-RefreshRequest"></a>++### RefreshRequest+Request to refresh the access token.+++++++<a name="bytebase-v1-RefreshResponse"></a>++### RefreshResponse+Response from refreshing the access token.+++++@@ -3124,6 +3146,7 @@ AuthService handles user authentication operations.| Login | [LoginRequest](#bytebase-v1-LoginRequest) | [LoginResponse](#bytebase-v1-LoginResponse) | Authenticates a user and returns access tokens. Permissions required: None || Logout | [LogoutRequest](#bytebase-v1-LogoutRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Logs out the current user session. Permissions required: None || ExchangeToken | [ExchangeTokenRequest](#bytebase-v1-ExchangeTokenRequest) | [ExchangeTokenResponse](#bytebase-v1-ExchangeTokenResponse) | Exchanges an external OIDC token for a Bytebase access token. Used by CI/CD pipelines with Workload Identity Federation. Permissions required: None (validates via OIDC token) |+| Refresh | [RefreshRequest](#bytebase-v1-RefreshRequest) | [RefreshResponse](#bytebase-v1-RefreshResponse) | Refreshes the access token using the refresh token cookie. Permissions required: None (validates via refresh token cookie) |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex c02f868b07..b3205d5175 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -818,6 +818,14 @@<a href="#bytebase.v1.OIDCIdentityProviderContext"><span class="badge">M</span>OIDCIdentityProviderContext</a></li>+ <li>+ <a href="#bytebase.v1.RefreshRequest"><span class="badge">M</span>RefreshRequest</a>+ </li>++ <li>+ <a href="#bytebase.v1.RefreshResponse"><span class="badge">M</span>RefreshResponse</a>+ </li>+@@ -9033,6 +9041,20 @@ Format: idps/{idp} </p></td>+ <h3 id="bytebase.v1.RefreshRequest">RefreshRequest</h3>+ <p>Request to refresh the access token.</p>++++++ <h3 id="bytebase.v1.RefreshResponse">RefreshResponse</h3>+ <p>Response from refreshing the access token.</p>+++++@@ -9072,6 +9094,14 @@ Used by CI/CD pipelines with Workload Identity Federation.Permissions required: None (validates via OIDC token)</p></td></tr>+ <tr>+ <td>Refresh</td>+ <td><a href="#bytebase.v1.RefreshRequest">RefreshRequest</a></td>+ <td><a href="#bytebase.v1.RefreshResponse">RefreshResponse</a></td>+ <td><p>Refreshes the access token using the refresh token cookie.+Permissions required: None (validates via refresh token cookie)</p></td>+ </tr>+</tbody></table>@@ -9120,6 +9150,16 @@ Permissions required: None (validates via OIDC token)</p></td></tr>+++ <tr>+ <td>Refresh</td>+ <td>POST</td>+ <td>/v1/auth/refresh</td>+ <td>*</td>+ </tr>++</tbody></table>diff --git a/proto/v1/v1/auth_service.proto b/proto/v1/v1/auth_service.protoindex fe18871e3c..3cf904ac38 100644--- a/proto/v1/v1/auth_service.proto+++ b/proto/v1/v1/auth_service.proto@@ -44,6 +44,16 @@ service AuthService {option (bytebase.v1.allow_without_credential) = true;option (bytebase.v1.audit) = true;}++ // Refreshes the access token using the refresh token cookie.+ // Permissions required: None (validates via refresh token cookie)+ rpc Refresh(RefreshRequest) returns (RefreshResponse) {+ option (google.api.http) = {+ post: "/v1/auth/refresh"+ body: "*"+ };+ option (bytebase.v1.allow_without_credential) = true;+ }}message LoginRequest {@@ -125,3 +135,9 @@ message ExchangeTokenResponse {// Bytebase access token.string access_token = 1;}++// Request to refresh the access token.+message RefreshRequest {}++// Response from refreshing the access token.+message RefreshResponse {}