Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: update iam policy (#16225)
ecmadaoed8128bf4984
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.goindex 2dc0a640e4..145957571b 100644--- a/backend/api/v1/project_service.go+++ b/backend/api/v1/project_service.go@@ -568,16 +568,10 @@ func (s *ProjectService) BatchGetIamPolicy(ctx context.Context, request *v1pb.Ba// SetIamPolicy sets the IAM policy for a project.func (s *ProjectService) SetIamPolicy(ctx context.Context, request *v1pb.SetIamPolicyRequest) (*v1pb.IamPolicy, error) {- var oldIamPolicyMsg *store.IamPolicyMessage-projectID, err := common.GetProjectID(request.Resource)if err != nil {return nil, status.Error(codes.InvalidArgument, err.Error())}- if err := s.validateIAMPolicy(ctx, request.Policy); err != nil {- return nil, status.Error(codes.InvalidArgument, err.Error())- }-project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{ResourceID: &projectID,})@@ -591,19 +585,27 @@ func (s *ProjectService) SetIamPolicy(ctx context.Context, request *v1pb.SetIamPreturn nil, status.Errorf(codes.NotFound, "project %q has been deleted", request.Resource)}- policy, err := convertToStoreIamPolicy(ctx, s.store, request.Policy)+ oldIamPolicyMsg, err := s.store.GetProjectIamPolicy(ctx, project.ResourceID)if err != nil {- return nil, status.Error(codes.Internal, err.Error())+ return nil, status.Errorf(codes.Internal, "failed to find project iam policy with error: %v", err.Error())+ }+ if request.Etag != "" && request.Etag != oldIamPolicyMsg.Etag {+ return nil, status.Errorf(codes.Aborted, "there is concurrent update to the project iam policy, please refresh and try again.")}- policyMessage, err := s.store.GetProjectIamPolicy(ctx, project.ResourceID)+ existProjectOwner, err := validateIAMPolicy(ctx, s.store, s.iamManager, request.Policy, oldIamPolicyMsg)if err != nil {- return nil, status.Errorf(codes.Internal, "failed to find project iam policy with error: %v", err.Error())+ return nil, err}- if request.Etag != "" && request.Etag != policyMessage.Etag {- return nil, status.Errorf(codes.Aborted, "there is concurrent update to the project iam policy, please refresh and try again.")+ // Must contain one owner binding.+ if !existProjectOwner {+ return nil, status.Errorf(codes.InvalidArgument, "IAM Policy must have at least one binding with %s", base.ProjectOwner.String())+ }++ policy, err := convertToStoreIamPolicy(ctx, s.store, request.Policy)+ if err != nil {+ return nil, err}- oldIamPolicyMsg = policyMessagepolicyPayload, err := protojson.Marshal(policy)if err != nil {@@ -1205,10 +1207,10 @@ func convertToStoreIamPolicy(ctx context.Context, stores *store.Store, iamPolicyfor _, binding := range iamPolicy.Bindings {var members []string- for _, member := range binding.Members {+ for _, member := range utils.Uniq(binding.Members) {storeMember, err := convertToStoreIamPolicyMember(ctx, stores, member)if err != nil {- return nil, err+ return nil, status.Errorf(codes.Internal, "failed to convert iam member with error: %v", err.Error())}members = append(members, storeMember)}@@ -1227,6 +1229,10 @@ func convertToStoreIamPolicy(ctx context.Context, stores *store.Store, iamPolicybindings = append(bindings, storeBinding)}+ if len(bindings) == 0 {+ return nil, status.Errorf(codes.InvalidArgument, "policy binding is empty")+ }+return &storepb.IamPolicy{Bindings: bindings,}, nil@@ -1336,87 +1342,112 @@ func convertToProjectMessage(resourceID string, project *v1pb.Project) (*store.P}, nil}-func (s *ProjectService) validateIAMPolicy(ctx context.Context, policy *v1pb.IamPolicy) error {+func getBindingIdentifier(role string, condition *expr.Expr) string {+ ids := []string{+ fmt.Sprintf("[role] %s", role),+ }+ if condition != nil {+ ids = append(+ ids,+ fmt.Sprintf("[title] %s", condition.Title),+ fmt.Sprintf("[description] %s", condition.Description),+ fmt.Sprintf("[expression] %s", condition.Expression),+ )+ }+ return strings.Join(ids, ";")+}++func validateIAMPolicy(+ ctx context.Context,+ stores *store.Store,+ iamManager *iam.Manager,+ policy *v1pb.IamPolicy,+ oldPolicyMessage *store.IamPolicyMessage,+) (bool, error) {if policy == nil {- return errors.Errorf("IAM Policy is required")+ return false, status.Error(codes.InvalidArgument, "IAM Policy is required")+ }+ if len(policy.Bindings) == 0 {+ return false, status.Error(codes.InvalidArgument, "IAM Binding is empty")}- generalSetting, err := s.store.GetWorkspaceGeneralSetting(ctx)+ generalSetting, err := stores.GetWorkspaceGeneralSetting(ctx)if err != nil {- return errors.Wrap(err, "failed to get workspace general setting")+ return false, status.Error(codes.Internal, "failed to get workspace general setting")}var maximumRoleExpiration *durationpb.Durationif generalSetting != nil {maximumRoleExpiration = generalSetting.MaximumRoleExpiration}- roleMessages, err := s.store.ListRoles(ctx)+ roleMessages, err := stores.ListRoles(ctx)if err != nil {- return status.Errorf(codes.Internal, "failed to list roles: %v", err)+ return false, status.Errorf(codes.Internal, "failed to list roles: %v", err)}- roles := convertToRoles(roleMessages, v1pb.Role_CUSTOM)- for _, predefinedRole := range s.iamManager.PredefinedRoles {- roles = append(roles, convertToRole(predefinedRole, v1pb.Role_BUILT_IN))+ roleMessages = append(roleMessages, iamManager.PredefinedRoles...)++ existingBindings := make(map[string]bool)+ for _, oldBinding := range oldPolicyMessage.Policy.Bindings {+ identifier := getBindingIdentifier(oldBinding.Role, oldBinding.Condition)+ existingBindings[identifier] = true}- return s.validateBindings(policy.Bindings, roles, maximumRoleExpiration)-}+ existProjectOwner := false+ bindings := []*v1pb.Binding{}+ for _, binding := range policy.Bindings {+ if len(binding.Members) == 0 {+ continue+ }+ if binding.Role == fmt.Sprintf("roles/%s", base.ProjectOwner) {+ existProjectOwner = true+ }-func (*ProjectService) validateBindings(bindings []*v1pb.Binding, roles []*v1pb.Role, maximumRoleExpiration *durationpb.Duration) error {- if len(bindings) == 0 {- return errors.Errorf("IAM Binding is required")+ identifier := getBindingIdentifier(binding.Role, binding.Condition)+ if !existingBindings[identifier] {+ bindings = append(bindings, binding)+ }}- projectRoleMap := make(map[string]bool)+ return existProjectOwner, validateBindings(bindings, roleMessages, maximumRoleExpiration)+}++func validateBindings(bindings []*v1pb.Binding, roles []*store.RoleMessage, maximumRoleExpiration *durationpb.Duration) error {existingRoles := make(map[string]bool)for _, role := range roles {- existingRoles[role.Name] = true+ existingRoles[common.FormatRole(role.ResourceID)] = true}+for _, binding := range bindings {- if len(binding.Members) == 0 {- continue- }if binding.Role == "" {- return errors.Errorf("IAM Binding role is required")+ return status.Error(codes.InvalidArgument, "IAM Binding role is required")}if !existingRoles[binding.Role] {- return errors.Errorf("IAM Binding role %s does not exist", binding.Role)- }-- // Users within each binding must be unique.- binding.Members = utils.Uniq(binding.Members)- for _, member := range binding.Members {- if err := validateMember(member); err != nil {- return err- }+ return status.Errorf(codes.InvalidArgument, "IAM Binding role %s does not exist", binding.Role)}- projectRoleMap[binding.Role] = trueif _, err := common.ValidateProjectMemberCELExpr(binding.Condition); err != nil {return err}- // Only validate when maximumRoleExpiration is set and the role is SQLEditorUser or ProjectExporter.- rolesToValidate := []string{fmt.Sprintf("roles/%s", base.SQLEditorUser), fmt.Sprintf("roles/%s", base.ProjectExporter)}- if maximumRoleExpiration != nil && binding.Condition != nil && binding.Condition.Expression != "" && slices.Contains(rolesToValidate, binding.Role) {- if err := validateIAMPolicyExpression(binding.Condition.Expression, maximumRoleExpiration); err != nil {- return err+ if binding.Role != fmt.Sprintf("roles/%s", base.ProjectOwner) && maximumRoleExpiration != nil {+ // Only validate when maximumRoleExpiration is set and the role is not project owner.+ if err := validateExpirationInExpression(binding.GetCondition().GetExpression(), maximumRoleExpiration); err != nil {+ return status.Errorf(codes.InvalidArgument, "failed to validate expiration for binding %v: %v", binding.Role, err.Error())}}}- // Must contain one owner binding.- if _, ok := projectRoleMap[common.FormatRole(base.ProjectOwner.String())]; !ok {- return errors.Errorf("IAM Policy must have at least one binding with %s", base.ProjectOwner.String())- }return nil}-// validateIAMPolicyExpression validates the IAM policy expression.+// validateExpirationInExpression validates the IAM policy expression.// Currently only validate the following expression:// * request.time < timestamp("2021-01-01T00:00:00Z")//// Other expressions will be ignored.-func validateIAMPolicyExpression(expr string, maximumRoleExpiration *durationpb.Duration) error {+func validateExpirationInExpression(expr string, maximumRoleExpiration *durationpb.Duration) error {+ if expr == "" {+ return nil+ }e, err := cel.NewEnv()if err != nil {return errors.Wrap(err, "failed to create cel environment")diff --git a/backend/api/v1/project_service_test.go b/backend/api/v1/project_service_test.goindex 44ac8af2fc..080511cf2b 100644--- a/backend/api/v1/project_service_test.go+++ b/backend/api/v1/project_service_test.go@@ -56,13 +56,13 @@ func TestValidateMembers(t *testing.T) {func TestValidateBindings(t *testing.T) {tests := []struct {bindings []*v1pb.Binding- roles []*v1pb.Role+ roles []*store.RoleMessagewantErr bool}{// Empty binding list.{bindings: []*v1pb.Binding{},- wantErr: true,+ wantErr: false,},// Invalid project role.{@@ -71,9 +71,9 @@ func TestValidateBindings(t *testing.T) {Role: "roles/haha",},},- roles: []*v1pb.Role{+ roles: []*store.RoleMessage{{- Name: "roles/projectOwner",+ ResourceID: "projectOwner",},},wantErr: true,@@ -86,37 +86,72 @@ func TestValidateBindings(t *testing.T) {Members: []string{"user:bytebase"},},{- Role: "role/projectDeveloper",+ Role: "roles/projectDeveloper",Members: []string{},},},- roles: []*v1pb.Role{+ roles: []*store.RoleMessage{{- Name: "roles/projectOwner",+ ResourceID: "projectOwner",},{- Name: "role/projectDeveloper",+ ResourceID: "projectDeveloper",},},wantErr: false,},+ {+ bindings: []*v1pb.Binding{+ {+ Role: "roles/projectOwner",+ Members: []string{},+ },+ },+ roles: []*store.RoleMessage{+ {+ ResourceID: "projectOwner",+ },+ {+ ResourceID: "projectDeveloper",+ },+ },+ wantErr: false,+ },+ // Invalid condition+ {+ bindings: []*v1pb.Binding{+ {+ Role: "roles/projectOwner",+ Members: []string{"user:bytebase"},+ Condition: &expr.Expr{+ Expression: `database == "employee" && environment_name == "test"`,+ },+ },+ },+ roles: []*store.RoleMessage{+ {+ ResourceID: "projectOwner",+ },+ },+ wantErr: true,+ },// Must contain one owner binding.{bindings: []*v1pb.Binding{{- Role: "role/projectDeveloper",+ Role: "roles/projectDeveloper",Members: []string{"user:bytebase"},},},- roles: []*v1pb.Role{+ roles: []*store.RoleMessage{{- Name: "roles/projectOwner",+ ResourceID: "projectOwner",},{- Name: "role/projectDeveloper",+ ResourceID: "projectDeveloper",},},- wantErr: true,+ wantErr: false,},{bindings: []*v1pb.Binding{@@ -130,12 +165,12 @@ func TestValidateBindings(t *testing.T) {Members: []string{"user:foo"},},},- roles: []*v1pb.Role{+ roles: []*store.RoleMessage{{- Name: "roles/projectOwner",+ ResourceID: "projectOwner",},{- Name: "role/projectDeveloper",+ ResourceID: "projectDeveloper",},},wantErr: false,@@ -148,12 +183,12 @@ func TestValidateBindings(t *testing.T) {Members: []string{"user:bytebase"},},},- roles: []*v1pb.Role{+ roles: []*store.RoleMessage{{- Name: "roles/projectOwner",+ ResourceID: "projectOwner",},{- Name: "role/projectDeveloper",+ ResourceID: "projectDeveloper",},},wantErr: false,@@ -165,16 +200,16 @@ func TestValidateBindings(t *testing.T) {Members: []string{"user:bytebase"},},{- Role: "role/projectDeveloper",+ Role: "roles/projectDeveloper",Members: []string{"user:foo"},},},- roles: []*v1pb.Role{+ roles: []*store.RoleMessage{{- Name: "roles/projectOwner",+ ResourceID: "projectOwner",},{- Name: "role/projectDeveloper",+ ResourceID: "projectDeveloper",},},wantErr: false,@@ -182,10 +217,8 @@ func TestValidateBindings(t *testing.T) {}a := require.New(t)- // Mock an empty project service to test the validateBindings function.- projectService := NewProjectService(nil, nil, nil, nil)for _, tt := range tests {- err := projectService.validateBindings(tt.bindings, tt.roles, nil)+ err := validateBindings(tt.bindings, tt.roles, nil)if tt.wantErr {a.Error(err)} else {@@ -213,7 +246,7 @@ func TestValidateIAMPolicyExpression(t *testing.T) {}for _, tt := range tests {- err := validateIAMPolicyExpression(tt.expr, tt.maximumRoleExpiration)+ err := validateExpirationInExpression(tt.expr, tt.maximumRoleExpiration)if tt.wantErr {require.Error(t, err)} else {diff --git a/backend/api/v1/workspace_service.go b/backend/api/v1/workspace_service.goindex f62e305751..047f0b7c7a 100644--- a/backend/api/v1/workspace_service.go+++ b/backend/api/v1/workspace_service.go@@ -47,9 +47,13 @@ func (s *WorkspaceService) SetIamPolicy(ctx context.Context, request *v1pb.SetIareturn nil, status.Errorf(codes.Aborted, "there is concurrent update to the workspace iam policy, please refresh and try again.")}+ if _, err := validateIAMPolicy(ctx, s.store, s.iamManager, request.Policy, policyMessage); err != nil {+ return nil, err+ }+iamPolicy, err := convertToStoreIamPolicy(ctx, s.store, request.Policy)if err != nil {- return nil, status.Errorf(codes.Internal, "failed to convert iam policy with error: %v", err.Error())+ return nil, err}users := utils.GetUsersByRoleInIAMPolicy(ctx, s.store, base.WorkspaceAdmin, iamPolicy)if !containsActiveEndUser(users) {diff --git a/frontend/src/components/ExpirationSelector.vue b/frontend/src/components/ExpirationSelector.vueindex 189e423eae..69cdeca236 100644--- a/frontend/src/components/ExpirationSelector.vue+++ b/frontend/src/components/ExpirationSelector.vue@@ -9,43 +9,45 @@<divv-for="option in options":key="option.value"- class="col-span-1 h-8 flex flex-row justify-start items-center"+ :class="[+ 'col-span-1 h-8 flex flex-row justify-start items-center',+ option.value === -2 ? 'col-span-2' : '',+ option.value === -1 ? 'col-span-3' : '',+ ]"><NRadio :value="option.value" :label="option.label" />- </div>- <div class="col-span-2 flex flex-row justify-start items-center">- <NRadio :value="-2" :label="$t('issue.grant-request.custom')" />- <NInputNumber- size="small"- style="width: 5rem"- :min="1"- :max="maximumRoleExpiration"- :placeholder="$t('common.date.days')"- :disabled="state.selected !== -2"- :value="customExpirationDays"- @update:value="handleCustomExpirationDaysChange"- />- <span class="ml-2">{{ $t("common.date.days") }}</span>- </div>- <div class="col-span-3 flex flex-row justify-start items-center">- <NRadio :value="-1" :label="$t('issue.grant-request.custom')" />- <NDatePicker- size="small"- :value="- state.selected === -1 ? state.expirationTimestampInMS : undefined- "- :disabled="state.selected !== -1"- :actions="null"- :update-value-on-close="true"- type="datetime"- :is-date-disabled="isDateDisabled"- clearable- @update:value="(val) => (state.expirationTimestampInMS = val)"- />- <span v-if="maximumRoleExpiration" class="ml-3 textinfolabel">- {{ $t("settings.general.workspace.maximum-role-expiration.self") }}:- {{ $t("common.date.days", { days: maximumRoleExpiration }) }}- </span>+ <template v-if="option.value === -2">+ <NInputNumber+ size="small"+ style="width: 5rem"+ :min="1"+ :max="maximumRoleExpiration"+ :placeholder="$t('common.date.days')"+ :disabled="state.selected !== -2"+ :value="customExpirationDays"+ @update:value="handleCustomExpirationDaysChange"+ />+ <span class="ml-2">{{ $t("common.date.days") }}</span>+ </template>+ <template v-else-if="option.value === -1">+ <NDatePicker+ size="small"+ :value="+ state.selected === -1 ? state.expirationTimestampInMS : undefined+ "+ :disabled="state.selected !== -1"+ :actions="null"+ :update-value-on-close="true"+ type="datetime"+ :is-date-disabled="isDateDisabled"+ clearable+ @update:value="(val) => (state.expirationTimestampInMS = val)"+ />+ <span v-if="maximumRoleExpiration" class="ml-3 textinfolabel">+ {{ $t("settings.general.workspace.maximum-role-expiration.self") }}:+ {{ $t("common.date.days", { days: maximumRoleExpiration }) }}+ </span>+ </template></div></NRadioGroup></template>@@ -54,7 +56,7 @@import { useLocalStorage } from "@vueuse/core";import dayjs from "dayjs";import { NRadio, NRadioGroup, NDatePicker, NInputNumber } from "naive-ui";-import { computed, reactive, watch, onMounted, watchEffect } from "vue";+import { computed, reactive, watch, watchEffect } from "vue";import { useI18n } from "vue-i18n";import { useSettingV1Store } from "@/store";import { PresetRoleType } from "@/types";@@ -162,6 +164,16 @@ const options = computed((): ExpirationOption[] => {label: t("project.members.never-expires"),});}+ options.push(+ {+ value: -2,+ label: t("issue.grant-request.custom"),+ },+ {+ value: -1,+ label: t("issue.grant-request.custom"),+ }+ );return options;});@@ -169,23 +181,25 @@ const onSelect = (value: number) => {if (value > 0) {state.expirationTimestampInMS =new Date().getTime() + value * 24 * 60 * 60 * 1000;- } else {- state.expirationTimestampInMS = undefined;}state.selected = value;};-onMounted(() => {- let value = state.selected;- if (!options.value.find((o) => o.value === state.selected)) {- value = options.value[0].value;- }- onSelect(value);-});-watch(() => props.role,- () => onSelect(options.value[0].value)+ () => {+ let value = state.selected;+ if (!options.value.find((o) => o.value === state.selected)) {+ const neverExpire = options.value.find((o) => o.value === 0);+ if (neverExpire) {+ value = neverExpire.value;+ } else {+ value = options.value[0].value;+ }+ }+ onSelect(value);+ },+ { immediate: true });watch(diff --git a/frontend/src/components/GeneralSetting/MaximumRoleExpirationSetting.vue b/frontend/src/components/GeneralSetting/MaximumRoleExpirationSetting.vueindex f8581a6ccd..4c12719945 100644--- a/frontend/src/components/GeneralSetting/MaximumRoleExpirationSetting.vue+++ b/frontend/src/components/GeneralSetting/MaximumRoleExpirationSetting.vue@@ -78,6 +78,7 @@ const handleSettingChange = async () => {"value.workspace_profile_setting_value.maximum_role_expiration",],});+ Object.assign(state, getInitialState());};defineExpose({diff --git a/frontend/src/components/SQLReview/components/SQLReviewForResource.vue b/frontend/src/components/SQLReview/components/SQLReviewForResource.vueindex e87afa85c8..4eaf808a69 100644--- a/frontend/src/components/SQLReview/components/SQLReviewForResource.vue+++ b/frontend/src/components/SQLReview/components/SQLReviewForResource.vue@@ -18,7 +18,12 @@@click="onSQLReviewPolicyClick">{{ pendingSelectReviewPolicy.name }}- <NButton quaternary size="tiny" @click.stop="onReviewPolicyRemove">+ <NButton+ v-if="allowEditSQLReviewTag"+ quaternary+ size="tiny"+ @click.stop="onReviewPolicyRemove"+ ><template #icon><XIcon class="w-4 h-auto" /></template>