Skip to content

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

5.5 KB
Raw Blame
// SiYuan - https://github.com/siyuan-note/siyuan
// Copyright (c) 2020-present, b3log.org
// SPDX-License-Identifier: AGPL-3.0-or-later

//go:build fts5

package model

import (
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/88250/lute/ast"
	"github.com/88250/lute/parse"
	"github.com/gin-gonic/gin"
	"github.com/siyuan-note/siyuan/kernel/conf"
	"github.com/siyuan-note/siyuan/kernel/filesys"
	"github.com/siyuan-note/siyuan/kernel/sql"
	"github.com/siyuan-note/siyuan/kernel/treenode"
	"github.com/siyuan-note/siyuan/kernel/util"
)

// setupExportPublishTest 为发布访问导出用例准备独立的临时工作空间和数据库连接。
func setupExportPublishTest(t *testing.T) {
	t.Helper()

	oldConf := Conf
	oldWorkspaceDir := util.WorkspaceDir
	oldConfDir := util.ConfDir
	oldDataDir := util.DataDir
	oldTempDir := util.TempDir
	oldQueueDir := util.QueueDir
	oldDBPath := util.DBPath
	oldHistoryDBPath := util.HistoryDBPath
	oldAssetContentDBPath := util.AssetContentDBPath
	oldBlockTreeDBPath := util.BlockTreeDBPath

	tempDir := t.TempDir()
	util.WorkspaceDir = tempDir
	util.ConfDir = filepath.Join(tempDir, "conf")
	util.DataDir = filepath.Join(tempDir, "data")
	util.TempDir = filepath.Join(tempDir, "temp")
	util.QueueDir = filepath.Join(util.TempDir, "queue")
	util.DBPath = filepath.Join(util.TempDir, util.DBName)
	util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
	util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
	util.BlockTreeDBPath = filepath.Join(tempDir, "blocktree.db")
	for _, dir := range []string{util.ConfDir, util.DataDir, util.TempDir, util.QueueDir} {
		if err := os.MkdirAll(dir, 0755); err != nil {
			t.Fatalf("create temporary directory %s: %v", dir, err)
		}
	}
	sql.InitDatabase(true)
	sql.InitHistoryDatabase(true)
	sql.InitAssetContentDatabase(true)
	Conf = NewAppConf()
	Conf.Editor.Store(conf.NewEditor())
	Conf.FileTree.Store(conf.NewFileTree())
	Conf.Search.Store(conf.NewSearch())
	Conf.Export.Store(conf.NewExport())
	treenode.InitBlockTree(true)
	invalidateEncryptedPublishAccessCache()

	t.Cleanup(func() {
		closeModelTestDatabases()
		treenode.CloseDatabase()
		Conf = oldConf
		util.WorkspaceDir = oldWorkspaceDir
		util.ConfDir = oldConfDir
		util.DataDir = oldDataDir
		util.TempDir = oldTempDir
		util.QueueDir = oldQueueDir
		util.DBPath = oldDBPath
		util.HistoryDBPath = oldHistoryDBPath
		util.AssetContentDBPath = oldAssetContentDBPath
		util.BlockTreeDBPath = oldBlockTreeDBPath
		invalidateEncryptedPublishAccessCache()
		if "" != oldBlockTreeDBPath {
			treenode.InitBlockTree(false)
		}
	})
}

// TestExportEmbedFilteredByPublishAccess 验证发布读者导出公共文档时,查询嵌入块匹配到的
// 发布禁用文档内容会被访问检查过滤,而管理员导出不受影响。
func TestExportEmbedFilteredByPublishAccess(t *testing.T) {
	setupExportPublishTest(t)

	const (
		boxID     = "20260826000000-box0001"
		publicID  = "20260826000001-public1"
		privateID = "20260826000002-prv0001"
		embedID   = "20260826000003-embed01"
		canary    = "PRIVATE_EMBED_CANARY_20260826"
	)

	publicTree := treenode.NewTree(boxID, "/"+publicID+".sy", "/Public", "Public")
	embed := &ast.Node{Type: ast.NodeBlockQueryEmbed, ID: embedID, Box: boxID, Path: publicTree.Path}
	embed.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript,
		Tokens: []byte("SELECT * FROM blocks WHERE id = '" + privateID + "'")})
	publicTree.Root.AppendChild(embed)

	privateTree := treenode.NewTree(boxID, "/"+privateID+".sy", "/Private", "Private")
	privateParagraph := privateTree.Root.FirstChild
	privateParagraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(canary)})

	for _, tree := range []*parse.Tree{publicTree, privateTree} {
		if _, err := filesys.WriteTree(tree); err != nil {
			t.Fatalf("write synthetic tree: %v", err)
		}
		treenode.UpsertBlockTree(tree)
		sql.IndexTreeQueue(tree)
	}
	sql.FlushQueue()
	t.Cleanup(func() {
		treenode.RemoveBlockTree(boxID, publicID)
		treenode.RemoveBlockTree(boxID, privateID)
	})

	c, _ := gin.CreateTestContext(httptest.NewRecorder())
	c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
	publishAccess := PublishAccess{
		{ID: publicID, Visible: true},
		{ID: privateID, Disable: true},
	}
	accessChecker := func(blockID string) bool {
		bt := treenode.GetBlockTree(blockID)
		if nil == bt {
			return false
		}
		return checkBlockTreeAccessableByPublishAccess(c, publishAccess, bt)
	}

	markdown := ExportStdMarkdown(publicID, &ExportOptions{
		Render: ExportRenderOptions{
			AssetsDestSpace2Underscore: false,
			FillCSSVar:                 false,
			AdjustHeadingLevel:         false,
			ImgTag:                     false,
			AVPublishFilter:            nil,
			AccessCheckers:             []EmbedBlockAccessChecker{accessChecker},
		},
	})
	if strings.Contains(markdown, canary) {
		t.Fatalf("publish reader received private embed content: %s", markdown)
	}
	stdHTML := ExportPreview(publicID, false, nil, accessChecker)
	if strings.Contains(stdHTML, canary) {
		t.Fatalf("publish reader received private embed content in preview: %s", stdHTML)
	}

	adminMarkdown := ExportStdMarkdown(publicID, &ExportOptions{
		Render: ExportRenderOptions{
			AssetsDestSpace2Underscore: false,
			FillCSSVar:                 false,
			AdjustHeadingLevel:         false,
			ImgTag:                     false,
			AVPublishFilter:            nil,
		},
	})
	if !strings.Contains(adminMarkdown, canary) {
		t.Fatalf("administrator export should include embed content: %s", adminMarkdown)
	}
}