fix version 1

This commit is contained in:
2026-09-22 21:15:34 +08:00
parent 9f86366638
commit d63d7e8b3a
277 changed files with 9959 additions and 1514 deletions

View File

@@ -53,6 +53,12 @@ func CopyFile(ctx context.Context, in *pb.CopyFileRequest) (reply *pb.StatusRepl
return nil, errcode.ErrAlreadyExists
}
// 校验容量配额,复制会新增一份文件占用
if err := checkQuota(auth.ID, file.Size); err != nil {
printer.Error("Check quota error: %v", err)
return nil, err
}
// 创建文件副本
newFile := models.CloudDiskFile{
Std_IICUDS: types.Std_IICUDS{

View File

@@ -85,10 +85,16 @@ func GetDir(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudDiskDirIte
}
}
// 根目录的 ParentID 为空,需先判空再解引用
parentID := uint64(0)
if dir.ParentID != nil {
parentID = uint64(*dir.ParentID)
}
reply = &pb.CloudDiskDirItem{
Id: uint64(dir.ID),
Identity: dir.Identity,
ParentId: uint64(*dir.ParentID),
ParentId: parentID,
Name: dir.Name,
Path: dir.Path,
CreatedAt: dir.CreatedAt.Format(time.RFC3339),

View File

@@ -91,10 +91,16 @@ func GetDirTree(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudDiskDi
}
}
// 根目录的 ParentID 为空,需先判空再解引用
parentID := uint64(0)
if dir.ParentID != nil {
parentID = uint64(*dir.ParentID)
}
reply = &pb.CloudDiskDirItem{
Id: uint64(dir.ID),
Identity: dir.Identity,
ParentId: uint64(*dir.ParentID),
ParentId: parentID,
Name: dir.Name,
Path: dir.Path,
CreatedAt: dir.CreatedAt.Format(time.RFC3339),

View File

@@ -0,0 +1,43 @@
package disk
import (
"bsm/full/module/base/cloud/internal/impl"
"bsm/full/module/base/cloud/internal/models"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/printer"
)
// defaultMaxStorage 默认容量配额100GB与 Space.Get 创建默认空间时的取值保持一致
const defaultMaxStorage int64 = 100 * 1024 * 1024 * 1024
// checkQuota 校验「已用空间 + 本次新增」是否超出配额,超出返回明确错误
func checkQuota(passportID uint, addSize int64) error {
if addSize <= 0 {
return nil
}
// 配额取用户空间记录的 max_storage无空间记录时使用默认配额
maxStorage := defaultMaxStorage
var space models.CloudSpace
if err := impl.DBService.Where("passport_id = ?", passportID).First(&space).Error; err == nil && space.MaxStorage > 0 {
maxStorage = space.MaxStorage
}
// 已用空间按云盘文件实际占用统计
var usedStorage int64
row := impl.DBService.Model(&models.CloudDiskFile{}).
Joins("JOIN cloud_disk_dirs ON cloud_disk_files.directory_id = cloud_disk_dirs.id").
Where("cloud_disk_dirs.passport_id = ?", passportID).
Select("COALESCE(SUM(cloud_disk_files.size), 0)").
Row()
if err := row.Scan(&usedStorage); err != nil {
printer.Error("Query used storage error: %v", err)
return errcode.ErrDB
}
if usedStorage+addSize > maxStorage {
return errcode.ErrResourceExhausted
}
return nil
}

View File

@@ -52,6 +52,12 @@ func UploadFile(ctx context.Context, in *pb.CloudDiskFileRequest) (reply *pb.Sta
return nil, errcode.ErrAlreadyExists
}
// 校验容量配额,「已用 + 本次」不得超过上限
if err := checkQuota(auth.ID, in.Size); err != nil {
printer.Error("Check quota error: %v", err)
return nil, err
}
// 生成文件哈希(如果未提供)
fileHash := in.Hash
if fileHash == "" {

View File

@@ -35,6 +35,13 @@ func CreatePrivateData(ctx context.Context, in *pb.CreatePrivateDataRequest) (re
}
// logic code
// 使用服务端密钥加密资料内容后落库,客户端传入的 is_encrypted 不再作为依据
encryptedData, err := encryptPrivateData(in.Data)
if err != nil {
printer.Error("Encrypt private data error: %v", err)
return nil, err
}
record := models.CloudPrivate{
Std_IICUDS: types.Std_IICUDS{
Identity: utils.UUID(),
@@ -50,8 +57,8 @@ func CreatePrivateData(ctx context.Context, in *pb.CreatePrivateDataRequest) (re
DataType: in.DataType,
Title: in.Title,
Description: in.Description,
Data: in.Data,
IsEncrypted: in.IsEncrypted,
Data: encryptedData,
IsEncrypted: true,
Tags: in.Tags,
}

View File

@@ -0,0 +1,73 @@
package private
import (
"os"
"strings"
"git.apinb.com/bsm-sdk/core/crypto/aes"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/printer"
)
// privateDataKey 返回服务端持有的私人资料加密密钥,仅从环境变量 BSM_CloudPrivateKey 读取。
// 请求参数中传入的密钥一律不作为服务端密钥使用;
// 未配置或长度不足时直接报错,禁止回退到公开默认值(否则等同于未加密)。
func privateDataKey() ([]byte, error) {
secret := strings.TrimSpace(os.Getenv("BSM_CloudPrivateKey"))
if secret == "" {
printer.Error("环境变量 BSM_CloudPrivateKey 未配置,私人资料加密不可用")
return nil, errcode.ErrInternal
}
key := []byte(secret)
switch {
case len(key) >= 32:
return key[:32], nil
case len(key) >= 24:
return key[:24], nil
case len(key) >= 16:
return key[:16], nil
default:
printer.Error("环境变量 BSM_CloudPrivateKey 长度不足 16 字节,私人资料加密不可用")
return nil, errcode.ErrInternal
}
}
// encryptPrivateData 使用服务端密钥加密私人资料内容,返回十六进制密文
func encryptPrivateData(plain string) (string, error) {
key, err := privateDataKey()
if err != nil {
return "", err
}
cipherText, err := aes.AESGCMEncrypt([]byte(plain), key)
if err != nil {
return "", errcode.ErrInternal
}
return cipherText, nil
}
// decryptPrivateData 使用服务端密钥解密私人资料内容
func decryptPrivateData(cipherText string) (string, error) {
key, err := privateDataKey()
if err != nil {
return "", err
}
plain, err := aes.AESGCMDecrypt(cipherText, key)
if err != nil {
return "", errcode.ErrInternal
}
return string(plain), nil
}
// decryptPrivateDataForRead 读取私人资料时解密内容。
// 历史记录未由服务端加密(或标记与内容不符)时按原值返回,避免旧数据不可读。
func decryptPrivateDataForRead(data string, isEncrypted bool) string {
if !isEncrypted || data == "" {
return data
}
plain, err := decryptPrivateData(data)
if err != nil {
return data
}
return plain
}

View File

@@ -2,18 +2,16 @@ package private
import (
"context"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"strings"
"time"
pb "bsm/full/module/base/cloud/pb"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/service"
)
// 解密数据
// 解密数据(使用服务端密钥,客户端传入的 Key 不再作为服务端密钥)
func DecryptData(ctx context.Context, in *pb.DataRequest) (reply *pb.StatusReply, err error) {
// parse authorization meta.
_, err = service.ParseMetaCtx(ctx, nil)
@@ -25,57 +23,16 @@ func DecryptData(ctx context.Context, in *pb.DataRequest) (reply *pb.StatusReply
if strings.TrimSpace(in.Data) == "" {
return nil, errcode.ErrInvalidArgument
}
if strings.TrimSpace(in.Key) == "" {
return nil, errcode.ErrInvalidArgument
}
// logic code
// 解码base64数据
ciphertext, err := base64.StdEncoding.DecodeString(in.Data)
if err != nil {
return nil, errcode.ErrInvalidArgument
}
key := []byte(in.Key)
if len(key) != 32 {
// 如果密钥长度不是32字节进行填充或截断
if len(key) < 32 {
for len(key) < 32 {
key = append(key, 0)
}
} else {
key = key[:32]
}
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, errcode.ErrInternal
}
// 使用GCM模式进行解密
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, errcode.ErrInternal
}
// 检查数据长度
if len(ciphertext) < gcm.NonceSize() {
return nil, errcode.ErrInvalidArgument
}
// 分离nonce和密文
nonce := ciphertext[:gcm.NonceSize()]
ciphertext = ciphertext[gcm.NonceSize():]
// 解密数据
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
plainData, err := decryptPrivateData(in.Data)
if err != nil {
printer.Error("Decrypt data error: %v", err)
return nil, errcode.ErrInvalidArgument
}
return &pb.StatusReply{
Details: string(plaintext),
Details: plainData,
Timeseq: time.Now().UnixMilli(),
}, nil
}

View File

@@ -2,20 +2,16 @@ package private
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
"strings"
"time"
pb "bsm/full/module/base/cloud/pb"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/service"
)
// 加密数据
// 加密数据(使用服务端密钥,客户端传入的 Key 不再作为服务端密钥)
func EncryptData(ctx context.Context, in *pb.DataRequest) (reply *pb.StatusReply, err error) {
// parse authorization meta.
_, err = service.ParseMetaCtx(ctx, nil)
@@ -27,47 +23,14 @@ func EncryptData(ctx context.Context, in *pb.DataRequest) (reply *pb.StatusReply
if strings.TrimSpace(in.Data) == "" {
return nil, errcode.ErrInvalidArgument
}
if strings.TrimSpace(in.Key) == "" {
return nil, errcode.ErrInvalidArgument
}
// logic code
// 简单的AES加密实现
key := []byte(in.Key)
if len(key) != 32 {
// 如果密钥长度不是32字节进行填充或截断
if len(key) < 32 {
for len(key) < 32 {
key = append(key, 0)
}
} else {
key = key[:32]
}
}
block, err := aes.NewCipher(key)
encryptedData, err := encryptPrivateData(in.Data)
if err != nil {
printer.Error("Encrypt data error: %v", err)
return nil, errcode.ErrInternal
}
// 使用GCM模式进行加密
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, errcode.ErrInternal
}
// 生成随机nonce
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, errcode.ErrInternal
}
// 加密数据
ciphertext := gcm.Seal(nonce, nonce, []byte(in.Data), nil)
// 返回base64编码的加密数据
encryptedData := base64.StdEncoding.EncodeToString(ciphertext)
return &pb.StatusReply{
Details: encryptedData,
Timeseq: time.Now().UnixMilli(),

View File

@@ -46,7 +46,7 @@ func GetPrivateData(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudPr
DataType: privateData.DataType,
Title: privateData.Title,
Description: privateData.Description,
Data: privateData.Data,
Data: decryptPrivateDataForRead(privateData.Data, privateData.IsEncrypted),
IsEncrypted: privateData.IsEncrypted,
Tags: privateData.Tags,
CreatedAt: privateData.CreatedAt.Format(time.RFC3339),

View File

@@ -65,7 +65,7 @@ func GetPrivateDataByType(ctx context.Context, in *pb.FetchRequest) (reply *pb.L
DataType: data.DataType,
Title: data.Title,
Description: data.Description,
Data: data.Data,
Data: decryptPrivateDataForRead(data.Data, data.IsEncrypted),
IsEncrypted: data.IsEncrypted,
Tags: data.Tags,
CreatedAt: data.CreatedAt.Format(time.RFC3339),

View File

@@ -54,7 +54,7 @@ func ListPrivateData(ctx context.Context, in *pb.FetchRequest) (reply *pb.ListPr
DataType: data.DataType,
Title: data.Title,
Description: data.Description,
Data: data.Data,
Data: decryptPrivateDataForRead(data.Data, data.IsEncrypted),
IsEncrypted: data.IsEncrypted,
Tags: data.Tags,
CreatedAt: data.CreatedAt.Format(time.RFC3339),

View File

@@ -64,7 +64,7 @@ func SearchPrivateData(ctx context.Context, in *pb.FetchRequest) (reply *pb.List
DataType: data.DataType,
Title: data.Title,
Description: data.Description,
Data: data.Data,
Data: decryptPrivateDataForRead(data.Data, data.IsEncrypted),
IsEncrypted: data.IsEncrypted,
Tags: data.Tags,
CreatedAt: data.CreatedAt.Format(time.RFC3339),

View File

@@ -48,12 +48,19 @@ func UpdatePrivateData(ctx context.Context, in *pb.CloudPrivateItem) (reply *pb.
return nil, errcode.ErrInvalidArgument
}
// 使用服务端密钥加密资料内容后落库,客户端传入的 is_encrypted 不再作为依据
encryptedData, err := encryptPrivateData(in.Data)
if err != nil {
printer.Error("Encrypt private data error: %v", err)
return nil, err
}
// 更新字段
privateData.DataType = in.DataType
privateData.Title = in.Title
privateData.Description = in.Description
privateData.Data = in.Data
privateData.IsEncrypted = in.IsEncrypted
privateData.Data = encryptedData
privateData.IsEncrypted = true
privateData.Tags = in.Tags
if err := impl.DBService.Save(&privateData).Error; err != nil {

View File

@@ -35,6 +35,16 @@ func CreateShare(ctx context.Context, in *pb.CreateShareRequest) (reply *pb.Stat
}
// logic code
// 校验目标资源确实属于当前用户,禁止对他人资源创建分享
owned, err := checkResourceOwner(auth.ID, in.ShareType, uint(in.ResourceId))
if err != nil {
printer.Error("Check share resource owner error: %v", err)
return nil, errcode.ErrDB
}
if !owned {
return nil, errcode.ErrPermissionDenied
}
// 生成分享令牌(如果未提供)
shareToken := in.ShareToken
if shareToken == "" {
@@ -85,3 +95,49 @@ func CreateShare(ctx context.Context, in *pb.CreateShareRequest) (reply *pb.Stat
Timeseq: time.Now().UnixMilli(),
}, nil
}
// checkResourceOwner 校验分享目标资源属于当前用户
func checkResourceOwner(passportID uint, shareType string, resourceID uint) (bool, error) {
var (
count int64
err error
)
switch strings.ToLower(strings.TrimSpace(shareType)) {
case "file":
err = impl.DBService.Model(&models.CloudDiskFile{}).
Joins("JOIN cloud_disk_dirs ON cloud_disk_files.directory_id = cloud_disk_dirs.id").
Where("cloud_disk_files.id = ? AND cloud_disk_dirs.passport_id = ?", resourceID, passportID).
Count(&count).Error
case "photo":
err = impl.DBService.Model(&models.CloudPhoto{}).
Joins("JOIN cloud_albums ON cloud_photos.album_id = cloud_albums.id").
Where("cloud_photos.id = ? AND cloud_albums.passport_id = ?", resourceID, passportID).
Count(&count).Error
case "album":
err = impl.DBService.Model(&models.CloudAlbum{}).
Where("id = ? AND passport_id = ?", resourceID, passportID).
Count(&count).Error
case "note":
err = impl.DBService.Model(&models.CloudNote{}).
Where("id = ? AND passport_id = ?", resourceID, passportID).
Count(&count).Error
case "bookmark":
err = impl.DBService.Model(&models.CloudBookmark{}).
Where("id = ? AND passport_id = ?", resourceID, passportID).
Count(&count).Error
case "private":
err = impl.DBService.Model(&models.CloudPrivate{}).
Where("id = ? AND passport_id = ?", resourceID, passportID).
Count(&count).Error
default:
// 未知的分享类型无法确认资源归属,直接拒绝
return false, nil
}
if err != nil {
return false, err
}
return count > 0, nil
}

View File

@@ -36,8 +36,15 @@ func GetShare(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudShareIte
}
if err := query.First(&share).Error; err != nil {
printer.Error("Share not found: %v", err)
return nil, errcode.ErrInvalidArgument
// 非创建者:凭分享 identity 可读取公开分享,使收件人能够取到分享指向的资源
if in.Id > 0 || in.Identity == "" {
printer.Error("Share not found: %v", err)
return nil, errcode.ErrInvalidArgument
}
if err := impl.DBService.Where("identity = ? AND is_public = ?", in.Identity, true).First(&share).Error; err != nil {
printer.Error("Share not found: %v", err)
return nil, errcode.ErrInvalidArgument
}
}
// 检查是否过期
@@ -45,13 +52,19 @@ func GetShare(ctx context.Context, in *pb.IdentRequest) (reply *pb.CloudShareIte
return nil, errcode.ErrInvalidArgument
}
// 非创建者读取分享时不回传分享密码
password := share.Password
if share.PassportID != auth.ID {
password = ""
}
reply = &pb.CloudShareItem{
Id: uint64(share.ID),
Identity: share.Identity,
ShareType: share.ShareType,
ResourceId: uint64(share.ResourceID),
ShareToken: share.ShareToken,
Password: share.Password,
Password: password,
ExpiresAt: share.ExpiresAt.Format(time.RFC3339),
ViewCount: int32(share.ViewCount),
DownloadCount: int32(share.DownloadCount),

View File

@@ -10,6 +10,7 @@ import (
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/service"
"git.apinb.com/bsm-sdk/core/types"
"git.apinb.com/bsm-sdk/core/utils"
)
// 获取空间数据
@@ -26,13 +27,15 @@ func Get(ctx context.Context, in *pb.Empty) (reply *pb.CloudSpace, err error) {
// 如果不存在,创建默认空间记录
space = models.CloudSpace{
Std_IICUDS: types.Std_IICUDS{
Identity: "default",
// identity 为全局唯一索引,不能写固定字面量,否则多用户创建空间互相冲突
Identity: utils.UUID(),
},
Std_Passport: types.Std_Passport{
PassportID: auth.ID,
PassportIdentity: auth.Identity,
},
KeyIdentifier: "default",
// 空间标识按用户唯一(取用户身份标识),避免多用户共用同一标识
KeyIdentifier: auth.Identity,
TotalStorage: 100 * 1024 * 1024 * 1024, // 100GB
UsedStorage: 0,
MaxStorage: 100 * 1024 * 1024 * 1024, // 100GB

View File

@@ -9,7 +9,8 @@ import (
type CloudSpace struct {
types.Std_IICUDS
types.Std_Passport
KeyIdentifier string `gorm:"uniqueIndex;size:32" json:"key_identifier"`
// 空间标识按用户唯一,仅建普通索引,允许多用户各自持有空间
KeyIdentifier string `gorm:"index;size:36" json:"key_identifier"`
TotalStorage int64 `json:"total_storage"` // 总存储空间
UsedStorage int64 `json:"used_storage"` // 已用存储空间
MaxStorage int64 `json:"max_storage"` // 最大存储空间