Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: prepare subscription table (#19739)
ecmadao76e74164f704
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex fd262458d1..1da1d0f71c 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -20665,6 +20665,8 @@ components:documentation for additional information.security: []tags:+ - name: bytebase.v1.SubscriptionService+ description: SubscriptionService manages enterprise subscriptions and licensing.- name: bytebase.v1.AccessGrantServicedescription: AccessGrantService manages temporary access grants within projects.- name: bytebase.v1.IssueService@@ -20719,8 +20721,6 @@ tags:description: ServiceAccountService manages service accounts for API integrations.- name: bytebase.v1.SheetServicedescription: SheetService manages SQL scripts and saved queries.- - name: bytebase.v1.SubscriptionService- description: SubscriptionService manages enterprise subscriptions and licensing.- name: bytebase.v1.WorkloadIdentityServicedescription: WorkloadIdentityService manages workload identities for external CI/CD integrations.- name: bytebase.v1.WorksheetServicediff --git a/backend/generated-go/store/subscription.pb.go b/backend/generated-go/store/subscription.pb.gonew file mode 100644index 0000000000..77a5c3db92--- /dev/null+++ b/backend/generated-go/store/subscription.pb.go@@ -0,0 +1,384 @@+// Code generated by protoc-gen-go. DO NOT EDIT.+// versions:+// protoc-gen-go v1.36.11+// protoc (unknown)+// source: store/subscription.proto++package store++import (+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"+ timestamppb "google.golang.org/protobuf/types/known/timestamppb"+ reflect "reflect"+ sync "sync"+ unsafe "unsafe"+)++const (+ // Verify that this generated code is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)+ // Verify that runtime/protoimpl is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)+)++type SubscriptionPayload_Status int32++const (+ SubscriptionPayload_STATUS_UNSPECIFIED SubscriptionPayload_Status = 0+ SubscriptionPayload_PENDING SubscriptionPayload_Status = 1+ SubscriptionPayload_ACTIVE SubscriptionPayload_Status = 2+ SubscriptionPayload_PAUSED SubscriptionPayload_Status = 3+ SubscriptionPayload_CANCELED SubscriptionPayload_Status = 4+)++// Enum value maps for SubscriptionPayload_Status.+var (+ SubscriptionPayload_Status_name = map[int32]string{+ 0: "STATUS_UNSPECIFIED",+ 1: "PENDING",+ 2: "ACTIVE",+ 3: "PAUSED",+ 4: "CANCELED",+ }+ SubscriptionPayload_Status_value = map[string]int32{+ "STATUS_UNSPECIFIED": 0,+ "PENDING": 1,+ "ACTIVE": 2,+ "PAUSED": 3,+ "CANCELED": 4,+ }+)++func (x SubscriptionPayload_Status) Enum() *SubscriptionPayload_Status {+ p := new(SubscriptionPayload_Status)+ *p = x+ return p+}++func (x SubscriptionPayload_Status) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (SubscriptionPayload_Status) Descriptor() protoreflect.EnumDescriptor {+ return file_store_subscription_proto_enumTypes[0].Descriptor()+}++func (SubscriptionPayload_Status) Type() protoreflect.EnumType {+ return &file_store_subscription_proto_enumTypes[0]+}++func (x SubscriptionPayload_Status) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use SubscriptionPayload_Status.Descriptor instead.+func (SubscriptionPayload_Status) EnumDescriptor() ([]byte, []int) {+ return file_store_subscription_proto_rawDescGZIP(), []int{0, 0}+}++type SubscriptionPayload_Plan int32++const (+ SubscriptionPayload_PLAN_UNSPECIFIED SubscriptionPayload_Plan = 0+ SubscriptionPayload_TEAM SubscriptionPayload_Plan = 1+ SubscriptionPayload_ENTERPRISE SubscriptionPayload_Plan = 2+)++// Enum value maps for SubscriptionPayload_Plan.+var (+ SubscriptionPayload_Plan_name = map[int32]string{+ 0: "PLAN_UNSPECIFIED",+ 1: "TEAM",+ 2: "ENTERPRISE",+ }+ SubscriptionPayload_Plan_value = map[string]int32{+ "PLAN_UNSPECIFIED": 0,+ "TEAM": 1,+ "ENTERPRISE": 2,+ }+)++func (x SubscriptionPayload_Plan) Enum() *SubscriptionPayload_Plan {+ p := new(SubscriptionPayload_Plan)+ *p = x+ return p+}++func (x SubscriptionPayload_Plan) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (SubscriptionPayload_Plan) Descriptor() protoreflect.EnumDescriptor {+ return file_store_subscription_proto_enumTypes[1].Descriptor()+}++func (SubscriptionPayload_Plan) Type() protoreflect.EnumType {+ return &file_store_subscription_proto_enumTypes[1]+}++func (x SubscriptionPayload_Plan) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use SubscriptionPayload_Plan.Descriptor instead.+func (SubscriptionPayload_Plan) EnumDescriptor() ([]byte, []int) {+ return file_store_subscription_proto_rawDescGZIP(), []int{0, 1}+}++type SubscriptionPayload_BillingInterval int32++const (+ SubscriptionPayload_BILLING_INTERVAL_UNSPECIFIED SubscriptionPayload_BillingInterval = 0+ SubscriptionPayload_MONTH SubscriptionPayload_BillingInterval = 1+ SubscriptionPayload_YEAR SubscriptionPayload_BillingInterval = 2+)++// Enum value maps for SubscriptionPayload_BillingInterval.+var (+ SubscriptionPayload_BillingInterval_name = map[int32]string{+ 0: "BILLING_INTERVAL_UNSPECIFIED",+ 1: "MONTH",+ 2: "YEAR",+ }+ SubscriptionPayload_BillingInterval_value = map[string]int32{+ "BILLING_INTERVAL_UNSPECIFIED": 0,+ "MONTH": 1,+ "YEAR": 2,+ }+)++func (x SubscriptionPayload_BillingInterval) Enum() *SubscriptionPayload_BillingInterval {+ p := new(SubscriptionPayload_BillingInterval)+ *p = x+ return p+}++func (x SubscriptionPayload_BillingInterval) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (SubscriptionPayload_BillingInterval) Descriptor() protoreflect.EnumDescriptor {+ return file_store_subscription_proto_enumTypes[2].Descriptor()+}++func (SubscriptionPayload_BillingInterval) Type() protoreflect.EnumType {+ return &file_store_subscription_proto_enumTypes[2]+}++func (x SubscriptionPayload_BillingInterval) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use SubscriptionPayload_BillingInterval.Descriptor instead.+func (SubscriptionPayload_BillingInterval) EnumDescriptor() ([]byte, []int) {+ return file_store_subscription_proto_rawDescGZIP(), []int{0, 2}+}++// SubscriptionPayload stores all subscription data for a workspace.+// Serialized as JSONB in the subscription table's payload column.+type SubscriptionPayload struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // Lifecycle+ Status SubscriptionPayload_Status `protobuf:"varint,1,opt,name=status,proto3,enum=bytebase.store.SubscriptionPayload_Status" json:"status,omitempty"`+ StartedAt *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=started_at,json=startedAt,proto3" json:"started_at,omitempty"`+ ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"`+ // Billing details+ Plan SubscriptionPayload_Plan `protobuf:"varint,4,opt,name=plan,proto3,enum=bytebase.store.SubscriptionPayload_Plan" json:"plan,omitempty"`+ Interval SubscriptionPayload_BillingInterval `protobuf:"varint,5,opt,name=interval,proto3,enum=bytebase.store.SubscriptionPayload_BillingInterval" json:"interval,omitempty"`+ Seat int32 `protobuf:"varint,6,opt,name=seat,proto3" json:"seat,omitempty"`+ InstanceCount int32 `protobuf:"varint,7,opt,name=instance_count,json=instanceCount,proto3" json:"instance_count,omitempty"`+ // Stripe integration+ StripeSubscriptionId string `protobuf:"bytes,8,opt,name=stripe_subscription_id,json=stripeSubscriptionId,proto3" json:"stripe_subscription_id,omitempty"`+ StripeCustomerId string `protobuf:"bytes,9,opt,name=stripe_customer_id,json=stripeCustomerId,proto3" json:"stripe_customer_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *SubscriptionPayload) Reset() {+ *x = SubscriptionPayload{}+ mi := &file_store_subscription_proto_msgTypes[0]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *SubscriptionPayload) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*SubscriptionPayload) ProtoMessage() {}++func (x *SubscriptionPayload) ProtoReflect() protoreflect.Message {+ mi := &file_store_subscription_proto_msgTypes[0]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use SubscriptionPayload.ProtoReflect.Descriptor instead.+func (*SubscriptionPayload) Descriptor() ([]byte, []int) {+ return file_store_subscription_proto_rawDescGZIP(), []int{0}+}++func (x *SubscriptionPayload) GetStatus() SubscriptionPayload_Status {+ if x != nil {+ return x.Status+ }+ return SubscriptionPayload_STATUS_UNSPECIFIED+}++func (x *SubscriptionPayload) GetStartedAt() *timestamppb.Timestamp {+ if x != nil {+ return x.StartedAt+ }+ return nil+}++func (x *SubscriptionPayload) GetExpiresAt() *timestamppb.Timestamp {+ if x != nil {+ return x.ExpiresAt+ }+ return nil+}++func (x *SubscriptionPayload) GetPlan() SubscriptionPayload_Plan {+ if x != nil {+ return x.Plan+ }+ return SubscriptionPayload_PLAN_UNSPECIFIED+}++func (x *SubscriptionPayload) GetInterval() SubscriptionPayload_BillingInterval {+ if x != nil {+ return x.Interval+ }+ return SubscriptionPayload_BILLING_INTERVAL_UNSPECIFIED+}++func (x *SubscriptionPayload) GetSeat() int32 {+ if x != nil {+ return x.Seat+ }+ return 0+}++func (x *SubscriptionPayload) GetInstanceCount() int32 {+ if x != nil {+ return x.InstanceCount+ }+ return 0+}++func (x *SubscriptionPayload) GetStripeSubscriptionId() string {+ if x != nil {+ return x.StripeSubscriptionId+ }+ return ""+}++func (x *SubscriptionPayload) GetStripeCustomerId() string {+ if x != nil {+ return x.StripeCustomerId+ }+ return ""+}++var File_store_subscription_proto protoreflect.FileDescriptor++const file_store_subscription_proto_rawDesc = "" ++ "\n" ++ "\x18store/subscription.proto\x12\x0ebytebase.store\x1a\x1fgoogle/protobuf/timestamp.proto\"\xd4\x05\n" ++ "\x13SubscriptionPayload\x12B\n" ++ "\x06status\x18\x01 \x01(\x0e2*.bytebase.store.SubscriptionPayload.StatusR\x06status\x129\n" ++ "\n" ++ "started_at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\tstartedAt\x129\n" ++ "\n" ++ "expires_at\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\x12<\n" ++ "\x04plan\x18\x04 \x01(\x0e2(.bytebase.store.SubscriptionPayload.PlanR\x04plan\x12O\n" ++ "\binterval\x18\x05 \x01(\x0e23.bytebase.store.SubscriptionPayload.BillingIntervalR\binterval\x12\x12\n" ++ "\x04seat\x18\x06 \x01(\x05R\x04seat\x12%\n" ++ "\x0einstance_count\x18\a \x01(\x05R\rinstanceCount\x124\n" ++ "\x16stripe_subscription_id\x18\b \x01(\tR\x14stripeSubscriptionId\x12,\n" ++ "\x12stripe_customer_id\x18\t \x01(\tR\x10stripeCustomerId\"S\n" ++ "\x06Status\x12\x16\n" ++ "\x12STATUS_UNSPECIFIED\x10\x00\x12\v\n" ++ "\aPENDING\x10\x01\x12\n" ++ "\n" ++ "\x06ACTIVE\x10\x02\x12\n" ++ "\n" ++ "\x06PAUSED\x10\x03\x12\f\n" ++ "\bCANCELED\x10\x04\"6\n" ++ "\x04Plan\x12\x14\n" ++ "\x10PLAN_UNSPECIFIED\x10\x00\x12\b\n" ++ "\x04TEAM\x10\x01\x12\x0e\n" ++ "\n" ++ "ENTERPRISE\x10\x02\"H\n" ++ "\x0fBillingInterval\x12 \n" ++ "\x1cBILLING_INTERVAL_UNSPECIFIED\x10\x00\x12\t\n" ++ "\x05MONTH\x10\x01\x12\b\n" ++ "\x04YEAR\x10\x02B\x94\x01\n" ++ "\x12com.bytebase.storeB\x11SubscriptionProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"++var (+ file_store_subscription_proto_rawDescOnce sync.Once+ file_store_subscription_proto_rawDescData []byte+)++func file_store_subscription_proto_rawDescGZIP() []byte {+ file_store_subscription_proto_rawDescOnce.Do(func() {+ file_store_subscription_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_store_subscription_proto_rawDesc), len(file_store_subscription_proto_rawDesc)))+ })+ return file_store_subscription_proto_rawDescData+}++var file_store_subscription_proto_enumTypes = make([]protoimpl.EnumInfo, 3)+var file_store_subscription_proto_msgTypes = make([]protoimpl.MessageInfo, 1)+var file_store_subscription_proto_goTypes = []any{+ (SubscriptionPayload_Status)(0), // 0: bytebase.store.SubscriptionPayload.Status+ (SubscriptionPayload_Plan)(0), // 1: bytebase.store.SubscriptionPayload.Plan+ (SubscriptionPayload_BillingInterval)(0), // 2: bytebase.store.SubscriptionPayload.BillingInterval+ (*SubscriptionPayload)(nil), // 3: bytebase.store.SubscriptionPayload+ (*timestamppb.Timestamp)(nil), // 4: google.protobuf.Timestamp+}+var file_store_subscription_proto_depIdxs = []int32{+ 0, // 0: bytebase.store.SubscriptionPayload.status:type_name -> bytebase.store.SubscriptionPayload.Status+ 4, // 1: bytebase.store.SubscriptionPayload.started_at:type_name -> google.protobuf.Timestamp+ 4, // 2: bytebase.store.SubscriptionPayload.expires_at:type_name -> google.protobuf.Timestamp+ 1, // 3: bytebase.store.SubscriptionPayload.plan:type_name -> bytebase.store.SubscriptionPayload.Plan+ 2, // 4: bytebase.store.SubscriptionPayload.interval:type_name -> bytebase.store.SubscriptionPayload.BillingInterval+ 5, // [5:5] is the sub-list for method output_type+ 5, // [5:5] is the sub-list for method input_type+ 5, // [5:5] is the sub-list for extension type_name+ 5, // [5:5] is the sub-list for extension extendee+ 0, // [0:5] is the sub-list for field type_name+}++func init() { file_store_subscription_proto_init() }+func file_store_subscription_proto_init() {+ if File_store_subscription_proto != nil {+ return+ }+ type x struct{}+ out := protoimpl.TypeBuilder{+ File: protoimpl.DescBuilder{+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_subscription_proto_rawDesc), len(file_store_subscription_proto_rawDesc)),+ NumEnums: 3,+ NumMessages: 1,+ NumExtensions: 0,+ NumServices: 0,+ },+ GoTypes: file_store_subscription_proto_goTypes,+ DependencyIndexes: file_store_subscription_proto_depIdxs,+ EnumInfos: file_store_subscription_proto_enumTypes,+ MessageInfos: file_store_subscription_proto_msgTypes,+ }.Build()+ File_store_subscription_proto = out.File+ file_store_subscription_proto_goTypes = nil+ file_store_subscription_proto_depIdxs = nil+}diff --git a/backend/generated-go/store/subscription_equal.pb.go b/backend/generated-go/store/subscription_equal.pb.gonew file mode 100644index 0000000000..57cd9fbb48--- /dev/null+++ b/backend/generated-go/store/subscription_equal.pb.go@@ -0,0 +1,41 @@+// Code generated by protoc-gen-equal-go. DO NOT EDIT.+// source: store/subscription.proto++package store++func (x *SubscriptionPayload) Equal(y *SubscriptionPayload) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Status != y.Status {+ return false+ }+ if p, q := x.StartedAt, y.StartedAt; (p == nil && q != nil) || (p != nil && (q == nil || p.Seconds != q.Seconds || p.Nanos != q.Nanos)) {+ return false+ }+ if p, q := x.ExpiresAt, y.ExpiresAt; (p == nil && q != nil) || (p != nil && (q == nil || p.Seconds != q.Seconds || p.Nanos != q.Nanos)) {+ return false+ }+ if x.Plan != y.Plan {+ return false+ }+ if x.Interval != y.Interval {+ return false+ }+ if x.Seat != y.Seat {+ return false+ }+ if x.InstanceCount != y.InstanceCount {+ return false+ }+ if x.StripeSubscriptionId != y.StripeSubscriptionId {+ return false+ }+ if x.StripeCustomerId != y.StripeCustomerId {+ return false+ }+ return true+}diff --git a/backend/migrator/migration/3.17/0014##add_subscription_table.sql b/backend/migrator/migration/3.17/0014##add_subscription_table.sqlnew file mode 100644index 0000000000..c0576be58f--- /dev/null+++ b/backend/migrator/migration/3.17/0014##add_subscription_table.sql@@ -0,0 +1,7 @@+CREATE TABLE IF NOT EXISTS subscription (+ workspace text NOT NULL REFERENCES workspace(resource_id) PRIMARY KEY,+ -- Stored as SubscriptionPayload (proto/store/store/subscription.proto)+ payload jsonb NOT NULL DEFAULT '{}',+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now()+);diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sqlindex fcc63ceae5..970d475d81 100644--- a/backend/migrator/migration/LATEST.sql+++ b/backend/migrator/migration/LATEST.sql@@ -17,6 +17,14 @@ CREATE TABLE workspace (deleted boolean NOT NULL DEFAULT FALSE);+CREATE TABLE subscription (+ workspace text NOT NULL REFERENCES workspace(resource_id) PRIMARY KEY,+ -- Stored as SubscriptionPayload (proto/store/store/subscription.proto)+ payload jsonb NOT NULL DEFAULT '{}',+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now()+);+CREATE TABLE principal (id serial PRIMARY KEY,deleted boolean NOT NULL DEFAULT FALSE,diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.goindex a874422ad3..44427faa23 100644--- a/backend/migrator/migrator_test.go+++ b/backend/migrator/migrator_test.go@@ -15,8 +15,8 @@ import (func TestLatestVersion(t *testing.T) {files, err := getSortedVersionedFiles()require.NoError(t, err)- require.Equal(t, semver.MustParse("3.17.13"), *files[len(files)-1].version)- require.Equal(t, "migration/3.17/0013##workspace_payload.sql", files[len(files)-1].path)+ require.Equal(t, semver.MustParse("3.17.14"), *files[len(files)-1].version)+ require.Equal(t, "migration/3.17/0014##add_subscription_table.sql", files[len(files)-1].path)}func TestVersionUnique(t *testing.T) {diff --git a/docs/plans/saas/07.api-resource-patterns.md b/docs/plans/saas/07.api-resource-patterns.mdnew file mode 100644index 0000000000..57bcb00907--- /dev/null+++ b/docs/plans/saas/07.api-resource-patterns.md@@ -0,0 +1,178 @@+# API Resource Name & Parent Patterns++This document catalogs every RPC method and its resource name/parent pattern, showing how the ACL layer can determine workspace ownership for each API call.++---++## Pattern Categories++| Category | ACL Validation | Example |+|----------|---------------|---------|+| **Workspace-level** (no parent) | Workspace from JWT context | `ListProjects`, `ListInstances` |+| **`projects/{project}`** parent | ACL validates project belongs to workspace | `ListIssues`, `CreatePlan` |+| **`instances/{instance}`** parent | ACL validates instance belongs to workspace | `ListInstanceRoles` |+| **`instances/{instance}/databases/{database}`** parent | ACL looks up database with workspace filter, resolves to project | `ListChangelogs`, `Query` |+| **Multi-level** (workspace/project/env/instance/database) | ACL matches the specific parent type | `OrgPolicyService` |+| **Global** (no workspace scope) | Skipped (allow_without_credential) | `Login`, `Signup` |++---++## Workspace-Level (No Parent)++These APIs list/create top-level resources. The workspace is resolved from the JWT context only.++| Service | Method | Notes |+|---------|--------|-------|+| ActuatorService | GetActuatorInfo, SetupSample, DeleteCache, GetResourcePackage | System operations |+| AuthService | Login, Logout, Signup, Refresh, ExchangeToken | allow_without_credential |+| CelService | BatchParse, BatchDeparse | Utility |+| GroupService | ListGroups, CreateGroup | |+| IdentityProviderService | ListIdentityProviders, CreateIdentityProvider | |+| InstanceService | ListInstances, CreateInstance, BatchSyncInstances, BatchUpdateInstances | |+| ProjectService | ListProjects, SearchProjects, CreateProject, BatchDeleteProjects | |+| ReviewConfigService | ListReviewConfigs, CreateReviewConfig | |+| RoleService | ListRoles, CreateRole | |+| SettingService | ListSettings | |+| SubscriptionService | GetSubscription, UpdateSubscription | |+| UserService | ListUsers, CreateUser, GetCurrentUser | |++---++## Name-Based (Top-Level Resource by Name)++These APIs operate on a single top-level resource by its name. ACL validates via workspace context.++| Service | Method | Name Pattern |+|---------|--------|-------------|+| GroupService | GetGroup, UpdateGroup, DeleteGroup | `groups/{group}` |+| GroupService | BatchGetGroups | `groups/{group}` (repeated) |+| IdentityProviderService | GetIdentityProvider, UpdateIdentityProvider, DeleteIdentityProvider, TestIdentityProvider | `idps/{idp}` |+| InstanceService | GetInstance, UpdateInstance, DeleteInstance, UndeleteInstance, SyncInstance, ListInstanceDatabase, AddDataSource, RemoveDataSource, UpdateDataSource | `instances/{instance}` |+| ProjectService | GetProject, UpdateProject, DeleteProject, UndeleteProject | `projects/{project}` |+| ProjectService | BatchGetProjects | `projects/{project}` (repeated) |+| ReviewConfigService | GetReviewConfig, UpdateReviewConfig, DeleteReviewConfig | `reviewConfigs/{reviewConfig}` |+| RoleService | GetRole, UpdateRole, DeleteRole | `roles/{role}` |+| SettingService | GetSetting, UpdateSetting | `settings/{setting}` |+| UserService | GetUser, UpdateUser, DeleteUser, UndeleteUser, UpdateEmail | `users/{user}` |+| UserService | BatchGetUsers | `users/{user}` (repeated) |+| ServiceAccountService | GetServiceAccount, UpdateServiceAccount, DeleteServiceAccount, UndeleteServiceAccount | `serviceAccounts/{email}` |+| WorkloadIdentityService | GetWorkloadIdentity, UpdateWorkloadIdentity, DeleteWorkloadIdentity, UndeleteWorkloadIdentity | `workloadIdentities/{email}` |++---++## `projects/{project}` Parent++These APIs are scoped to a project. ACL validates the project belongs to the workspace.++| Service | Method | Resource Pattern |+|---------|--------|-----------------|+| AccessGrantService | ListAccessGrants, CreateAccessGrant, SearchMyAccessGrants | parent: `projects/{project}` |+| AccessGrantService | GetAccessGrant, ActivateAccessGrant, RevokeAccessGrant | name: `projects/{project}/accessGrants/{accessGrant}` |+| DatabaseGroupService | ListDatabaseGroups, CreateDatabaseGroup | parent: `projects/{project}` |+| DatabaseGroupService | GetDatabaseGroup, UpdateDatabaseGroup, DeleteDatabaseGroup | name: `projects/{project}/databaseGroups/{databaseGroup}` |+| IssueService | ListIssues, SearchIssues, CreateIssue, BatchUpdateIssuesStatus | parent: `projects/{project}` |+| IssueService | GetIssue, UpdateIssue, ApproveIssue, RejectIssue, RequestIssue | name: `projects/{project}/issues/{issue}` |+| IssueService | ListIssueComments, CreateIssueComment, UpdateIssueComment | parent: `projects/{project}/issues/{issue}` |+| PlanService | ListPlans, CreatePlan | parent: `projects/{project}` |+| PlanService | GetPlan, UpdatePlan, RunPlanChecks | name: `projects/{project}/plans/{plan}` |+| PlanService | GetPlanCheckRun, CancelPlanCheckRun | name: `projects/{project}/plans/{plan}/planCheckRun` |+| ProjectService | GetIamPolicy, SetIamPolicy | resource: `projects/{project}` |+| ProjectService | AddWebhook, TestWebhook | project: `projects/{project}` |+| ProjectService | UpdateWebhook, RemoveWebhook | name: `projects/{project}/webhooks/{webhook}` |+| ReleaseService | ListReleases, CreateRelease, CheckRelease, ListReleaseCategories | parent: `projects/{project}` |+| ReleaseService | GetRelease, UpdateRelease, DeleteRelease, UndeleteRelease | name: `projects/{project}/releases/{release}` |+| RolloutService | ListRollouts | parent: `projects/{project}` |+| RolloutService | CreateRollout | parent: `projects/{project}/plans/{plan}` |+| RolloutService | GetRollout | name: `projects/{project}/plans/{plan}/rollout` |+| RolloutService | BatchRunTasks, BatchSkipTasks | parent: `projects/{project}/plans/{plan}/rollout/stages/{stage}` |+| RolloutService | ListTaskRuns, BatchCancelTaskRuns | parent: `projects/{project}/plans/{plan}/rollout/stages/{stage}/tasks/{task}` |+| RolloutService | GetTaskRun, GetTaskRunLog, GetTaskRunSession, PreviewTaskRunRollback | name: `projects/{project}/.../taskRuns/{taskRun}` |+| SheetService | CreateSheet, BatchCreateSheets | parent: `projects/{project}` |+| SheetService | GetSheet | name: `projects/{project}/sheets/{sheet}` |+| WorksheetService | CreateWorksheet, SearchWorksheets | parent: `projects/{project}` |+| WorksheetService | GetWorksheet, UpdateWorksheet, DeleteWorksheet, UpdateWorksheetOrganizer | name: `projects/{project}/worksheets/{worksheet}` |+| WorksheetService | BatchUpdateWorksheetOrganizer | workspace-level batch |++---++## `instances/{instance}` Parent++| Service | Method | Resource Pattern |+|---------|--------|-----------------|+| InstanceRoleService | ListInstanceRoles | parent: `instances/{instance}` |++---++## `instances/{instance}/databases/{database}` Parent++These APIs are scoped to a database. ACL looks up the database with workspace filter and resolves to the parent project.++| Service | Method | Resource Pattern |+|---------|--------|-----------------|+| DatabaseService | GetDatabase, UpdateDatabase, SyncDatabase | name: `instances/{instance}/databases/{database}` |+| DatabaseService | GetDatabaseMetadata, GetDatabaseSchema, GetDatabaseSDLSchema, GetSchemaString | name: `instances/{instance}/databases/{database}/...` |+| DatabaseService | ListChangelogs | parent: `instances/{instance}/databases/{database}` |+| DatabaseService | GetChangelog, DiffSchema | name: `instances/{instance}/databases/{database}/changelogs/{changelog}` |+| DatabaseService | BatchUpdateDatabases, BatchSyncDatabases | parent: `instances/{instance}` |+| DatabaseCatalogService | GetDatabaseCatalog, UpdateDatabaseCatalog | name: `instances/{instance}/databases/{database}/catalog` |+| RevisionService | ListRevisions, BatchCreateRevisions | parent: `instances/{instance}/databases/{database}` |+| RevisionService | GetRevision, DeleteRevision | name: `instances/{instance}/databases/{database}/revisions/{revision}` |+| SQLService | Query, Export, AdminExecute | name: `instances/{instance}/databases/{database}` |++---++## Multi-Parent APIs++These APIs accept different parent types depending on the use case.++### DatabaseService — ListDatabases / BatchGetDatabases++Accepts multiple parent types:+- `projects/{project}` — list databases in a project+- `instances/{instance}` — list databases in an instance+- `workspaces/{workspace}` — list all databases in a workspace++### ServiceAccountService / WorkloadIdentityService — List / Create++Accepts multiple parent types:+- `projects/{project}` — project-scoped accounts+- `workspaces/{workspace}` — workspace-scoped accounts++### OrgPolicyService — All Methods++Accepts 5 different parent/name levels:+- `workspaces/{workspace}/policies/{policy}`+- `projects/{project}/policies/{policy}`+- `environments/{environment}/policies/{policy}`+- `instances/{instance}/policies/{policy}`+- `instances/{instance}/databases/{database}/policies/{policy}`++### AuditLogService — SearchAuditLogs / ExportAuditLogs++Accepts:+- `projects/{project}` — project-scoped audit logs+- No parent — workspace-level audit logs++### WorkspaceService — GetIamPolicy / SetIamPolicy++- `workspaces/{workspace}` resource++### SQLService — DiffMetadata / AICompletion / SearchQueryHistories++- Workspace-level utility methods (no resource parent)++---++## ACL Resource Resolution Summary++The ACL interceptor (`populateRawResources`) handles these patterns:++```+workspaces/{id} → ResourceTypeWorkspace (direct match)+projects/{id}[/...] → ResourceTypeProject (extract project ID)+instances/{id}/databases/{name}... → Look up database → ResourceTypeProject (parent project)+instances/{id}[/...] → Look up instance → ResourceTypeWorkspace+(default) → ResourceTypeWorkspace (from context)+```++All API resource patterns map to one of these ACL cases. No API endpoint bypasses workspace validation (except `allow_without_credential` methods like Login/Signup).diff --git a/docs/plans/saas/08.in-app-purchase.md b/docs/plans/saas/08.in-app-purchase.mdnew file mode 100644index 0000000000..34570e7422--- /dev/null+++ b/docs/plans/saas/08.in-app-purchase.md@@ -0,0 +1,634 @@+# In-App Purchase for SaaS Workspaces++Move the purchase workflow from the hub codebase into the Bytebase codebase so SaaS users can purchase licenses directly from their workspace.++---++## Scope++**In scope**: Stripe checkout, webhooks, subscription CRUD, pricing, license activation — SaaS only.++**Out of scope**: GCP deployment, Paddle, self-host license download, Auth0, Mailchimp, Slack notifications, cloud workspace provisioning.++**Guiding principle**: Non-SaaS hides the purchase UI and rejects purchase APIs. The existing `UpdateSubscription` (manual JWT upload) remains for self-hosted.++---++## Current State++### Bytebase (this codebase)++- **License storage**: JWT string in `setting` table (workspace-scoped), key `(workspace, "bb.workspace.license")`.+- **License parsing**: `enterprise/license.go` — RSA256 JWT with claims `{seat, instanceCount, instance, plan, orgName, workspaceId, ha, trialing}`.+- **LicenseService**: `LoadSubscription(ctx, workspaceID)` → cached `*v1pb.Subscription`. `StoreLicense(ctx, workspaceID, jwt)` → validates + persists.+- **API**: `GetSubscription` (unauthenticated), `UpdateSubscription` (manual JWT upload, `bb.settings.set`).+- **Frontend**: `SettingWorkspaceSubscription.vue` — shows plan info, textarea for JWT upload (self-host only).+- **Webhook infra**: Echo routes under `/hook/` (SCIM already registered here).++### Hub (source of truth for purchase logic)++- **Subscription table**: `id, org, instance_count, seat, interval, status, expires_at, payload(JSONB)`.+- **Stripe checkout**: Creates `CheckoutSession` with dynamic `PriceData`, metadata `{sub_id, plan, interval, instance_count, user_count, source}`.+- **Stripe webhooks**: `customer.subscription.created/updated/paused/resumed/deleted`, `invoice.paid`.+- **Cancellation**: Monthly = immediate proration + refund across charges. Annual = cancel at period end.+- **Subscription update**: Cancel old Stripe sub → create new one with existing customer's payment method.+- **Pricing**: `PlanLimitConfig` per plan type, `PriceModel` calculates total from base + additionals.+- **License generation**: RS256 JWT with same claims structure as Bytebase parser expects.++---++## Design++### 1. Database: `subscription` Table++Add a new `subscription` table (workspace-scoped). This replaces hub's subscription table with `org` → `workspace`.++```sql+CREATE TABLE subscription (+ id text NOT NULL,+ workspace text NOT NULL REFERENCES workspace(resource_id),+ status text NOT NULL DEFAULT '', -- 'PENDING', 'ACTIVE', 'PAUSED', 'CANCELED'+ started_at timestamptz NOT NULL DEFAULT now(),+ expires_at timestamptz NOT NULL DEFAULT now(),+ payload jsonb NOT NULL DEFAULT '{}', -- SubscriptionPayload proto+ etag text NOT NULL DEFAULT '',+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (id),+ UNIQUE (workspace)+);+```++The table is intentionally minimal — only `status`, `started_at`, `expires_at` are top-level columns because they are queried/filtered on. All billing details live in `payload` JSONB so the schema can evolve without DDL migrations.++**Key differences from hub**:+- `workspace` FK instead of `org` FK.+- `seat`, `interval`, `instance_count` moved into `payload` (not top-level columns).+- One subscription per workspace (unique constraint).++**Payload** (proto, stored as JSONB via `protojson.Marshal` → camelCase keys):++```protobuf+// In proto/store/store/subscription.proto++import "v1/subscription_service.proto";++message SubscriptionPayload {+ // Stripe integration+ string stripe_subscription_id = 1;+ string stripe_customer_id = 2;++ // Billing details — enums reuse the v1 API types+ bytebase.v1.PlanType plan = 3;+ BillingInterval interval = 4;+ int32 seat = 5;+ int32 instance_count = 6; // fixed at 10 for TEAM, but stored for license generation++ enum BillingInterval {+ BILLING_INTERVAL_UNSPECIFIED = 0;+ MONTH = 1;+ YEAR = 2;+ }+}+```++Note: `plan` reuses the existing `bytebase.v1.PlanType` enum (`FREE`, `TEAM`, `ENTERPRISE`) from `subscription_service.proto`. `interval` uses a local `BillingInterval` enum since no equivalent exists in v1 today. `protojson.Marshal` serializes enums as their string names (e.g., `"TEAM"`, `"MONTH"`) in JSONB.++No `DeploymentType` (always SaaS). No `PaddlePayload`. No `Source` enum (always Stripe). Billing fields in the payload keep the table lean and make it easy to add new fields (e.g., future per-instance pricing) without schema changes.++### 2. Store Layer++New file: `backend/store/subscription.go`++```go+type SubscriptionMessage struct {+ Workspace string+ Status string // "PENDING", "ACTIVE", "PAUSED", "CANCELED"+ StartedAt time.Time+ ExpiresAt time.Time+ Payload *storepb.SubscriptionPayload // seat, interval, instance_count, plan, stripe IDs+ Etag string+ CreatedAt time.Time+ UpdatedAt time.Time+}++type UpdateSubscriptionMessage struct {+ Etag *string+ Status *string+ ExpiresAt *time.Time+ Payload *storepb.SubscriptionPayload // updates billing details + stripe IDs atomically+}++func (s *Store) CreateSubscription(ctx context.Context, create *SubscriptionMessage) (*SubscriptionMessage, error)+func (s *Store) GetSubscriptionByWorkspace(ctx context.Context, workspace string) (*SubscriptionMessage, error)+func (s *Store) UpdateSubscription(ctx context.Context, workspace string, update *UpdateSubscriptionMessage) (*SubscriptionMessage, error)+```++No `ID` column — `workspace` is the PK (one subscription per workspace). No `FindSubscriptionMessage` — all lookups are by workspace directly.++### 3. Proto Changes++Extend `proto/v1/v1/subscription_service.proto`:++```protobuf+service SubscriptionService {+ // Existing+ rpc GetSubscription(GetSubscriptionRequest) returns (Subscription) { ... }+ rpc UpdateSubscription(UpdateSubscriptionRequest) returns (Subscription) { ... }++ // New — SaaS purchase flow+ rpc CreatePurchase(CreatePurchaseRequest) returns (CreatePurchaseResponse) {+ option (google.api.http) = {+ post: "/v1/subscription:purchase"+ body: "*"+ };+ option (bytebase.v1.permission) = "bb.settings.set";+ option (bytebase.v1.auth_method) = IAM;+ }++ rpc UpdatePurchase(UpdatePurchaseRequest) returns (UpdatePurchaseResponse) {+ option (google.api.http) = {+ post: "/v1/subscription:updatePurchase"+ body: "*"+ };+ option (bytebase.v1.permission) = "bb.settings.set";+ option (bytebase.v1.auth_method) = IAM;+ }++ rpc CancelPurchase(CancelPurchaseRequest) returns (CancelPurchaseResponse) {+ option (google.api.http) = {+ post: "/v1/subscription:cancelPurchase"+ body: "*"+ };+ option (bytebase.v1.permission) = "bb.settings.set";+ option (bytebase.v1.auth_method) = IAM;+ }++ rpc GetPaymentInfo(GetPaymentInfoRequest) returns (PaymentInfo) {+ option (google.api.http) = {get: "/v1/subscription/paymentInfo"};+ option (bytebase.v1.permission) = "bb.settings.set";+ option (bytebase.v1.auth_method) = IAM;+ }++ rpc ListPlans(ListPlansRequest) returns (ListPlansResponse) {+ option (google.api.http) = {get: "/v1/subscription/plans"};+ option (bytebase.v1.allow_without_credential) = true;+ }+}++message CreatePurchaseRequest {+ PlanType plan = 1;+ BillingInterval interval = 2;+ int32 seats = 3;+}++message CreatePurchaseResponse {+ string payment_url = 1; // Stripe Checkout URL+}++message UpdatePurchaseRequest {+ PlanType plan = 1;+ BillingInterval interval = 2;+ int32 seats = 3;+ string etag = 4;+}++message UpdatePurchaseResponse {+ // If payment_url is set, redirect to Stripe Checkout.+ // If empty, the update was applied directly (existing payment method reused).+ string payment_url = 1;+}++message CancelPurchaseRequest {+ string etag = 1;+}++message CancelPurchaseResponse {}++message GetPaymentInfoRequest {}++message PaymentInfo {+ string total_price = 1;+ string currency = 2;+ string period_start = 3;+ string period_end = 4;+ string invoice_url = 5; // Stripe Billing Portal URL+}++enum BillingInterval {+ BILLING_INTERVAL_UNSPECIFIED = 0;+ MONTH = 1;+ YEAR = 2;+}++message PurchasePlan {+ PlanType type = 1;+ bool self_service_purchase = 2;+ repeated PurchasePlanAdditional additionals = 3;+ repeated PurchaseBillingMethod billing_methods = 4;+}++message PurchasePlanAdditional {+ enum Type {+ TYPE_UNSPECIFIED = 0;+ USER = 1;+ }+ Type type = 1;+ int32 unit_price = 2; // cents per month+ int32 free_count = 3;+ int32 minimum_count = 4;+ int32 maximum_count = 5; // -1 = unlimited+}++message PurchaseBillingMethod {+ BillingInterval interval = 1;+ PurchaseDiscount discount = 2;+}++message PurchaseDiscount {+ string description = 1;+ string promotion_code = 2;+}++message ListPlansRequest {}++message ListPlansResponse {+ repeated PurchasePlan plans = 1;+}+```++**Why separate `CreatePurchase`/`UpdatePurchase`/`CancelPurchase` from existing `UpdateSubscription`?**+- `UpdateSubscription` is the self-hosted JWT upload path (will be disabled in SaaS).+- Purchase RPCs are SaaS-only and involve Stripe interaction.+- Clean separation — no conditional logic mixing two unrelated flows.++### 4. Pricing Module++New package: `backend/enterprise/pricing/`++Port from hub with simplifications:++```go+// backend/enterprise/pricing/plan.go++type PlanLimitConfig struct {+ Type v1pb.PlanType+ FreeSeatCount int+ MaximumSeatCount int // -1 = unlimited+ PricePerSeatPerMonth int64 // cents+}++var planLimits = map[v1pb.PlanType]*PlanLimitConfig{+ v1pb.PlanType_FREE: {+ FreeSeatCount: 20,+ MaximumSeatCount: 20,+ PricePerSeatPerMonth: 0,+ },+ v1pb.PlanType_TEAM: {+ FreeSeatCount: 0,+ MaximumSeatCount: -1, // unlimited+ PricePerSeatPerMonth: 2000, // $20/user/month in cents+ },+}++// ListPlans returns purchase plans for the API.+func ListPlans() []*v1pb.PurchasePlan { ... }+```++```go+// backend/enterprise/pricing/pricing.go++type PriceModel struct {+ Plan *PlanLimitConfig+ Interval v1pb.BillingInterval+ Seats int32+}++// GetPrice returns total price in USD cents.+func (m *PriceModel) GetPrice() (int64, error) {+ // seats × pricePerSeat × intervalMonths+ // Apply discount for annual billing if configured+}++// GetStripeInterval converts to Stripe interval string.+func (m *PriceModel) GetStripeInterval() string { ... }+```++**Dropped from hub**: `PricePerInstancePerMonth` (TEAM has fixed 10 instances), multi-currency support, Paddle price maps.++### 5. Stripe Plugin++New package: `backend/plugin/stripe/`++```go+// backend/plugin/stripe/stripe.go++// Init sets the Stripe API key from config. Called at server startup.+func Init(apiKey string) {+ stripe.Key = apiKey+}++// CreateCheckoutSession creates a Stripe Checkout Session for subscription purchase.+func CreateCheckoutSession(params *CheckoutParams) (string, error) { ... }++// CancelSubscription cancels a Stripe subscription.+// Monthly: immediate with proration. Annual: at period end.+func CancelSubscription(stripeSubID string, monthly bool, forceRefund bool) (*stripe.Subscription, error) { ... }++// CreateSubscriptionDirect creates a new Stripe subscription using an existing customer's payment method.+func CreateSubscriptionDirect(params *DirectSubscriptionParams) (*stripe.Subscription, error) { ... }++// RefundFromSubscription refunds proration credit after cancellation.+func RefundFromSubscription(sub *stripe.Subscription, internalSubID string) error { ... }++// GetMetadata builds metadata map for Stripe subscription.+func GetMetadata(subID string, plan string, interval string, seats int) map[string]string { ... }++// FindLastPaidInvoice finds the last paid invoice for a subscription.+func FindLastPaidInvoice(sub *stripe.Subscription) (*stripe.Invoice, error) { ... }++// GetPromotionByCode looks up an active promotion code.+func GetPromotionByCode(code string, price int64) *stripe.PromotionCode { ... }+```++Direct port of hub's `plugin/stripe/stripe.go` with Paddle references removed.++### 6. Stripe Webhook Handler++New file: `backend/api/stripe/webhook.go`++Register via Echo routes alongside SCIM (in `echo_routes.go`):++```go+// echo_routes.go+stripeWebhook := hookGroup.Group("/stripe")+stripeWebhookHandler.RegisterRoutes(stripeWebhook)+```++Route: `POST /hook/stripe/callback`++```go+type WebhookHandler struct {+ store *store.Store+ licenseService *enterprise.LicenseService+ stripeSecret string // webhook signing secret+}++func (h *WebhookHandler) HandleCallback(c echo.Context) error {+ // 1. Verify Stripe signature+ // 2. Parse event+ // 3. Filter by metadata source="bytebase_hub"+ // 4. Route to handler by event type+}+```++**Event handlers** (ported from hub `webhook/stripe.go`):++| Event | Handler |+|-------|---------|+| `customer.subscription.created` | Extract metadata, update subscription with Stripe IDs |+| `customer.subscription.updated` | Map Stripe status → internal status |+| `customer.subscription.paused` | Set PAUSED, invalidate license cache |+| `customer.subscription.resumed` | Set ACTIVE, regenerate + store license |+| `customer.subscription.deleted` | Set CANCELED, clear license |+| `invoice.paid` | Update seats/interval from metadata, extend `expires_at`, generate + store license JWT |++**License activation on `invoice.paid`** (replaces hub's GCP injection):++```go+func (h *WebhookHandler) activateLicense(ctx context.Context, sub *SubscriptionMessage) error {+ // 1. Build license claims from subscription data+ claims := &enterprise.Claims{+ Seats: sub.Seats,+ ActiveInstances: 10, // fixed for TEAM+ Instances: 10,+ Plan: sub.Payload.Plan,+ WorkspaceID: sub.Workspace,+ }+ // 2. Sign JWT using the license private key+ jwt := h.licenseService.CreateLicense(claims)+ // 3. Store directly via LicenseService+ h.licenseService.StoreLicense(ctx, sub.Workspace, jwt)+ // → This updates the setting table AND invalidates the cache+}+```++This is the key simplification: instead of generating a JWT on a remote hub and injecting it via GCP API, we generate and store it in-process.++### 7. Configuration++Add to `backend/component/config/profile.go`:++```go+type Profile struct {+ // ... existing fields+ StripeAPIKey string+ StripeWebhookSecret string+}+```++Loaded from environment variables:+- `STRIPE_API_KEY` — Stripe secret key+- `STRIPE_WEBHOOK_SECRET` — Webhook signing secret++Only used when `profile.SaaS == true`. Non-SaaS ignores these.++### 8. API Service Changes++Expand `backend/api/v1/subscription_service.go`:++```go+type SubscriptionService struct {+ v1connect.UnimplementedSubscriptionServiceHandler+ profile *config.Profile+ store *store.Store+ licenseService *enterprise.LicenseService+}++// GetSubscription — unchanged (returns current subscription from license cache).++// UpdateSubscription — self-hosted JWT upload (gated: rejected if profile.SaaS).++// CreatePurchase — SaaS only.+func (s *SubscriptionService) CreatePurchase(ctx, req) {+ if !s.profile.SaaS {+ return Unimplemented+ }+ workspaceID := common.GetWorkspaceIDFromContext(ctx)+ // 1. Validate plan is self-service purchasable+ // 2. Calculate price via pricing.GetPriceModel()+ // 3. Check no existing active subscription+ // 4. Create subscription record (status=PENDING)+ // 5. Create Stripe Checkout Session+ // 6. Return payment URL+}++// UpdatePurchase — SaaS only.+func (s *SubscriptionService) UpdatePurchase(ctx, req) {+ if !s.profile.SaaS {+ return Unimplemented+ }+ // 1. Validate etag+ // 2. If subscription is PENDING: activate with new settings, generate new checkout URL+ // 3. If plan/interval/seats changed: cancel old Stripe sub → create new one+ // 4. Return payment URL or empty (if direct creation succeeded)+}++// CancelPurchase — SaaS only.+func (s *SubscriptionService) CancelPurchase(ctx, req) {+ if !s.profile.SaaS {+ return Unimplemented+ }+ // 1. Validate etag+ // 2. Monthly: cancel immediately with proration + refund+ // 3. Annual: cancel at period end+ // 4. Clear license+}++// GetPaymentInfo — SaaS only.+func (s *SubscriptionService) GetPaymentInfo(ctx, req) {+ // Fetch last paid invoice from Stripe+ // Create Billing Portal session for invoice management+}++// ListPlans — public.+func (s *SubscriptionService) ListPlans(ctx, req) {+ return pricing.ListPlans()+}+```++### 9. License Key Management++**Problem**: Hub uses a private key to sign license JWTs. Bytebase uses a public key to verify them. For in-app purchase, Bytebase needs the private key to sign licenses.++**Solution**: Add a `prod.priv.pem` (and `dev.priv.pem`) to `backend/enterprise/keys/`, loaded only when `profile.SaaS == true`.++```go+type Config struct {+ publicKey *rsa.PublicKey+ privateKey *rsa.PrivateKey // nil for self-hosted+}++// CreateLicense signs a new license JWT. Only available in SaaS mode.+func (s *LicenseService) CreateLicense(claims *claims) (string, error) {+ if s.config.privateKey == nil {+ return "", errors.New("license signing not available")+ }+ token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)+ token.Header["kid"] = "v1"+ return token.SignedString(s.config.privateKey)+}+```++The private key should be provided via environment variable (not embedded in binary) for security:+- `LICENSE_PRIVATE_KEY` — PEM-encoded RSA private key, loaded only when `profile.SaaS == true`.++### 10. Frontend Changes++#### SettingWorkspaceSubscription.vue++The page needs two modes:++```+if (SaaS mode):+ Show: Plan card, seats config, billing interval toggle, purchase button+ Show: Subscription status (PENDING/ACTIVE/PAUSED/CANCELED/EXPIRED)+ Show: Payment info (price, period, invoice link)+ Show: Cancel button+ Hide: License textarea upload+else (self-hosted):+ Show: Current plan info, license textarea upload (existing behavior)+ Hide: Purchase UI+```++#### New Components++- **`PurchasePlanCard.vue`** — Plan selection with seat counter, billing toggle. Port from hub's `PlanPricing.vue`, simplified (no instance counter, no deployment type selector, always CLOUD).+- **`SubscriptionManagement.vue`** — Shows active subscription details, payment info, cancel button. Port from hub's `DashboardSubscriptionManagement.vue`.+- **`PendingPayment.vue`** — Shown after Stripe redirect while polling for subscription activation.++#### Frontend Store Extension++Extend `frontend/src/store/modules/v1/subscription.ts`:++```typescript+// New actions (SaaS only)+async createPurchase(plan, interval, seats): Promise<{ paymentUrl: string }>+async updatePurchase(plan, interval, seats, etag): Promise<{ paymentUrl: string }>+async cancelPurchase(etag): Promise<void>+async fetchPaymentInfo(): Promise<PaymentInfo>+async fetchPlans(): Promise<PurchasePlan[]>++// New state+purchaseSubscription: Ref<PurchaseSubscription | undefined> // from subscription table+paymentInfo: Ref<PaymentInfo | undefined>+plans: Ref<PurchasePlan[]>+```++#### Stripe Checkout Redirect Flow++```+User clicks "Subscribe" → createPurchase() → backend returns paymentUrl+ → window.location.href = paymentUrl (redirect to Stripe Checkout)+ → Stripe success → redirect to /setting/subscription?from=STRIPE+ → Frontend polls GetSubscription until plan becomes ACTIVE+ → Show subscription management UI+```++The `?from=STRIPE` query param triggers the pending payment polling view (same pattern as hub).++---++## Implementation Plan++### Phase 1: Backend Foundation++1. **Database migration** — Add `subscription` table. Add `SubscriptionPayload` to `proto/store/`.+2. **Store layer** — `backend/store/subscription.go` with CRUD methods.+3. **Pricing module** — `backend/enterprise/pricing/` with plan config and price calculation.+4. **Stripe plugin** — `backend/plugin/stripe/` with checkout session, cancellation, refund.++### Phase 2: API & Webhooks++5. **Proto definitions** — Add new RPCs and messages to `subscription_service.proto`.+6. **Subscription service** — Implement `CreatePurchase`, `UpdatePurchase`, `CancelPurchase`, `GetPaymentInfo`, `ListPlans`.+7. **Stripe webhook** — `backend/api/stripe/webhook.go`, register in `echo_routes.go`.+8. **License signing** — Add `CreateLicense` to `LicenseService`, load private key in SaaS mode.+9. **SaaS gate** — `UpdateSubscription` blocked in SaaS, purchase APIs blocked in non-SaaS.++### Phase 3: Frontend++10. **Subscription store** — Add purchase actions and state.+11. **Plan selection UI** — `PurchasePlanCard.vue` with seat counter and billing toggle.+12. **Subscription management** — Status display, payment info, cancel flow.+13. **Pending payment** — Polling view after Stripe redirect.+14. **Conditional rendering** — Show purchase UI in SaaS, license upload in self-hosted.++### Phase 4: Integration & Testing++15. **Stripe test mode** — End-to-end testing with Stripe test keys.+16. **Webhook testing** — Stripe CLI (`stripe listen --forward-to`) for local webhook testing.+17. **Edge cases** — Expired subscription, failed payment retry, concurrent updates (etag), plan changes mid-billing.++---++## Key Differences from Hub++| Aspect | Hub | Bytebase SaaS |+|--------|-----|----------------|+| License delivery | JWT download (self-host) or GCP injection (cloud) | In-process `StoreLicense()` |+| Instance pricing | Per-instance additional | Fixed 10 instances (TEAM) |+| Payment providers | Stripe + Paddle | Stripe only |+| Grace period | +7 days (self-host), +12h (cloud) | None needed (instant activation) |+| Subscription owner | `org` entity | `workspace` directly |++---++## Security Considerations++1. **Stripe webhook signature verification** — Must validate `Stripe-Signature` header against `STRIPE_WEBHOOK_SECRET`. Reject unsigned requests.+2. **License private key** — Environment variable only, never embedded in binary. Only loaded in SaaS mode.+3. **SaaS gate** — All purchase APIs must check `profile.SaaS` before proceeding. Non-SaaS deployments must never expose Stripe integration.+4. **Etag-based optimistic locking** — Prevents race conditions on subscription updates.+5. **Metadata validation** — Webhook handler must verify `source=bytebase_hub` in metadata to filter out unrelated Stripe events.+6. **HTTPS only** — Stripe webhooks require HTTPS endpoints.diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex c357506e90..b081953a06 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -30142,6 +30142,8 @@ components:documentation for additional information.security: []tags:+ - name: SubscriptionService+ description: SubscriptionService manages enterprise subscriptions and licensing.- name: AccessGrantServicedescription: AccessGrantService manages temporary access grants within projects.- name: IssueService@@ -30196,8 +30198,6 @@ tags:description: ServiceAccountService manages service accounts for API integrations.- name: SheetServicedescription: SheetService manages SQL scripts and saved queries.- - name: SubscriptionService- description: SubscriptionService manages enterprise subscriptions and licensing.- name: WorkloadIdentityServicedescription: WorkloadIdentityService manages workload identities for external CI/CD integrations.- name: WorksheetServicediff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex 64932a2548..93ea154a18 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -284,6 +284,13 @@- [Signal.Type](#bytebase-store-Signal-Type)+- [store/subscription.proto](#store_subscription-proto)+ - [SubscriptionPayload](#bytebase-store-SubscriptionPayload)++ - [SubscriptionPayload.BillingInterval](#bytebase-store-SubscriptionPayload-BillingInterval)+ - [SubscriptionPayload.Plan](#bytebase-store-SubscriptionPayload-Plan)+ - [SubscriptionPayload.Status](#bytebase-store-SubscriptionPayload-Status)+- [store/task.proto](#store_task-proto)- [Task](#bytebase-store-Task)@@ -4698,6 +4705,87 @@ Type represents the type of signal.+<a name="store_subscription-proto"></a>+<p align="right"><a href="#top">Top</a></p>++## store/subscription.proto++++<a name="bytebase-store-SubscriptionPayload"></a>++### SubscriptionPayload+SubscriptionPayload stores all subscription data for a workspace.+Serialized as JSONB in the subscription table's payload column.+++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| status | [SubscriptionPayload.Status](#bytebase-store-SubscriptionPayload-Status) | | Lifecycle |+| started_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | |+| expires_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | |+| plan | [SubscriptionPayload.Plan](#bytebase-store-SubscriptionPayload-Plan) | | Billing details |+| interval | [SubscriptionPayload.BillingInterval](#bytebase-store-SubscriptionPayload-BillingInterval) | | |+| seat | [int32](#int32) | | |+| instance_count | [int32](#int32) | | |+| stripe_subscription_id | [string](#string) | | Stripe integration |+| stripe_customer_id | [string](#string) | | |+++++++++<a name="bytebase-store-SubscriptionPayload-BillingInterval"></a>++### SubscriptionPayload.BillingInterval+++| Name | Number | Description |+| ---- | ------ | ----------- |+| BILLING_INTERVAL_UNSPECIFIED | 0 | |+| MONTH | 1 | |+| YEAR | 2 | |++++<a name="bytebase-store-SubscriptionPayload-Plan"></a>++### SubscriptionPayload.Plan+++| Name | Number | Description |+| ---- | ------ | ----------- |+| PLAN_UNSPECIFIED | 0 | |+| TEAM | 1 | |+| ENTERPRISE | 2 | |++++<a name="bytebase-store-SubscriptionPayload-Status"></a>++### SubscriptionPayload.Status+++| Name | Number | Description |+| ---- | ------ | ----------- |+| STATUS_UNSPECIFIED | 0 | |+| PENDING | 1 | |+| ACTIVE | 2 | |+| PAUSED | 3 | |+| CANCELED | 4 | |++++++++++<a name="store_task-proto"></a><p align="right"><a href="#top">Top</a></p>diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex e5e8559149..2582353d15 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -1315,6 +1315,33 @@</li>+ <li>+ <a href="#store%2fsubscription.proto">store/subscription.proto</a>+ <ul>++ <li>+ <a href="#bytebase.store.SubscriptionPayload"><span class="badge">M</span>SubscriptionPayload</a>+ </li>+++ <li>+ <a href="#bytebase.store.SubscriptionPayload.BillingInterval"><span class="badge">E</span>SubscriptionPayload.BillingInterval</a>+ </li>++ <li>+ <a href="#bytebase.store.SubscriptionPayload.Plan"><span class="badge">E</span>SubscriptionPayload.Plan</a>+ </li>++ <li>+ <a href="#bytebase.store.SubscriptionPayload.Status"><span class="badge">E</span>SubscriptionPayload.Status</a>+ </li>++++ </ul>+ </li>++<li><a href="#store%2ftask.proto">store/task.proto</a><ul>@@ -12828,6 +12855,199 @@ Default to this mode.</p></td>+ <div class="file-heading">+ <h2 id="store/subscription.proto">store/subscription.proto</h2><a href="#title">Top</a>+ </div>+ <p></p>+++ <h3 id="bytebase.store.SubscriptionPayload">SubscriptionPayload</h3>+ <p>SubscriptionPayload stores all subscription data for a workspace.</p><p>Serialized as JSONB in the subscription table's payload column.</p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>status</td>+ <td><a href="#bytebase.store.SubscriptionPayload.Status">SubscriptionPayload.Status</a></td>+ <td></td>+ <td><p>Lifecycle </p></td>+ </tr>++ <tr>+ <td>started_at</td>+ <td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>++ <tr>+ <td>expires_at</td>+ <td><a href="#google.protobuf.Timestamp">google.protobuf.Timestamp</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>++ <tr>+ <td>plan</td>+ <td><a href="#bytebase.store.SubscriptionPayload.Plan">SubscriptionPayload.Plan</a></td>+ <td></td>+ <td><p>Billing details </p></td>+ </tr>++ <tr>+ <td>interval</td>+ <td><a href="#bytebase.store.SubscriptionPayload.BillingInterval">SubscriptionPayload.BillingInterval</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>++ <tr>+ <td>seat</td>+ <td><a href="#int32">int32</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>++ <tr>+ <td>instance_count</td>+ <td><a href="#int32">int32</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>++ <tr>+ <td>stripe_subscription_id</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>Stripe integration </p></td>+ </tr>++ <tr>+ <td>stripe_customer_id</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>++ </tbody>+ </table>++++++++ <h3 id="bytebase.store.SubscriptionPayload.BillingInterval">SubscriptionPayload.BillingInterval</h3>+ <p></p>+ <table class="enum-table">+ <thead>+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>BILLING_INTERVAL_UNSPECIFIED</td>+ <td>0</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>MONTH</td>+ <td>1</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>YEAR</td>+ <td>2</td>+ <td><p></p></td>+ </tr>++ </tbody>+ </table>++ <h3 id="bytebase.store.SubscriptionPayload.Plan">SubscriptionPayload.Plan</h3>+ <p></p>+ <table class="enum-table">+ <thead>+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>PLAN_UNSPECIFIED</td>+ <td>0</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>TEAM</td>+ <td>1</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>ENTERPRISE</td>+ <td>2</td>+ <td><p></p></td>+ </tr>++ </tbody>+ </table>++ <h3 id="bytebase.store.SubscriptionPayload.Status">SubscriptionPayload.Status</h3>+ <p></p>+ <table class="enum-table">+ <thead>+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>STATUS_UNSPECIFIED</td>+ <td>0</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>PENDING</td>+ <td>1</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>ACTIVE</td>+ <td>2</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>PAUSED</td>+ <td>3</td>+ <td><p></p></td>+ </tr>++ <tr>+ <td>CANCELED</td>+ <td>4</td>+ <td><p></p></td>+ </tr>++ </tbody>+ </table>+++++++<div class="file-heading"><h2 id="store/task.proto">store/task.proto</h2><a href="#title">Top</a></div>diff --git a/proto/store/store/subscription.proto b/proto/store/store/subscription.protonew file mode 100644index 0000000000..85e412e8ad--- /dev/null+++ b/proto/store/store/subscription.proto@@ -0,0 +1,46 @@+syntax = "proto3";++package bytebase.store;++import "google/protobuf/timestamp.proto";++option go_package = "generated-go/store";++// SubscriptionPayload stores all subscription data for a workspace.+// Serialized as JSONB in the subscription table's payload column.+message SubscriptionPayload {+ enum Status {+ STATUS_UNSPECIFIED = 0;+ PENDING = 1;+ ACTIVE = 2;+ PAUSED = 3;+ CANCELED = 4;+ }++ enum Plan {+ PLAN_UNSPECIFIED = 0;+ TEAM = 1;+ ENTERPRISE = 2;+ }++ enum BillingInterval {+ BILLING_INTERVAL_UNSPECIFIED = 0;+ MONTH = 1;+ YEAR = 2;+ }++ // Lifecycle+ Status status = 1;+ google.protobuf.Timestamp started_at = 2;+ google.protobuf.Timestamp expires_at = 3;++ // Billing details+ Plan plan = 4;+ BillingInterval interval = 5;+ int32 seat = 6;+ int32 instance_count = 7;++ // Stripe integration+ string stripe_subscription_id = 8;+ string stripe_customer_id = 9;+}