Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: strengthen multi-workspace isolation across ACL, store, auth, and LSP (#19682)
ecmadao25ba02f5dc17
diff --git a/backend/api/lsp/completion.go b/backend/api/lsp/completion.goindex 65b3e04733..1a5098106e 100644--- a/backend/api/lsp/completion.go+++ b/backend/api/lsp/completion.go@@ -145,7 +145,7 @@ func convertLSPCompletionItemKind(tp parserbase.CandidateType) lsp.CompletionIte}func (h *Handler) GetDatabaseMetadataFunc(ctx context.Context, instanceID, databaseName string) (string, *model.DatabaseMetadata, error) {- metadata, err := h.store.GetDBSchemaSnapshot(ctx, h.workspaceID, instanceID, databaseName)+ metadata, err := h.store.GetDBSchemaSnapshot(ctx, common.GetWorkspaceIDFromContext(ctx), instanceID, databaseName)if err != nil {return "", nil, errors.Wrap(err, "failed to get database schema")}@@ -161,6 +161,7 @@ func (h *Handler) ListDatabaseNamesFunc(ctx context.Context, instanceID string)}databases, err := h.store.ListDatabases(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,})if err != nil {diff --git a/backend/api/lsp/handler.go b/backend/api/lsp/handler.goindex f0505fdea8..95a361e827 100644--- a/backend/api/lsp/handler.go+++ b/backend/api/lsp/handler.go@@ -49,12 +49,10 @@ const ()// NewHandlerWithAuth creates a new Language Server Protocol handler with authentication.-func NewHandlerWithAuth(s *store.Store, profile *config.Profile, iamManager *iam.Manager, user *store.UserMessage, workspaceID string, tokenExpiry time.Time) jsonrpc2.Handler {+func NewHandlerWithAuth(s *store.Store, profile *config.Profile, iamManager *iam.Manager, _ *store.UserMessage, _ string, tokenExpiry time.Time) jsonrpc2.Handler {handler := &Handler{store: s,profile: profile,- user: user,- workspaceID: workspaceID,tokenExpiry: tokenExpiry,iamManager: iamManager,diagnosticsDebouncer: NewDiagnosticsDebouncer(500 * time.Millisecond), // 500ms debounce@@ -84,8 +82,6 @@ type Handler struct {store *store.Store// Auth-related fields- user *store.UserMessage- workspaceID stringtokenExpiry time.TimeiamManager *iam.Manager@@ -168,7 +164,7 @@ func (h *Handler) getEngineType(ctx context.Context) storepb.Engine {}instance, err := h.store.GetInstance(ctx, &store.FindInstanceMessage{- Workspace: h.workspaceID,+ Workspace: common.GetWorkspaceIDFromContext(ctx),ResourceID: &instanceID,})if err != nil {@@ -208,10 +204,13 @@ func (h *Handler) checkTokenExpiry() error {}func (h *Handler) checkMetadataPermissions(ctx context.Context, metadata SetMetadataCommandArguments) error {- if h.user == nil {+ user, ok := ctx.Value(common.UserContextKey).(*store.UserMessage)+ if !ok || user == nil {return errors.New("user not authenticated")}+ workspaceID := common.GetWorkspaceIDFromContext(ctx)+// If database is specified, check database schema permissionif metadata.DatabaseName != "" && metadata.InstanceID != "" {// Need to get database to find its project@@ -221,6 +220,7 @@ func (h *Handler) checkMetadataPermissions(ctx context.Context, metadata SetMeta}database, err := h.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: workspaceID,InstanceID: &instanceID,DatabaseName: &metadata.DatabaseName,})@@ -232,7 +232,7 @@ func (h *Handler) checkMetadataPermissions(ctx context.Context, metadata SetMeta}// Check bb.databases.getSchema permission- ok, err := h.iamManager.CheckPermission(ctx, permission.DatabasesGetSchema, h.user, h.workspaceID, database.ProjectID)+ ok, err := h.iamManager.CheckPermission(ctx, permission.DatabasesGetSchema, user, workspaceID, database.ProjectID)if err != nil {return errors.Wrap(err, "failed to check permission")}@@ -241,7 +241,7 @@ func (h *Handler) checkMetadataPermissions(ctx context.Context, metadata SetMeta}} else if metadata.InstanceID != "" && metadata.DatabaseName == "" {// If only instance is specified, check instance get permission- ok, err := h.iamManager.CheckPermission(ctx, permission.InstancesGet, h.user, h.workspaceID)+ ok, err := h.iamManager.CheckPermission(ctx, permission.InstancesGet, user, workspaceID)if err != nil {return errors.Wrap(err, "failed to check permission")}diff --git a/backend/api/lsp/lsp.go b/backend/api/lsp/lsp.goindex 5a7840c887..790ae1c22c 100644--- a/backend/api/lsp/lsp.go+++ b/backend/api/lsp/lsp.go@@ -1,6 +1,7 @@package lspimport (+ "context""io""log/slog""net/http"@@ -15,6 +16,7 @@ import (wsjsonrpc2 "github.com/sourcegraph/jsonrpc2/websocket""github.com/bytebase/bytebase/backend/api/auth"+ "github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/common/stacktrace""github.com/bytebase/bytebase/backend/component/config"@@ -52,6 +54,8 @@ func (s *Server) Router(c *echo.Context) error {handler, closer := newHandler(s.store, s.profile, s.iamManager, user, workspaceID, tokenExpiry)ctx := c.Request().Context()+ ctx = context.WithValue(ctx, common.UserContextKey, user)+ ctx = context.WithValue(ctx, common.WorkspaceIDContextKey, workspaceID)<-jsonrpc2.NewConn(ctx, wsjsonrpc2.NewObjectStream(connection), handler, nil /* connOpt */).DisconnectNotify()err = closer.Close()if err != nil {diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 964ca6dced..5bb6ba1679 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -7343,10 +7343,6 @@ components:type: stringtitle: external_urldescription: The external URL where users or webhook callbacks access Bytebase.- needAdminSetup:- type: boolean- title: need_admin_setup- description: Whether the Bytebase instance requires initial admin setup.lastActiveTime:title: last_active_timedescription: The last time any API call was made, refreshed on each request.diff --git a/backend/api/v1/access_grant_service.go b/backend/api/v1/access_grant_service.goindex 6fa00bc983..d06c634441 100644--- a/backend/api/v1/access_grant_service.go+++ b/backend/api/v1/access_grant_service.go@@ -49,6 +49,7 @@ func (s *AccessGrantService) GetAccessGrant(ctx context.Context, request *connec}grant, err := s.store.GetAccessGrant(ctx, &store.FindAccessGrantMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ID: &accessGrantID,ProjectID: &projectID,})@@ -81,6 +82,7 @@ func (s *AccessGrantService) ListAccessGrants(ctx context.Context, request *connlimitPlusOne := offset.limit + 1find := &store.FindAccessGrantMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: &projectID,Limit: &limitPlusOne,Offset: &offset.offset,@@ -250,7 +252,8 @@ func (s *AccessGrantService) CreateAccessGrant(ctx context.Context, request *conif issue.Status == storepb.Issue_DONE {// Refresh the grant if issue is completed.grant, err = s.store.GetAccessGrant(ctx, &store.FindAccessGrantMessage{- ID: &grant.ID,+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ ID: &grant.ID,})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get access grant %v", grant.ID))@@ -282,6 +285,7 @@ func activateAccessGrant(ctx context.Context, stores *store.Store, accessGrantNa}grant, err := stores.GetAccessGrant(ctx, &store.FindAccessGrantMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ID: &accessGrantID,ProjectID: &projectID,})@@ -323,6 +327,7 @@ func (s *AccessGrantService) RevokeAccessGrant(ctx context.Context, request *con}grant, err := s.store.GetAccessGrant(ctx, &store.FindAccessGrantMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ID: &accessGrantID,ProjectID: &projectID,})@@ -371,6 +376,7 @@ func (s *AccessGrantService) SearchMyAccessGrants(ctx context.Context, request *limitPlusOne := offset.limit + 1find := &store.FindAccessGrantMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: &projectID,Creator: &user.Email,Limit: &limitPlusOne,diff --git a/backend/api/v1/acl.go b/backend/api/v1/acl.goindex 3f0d0bb966..0fc9d840d0 100644--- a/backend/api/v1/acl.go+++ b/backend/api/v1/acl.go@@ -127,9 +127,11 @@ func (in *ACLInterceptor) doACLCheck(ctx context.Context, request any, fullMethoif !ok {return connect.NewError(connect.CodeInternal, errors.New("auth context not found"))}- if err := populateRawResources(ctx, in.store, authContext, request, fullMethod); err != nil {+ resources, err := populateRawResources(ctx, in.store, request, fullMethod)+ if err != nil {return connect.NewError(connect.CodeInternal, errors.Errorf("failed to populate raw resources %s", err))}+ authContext.Resources = resourcesif auth.IsAuthenticationSkipped(fullMethod, authContext) {return nil@@ -144,6 +146,34 @@ func (in *ACLInterceptor) doACLCheck(ctx context.Context, request any, fullMethoreturn connect.NewError(connect.CodeUnauthenticated, errors.Errorf("unauthenticated for method %q", fullMethod))}+ workspaceID := common.GetWorkspaceIDFromContext(ctx)+ if workspaceID == "" {+ return connect.NewError(connect.CodeUnauthenticated, errors.Errorf("empty workspace id"))+ }++ // Workspace isolation: verify all resources belong to the caller's workspace.+ // Instance and database ownership is already validated in populateRawResources+ // (via workspace-filtered store lookups). Here we validate workspace and project resources.+ // Runs after authentication so unauthenticated requests get 401 first,+ // preventing resource existence probing.+ for _, resource := range authContext.Resources {+ switch resource.Type {+ case common.ResourceTypeWorkspace:+ if resource.ID != workspaceID {+ return connect.NewError(connect.CodePermissionDenied, errors.Errorf("workspace mismatch"))+ }+ case common.ResourceTypeProject:+ project, err := in.store.GetProject(ctx, &store.FindProjectMessage{Workspace: workspaceID, ResourceID: &resource.ID})+ if err != nil {+ return connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get project"))+ }+ if project == nil || project.Workspace != workspaceID {+ return connect.NewError(connect.CodeNotFound, errors.Errorf("project %q not found", resource.ID))+ }+ default:+ }+ }+ok, extra, err := doIAMPermissionCheck(ctx, in.iamManager, fullMethod, user, authContext)if err != nil {return connect.NewError(connect.CodeInternal, errors.Errorf("failed to check permission for method %q, extra %v, err: %v", fullMethod, extra, err))@@ -224,9 +254,6 @@ func doIAMPermissionCheck(ctx context.Context, iamManager *iam.Manager, fullMethfor _, resource := range authContext.Resources {switch resource.Type {case common.ResourceTypeWorkspace:- if workspaceID != resource.ID {- return false, nil, errors.Errorf("request workspace %v does not match the workspace %v in token", resource.ID, workspaceID)- }hasWorkspaceResource = truecase common.ResourceTypeProject:projectIDMap[resource.ID] = true@@ -267,11 +294,23 @@ func doIAMPermissionCheck(ctx context.Context, iamManager *iam.Manager, fullMethvar projectRegex = regexp.MustCompile(`^projects/[^/]+`)var databaseRegex = regexp.MustCompile(`^instances/[^/]+/databases/[^/]+`)--func populateRawResources(ctx context.Context, stores *store.Store, authContext *common.AuthContext, request any, method string) error {+var instanceRegex = regexp.MustCompile(`^instances/[^/]+`)++// populateRawResources extracts resources from the request and validates workspace ownership.+//+// Resource resolution strategy:+// - workspaces/{id} → ResourceTypeWorkspace (direct match)+// - projects/{id} → ResourceTypeProject (direct match)+// - instances/{id}/databases/{name} → looks up database with workspace filter, returns ResourceTypeProject (parent project)+// - instances/{id}[/...] → looks up instance with workspace filter, returns ResourceTypeWorkspace (instance permissions are workspace-scoped)+// - default → ResourceTypeWorkspace from context (fallback for unmatched patterns)+//+// All instance/database lookups use the workspace ID from the request context,+// ensuring the resource belongs to the caller's workspace before any permission check.+func populateRawResources(ctx context.Context, stores *store.Store, request any, method string) ([]*common.Resource, error) {rawNames, err := getResourceFromRequest(ctx, request, method)if err != nil {- return err+ return nil, err}var resources []*common.Resource@@ -280,7 +319,7 @@ func populateRawResources(ctx context.Context, stores *store.Store, authContextcase strings.HasPrefix(name, "workspaces/"):wsID, err := common.GetWorkspaceID(name)if err != nil {- return err+ return nil, err}resources = append(resources, &common.Resource{Type: common.ResourceTypeWorkspace,@@ -290,39 +329,68 @@ func populateRawResources(ctx context.Context, stores *store.Store, authContextcase strings.HasPrefix(name, "projects/") && name != "projects/-":project := projectRegex.FindString(name)if project == "" {- return errors.Errorf("invalid project resource %q", name)+ return nil, errors.Errorf("invalid project resource %q", name)}projectID, err := common.GetProjectID(project)if err != nil {- return err+ return nil, err}resources = append(resources, &common.Resource{Type: common.ResourceTypeProject,ID: projectID,})+ // Database resources: look up the database (with workspace filter) and resolve+ // to its parent project for project-level permission checks.case strings.HasPrefix(name, "instances/") && strings.Contains(name, "/databases/") && !strings.HasPrefix(name, "instances/-/databases/"):match := databaseRegex.FindString(name)if match != "" {instanceID, databaseName, err := common.GetInstanceDatabaseID(match)if err != nil {- return errors.Wrapf(err, "failed to parse %q", match)+ return nil, errors.Wrapf(err, "failed to parse %q", match)}database, err := stores.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,})if err != nil {- return errors.Wrapf(err, "failed to get database")+ return nil, errors.Wrapf(err, "failed to get database")}if database == nil {- return errors.Errorf("database %q not found", match)+ return nil, errors.Errorf("database %q not found", match)}resources = append(resources, &common.Resource{Type: common.ResourceTypeProject,ID: database.ProjectID,})}+ // Instance resources (e.g. instances/{id}, instances/{id}/roles/{role}):+ // validate the instance belongs to the caller's workspace. Returns workspace+ // resource since instance permissions are workspace-scoped.+ case strings.HasPrefix(name, "instances/") && !strings.Contains(name, "/databases/"):+ match := instanceRegex.FindString(name)+ if match != "" {+ instanceID, err := common.GetInstanceID(match)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to parse %q", match)+ }+ workspaceID := common.GetWorkspaceIDFromContext(ctx)+ instance, err := stores.GetInstance(ctx, &store.FindInstanceMessage{+ Workspace: workspaceID,+ ResourceID: &instanceID,+ })+ if err != nil {+ return nil, errors.Wrapf(err, "failed to get instance")+ }+ if instance == nil {+ return nil, errors.Errorf("instance %q not found", match)+ }+ resources = append(resources, &common.Resource{+ Type: common.ResourceTypeWorkspace,+ ID: workspaceID,+ })+ }default:if workspaceID := common.GetWorkspaceIDFromContext(ctx); workspaceID != "" {resources = append(resources, &common.Resource{@@ -332,8 +400,7 @@ func populateRawResources(ctx context.Context, stores *store.Store, authContext}}}- authContext.Resources = resources- return nil+ return resources, nil}func getResourceFromRequest(ctx context.Context, request any, method string) ([]string, error) {diff --git a/backend/api/v1/actuator_service.go b/backend/api/v1/actuator_service.goindex 5809c1b259..a635d70ff5 100644--- a/backend/api/v1/actuator_service.go+++ b/backend/api/v1/actuator_service.go@@ -153,6 +153,14 @@ func (s *ActuatorService) SetupSample(return connect.NewResponse(&emptypb.Empty{}), nil}+var defaultAccountRestriction = &v1pb.Restriction{+ DisallowSignup: false,+ DisallowPasswordSignin: false,+ PasswordRestriction: &v1pb.WorkspaceProfileSetting_PasswordRestriction{+ MinLength: 8,+ },+}+func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string) (*v1pb.ActuatorInfo, error) {serverInfo := v1pb.ActuatorInfo{Version: s.profile.Version,@@ -163,12 +171,7 @@ func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string)Docker: s.profile.IsDocker,ExternalUrlFromFlag: s.profile.ExternalURL != "",ReplicaCount: int32(s.licenseService.CountActiveReplicas(ctx)),- Restriction: &v1pb.Restriction{- PasswordRestriction: &v1pb.WorkspaceProfileSetting_PasswordRestriction{- MinLength: 8,- },- },- NeedAdminSetup: true,+ Restriction: defaultAccountRestriction,}if workspaceID != "" {@@ -195,7 +198,6 @@ func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string)if err != nil {return nil, connect.NewError(connect.CodeInternal, err)}- serverInfo.NeedAdminSetup = activeEndUserCount <= 1serverInfo.ActivatedUserCount = int32(activeEndUserCount)setting, err := s.store.GetWorkspaceProfileSetting(ctx, workspaceID)@@ -203,7 +205,7 @@ func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string)return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find workspace setting"))}serverInfo.Restriction = &v1pb.Restriction{- PasswordRestriction: convertPasswordRestriction(setting.GetPasswordRestriction()),+ PasswordRestriction: convertToV1PasswordRestriction(setting.GetPasswordRestriction()),DisallowSignup: setting.DisallowSignup,DisallowPasswordSignin: setting.DisallowPasswordSignin,}@@ -304,8 +306,8 @@ func (s *ActuatorService) getUnlicensedFeatures(ctx context.Context, workspaceIDreturn unlicensedFeatures}-// convertPasswordRestriction converts store PasswordRestriction to v1 PasswordRestriction.-func convertPasswordRestriction(pr *storepb.WorkspaceProfileSetting_PasswordRestriction) *v1pb.WorkspaceProfileSetting_PasswordRestriction {+// convertToV1PasswordRestriction converts store PasswordRestriction to v1 PasswordRestriction.+func convertToV1PasswordRestriction(pr *storepb.WorkspaceProfileSetting_PasswordRestriction) *v1pb.WorkspaceProfileSetting_PasswordRestriction {if pr == nil {return nil}diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.goindex f87b492178..725cfbc997 100644--- a/backend/api/v1/auth_service.go+++ b/backend/api/v1/auth_service.go@@ -232,9 +232,8 @@ func (s *AuthService) Signup(ctx context.Context, req *connect.Request[v1pb.Signif err := validatePassword(ctx, s.store, workspaceID, request.Password); err != nil {return nil, err}- } else if len(request.Password) < 8 {- // TODO(ed): optimize this- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("password length should be no less than 8 characters"))+ } else if err := validatePasswordWithRestriction(request.Password, convertToStorePasswordRestriction(defaultAccountRestriction.PasswordRestriction)); err != nil {+ return nil, err}passwordHash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)@@ -309,10 +308,12 @@ func (s *AuthService) Signup(ctx context.Context, req *connect.Request[v1pb.SignrefreshCookie := auth.GetRefreshTokenCookie(origin, refreshToken, refreshTokenDuration)resp.Header().Add("Set-Cookie", refreshCookie.String())- // Update last login time.+ // Update last login time and workspace.if _, err := s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{Profile: &storepb.UserProfile{- LastLoginTime: timestamppb.Now(),+ LastLoginTime: timestamppb.Now(),+ Source: user.Profile.GetSource(),+ LastLoginWorkspace: workspaceID,},}); err != nil {slog.Error("failed to update user profile", log.BBError(err), slog.String("user", user.Email))@@ -379,10 +380,10 @@ func (s *AuthService) Refresh(ctx context.Context, req *connect.Request[v1pb.Refreturn nil, connect.NewError(connect.CodeUnauthenticated, errors.New("user not found"))}- // 5. Issue new tokens- workspaceID, err := s.store.FindWorkspaceIDByMemberEmail(ctx, common.FormatUserEmail(user.Email), !s.profile.SaaS)+ // 5. Issue new tokens — preserve the workspace from the original login session.+ workspaceID, err := s.resolveWorkspaceForRefresh(ctx, user)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get workspace"))+ return nil, connect.NewError(connect.CodeUnauthenticated, errors.Wrap(err, "failed to resolve workspace"))}accessTokenDuration := auth.GetAccessTokenDuration(ctx, s.store, s.licenseService, workspaceID)accessToken, err := auth.GenerateAccessToken(user.Email, workspaceID, s.secret, accessTokenDuration)@@ -919,10 +920,8 @@ func (s *AuthService) generateLoginToken(ctx context.Context, user *store.UserMe// resolveWorkspaceForLogin determines the workspace for a login token.// For SA/WI: looks up the account record to get workspace.-// For END_USER: finds workspaces via IAM policy membership.-// - If the user belongs to exactly 1 workspace, use it.-// - If multiple, use the first one (TODO: workspace picker in SaaS mode).-// - If none, return error.+// For END_USER: prefers the last login workspace (from user profile) if still valid,+// otherwise falls back to the first workspace from IAM membership.func (s *AuthService) resolveWorkspaceForLogin(ctx context.Context, user *store.UserMessage) (string, error) {// Determine member name format based on user type.var memberName string@@ -943,8 +942,54 @@ func (s *AuthService) resolveWorkspaceForLogin(ctx context.Context, user *store.return "", errors.Errorf("unsupported user type %s for login", user.Type)}- // find workspaces by IAM policy membership.- return s.store.FindWorkspaceIDByMemberEmail(ctx, memberName, !s.profile.SaaS)+ includeAllUser := !s.profile.SaaS++ // Prefer the last login workspace if it's still valid.+ if lastWS := user.Profile.GetLastLoginWorkspace(); lastWS != "" {+ workspaces, err := s.store.FindWorkspacesByMemberEmail(ctx, memberName, includeAllUser)+ if err != nil {+ return "", errors.Wrap(err, "failed to find workspaces for user")+ }+ for _, ws := range workspaces {+ if ws.ResourceID == lastWS {+ return lastWS, nil+ }+ }+ // Last login workspace no longer valid (removed from membership or deleted).+ // Fall through to default selection.+ if len(workspaces) > 0 {+ return workspaces[0].ResourceID, nil+ }+ return "", errors.Errorf("%q is not a member of any workspace", memberName)+ }++ // No last login workspace — use the first one.+ return s.store.FindWorkspaceIDByMemberEmail(ctx, memberName, includeAllUser)+}++// resolveWorkspaceForRefresh returns the workspace for a token refresh.+// It must return the same workspace as the original login session.+// If the user is no longer a member of that workspace, the refresh fails.+func (s *AuthService) resolveWorkspaceForRefresh(ctx context.Context, user *store.UserMessage) (string, error) {+ workspaceID := user.Profile.GetLastLoginWorkspace()+ if workspaceID == "" {+ // Fallback for users who logged in before last_login_workspace was implemented.+ return s.resolveWorkspaceForLogin(ctx, user)+ }++ // Verify the user is still a member of the workspace.+ includeAllUser := !s.profile.SaaS+ memberName := common.FormatUserEmail(user.Email)+ workspaces, err := s.store.FindWorkspacesByMemberEmail(ctx, memberName, includeAllUser)+ if err != nil {+ return "", errors.Wrap(err, "failed to find workspaces for user")+ }+ for _, ws := range workspaces {+ if ws.ResourceID == workspaceID {+ return workspaceID, nil+ }+ }+ return "", errors.Errorf("user %q is no longer a member of workspace %q", user.Email, workspaceID)}// finalizeLogin builds the response, sets cookies if needed, and updates the user profile.@@ -987,6 +1032,8 @@ func (s *AuthService) finalizeLogin(ctx context.Context, req *connect.Request[v1Profile: &storepb.UserProfile{LastLoginTime: timestamppb.Now(),LastChangePasswordTime: user.Profile.GetLastChangePasswordTime(),+ Source: user.Profile.GetSource(),+ LastLoginWorkspace: workspaceID,},}); err != nil {slog.Error("failed to update user profile", log.BBError(err), slog.String("user", user.Email))diff --git a/backend/api/v1/database_catalog_service.go b/backend/api/v1/database_catalog_service.goindex c8cdfe8717..3d136437a3 100644--- a/backend/api/v1/database_catalog_service.go+++ b/backend/api/v1/database_catalog_service.go@@ -40,6 +40,7 @@ func (s *DatabaseCatalogService) GetDatabaseCatalog(ctx context.Context, req *coreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", databaseResourceName))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,@@ -79,6 +80,7 @@ func (s *DatabaseCatalogService) UpdateDatabaseCatalog(ctx context.Context, reqreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", databaseResourceName))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})diff --git a/backend/api/v1/database_group_service.go b/backend/api/v1/database_group_service.goindex 72581cc19a..6fff6e8203 100644--- a/backend/api/v1/database_group_service.go+++ b/backend/api/v1/database_group_service.go@@ -228,7 +228,7 @@ func (s *DatabaseGroupService) ListDatabaseGroups(ctx context.Context, req *connvar allProjectDatabases []*store.DatabaseMessageif req.Msg.View == v1pb.DatabaseGroupView_DATABASE_GROUP_VIEW_FULL {- allProjectDatabases, err = s.store.ListDatabases(ctx, &store.FindDatabaseMessage{ProjectID: &projectResourceID})+ allProjectDatabases, err = s.store.ListDatabases(ctx, &store.FindDatabaseMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: &projectResourceID})if err != nil {return nil, connect.NewError(connect.CodeInternal, err)}@@ -288,7 +288,7 @@ func getDatabaseGroupByName(ctx context.Context, stores *store.Store, databaseGrfunc convertStoreToV1DatabaseGroupWithView(ctx context.Context, stores *store.Store, databaseGroup *store.DatabaseGroupMessage, projectResourceID string, view v1pb.DatabaseGroupView) (*v1pb.DatabaseGroup, error) {var allProjectDatabases []*store.DatabaseMessageif view == v1pb.DatabaseGroupView_DATABASE_GROUP_VIEW_FULL {- databases, err := stores.ListDatabases(ctx, &store.FindDatabaseMessage{ProjectID: &projectResourceID})+ databases, err := stores.ListDatabases(ctx, &store.FindDatabaseMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: &projectResourceID})if err != nil {return nil, connect.NewError(connect.CodeInternal, err)}diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.goindex 6e0b428126..712b696958 100644--- a/backend/api/v1/database_service.go+++ b/backend/api/v1/database_service.go@@ -53,6 +53,7 @@ func (s *DatabaseService) GetDatabase(ctx context.Context, req *connect.Request[return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", req.Msg.Name))}databaseMessage, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,@@ -93,6 +94,7 @@ func (s *DatabaseService) BatchGetDatabases(ctx context.Context, req *connect.Rereturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", name))}databaseMessage, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,@@ -185,6 +187,7 @@ func (s *DatabaseService) ListDatabases(ctx context.Context, req *connect.RequeslimitPlusOne := offset.limit + 1find := &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),Limit: &limitPlusOne,Offset: &offset.offset,ShowDeleted: req.Msg.ShowDeleted,@@ -283,6 +286,7 @@ func (s *DatabaseService) UpdateDatabase(ctx context.Context, req *connect.Requereturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", req.Msg.Database.Name))}databaseMessage, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})@@ -394,6 +398,7 @@ func (s *DatabaseService) SyncDatabase(ctx context.Context, req *connect.Requestreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", req.Msg.Name))}databaseMessage, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})@@ -420,6 +425,7 @@ func (s *DatabaseService) BatchSyncDatabases(ctx context.Context, req *connect.Rreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", name))}databaseMessage, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})@@ -539,6 +545,7 @@ func (s *DatabaseService) GetDatabaseMetadata(ctx context.Context, req *connect.return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", name))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,@@ -592,6 +599,7 @@ func (s *DatabaseService) GetDatabaseSchema(ctx context.Context, req *connect.Rereturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("%v", err.Error()))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,@@ -639,6 +647,7 @@ func (s *DatabaseService) GetDatabaseSDLSchema(ctx context.Context, req *connect}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,@@ -1020,6 +1029,7 @@ func (s *DatabaseService) GetSchemaString(ctx context.Context, req *connect.Requreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", req.Msg.Name))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,diff --git a/backend/api/v1/database_service_changelog.go b/backend/api/v1/database_service_changelog.goindex 327c47991a..9eec6c0304 100644--- a/backend/api/v1/database_service_changelog.go+++ b/backend/api/v1/database_service_changelog.go@@ -94,6 +94,7 @@ func (s *DatabaseService) ListChangelogs(ctx context.Context, req *connect.Requereturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", req.Msg.Parent))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,@@ -172,6 +173,7 @@ func (s *DatabaseService) GetChangelog(ctx context.Context, req *connect.Request}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.goindex 32f6cb0495..f6bfaf0ad9 100644--- a/backend/api/v1/instance_service.go+++ b/backend/api/v1/instance_service.go@@ -454,7 +454,7 @@ func (s *InstanceService) DeleteInstance(ctx context.Context, req *connect.Requereturn connect.NewResponse(&emptypb.Empty{}), nil}- databases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID})+ databases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), InstanceID: &instance.ResourceID})if err != nil {return nil, err}@@ -464,7 +464,7 @@ func (s *InstanceService) DeleteInstance(ctx context.Context, req *connect.Requeif err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get default project ID"))}- if err := s.store.BatchUpdateDatabases(ctx, databases, &store.BatchUpdateDatabases{ProjectID: &defaultProjectID}); err != nil {+ if err := s.store.BatchUpdateDatabases(ctx, databases, &store.BatchUpdateDatabases{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: &defaultProjectID}); err != nil {return nil, connect.NewError(connect.CodeInternal, err)}}diff --git a/backend/api/v1/issue_hook.go b/backend/api/v1/issue_hook.goindex 82b5744395..b994542cf9 100644--- a/backend/api/v1/issue_hook.go+++ b/backend/api/v1/issue_hook.go@@ -59,7 +59,7 @@ func postCreateIssue(// Refresh issue to get updated approval payload.uid := issue.UIDvar err error- issue, err = stores.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{issue.ProjectID}, UID: &uid})+ issue, err = stores.GetIssue(ctx, &store.FindIssueMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectIDs: []string{issue.ProjectID}, UID: &uid})if err != nil {return nil, errors.Wrapf(err, "failed to refresh issue")}diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.goindex 5fe487d077..5b5f045060 100644--- a/backend/api/v1/issue_service.go+++ b/backend/api/v1/issue_service.go@@ -82,8 +82,9 @@ func (s *IssueService) getIssueFind(offset *int,) (*store.FindIssueMessage, *filterIssueMessage, error) {issueFind := &store.FindIssueMessage{- Limit: limit,- Offset: offset,+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ Limit: limit,+ Offset: offset,}if query != "" {issueFind.Query = &query@@ -495,7 +496,7 @@ func (s *IssueService) buildIssueMessage(ctx context.Context, project *store.Proreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("%v", err.Error()))}- plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{UID: &planID, ProjectID: project.ResourceID})+ plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), UID: &planID, ProjectID: project.ResourceID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get plan"))}@@ -1058,6 +1059,7 @@ func (s *IssueService) ListIssueComments(ctx context.Context, req *connect.Requereturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("%v", err.Error()))}issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),UID: &issueUID,ProjectIDs: []string{projectID},})@@ -1213,6 +1215,7 @@ func (s *IssueService) getIssueMessage(ctx context.Context, name string) (*storereturn nil, connect.NewError(connect.CodeInvalidArgument, err)}issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),UID: &issueUID,ProjectIDs: []string{projectID},})diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.goindex ab7f493d1b..b074d90da0 100644--- a/backend/api/v1/plan_service.go+++ b/backend/api/v1/plan_service.go@@ -55,6 +55,7 @@ func (s *PlanService) GetPlan(ctx context.Context, request *connect.Request[v1pbreturn nil, connect.NewError(connect.CodeInvalidArgument, err)}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),UID: &planID,ProjectID: projectID,})@@ -90,6 +91,7 @@ func (s *PlanService) ListPlans(ctx context.Context, request *connect.Request[v1limitPlusOne := offset.limit + 1find := &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),Limit: &limitPlusOne,Offset: &offset.offset,ProjectID: projectID,@@ -238,7 +240,7 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[vif project == nil {return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("project %q not found", projectID))}- oldPlan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{ProjectID: projectID, UID: &planID})+ oldPlan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, UID: &planID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get plan %q: %v", req.Plan.Name, err))}@@ -324,7 +326,7 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[vplanCheckRunsTrigger = true// Evict approvals if issue exists to request re-approval.- issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{projectID}, PlanUID: &oldPlan.UID})+ issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectIDs: []string{projectID}, PlanUID: &oldPlan.UID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get issue: %v", err))}@@ -423,6 +425,7 @@ func (s *PlanService) RunPlanChecks(ctx context.Context, request *connect.Requesreturn nil, connect.NewError(connect.CodeNotFound, errors.Errorf("project not found for id: %v", projectID))}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),UID: &planID,ProjectID: projectID,})@@ -670,6 +673,7 @@ func validateSpecs(ctx context.Context, s *store.Store, projectID string, specsreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid database name %q", name))}db, err := s.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &dbName,})@@ -770,7 +774,7 @@ func convertToPlans(ctx context.Context, s *store.Store, plans []*store.PlanMessplanUIDs[i] = int64(p.UID)}- issues, err := s.ListIssues(ctx, &store.FindIssueMessage{ProjectIDs: []string{plans[0].ProjectID}, PlanUIDs: &planUIDs})+ issues, err := s.ListIssues(ctx, &store.FindIssueMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectIDs: []string{plans[0].ProjectID}, PlanUIDs: &planUIDs})if err != nil {return nil, errors.Wrap(err, "failed to batch list issues")}@@ -799,7 +803,7 @@ func convertToPlans(ctx context.Context, s *store.Store, plans []*store.PlanMess}func convertToPlan(ctx context.Context, s *store.Store, plan *store.PlanMessage) (*v1pb.Plan, error) {- issue, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{plan.ProjectID}, PlanUID: &plan.UID})+ issue, err := s.GetIssue(ctx, &store.FindIssueMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectIDs: []string{plan.ProjectID}, PlanUID: &plan.UID})if err != nil {return nil, errors.Wrapf(err, "failed to get issue by plan uid %d", plan.UID)}diff --git a/backend/api/v1/query_result_masker.go b/backend/api/v1/query_result_masker.goindex 00705a296d..255f2b2fb0 100644--- a/backend/api/v1/query_result_masker.go+++ b/backend/api/v1/query_result_masker.go@@ -237,6 +237,7 @@ func newMaskingDataProviderFromDBNames(ctx context.Context, s *store.Store, inst}databases, err := s.ListDatabases(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instance.ResourceID,DatabaseNames: dbNames,})diff --git a/backend/api/v1/release_service_check.go b/backend/api/v1/release_service_check.goindex b6a7f0e112..9b08f17ff0 100644--- a/backend/api/v1/release_service_check.go+++ b/backend/api/v1/release_service_check.go@@ -55,6 +55,7 @@ func (s *ReleaseService) CheckRelease(ctx context.Context, req *connect.Request[// Handle database target.if instanceID, databaseName, err := common.GetInstanceDatabaseID(target); err == nil {database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})@@ -93,6 +94,7 @@ func (s *ReleaseService) CheckRelease(ctx context.Context, req *connect.Request[return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("database group %q not found", databaseGroupResourceID))}groupDatabases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: &projectResourceID,})if err != nil {diff --git a/backend/api/v1/revision_service.go b/backend/api/v1/revision_service.goindex 2b46b2eaad..e3ecd562b7 100644--- a/backend/api/v1/revision_service.go+++ b/backend/api/v1/revision_service.go@@ -42,6 +42,7 @@ func (s *RevisionService) ListRevisions(return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", request.Parent))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,@@ -102,6 +103,7 @@ func (s *RevisionService) GetRevision(return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to get revision ID from %v", request.Name))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,ShowDeleted: true,@@ -132,6 +134,7 @@ func (s *RevisionService) BatchCreateRevisions(return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", request.Parent))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})@@ -199,7 +202,11 @@ func (s *RevisionService) createRevisions(if err != nil {return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("failed to get taskRun from %q", revision.TaskRun))}- taskRun, err := s.store.GetTaskRunByUID(ctx, projectID, taskRunID)+ taskRun, err := s.store.GetTaskRunV1(ctx, &store.FindTaskRunMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ ProjectID: projectID,+ UID: &taskRunID,+ })if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get taskRun"))}diff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.goindex 014630ffa5..808f0f6ebc 100644--- a/backend/api/v1/rollout_service.go+++ b/backend/api/v1/rollout_service.go@@ -72,6 +72,7 @@ func (s *RolloutService) GetRollout(ctx context.Context, req *connect.Request[v1// getRolloutWithTasks inlinedplan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -86,7 +87,7 @@ func (s *RolloutService) GetRollout(ctx context.Context, req *connect.Request[v1return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("rollout %d not found in project %s", planID, projectID))}- tasks, err := s.store.ListTasks(ctx, &store.TaskFind{ProjectID: projectID, PlanID: &planID})+ tasks, err := s.store.ListTasks(ctx, &store.TaskFind{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, PlanID: &planID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get tasks"))}@@ -139,6 +140,7 @@ func (s *RolloutService) ListRollouts(ctx context.Context, req *connect.Request[// Filter plans to only those with rollouts (tasks).hasRollout := truefindPlan := &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,Limit: &limitPlusOne,Offset: &offset.offset,@@ -168,7 +170,7 @@ func (s *RolloutService) ListRollouts(ctx context.Context, req *connect.Request[var allTasks []*store.TaskMessageif len(planIDs) > 0 {var err error- allTasks, err = s.store.ListTasks(ctx, &store.TaskFind{ProjectID: projectID, PlanIDs: &planIDs})+ allTasks, err = s.store.ListTasks(ctx, &store.TaskFind{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, PlanIDs: &planIDs})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to list tasks"))}@@ -240,7 +242,7 @@ func (s *RolloutService) CreateRollout(ctx context.Context, req *connect.Requestreturn nil, connect.NewError(connect.CodeNotFound, errors.Errorf("project not found for id: %v", projectID))}- plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{ProjectID: projectID, UID: &planID})+ plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, UID: &planID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get plan"))}@@ -255,6 +257,7 @@ func (s *RolloutService) CreateRollout(ctx context.Context, req *connect.Request// Fetch issue associated with this plan (if any)issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectIDs: []string{projectID},PlanUID: &planID,})@@ -290,7 +293,7 @@ func (s *RolloutService) CreateRollout(ctx context.Context, req *connect.Requestreturn nil, connect.NewError(connect.CodeInternal, err)}- tasks, err = s.store.ListTasks(ctx, &store.TaskFind{ProjectID: projectID, PlanID: &planID})+ tasks, err = s.store.ListTasks(ctx, &store.TaskFind{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, PlanID: &planID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get tasks"))}@@ -336,6 +339,7 @@ func (s *RolloutService) ListTaskRuns(ctx context.Context, req *connect.Request[}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -346,6 +350,7 @@ func (s *RolloutService) ListTaskRuns(ctx context.Context, req *connect.Request[return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("rollout %d not found in project %s", planID, projectID))}taskRuns, err := s.store.ListTaskRuns(ctx, &store.FindTaskRunMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,PlanUID: &planID,Environment: maybeStageID,@@ -482,6 +487,7 @@ func (s *RolloutService) GetTaskRun(ctx context.Context, req *connect.Request[v1}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -493,6 +499,7 @@ func (s *RolloutService) GetTaskRun(ctx context.Context, req *connect.Request[v1}taskRun, err := s.store.GetTaskRunV1(ctx, &store.FindTaskRunMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &taskRunUID,PlanUID: &planID,@@ -519,6 +526,7 @@ func (s *RolloutService) GetTaskRunLog(ctx context.Context, req *connect.Request}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -530,6 +538,7 @@ func (s *RolloutService) GetTaskRunLog(ctx context.Context, req *connect.Request}taskRun, err := s.store.GetTaskRunV1(ctx, &store.FindTaskRunMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &taskRunUID,PlanUID: &planID,@@ -556,6 +565,7 @@ func (s *RolloutService) GetTaskRunSession(ctx context.Context, req *connect.Req}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -566,7 +576,7 @@ func (s *RolloutService) GetTaskRunSession(ctx context.Context, req *connect.Reqreturn nil, connect.NewError(connect.CodeNotFound, errors.Errorf("plan %d not found in project %s", planID, projectID))}- tasks, err := s.store.ListTasks(ctx, &store.TaskFind{ProjectID: projectID, ID: &taskUID, PlanID: &planID})+ tasks, err := s.store.ListTasks(ctx, &store.TaskFind{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, ID: &taskUID, PlanID: &planID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get task"))}@@ -720,6 +730,7 @@ func (s *RolloutService) BatchRunTasks(ctx context.Context, req *connect.Request}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -737,6 +748,7 @@ func (s *RolloutService) BatchRunTasks(ctx context.Context, req *connect.Request}issueN, err := s.store.GetIssue(ctx, &store.FindIssueMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectIDs: []string{projectID},PlanUID: &planID,})@@ -768,7 +780,7 @@ func (s *RolloutService) BatchRunTasks(ctx context.Context, req *connect.Request}// Get all tasks in the same environment- stageToRunTasks, err := s.store.ListTasks(ctx, &store.TaskFind{ProjectID: projectID, PlanID: &planID, Environment: &environmentToRun})+ stageToRunTasks, err := s.store.ListTasks(ctx, &store.TaskFind{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, PlanID: &planID, Environment: &environmentToRun})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to list tasks"))}@@ -861,6 +873,7 @@ func (s *RolloutService) BatchSkipTasks(ctx context.Context, req *connect.Reques}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -872,6 +885,7 @@ func (s *RolloutService) BatchSkipTasks(ctx context.Context, req *connect.Reques}issueN, err := s.store.GetIssue(ctx, &store.FindIssueMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectIDs: []string{projectID},PlanUID: &planID,})@@ -879,7 +893,7 @@ func (s *RolloutService) BatchSkipTasks(ctx context.Context, req *connect.Requesreturn nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find issue"))}- tasks, err := s.store.ListTasks(ctx, &store.TaskFind{ProjectID: projectID, PlanID: &planID})+ tasks, err := s.store.ListTasks(ctx, &store.TaskFind{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, PlanID: &planID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to list tasks"))}@@ -952,6 +966,7 @@ func (s *RolloutService) BatchCancelTaskRuns(ctx context.Context, req *connect.R}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -963,6 +978,7 @@ func (s *RolloutService) BatchCancelTaskRuns(ctx context.Context, req *connect.R}issueN, err := s.store.GetIssue(ctx, &store.FindIssueMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectIDs: []string{projectID},PlanUID: &planID,})@@ -1004,6 +1020,7 @@ func (s *RolloutService) BatchCancelTaskRuns(ctx context.Context, req *connect.R}taskRuns, err := s.store.ListTaskRuns(ctx, &store.FindTaskRunMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UIDs: &taskRunIDs,})@@ -1050,6 +1067,7 @@ func (s *RolloutService) PreviewTaskRunRollback(ctx context.Context, req *connec}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -1061,6 +1079,7 @@ func (s *RolloutService) PreviewTaskRunRollback(ctx context.Context, req *connec}taskRuns, err := s.store.ListTaskRuns(ctx, &store.FindTaskRunMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &taskRunUID,PlanUID: &planID,@@ -1105,7 +1124,7 @@ func (s *RolloutService) PreviewTaskRunRollback(ctx context.Context, req *connecreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("task run %v has no backup detail in logs", taskRun.ID))}- tasks, err := s.store.ListTasks(ctx, &store.TaskFind{ProjectID: projectID, ID: &taskUID, PlanID: &planID})+ tasks, err := s.store.ListTasks(ctx, &store.TaskFind{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, ID: &taskUID, PlanID: &planID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get task"))}diff --git a/backend/api/v1/rollout_service_task.go b/backend/api/v1/rollout_service_task.goindex 50a59faee7..6e0e4eed6a 100644--- a/backend/api/v1/rollout_service_task.go+++ b/backend/api/v1/rollout_service_task.go@@ -38,7 +38,7 @@ func applyDatabaseGroupSpecTransformations(ctx context.Context, s *store.Store,return nil, errors.Errorf("database group %q not found", config.Targets[0])}- allDatabases, err := s.ListDatabases(ctx, &store.FindDatabaseMessage{ProjectID: &projectID})+ allDatabases, err := s.ListDatabases(ctx, &store.FindDatabaseMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: &projectID})if err != nil {return nil, errors.Wrapf(err, "failed to list databases for project %q", projectID)}@@ -261,6 +261,7 @@ func getDatabaseMessagesByTargets(ctx context.Context, s *store.Store, targets [return nil, errors.Wrapf(err, "failed to parse %q", matched.Name)}database, err := s.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})@@ -278,6 +279,7 @@ func getDatabaseMessagesByTargets(ctx context.Context, s *store.Store, targets [return nil, errors.Wrapf(err, "failed to parse %q", target)}database, err := s.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.goindex 26918af81c..4b38f4d423 100644--- a/backend/api/v1/setting_service.go+++ b/backend/api/v1/setting_service.go@@ -553,6 +553,7 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Reqreturn nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to unset environment %v for instances", env.Id))}if err := s.store.BatchUpdateDatabases(ctx, nil, &store.BatchUpdateDatabases{+ Workspace: common.GetWorkspaceIDFromContext(ctx),EnvironmentID: &emptyStr,FindByEnvironmentID: &env.Id,}); err != nil {diff --git a/backend/api/v1/setting_service_converter.go b/backend/api/v1/setting_service_converter.goindex a33ed20b17..41bb385c34 100644--- a/backend/api/v1/setting_service_converter.go+++ b/backend/api/v1/setting_service_converter.go@@ -250,7 +250,7 @@ func convertWorkspaceProfileSetting(v1Setting *v1pb.WorkspaceProfileSetting) *stWatermark: v1Setting.Watermark,DirectorySyncToken: v1Setting.DirectorySyncToken,BrandingLogo: v1Setting.BrandingLogo,- PasswordRestriction: convertPasswordRestrictionSetting(v1Setting.PasswordRestriction),+ PasswordRestriction: convertToStorePasswordRestriction(v1Setting.PasswordRestriction),EnableDebug: v1Setting.EnableDebug,SqlResultSize: v1Setting.SqlResultSize,QueryTimeout: v1Setting.QueryTimeout,@@ -716,7 +716,7 @@ func convertToAlgorithmRangeMaskSlices(storeSlices []*storepb.Algorithm_RangeMasreturn v1Slices}-func convertPasswordRestrictionSetting(v1Setting *v1pb.WorkspaceProfileSetting_PasswordRestriction) *storepb.WorkspaceProfileSetting_PasswordRestriction {+func convertToStorePasswordRestriction(v1Setting *v1pb.WorkspaceProfileSetting_PasswordRestriction) *storepb.WorkspaceProfileSetting_PasswordRestriction {if v1Setting == nil {return nil}diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex d159fabcf5..fe15e153dd 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -204,6 +204,7 @@ func (s *SQLService) preCheckAccess(ctx context.Context, request *v1pb.QueryRequ}grants, err := s.store.ListAccessGrants(ctx, &store.FindAccessGrantMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: &database.ProjectID,Creator: &user.Email,FilterQ: filterQ,@@ -626,7 +627,7 @@ func queryRetry(// Sync database metadata.for accessDatabaseName := range syncDatabaseMap {slog.Debug("sync database metadata", slog.String("instance", instance.ResourceID), slog.String("database", accessDatabaseName))- d, err := stores.GetDatabase(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID, DatabaseName: &accessDatabaseName})+ d, err := stores.GetDatabase(ctx, &store.FindDatabaseMessage{Workspace: common.GetWorkspaceIDFromContext(ctx), InstanceID: &instance.ResourceID, DatabaseName: &accessDatabaseName})if err != nil {return nil, nil, duration, err}@@ -893,6 +894,7 @@ func (s *SQLService) doExportFromIssue(ctx context.Context, requestName string)}plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,UID: &planID,})@@ -903,7 +905,7 @@ func (s *SQLService) doExportFromIssue(ctx context.Context, requestName string)return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("rollout %d not found in project %s", planID, projectID))}- tasks, err := s.store.ListTasks(ctx, &store.TaskFind{ProjectID: projectID, PlanID: &plan.UID})+ tasks, err := s.store.ListTasks(ctx, &store.TaskFind{Workspace: common.GetWorkspaceIDFromContext(ctx), ProjectID: projectID, PlanID: &plan.UID})if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get tasks: %v", err))}@@ -930,6 +932,7 @@ func (s *SQLService) doExportFromIssue(ctx context.Context, requestName string)}taskRuns, err := s.store.ListTaskRuns(ctx, &store.FindTaskRunMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),ProjectID: projectID,TaskUID: &task.ID,Status: &targetTaskRunStatus,@@ -1328,6 +1331,7 @@ func BuildGetLinkedDatabaseMetadataFunc(storeInstance *store.Store, engine storereturn func(ctx context.Context, instanceID string, linkedDatabaseName string, schemaName string) (string, string, *model.DatabaseMetadata, error) {// Find the linked database metadata.databases, err := storeInstance.ListDatabases(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,})if err != nil {@@ -1357,6 +1361,7 @@ func BuildGetLinkedDatabaseMetadataFunc(storeInstance *store.Store, engine storedatabaseName = schemaName}databaseList, err := storeInstance.ListDatabases(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),DatabaseName: &databaseName,Engine: &engine,})@@ -1419,6 +1424,7 @@ func BuildGetDatabaseMetadataFunc(storeInstance *store.Store) parserbase.GetDatafunc BuildListDatabaseNamesFunc(storeInstance *store.Store) parserbase.ListDatabaseNamesFunc {return func(ctx context.Context, instanceID string) ([]string, error) {databases, err := storeInstance.ListDatabases(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,})if err != nil {@@ -1616,6 +1622,7 @@ func (s *SQLService) prepareRelatedMessage(ctx context.Context, requestName strireturn nil, nil, nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to parse %q", requestName))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})diff --git a/backend/api/v1/subscription_service.go b/backend/api/v1/subscription_service.goindex b044fd9215..17263ebba2 100644--- a/backend/api/v1/subscription_service.go+++ b/backend/api/v1/subscription_service.go@@ -40,6 +40,7 @@ func (s *SubscriptionService) GetSubscription(ctx context.Context, _ *connect.Re// UpdateSubscription updates the subscription license.func (s *SubscriptionService) UpdateSubscription(ctx context.Context, req *connect.Request[v1pb.UpdateSubscriptionRequest]) (*connect.Response[v1pb.Subscription], error) {if s.profile.SaaS {+ // TODO(ed): allowed in SaaS v2return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("cannot update license in the SaaS mode"))}if err := s.licenseService.StoreLicense(ctx, common.GetWorkspaceIDFromContext(ctx), req.Msg.License); err != nil {diff --git a/backend/api/v1/user_service.go b/backend/api/v1/user_service.goindex 309d3a4982..ef1c736ac7 100644--- a/backend/api/v1/user_service.go+++ b/backend/api/v1/user_service.go@@ -271,6 +271,10 @@ func validatePassword(ctx context.Context, store *store.Store, workspace, passwo}passwordRestriction := setting.GetPasswordRestriction()+ return validatePasswordWithRestriction(password, passwordRestriction)+}++func validatePasswordWithRestriction(password string, passwordRestriction *storepb.WorkspaceProfileSetting_PasswordRestriction) error {if len(password) < int(passwordRestriction.GetMinLength()) {return connect.NewError(connect.CodeInvalidArgument, errors.Errorf("password length should no less than %v characters", passwordRestriction.GetMinLength()))}diff --git a/backend/api/v1/worksheet_service.go b/backend/api/v1/worksheet_service.goindex 50da2ba5f7..27c4cbde5f 100644--- a/backend/api/v1/worksheet_service.go+++ b/backend/api/v1/worksheet_service.go@@ -72,6 +72,7 @@ func (s *WorksheetService) CreateWorksheet(return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", request.Worksheet.Database))}db, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})@@ -237,6 +238,7 @@ func (s *WorksheetService) UpdateWorksheet(return nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrapf(err, "failed to parse %q", request.Worksheet.Database))}database, err := s.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: common.GetWorkspaceIDFromContext(ctx),InstanceID: &instanceID,DatabaseName: &databaseName,})diff --git a/backend/component/export/resources.go b/backend/component/export/resources.goindex 64aa1ac956..9c8f5c88d5 100644--- a/backend/component/export/resources.go+++ b/backend/component/export/resources.go@@ -87,6 +87,7 @@ func getResourcesForMySQL(}database, err := storeInstance.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: instance.Workspace,InstanceID: &instance.ResourceID,DatabaseName: &databaseName,})@@ -120,6 +121,7 @@ func getResourcesForMySQL(}if sourceColumn.Database != dbMetadata.GetProto().Name {resourceDB, err := storeInstance.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: instance.Workspace,InstanceID: &instance.ResourceID,DatabaseName: &sourceColumn.Database,})@@ -179,6 +181,7 @@ func getResourcesForPostgres(}database, err := storeInstance.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: instance.Workspace,InstanceID: &instance.ResourceID,DatabaseName: &databaseName,})@@ -250,6 +253,7 @@ func getResourcesForRedshift(}database, err := storeInstance.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: instance.Workspace,InstanceID: &instance.ResourceID,DatabaseName: &databaseName,})diff --git a/backend/component/sampleinstance/manager.go b/backend/component/sampleinstance/manager.goindex 36c3257a7b..56336c7fde 100644--- a/backend/component/sampleinstance/manager.go+++ b/backend/component/sampleinstance/manager.go@@ -283,6 +283,7 @@ func (m *Manager) generateInstance(}testDatabase, err := m.store.GetDatabase(ctx, &store.FindDatabaseMessage{+ Workspace: instance.Workspace,InstanceID: &instance.ResourceID,DatabaseName: &dbName,})diff --git a/backend/generated-go/store/user.pb.go b/backend/generated-go/store/user.pb.goindex 1157847d60..3985db82f4 100644--- a/backend/generated-go/store/user.pb.go+++ b/backend/generated-go/store/user.pb.go@@ -215,9 +215,12 @@ type UserProfile struct {LastLoginTime *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=last_login_time,json=lastLoginTime,proto3" json:"last_login_time,omitempty"`LastChangePasswordTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=last_change_password_time,json=lastChangePasswordTime,proto3" json:"last_change_password_time,omitempty"`// The source indicates where the user comes from. For now we support Entra ID SCIM sync, so the source could be Entra ID.- Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"`+ // The workspace resource ID the user last logged into.+ // Used to auto-select workspace on next login instead of requiring a workspace picker.+ LastLoginWorkspace string `protobuf:"bytes,5,opt,name=last_login_workspace,json=lastLoginWorkspace,proto3" json:"last_login_workspace,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *UserProfile) Reset() {@@ -271,6 +274,13 @@ func (x *UserProfile) GetSource() string {return ""}+func (x *UserProfile) GetLastLoginWorkspace() string {+ if x != nil {+ return x.LastLoginWorkspace+ }+ return ""+}+// WorkloadIdentityConfig stores OIDC configuration for workload identity.type WorkloadIdentityConfig struct {state protoimpl.MessageState `protogen:"open.v1"`@@ -355,11 +365,12 @@ const file_store_user_proto_rawDesc = "" +"\x0ftemp_otp_secret\x18\x02 \x01(\tR\rtempOtpSecret\x12%\n" +"\x0erecovery_codes\x18\x03 \x03(\tR\rrecoveryCodes\x12.\n" +"\x13temp_recovery_codes\x18\x04 \x03(\tR\x11tempRecoveryCodes\x12Z\n" +- "\x1ctemp_otp_secret_created_time\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\x18tempOtpSecretCreatedTime\"\xc6\x01\n" ++ "\x1ctemp_otp_secret_created_time\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\x18tempOtpSecretCreatedTime\"\xf8\x01\n" +"\vUserProfile\x12B\n" +"\x0flast_login_time\x18\x01 \x01(\v2\x1a.google.protobuf.TimestampR\rlastLoginTime\x12U\n" +"\x19last_change_password_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x16lastChangePasswordTime\x12\x16\n" +- "\x06source\x18\x03 \x01(\tR\x06sourceJ\x04\b\x04\x10\x05\"\xae\x02\n" ++ "\x06source\x18\x03 \x01(\tR\x06source\x120\n" ++ "\x14last_login_workspace\x18\x05 \x01(\tR\x12lastLoginWorkspaceJ\x04\b\x04\x10\x05\"\xae\x02\n" +"\x16WorkloadIdentityConfig\x12X\n" +"\rprovider_type\x18\x01 \x01(\x0e23.bytebase.store.WorkloadIdentityConfig.ProviderTypeR\fproviderType\x12\x1d\n" +"\n" +diff --git a/backend/generated-go/store/user_equal.pb.go b/backend/generated-go/store/user_equal.pb.goindex 0d01003953..c82b75310a 100644--- a/backend/generated-go/store/user_equal.pb.go+++ b/backend/generated-go/store/user_equal.pb.go@@ -54,6 +54,9 @@ func (x *UserProfile) Equal(y *UserProfile) bool {if x.Source != y.Source {return false}+ if x.LastLoginWorkspace != y.LastLoginWorkspace {+ return false+ }return true}diff --git a/backend/generated-go/v1/actuator_service.pb.go b/backend/generated-go/v1/actuator_service.pb.goindex 8492551aaa..7f0859b2cc 100644--- a/backend/generated-go/v1/actuator_service.pb.go+++ b/backend/generated-go/v1/actuator_service.pb.go@@ -357,8 +357,6 @@ type ActuatorInfo struct {Port string `protobuf:"bytes,7,opt,name=port,proto3" json:"port,omitempty"`// The external URL where users or webhook callbacks access Bytebase.ExternalUrl string `protobuf:"bytes,8,opt,name=external_url,json=externalUrl,proto3" json:"external_url,omitempty"`- // Whether the Bytebase instance requires initial admin setup.- NeedAdminSetup bool `protobuf:"varint,9,opt,name=need_admin_setup,json=needAdminSetup,proto3" json:"need_admin_setup,omitempty"`// The last time any API call was made, refreshed on each request.LastActiveTime *timestamppb.Timestamp `protobuf:"bytes,11,opt,name=last_active_time,json=lastActiveTime,proto3" json:"last_active_time,omitempty"`// The unique identifier for the workspace.@@ -474,13 +472,6 @@ func (x *ActuatorInfo) GetExternalUrl() string {return ""}-func (x *ActuatorInfo) GetNeedAdminSetup() bool {- if x != nil {- return x.NeedAdminSetup- }- return false-}-func (x *ActuatorInfo) GetLastActiveTime() *timestamppb.Timestamp {if x != nil {return x.LastActiveTime@@ -583,7 +574,7 @@ const file_v1_actuator_service_proto_rawDesc = "" +"\vRestriction\x12,\n" +"\x0fdisallow_signup\x18\x01 \x01(\bB\x03\xe0A\x03R\x0edisallowSignup\x12=\n" +"\x18disallow_password_signin\x18\x02 \x01(\bB\x03\xe0A\x03R\x16disallowPasswordSignin\x12p\n" +- "\x14password_restriction\x18\x03 \x01(\v28.bytebase.v1.WorkspaceProfileSetting.PasswordRestrictionB\x03\xe0A\x03R\x13passwordRestriction\"\xb6\a\n" ++ "\x14password_restriction\x18\x03 \x01(\v28.bytebase.v1.WorkspaceProfileSetting.PasswordRestrictionB\x03\xe0A\x03R\x13passwordRestriction\"\x8d\a\n" +"\fActuatorInfo\x12\x1d\n" +"\aversion\x18\x01 \x01(\tB\x03\xe0A\x03R\aversion\x12\"\n" +"\n" +@@ -593,8 +584,7 @@ const file_v1_actuator_service_proto_rawDesc = "" +"\x04demo\x18\x05 \x01(\bB\x03\xe0A\x03R\x04demo\x12\x17\n" +"\x04host\x18\x06 \x01(\tB\x03\xe0A\x03R\x04host\x12\x17\n" +"\x04port\x18\a \x01(\tB\x03\xe0A\x03R\x04port\x12&\n" +- "\fexternal_url\x18\b \x01(\tB\x03\xe0A\x03R\vexternalUrl\x12-\n" +- "\x10need_admin_setup\x18\t \x01(\bB\x03\xe0A\x03R\x0eneedAdminSetup\x12I\n" ++ "\fexternal_url\x18\b \x01(\tB\x03\xe0A\x03R\vexternalUrl\x12I\n" +"\x10last_active_time\x18\v \x01(\v2\x1a.google.protobuf.TimestampB\x03\xe0A\x03R\x0elastActiveTime\x12!\n" +"\tworkspace\x18\r \x01(\tB\x03\xe0A\x03R\tworkspace\x124\n" +"\x13unlicensed_features\x18\x0f \x03(\tB\x03\xe0A\x03R\x12unlicensedFeatures\x12\x1b\n" +@@ -606,7 +596,8 @@ const file_v1_actuator_service_proto_rawDesc = "" +"\x16external_url_from_flag\x18\x17 \x01(\bB\x03\xe0A\x03R\x13externalUrlFromFlag\x12(\n" +"\rreplica_count\x18\x18 \x01(\x05B\x03\xe0A\x03R\freplicaCount\x12?\n" +"\vrestriction\x18\x19 \x01(\v2\x18.bytebase.v1.RestrictionB\x03\xe0A\x03R\vrestriction\x12,\n" +- "\x0fdefault_project\x18\x1a \x01(\tB\x03\xe0A\x03R\x0edefaultProjectJ\x04\b\n" ++ "\x0fdefault_project\x18\x1a \x01(\tB\x03\xe0A\x03R\x0edefaultProjectJ\x04\b\t\x10\n" ++ "J\x04\b\n" +"\x10\vJ\x04\b\f\x10\rJ\x04\b\x10\x10\x11J\x04\b\x11\x10\x12J\x04\b\x0e\x10\x0f2\xe8\x05\n" +"\x0fActuatorService\x12s\n" +"\x0fGetActuatorInfo\x12#.bytebase.v1.GetActuatorInfoRequest\x1a\x19.bytebase.v1.ActuatorInfo\" \xdaA\x00\x80\xea0\x01\x82\xd3\xe4\x93\x02\x13\x12\x11/v1/actuator/info\x12\x82\x01\n" +diff --git a/backend/generated-go/v1/actuator_service_equal.pb.go b/backend/generated-go/v1/actuator_service_equal.pb.goindex 18061e9478..0ee8c8997c 100644--- a/backend/generated-go/v1/actuator_service_equal.pb.go+++ b/backend/generated-go/v1/actuator_service_equal.pb.go@@ -122,9 +122,6 @@ func (x *ActuatorInfo) Equal(y *ActuatorInfo) bool {if x.ExternalUrl != y.ExternalUrl {return false}- if x.NeedAdminSetup != y.NeedAdminSetup {- return false- }if p, q := x.LastActiveTime, y.LastActiveTime; (p == nil && q != nil) || (p != nil && (q == nil || p.Seconds != q.Seconds || p.Nanos != q.Nanos)) {return false}diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sqlindex a0f9b03725..36d81827ae 100644--- a/backend/migrator/migration/LATEST.sql+++ b/backend/migrator/migration/LATEST.sql@@ -21,6 +21,7 @@ CREATE TABLE principal (deleted boolean NOT NULL DEFAULT FALSE,created_at timestamptz NOT NULL DEFAULT now(),name text NOT NULL,+ -- golbal uniqueemail text NOT NULL,password_hash text NOT NULL,phone text NOT NULL DEFAULT '',@@ -54,6 +55,7 @@ CREATE INDEX idx_setting_workspace ON setting(workspace);-- RoleCREATE TABLE role (+ -- golbal uniqueresource_id text NOT NULL PRIMARY KEY,workspace text NOT NULL REFERENCES workspace(resource_id),name text NOT NULL,@@ -95,6 +97,7 @@ CREATE UNIQUE INDEX idx_policy_unique_workspace_resource ON policy(workspace, re-- idp stores generic identity provider.CREATE TABLE idp (+ -- golbal uniqueresource_id text NOT NULL PRIMARY KEY,workspace text NOT NULL REFERENCES workspace(resource_id),name text NOT NULL,@@ -106,6 +109,7 @@ CREATE TABLE idp ();CREATE TABLE user_group (+ -- golbal uniqueid text PRIMARY KEY DEFAULT gen_random_uuid()::text,workspace text NOT NULL REFERENCES workspace(resource_id),email text,@@ -119,6 +123,7 @@ CREATE UNIQUE INDEX idx_user_group_unique_email ON user_group(workspace, email)-- review config table.CREATE TABLE review_config (+ -- golbal uniqueid text NOT NULL PRIMARY KEY,workspace text NOT NULL REFERENCES workspace(resource_id),enabled boolean NOT NULL DEFAULT TRUE,@@ -128,6 +133,7 @@ CREATE TABLE review_config ();CREATE TABLE audit_log (+ -- golbal uniqueresource_id text PRIMARY KEY DEFAULT gen_random_uuid()::text,workspace text NOT NULL REFERENCES workspace(resource_id),created_at timestamptz NOT NULL DEFAULT now(),@@ -144,6 +150,7 @@ CREATE INDEX idx_audit_log_payload_resource ON audit_log((payload->>'resource'))CREATE INDEX idx_audit_log_payload_user ON audit_log((payload->>'user'));CREATE TABLE export_archive (+ -- golbal uniqueresource_id text PRIMARY KEY DEFAULT gen_random_uuid()::text,workspace text NOT NULL REFERENCES workspace(resource_id),created_at timestamptz NOT NULL DEFAULT now(),@@ -157,6 +164,7 @@ CREATE TABLE export_archive (-----------------------CREATE TABLE project (+ -- golbal uniqueresource_id text NOT NULL PRIMARY KEY,workspace text NOT NULL REFERENCES workspace(resource_id),deleted boolean NOT NULL DEFAULT FALSE,@@ -173,6 +181,7 @@ CREATE TABLE service_account (deleted boolean NOT NULL DEFAULT FALSE,created_at timestamptz NOT NULL DEFAULT now(),name text NOT NULL,+ -- golbal uniqueemail text NOT NULL PRIMARY KEY,workspace text NOT NULL REFERENCES workspace(resource_id),service_key_hash text NOT NULL,@@ -188,6 +197,7 @@ CREATE TABLE workload_identity (deleted boolean NOT NULL DEFAULT FALSE,created_at timestamptz NOT NULL DEFAULT now(),name text NOT NULL,+ -- golbal uniqueemail text NOT NULL PRIMARY KEY,workspace text NOT NULL REFERENCES workspace(resource_id),project text REFERENCES project(resource_id),@@ -201,6 +211,7 @@ CREATE INDEX idx_workload_identity_workspace ON workload_identity(workspace);-- Project HookCREATE TABLE project_webhook (+ -- golbal uniqueresource_id text PRIMARY KEY DEFAULT gen_random_uuid()::text,project text NOT NULL REFERENCES project(resource_id),-- Stored as ProjectWebhook (proto/store/store/project_webhook.proto)@@ -216,6 +227,7 @@ CREATE TABLE sheet_blob (-- plan table stores the plan for a projectCREATE TABLE plan (+ -- unique and auto-increase per projectid bigint NOT NULL,deleted boolean NOT NULL DEFAULT FALSE,creator text NOT NULL,@@ -234,6 +246,7 @@ CREATE INDEX idx_plan_creator ON plan(creator);CREATE INDEX idx_plan_config_has_rollout ON plan ((config->>'hasRollout'));CREATE TABLE plan_check_run (+ -- unique and auto-increase per projectid bigint NOT NULL,created_at timestamptz NOT NULL DEFAULT now(),updated_at timestamptz NOT NULL DEFAULT now(),@@ -264,6 +277,7 @@ CREATE TABLE plan_webhook_delivery (-- issueCREATE TABLE issue (+ -- unique and auto-increase per projectid bigint NOT NULL,creator text NOT NULL,created_at timestamptz NOT NULL DEFAULT now(),@@ -289,6 +303,7 @@ CREATE INDEX idx_issue_creator ON issue(creator);CREATE INDEX idx_issue_ts_vector ON issue USING GIN(ts_vector);CREATE TABLE issue_comment (+ -- global uniqueresource_id text NOT NULL DEFAULT gen_random_uuid()::text,creator text NOT NULL,created_at timestamptz NOT NULL DEFAULT now(),@@ -306,6 +321,7 @@ CREATE UNIQUE INDEX idx_issue_comment_unique_resource_id ON issue_comment(resour-- worksheet table stores worksheets in SQL Editor.CREATE TABLE worksheet (+ -- global uniqueresource_id text NOT NULL DEFAULT gen_random_uuid()::text,creator text NOT NULL,created_at timestamptz NOT NULL DEFAULT now(),@@ -338,6 +354,7 @@ CREATE INDEX idx_worksheet_organizer_payload ON worksheet_organizer USING GIN(paCREATE TABLE db_group (project text NOT NULL REFERENCES project(resource_id),+ -- global uniqueresource_id text NOT NULL,name text NOT NULL DEFAULT '',-- Stored as google.type.Expr (from Google Common Expression Language)@@ -366,6 +383,7 @@ CREATE INDEX idx_release_project_release_id ON release(project, release_id);CREATE INDEX idx_release_category ON release(project, category);CREATE TABLE access_grant (+ -- global uniqueid text PRIMARY KEY,project text NOT NULL REFERENCES project(resource_id),creator text NOT NULL,@@ -380,6 +398,7 @@ CREATE TABLE access_grant (CREATE INDEX idx_access_grant_project_creator_expire_time ON access_grant(project, creator, expire_time);CREATE TABLE query_history (+ -- global uniqueresource_id text PRIMARY KEY DEFAULT gen_random_uuid()::text,creator text NOT NULL,created_at timestamptz NOT NULL DEFAULT now(),@@ -400,6 +419,7 @@ CREATE INDEX idx_query_history_creator_created_at_project ON query_history(creat-----------------------CREATE TABLE instance (+ -- global uniqueresource_id text NOT NULL PRIMARY KEY,workspace text NOT NULL REFERENCES workspace(resource_id),deleted boolean NOT NULL DEFAULT FALSE,@@ -440,6 +460,7 @@ CREATE TABLE db_schema ();CREATE TABLE revision (+ -- global uniqueresource_id text PRIMARY KEY DEFAULT gen_random_uuid()::text,instance text NOT NULL,db_name text NOT NULL,@@ -456,6 +477,7 @@ CREATE UNIQUE INDEX idx_revision_unique_instance_db_name_type_version_deleted_atCREATE INDEX idx_revision_instance_db_name_type_version ON revision(instance, db_name, (payload->>'type'), version);CREATE TABLE sync_history (+ -- global uniqueresource_id text PRIMARY KEY DEFAULT gen_random_uuid()::text,created_at timestamptz NOT NULL DEFAULT now(),instance text NOT NULL,@@ -469,6 +491,7 @@ CREATE TABLE sync_history (CREATE INDEX idx_sync_history_instance_db_name_created_at ON sync_history (instance, db_name, created_at);CREATE TABLE changelog (+ -- global uniqueresource_id text PRIMARY KEY DEFAULT gen_random_uuid()::text,created_at timestamptz NOT NULL DEFAULT now(),instance text NOT NULL,@@ -498,6 +521,7 @@ ALTER SEQUENCE instance_change_history_id_seq RESTART WITH 101;-- task table stores the task for a planCREATE TABLE task (+ -- unique and auto-increase per projectid bigint NOT NULL,project text NOT NULL REFERENCES project(resource_id),plan_id bigint NOT NULL,@@ -515,6 +539,7 @@ CREATE INDEX idx_task_plan_id_environment ON task(project, plan_id, environment)-- task run table stores the task runCREATE TABLE task_run (+ -- unique and auto-increase per projectid bigint NOT NULL,creator text,created_at timestamptz NOT NULL DEFAULT now(),diff --git a/backend/runner/taskrun/database_migrate_executor.go b/backend/runner/taskrun/database_migrate_executor.goindex b3de179157..d6ffb1ab20 100644--- a/backend/runner/taskrun/database_migrate_executor.go+++ b/backend/runner/taskrun/database_migrate_executor.go@@ -170,12 +170,18 @@ func (exec *DatabaseMigrateExecutor) runStandardMigration(ctx context.Context, dvar priorBackupDetail *storepb.PriorBackupDetailif task.Payload.GetEnablePriorBackup() {// Check if this specific task run wants to skip backup.- taskRun, err := exec.store.GetTaskRunByUID(ctx, database.ProjectID, taskRunUID)+ taskRun, err := exec.store.GetTaskRunV1(ctx, &store.FindTaskRunMessage{+ ProjectID: database.ProjectID,+ UID: &taskRunUID,+ })if err != nil {return nil, errors.Wrapf(err, "failed to get task run")}- skipBackup := taskRun.PayloadProto.GetSkipPriorBackup()+ if taskRun == nil {+ return nil, errors.Errorf("task run %d not found in project %s", taskRunUID, database.ProjectID)+ }+ skipBackup := taskRun.PayloadProto.GetSkipPriorBackup()if !skipBackup {exec.store.CreateTaskRunLogS(ctx, database.ProjectID, taskRunUID, time.Now(), exec.profile.ReplicaID, &storepb.TaskRunLog{Type: storepb.TaskRunLog_PRIOR_BACKUP_START,diff --git a/backend/store/access_grant.go b/backend/store/access_grant.goindex 322e25b73d..659763b263 100644--- a/backend/store/access_grant.go+++ b/backend/store/access_grant.go@@ -37,6 +37,9 @@ type AccessGrantMessage struct {// FindAccessGrantMessage is the message for finding access grants.type FindAccessGrantMessage struct {+ // Workspace filters access grants by the parent project's workspace.+ // Empty string skips filtering.+ Workspace stringID *stringProjectID *stringCreator *string@@ -117,6 +120,10 @@ func (s *Store) ListAccessGrants(ctx context.Context, find *FindAccessGrantMessaWHERE TRUE`)+ if find.Workspace != "" {+ q.And("project IN (SELECT resource_id FROM project WHERE workspace = ?)", find.Workspace)+ }+if filterQ := find.FilterQ; filterQ != nil {q.And("?", filterQ)}diff --git a/backend/store/database.go b/backend/store/database.goindex e38e5428d7..00f67210bc 100644--- a/backend/store/database.go+++ b/backend/store/database.go@@ -51,6 +51,9 @@ type UpdateDatabaseMessage struct {// BatchUpdateDatabases is the message for batch updating databases.type BatchUpdateDatabases struct {+ // Workspace scopes the update to databases whose instance belongs to this workspace.+ // Empty string skips filtering (cross-workspace).+ Workspace stringProjectID *stringFindByEnvironmentID *string// Empty string will unset the environment.@@ -59,6 +62,9 @@ type BatchUpdateDatabases struct {// FindDatabaseMessage is the message for finding databases.type FindDatabaseMessage struct {+ // Workspace filters databases by the parent instance's workspace.+ // Empty string skips filtering (for cross-workspace queries like runners).+ Workspace stringProjectID *stringEffectiveEnvironmentID *stringInstanceID *string@@ -75,10 +81,25 @@ type FindDatabaseMessage struct {OrderByKeys []*OrderByKey}+// removeDatabaseCache invalidates both workspace-scoped and unscoped cache entries for a database.+func (s *Store) removeDatabaseCache(ctx context.Context, instanceID, databaseName string) {+ // Remove unscoped (runner) cache entry.+ s.databaseCache.Remove(getDatabaseCacheKey("", instanceID, databaseName))+ // Remove workspace-scoped (API) cache entry.+ // Query workspace directly from instance table to avoid workspace-filtering issues with GetInstance.+ var workspace string+ if err := s.GetDB().QueryRowContext(ctx,+ "SELECT workspace FROM instance WHERE resource_id = $1", instanceID,+ ).Scan(&workspace); err != nil {+ return+ }+ s.databaseCache.Remove(getDatabaseCacheKey(workspace, instanceID, databaseName))+}+// GetDatabase gets a database.func (s *Store) GetDatabase(ctx context.Context, find *FindDatabaseMessage) (*DatabaseMessage, error) {if find.InstanceID != nil && find.DatabaseName != nil {- if v, ok := s.databaseCache.Get(getDatabaseCacheKey(*find.InstanceID, *find.DatabaseName)); ok && s.enableCache {+ if v, ok := s.databaseCache.Get(getDatabaseCacheKey(find.Workspace, *find.InstanceID, *find.DatabaseName)); ok && s.enableCache {return v, nil}}@@ -95,7 +116,7 @@ func (s *Store) GetDatabase(ctx context.Context, find *FindDatabaseMessage) (*Da}database := databases[0]- s.databaseCache.Add(getDatabaseCacheKey(database.InstanceID, database.DatabaseName), database)+ s.databaseCache.Add(getDatabaseCacheKey(find.Workspace, database.InstanceID, database.DatabaseName), database)return database, nil}@@ -115,6 +136,9 @@ func (s *Store) ListDatabases(ctx context.Context, find *FindDatabaseMessage) ([from.Space("LEFT JOIN instance ON db.instance = instance.resource_id")+ if find.Workspace != "" {+ where.And("instance.workspace = ?", find.Workspace)+ }if v := find.ProjectID; v != nil {where.And("db.project = ?", *v)}@@ -227,7 +251,7 @@ func (s *Store) ListDatabases(ctx context.Context, find *FindDatabaseMessage) ([}for _, database := range databases {- s.databaseCache.Add(getDatabaseCacheKey(database.InstanceID, database.DatabaseName), database)+ s.databaseCache.Add(getDatabaseCacheKey(find.Workspace, database.InstanceID, database.DatabaseName), database)}return databases, nil}@@ -260,7 +284,7 @@ func (s *Store) CreateDatabaseDefault(ctx context.Context, create *DatabaseMessa}// Invalidate and update the cache.- s.databaseCache.Remove(getDatabaseCacheKey(create.InstanceID, create.DatabaseName))+ s.removeDatabaseCache(ctx, create.InstanceID, create.DatabaseName)return s.GetDatabase(ctx, &FindDatabaseMessage{InstanceID: &create.InstanceID, DatabaseName: &create.DatabaseName, ShowDeleted: true})}@@ -309,7 +333,7 @@ func (s *Store) UpsertDatabase(ctx context.Context, create *DatabaseMessage) (*D}// Invalidate and update the cache.- s.databaseCache.Remove(getDatabaseCacheKey(create.InstanceID, create.DatabaseName))+ s.removeDatabaseCache(ctx, create.InstanceID, create.DatabaseName)return s.GetDatabase(ctx, &FindDatabaseMessage{InstanceID: &create.InstanceID, DatabaseName: &create.DatabaseName, ShowDeleted: true})}@@ -365,7 +389,7 @@ func (s *Store) UpdateDatabase(ctx context.Context, patch *UpdateDatabaseMessage}// Invalidate and update database cache.- s.databaseCache.Remove(getDatabaseCacheKey(patch.InstanceID, patch.DatabaseName))+ s.removeDatabaseCache(ctx, patch.InstanceID, patch.DatabaseName)return s.GetDatabase(ctx, &FindDatabaseMessage{InstanceID: &patch.InstanceID, DatabaseName: &patch.DatabaseName, ShowDeleted: true})}@@ -406,6 +430,10 @@ func (s *Store) BatchUpdateDatabases(ctx context.Context, databases []*DatabaseMreturn errors.Errorf("empty where")}+ if update.Workspace != "" {+ where.And("db.instance IN (SELECT resource_id FROM instance WHERE workspace = ?)", update.Workspace)+ }+q := qb.Q().Space("UPDATE db SET ? WHERE ?", set, where)query, args, err := q.ToSQL()@@ -419,7 +447,7 @@ func (s *Store) BatchUpdateDatabases(ctx context.Context, databases []*DatabaseM// Invalidate cache for updated databasesfor _, database := range databases {- s.databaseCache.Remove(getDatabaseCacheKey(database.InstanceID, database.DatabaseName))+ s.removeDatabaseCache(ctx, database.InstanceID, database.DatabaseName)}return nil}diff --git a/backend/store/db_schema.go b/backend/store/db_schema.goindex 29fc4fc2b5..2ebc2ee572 100644--- a/backend/store/db_schema.go+++ b/backend/store/db_schema.go@@ -28,11 +28,15 @@ type FindDBSchemaMessage struct {func (s *Store) GetDBSchema(ctx context.Context, find *FindDBSchemaMessage) (*model.DatabaseMetadata, error) {q := qb.Q().Space(`SELECT- metadata,- raw_dump,- config+ db_schema.metadata,+ db_schema.raw_dump,+ db_schema.configFROM db_schema- WHERE instance = ? AND db_name = ?`, find.InstanceID, find.DatabaseName)+ JOIN instance ON instance.resource_id = db_schema.instance+ WHERE db_schema.instance = ? AND db_schema.db_name = ?`, find.InstanceID, find.DatabaseName)+ if find.Workspace != "" {+ q.And("instance.workspace = ?", find.Workspace)+ }query, args, err := q.ToSQL()if err != nil {diff --git a/backend/store/issue.go b/backend/store/issue.goindex b267466eb3..af98afb195 100644--- a/backend/store/issue.go+++ b/backend/store/issue.go@@ -58,6 +58,9 @@ type UpdateIssueMessage struct {// FindIssueMessage is the message to find issues.type FindIssueMessage struct {+ // Workspace filters issues by the parent project's workspace.+ // Empty string skips filtering (for cross-workspace queries like runners).+ Workspace string// Required fieldProjectIDs []string@@ -250,14 +253,15 @@ func (s *Store) ListIssues(ctx context.Context, find *FindIssueMessage) ([]*Issufrom := qb.Q().Space("issue")where := qb.Q()- if len(find.ProjectIDs) == 0 {- return nil, errors.Errorf("empty project filter")- }if len(find.ProjectIDs) == 1 {where.And("issue.project = ?", find.ProjectIDs[0])} else {where.And("issue.project = ANY(?)", find.ProjectIDs)}+ if find.Workspace != "" {+ from.Space("JOIN project ON issue.project = project.resource_id")+ where.And("project.workspace = ?", find.Workspace)+ }if v := find.UID; v != nil {where.And("issue.id = ?", *v)diff --git a/backend/store/plan.go b/backend/store/plan.goindex b844dbc064..5e33fec019 100644--- a/backend/store/plan.go+++ b/backend/store/plan.go@@ -35,6 +35,9 @@ type PlanMessage struct {// FindPlanMessage is the message to find a plan.type FindPlanMessage struct {+ // Workspace filters plans by the parent project's workspace.+ // Empty string skips filtering (for cross-workspace queries like runners).+ Workspace stringUID *int64ProjectID string@@ -142,6 +145,10 @@ func (s *Store) ListPlans(ctx context.Context, find *FindPlanMessage) ([]*PlanMeWHERE plan.project = ?`, find.ProjectID)+ if find.Workspace != "" {+ q.And("plan.project IN (SELECT resource_id FROM project WHERE workspace = ?)", find.Workspace)+ }+if filterQ := find.FilterQ; filterQ != nil {q.And("?", filterQ)}diff --git a/backend/store/project.go b/backend/store/project.goindex 956375b07d..50ece15dda 100644--- a/backend/store/project.go+++ b/backend/store/project.go@@ -129,7 +129,6 @@ func (s *Store) ListProjects(ctx context.Context, find *FindProjectMessage) ([]*}q.Space(fmt.Sprintf("ORDER BY %s", strings.Join(orderBy, ", ")))} else {- // TODO(ed): order won't workq.Space("ORDER BY project.resource_id")}if v := find.Limit; v != nil {diff --git a/backend/store/store.go b/backend/store/store.goindex bbe8ca4b2e..ad7a78dbe6 100644--- a/backend/store/store.go+++ b/backend/store/store.go@@ -157,8 +157,8 @@ func getPolicyCacheKey(workspace string, resourceType storepb.Policy_Resource, rreturn fmt.Sprintf("workspaces/%s/policies/%s/%s/%s", workspace, resourceType, resource, policyType)}-func getDatabaseCacheKey(instanceID, databaseName string) string {- return fmt.Sprintf("%s/%s", instanceID, databaseName)+func getDatabaseCacheKey(workspace, instanceID, databaseName string) string {+ return fmt.Sprintf("workspaces/%s/%s/%s", workspace, instanceID, databaseName)}func getDBSchemaCacheKey(instanceID, databaseName string) string {diff --git a/backend/store/task.go b/backend/store/task.goindex e3db4963a7..18d21fe7ab 100644--- a/backend/store/task.go+++ b/backend/store/task.go@@ -49,8 +49,11 @@ func (t *TaskMessage) GetDatabaseName() string {// TaskFind is the API message for finding tasks.type TaskFind struct {- ID *int64- IDs *[]int64+ // Workspace filters tasks by the parent project's workspace.+ // Empty string skips filtering (for cross-workspace queries like runners).+ Workspace string+ ID *int64+ IDs *[]int64// Related fieldsProjectID string@@ -281,6 +284,9 @@ func (*Store) listTasksImpl(ctx context.Context, txn *sql.Tx, find *TaskFind) ([LIMIT 1) AS latest_task_run ON TRUEWHERE task.project = ?`, storepb.TaskRun_NOT_STARTED.String(), find.ProjectID)+ if find.Workspace != "" {+ q.Space("AND task.project IN (SELECT resource_id FROM project WHERE workspace = ?)", find.Workspace)+ }if v := find.ID; v != nil {q.Space("AND task.id = ?", *v)}diff --git a/backend/store/task_run.go b/backend/store/task_run.goindex 304e5764b3..504db370c1 100644--- a/backend/store/task_run.go+++ b/backend/store/task_run.go@@ -34,6 +34,9 @@ type TaskRunMessage struct {// FindTaskRunMessage is the message for finding task runs.type FindTaskRunMessage struct {+ // Workspace filters task runs by the parent project's workspace.+ // Empty string skips filtering (for cross-workspace queries like runners).+ Workspace stringUID *int64UIDs *[]int64ProjectID string@@ -78,6 +81,10 @@ func (s *Store) ListTaskRuns(ctx context.Context, find *FindTaskRunMessage) ([]*WHERE task_run.project = ?`, find.ProjectID)+ if find.Workspace != "" {+ q.And("task_run.project IN (SELECT resource_id FROM project WHERE workspace = ?)", find.Workspace)+ }+if v := find.UID; v != nil {q.And("task_run.id = ?", *v)}@@ -179,7 +186,7 @@ func (s *Store) GetTaskRunV1(ctx context.Context, find *FindTaskRunMessage) (*Tareturn nil, err}if len(taskRuns) == 0 {- return nil, errors.Errorf("task run not found")+ return nil, nil}if len(taskRuns) > 1 {return nil, errors.Errorf("expected to get one task run, but got %d", len(taskRuns))@@ -187,11 +194,6 @@ func (s *Store) GetTaskRunV1(ctx context.Context, find *FindTaskRunMessage) (*Tareturn taskRuns[0], nil}-// GetTaskRunByUID gets a task run by uid.-func (s *Store) GetTaskRunByUID(ctx context.Context, projectID string, uid int64) (*TaskRunMessage, error) {- return s.GetTaskRunV1(ctx, &FindTaskRunMessage{ProjectID: projectID, UID: &uid})-}-// UpdateTaskRunStatus updates task run status.func (s *Store) UpdateTaskRunStatus(ctx context.Context, patch *TaskRunStatusPatch) (*TaskRunMessage, error) {tx, err := s.GetDB().BeginTx(ctx, nil)diff --git a/backend/store/workspace.go b/backend/store/workspace.goindex 308da780f8..5704fbd7de 100644--- a/backend/store/workspace.go+++ b/backend/store/workspace.go@@ -156,8 +156,8 @@ func (s *Store) FindWorkspaceIDByMemberEmail(ctx context.Context, memberName strif len(workspaces) == 0 {return "", errors.Errorf("%q is not a member of any workspace", memberName)}- // TODO(ed): In SaaS mode with multiple workspaces, return a workspace picker- // instead of auto-selecting the first one. For now, use the first workspace.+ // Returns the first workspace. The caller (resolveWorkspaceForLogin) may+ // override this with the user's last login workspace from their profile.return workspaces[0].ResourceID, nil}diff --git a/docs/plans/saas/00.challenges-and-roadmap.md b/docs/plans/saas/00.challenges-and-roadmap.mdindex 7882a6a924..35b2be3e65 100644--- a/docs/plans/saas/00.challenges-and-roadmap.md+++ b/docs/plans/saas/00.challenges-and-roadmap.md@@ -181,6 +181,37 @@ These are children of Tier 2 tables. They have no `project` FK and no `workspace---+## Architecture Diagram++```+┌─────────────────────────────────────────────────────────────┐+│ Request Flow │+│ │+│ Client → Auth Interceptor → ACL Interceptor → Service │+│ │ │ │ │+│ Set workspace Validate Use │+│ in context workspace workspace │+│ from JWT ownership for queries │+│ │+├─────────────────────────────────────────────────────────────┤+│ Store Layer │+│ │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │+│ │ Root Tables │ │ Child Tables │ │ Global Tables │ │+│ │ workspace FK │ │ project/inst │ │ No workspace │ │+│ │ (required) │ │ FK (indirect)│ │ (principal, │ │+│ │ │ │ │ │ sheet_blob, etc) │ │+│ └──────────────┘ └──────────────┘ └──────────────────┘ │+├─────────────────────────────────────────────────────────────┤+│ Background Runners │+│ │+│ Cross-workspace polling → Resolve workspace from entity │+│ → Use workspace for settings/policies │+└─────────────────────────────────────────────────────────────┘+```++---+## Roadmap| Step | File | Description |diff --git a/docs/plans/saas/05.progress.md b/docs/plans/saas/05.progress.mdindex 28f422119f..1abf1f31b9 100644--- a/docs/plans/saas/05.progress.md+++ b/docs/plans/saas/05.progress.md@@ -1,12 +1,12 @@# SaaS Migration Progress-Current status of the workspace isolation implementation. **129 files changed, ~4000 lines modified.**+Current status of the workspace isolation implementation. **185+ files changed, ~4700 lines modified.**---## Completed-### Database Migration (Step 02)+### Database Migration- [x] **`server_config` table** — Global config (single row), stores `auth_secret` via `payload` JSONB- [x] **`workspace` table** — Workspace identity with `resource_id` PK@@ -15,45 +15,58 @@ Current status of the workspace isolation implementation. **129 files changed, ~- [x] **`oauth2_authorization_code` / `oauth2_refresh_token`** — No workspace column (scoped through `client_id` FK)- [x] **Auth secret migrated** from `SystemSetting` JSON to `server_config.payload`- [x] **`SystemSetting` proto** — `auth_secret` and `workspace_id` fields reserved+- [x] **LATEST.sql** — `plan`, `task`, `task_run`, `plan_check_run`, `issue` changed from `serial` to `bigint NOT NULL`+- [x] **LATEST.sql** — `worksheet.id` column dropped (PK is `resource_id`)+- [x] **LATEST.sql** — Audit log composite index `(workspace, created_at DESC)` replaces separate indexes+- [x] **LATEST.sql** — Seed data: only `server_config` (workspace created by Go signup flow)+- [x] **Migration 0006** — Drops worksheet `id` column (fixes "null value in column id" error)+- [x] **Migration 0009** — Composite audit log index created-### Store Layer (Step 03)+### Store Layer- [x] **All root tables enforce workspace on CRUD** (INSERT, SELECT, UPDATE, DELETE)-- [x] **`workspace.go`**: `GetWorkspaceID()` (startup/OAuth2), `FindWorkspacesByMemberEmail()`, `FindWorkspaceIDByMemberEmail()`+- [x] **`workspace.go`**: `GetWorkspaceID()` returns `("", nil)` when no workspace exists, `FindWorkspacesByMemberEmail()`, `FindWorkspaceIDByMemberEmail()`, `CreateWorkspace()` with proto-based settings/policy- [x] **`runner_queries.go`**: Cross-workspace methods (`GetProjectByResourceID`, `GetInstanceByResourceID`, `ListAllInstances`, `DeleteExpiredExportArchivesAll`)- [x] **`account.go`**: `AccountMessage` + `GetAccountByEmail()` for auth layer-- [x] **Separated workspace-scoped vs cross-workspace lookups** for SA/WI- [x] **`GetServerConfig()` / `GetAuthSecret()`** — reads from `server_config` table-- [x] **`CountActiveEndUsersPerWorkspace`** — counts via IAM policy membership-- [x] **`GetIdentityProviderByID`** — cross-workspace IDP lookup for SSO login-- [x] **Cache keys include workspace**-- [x] **OAuth2 auth code/refresh token** queries require `clientID`+- [x] **`CountActiveEndUsersPerWorkspace`** — counts via IAM policy membership (explicit members only, not `allUsers`)+- [x] **`CountAllActivePrincipals`** — counts all principals globally (for `allUsers` admin check)+- [x] **`GetDefaultProjectID(ctx, workspace)`** — checks new format first, falls back to legacy `"default"`+- [x] **`BatchGetUsersByEmails`** — workspace-scoped via IAM join+- [x] **Cache fixes** — `settingCache`, `groupCache`, `groupMembersCache`, `memberGroupsCache` all include workspace in keys. `UpdatePolicy` sets `Workspace` on cached entry. `DeletePolicy` invalidates `iamPolicyCache`. `UpdateUserReferenceInPolicies` invalidates `iamPolicyCache` and purges group caches.+- [x] **`SearchAuditLogs`** — workspace filter is optional (empty = cross-workspace for login lockout)-### Auth & Token Flow (Steps 03-04)+### Auth & Token Flow- [x] **Workspace in JWT claims** (`WorkspaceID` field)- [x] **Auth middleware** injects workspace into context, verifies membership-- [x] **Login workspace resolution** via `FindWorkspacesByMemberEmail` (IAM policy)-- [x] **`LoginResponse.workspace`** — returns workspace name to frontend after login-- [x] **`generateLoginToken`** returns both token and workspace ID-- [x] **IDP (SSO) login** — resolves workspace from `idp.Workspace`, adds new user to workspace IAM-- [x] **Token refresh** keeps workspace from original token--### API Layer (Step 03)--- [x] **All API v1 handlers pass workspace** to store queries-- [x] **Only authorized API code** uses `common.GetWorkspaceIDFromContext`-- [x] **Non-API code** accepts workspace as parameter-- [x] **LSP handler** stores workspace from token on handler struct-- [x] **Actuator service**: unauthenticated returns basic info, authenticated returns full workspace-scoped info-- [x] **Workspace-scoped actuator endpoint**: `GET /v1/{name=workspaces/*}/actuator/info` (requires auth)-- [x] **Resource package**: `additional_bindings` for `/v1/{name=workspaces/*}/actuator/resources` (no auth)--### Background Runners (Step 04)+- [x] **Login workspace resolution** via `FindWorkspacesByMemberEmail` (IAM policy). Workspace resolved early in Login flow, passed as parameter (not via context).+- [x] **`Signup` API** (`POST /v1/auth/signup`, `allow_without_credential`) — Creates principal + workspace. Self-hosted: joins existing workspace or creates if none exists. SaaS: creates new workspace per user.+- [x] **`CreateUser` refactored** — Admin-only (`bb.users.create` permission), self-hosted only. SaaS blocked.+- [x] **Login lockout** — `countRecentLoginFailures` searches audit logs cross-workspace (per-email rate limit)+- [x] **IDP (SSO) login** — resolves workspace from `idp.Workspace`, passes workspace explicitly (no context injection)+- [x] **ExchangeToken** — uses `GetWorkloadIdentityByEmail` (cross-workspace) and `wi.Workspace`+- [x] **All `allow_without_credential` APIs audited** — no `GetWorkspaceIDFromContext` in unauthenticated paths++### API Layer++- [x] **All auth_service functions** accept `workspaceID` as parameter (not from context): `validateLoginPermissions`, `checkMFARequired`, `needResetPassword`, `isUserWorkspaceAdmin`, `validateEmailWithDomains`, `syncUserGroups`, `generateLoginToken`+- [x] **`UpdateUser`** — SaaS: self-updates only. Self-hosted: admin can update others.+- [x] **`DeleteUser` / `UndeleteUser` / `UpdateEmail`** — SaaS: blocked.+- [x] **`GetUser` / `BatchGetUsers`** — workspace-scoped via IAM join+- [x] **`SetIamPolicy`** — blocks `allUsers` in SaaS. No member count check (enforced at CreateUser/IDP level).+- [x] **`ListIdentityProviders`** — self-hosted falls back to `store.GetWorkspaceID` for unauthenticated login page+- [x] **`GetSubscription`** — falls back to free subscription if no workspace context+- [x] **ACL simplified** — removed `rawResource` struct, `getResourceFromRequest` returns `[]string`+- [x] **Default project** — `CreateProject` blocks `"default"` and `"default-*"` project IDs as reserved. `IsDefaultProject` handles both legacy and new formats.+- [x] **`userCountGuard`** — uses explicit `workspaceID` parameter++### Background Runners- [x] **Runners use cross-workspace store methods**- [x] **Workspace resolved from loaded entities**- [x] **`CheckReplicaLimit` skips in SaaS mode**+- [x] **Schema sync** — `CreateDatabaseDefault` uses `GetDefaultProjectID` (handles legacy)### OAuth2@@ -63,78 +76,109 @@ Current status of the workspace isolation implementation. **129 files changed, ~### Infrastructure-- [x] **`server_config`** — Only `auth_secret` (JSONB payload). All other settings in per-workspace WORKSPACE_PROFILE-- [x] **`ServerConfigPayload` proto** — Minimal: `auth_secret` only-- [x] **Self-hosted features** guarded by `!profile.SaaS` (sample instances, debug, metrics, audit log stdout)-- [x] **SaaS telemetry** disabled by default (operator manages their own monitoring)+- [x] **Server startup** — No workspace dependency. Loads settings if workspace exists, skips on first boot.+- [x] **`server_config`** — Only `auth_secret` (JSONB payload)+- [x] **Self-hosted features** guarded by `!profile.SaaS`+- [x] **`DisallowSignup` override removed** — SaaS no longer forces it true (signup always allowed)+- [x] **Per-workspace licensing** — `LoadSubscription`, `StoreLicense`, `GetUserLimit`, `GetActivatedInstanceLimit` all workspace-scoped with workspace in cache key++### Frontend++- [x] **`isDefaultProject`** — reads from `useActuatorV1Store().serverInfo?.defaultProject` internally. Single-arg call.+- [x] **`Signup` API** — frontend uses `authServiceClientConnect.signup()` instead of `CreateUser` + `Login`+- [x] **Auth interceptor** — skips token refresh for `Signup` method+- [x] **`DEFAULT_PROJECT_PREFIX`** — unexported, used only internally by `getDefaultProjectName`----## Remaining TODO(ed) Items+## SaaS vs Self-hosted Behavior Differences-| File | Description |-|------|-------------|-| `actuator_service.go:145` | Skip sample setup in SaaS mode (currently returns error) |-| `workspace.go:46` | Multiple workspaces: auto-selects first. SaaS needs workspace picker |-| `server.go:158,170,180,284` | Self-host-only features guarded by `!profile.SaaS` |-| `project.go:108` | ORDER BY may not work with workspace filter |+See [06.saas-vs-selfhosted.md](./06.saas-vs-selfhosted.md) for a comprehensive catalog of every code path difference.----## High Priority — Not Yet Implemented+## Workspace Isolation Audit (Code Review)++A full code review was conducted to verify workspace isolation across the entire backend. All previously flagged API gaps were investigated and found to be properly isolated.++### Fixes Applied++| # | Fix | Files Changed |+|---|-----|---------------|+| 1 | ACL now validates instance-scoped resources (e.g. `instances/{id}`, `instances/{id}/roles/{role}`) by looking up the instance with workspace filter | `backend/api/v1/acl.go` |+| 2 | Added missing `Workspace` param to `GetDatabase`/`ListDatabases` calls | `backend/api/lsp/handler.go`, `backend/api/lsp/completion.go`, `backend/component/export/resources.go` (4 calls), `backend/component/sampleinstance/manager.go` |+| 3 | LSP handler refactored: user and workspaceID injected into context at WebSocket connection time, removed from handler struct. Now uses `common.GetWorkspaceIDFromContext(ctx)` consistently | `backend/api/lsp/lsp.go`, `backend/api/lsp/handler.go`, `backend/api/lsp/completion.go` |+| 4 | Added cross-workspace documentation comments to ACL `populateRawResources` (resource resolution strategy, per-case comments) | `backend/api/v1/acl.go` |+| 5 | `db_schema.go` `GetDBSchema` now JOINs to instance table and filters by `instance.workspace` when workspace param is provided | `backend/store/db_schema.go` |-### Workspace-scoped resource listing+### API Layer Verification-All List/Search/Get endpoints for project-child tables must validate the parent project belongs to the user's workspace. Currently, child table queries filter by project FK but don't verify the project's workspace, which could leak data across workspaces.+All previously flagged services were verified to properly enforce workspace isolation:-**Affected endpoints and store queries:**+- **`instance_role_service.go`** — uses `getInstanceMessage` helper which filters by workspace. ACL layer now also validates instance ownership.+- **`changelog_service.go`** — `ListChangelogs` and `GetChangelog` look up the database with `Workspace: common.GetWorkspaceIDFromContext(ctx)`. ACL's database case also validates.+- **`database_group_service.go`** — all methods call `store.GetProject` with workspace filter before accessing database groups.+- **`database_service.go`** — `GetDatabase`, `BatchGetDatabases`, `UpdateDatabase` all use workspace-filtered lookups.+- **`revision_service.go`** — validates database with workspace filter before querying revisions.+- **`issue_service.go`** — `getIssueFind()` sets workspace from context; `getIssueMessage()` passes workspace.+- **`plan_service.go`** — all `GetPlan`/`ListPlans` calls pass workspace.+- **`rollout_service.go`** — all task/plan lookups pass workspace.+- **`access_grant_service.go`** — `GetAccessGrant` with workspace filter before any update.+- **`release_service.go`** — project lookup with workspace filter before accessing releases.+- **`worksheet_service.go`** — project lookup with workspace filter before accessing worksheets.-| Category | Endpoints | Risk |-|----------|-----------|------|-| **Databases** | `ListDatabases`, `BatchGetDatabases`, `GetDatabase` | `FindDatabaseMessage` doesn't include workspace. Queries by project/instance which are workspace-scoped in store, but API doesn't validate parent workspace. |-| **Issues** | `ListIssues`, `SearchIssues`, `GetIssue` | `FindIssueMessage` has `ProjectIDs` but no workspace. Project-level filter is set from request `parent` without workspace validation. |-| **Plans** | `ListPlans`, `GetPlan` | `FindPlanMessage` queries by `ProjectID` without workspace validation on the project. |-| **Database Groups** | `ListDatabaseGroups`, `GetDatabaseGroup` | `FindDatabaseGroupMessage` has no workspace. `ListDatabaseGroups` in actuator queries with `{}` (all workspaces). |-| **Changelogs** | `ListChangelogs` | Queried by database which is instance-scoped, but no workspace validation on instance. |-| **Releases** | `ListReleases` | Queried by project without workspace validation. |-| **Worksheets** | `ListWorksheets` | Queried by project/creator without workspace validation. |-| **Task Runs** | `ListTaskRuns` | Queried by plan/project without workspace validation. |-| **Access Grants** | `ListAccessGrants` | Queried by project without workspace validation. |-| **Query History** | `SearchQueryHistories` | Queried by creator without workspace validation on project. |+### Store Layer Verification-**Fix pattern:** For each child List/Get endpoint:-1. Extract `projectID` (or `instanceID`) from request `parent`-2. Validate the parent belongs to the current workspace: `GetProject(ctx, FindProjectMessage{Workspace: wsID, ResourceID: &projectID})`-3. Only then query children+Every public store method was audited:-**Also need:** Add workspace to `FindDatabaseGroupMessage` (it's a project-child but currently has no workspace-aware parent validation in the store).+- **Root tables** (`project`, `instance`, `policy`, `setting`, `role`, `group`, etc.): All enforce workspace via direct `WHERE workspace = ?`.+- **Child tables** (`changelog`, `revision`, `worksheet`, `db_schema`, etc.): Scoped via globally unique parent PKs. API layer validates workspace on the parent before calling these methods.+- **Global tables** (`principal`, `sheet_blob`): Intentionally cross-workspace by design. Principals are global identities. Sheet blobs are content-addressed (SHA256 dedup).+- **All API-layer callers of optional-workspace store methods** properly pass `common.GetWorkspaceIDFromContext(ctx)`. Verified for `GetDatabase`, `ListDatabases`, `GetIssue`, `ListIssues`, `GetPlan`, `ListPlans`, `ListTasks`, `ListTaskRuns`.++### Remaining++- [ ] **Workspace switching endpoint** — Issue new JWT with different `workspace_id` (login auto-selects the first workspace; users switch after login)+- [ ] **Cross-workspace user management** — List workspaces for a user+- [ ] **Workspace admin panel** — Manage workspace settings, members+- [ ] **Schema sync perf** — when database count grows, consider querying per instance or adding `InstanceIDs` batch filter to `FindDatabaseMessage`----## Not Yet Started+## Impact on Existing Self-hosted Customers-### Auth Flow+### Breaking Changes-- [ ] **Workspace picker UI** — Show picker if user has multiple workspaces-- [ ] **Workspace switching endpoint** — Issue new JWT with different `workspace_id`+1. **Signup API moved** — `CreateUser` (`POST /v1/users`) now requires `bb.users.create` permission. Self-service signup moved to `Signup` (`POST /v1/auth/signup`). API consumers using `CreateUser` for registration will break.+2. **`CreateUser` no longer adds to workspace IAM** — Admin creates principal only. Must separately add to IAM for the user to login.-### Future+### Non-breaking Changes-- [ ] **Workspace creation API** — Create new workspaces, invite users-- [ ] **Per-workspace licensing** — Each workspace has its own license-- [ ] **Cross-workspace user management** — List workspaces for a user+3. **Default project** — New workspaces get `default-{workspaceID}`. Existing `default` project preserved. Code handles both formats.+4. **Workspace table + migration** — Instant `ADD COLUMN` with default. No table rewrite.+5. **Login flow** — Self-hosted with `allUsers` in IAM works identically to before.+6. **Cache fixes** — Fixes potential stale cache bugs.+7. **Server startup** — Resilient to missing workspace on first boot.---## Design Decisions-1. **`server_config` only stores `auth_secret`** — All other settings (password restrictions, signup control, token durations, metrics, debug) live in per-workspace WORKSPACE_PROFILE. Reason: avoid split-brain between two config sources. The login page can get restrictions from the workspace-scoped actuator endpoint.+1. **`server_config` only stores `auth_secret`** — All other settings live in per-workspace WORKSPACE_PROFILE.-2. **Root table PKs (`resource_id`) are globally unique** — No composite PK migration needed. Workspace-scoped unique indexes only for tables where PK is not `resource_id` (setting, user_group, service_account, workload_identity, policy).+2. **Root table PKs (`resource_id`) are globally unique** — No composite PK migration needed.3. **Three access patterns for store queries**:- **API layer**: `common.GetWorkspaceIDFromContext(ctx)` from JWT- - **Runners**: Cross-workspace methods (`GetProjectByResourceID`, `ListAllInstances`)+ - **Runners**: Cross-workspace methods- **Login/startup**: `store.GetWorkspaceID(ctx)` or `FindWorkspacesByMemberEmail`-4. **OAuth2 child tables** (auth code, refresh token) don't need workspace — scoped through `client_id` FK to workspace-scoped `oauth2_client`.+4. **OAuth2 child tables** don't need workspace — scoped through `client_id` FK.++5. **Default project naming** — New workspaces: `default-{workspaceID}`. Legacy: `default`. `IsDefaultProject` and frontend handle both. No data migration needed.++6. **`Signup` vs `CreateUser`** — Signup is self-service (both modes). CreateUser is admin-only (self-hosted). SaaS admins add members via workspace IAM policy.++7. **`disallow_signup`** — Self-hosted only. Not applicable in SaaS (admin invites via IAM, signup always allowed for new workspace creation).++8. **`allow_without_credential` APIs** — No `GetWorkspaceIDFromContext` in unauthenticated paths. Workspace resolved from entity data or `store.GetWorkspaceID` for self-hosted.diff --git a/docs/plans/saas/06.saas-vs-selfhosted.md b/docs/plans/saas/06.saas-vs-selfhosted.mdnew file mode 100644index 0000000000..6a3634c334--- /dev/null+++ b/docs/plans/saas/06.saas-vs-selfhosted.md@@ -0,0 +1,192 @@+# SaaS vs Self-Hosted Behavior Differences++This document catalogs every code path where SaaS and self-hosted modes diverge, based on `profile.SaaS` checks.++---++## 1. User Management++### CreateUser — `backend/api/v1/user_service.go:192`++- **SaaS**: Blocked (`CodeUnimplemented`). Users are added via workspace IAM policy.+- **Self-hosted**: Allowed with `bb.users.create` permission.++### UpdateUser (other user) — `backend/api/v1/user_service.go:338`++- **SaaS**: Only self-updates allowed. Updating another user's profile returns `CodePermissionDenied` because principals are global (shared across workspaces).+- **Self-hosted**: Admins with `bb.users.update` permission can update other users.++### DeleteUser — `backend/api/v1/user_service.go:490`++- **SaaS**: Blocked (`CodeUnimplemented`).+- **Self-hosted**: Allowed with permission. Checks that at least one workspace admin remains.++### UndeleteUser — `backend/api/v1/user_service.go:577`++- **SaaS**: Blocked (`CodeUnimplemented`).+- **Self-hosted**: Allowed with permission and license checks.++### UpdateEmail — `backend/api/v1/user_service.go:630`++- **SaaS**: Blocked (`CodeUnimplemented`).+- **Self-hosted**: Allowed with `bb.users.updateEmail` permission.++### hasExtraWorkspaceAdmin — `backend/api/v1/user_service.go:555`++- **SaaS**: `allUsers` binding is never counted as admin coverage.+- **Self-hosted**: `allUsers` binding means every principal is an admin; counts all active principals via `CountAllActivePrincipals`.++---++## 2. Authentication & Signup++### Signup — Workspace Resolution — `backend/api/v1/auth_service.go:199-230`++**Finding workspaces** (line 199):+- **SaaS**: `FindWorkspacesByMemberEmail(ctx, email, false)` — only explicit membership.+- **Self-hosted**: `FindWorkspacesByMemberEmail(ctx, email, true)` — includes `allUsers` workspaces.++**Fallback when not a member** (line 208-217):+- **SaaS**: No fallback. If not explicitly a member, `workspaceID` stays empty → new workspace created.+- **Self-hosted**: Falls back to `store.GetWorkspaceID()` to auto-join the single existing workspace.++**DisallowSignup check** (line 220-229):+- **SaaS**: Skipped entirely.+- **Self-hosted**: Checks workspace setting `disallow_signup` (gated by `FEATURE_DISALLOW_SELF_SERVICE_SIGNUP` license).++### Login — Workspace Resolution — `backend/api/v1/auth_service.go:947`++- **SaaS**: `FindWorkspaceIDByMemberEmail(ctx, email, false)` — explicit membership only.+- **Self-hosted**: `FindWorkspaceIDByMemberEmail(ctx, email, true)` — includes `allUsers`.++### Auth Interceptor — `backend/api/auth/auth.go:251`++- **SaaS**: `allUsers` is never a valid principal for workspace membership.+- **Self-hosted**: `allUsers` is valid — any principal is considered a member.++---++## 3. Workspace IAM++### SetWorkspaceIamPolicy — `backend/api/v1/workspace_service.go:70`++- **SaaS**: Rejects any binding containing `allUsers` with error: "allUsers is not allowed in workspace IAM policy in SaaS mode, add members explicitly".+- **Self-hosted**: `allUsers` allowed in bindings.++### IAM Permission Check — `backend/component/iam/manager.go:51`++- **SaaS**: At workspace level, `allUsers` is skipped (`skipAllUsers=true`). At project level, `allUsers` means "all workspace members" (still allowed).+- **Self-hosted**: `allUsers` grants permission at both workspace and project levels.++---++## 4. Settings++### disallow_signup — `backend/api/v1/setting_service.go:210`++- **SaaS**: Cannot be modified. Returns "feature unavailable in current mode".+- **Self-hosted**: Modifiable (gated by license feature `FEATURE_DISALLOW_SELF_SERVICE_SIGNUP`).++### external_url — `backend/api/v1/setting_service.go:220`++- **SaaS**: Cannot be modified. Managed by SaaS operator.+- **Self-hosted**: Modifiable via UI (unless already set by CLI flag `--external-url`).++### IsFeatureUnavailable — `backend/component/config/profile.go:63`++- Uses `saasFeatureControlMap` (currently empty). Reserved for future SaaS-specific feature gating.++---++## 5. Subscription & Licensing++### UpdateSubscription — `backend/api/v1/subscription_service.go:42`++- **SaaS**: Blocked. License managed by operator.+- **Self-hosted**: Allowed via `StoreLicense()`.++### CheckReplicaLimit — `backend/enterprise/license.go:414`++- **SaaS**: Skipped entirely (`return nil`). Replica scaling managed by operator.+- **Self-hosted**: Enforces replica limit based on HA license. Without HA, max 1 replica.++---++## 6. Instance Management++### IAM Credential Validation — `backend/api/v1/instance_service.go:281`++- **SaaS**: Default IAM credentials (Google Cloud SQL, AWS RDS, Azure) are prohibited. Requires explicit credentials with `iam_extension` set.+- **Self-hosted**: All IAM credential types allowed including default credentials.++---++## 7. Sample Instances++### Manager Initialization — `backend/server/server.go:157`++- **SaaS**: `sampleInstanceManager` is not initialized.+- **Self-hosted**: Initialized and loads workspace-dependent settings.++### SetupSample RPC — `backend/api/v1/actuator_service.go:135`++- **SaaS**: Returns empty response immediately.+- **Self-hosted**: Executes sample data generation.++---++## 8. OAuth2++### Legacy Routes — `backend/api/oauth2/oauth2.go:67`++- **SaaS**: Legacy routes (without workspace ID in URL) are not registered.+- **Self-hosted**: Legacy routes (`/api/oauth2/register`, `/api/oauth2/authorize`, etc.) are registered for backwards compatibility.++### Workspace Resolution — `backend/api/oauth2/oauth2.go:82`++- **SaaS**: Requires explicit workspace ID in URL parameter. Returns error if missing.+- **Self-hosted**: Falls back to `store.GetWorkspaceID()` if workspace ID not in URL.++---++## 9. Actuator / System Info++### GetActuatorInfo — `backend/api/v1/actuator_service.go:60`++- **SaaS**: Uses workspace from auth context (URL). No store fallback.+- **Self-hosted**: Falls back to `store.GetWorkspaceID()` to get the single workspace.++### ActuatorInfo Response — `backend/api/v1/actuator_service.go:160`++- Returns `Saas: true/false` in the response so the frontend can adjust its behavior.++---++## 10. Identity Providers++### ListIdentityProviders — `backend/api/v1/idp_service.go:59`++- **SaaS**: Requires workspace ID from auth context. No fallback.+- **Self-hosted**: Falls back to `store.GetWorkspaceID()` for unauthenticated login page (the endpoint is `allow_without_credential`).++---++## Summary Table++| Area | Self-Hosted | SaaS |+|------|-------------|------|+| **CreateUser** | Allowed (with permission) | Blocked — use workspace IAM |+| **UpdateUser (other)** | Allowed (with permission) | Self-updates only |+| **DeleteUser / UndeleteUser / UpdateEmail** | Allowed (with permission) | Blocked |+| **Signup: workspace resolution** | Includes `allUsers`, auto-joins existing | Explicit membership only, creates new workspace |+| **Signup: disallow_signup** | Enforced (with license) | Skipped |+| **Workspace IAM: allUsers** | Allowed | Blocked |+| **IAM permission: allUsers** | Grants permission at workspace + project level | Skipped at workspace level, allowed at project level |+| **disallow_signup setting** | Configurable | Cannot modify |+| **external_url setting** | Configurable | Cannot modify |+| **License updates** | Allowed | Blocked |+| **Replica limit** | Enforced by license | Skipped (operator-managed) |+| **IAM credentials** | Default credentials allowed | Explicit credentials required |+| **Sample instances** | Available | Disabled |+| **OAuth2 legacy routes** | Registered | Not registered |+| **Workspace ID resolution** | Falls back to store | Required in URL/auth context |diff --git a/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue b/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vueindex ecc56cf22f..ca7d556859 100644--- a/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue+++ b/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue@@ -37,7 +37,7 @@:link="false"/><EnvironmentV1Name- class="ml-1 text-sm text-gray-400 max-w-[124px]"+ class="ml-1 text-sm text-gray-400 max-w-31":environment="getDatabaseEnvironment(database)":link="false"/>diff --git a/frontend/src/components/EnvironmentForm/Form.vue b/frontend/src/components/EnvironmentForm/Form.vueindex f476bbbb84..15c2245008 100644--- a/frontend/src/components/EnvironmentForm/Form.vue+++ b/frontend/src/components/EnvironmentForm/Form.vue@@ -222,6 +222,7 @@ const {const environmentStore = useEnvironmentV1Store();const instanceStore = useInstanceV1Store();const databaseStore = useDatabaseV1Store();+const actuatorStore = useActuatorV1Store();const hasGetPolicyPermission = computed(() => {return hasWorkspacePermissionV2("bb.policies.get");@@ -279,7 +280,7 @@ const fetchDatabases = async () => {try {const resp = await databaseStore.fetchDatabases({pageSize: 1,- parent: useActuatorV1Store().workspaceResourceName,+ parent: actuatorStore.workspaceResourceName,filter: {environment: environment.value.name,},diff --git a/frontend/src/components/GeneralSetting/GeneralSetting.vue b/frontend/src/components/GeneralSetting/GeneralSetting.vueindex 2ebd9312b2..676456dfb5 100644--- a/frontend/src/components/GeneralSetting/GeneralSetting.vue+++ b/frontend/src/components/GeneralSetting/GeneralSetting.vue@@ -12,7 +12,7 @@v-model:mode="state.databaseChangeMode"/>- <div v-if="!isSaaSMode">+ <div><label class="flex items-center gap-x-2"><span class="font-medium">{{$t("settings.general.workspace.external-url.self")@@ -24,7 +24,7 @@url="https://docs.bytebase.com/get-started/self-host/external-url?source=console"/></div>- <div v-if="externalUrlFromFlag" class="mb-2 text-sm text-accent">+ <div v-if="externalUrlFromFlag && !isSaaSMode" class="mb-2 text-sm text-accent">{{ $t("settings.general.workspace.external-url.managed-by-flag") }}</div><PermissionGuardWrapperdiff --git a/frontend/src/components/Project/ProjectArchiveRestoreButton.vue b/frontend/src/components/Project/ProjectArchiveRestoreButton.vuedeleted file mode 100644index fd0c898be0..0000000000--- a/frontend/src/components/Project/ProjectArchiveRestoreButton.vue+++ /dev/null@@ -1,82 +0,0 @@-<template>- <div- v-if="allowArchiveOrRestore"- class="w-full flex items-center justify-between"- >- <template v-if="project.state === State.ACTIVE">- <BBButtonConfirm- :type="'ARCHIVE'"- :button-text="$t('project.settings.archive.btn-text')"- :ok-text="$t('common.archive')"- :confirm-title="- $t('project.settings.archive.title') + ` '${project.title}'?`- "- :confirm-description="$t('project.settings.archive.description')"- :require-confirm="true"- @confirm="archiveOrRestoreProject(true)"- />- </template>- <template v-else-if="project.state === State.DELETED">- <BBButtonConfirm- :type="'RESTORE'"- :button-text="$t('project.settings.restore.btn-text')"- :ok-text="$t('common.restore')"- :confirm-title="- $t('project.settings.restore.title') + ` '${project.title}'?`- "- :confirm-description="''"- :require-confirm="true"- @confirm="archiveOrRestoreProject(false)"- />- </template>- <ResourceHardDeleteButton :resource="project" @delete="hardDeleteProject" />- </div>-</template>--<script setup lang="ts">-import { computed } from "vue";-import { useRouter } from "vue-router";-import { BBButtonConfirm } from "@/bbkit";-import ResourceHardDeleteButton from "@/components/v2/Button/ResourceHardDeleteButton.vue";-import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";-import { useProjectV1Store } from "@/store";-import { State } from "@/types/proto-es/v1/common_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { hasWorkspacePermissionV2 } from "@/utils";--const props = defineProps<{- project: Project;-}>();--const projectV1Store = useProjectV1Store();-const router = useRouter();--const allowArchiveOrRestore = computed(() => {- if (props.project.state === State.ACTIVE) {- return hasWorkspacePermissionV2("bb.projects.delete");- }- return hasWorkspacePermissionV2("bb.projects.undelete");-});--const archiveOrRestoreProject = async (archive: boolean) => {- if (archive) {- await projectV1Store.archiveProject(props.project);- } else {- await projectV1Store.restoreProject(props.project);- }-- if (archive) {- router.replace({- name: PROJECT_V1_ROUTE_DASHBOARD,- });- }-};--const hardDeleteProject = async (resource: string) => {- await projectV1Store.deleteProject(resource);- router.replace({- name: PROJECT_V1_ROUTE_DASHBOARD,- query: { q: "state:DELETED" },- });-};-</script>diff --git a/frontend/src/components/ProjectSettingPanel.vue b/frontend/src/components/ProjectSettingPanel.vueindex efa4ad6866..36a6ffbca5 100644--- a/frontend/src/components/ProjectSettingPanel.vue+++ b/frontend/src/components/ProjectSettingPanel.vue@@ -75,17 +75,27 @@{{ $t('common.archive-description', { name: project.title || project.name }) }}</p></div>- <BBButtonConfirm- type="ARCHIVE"- :button-text="$t('common.archive')"- :confirm-title="$t('common.confirm-archive')"- :confirm-description="- $t('project.settings.confirm-archive-project', { name: project.title || project.name })- "- :require-confirm="true"- :disabled="dangerZoneState.isExecuting"- @confirm="handleArchive"- />+ <PermissionGuardWrapper+ v-slot="slotProps"+ :project="project"+ :permissions="[+ 'bb.projects.delete'+ ]"+ >+ <div>+ <BBButtonConfirm+ type="ARCHIVE"+ :button-text="$t('common.archive')"+ :confirm-title="$t('common.confirm-archive')"+ :confirm-description="+ $t('project.settings.confirm-archive-project', { name: project.title || project.name })+ "+ :require-confirm="true"+ :disabled="dangerZoneState.isExecuting || slotProps.disabled"+ @confirm="handleArchive"+ />+ </div>+ </PermissionGuardWrapper></template><template v-else-if="project.state === State.DELETED"><div class="flex-1">@@ -96,17 +106,27 @@{{ $t('project.settings.restore.btn-text') }}</p></div>- <BBButtonConfirm- type="RESTORE"- :button-text="$t('common.restore')"- :confirm-title="$t('project.settings.restore.title')"- :confirm-description="- $t('project.settings.restore.title') + ` '${project.title || project.name}'?`- "- :require-confirm="true"- :disabled="dangerZoneState.isExecuting"- @confirm="handleRestore"- />+ <PermissionGuardWrapper+ v-slot="slotProps"+ :project="project"+ :permissions="[+ 'bb.projects.undelete'+ ]"+ >+ <div>+ <BBButtonConfirm+ type="RESTORE"+ :button-text="$t('common.restore')"+ :confirm-title="$t('project.settings.restore.title')"+ :confirm-description="+ $t('project.settings.restore.title') + ` '${project.title || project.name}'?`+ "+ :require-confirm="true"+ :disabled="dangerZoneState.isExecuting || slotProps.disabled"+ @confirm="handleRestore"+ />+ </div>+ </PermissionGuardWrapper></template></div>@@ -120,17 +140,27 @@{{ $t('common.delete-resource-description', { name: project.title || project.name }) }}</p></div>- <BBButtonConfirm- type="DELETE"- :button-text="$t('common.delete')"- :confirm-title="$t('common.confirm-delete')"- :confirm-description="- $t('project.settings.confirm-delete-project', { name: project.title || project.name })- "- :require-confirm="true"- :disabled="dangerZoneState.isExecuting"- @confirm="handleDelete"- />+ <PermissionGuardWrapper+ v-slot="slotProps"+ :project="project"+ :permissions="[+ 'bb.projects.delete'+ ]"+ >+ <div>+ <BBButtonConfirm+ type="DELETE"+ :button-text="$t('common.delete')"+ :confirm-title="$t('common.confirm-delete')"+ :confirm-description="+ $t('project.settings.confirm-delete-project', { name: project.title || project.name })+ "+ :require-confirm="true"+ :disabled="dangerZoneState.isExecuting || slotProps.disabled"+ @confirm="handleDelete"+ />+ </div>+ </PermissionGuardWrapper></div></div></div>diff --git a/frontend/src/components/v2/Select/DatabaseSelect.vue b/frontend/src/components/v2/Select/DatabaseSelect.vueindex 9091d7d2a6..f24a1eb3c9 100644--- a/frontend/src/components/v2/Select/DatabaseSelect.vue+++ b/frontend/src/components/v2/Select/DatabaseSelect.vue@@ -19,8 +19,7 @@import { computedAsync } from "@vueuse/core";import { computed } from "vue";import { RichDatabaseName } from "@/components/v2";-import { useDatabaseV1Store } from "@/store";-import { workspaceNamePrefix } from "@/store/modules/v1/common";+import { useActuatorV1Store, useDatabaseV1Store } from "@/store";import { type Engine } from "@/types/proto-es/v1/common_pb";import type { Database } from "@/types/proto-es/v1/database_service_pb";import { extractDatabaseResourceName } from "@/utils";@@ -58,6 +57,7 @@ defineEmits<{}>();const databaseStore = useDatabaseV1Store();+const actuatorStore = useActuatorV1Store();const getOption = (db: Database) => {return {@@ -89,7 +89,7 @@ const handleSearch = async (params: {pageSize: number;}) => {const { databases, nextPageToken } = await databaseStore.fetchDatabases({- parent: props.projectName ?? `${workspaceNamePrefix}-`,+ parent: props.projectName ?? actuatorStore.workspaceResourceName,filter: {environment: props.environmentName,engines: props.allowedEngineTypeList,diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 7d4b274e6c..6d80ffc972 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1861,11 +1861,6 @@"success-updated": "Project settings updated successfully.","update-failed": "Failed to update the project setting.","success-member-added-prompt": "Successfully added to the project.",- "archive": {- "title": "Archive project",- "description": "Archived projects will not be displayed.",- "btn-text": "Archive this @.lower:{'common.project'}"- },"restore": {"title": "Restore project","btn-text": "Restore this @.lower:{'common.project'}"diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 7636511ebc..828d86dd02 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1861,11 +1861,6 @@"success-updated": "La configuración del proyecto se actualizó correctamente.","update-failed": "No se pudo actualizar la configuración del proyecto.","success-member-added-prompt": "Se agregó correctamente al proyecto.",- "archive": {- "title": "Archivar proyecto",- "description": "Proyectos archivados no se mostrarán.",- "btn-text": "Archivar este @.lower:{'common.project'}"- },"restore": {"title": "Restaurar proyecto","btn-text": "Restaurar este @.lower:{'common.project'}"diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex a7d2b742ba..e467642225 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1861,11 +1861,6 @@"success-updated": "プロジェクト設定が正常に更新されました","update-failed": "プロジェクト設定の更新に失敗しました。","success-member-added-prompt": "現在のプロジェクトに正常に追加されました。",- "archive": {- "title": "アーカイブアイテム",- "description": "アーカイブされたアイテムは表示されなくなります。",- "btn-text": "この @:common.project をアーカイブする"- },"restore": {"title": "アイテムを復元する","btn-text": "この @:common.project を復元します"diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex e2e873c094..240a9e3669 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1861,11 +1861,6 @@"success-updated": "Đã cập nhật thành công cài đặt dự án.","update-failed": "Không cập nhật được cài đặt dự án.","success-member-added-prompt": "Đã thêm thành công vào dự án.",- "archive": {- "title": "Lưu trữ dự án",- "description": "Các dự án đã lưu trữ sẽ không được hiển thị.",- "btn-text": "Lưu trữ @.lower:{'common.project'} này"- },"restore": {"title": "Khôi phục dự án","btn-text": "Khôi phục @.lower:{'common.project'} này"diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 0804a2f7d1..bee5b409f0 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1861,11 +1861,6 @@"success-updated": "项目设置更新成功","update-failed": "无法更新项目设置。","success-member-added-prompt": "成功添加到当前项目中.",- "archive": {- "title": "归档项目",- "description": "已归档项目将不再显示。",- "btn-text": "归档这个@:common.project"- },"restore": {"title": "恢复项目","btn-text": "恢复这个@:common.project"diff --git a/frontend/src/store/modules/v1/actuator.ts b/frontend/src/store/modules/v1/actuator.tsindex 0df4be83d3..b8fd96cbdf 100644--- a/frontend/src/store/modules/v1/actuator.ts+++ b/frontend/src/store/modules/v1/actuator.ts@@ -37,10 +37,8 @@ export const useActuatorV1Store = defineStore("actuator_v1", () => {});const appProfile = ref<AppProfile>(defaultAppProfile());const onboardingState = useLocalStorage<{- isOnboarding: boolean;consumed: string[];}>(STORAGE_KEY_ONBOARDING, {- isOnboarding: false,consumed: [],});@@ -84,10 +82,6 @@ export const useActuatorV1Store = defineStore("actuator_v1", () => {() => serverInfo.value?.workspace ?? "");- const needAdminSetup = computed(- () => serverInfo.value?.needAdminSetup || false- );-const needConfigureExternalUrl = computed(() => {if (!serverInfo.value) return false;const url = serverInfo.value?.externalUrl ?? "";@@ -119,6 +113,10 @@ export const useActuatorV1Store = defineStore("actuator_v1", () => {() => serverInfo.value?.activatedUserCount ?? 0);+ const enableOnboarding = computed(() => {+ return activeUserCount.value === 1 && !isSaaSMode.value;+ });+const updateUserStat = (count: number) => {if (!serverInfo.value) {return;@@ -261,15 +259,15 @@ export const useActuatorV1Store = defineStore("actuator_v1", () => {isDocker,isSaaSMode,workspaceResourceName,- needAdminSetup,needConfigureExternalUrl,hasNewRelease,activatedInstanceCount,totalInstanceCount,replicaCount,quickStartEnabled,- // Actions+ enableOnboarding,activeUserCount,+ // ActionsupdateUserStat,setLogo,setServerInfo,diff --git a/frontend/src/store/modules/v1/auth.ts b/frontend/src/store/modules/v1/auth.tsindex e34eb4add6..66f03d9acb 100644--- a/frontend/src/store/modules/v1/auth.ts+++ b/frontend/src/store/modules/v1/auth.ts@@ -161,8 +161,7 @@ export const useAuthStore = defineStore("auth_v1", () => {await actuatorStore.fetchServerInfo(user?.workspace);authSessionKey.value = uniqueId();- if (actuatorStore.needAdminSetup) {- actuatorStore.onboardingState.isOnboarding = true;+ if (actuatorStore.enableOnboarding) {return router.replace({ name: SETUP_MODULE });}diff --git a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts b/frontend/src/types/proto-es/v1/actuator_service_pb.d.tsindex 4f1bebc674..03d5b2be69 100644--- a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts@@ -210,13 +210,6 @@ export declare type ActuatorInfo = Message<"bytebase.v1.ActuatorInfo"> & {*/externalUrl: string;- /**- * Whether the Bytebase instance requires initial admin setup.- *- * @generated from field: bool need_admin_setup = 9;- */- needAdminSetup: boolean;-/*** The last time any API call was made, refreshed on each request.*diff --git a/frontend/src/types/proto-es/v1/actuator_service_pb.js b/frontend/src/types/proto-es/v1/actuator_service_pb.jsindex 99ab91cd5d..63a4e13e3f 100644--- a/frontend/src/types/proto-es/v1/actuator_service_pb.js+++ b/frontend/src/types/proto-es/v1/actuator_service_pb.js@@ -15,7 +15,7 @@ import { file_v1_setting_service } from "./setting_service_pb";* Describes the file v1/actuator_service.proto.*/export const file_v1_actuator_service = /*@__PURE__*/- fileDesc("Chl2MS9hY3R1YXRvcl9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSIpChlHZXRSZXNvdXJjZVBhY2thZ2VSZXF1ZXN0EgwKBG5hbWUYASABKAkiHwoPUmVzb3VyY2VQYWNrYWdlEgwKBGxvZ28YASABKAwiFAoSU2V0dXBTYW1wbGVSZXF1ZXN0IhgKFkdldEFjdHVhdG9ySW5mb1JlcXVlc3QiTwofR2V0V29ya3NwYWNlQWN0dWF0b3JJbmZvUmVxdWVzdBIsCgRuYW1lGAEgASgJQh7gQQL6QRgKFmJ5dGViYXNlLmNvbS9Xb3Jrc3BhY2UiFAoSRGVsZXRlQ2FjaGVSZXF1ZXN0Iq8BCgtSZXN0cmljdGlvbhIcCg9kaXNhbGxvd19zaWdudXAYASABKAhCA+BBAxIlChhkaXNhbGxvd19wYXNzd29yZF9zaWduaW4YAiABKAhCA+BBAxJbChRwYXNzd29yZF9yZXN0cmljdGlvbhgDIAEoCzI4LmJ5dGViYXNlLnYxLldvcmtzcGFjZVByb2ZpbGVTZXR0aW5nLlBhc3N3b3JkUmVzdHJpY3Rpb25CA+BBAyKeBQoMQWN0dWF0b3JJbmZvEhQKB3ZlcnNpb24YASABKAlCA+BBAxIXCgpnaXRfY29tbWl0GAIgASgJQgPgQQMSFQoIcmVhZG9ubHkYAyABKAhCA+BBAxIRCgRzYWFzGAQgASgIQgPgQQMSEQoEZGVtbxgFIAEoCEID4EEDEhEKBGhvc3QYBiABKAlCA+BBAxIRCgRwb3J0GAcgASgJQgPgQQMSGQoMZXh0ZXJuYWxfdXJsGAggASgJQgPgQQMSHQoQbmVlZF9hZG1pbl9zZXR1cBgJIAEoCEID4EEDEjkKEGxhc3RfYWN0aXZlX3RpbWUYCyABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wQgPgQQMSFgoJd29ya3NwYWNlGA0gASgJQgPgQQMSIAoTdW5saWNlbnNlZF9mZWF0dXJlcxgPIAMoCUID4EEDEhMKBmRvY2tlchgSIAEoCEID4EEDEiEKFGFjdGl2YXRlZF91c2VyX2NvdW50GBMgASgFQgPgQQMSJQoYYWN0aXZhdGVkX2luc3RhbmNlX2NvdW50GBQgASgFQgPgQQMSIQoUdG90YWxfaW5zdGFuY2VfY291bnQYFSABKAVCA+BBAxIaCg1lbmFibGVfc2FtcGxlGBYgASgIQgPgQQMSIwoWZXh0ZXJuYWxfdXJsX2Zyb21fZmxhZxgXIAEoCEID4EEDEhoKDXJlcGxpY2FfY291bnQYGCABKAVCA+BBAxIyCgtyZXN0cmljdGlvbhgZIAEoCzIYLmJ5dGViYXNlLnYxLlJlc3RyaWN0aW9uQgPgQQMSHAoPZGVmYXVsdF9wcm9qZWN0GBogASgJQgPgQQNKBAgKEAtKBAgMEA1KBAgQEBFKBAgREBJKBAgOEA8y6AUKD0FjdHVhdG9yU2VydmljZRJzCg9HZXRBY3R1YXRvckluZm8SIy5ieXRlYmFzZS52MS5HZXRBY3R1YXRvckluZm9SZXF1ZXN0GhkuYnl0ZWJhc2UudjEuQWN0dWF0b3JJbmZvIiDaQQCA6jABgtPkkwITEhEvdjEvYWN0dWF0b3IvaW5mbxKCAQoLU2V0dXBTYW1wbGUSHy5ieXRlYmFzZS52MS5TZXR1cFNhbXBsZVJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiOorqMBJiYi5wcm9qZWN0cy5jcmVhdGWQ6jABgtPkkwIaIhgvdjEvYWN0dWF0b3I6c2V0dXBTYW1wbGUSZgoLRGVsZXRlQ2FjaGUSHy5ieXRlYmFzZS52MS5EZWxldGVDYWNoZVJlcXVlc3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiHoDqMAGC0+STAhQqEi92MS9hY3R1YXRvci9jYWNoZRKvAQoSR2V0UmVzb3VyY2VQYWNrYWdlEiYuYnl0ZWJhc2UudjEuR2V0UmVzb3VyY2VQYWNrYWdlUmVxdWVzdBocLmJ5dGViYXNlLnYxLlJlc291cmNlUGFja2FnZSJT2kEAgOowAYLT5JMCRlosEiovdjEve25hbWU9d29ya3NwYWNlcy8qfS9hY3R1YXRvci9yZXNvdXJjZXMSFi92MS9hY3R1YXRvci9yZXNvdXJjZXMSwAEKGEdldFdvcmtzcGFjZUFjdHVhdG9ySW5mbxIsLmJ5dGViYXNlLnYxLkdldFdvcmtzcGFjZUFjdHVhdG9ySW5mb1JlcXVlc3QaGS5ieXRlYmFzZS52MS5BY3R1YXRvckluZm8iW9pBBG5hbWWK6jAfYmIuc2V0dGluZ3MuZ2V0V29ya3NwYWNlUHJvZmlsZZDqMAGC0+STAicSJS92MS97bmFtZT13b3Jrc3BhY2VzLyp9L2FjdHVhdG9yL2luZm9CqgEKD2NvbS5ieXRlYmFzZS52MUIUQWN0dWF0b3JTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_timestamp, file_v1_annotation, file_v1_setting_service]);+ fileDesc("Chl2MS9hY3R1YXRvcl9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSIpChlHZXRSZXNvdXJjZVBhY2thZ2VSZXF1ZXN0EgwKBG5hbWUYASABKAkiHwoPUmVzb3VyY2VQYWNrYWdlEgwKBGxvZ28YASABKAwiFAoSU2V0dXBTYW1wbGVSZXF1ZXN0IhgKFkdldEFjdHVhdG9ySW5mb1JlcXVlc3QiTwofR2V0V29ya3NwYWNlQWN0dWF0b3JJbmZvUmVxdWVzdBIsCgRuYW1lGAEgASgJQh7gQQL6QRgKFmJ5dGViYXNlLmNvbS9Xb3Jrc3BhY2UiFAoSRGVsZXRlQ2FjaGVSZXF1ZXN0Iq8BCgtSZXN0cmljdGlvbhIcCg9kaXNhbGxvd19zaWdudXAYASABKAhCA+BBAxIlChhkaXNhbGxvd19wYXNzd29yZF9zaWduaW4YAiABKAhCA+BBAxJbChRwYXNzd29yZF9yZXN0cmljdGlvbhgDIAEoCzI4LmJ5dGViYXNlLnYxLldvcmtzcGFjZVByb2ZpbGVTZXR0aW5nLlBhc3N3b3JkUmVzdHJpY3Rpb25CA+BBAyKFBQoMQWN0dWF0b3JJbmZvEhQKB3ZlcnNpb24YASABKAlCA+BBAxIXCgpnaXRfY29tbWl0GAIgASgJQgPgQQMSFQoIcmVhZG9ubHkYAyABKAhCA+BBAxIRCgRzYWFzGAQgASgIQgPgQQMSEQoEZGVtbxgFIAEoCEID4EEDEhEKBGhvc3QYBiABKAlCA+BBAxIRCgRwb3J0GAcgASgJQgPgQQMSGQoMZXh0ZXJuYWxfdXJsGAggASgJQgPgQQMSOQoQbGFzdF9hY3RpdmVfdGltZRgLIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIWCgl3b3Jrc3BhY2UYDSABKAlCA+BBAxIgChN1bmxpY2Vuc2VkX2ZlYXR1cmVzGA8gAygJQgPgQQMSEwoGZG9ja2VyGBIgASgIQgPgQQMSIQoUYWN0aXZhdGVkX3VzZXJfY291bnQYEyABKAVCA+BBAxIlChhhY3RpdmF0ZWRfaW5zdGFuY2VfY291bnQYFCABKAVCA+BBAxIhChR0b3RhbF9pbnN0YW5jZV9jb3VudBgVIAEoBUID4EEDEhoKDWVuYWJsZV9zYW1wbGUYFiABKAhCA+BBAxIjChZleHRlcm5hbF91cmxfZnJvbV9mbGFnGBcgASgIQgPgQQMSGgoNcmVwbGljYV9jb3VudBgYIAEoBUID4EEDEjIKC3Jlc3RyaWN0aW9uGBkgASgLMhguYnl0ZWJhc2UudjEuUmVzdHJpY3Rpb25CA+BBAxIcCg9kZWZhdWx0X3Byb2plY3QYGiABKAlCA+BBA0oECAkQCkoECAoQC0oECAwQDUoECBAQEUoECBEQEkoECA4QDzLoBQoPQWN0dWF0b3JTZXJ2aWNlEnMKD0dldEFjdHVhdG9ySW5mbxIjLmJ5dGViYXNlLnYxLkdldEFjdHVhdG9ySW5mb1JlcXVlc3QaGS5ieXRlYmFzZS52MS5BY3R1YXRvckluZm8iINpBAIDqMAGC0+STAhMSES92MS9hY3R1YXRvci9pbmZvEoIBCgtTZXR1cFNhbXBsZRIfLmJ5dGViYXNlLnYxLlNldHVwU2FtcGxlUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSI6iuowEmJiLnByb2plY3RzLmNyZWF0ZZDqMAGC0+STAhoiGC92MS9hY3R1YXRvcjpzZXR1cFNhbXBsZRJmCgtEZWxldGVDYWNoZRIfLmJ5dGViYXNlLnYxLkRlbGV0ZUNhY2hlUmVxdWVzdBoWLmdvb2dsZS5wcm90b2J1Zi5FbXB0eSIegOowAYLT5JMCFCoSL3YxL2FjdHVhdG9yL2NhY2hlEq8BChJHZXRSZXNvdXJjZVBhY2thZ2USJi5ieXRlYmFzZS52MS5HZXRSZXNvdXJjZVBhY2thZ2VSZXF1ZXN0GhwuYnl0ZWJhc2UudjEuUmVzb3VyY2VQYWNrYWdlIlPaQQCA6jABgtPkkwJGWiwSKi92MS97bmFtZT13b3Jrc3BhY2VzLyp9L2FjdHVhdG9yL3Jlc291cmNlcxIWL3YxL2FjdHVhdG9yL3Jlc291cmNlcxLAAQoYR2V0V29ya3NwYWNlQWN0dWF0b3JJbmZvEiwuYnl0ZWJhc2UudjEuR2V0V29ya3NwYWNlQWN0dWF0b3JJbmZvUmVxdWVzdBoZLmJ5dGViYXNlLnYxLkFjdHVhdG9ySW5mbyJb2kEEbmFtZYrqMB9iYi5zZXR0aW5ncy5nZXRXb3Jrc3BhY2VQcm9maWxlkOowAYLT5JMCJxIlL3YxL3tuYW1lPXdvcmtzcGFjZXMvKn0vYWN0dWF0b3IvaW5mb0KqAQoPY29tLmJ5dGViYXNlLnYxQhRBY3R1YXRvclNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_timestamp, file_v1_annotation, file_v1_setting_service]);/*** Describes the message bytebase.v1.GetResourcePackageRequest.diff --git a/frontend/src/views/SettingWorkspaceGeneral.vue b/frontend/src/views/SettingWorkspaceGeneral.vueindex 6e364dba1f..dc14d85321 100644--- a/frontend/src/views/SettingWorkspaceGeneral.vue+++ b/frontend/src/views/SettingWorkspaceGeneral.vue@@ -29,6 +29,7 @@:title="$t('settings.general.workspace.announcement.self')"/><PermissionGuardWrapper+ v-if="!actuatorStore.isSaaSMode"v-slot="slotProps":permissions="['bb.settings.setWorkspaceProfile'@@ -40,6 +41,7 @@/></PermissionGuardWrapper><PermissionGuardWrapper+ v-if="!actuatorStore.isSaaSMode"v-slot="slotProps":permissions="['bb.settings.setWorkspaceProfile'@@ -84,10 +86,11 @@ import {} from "@/components/GeneralSetting";import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";import { useRouteChangeGuard } from "@/composables/useRouteChangeGuard";-import { pushNotification } from "@/store";+import { pushNotification, useActuatorV1Store } from "@/store";const route = useRoute();const { t } = useI18n();+const actuatorStore = useActuatorV1Store();const accountSettingRef = ref<InstanceType<typeof AccountSetting>>();const generalSettingRef = ref<InstanceType<typeof GeneralSetting>>();diff --git a/frontend/src/views/Setup/AdminSetup.vue b/frontend/src/views/Setup/AdminSetup.vueindex c10727b8a9..49a11b6eb6 100644--- a/frontend/src/views/Setup/AdminSetup.vue+++ b/frontend/src/views/Setup/AdminSetup.vue@@ -181,7 +181,6 @@ const changeStepIndex = (nextIndex: number) => {};const onCancel = (to: RouteLocationRaw) => {- actuatorV1Store.onboardingState.isOnboarding = false;router.push(to);};@@ -221,7 +220,7 @@ const tryFinishSetup = async () => {};onMounted(async () => {- if (!actuatorV1Store.onboardingState.isOnboarding) {+ if (!actuatorV1Store.enableOnboarding) {const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");return onCancel(getHomePageByMode(databaseChangeMode.value));}diff --git a/frontend/src/views/auth/Signin.vue b/frontend/src/views/auth/Signin.vueindex 871cf3eb28..c10b67f968 100644--- a/frontend/src/views/auth/Signin.vue+++ b/frontend/src/views/auth/Signin.vue@@ -275,7 +275,7 @@ watchEffect(() => {// Unable to achieve it in router.beforeEach because actuator/info is fetched async and returns// after router has already made the decision on first page load.if (- actuatorStore.needAdminSetup &&+ actuatorStore.activeUserCount === 0 &&!disallowSignup.value &&!isSaaSMode.value) {diff --git a/frontend/src/views/auth/Signup.vue b/frontend/src/views/auth/Signup.vueindex 577379caec..9294e3bb49 100644--- a/frontend/src/views/auth/Signup.vue+++ b/frontend/src/views/auth/Signup.vue@@ -176,7 +176,9 @@ const state = reactive<LocalState>({isLoading: false,});-const { needAdminSetup, serverInfo } = storeToRefs(actuatorStore);+const { activeUserCount, serverInfo } = storeToRefs(actuatorStore);++const needAdminSetup = computed(() => activeUserCount.value === 0);const allowSignup = computed(() => {return (diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex e1cf4ea6f3..b4feb288b0 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -16446,11 +16446,6 @@ components:title: external_urldescription: The external URL where users or webhook callbacks access Bytebase.readOnly: true- needAdminSetup:- type: boolean- title: need_admin_setup- description: Whether the Bytebase instance requires initial admin setup.- readOnly: truelastActiveTime:title: last_active_timedescription: The last time any API call was made, refreshed on each request.diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex 43ce37a1c0..070b0a7635 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -5212,6 +5212,7 @@ MFAConfig is the MFA configuration for a user.| last_login_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | || last_change_password_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | || source | [string](#string) | | The source indicates where the user comes from. For now we support Entra ID SCIM sync, so the source could be Entra ID. |+| last_login_workspace | [string](#string) | | The workspace resource ID the user last logged into. Used to auto-select workspace on next login instead of requiring a workspace picker. |diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex 70fdaf1e1c..e4586bda8d 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -13925,6 +13925,14 @@ Example: For "SELECT 你好;" in a UTF-8 sheet, range [0, 13) represents<td><p>The source indicates where the user comes from. For now we support Entra ID SCIM sync, so the source could be Entra ID. </p></td></tr>+ <tr>+ <td>last_login_workspace</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>The workspace resource ID the user last logged into.+Used to auto-select workspace on next login instead of requiring a workspace picker. </p></td>+ </tr>+</tbody></table>diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex fd8f1c2f1c..a1b576d81e 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -2549,7 +2549,6 @@ Actuator concept is similar to the Spring Boot Actuator.| host | [string](#string) | | The host address of the Bytebase instance. || port | [string](#string) | | The port number of the Bytebase instance. || external_url | [string](#string) | | The external URL where users or webhook callbacks access Bytebase. |-| need_admin_setup | [bool](#bool) | | Whether the Bytebase instance requires initial admin setup. || last_active_time | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | The last time any API call was made, refreshed on each request. || workspace | [string](#string) | | The unique identifier for the workspace. Format: workspaces/{id} || unlicensed_features | [string](#string) | repeated | List of features that are not licensed. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex b3fe635fa6..7208f696a9 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -7843,13 +7843,6 @@ Permissions required: bb.settings.set</p></td><td><p>The external URL where users or webhook callbacks access Bytebase. </p></td></tr>- <tr>- <td>need_admin_setup</td>- <td><a href="#bool">bool</a></td>- <td></td>- <td><p>Whether the Bytebase instance requires initial admin setup. </p></td>- </tr>-<tr><td>last_active_time</td><td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>diff --git a/proto/store/store/user.proto b/proto/store/store/user.protoindex a91102982e..d223e91946 100644--- a/proto/store/store/user.proto+++ b/proto/store/store/user.proto@@ -41,6 +41,9 @@ message UserProfile {// The source indicates where the user comes from. For now we support Entra ID SCIM sync, so the source could be Entra ID.string source = 3;reserved 4;+ // The workspace resource ID the user last logged into.+ // Used to auto-select workspace on next login instead of requiring a workspace picker.+ string last_login_workspace = 5;}// WorkloadIdentityConfig stores OIDC configuration for workload identity.diff --git a/proto/v1/v1/actuator_service.proto b/proto/v1/v1/actuator_service.protoindex 0d1e93ed8a..5a96fc7d3a 100644--- a/proto/v1/v1/actuator_service.proto+++ b/proto/v1/v1/actuator_service.proto@@ -106,7 +106,7 @@ message Restriction {// System information and configuration for the Bytebase instance.// Actuator concept is similar to the Spring Boot Actuator.message ActuatorInfo {- reserved 10, 12, 16, 17, 14;+ reserved 9, 10, 12, 16, 17, 14;// The Bytebase server version.string version = 1 [(google.api.field_behavior) = OUTPUT_ONLY];@@ -132,9 +132,6 @@ message ActuatorInfo {// The external URL where users or webhook callbacks access Bytebase.string external_url = 8 [(google.api.field_behavior) = OUTPUT_ONLY];- // Whether the Bytebase instance requires initial admin setup.- bool need_admin_setup = 9 [(google.api.field_behavior) = OUTPUT_ONLY];-// The last time any API call was made, refreshed on each request.google.protobuf.Timestamp last_active_time = 11 [(google.api.field_behavior) = OUTPUT_ONLY];