Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 67 additions & 14 deletions common/cf-v2-edit-fence.c
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ cf_v2_writer_capabilities(GError **error)
return 0;
gboolean db_error = FALSE;
seaf_db_statement_exists(seaf->db,
"SELECT repo_id,path_hash,path,file_id,protected_by,protected_at "
"SELECT repo_id,path_hash,path,file_id,entry_type,protected_by,protected_at "
"FROM cf_file_protection FORCE INDEX (PRIMARY,cf_file_protection_prefix) LIMIT 0",
&db_error, 0);
return (guard_available(seaf) > 0 ? 1 : 0) | (db_error ? 0 : 2);
Expand All @@ -199,6 +199,7 @@ struct _CfV2EditPrepared {
int checkout, protection, origin_protection;
char *origin;
char *prefix;
gboolean root_changed;
GHashTable *candidate_ids;
};

Expand Down Expand Up @@ -236,20 +237,27 @@ virtual_protected_row(SeafDBRow *row, void *data)
proof->invalid = TRUE;
return FALSE;
}
const char *kind = seaf_db_row_get_column_text(row, 2);
if (!kind || (strcmp(kind, "dir") && strcmp(kind, "file"))) {
proof->invalid = TRUE;
return FALSE;
}
if (proof->final) {
const char *candidate = g_hash_table_lookup(p->candidate_ids, path);
if (!candidate || !*candidate || strcmp(candidate, id)) {
g_autofree char *expected = g_strconcat(kind, id, NULL);
if (g_strcmp0(candidate, expected)) {
proof->invalid = TRUE;
return FALSE;
}
} else if (!g_hash_table_contains(p->candidate_ids, path)) {
if (g_hash_table_size(p->candidate_ids) >= 8192) { proof->invalid = TRUE; return FALSE; }
GError *error = NULL;
char *candidate = seaf_fs_manager_get_seafile_id_by_path(
g_autofree char *candidate = (!strcmp(kind, "dir") ? seaf_fs_manager_get_seafdir_id_by_path :
seaf_fs_manager_get_seafile_id_by_path)(
proof->session->fs_mgr, p->origin, proof->version, proof->root,
path + strlen(p->prefix), &error);
g_clear_error(&error);
g_hash_table_insert(p->candidate_ids, g_strdup(path), candidate ? candidate : g_strdup(""));
g_hash_table_insert(p->candidate_ids, g_strdup(path), candidate ? g_strconcat(kind, candidate, NULL) : g_strdup(""));
}
return TRUE;
}
Expand All @@ -261,7 +269,7 @@ virtual_rows(SeafDBTrans *trans, VirtualProof *proof, const char *changed)
CfV2EditPrepared *p = proof->prepared;
char *path = g_strconcat(p->prefix, "/", changed[0] == '/' ? changed + 1 : changed, NULL);
char *pattern = protection_prefix(path);
const char *query = "SELECT path,file_id FROM cf_file_protection "
const char *query = "SELECT path,file_id,entry_type FROM cf_file_protection "
"WHERE repo_id=? AND (path=? OR path LIKE ? ESCAPE '!') LIMIT 8193";
char *sql = g_strconcat(query, trans ? " FOR UPDATE" : "", NULL);
proof->count = 0;
Expand Down Expand Up @@ -364,16 +372,19 @@ cf_v2_edit_prepare_unscoped_branch(struct _SeafileSession *session,
SeafCommit *new_commit = seaf_commit_manager_get_commit(
session->commit_mgr, repo_id, repo->version, new_commit_id);
int result = (old_commit && new_commit)
? diff_commit_roots(repo->store_id, repo->version,
? diff_commit_roots_for_protection(repo->store_id, repo->version,
old_commit->root_id, new_commit->root_id,
&prepared->changes, FALSE)
&prepared->changes, FALSE, policy.protection || prepared->origin_protection)
: -1;
if (result == 0 && prepared->origin_protection) {
prepared->root_changed = strcmp(old_commit->root_id, new_commit->root_id) != 0;
VirtualProof proof = {prepared, session, new_commit->root_id, repo->version, FALSE, FALSE, 0};
guint count = 0;
for (GList *entry = prepared->changes; entry; entry = entry->next) {
DiffEntry *delta = entry->data;
if (++count > 8192 || !delta || virtual_rows(NULL, &proof, delta->name) ||
if (++count > 8192 || !delta) { result = -1; break; }
if (delta->status == DIFF_STATUS_DIR_MODIFIED) continue;
if (virtual_rows(NULL, &proof, delta->name) ||
virtual_rows(NULL, &proof, delta->new_name)) { result = -1; break; }
}
}
Expand Down Expand Up @@ -415,7 +426,29 @@ protection_prefix(const char *path)
}

static int
protection_changed_path(SeafDBTrans *trans, const char *repo_id, const char *changed)
protected_directories(SeafDBTrans *trans, const char *repo_id, const char *path, gboolean include_self, GHashTable *checked)
{
g_autofree char *parent = g_strdup(path);
char *slash;
if (!include_self && (slash = strrchr(parent, '/'))) *slash = 0;
while (*parent && strcmp(parent, "/")) {
if (g_hash_table_contains(checked, parent)) break;
g_autofree char *hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, parent, -1);
int n = seaf_db_trans_foreach_selected_row(trans,
"SELECT 1 FROM cf_file_protection WHERE repo_id=? AND path_hash=UNHEX(?) "
"AND path=? AND entry_type='dir' LIMIT 1 FOR UPDATE",
protection_found, NULL, 3, "string", repo_id, "string", hash, "string", parent);
if (n != 0) return n < 0 ? -1 : 1;
g_hash_table_add(checked, g_strdup(parent));
slash = strrchr(parent, '/');
if (!slash) break;
*slash = 0;
}
return 0;
}

static int
protection_changed_path(SeafDBTrans *trans, const char *repo_id, const char *changed, GHashTable *checked)
{
if (!changed || !*changed)
return 0;
Expand All @@ -431,9 +464,7 @@ protection_changed_path(SeafDBTrans *trans, const char *repo_id, const char *cha
protection_found, NULL, 3,
"string", repo_id, "string", hash, "string", path);
g_free(hash);
/* 修改原因(2026-11-17):命中与查询失败原先都返回 -1,调用方无法区分
* "文件已定版"和"SQL 不可用",最终只能给用户一句 authority unavailable。
* 这里拆成 1=命中、-1=故障;判定仍然是同一批查询,不增加任何 I/O。 */
/* Preserve the distinction between a protected path and unavailable SQL. */
if (n < 0) { g_free(path); return -1; }
if (n > 0) { g_free(path); return 1; }
char *prefix = protection_prefix(path);
Expand All @@ -442,6 +473,7 @@ protection_changed_path(SeafDBTrans *trans, const char *repo_id, const char *cha
"WHERE repo_id=? AND path LIKE ? ESCAPE '!' LIMIT 1 FOR UPDATE",
protection_found, NULL, 2, "string", repo_id, "string", prefix);
g_free(prefix);
if (n == 0) n = protected_directories(trans, repo_id, path, FALSE, checked);
g_free(path);
if (n < 0) return -1;
return n > 0 ? 1 : 0;
Expand All @@ -466,10 +498,23 @@ cf_v2_edit_check_unscoped_branch(SeafDBTrans *trans,
(prepared->origin && (!read_repo_policy(session, trans, prepared->origin, &origin) ||
origin.protection != prepared->origin_protection)))
return -1;
g_autoptr(GHashTable) checked = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
if (prepared->origin_protection) {
if (prepared->root_changed) {
int hit = protected_directories(trans, prepared->origin, prepared->prefix, TRUE, checked);
if (hit != 0) return hit < 0 ? -1 : CF_V2_EDIT_DENIED_PROTECTED;
}
VirtualProof proof = {(CfV2EditPrepared *)prepared, session, NULL, 0, TRUE, FALSE, 0};
for (GList *entry = prepared->changes; entry; entry = entry->next) {
DiffEntry *delta = entry->data;
const char *names[] = {delta->name, delta->new_name};
for (int i = 0; i < 2; ++i) {
if (!names[i] || !*names[i]) continue;
g_autofree char *path = g_build_filename(prepared->prefix, names[i], NULL);
int parent = protected_directories(trans, prepared->origin, path, delta->status == DIFF_STATUS_DIR_MODIFIED, checked);
if (parent != 0) return parent < 0 ? -1 : CF_V2_EDIT_DENIED_PROTECTED;
}
if (delta->status == DIFF_STATUS_DIR_MODIFIED) continue;
int hit = virtual_rows(trans, &proof, delta->name);
int renamed = virtual_rows(trans, &proof, delta->new_name);
if (hit < 0 || renamed < 0) return -1;
Expand All @@ -480,13 +525,20 @@ cf_v2_edit_check_unscoped_branch(SeafDBTrans *trans,
if (seaf_db_type(session->db) != SEAF_DB_TYPE_MYSQL)
return -1;
if (policy.protection) {
g_hash_table_remove_all(checked);
guint count = 0;
for (GList *entry = prepared->changes; entry; entry = entry->next) {
if (++count > 8192) return -1;
DiffEntry *delta = entry->data;
if (!delta) return -1;
int hit = protection_changed_path(trans, repo_id, delta->name);
int renamed = protection_changed_path(trans, repo_id, delta->new_name);
if (delta->status == DIFF_STATUS_DIR_MODIFIED) {
g_autofree char *dir = g_build_filename("/", delta->name, NULL);
int hit = protected_directories(trans, repo_id, dir, TRUE, checked);
if (hit != 0) return hit < 0 ? -1 : CF_V2_EDIT_DENIED_PROTECTED;
continue;
}
int hit = protection_changed_path(trans, repo_id, delta->name, checked);
int renamed = protection_changed_path(trans, repo_id, delta->new_name, checked);
/* 修改原因(2026-11-17):故障优先归为不可验证,不能被误报成
* "文件已定版";只有真正命中保护行才回传专用原因码。 */
if (hit < 0 || renamed < 0) return -1;
Expand All @@ -507,6 +559,7 @@ cf_v2_edit_check_unscoped_branch(SeafDBTrans *trans,
rc = 0;
for (GList *entry = prepared->changes; entry && rc == 0; entry = entry->next) {
DiffEntry *delta = entry->data;
if (delta->status == DIFF_STATUS_DIR_MODIFIED) continue;
for (guint i = 0; i < guards.paths->len; ++i) {
const char *path = g_ptr_array_index(guards.paths, i);
if (path_touches(delta->name, path) || path_touches(delta->new_name, path)) {
Expand Down
14 changes: 14 additions & 0 deletions common/diff-simple.c
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ diff_trees (int n, const char *roots[], DiffOptions *opt)
}

typedef struct DiffData {
gboolean include_directories;
GList **results;
gboolean fold_dir_diff;
} DiffData;
Expand Down Expand Up @@ -305,6 +306,10 @@ twoway_diff_dirs (int n, const char *basedir, SeafDirent *dirs[], void *vdata,
SeafDirent *tree1 = dirs[0];
SeafDirent *tree2 = dirs[1];

if (tree1 && tree2 && data->include_directories) {
de = diff_entry_new_from_dirent (DIFF_TYPE_COMMITS, DIFF_STATUS_DIR_MODIFIED, tree2, basedir);
*results = g_list_prepend (*results, de);
}
if (!tree1) {
if (strcmp (tree2->id, EMPTY_SHA1) == 0 || data->fold_dir_diff) {
de = diff_entry_new_from_dirent (DIFF_TYPE_COMMITS, DIFF_STATUS_DIR_ADDED,
Expand Down Expand Up @@ -381,12 +386,21 @@ int
diff_commit_roots (const char *store_id, int version,
const char *root1, const char *root2, GList **results,
gboolean fold_dir_diff)
{
return diff_commit_roots_for_protection(store_id, version, root1, root2, results, fold_dir_diff, FALSE);
}

int
diff_commit_roots_for_protection (const char *store_id, int version,
const char *root1, const char *root2, GList **results,
gboolean fold_dir_diff, gboolean include_directories)
{
DiffOptions opt;
const char *roots[2];

DiffData data;
memset (&data, 0, sizeof(data));
data.include_directories = include_directories;
data.results = results;
data.fold_dir_diff = fold_dir_diff;

Expand Down
6 changes: 6 additions & 0 deletions common/diff-simple.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#define DIFF_STATUS_UNMERGED 'U'
#define DIFF_STATUS_DIR_ADDED 'B'
#define DIFF_STATUS_DIR_DELETED 'C'
#define DIFF_STATUS_DIR_MODIFIED 'F' /* Protection diff only. */
#define DIFF_STATUS_DIR_RENAMED 'E'

enum {
Expand Down Expand Up @@ -65,6 +66,11 @@ diff_commit_roots (const char *store_id, int version,
const char *root1, const char *root2, GList **results,
gboolean fold_dir_diff);

int
diff_commit_roots_for_protection (const char *store_id, int version,
const char *root1, const char *root2, GList **results,
gboolean fold_dir_diff, gboolean include_directories);

int
diff_merge (SeafCommit *merge, GList **results, gboolean fold_dir_diff);

Expand Down
10 changes: 9 additions & 1 deletion doc/file-protection-v1.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# CloudFile 文件定版保护 V1:部署与验收合同

状态:开发分支;尚未在 C/Go/Hub 及真实 MariaDB 上通过端到端验收,禁止单仓独立合并或直接部署。
状态:开发分支。C/Go/Hub 与 MariaDB 的本地隔离验收已覆盖目录和既有共享视图。真实 Etech SSO、匿名外链和目标环境部署需独立验收。
技术基线:Seafile CE14 + CloudFile V2,不依赖 Pro。

## 功能语义
Expand Down Expand Up @@ -67,6 +67,14 @@ Server/Hub/Docker 组合 -> 启动 -> 验收。
Hub 通过权限校验、文件存在及版本 HEAD CAS,持有 native Branch(master) 锁,原子写入保护表和已有 cf_audit_event。
列表状态通过批量读取投影,不向原生 CE 标签写入 SYS_FILE_PROTECTED;普通标签复制不能传播不可变状态。

## 目录定版与 V2 接口

同一库使用同一张保护表。主键仍为资料库和规范路径哈希,`entry_type` 为 `file` 或 `dir`,物理列 `file_id` 保存定版时的文件或目录对象 ID。每个显式定版对象占一行。目录及子树冻结,祖先可以创建兄弟项,影响定版路径的改名、移动和删除会被拒绝。解除目录定版后,子树内原有独立记录继续生效。资料库根沿用库级管理,虚拟库只查询有效状态,显式定版在源库进行。

Hub 的 `/api/v2.1/cloudfile/protection/v2/` 复用 `status/`、`protect/`、`unprotect/`。三者均要求 `repo_id` 和 `entry_type`。状态查询传 `path`,批量查询传同类型的 `paths`(最多 200 项),变更另传确认时的 `expected_object_id`。回执区分 `direct`、`inherited` 和有效状态 `protected`,`object_id` 用于版本确认。存在定版祖先时,子项不能单独改变定版状态。旧 V1 文件请求沿用原字段;解除继承保护返回 409。

**升级顺序**:在受控停写窗口内,已有库执行一次 `scripts/sql/mysql/migrate-directory-protection.sql`,新装使用更新后的建表 DDL。更新全部 C/Go 写入节点和 Docker Schema 校验,再开放新版 Hub、EAP 和 Web。旧 Go 能力检查严格校验列集合,不能将加列与升级写入节点分开上线。存在目录记录时,恢复旧写入程序会失去继承保护。库级 protection 开关、分享令牌、ACL 均沿用既有配置。

## 缺陷记录

### D1:关闭库级 protection 未校验残留定版记录(2026-11-16 已修复)
Expand Down
36 changes: 34 additions & 2 deletions fileserver/cf_file_protection.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"crypto/sha256"
"database/sql"
"errors"
"path"
"strings"

"github.com/haiwen/seafile-server/fileserver/diff"
Expand All @@ -26,7 +27,31 @@ func cfProtectionLikePattern(value string) string {
return strings.NewReplacer("!", "!!", "%", "!%", "_", "!_").Replace(value) + "/%"
}

// The same parent is checked only once per repository transaction.
func cfProtectedDirectories(ctx context.Context, tx *sql.Tx, repoID, directory string, checked map[string]bool) error {
for parent := directory; parent != "/" && parent != "."; parent = path.Dir(parent) {
if checked[parent] {
break
}
hash := sha256.Sum256([]byte(parent))
var found int
err := tx.QueryRowContext(ctx, "SELECT 1 FROM cf_file_protection WHERE repo_id=? AND path_hash=? AND path=? AND entry_type='dir' LIMIT 1 FOR UPDATE", repoID, hash[:], parent).Scan(&found)
if err == nil {
return errCFFileProtected
}
if err != sql.ErrNoRows {
return errCFProtectionUnavailable
}
checked[parent] = true
}
return nil
}

func cfProtectionPath(ctx context.Context, tx *sql.Tx, repoID, changed string) error {
return cfProtectionPathChecked(ctx, tx, repoID, changed, make(map[string]bool))
}

func cfProtectionPathChecked(ctx context.Context, tx *sql.Tx, repoID, changed string, checked map[string]bool) error {
if tx == nil || changed == "" || strings.ContainsRune(changed, '\x00') {
return errCFProtectionUnavailable
}
Expand All @@ -50,17 +75,24 @@ func cfProtectionPath(ctx context.Context, tx *sql.Tx, repoID, changed string) e
if err != sql.ErrNoRows {
return errCFProtectionUnavailable
}
return nil
return cfProtectedDirectories(ctx, tx, repoID, path.Dir(target), checked)
}

func cfProtectionChanges(ctx context.Context, tx *sql.Tx, repoID string, changes []*diff.DiffEntry) error {
if tx == nil || changes == nil || len(changes) > 8192 {
return errCFProtectionUnavailable
}
checked := make(map[string]bool)
for _, change := range changes {
if change == nil {
return errCFProtectionUnavailable
}
if change.Status == diff.DiffStatusDirModified {
if err := cfProtectedDirectories(ctx, tx, repoID, "/"+strings.TrimPrefix(change.Name, "/"), checked); err != nil {
return err
}
continue
}
seen := make(map[string]struct{}, 2)
for _, name := range []string{change.Name, change.NewName} {
if name == "" {
Expand All @@ -70,7 +102,7 @@ func cfProtectionChanges(ctx context.Context, tx *sql.Tx, repoID string, changes
continue
}
seen[name] = struct{}{}
if err := cfProtectionPath(ctx, tx, repoID, name); err != nil {
if err := cfProtectionPathChecked(ctx, tx, repoID, name, checked); err != nil {
return err
}
}
Expand Down
23 changes: 21 additions & 2 deletions fileserver/cf_file_protection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ func TestFileProtectionExactAndParentDirectory(t *testing.T) {
}{
{"protected original", uploadGuardFixture{protectionExact: true}, "design/original.prt", errCFFileProtected},
{"parent rename or delete", uploadGuardFixture{protectionDescendant: true}, "design", errCFFileProtected},
{"protected grandparent", uploadGuardFixture{protectedDirectory: "/design"}, "design/sub/new", errCFFileProtected},
{"sibling with common prefix", uploadGuardFixture{protectedDirectory: "/design"}, "design2/new", nil},
{"other file", uploadGuardFixture{}, "design/work.prt", nil},
{"unavailable metadata", uploadGuardFixture{failGuard: true}, "design/original.prt", errCFProtectionUnavailable},
} {
Expand All @@ -83,8 +85,8 @@ func TestFileProtectionExactAndParentDirectory(t *testing.T) {
t.Fatalf("result=%v want=%v", err, tc.expected)
}
})
if len(f.queries) < 2 || len(f.queries) > 3 {
t.Fatalf("expected 1-2 scoped Protection SQL checks, got %d", len(f.queries))
if len(f.queries) < 2 || len(f.queries) > 5 {
t.Fatalf("expected bounded scoped Protection SQL checks, got %d", len(f.queries))
}
for _, query := range f.queries[1:] {
if !strings.Contains(query, "cf_file_protection") ||
Expand All @@ -110,3 +112,20 @@ func TestFileProtectionCopyAndEscapedDirectories(t *testing.T) {
t.Fatalf("LIKE wildcard escaping failed: %q", pattern)
}
}

func TestChangedDirectoryChecksItsOwnProtectionWithoutFreezingSiblings(t *testing.T) {
for _, tc := range []struct {
path string
want error
}{
{"design", nil}, {"design/published", errCFFileProtected}, {"design/published/child", errCFFileProtected},
} {
f := &uploadGuardFixture{protectedDirectory: "/design/published", protectionDescendant: true}
withProtectionFixture(t, f, func(tx *sql.Tx) {
err := cfProtectionChanges(context.Background(), tx, "repo", []*diff.DiffEntry{{Status: diff.DiffStatusDirModified, Name: tc.path}})
if !errors.Is(err, tc.want) {
t.Fatalf("%s: got %v, want %v", tc.path, err, tc.want)
}
})
}
}
Loading
Loading