Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:lock: Harden encrypted resource exports #18034

Daniel2f7b60a03b72
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index fa2586a51d..4bca149785 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -793,14 +793,14 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) error
sql.RemoveEncryptedDBFile(boxID) // 清理已创建的 content db 文件,避免遗留空加密库
return err
}
- cachedDEKs[boxID] = dek
+ cachedDEKs[boxID] = dek
- // 初始化自动锁定访问时间戳,记录解锁时刻
- newVal := &atomic.Int64{}
- newVal.Store(time.Now().UnixNano())
- boxLastAccess.Store(boxID, newVal)
+ // 初始化自动锁定访问时间戳,记录解锁时刻
+ newVal := &atomic.Int64{}
+ newVal.Store(time.Now().UnixNano())
+ boxLastAccess.Store(boxID, newVal)
- // 修复 conf.json:若 conf 未正确标记加密状态则修正(例如从 backup 解锁后)
+ // 修复 conf.json:若 conf 未正确标记加密状态则修正(例如从 backup 解锁后)
box := &Box{ID: boxID}
boxConf := box.GetConf()
if boxConf == nil || !boxConf.Encrypted || boxConf.BoxCrypt == nil ||
@@ -847,6 +847,7 @@ func LockBox(boxID string) {
// lockBoxHeld 在已持有 box 写锁的前提下执行该 box 的锁定清理(不含全局缓存刷新)。
func lockBoxHeld(boxID string) {
+ RevokeManagedEncryptedExportsForBox(boxID)
cachedDEKsLock.Lock()
if dek, ok := cachedDEKs[boxID]; ok {
@@ -1537,14 +1538,14 @@ func CreateEncryptedBox(name, password string) (id string, err error) {
sql.CloseEncryptedDB(id)
return "", err
}
- cachedDEKs[id] = dek
+ cachedDEKs[id] = dek
- // 初始化自动锁定访问时间戳,与 UnlockBox 对称
- newVal := &atomic.Int64{}
- newVal.Store(time.Now().UnixNano())
- boxLastAccess.Store(id, newVal)
+ // 初始化自动锁定访问时间戳,与 UnlockBox 对称
+ newVal := &atomic.Int64{}
+ newVal.Store(time.Now().UnixNano())
+ boxLastAccess.Store(id, newVal)
- IncSync()
+ IncSync()
return id, nil
}
diff --git a/kernel/model/encrypted_export.go b/kernel/model/encrypted_export.go
new file mode 100644
index 0000000000..863ad60a58
--- /dev/null
+++ b/kernel/model/encrypted_export.go
@@ -0,0 +1,90 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "os"
+ "path"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+type managedEncryptedExport struct {
+ boxID string
+ artifact string
+ expiresAt time.Time
+}
+
+var managedEncryptedExports = struct {
+ sync.Mutex
+ jobs map[string]managedEncryptedExport
+}{jobs: map[string]managedEncryptedExport{}}
+
+func newManagedEncryptedExportID() (string, error) {
+ random := make([]byte, 16)
+ if _, err := rand.Read(random); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(random), nil
+}
+
+func registerManagedEncryptedExport(boxID, artifact string) string {
+ relativePath := path.Join(boxID, "resources", filepath.Base(artifact))
+ managedEncryptedExports.Lock()
+ managedEncryptedExports.jobs[relativePath] = managedEncryptedExport{
+ boxID: boxID,
+ artifact: artifact,
+ expiresAt: time.Now().Add(time.Hour),
+ }
+ managedEncryptedExports.Unlock()
+ return relativePath
+}
+
+// ResolveManagedEncryptedExport 返回仍有效的加密导出产物,未登记、已撤销或过期的路径均不可下载。
+func ResolveManagedEncryptedExport(relativePath string) (boxID, artifact string, ok bool) {
+ relativePath = path.Clean("/" + relativePath)
+ relativePath = relativePath[1:]
+
+ managedEncryptedExports.Lock()
+ job, ok := managedEncryptedExports.jobs[relativePath]
+ if !ok {
+ managedEncryptedExports.Unlock()
+ return "", "", false
+ }
+ if time.Now().After(job.expiresAt) {
+ delete(managedEncryptedExports.jobs, relativePath)
+ managedEncryptedExports.Unlock()
+ _ = os.Remove(job.artifact)
+ return "", "", false
+ }
+ managedEncryptedExports.Unlock()
+ return job.boxID, job.artifact, true
+}
+
+// RevokeManagedEncryptedExportsForBox 使指定笔记本的所有导出下载链接立即失效。
+func RevokeManagedEncryptedExportsForBox(boxID string) {
+ managedEncryptedExports.Lock()
+ defer managedEncryptedExports.Unlock()
+ for relativePath, job := range managedEncryptedExports.jobs {
+ if job.boxID == boxID {
+ delete(managedEncryptedExports.jobs, relativePath)
+ }
+ }
+}
diff --git a/kernel/model/encrypted_export_test.go b/kernel/model/encrypted_export_test.go
new file mode 100644
index 0000000000..6cdb89f80b
--- /dev/null
+++ b/kernel/model/encrypted_export_test.go
@@ -0,0 +1,26 @@
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestManagedEncryptedExportRevocation(t *testing.T) {
+ boxID := "20260711211244-abcdefg"
+ artifact := filepath.Join(t.TempDir(), "export.zip")
+ if err := os.WriteFile(artifact, []byte("plaintext"), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ relativePath := registerManagedEncryptedExport(boxID, artifact)
+ resolvedBoxID, resolvedArtifact, ok := ResolveManagedEncryptedExport("/" + relativePath)
+ if !ok || resolvedBoxID != boxID || resolvedArtifact != artifact {
+ t.Fatalf("managed export was not resolved correctly: box=%q artifact=%q ok=%t", resolvedBoxID, resolvedArtifact, ok)
+ }
+
+ RevokeManagedEncryptedExportsForBox(boxID)
+ if _, _, ok = ResolveManagedEncryptedExport(relativePath); ok {
+ t.Fatal("revoked managed export remained downloadable")
+ }
+}
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 067bcc4290..415e2bb3c8 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -712,9 +712,16 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st
}
// 加密笔记本的物理导出目录使用随机标识,mainName 仅用于用户可见的压缩包名称和包内顶层目录。
- exportID := gulu.Rand.String(7)
+ exportID, err := newManagedEncryptedExportID()
+ if err != nil {
+ return "", err
+ }
exportFolderPath := filepath.Join(exportBasePath, exportID)
- zipFileName := util.FilterFileName(mainName) + ".zip"
+ zipBaseName := util.FilterFileName(filepath.Base(mainName))
+ if zipBaseName == "" {
+ zipBaseName = "resources"
+ }
+ zipFileName := zipBaseName + ".zip"
zipFilePath := filepath.Join(exportBasePath, exportID+"-"+zipFileName)
if encryptedBoxID == "" {
// 保持普通资源导出的既有物理路径与返回值兼容。
@@ -756,7 +763,7 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st
return
}
- if err = zip.AddDirectory(mainName, exportFolderPath); err != nil {
+ if err = zip.AddDirectory(zipBaseName, exportFolderPath); err != nil {
logging.LogErrorf("create export zip [%s] failed: %s", exportFolderPath, err)
return
}
@@ -767,7 +774,7 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st
exportFilePath = path.Join("temp", "export")
if encryptedBoxID != "" {
- exportFilePath = path.Join(exportFilePath, encryptedBoxID, "resources", filepath.Base(zipFilePath))
+ exportFilePath = path.Join("temp", "export", registerManagedEncryptedExport(encryptedBoxID, zipFilePath))
} else {
exportFilePath = path.Join(exportFilePath, filepath.Base(zipFilePath))
}
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 79fe0b8ca3..5d2be7bdce 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -361,9 +361,19 @@ func serveExport(ginServer *gin.Engine) {
// 加密笔记本锁定后拒绝访问其导出临时目录
if parts := strings.SplitN(strings.TrimPrefix(decodedPath, "/"), "/", 2); len(parts) >= 1 && ast.IsNodeIDPattern(parts[0]) && model.IsEncryptedBox(parts[0]) {
- model.HoldBoxReadLock(parts[0])
- defer model.ReleaseBoxReadLock(parts[0])
- if _, dekErr := model.GetDEKIfUnlocked(parts[0]); dekErr != nil {
+ boxID, artifact, ok := model.ResolveManagedEncryptedExport(decodedPath)
+ if !ok || boxID != parts[0] {
+ c.Status(http.StatusNotFound)
+ return
+ }
+ fullPath = artifact
+ if !gulu.File.IsSubPath(exportBaseDir, fullPath) {
+ c.Status(http.StatusForbidden)
+ return
+ }
+ model.HoldBoxReadLock(boxID)
+ defer model.ReleaseBoxReadLock(boxID)
+ if _, dekErr := model.GetDEKIfUnlocked(boxID); dekErr != nil {
c.Status(http.StatusForbidden)
return
}