An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Prevent encrypted asset cleanup from removing referenced files https://github.com/siyuan-note/siyuan/issues/20633
Danielb6660a382a65
diff --git a/app/src/config/encryptedAssets.test.ts b/app/src/config/encryptedAssets.test.tsindex ae6107a15c..3cb5816bcb 100644--- a/app/src/config/encryptedAssets.test.ts+++ b/app/src/config/encryptedAssets.test.ts@@ -45,6 +45,7 @@ const setup = (mobile = false) => {]};let releaseScan: (() => void) | undefined;let delay = false;+ let maintenanceFailure = false;let previewClears = 0;const previews: string[][] = [];const siyuan = {config: {readonly: false}, notebooks: [{id: "secret", encrypted: true, closed: false}],@@ -81,7 +82,11 @@ const setup = (mobile = false) => {escapeHtml: (text: string) => text.replaceAll("<", "<").replaceAll(">", ">"),getNotebookName: () => "Private notebook",isMobile: () => mobile,- runSettingsMaintenance: (action: () => Promise<unknown>) => { const task = action(); pending.push(task); return task; },+ runSettingsMaintenance: (action: () => Promise<unknown>) => {+ const task = maintenanceFailure ? Promise.resolve() : action();+ pending.push(task);+ return task;+ },};runInNewContext(compiled, {exports, require: () => dependencies,window: {siyuan}});@@ -94,6 +99,7 @@ const setup = (mobile = false) => {delay: () => { delay = true; },release: () => { delay = false; releaseScan?.(); },fail: () => { response = {code: -1, data: []}; },+ failMaintenance: (fail: boolean) => { maintenanceFailure = fail; },previewClears: () => previewClears,};};@@ -123,6 +129,28 @@ for (const mobile of [false, true]) {});}+test("maintenance preparation failure releases cleanup controls and permits retry", async () => {+ const state = setup();+ state.open();+ await state.settle();+ state.controls.all.checked = true;+ state.controls.all.dispatch("change");+ state.controls.delete.dispatch("click");+ state.failMaintenance(true);+ state.callbacks[0]();+ await state.settle();+ assert.equal(state.requests.some(request => request.url.endsWith("removeUnusedEncryptedBoxAssets")), false);+ assert.equal(state.controls.refresh.disabled, false);+ state.failMaintenance(false);+ state.controls.all.checked = true;+ state.controls.all.dispatch("change");+ state.controls.delete.dispatch("click");+ state.callbacks[1]();+ await state.settle();+ assert.equal(state.requests.filter(request => request.url.endsWith("removeUnusedEncryptedBoxAssets")).length, 1);+ assert.equal(state.controls.refresh.disabled, false);+});+test("closing during a scan prevents publishing late decrypted filenames", async () => {const state = setup();state.delay();diff --git a/app/src/config/encryptedAssets.ts b/app/src/config/encryptedAssets.tsindex c7273a7b91..f101a71350 100644--- a/app/src/config/encryptedAssets.ts+++ b/app/src/config/encryptedAssets.ts@@ -133,16 +133,14 @@ export const openEncryptedAssetsCleanup = (notebook: string) => {busy = true;update();void runSettingsMaintenance(async () => {- try {- const response = await fetchSyncPost("/api/asset/removeUnusedEncryptedBoxAssets", {notebook, paths});- if (response.code === 0 && active()) {- showMessage(lang.deleted);- }- } finally {- busy = false;- if (active()) {- await scan();- }+ const response = await fetchSyncPost("/api/asset/removeUnusedEncryptedBoxAssets", {notebook, paths});+ if (response.code === 0 && active()) {+ showMessage(lang.deleted);+ }+ }).finally(async () => {+ busy = false;+ if (active()) {+ await scan();}});});diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex 26d2ac720a..d0600bed9e 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -363,10 +363,7 @@ var getUnusedAssets = contractHandler(apicontract.GetUnusedAssets, func(c *gin.C})var getUnusedEncryptedBoxAssets = contractHandler(apicontract.GetUnusedEncryptedBoxAssets, func(c *gin.Context, request apicontract.EncryptedBoxAssetsRequest) apicontract.Response[[]*apicontract.AssetUnusedItem] {- if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {- return apicontract.Failure[[]*apicontract.AssetUnusedItem](-1, model.Conf.Language(314))- }- items, err := model.UnusedEncryptedBoxAssets(c.Request.Context(), request.Notebook)+ items, err := model.UnusedEncryptedBoxAssets(encryptedBoxRequestScope(c), request.Notebook)if err != nil {return apicontract.Failure[[]*apicontract.AssetUnusedItem](-1, err.Error())}@@ -374,10 +371,7 @@ var getUnusedEncryptedBoxAssets = contractHandler(apicontract.GetUnusedEncrypted})var removeUnusedEncryptedBoxAssets = contractHandler(apicontract.RemoveUnusedEncryptedBoxAssets, func(c *gin.Context, request apicontract.RemoveEncryptedBoxAssetsRequest) apicontract.Response[apicontract.AssetPathsData] {- if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {- return apicontract.Failure[apicontract.AssetPathsData](-1, model.Conf.Language(314))- }- paths, err := model.RemoveUnusedEncryptedBoxAssets(c.Request.Context(), request.Notebook, request.Paths)+ paths, err := model.RemoveUnusedEncryptedBoxAssets(encryptedBoxRequestScope(c), request.Notebook, request.Paths)if err != nil {return apicontract.Failure[apicontract.AssetPathsData](-1, err.Error())}diff --git a/kernel/api/box_lease.go b/kernel/api/box_lease.goindex 4c3d3f0acc..63dce5de79 100644--- a/kernel/api/box_lease.go+++ b/kernel/api/box_lease.go@@ -17,6 +17,7 @@package apiimport (+ "context""errors""slices""sort"@@ -28,12 +29,23 @@ import ()const requestBoxLeasesKey = "siyuan-request-box-leases"+const requestBoxOperationScopeKey = "siyuan-request-box-operation-scope"func boxLeaseMiddleware(c *gin.Context) {defer releaseRequestBoxLeases(c)c.Next()}+// encryptedBoxRequestScope 将模型层取得的单个租约保留到响应写入完成,避免同一请求重复计数。+func encryptedBoxRequestScope(c *gin.Context) context.Context {+ if _, exists := c.Get(requestBoxOperationScopeKey); !exists {+ ctx, release := model.WithEncryptedBoxOperationScope(c.Request.Context())+ c.Request = c.Request.WithContext(ctx)+ c.Set(requestBoxOperationScopeKey, release)+ }+ return c.Request.Context()+}+func holdEncryptedBoxRequest(c *gin.Context, boxID string) error {if boxID == "" || !model.IsEncryptedBox(boxID) {return nil@@ -112,6 +124,12 @@ func releaseEncryptedBoxRequest(c *gin.Context, boxID string) {}func releaseRequestBoxLeases(c *gin.Context) {+ if value, exists := c.Get(requestBoxOperationScopeKey); exists {+ if release, ok := value.(func()); ok {+ release()+ c.Set(requestBoxOperationScopeKey, nil)+ }+ }leases := requestBoxLeases(c)for _, lease := range slices.Backward(leases) {model.ReleaseEncryptedBoxOperation(lease)diff --git a/kernel/api/contract_encrypted_assets_cleanup_test.go b/kernel/api/contract_encrypted_assets_cleanup_test.goindex cfb0781215..5faa2b7434 100644--- a/kernel/api/contract_encrypted_assets_cleanup_test.go+++ b/kernel/api/contract_encrypted_assets_cleanup_test.go@@ -26,6 +26,7 @@ func TestAPIContractEncryptedAssetCleanupAdmission(t *testing.T) {model.Conf = model.NewAppConf()t.Cleanup(func() { model.Conf = previous })engine := gin.New()+ engine.Use(boxLeaseMiddleware)engine.POST("/api/asset/getUnusedEncryptedBoxAssets", getUnusedEncryptedBoxAssets)engine.POST("/api/asset/removeUnusedEncryptedBoxAssets", removeUnusedEncryptedBoxAssets)for _, endpoint := range []string{"getUnusedEncryptedBoxAssets", "removeUnusedEncryptedBoxAssets"} {@@ -110,6 +111,13 @@ func TestAPIContractEncryptedAssetCleanupRoundTrip(t *testing.T) {}engine := gin.New()engine.Use(boxLeaseMiddleware)+ engine.Use(func(c *gin.Context) {+ c.Next()+ // 外层响应尚未退出,独立清理必须被当前请求保留的租约拒绝。+ if _, err := model.UnusedEncryptedBoxAssets(context.Background(), boxID); err == nil {+ t.Error("cleanup response released its notebook lease before middleware completion")+ }+ })engine.POST("/api/asset/getUnusedEncryptedBoxAssets", getUnusedEncryptedBoxAssets)engine.POST("/api/asset/removeUnusedEncryptedBoxAssets", removeUnusedEncryptedBoxAssets)call := func(endpoint, body string) []byte {@@ -119,6 +127,21 @@ func TestAPIContractEncryptedAssetCleanupRoundTrip(t *testing.T) {requireAPIContract(t, "POST", endpoint, recorder)return recorder.Body.Bytes()}+ func() {+ if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {+ t.Fatal(err)+ }+ defer model.ReleaseEncryptedBoxOperation(boxID)+ for _, endpoint := range []string{"getUnusedEncryptedBoxAssets", "removeUnusedEncryptedBoxAssets"} {+ data := call("/api/asset/"+endpoint, `{"notebook":"`+boxID+`","paths":["assets/unused.png"]}`)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(data, &response); err != nil || response.Code != -1 {+ t.Fatalf("cleanup accepted another active request: %s, %v", data, err)+ }+ }+ }()var listed struct {Code int `json:"code"`Data []*apicontract.AssetUnusedItem `json:"data"`diff --git a/kernel/model/asset_relink_references.go b/kernel/model/asset_relink_references.goindex 9cfb73d15c..bd2641b04d 100644--- a/kernel/model/asset_relink_references.go+++ b/kernel/model/asset_relink_references.go@@ -113,7 +113,6 @@ func (r *assetRelinker) reference(raw, kind string, location apicontract.AssetRereturn ret}-var relinkAssetListPattern = regexp.MustCompile(`[^\s,]+`)var relinkCSSURLPattern = regexp.MustCompile(`(?i)url\(\s*(?:"([^"]*)"|'([^']*)'|([^\s)]*))\s*\)`)var relinkHTMLAttrPattern = regexp.MustCompile("([^\\s=<>/]+)(\\s*=\\s*)(\"[^\"]*\"|'[^']*'|[^\\s>]+)")@@ -122,7 +121,7 @@ func (r *assetRelinker) list(raw, kind string, location apicontract.AssetReferenif p, err := relinkPath(raw); err == nil && (p == r.oldPath || r.routes[p] != nil) {return r.reference(raw, kind, location)}- return relinkAssetListPattern.ReplaceAllStringFunc(raw, func(value string) string {+ return assetListPattern.ReplaceAllStringFunc(raw, func(value string) string {return r.reference(value, kind, location)})}diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 0ddf59adfc..8f24947a2c 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -2614,12 +2614,17 @@ func getAssetsLinkDestsWithAttributeViewItemFilter(itemFilter attributeViewItemFilter,normalize ...func(string) string,) (ret []string) {- return getAssetsLinkDestsWithOptions(node, includeServePath, itemFilter, true, normalize...)+ return getAssetsLinkDestsWithOptions(node, includeServePath, itemFilter, assetLinkScanOptions{resolveAttributeViews: true}, normalize...)}-// getAssetsLinkDestsWithOptions 允许独立扫描数据库定义的调用方关闭节点中的数据库加载。+type assetLinkScanOptions struct {+ resolveAttributeViews bool+ expandAssetLists bool+}++// getAssetsLinkDestsWithOptions 控制数据库加载与资源列表展开;保守展开仅用于已有完整资源清单的扫描。func getAssetsLinkDestsWithOptions(- node *ast.Node, includeServePath bool, itemFilter attributeViewItemFilter, resolveAttributeViews bool,+ node *ast.Node, includeServePath bool, itemFilter attributeViewItemFilter, options assetLinkScanOptions,normalize ...func(string) string,) (ret []string) {ret = []string{}@@ -2630,11 +2635,7 @@ func getAssetsLinkDestsWithOptions(for _, kv := range n.KramdownIAL {k := kv[0]if strings.HasPrefix(k, "custom-data-assets") {- dest := normalizeScannedAsset(kv[1], normalize)- if "" == dest || !util.IsAssetLinkDest([]byte(dest), includeServePath) {- continue- }- ret = append(ret, dest)+ ret = append(ret, assetListLinkDests(kv[1], includeServePath, options.expandAssetLists, normalize...)...)}}}@@ -2672,7 +2673,7 @@ func getAssetsLinkDestsWithOptions(ret = append(ret, dest)}} else if ast.NodeAttributeView == n.Type {- if !resolveAttributeViews {+ if !options.resolveAttributeViews {return ast.WalkContinue}attrView, _ := av.ParseAttributeView(n.AttributeViewID)@@ -2688,13 +2689,9 @@ func getAssetsLinkDestsWithOptions(// 兼容两种属性名 custom-data-assets 和 data-assets https://github.com/siyuan-note/siyuan/issues/4122#issuecomment-1154796568dataAssets = n.IALAttr("data-assets")}- dataAssets = normalizeScannedAsset(dataAssets, normalize)- if !util.IsAssetLinkDest([]byte(dataAssets), includeServePath) {- return ast.WalkContinue- }- ret = append(ret, dataAssets)+ ret = append(ret, assetListLinkDests(dataAssets, includeServePath, options.expandAssetLists, normalize...)...)} else { // HTMLBlock/InlineHTML/IFrame/Audio/Video- ret = append(ret, htmlAssetLinkDests(n.Tokens, includeServePath, normalize...)...)+ ret = append(ret, htmlAssetLinkDestsWithOptions(n.Tokens, includeServePath, options.expandAssetLists, normalize...)...)}}return ast.WalkContinue@@ -2709,7 +2706,28 @@ func getAssetsLinkDestsWithOptions(return}+var assetListPattern = regexp.MustCompile(`[^\s,]+`)++// assetListLinkDests 同时保留完整路径与列表项,兼容文件名中的空格、逗号和多值资源属性。+func assetListLinkDests(raw string, includeServePath, expand bool, normalize ...func(string) string) (ret []string) {+ values := []string{raw}+ if expand {+ values = append(values, assetListPattern.FindAllString(raw, -1)...)+ }+ for _, value := range values {+ dest := normalizeScannedAsset(value, normalize)+ if dest != "" && util.IsAssetLinkDest([]byte(dest), includeServePath) {+ ret = append(ret, dest)+ }+ }+ return+}+func htmlAssetLinkDests(tokens []byte, includeServePath bool, normalize ...func(string) string) (ret []string) {+ return htmlAssetLinkDestsWithOptions(tokens, includeServePath, false, normalize...)+}++func htmlAssetLinkDestsWithOptions(tokens []byte, includeServePath, expandAssetLists bool, normalize ...func(string) string) (ret []string) {// 逐个读取标签属性,兼容内联标签片段并只解码一层 HTML 实体。tokenizer := html.NewTokenizer(bytes.NewReader(tokens))for {@@ -2718,6 +2736,10 @@ func htmlAssetLinkDests(tokens []byte, includeServePath bool, normalize ...func(returncase html.StartTagToken, html.SelfClosingTagToken:for _, attr := range tokenizer.Token().Attr {+ if expandAssetLists && (attr.Key == "data-assets" || strings.HasPrefix(attr.Key, "custom-data-assets")) {+ ret = append(ret, assetListLinkDests(attr.Val, includeServePath, true, normalize...)...)+ continue+ }dest := normalizeScannedAsset(strings.TrimSpace(attr.Val), normalize)if util.IsAssetLinkDest([]byte(dest), includeServePath) {ret = append(ret, dest)diff --git a/kernel/model/assets_cleanup_test.go b/kernel/model/assets_cleanup_test.goindex 876e33e899..5894830d7f 100644--- a/kernel/model/assets_cleanup_test.go+++ b/kernel/model/assets_cleanup_test.go@@ -67,6 +67,41 @@ func TestUnusedAssetsPathPrefixes(t *testing.T) {}}+func TestAssetListReferences(t *testing.T) {+ for _, kind := range []string{"attribute", "widget", "html"} {+ t.Run(kind, func(t *testing.T) {+ root := &ast.Node{Type: ast.NodeDocument}+ switch kind {+ case "attribute":+ paragraph := &ast.Node{Type: ast.NodeParagraph}+ paragraph.SetIALAttr("custom-data-assets-list", "assets/a.png assets/b.png,assets/c.png")+ root.AppendChild(paragraph)+ case "widget":+ widget := &ast.Node{Type: ast.NodeWidget}+ widget.SetIALAttr("data-assets", "assets/a.png assets/b.png,assets/c.png")+ root.AppendChild(widget)+ case "html":+ root.AppendChild(&ast.Node{Type: ast.NodeHTMLBlock, Tokens: []byte(`<div custom-data-assets-list="assets/a.png assets/b.png,assets/c.png"></div>`)})+ }+ dests := getAssetsLinkDestsWithOptions(root, false, nil, assetLinkScanOptions{expandAssetLists: true}, normalizeAssetScanLinkDest)+ for _, want := range []string{"assets/a.png", "assets/b.png", "assets/c.png"} {+ found := false+ for _, dest := range dests {+ found = found || dest == want+ }+ if !found {+ t.Errorf("missing resource %s in %v", want, dests)+ }+ }+ })+ }+ paragraph := &ast.Node{Type: ast.NodeParagraph}+ paragraph.SetIALAttr("custom-data-assets", "assets/space name.png")+ if got := getAssetsLinkDests(paragraph, false, normalizeAssetScanLinkDest); !reflect.DeepEqual(got, []string{"assets/space name.png"}) {+ t.Fatalf("ordinary reference extraction split a filename: %v", got)+ }+}+func TestNormalizeAssetScanLinkDest(t *testing.T) {for _, test := range []struct{ input, want string }{{"/assets/a.png?x=1#part", "assets/a.png?x=1#part"},diff --git a/kernel/model/encrypted_assets_cleanup.go b/kernel/model/encrypted_assets_cleanup.goindex 7eb487d1b4..be6684551c 100644--- a/kernel/model/encrypted_assets_cleanup.go+++ b/kernel/model/encrypted_assets_cleanup.go@@ -131,10 +131,11 @@ func withEncryptedAssetCleanup(ctx context.Context, boxID string, operation funcif !ast.IsNodeIDPattern(boxID) || !IsEncryptedBox(boxID) {return errors.New("an encrypted notebook ID is required")}- if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ release, err := AcquireEncryptedBoxOperations(ctx, []string{boxID})+ if err != nil {return errors.New(Conf.Language(314))}- defer ReleaseEncryptedBoxOperation(boxID)+ defer release()if err := lockAssetRelink(ctx, &syncLock); err != nil {return err}@@ -172,12 +173,12 @@ func withEncryptedAssetCleanup(ctx context.Context, boxID string, operation funcreturn operation(dek)}-// admitEncryptedAssetCleanup 暂停新请求,已有读写冲突时由笔记本写锁立即拒绝清理,避免读锁重入死锁。+// admitEncryptedAssetCleanup 仅允许当前响应的单个租约进入清理,拒绝尚未持读锁的在途操作。func admitEncryptedAssetCleanup(boxID string) (func(), error) {lifecycle := getEncryptedBoxLifecycle(boxID)lifecycle.lock.Lock()defer lifecycle.lock.Unlock()- if lifecycle.assetCleanup {+ if lifecycle.assetCleanup || lifecycle.activeOperations != 1 {return nil, errors.New(Conf.Language(239))}lifecycle.assetCleanup = true@@ -224,6 +225,37 @@ func scanEncryptedBoxUnusedAssets(ctx context.Context, boxID string, dek []byte)}assets := map[string]string{}assetRoot := filepath.Join(root, "assets")+ deferred, err := DeferredSyncAssets()+ if err != nil {+ return nil, err+ }+ for _, file := range deferred {+ if err = ctx.Err(); err != nil {+ return nil, err+ }+ if !strings.HasPrefix(file.Path, "/"+boxID+"/assets/") {+ continue+ }+ absPath := filepath.Join(util.DataDir, filepath.FromSlash(strings.TrimPrefix(file.Path, "/")))+ key, keyErr := assetPathMapKey(assetRoot, absPath, false)+ if keyErr != nil {+ return nil, keyErr+ }+ skip := false+ for p := absPath; p != assetRoot; p = filepath.Dir(p) {+ if isSkipFile(filepath.Base(p)) || filelock.IsHidden(p) {+ skip = true+ break+ }+ }+ if skip {+ continue+ }+ assets[key] = absPath+ for dir, absDir := path.Dir(key), filepath.Dir(absPath); dir != "assets"; dir, absDir = path.Dir(dir), filepath.Dir(absDir) {+ assets[dir+"/"] = absDir+ }+ }err = walkEncryptedCleanupFiles(ctx, assetRoot, true, func(p string, entry fs.DirEntry) error {if entry.IsDir() {if p == assetRoot {@@ -301,7 +333,7 @@ func scanEncryptedBoxUnusedAssets(ctx context.Context, boxID string, dek []byte)if projectionErr := treenode.RefreshTableCellRichProjection(tree.Root); projectionErr != nil {return projectionErr}- for _, dest := range getAssetsLinkDestsWithOptions(tree.Root, false, nil, false, normalizeAssetScanLinkDest) {+ for _, dest := range getAssetsLinkDestsWithOptions(tree.Root, false, nil, assetLinkScanOptions{expandAssetLists: true}, normalizeAssetScanLinkDest) {collect(dest)}collect(treenode.GetDocTitleImgPath(tree.Root))@@ -356,17 +388,37 @@ func scanEncryptedBoxUnusedAssets(ctx context.Context, boxID string, dek []byte)if err != nil {return nil, fmt.Errorf("read agent asset references failed: %w", err)}- for _, dest := range removeReferencedAssetPaths(assets, dests) {- if strings.HasSuffix(strings.ToLower(dest), ".pdf") {- delete(assets, dest+".sya")+ // PDF 正文可以尚未下载或暂时缺失,标注保护只依据持久化引用。+ var companions []string+ for dest := range dests {+ if index := strings.IndexAny(dest, "?#"); index >= 0 {+ dest = dest[:index]+ }+ decoded, _ := url.PathUnescape(dest)+ if strings.HasSuffix(strings.ToLower(dest), ".pdf") || strings.HasSuffix(strings.ToLower(decoded), ".pdf") {+ companions = append(companions, dest+".sya")}+ }+ for _, dest := range companions {+ dests[dest] = true+ }+ for _, dest := range removeReferencedAssetPaths(assets, dests) {delete(assets, dest)}ret = []*UnusedItem{}for p, absPath := range assets {+ if err = ctx.Err(); err != nil {+ return nil, err+ }if strings.HasSuffix(p, "/") {continue}+ if err = validateEncryptedCleanupPath(util.DataDir, absPath); err != nil {+ return nil, err+ }+ if err = EnsureAssetLocal(absPath); err != nil {+ return nil, err+ }file, openErr := os.Open(absPath)if openErr != nil {return nil, openErr@@ -397,7 +449,7 @@ func collectEncryptedCleanupJSON(data []byte, luteEngine *lute.Lute, collect fun}collect(typed)tree := parse.Parse("", []byte(typed), luteEngine.ParseOptions)- for _, dest := range getAssetsLinkDestsWithOptions(tree.Root, false, nil, false) {+ for _, dest := range getAssetsLinkDestsWithOptions(tree.Root, false, nil, assetLinkScanOptions{expandAssetLists: true}) {collect(dest)}case []any:diff --git a/kernel/model/encrypted_assets_cleanup_test.go b/kernel/model/encrypted_assets_cleanup_test.goindex a64ca39fc3..e76f451492 100644--- a/kernel/model/encrypted_assets_cleanup_test.go+++ b/kernel/model/encrypted_assets_cleanup_test.go@@ -12,6 +12,7 @@ import ("testing""time"+ "github.com/siyuan-note/siyuan/kernel/av""github.com/siyuan-note/siyuan/kernel/util")@@ -107,6 +108,161 @@ func TestEncryptedAssetCleanupReferences(t *testing.T) {}}+func TestEncryptedAssetCleanupMultipleAttributeAssets(t *testing.T) {+ boxID, docPath, dek := setupEncryptedCleanupTest(t)+ originals := map[string][]byte{}+ for _, name := range []string{"a.png", "b.png", "space name.png", "comma,name.png"} {+ originals[name] = writeEncryptedCleanupAsset(t, boxID, name, dek, false)+ }+ writeEncryptedCleanupAsset(t, boxID, "unused.png", dek, false)+ writeEncryptedCleanupDoc(t, boxID, docPath, dek,+ `{"Type":"NodeParagraph","ID":"20261017000001-abcdefg","Properties":{"custom-data-assets-list":"assets/a.png assets/b.png,assets/a.png?box=`+boxID+`","custom-data-assets-space":"assets/space name.png","custom-data-assets-comma":"assets/comma,name.png"},"Children":[]}`)+ items, err := UnusedEncryptedBoxAssets(context.Background(), boxID)+ if err != nil || len(items) != 1 || items[0].Item != "assets/unused.png" {+ t.Fatalf("attribute resources were classified as unused: %+v, %v", items, err)+ }+ if _, err = RemoveUnusedEncryptedBoxAssets(context.Background(), boxID, []string{"assets/a.png", "assets/b.png"}); err == nil {+ t.Fatal("accepted referenced attribute resources for deletion")+ }+ for name, original := range originals {+ got, err := os.ReadFile(filepath.Join(util.DataDir, boxID, "assets", name))+ if err != nil || !bytes.Equal(got, original) {+ t.Fatalf("changed referenced resource %s: %v", name, err)+ }+ }+}++func TestEncryptedAssetCleanupRejectsActiveWriter(t *testing.T) {+ boxID, _, dek := setupEncryptedCleanupTest(t)+ original := writeEncryptedCleanupAsset(t, boxID, "unused.png", dek, false)+ avID := "20261017000002-abcdefg"+ view := &av.AttributeView{ID: avID, Spec: av.PlainTextSpec, Views: []*av.View{}, KeyValues: []*av.KeyValues{}}+ av.SetAVBoxID(avID, boxID)+ t.Cleanup(func() { av.SetAVBoxID(avID, "") })+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ t.Fatal(err)+ }+ released := false+ defer func() {+ if !released {+ ReleaseEncryptedBoxOperation(boxID)+ }+ }()+ view.KeyValues = append(view.KeyValues, &av.KeyValues{+ Key: &av.Key{ID: "20261017000003-abcdefg", Name: "asset", Type: av.KeyTypeMAsset},+ Values: []*av.Value{{ID: "20261017000004-abcdefg", Type: av.KeyTypeMAsset,+ MAsset: []*av.ValueAsset{{Type: av.AssetTypeImage, Name: "image", Content: "assets/unused.png"}}}},+ })+ // 写入已取得响应租约,但仍处于读改写阶段,尚未持有保存所需的笔记本读锁。+ if _, err := UnusedEncryptedBoxAssets(context.Background(), boxID); err == nil {+ t.Fatal("scan accepted a pending writer")+ }+ if removed, err := RemoveUnusedEncryptedBoxAssets(context.Background(), boxID, []string{"assets/unused.png"}); err == nil || len(removed) != 0 {+ t.Fatalf("cleanup accepted a pending writer: %v, %v", removed, err)+ }+ if err := av.SaveAttributeView(view); err != nil {+ t.Fatal(err)+ }+ ReleaseEncryptedBoxOperation(boxID)+ released = true+ if items, err := UnusedEncryptedBoxAssets(context.Background(), boxID); err != nil || len(items) != 0 {+ t.Fatalf("completed writer's reference was lost: %+v, %v", items, err)+ }+ got, err := os.ReadFile(filepath.Join(util.DataDir, boxID, "assets", "unused.png"))+ if err != nil || !bytes.Equal(got, original) {+ t.Fatalf("pending writer's asset changed: %v", err)+ }+}++func TestEncryptedAssetCleanupDeferredAssets(t *testing.T) {+ full, partial, fullData := prepareAssetDownloadRepoTest(t)+ boxID, docID := "20261017000000-abcdefg", "20261017000001-abcdefg"+ dek := bytes.Repeat([]byte{0x31}, 32)+ doc, err := EncryptFile(boxID, docID+".sy", dek, []byte(`{"Type":"NodeDocument","ID":"`+docID+`","Spec":"2","Properties":{"id":"`+docID+`","title":"fixture"},"Children":[{"Type":"NodeParagraph","Children":[{"Type":"NodeTextMark","TextMarkType":"a","TextMarkAHref":"assets/used.pdf?page=2","TextMarkTextContent":"PDF"},{"Type":"NodeTextMark","TextMarkType":"a","TextMarkAHref":"assets/folder/","TextMarkTextContent":"folder"}]}]}`))+ if err != nil {+ t.Fatal(err)+ }+ writeEncryptedCleanupFile(t, filepath.Join(fullData, boxID, docID+".sy"), doc)+ originals := map[string][]byte{}+ for _, name := range []string{"unused.png", "used.pdf", "used.pdf.sya", "folder/kept.png"} {+ data, err := EncryptAsset(boxID, filepath.Base(name), "original-"+filepath.Base(name), dek, []byte("payload"))+ if err != nil {+ t.Fatal(err)+ }+ originals[name] = data+ writeEncryptedCleanupFile(t, filepath.Join(fullData, boxID, "assets", name), data)+ }+ if _, err = full.Index("encrypted fixture", true, nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = full.Sync(nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err = partial.Sync(nil); err != nil {+ t.Fatal(err)+ }+ markRuntimeEncryptedBox(boxID)+ setDEKForTest(boxID, append([]byte(nil), dek...))+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)+ t.Cleanup(func() {+ cachedDEKsLock.Lock()+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ forgetRuntimeEncryptedBox(boxID)+ setEncryptedBoxState(boxID, EncryptedBoxStateLocked)+ })+ assetRoot := filepath.Join(util.DataDir, boxID, "assets")+ for _, name := range []string{"unused.png", "used.pdf", "folder/kept.png"} {+ if _, err = os.Stat(filepath.Join(assetRoot, name)); !os.IsNotExist(err) {+ t.Fatalf("fixture resource was not deferred: %s, %v", name, err)+ }+ }+ items, err := UnusedEncryptedBoxAssets(context.Background(), boxID)+ if err != nil || len(items) != 1 || items[0].Item != "assets/unused.png" || items[0].Name != "original-unused.png" {+ t.Fatalf("incorrect deferred cleanup candidates: %+v, %v", items, err)+ }+ for _, name := range []string{"used.pdf", "folder/kept.png"} {+ if _, err = os.Stat(filepath.Join(assetRoot, name)); !os.IsNotExist(err) {+ t.Fatalf("scan downloaded a referenced resource: %s, %v", name, err)+ }+ }+ if _, err = RemoveUnusedEncryptedBoxAssets(context.Background(), boxID, []string{"assets/used.pdf.sya"}); err == nil {+ t.Fatal("accepted annotations belonging to a referenced deferred PDF")+ }+ got, err := os.ReadFile(filepath.Join(assetRoot, "used.pdf.sya"))+ if err != nil || !bytes.Equal(got, originals["used.pdf.sya"]) {+ t.Fatalf("referenced PDF annotations changed: %v", err)+ }+ removed, err := RemoveUnusedEncryptedBoxAssets(context.Background(), boxID, []string{"assets/unused.png"})+ if err != nil || !reflect.DeepEqual(removed, []string{"assets/unused.png"}) {+ t.Fatalf("deferred cleanup failed: %v, %v", removed, err)+ }+ histories, _ := filepath.Glob(filepath.Join(util.HistoryDir, "*-clean", boxID, "assets", "unused.png"))+ if len(histories) != 1 {+ t.Fatalf("missing deferred resource history: %v", histories)+ }+ got, err = os.ReadFile(histories[0])+ if err != nil || !bytes.Equal(got, originals["unused.png"]) {+ t.Fatal("deferred history did not preserve ciphertext")+ }+ if items, err = UnusedEncryptedBoxAssets(context.Background(), boxID); err != nil || len(items) != 0 {+ t.Fatalf("deleted deferred resource reappeared: %+v, %v", items, err)+ }+}++func TestEncryptedAssetCleanupMissingPDFKeepsAnnotations(t *testing.T) {+ boxID, docPath, dek := setupEncryptedCleanupTest(t)+ writeEncryptedCleanupDoc(t, boxID, docPath, dek,+ `{"Type":"NodeParagraph","Children":[{"Type":"NodeTextMark","TextMarkType":"a","TextMarkAHref":"assets/missing%2Epdf?page=2","TextMarkTextContent":"PDF"}]}`)+ writeEncryptedCleanupAsset(t, boxID, "missing.pdf.sya", dek, false)+ if items, err := UnusedEncryptedBoxAssets(context.Background(), boxID); err != nil || len(items) != 0 {+ t.Fatalf("missing PDF's annotations were not protected: %+v, %v", items, err)+ }+}+func TestEncryptedAssetCleanupAbortUnreadable(t *testing.T) {for _, kind := range []string{"document authentication", "document JSON", "new spec", "database authentication", "database spec", "database directory", "agent JSON", "asset authentication"} {t.Run(kind, func(t *testing.T) {