encrypted.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. "time"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/log"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/pkg/util/reflectutils"
  22. "yunion.io/x/pkg/util/timeutils"
  23. "yunion.io/x/onecloud/pkg/apis"
  24. identity_apis "yunion.io/x/onecloud/pkg/apis/identity"
  25. "yunion.io/x/onecloud/pkg/cloudcommon/consts"
  26. "yunion.io/x/onecloud/pkg/httperrors"
  27. "yunion.io/x/onecloud/pkg/mcclient"
  28. "yunion.io/x/onecloud/pkg/mcclient/auth"
  29. identity_modules "yunion.io/x/onecloud/pkg/mcclient/modules/identity"
  30. "yunion.io/x/onecloud/pkg/util/stringutils2"
  31. )
  32. type SEncryptedResourceManager struct {
  33. }
  34. // +onecloud:model-api-gen
  35. type SEncryptedResource struct {
  36. // 加密密钥ID
  37. EncryptKeyId string `width:"32" charset:"ascii" nullable:"true" get:"user" list:"user" create:"optional"`
  38. }
  39. func (res *SEncryptedResource) IsEncrypted() bool {
  40. return len(res.EncryptKeyId) > 0
  41. }
  42. func (res *SEncryptedResource) GetEncryptInfo(
  43. ctx context.Context,
  44. userCred mcclient.TokenCredential,
  45. ) (apis.SEncryptInfo, error) {
  46. ret := apis.SEncryptInfo{}
  47. session := auth.GetSession(ctx, userCred, consts.GetRegion())
  48. secKey, err := identity_modules.Credentials.GetEncryptKey(session, res.EncryptKeyId)
  49. if err != nil {
  50. return ret, errors.Wrap(err, "GetEncryptKey")
  51. }
  52. ret.Id = secKey.KeyId
  53. ret.Name = secKey.KeyName
  54. ret.Key = secKey.Key
  55. ret.Alg = secKey.Alg
  56. return ret, nil
  57. }
  58. func (res *SEncryptedResource) ValidateEncryption(ctx context.Context, userCred mcclient.TokenCredential) error {
  59. if res.IsEncrypted() {
  60. _, err := res.GetEncryptInfo(ctx, userCred)
  61. if err != nil {
  62. return errors.Wrap(err, "GetEncryptInfo")
  63. }
  64. }
  65. return nil
  66. }
  67. func (manager *SEncryptedResourceManager) ValidateCreateData(
  68. ctx context.Context,
  69. userCred mcclient.TokenCredential,
  70. ownerId mcclient.IIdentityProvider,
  71. query jsonutils.JSONObject,
  72. input apis.EncryptedResourceCreateInput,
  73. ) (apis.EncryptedResourceCreateInput, error) {
  74. if input.EncryptKeyId != nil && len(*input.EncryptKeyId) > 0 {
  75. session := auth.GetSession(ctx, userCred, consts.GetRegion())
  76. keyObj, err := identity_modules.Credentials.Get(session, *input.EncryptKeyId, nil)
  77. if err != nil {
  78. return input, errors.Wrap(err, "Credentials get key")
  79. }
  80. keyType, _ := keyObj.GetString("type")
  81. if keyType != identity_apis.ENCRYPT_KEY_TYPE {
  82. return input, errors.Wrap(httperrors.ErrInvalidFormat, "key type is not enc_key")
  83. }
  84. keyId, err := keyObj.GetString("id")
  85. if err != nil {
  86. return input, errors.Wrap(err, "GetString key Id")
  87. }
  88. input.EncryptKeyId = &keyId
  89. }
  90. return input, nil
  91. }
  92. func (res *SEncryptedResource) CustomizeCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, data jsonutils.JSONObject, nameHint string) error {
  93. if len(res.EncryptKeyId) == 0 && jsonutils.QueryBoolean(data, "encrypt_key_new", false) && !jsonutils.QueryBoolean(data, "dry_run", false) {
  94. // create new encrypt key
  95. session := auth.GetAdminSession(ctx, consts.GetRegion())
  96. now := time.Now()
  97. keyName := "key-" + nameHint + "-" + timeutils.ShortDate(now)
  98. algName, _ := data.GetString("encrypt_key_alg")
  99. userId, _ := data.GetString("encrypt_key_user_id")
  100. secret, err := identity_modules.Credentials.CreateEncryptKey(session, userId, keyName, algName)
  101. if err != nil {
  102. return errors.Wrap(err, "Credentials.CreateEncryptKey")
  103. }
  104. res.EncryptKeyId = secret.KeyId
  105. }
  106. return nil
  107. }
  108. func (manager *SEncryptedResourceManager) FetchCustomizeColumns(
  109. ctx context.Context,
  110. userCred mcclient.TokenCredential,
  111. query jsonutils.JSONObject,
  112. objs []interface{},
  113. fields stringutils2.SSortedStrings,
  114. isList bool,
  115. ) []apis.EncryptedResourceDetails {
  116. rets := make([]apis.EncryptedResourceDetails, len(objs))
  117. session := auth.GetSession(ctx, userCred, consts.GetRegion())
  118. encKeyMap := make(map[string]identity_modules.SEncryptKeySecret)
  119. for i := range objs {
  120. var base *SEncryptedResource
  121. reflectutils.FindAnonymouStructPointer(objs[i], &base)
  122. if base != nil && len(base.EncryptKeyId) > 0 {
  123. encKey, ok := encKeyMap[base.EncryptKeyId]
  124. if !ok {
  125. secKey, err := identity_modules.Credentials.GetEncryptKey(session, base.EncryptKeyId)
  126. if err != nil {
  127. log.Errorf("fail to fetch enc key %s: %s", base.EncryptKeyId, err)
  128. continue
  129. }
  130. encKey = secKey
  131. encKeyMap[base.EncryptKeyId] = secKey
  132. }
  133. rets[i].EncryptKey = encKey.KeyName
  134. rets[i].EncryptAlg = string(encKey.Alg)
  135. rets[i].EncryptKeyUser = string(encKey.User)
  136. rets[i].EncryptKeyUserId = string(encKey.UserId)
  137. rets[i].EncryptKeyUserDomain = string(encKey.Domain)
  138. rets[i].EncryptKeyUserDomainId = string(encKey.DomainId)
  139. }
  140. }
  141. return rets
  142. }