sharedresource.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package db
  15. import (
  16. "context"
  17. "database/sql"
  18. "yunion.io/x/pkg/errors"
  19. "yunion.io/x/pkg/util/rbacscope"
  20. "yunion.io/x/pkg/utils"
  21. "yunion.io/x/onecloud/pkg/cloudcommon/consts"
  22. "yunion.io/x/onecloud/pkg/cloudcommon/policy"
  23. "yunion.io/x/onecloud/pkg/httperrors"
  24. "yunion.io/x/onecloud/pkg/mcclient"
  25. "yunion.io/x/onecloud/pkg/util/stringutils2"
  26. )
  27. const (
  28. SharedTargetProject = "project"
  29. SharedTargetDomain = "domain"
  30. )
  31. // sharing resource between projects/domains
  32. type SSharedResource struct {
  33. SResourceBase
  34. Id int64 `primary:"true" auto_increment:"true"`
  35. ResourceType string `width:"32" charset:"ascii" nullable:"false" json:"resource_type"`
  36. ResourceId string `width:"128" charset:"ascii" nullable:"false" index:"true" json:"resource_id"`
  37. // OwnerProjectId string `width:"128" charset:"ascii" nullable:"false" index:"true" json:"owner_project_id"`
  38. TargetProjectId string `width:"128" charset:"ascii" nullable:"false" index:"true" json:"target_project_id"`
  39. TargetType string `width:"8" charset:"ascii" default:"project" nullable:"false" json:"target_type"`
  40. }
  41. type SSharedResourceManager struct {
  42. SResourceBaseManager
  43. }
  44. var SharedResourceManager *SSharedResourceManager
  45. func init() {
  46. SharedResourceManager = &SSharedResourceManager{
  47. SResourceBaseManager: NewResourceBaseManager(
  48. SSharedResource{},
  49. "shared_resources_tbl",
  50. "shared_resource",
  51. "shared_resources",
  52. ),
  53. }
  54. }
  55. func (manager *SSharedResourceManager) CleanModelShares(ctx context.Context, userCred mcclient.TokenCredential, model ISharableBaseModel) error {
  56. var err error
  57. resScope := model.GetModelManager().ResourceScope()
  58. switch resScope {
  59. case rbacscope.ScopeProject:
  60. _, err = manager.shareToTarget(ctx, userCred, model, SharedTargetProject, nil, nil, nil)
  61. if err != nil {
  62. return errors.Wrap(err, "remove shared project")
  63. }
  64. _, err = manager.shareToTarget(ctx, userCred, model, SharedTargetDomain, nil, nil, nil)
  65. if err != nil {
  66. return errors.Wrap(err, "remove shared domain")
  67. }
  68. case rbacscope.ScopeDomain:
  69. _, err = manager.shareToTarget(ctx, userCred, model, SharedTargetDomain, nil, nil, nil)
  70. if err != nil {
  71. return errors.Wrap(err, "remove shared domain")
  72. }
  73. }
  74. return nil
  75. }
  76. func (manager *SSharedResourceManager) shareToTarget(
  77. ctx context.Context,
  78. userCred mcclient.TokenCredential,
  79. model ISharableBaseModel,
  80. targetType string,
  81. targetIds []string,
  82. candidateIds []string,
  83. requireDomainIds []string,
  84. ) ([]string, error) {
  85. var requireScope rbacscope.TRbacScope
  86. resScope := model.GetModelManager().ResourceScope()
  87. switch resScope {
  88. case rbacscope.ScopeUser:
  89. switch targetType {
  90. case SharedTargetDomain:
  91. // should have system-level privileges
  92. requireScope = rbacscope.ScopeSystem
  93. case SharedTargetProject:
  94. requireScope = rbacscope.ScopeDomain
  95. }
  96. case rbacscope.ScopeProject:
  97. switch targetType {
  98. case SharedTargetProject:
  99. // should have domain-level privileges
  100. // cannot share to a project across domain
  101. requireScope = rbacscope.ScopeDomain
  102. case SharedTargetDomain:
  103. // should have system-level privileges
  104. requireScope = rbacscope.ScopeSystem
  105. }
  106. case rbacscope.ScopeDomain:
  107. switch targetType {
  108. case SharedTargetDomain:
  109. // should have system-level privileges
  110. requireScope = rbacscope.ScopeSystem
  111. case SharedTargetProject:
  112. if len(targetIds) > 0 {
  113. return nil, errors.Wrap(httperrors.ErrNotSupported, "cannot share a domain resource to specific project")
  114. }
  115. }
  116. default:
  117. return nil, errors.Wrap(httperrors.ErrNotSupported, "cannot share a non-project/domain resource")
  118. }
  119. srs := make([]SSharedResource, 0)
  120. q := SharedResourceManager.Query()
  121. q = q.Equals("resource_type", model.Keyword())
  122. q = q.Equals("resource_id", model.GetId())
  123. q = q.Equals("target_type", targetType)
  124. err := FetchModelObjects(SharedResourceManager, q, &srs)
  125. if err != nil && errors.Cause(err) != sql.ErrNoRows {
  126. return nil, errors.Wrap(err, "Fetch shared project")
  127. }
  128. srsMap := make(map[string]*SSharedResource)
  129. _existIds := make([]string, len(srs))
  130. for i := 0; i < len(srs); i++ {
  131. _existIds[i] = srs[i].TargetProjectId
  132. srsMap[srs[i].TargetProjectId] = &srs[i]
  133. }
  134. existIds := stringutils2.NewSortedStrings(_existIds)
  135. newIds := stringutils2.NewSortedStrings([]string{})
  136. modelOwnerId := model.GetOwnerId()
  137. for i := 0; i < len(targetIds); i++ {
  138. switch targetType {
  139. case SharedTargetProject:
  140. tenant, err := DefaultProjectFetcher(ctx, targetIds[i], "")
  141. if err != nil {
  142. return nil, errors.Wrapf(err, "fetch tenant %s error", targetIds[i])
  143. }
  144. if tenant.DomainId != modelOwnerId.GetProjectDomainId() {
  145. return nil, errors.Wrap(httperrors.ErrBadRequest, "can't shared project to other domain")
  146. }
  147. if tenant.GetId() == modelOwnerId.GetProjectId() {
  148. // ignore self project
  149. continue
  150. // return nil, errors.Wrap(httperrors.ErrBadRequest, "can't share to self project")
  151. }
  152. newIds = stringutils2.Append(newIds, tenant.GetId())
  153. case SharedTargetDomain:
  154. domain, err := DefaultDomainFetcher(ctx, targetIds[i])
  155. if err != nil {
  156. return nil, errors.Wrapf(err, "fetch domain %s error", targetIds[i])
  157. }
  158. if domain.GetId() == modelOwnerId.GetProjectDomainId() {
  159. // ignore self domain
  160. continue
  161. // return nil, errors.Wrapf(httperrors.ErrBadRequest, "can't share to self domain %s", modelOwnerId.GetProjectDomainId())
  162. }
  163. if len(candidateIds) > 0 && !utils.IsInStringArray(domain.GetId(), candidateIds) {
  164. return nil, errors.Wrapf(httperrors.ErrForbidden, "share target domain %s not in candidate list %s", domain.GetId(), candidateIds)
  165. }
  166. newIds = stringutils2.Append(newIds, domain.GetId())
  167. }
  168. }
  169. delIds, keepIds, addIds := stringutils2.Split(existIds, newIds)
  170. if len(delIds) == 0 && len(addIds) == 0 {
  171. return keepIds, nil
  172. }
  173. if targetType == SharedTargetDomain && len(requireDomainIds) > 0 && len(delIds) > 0 {
  174. for _, delId := range delIds {
  175. if utils.IsInStringArray(delId, requireDomainIds) {
  176. return nil, errors.Wrapf(httperrors.ErrForbidden, "domain %s is required to share", delId)
  177. }
  178. }
  179. }
  180. allowScope, policyTags := policy.PolicyManager.AllowScope(userCred, consts.GetServiceType(), model.KeywordPlural(), policy.PolicyActionPerform, "public")
  181. if requireScope.HigherThan(allowScope) {
  182. return nil, errors.Wrapf(httperrors.ErrNotSufficientPrivilege, "require %s allow %s", requireScope, allowScope)
  183. }
  184. err = objectConfirmPolicyTags(ctx, model, policyTags)
  185. if err != nil {
  186. return nil, errors.Wrap(err, "objectConfirmPolicyTags")
  187. }
  188. for _, targetId := range delIds {
  189. sr := srsMap[targetId]
  190. if err := sr.Delete(ctx, userCred); err != nil {
  191. return nil, errors.Wrap(err, "delete")
  192. }
  193. }
  194. for _, targetId := range addIds {
  195. sharedResource := new(SSharedResource)
  196. sharedResource.ResourceType = model.Keyword()
  197. sharedResource.ResourceId = model.GetId()
  198. sharedResource.TargetProjectId = targetId
  199. sharedResource.TargetType = targetType
  200. if insetErr := SharedResourceManager.TableSpec().Insert(ctx, sharedResource); insetErr != nil {
  201. return nil, httperrors.NewInternalServerError("Insert shared resource failed %s", insetErr)
  202. }
  203. }
  204. keepIds = append(keepIds, addIds...)
  205. return keepIds, nil
  206. }