Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: implement permissions in role store (#10451)
boojack64ffbc1c33ef
diff --git a/backend/bin/server/cmd/profile_dev.go b/backend/bin/server/cmd/profile_dev.goindex 8de7eb04b1..5ba659d1ee 100644--- a/backend/bin/server/cmd/profile_dev.go+++ b/backend/bin/server/cmd/profile_dev.go@@ -16,6 +16,7 @@ func activeProfile(dataDir string) config.Profile {p.BackupRunnerInterval = 10 * time.Secondp.AppRunnerInterval = 30 * time.Secondp.EnableMetric = false+ p.DevelopmentIAM = true// Metric collection is disabled in dev mode.// p.MetricConnectionKey = "3zcZLeX3ahvlueEJqNyJysGfVAErsjjT"return pdiff --git a/backend/migrator/migration/dev/LATEST.sql b/backend/migrator/migration/dev/LATEST.sqlindex 69603f5e17..06c3357d0d 100644--- a/backend/migrator/migration/dev/LATEST.sql+++ b/backend/migrator/migration/dev/LATEST.sql@@ -136,7 +136,7 @@ CREATE TABLE role (resource_id TEXT NOT NULL, -- user-defined id, such as projectDBAname TEXT NOT NULL,description TEXT NOT NULL,- permissions JSONB NOT NULL DEFAULT '{}', -- saved for future use+ permissions JSONB NOT NULL DEFAULT '{}',payload JSONB NOT NULL DEFAULT '{}' -- saved for future use);@@ -244,7 +244,7 @@ CREATE TABLE project (schema_change_type TEXT NOT NULL CHECK (schema_change_type IN ('DDL', 'SDL')) DEFAULT 'DDL',resource_id TEXT NOT NULL,data_classification_config_id TEXT NOT NULL DEFAULT '',- setting JSONB NOT NULL DEFAULT '{}'+ setting JSONB NOT NULL DEFAULT '{}');CREATE UNIQUE INDEX idx_project_unique_key ON project(key);diff --git a/backend/migrator/migration/prod/LATEST.sql b/backend/migrator/migration/prod/LATEST.sqlindex a038e02272..f79cad5731 100644--- a/backend/migrator/migration/prod/LATEST.sql+++ b/backend/migrator/migration/prod/LATEST.sql@@ -136,7 +136,7 @@ CREATE TABLE role (resource_id TEXT NOT NULL, -- user-defined id, such as projectDBAname TEXT NOT NULL,description TEXT NOT NULL,- permissions JSONB NOT NULL DEFAULT '{}', -- saved for future use+ permissions JSONB NOT NULL DEFAULT '{}',payload JSONB NOT NULL DEFAULT '{}' -- saved for future use);@@ -243,7 +243,7 @@ CREATE TABLE project (schema_change_type TEXT NOT NULL CHECK (schema_change_type IN ('DDL', 'SDL')) DEFAULT 'DDL',resource_id TEXT NOT NULL,data_classification_config_id TEXT NOT NULL DEFAULT '',- setting JSONB NOT NULL DEFAULT '{}'+ setting JSONB NOT NULL DEFAULT '{}');CREATE UNIQUE INDEX idx_project_unique_key ON project(key);@@ -763,7 +763,7 @@ CREATE INDEX idx_issue_assignee_id ON issue(assignee_id);CREATE INDEX idx_issue_created_ts ON issue(created_ts);-CREATE INDEX idx_issue_ts_vector ON issue USING gin(ts_vector);+CREATE INDEX idx_issue_ts_vector ON issue USING GIN(ts_vector);ALTER SEQUENCE issue_id_seq RESTART WITH 101;@@ -798,10 +798,10 @@ CREATE TABLE instance_change_history (database_id INTEGER REFERENCES db (id),-- issue_id is nullable because this field is backfilled and may not be present.issue_id INTEGER REFERENCES issue (id),- -- Record the client version creating this migration history. For Bytebase, we use its binary release version. Different Bytebase release might+ -- Record the client version creating this change history. For Bytebase, we use its binary release version. Different Bytebase release might-- record different history info and this field helps to handle such situation properly. Moreover, it helps debugging.release_version TEXT NOT NULL,- -- Used to detect out of order migration together with 'namespace' and 'version' column.+ -- Used to detect out of order change history together with 'namespace' and 'version' column.sequence BIGINT NOT NULL CONSTRAINT instance_change_history_sequence_check CHECK (sequence >= 0),-- We call it source because maybe we could load history from other migration tool.-- Currently allowed values are UI, VCS, LIBRARY.@@ -809,20 +809,20 @@ CREATE TABLE instance_change_history (-- Currently allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.type TEXT NOT NULL CONSTRAINT instance_change_history_type_check CHECK (type IN ('BASELINE', 'MIGRATE', 'MIGRATE_SDL', 'BRANCH', 'DATA')),-- Currently allowed values are PENDING, DONE, FAILED.- -- PostgreSQL can't do cross database transaction, so we can't record DDL and migration_history into a single transaction.+ -- PostgreSQL can't do cross database transaction, so we can't record DDL and change_history into a single transaction.-- Thus, we create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.status TEXT NOT NULL CONSTRAINT instance_change_history_status_check CHECK (status IN ('PENDING', 'DONE', 'FAILED')),- -- Record the migration version.+ -- Record the change version.version TEXT NOT NULL,description TEXT NOT NULL,-- Record the change statement in preview format.statement TEXT NOT NULL,-- Record the sheet for the change statement. Optional.sheet_id BIGINT NULL,- -- Record the schema after migration+ -- Record the schema after changeschema TEXT NOT NULL,- -- Record the schema before migration. Though we could also fetch it from the previous migration history, it would complicate fetching logic.- -- Besides, by storing the schema_prev, we can perform consistency check to see if the migration history has any gaps.+ -- Record the schema before change. Though we could also fetch it from the previous change history, it would complicate fetching logic.+ -- Besides, by storing the schema_prev, we can perform consistency check to see if the change history has any gaps.schema_prev TEXT NOT NULL,execution_duration_ns BIGINT NOT NULL,payload JSONB NOT NULL DEFAULT '{}'diff --git a/backend/store/role.go b/backend/store/role.goindex 7a60b80fea..0a42c0ce8a 100644--- a/backend/store/role.go+++ b/backend/store/role.go@@ -6,7 +6,10 @@ import ("fmt""strings"+ "google.golang.org/protobuf/encoding/protojson"+api "github.com/bytebase/bytebase/backend/legacyapi"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store")// RoleMessage is the message for roles.@@ -14,6 +17,7 @@ type RoleMessage struct {ResourceID stringName stringDescription string+ Permissions *storepb.RolePermissions// Output onlyCreatorID int@@ -26,16 +30,21 @@ type UpdateRoleMessage struct {Name *stringDescription *string+ Permissions *storepb.RolePermissions}// CreateRole creates a new role.func (s *Store) CreateRole(ctx context.Context, create *RoleMessage, creatorID int) (*RoleMessage, error) {query := `INSERT INTO- role (creator_id, updater_id, resource_id, name, description)- VALUES ($1, $2, $3, $4, $5)+ role (creator_id, updater_id, resource_id, name, description, permissions)+ VALUES ($1, $2, $3, $4, $5, $6)`- if _, err := s.db.db.ExecContext(ctx, query, creatorID, creatorID, create.ResourceID, create.Name, create.Description); err != nil {+ permissionBytes, err := protojson.Marshal(create.Permissions)+ if err != nil {+ return nil, err+ }+ if _, err := s.db.db.ExecContext(ctx, query, creatorID, creatorID, create.ResourceID, create.Name, create.Description, permissionBytes); err != nil {return nil, err}return create, nil@@ -45,17 +54,23 @@ func (s *Store) CreateRole(ctx context.Context, create *RoleMessage, creatorID ifunc (s *Store) GetRole(ctx context.Context, resourceID string) (*RoleMessage, error) {query := `SELECT- creator_id, name, description+ creator_id, name, description, permissionsFROM roleWHERE resource_id = $1`var role RoleMessage- if err := s.db.db.QueryRowContext(ctx, query, resourceID).Scan(&role.CreatorID, &role.Name, &role.Description); err != nil {+ var permissions []byte+ if err := s.db.db.QueryRowContext(ctx, query, resourceID).Scan(&role.CreatorID, &role.Name, &role.Description, &permissions); err != nil {if err == sql.ErrNoRows {return nil, nil}return nil, err}+ var rolePermissions storepb.RolePermissions+ if err := protojson.Unmarshal(permissions, &rolePermissions); err != nil {+ return nil, err+ }+ role.Permissions = &rolePermissionsrole.ResourceID = resourceIDreturn &role, nil}@@ -64,7 +79,7 @@ func (s *Store) GetRole(ctx context.Context, resourceID string) (*RoleMessage, efunc (s *Store) ListRoles(ctx context.Context) ([]*RoleMessage, error) {query := `SELECT- creator_id, resource_id, name, description+ creator_id, resource_id, name, description, permissionsFROM role`rows, err := s.db.db.QueryContext(ctx, query)@@ -133,9 +148,15 @@ func (s *Store) ListRoles(ctx context.Context) ([]*RoleMessage, error) {for rows.Next() {var role RoleMessage- if err := rows.Scan(&role.CreatorID, &role.ResourceID, &role.Name, &role.Description); err != nil {+ var permissions []byte+ if err := rows.Scan(&role.CreatorID, &role.ResourceID, &role.Name, &role.Description, &permissions); err != nil {+ return nil, err+ }+ var rolePermissions storepb.RolePermissions+ if err := protojson.Unmarshal(permissions, &rolePermissions); err != nil {return nil, err}+ role.Permissions = &rolePermissionsroles = append(roles, &role)}@@ -155,22 +176,34 @@ func (s *Store) UpdateRole(ctx context.Context, patch *UpdateRoleMessage) (*Roleif v := patch.Description; v != nil {set, args = append(set, fmt.Sprintf("description = $%d", len(args)+1)), append(args, *v)}+ if v := patch.Permissions; v != nil {+ permissionBytes, err := protojson.Marshal(v)+ if err != nil {+ return nil, err+ }+ set, args = append(set, fmt.Sprintf("permissions = $%d", len(args)+1)), append(args, permissionBytes)+ }args = append(args, patch.ResourceID)query := fmt.Sprintf(`UPDATE roleSET `+strings.Join(set, ", ")+`WHERE resource_id = $%d- RETURNING creator_id, name, description+ RETURNING creator_id, name, description, permissions`, len(args))role := RoleMessage{ResourceID: patch.ResourceID,}- if err := s.db.db.QueryRowContext(ctx, query, args...).Scan(&role.CreatorID, &role.Name, &role.Description); err != nil {+ var permissions []byte+ if err := s.db.db.QueryRowContext(ctx, query, args...).Scan(&role.CreatorID, &role.Name, &role.Description, &permissions); err != nil {return nil, err}-+ var rolePermissions storepb.RolePermissions+ if err := protojson.Unmarshal(permissions, &rolePermissions); err != nil {+ return nil, err+ }+ role.Permissions = &rolePermissionsreturn &role, nil}diff --git a/frontend/src/types/proto/store/role.ts b/frontend/src/types/proto/store/role.tsnew file mode 100644index 0000000000..24964b52ed--- /dev/null+++ b/frontend/src/types/proto/store/role.ts@@ -0,0 +1,83 @@+/* eslint-disable */+import Long from "long";+import _m0 from "protobufjs/minimal";++export const protobufPackage = "bytebase.store";++export interface RolePermissions {+ permissions: string[];+}++function createBaseRolePermissions(): RolePermissions {+ return { permissions: [] };+}++export const RolePermissions = {+ encode(message: RolePermissions, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {+ for (const v of message.permissions) {+ writer.uint32(10).string(v!);+ }+ return writer;+ },++ decode(input: _m0.Reader | Uint8Array, length?: number): RolePermissions {+ const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input);+ let end = length === undefined ? reader.len : reader.pos + length;+ const message = createBaseRolePermissions();+ while (reader.pos < end) {+ const tag = reader.uint32();+ switch (tag >>> 3) {+ case 1:+ if (tag !== 10) {+ break;+ }++ message.permissions.push(reader.string());+ continue;+ }+ if ((tag & 7) === 4 || tag === 0) {+ break;+ }+ reader.skipType(tag & 7);+ }+ return message;+ },++ fromJSON(object: any): RolePermissions {+ return {+ permissions: globalThis.Array.isArray(object?.permissions)+ ? object.permissions.map((e: any) => globalThis.String(e))+ : [],+ };+ },++ toJSON(message: RolePermissions): unknown {+ const obj: any = {};+ if (message.permissions?.length) {+ obj.permissions = message.permissions;+ }+ return obj;+ },++ create(base?: DeepPartial<RolePermissions>): RolePermissions {+ return RolePermissions.fromPartial(base ?? {});+ },+ fromPartial(object: DeepPartial<RolePermissions>): RolePermissions {+ const message = createBaseRolePermissions();+ message.permissions = object.permissions?.map((e) => e) || [];+ return message;+ },+};++type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;++export type DeepPartial<T> = T extends Builtin ? T+ : T extends Long ? string | number | Long : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>+ : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>+ : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }+ : Partial<T>;++if (_m0.util.Long !== Long) {+ _m0.util.Long = Long as any;+ _m0.configure();+}diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex 97b98be01f..105b07d424 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -156,6 +156,9 @@- [ProtectionRule.Target](#bytebase-store-ProtectionRule-Target)+- [store/role.proto](#store_role-proto)+ - [RolePermissions](#bytebase-store-RolePermissions)+- [store/setting.proto](#store_setting-proto)- [AgentPluginSetting](#bytebase-store-AgentPluginSetting)- [Announcement](#bytebase-store-Announcement)@@ -2419,6 +2422,37 @@ The type of target.+<a name="store_role-proto"></a>+<p align="right"><a href="#top">Top</a></p>++## store/role.proto++++<a name="bytebase-store-RolePermissions"></a>++### RolePermissions++++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| permissions | [string](#string) | repeated | |+++++++++++++++<a name="store_setting-proto"></a><p align="right"><a href="#top">Top</a></p>diff --git a/proto/generated-go/store/role.pb.go b/proto/generated-go/store/role.pb.gonew file mode 100644index 0000000000..8ae68102e8--- /dev/null+++ b/proto/generated-go/store/role.pb.go@@ -0,0 +1,144 @@+// Code generated by protoc-gen-go. DO NOT EDIT.+// versions:+// protoc-gen-go v1.32.0+// protoc (unknown)+// source: store/role.proto++package store++import (+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"+ reflect "reflect"+ sync "sync"+)++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 RolePermissions struct {+ state protoimpl.MessageState+ sizeCache protoimpl.SizeCache+ unknownFields protoimpl.UnknownFields++ Permissions []string `protobuf:"bytes,1,rep,name=permissions,proto3" json:"permissions,omitempty"`+}++func (x *RolePermissions) Reset() {+ *x = RolePermissions{}+ if protoimpl.UnsafeEnabled {+ mi := &file_store_role_proto_msgTypes[0]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+ }+}++func (x *RolePermissions) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RolePermissions) ProtoMessage() {}++func (x *RolePermissions) ProtoReflect() protoreflect.Message {+ mi := &file_store_role_proto_msgTypes[0]+ if protoimpl.UnsafeEnabled && x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RolePermissions.ProtoReflect.Descriptor instead.+func (*RolePermissions) Descriptor() ([]byte, []int) {+ return file_store_role_proto_rawDescGZIP(), []int{0}+}++func (x *RolePermissions) GetPermissions() []string {+ if x != nil {+ return x.Permissions+ }+ return nil+}++var File_store_role_proto protoreflect.FileDescriptor++var file_store_role_proto_rawDesc = []byte{+ 0x0a, 0x10, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x72, 0x6f, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f,+ 0x74, 0x6f, 0x12, 0x0e, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x73, 0x74, 0x6f,+ 0x72, 0x65, 0x22, 0x33, 0x0a, 0x0f, 0x52, 0x6f, 0x6c, 0x65, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73,+ 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73,+ 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0b, 0x70, 0x65, 0x72, 0x6d,+ 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x42, 0x14, 0x5a, 0x12, 0x67, 0x65, 0x6e, 0x65, 0x72,+ 0x61, 0x74, 0x65, 0x64, 0x2d, 0x67, 0x6f, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70,+ 0x72, 0x6f, 0x74, 0x6f, 0x33,+}++var (+ file_store_role_proto_rawDescOnce sync.Once+ file_store_role_proto_rawDescData = file_store_role_proto_rawDesc+)++func file_store_role_proto_rawDescGZIP() []byte {+ file_store_role_proto_rawDescOnce.Do(func() {+ file_store_role_proto_rawDescData = protoimpl.X.CompressGZIP(file_store_role_proto_rawDescData)+ })+ return file_store_role_proto_rawDescData+}++var file_store_role_proto_msgTypes = make([]protoimpl.MessageInfo, 1)+var file_store_role_proto_goTypes = []interface{}{+ (*RolePermissions)(nil), // 0: bytebase.store.RolePermissions+}+var file_store_role_proto_depIdxs = []int32{+ 0, // [0:0] is the sub-list for method output_type+ 0, // [0:0] is the sub-list for method input_type+ 0, // [0:0] is the sub-list for extension type_name+ 0, // [0:0] is the sub-list for extension extendee+ 0, // [0:0] is the sub-list for field type_name+}++func init() { file_store_role_proto_init() }+func file_store_role_proto_init() {+ if File_store_role_proto != nil {+ return+ }+ if !protoimpl.UnsafeEnabled {+ file_store_role_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {+ switch v := v.(*RolePermissions); i {+ case 0:+ return &v.state+ case 1:+ return &v.sizeCache+ case 2:+ return &v.unknownFields+ default:+ return nil+ }+ }+ }+ type x struct{}+ out := protoimpl.TypeBuilder{+ File: protoimpl.DescBuilder{+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),+ RawDescriptor: file_store_role_proto_rawDesc,+ NumEnums: 0,+ NumMessages: 1,+ NumExtensions: 0,+ NumServices: 0,+ },+ GoTypes: file_store_role_proto_goTypes,+ DependencyIndexes: file_store_role_proto_depIdxs,+ MessageInfos: file_store_role_proto_msgTypes,+ }.Build()+ File_store_role_proto = out.File+ file_store_role_proto_rawDesc = nil+ file_store_role_proto_goTypes = nil+ file_store_role_proto_depIdxs = nil+}diff --git a/proto/store/role.proto b/proto/store/role.protonew file mode 100644index 0000000000..a6e1e047d5--- /dev/null+++ b/proto/store/role.proto@@ -0,0 +1,9 @@+syntax = "proto3";++package bytebase.store;++option go_package = "generated-go/store";++message RolePermissions {+ repeated string permissions = 1;+}