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
6 changes: 3 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ CloudFile Server、Hub、Docker 共用以下规则:

## 当前数据库(未正式发布 V2)

- 唯一扩展表为 `cf_library_storage`、`cf_dir_acl`、`cf_sso_group_map`、`cf_edit_guard`、`cf_audit_event`;新装一次创建全部五表,已有卷只校验。
- 唯一扩展表为 `cf_library_storage`、`cf_dir_acl`、`cf_sso_group_map`、`cf_edit_guard`、`cf_audit_event`、`cf_file_protection`;新装一次创建全部六表,已有卷只校验。
- 不迁移或追溯开发期旧数据。存储绑定从 Seafile 的 Repo/RepoStorageId 重新识别,ACL/共享和组织/角色从客户 Provider 重新同步,Guard/审计从空表开始;旧 `cf_tag`、Resource、Intent、Session、Outbox 不恢复。
- 绝不清除 CE 原生 Repo、Branch、文件内容、版本或原生 Tag,也不因为缺表自动建立旧扩展 DDL、迁移服务或产品级升级框架。

Expand All @@ -67,7 +67,7 @@ CloudFile Server、Hub、Docker 共用以下规则:

## SQL 表边界

- 当前 Server V2 只允许 `cf_library_storage`、`cf_dir_acl`、`cf_sso_group_map`、`cf_edit_guard`、`cf_audit_event` 业务表。历史 `cf_library_storage_key` 的分配和冷 GC 账本不允许重新引入;存储依赖 `cf-v2-storage.c` 的预占与激活。
- 当前 Server V2 只允许 `cf_library_storage`、`cf_dir_acl`、`cf_sso_group_map`、`cf_edit_guard`、`cf_audit_event`、`cf_file_protection` 业务表。历史 `cf_library_storage_key` 的分配和冷 GC 账本不允许重新引入;存储依赖 `cf-v2-storage.c` 的预占与激活。
- `scripts/sql/mysql/cloudfile.sql` 和 `scripts/sql/sqlite/cloudfile.sql` 属于未发行旧设计,已从产品源码删除。旧数据库迁移属于外置一次性工具,不属于构建/启动路径。

## 现行 V2 权限契约:禁止“托管库”复活(2026-10-21)
Expand All @@ -76,4 +76,4 @@ CloudFile Server、Hub、Docker 共用以下规则:
- 唯一权限链:Seafile CE 原生库资格 + Hub `Authority.effective()` 对当前身份和实际路径的 ACL/共享目录结果 + C/Go 真实文件与最终 Commit 终判。无整库资格但有 `share_mode=true` 的用户只从共享目录根进入,不得开放库根、父级或兄弟目录。
- **坚决禁止**恢复 `cf_managed_library`、`cf_managed_library_share`、`cf_library_share_revision`、`checkLegacyLibrary`、`cf_policy_check_legacy_library`、`managed_library_guard`、`allow_legacy_managed_reads`,也禁止恢复用于断言“库有任意 ACL 行就应全库拒绝”的测试。
- 没有可信当前用户/路径的整库同步或无范围票据,允许因该**操作缺乏授权证明**而拒绝;这不是库分类。任何有路径证明的 Web/API/Agent/下载/上传必须按实际目标裁决,不能用无关目录的 ACL 拒绝整个库。策略异常不回退宽权限。
- 当前文档与测试应以 V2 权限终判契约及五张扩展表为准;历史文档只用于追溯,不得作为实施依据。跨仓变更必须维护防复活的源码扫描和正反权限用例。
- 当前文档与测试应以 V2 权限终判契约及六张扩展表为准;历史文档只用于追溯,不得作为实施依据。跨仓变更必须维护防复活的源码扫描和正反权限用例。
134 changes: 120 additions & 14 deletions common/cf-v2-edit-fence.c
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,49 @@ canonical_repo_id(const char *id)
return TRUE;
}

/* Repository allowlist parsed once; OFF libraries never query Protection.
* Protection has no lease and is independent of cf_edit_guard / Checkout. */
static gsize protection_policy_state = 0;
static GHashTable *protection_repo_ids;

int
cf_v2_file_protection_policy(struct _SeafileSession *session, const char *repo_id)
{
if (g_once_init_enter(&protection_policy_state)) {
gboolean valid = session && session->config;
GError *error = NULL;
char *raw = valid ? g_key_file_get_string(session->config, "cloudfile",
"protection_repo_ids", &error) : NULL;
if (error) {
valid = error->domain == G_KEY_FILE_ERROR &&
(error->code == G_KEY_FILE_ERROR_KEY_NOT_FOUND ||
error->code == G_KEY_FILE_ERROR_GROUP_NOT_FOUND);
g_clear_error(&error);
}
protection_repo_ids = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
if (raw && strlen(raw) > 8192)
valid = FALSE;
if (valid && raw && *g_strstrip(raw)) {
char **parts = g_strsplit(raw, ",", -1);
for (char **q = parts; *q && valid; ++q) {
char *id = g_strstrip(*q);
if (!canonical_repo_id(id) || g_hash_table_contains(protection_repo_ids, id))
valid = FALSE;
else
g_hash_table_add(protection_repo_ids, g_strdup(id));
}
g_strfreev(parts);
}
g_free(raw);
if (!valid)
seaf_warning("CloudFile: invalid file protection repository configuration; writes denied.\n");
g_once_init_leave(&protection_policy_state, valid ? 1 : 2);
}
if (protection_policy_state == 2) return -1;
if (!repo_id) return 0;
return g_hash_table_contains(protection_repo_ids, repo_id) ? 1 : 0;
}

int
cf_v2_edit_repo_checkout(struct _SeafileSession *session, const char *repo_id)
{
Expand Down Expand Up @@ -183,9 +226,12 @@ cf_v2_edit_prepare_unscoped_branch(struct _SeafileSession *session,
prepared->repo_id = g_strdup(repo_id);
prepared->old_id = g_strdup(old_commit_id);
prepared->new_id = g_strdup(new_commit_id);
if (policy == 0 || !strcmp(old_commit_id, new_commit_id))
int protection = cf_v2_file_protection_policy(session, repo_id);
if (policy < 0 || protection < 0)
goto fail;
if ((policy == 0 && protection == 0) || !strcmp(old_commit_id, new_commit_id))
return prepared;
if (guard_available(session) <= 0)
if (policy == 1 && guard_available(session) <= 0)
goto fail;
SeafRepo *repo = seaf_repo_manager_get_repo(session->repo_mgr, repo_id);
if (!repo)
Expand All @@ -212,6 +258,58 @@ cf_v2_edit_prepare_unscoped_branch(struct _SeafileSession *session,
return NULL;
}

/* Exact key lookup for files, prefix lookup for removed/renamed directories.
* This runs after Branch(master) is locked and does not scan all protected rows.
* A failed query blocks the candidate, never silently unprotects the file. */
static gboolean
protection_found(SeafDBRow *row, void *data)
{
(void)row;
(void)data;
return FALSE;
}

static char *
protection_prefix(const char *path)
{
GString *s = g_string_new("");
for (const char *c = path; *c; ++c) {
if (*c == '!' || *c == '%' || *c == '_')
g_string_append_c(s, '!');
g_string_append_c(s, *c);
}
g_string_append(s, "/%");
return g_string_free(s, FALSE);
}

static int
protection_changed_path(SeafDBTrans *trans, const char *repo_id, const char *changed)
{
if (!changed || !*changed)
return 0;
char *path = changed[0] == '/' ? g_strdup(changed) : g_strconcat("/", changed, NULL);
if (!strcmp(path, "/") || strlen(path) > 4096 || !g_utf8_validate(path, -1, NULL)) {
g_free(path);
return -1;
}
char *hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, path, -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=? LIMIT 1 FOR UPDATE",
protection_found, NULL, 3,
"string", repo_id, "string", hash, "string", path);
g_free(hash);
if (n != 0) { g_free(path); return -1; }
char *prefix = protection_prefix(path);
n = seaf_db_trans_foreach_selected_row(trans,
"SELECT 1 FROM cf_file_protection FORCE INDEX (cf_file_protection_prefix) "
"WHERE repo_id=? AND path LIKE ? ESCAPE '!' LIMIT 1 FOR UPDATE",
protection_found, NULL, 2, "string", repo_id, "string", prefix);
g_free(prefix);
g_free(path);
return n == 0 ? 0 : -1;
}

int
cf_v2_edit_check_unscoped_branch(SeafDBTrans *trans,
struct _SeafileSession *session,
Expand All @@ -225,31 +323,39 @@ cf_v2_edit_check_unscoped_branch(SeafDBTrans *trans,
g_strcmp0(prepared->old_id, old_commit_id) ||
g_strcmp0(prepared->new_id, new_commit_id))
return -1;
int policy = cf_v2_edit_repo_checkout(session, repo_id);
if (policy <= 0)
return policy;
if (guard_available(session) <= 0)
return -1;
int checkout = cf_v2_edit_repo_checkout(session, repo_id);
int protection = cf_v2_file_protection_policy(session, repo_id);
if (checkout < 0 || protection < 0) return -1;
if (checkout == 0 && protection == 0) return 0;
if (seaf_db_type(session->db) != SEAF_DB_TYPE_MYSQL)
return -1;
if (protection == 1) {
guint count = 0;
for (GList *entry = prepared->changes; entry; entry = entry->next) {
if (++count > 8192) return -1;
DiffEntry *delta = entry->data;
if (!delta || protection_changed_path(trans, repo_id, delta->name) ||
protection_changed_path(trans, repo_id, delta->new_name))
return -1;
}
}
if (checkout == 0) return 0;
if (guard_available(session) <= 0) return -1;

GuardPaths guards = {g_ptr_array_new_with_free_func(g_free), FALSE};
int count = seaf_db_trans_foreach_selected_row(trans,
int n = seaf_db_trans_foreach_selected_row(trans,
"SELECT path FROM cf_edit_guard FORCE INDEX (cf_edit_guard_active) "
"WHERE repo_id=? AND guard_id IS NOT NULL "
"AND lease_expires_at>UTC_TIMESTAMP(6) FOR UPDATE",
read_guard_path, &guards, 1, "string", repo_id);
int rc = -1;
if (count < 0 || guards.invalid)
goto done;
if (n < 0 || guards.invalid) goto done;
rc = 0;
for (GList *entry = prepared->changes; entry != NULL && rc == 0;
entry = entry->next) {
for (GList *entry = prepared->changes; entry && rc == 0; entry = entry->next) {
DiffEntry *delta = entry->data;
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)) {
if (path_touches(delta->name, path) || path_touches(delta->new_name, path)) {
rc = -1;
break;
}
Expand Down
3 changes: 3 additions & 0 deletions common/cf-v2-edit-fence.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ struct _SeafileSession;
* Pure in-memory policy check; never queries Guard for OFF repositories. */
int cf_v2_edit_repo_checkout(struct _SeafileSession *session, const char *repo_id);

// Separate permanent file-protection scope; never interpreted as a Checkout.
int cf_v2_file_protection_policy(struct _SeafileSession *session, const char *repo_id);

/* One candidate commit diff is calculated before acquiring Branch(master)
* for OPTIONAL libraries. Recheck the current Guard rows under the short final
* transaction, without traversing Seafile objects while holding Branch. */
Expand Down
58 changes: 58 additions & 0 deletions doc/file-protection-v1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# CloudFile 文件定版保护 V1:部署与验收合同

状态:开发分支;尚未在 C/Go/Hub 及真实 MariaDB 上通过端到端验收,禁止单仓独立合并或直接部署。
技术基线:Seafile CE14 + CloudFile V2,不依赖 Pro。

## 功能语义

- 对选定资料库中的单个技术文件设置长期不可变状态。所有普通用户(含库管理员)不能覆盖、删除、重命名、移动原件或通过历史版本恢复覆盖它。
- 影响定版文件的上级目录删除、改名、移动均拒绝。V1 暂不允许同库目录改名后自动迁移保护路径。
- 原件允许预览、下载、普通复制;副本不继承保护,允许继续编辑。
- 文件保护与目录 ACL、Checkout 不同;原生 File ID 是定版时的内容校验,不是跨路径唯一身份。
- 仅平台系统管理员且具有资料库管理权限才能 Protect/Unprotect;非管理员的 File Protection 管理 API 直接拒绝。
- 这不是防数据库超级管理员篡改的 WORM 或合规归档承诺。

## 代码复用与最终执行

- C/Go 最终 Branch(master) 提交事务内检查稀疏保护状态,并拒绝覆盖/删除、目录结构影响及提交失败后的回退绕过。
- FileOp PREPARE 是提前提示,不是并发最终授权。
- Agent2 已签出的编辑凭证同样需要通过原生 cfEditCommit 的最终状态检查。
- Repo 删除走独立管理链路,不经文件 Branch。V1 为避免竞态,**保护范围内资料库一律禁止整库删除**;解除所有保护后,可在受控维护中从配置移除该库并完整重启,再删除。
- 未选中的资料库跳过 Protection SQL;选中资料库的保护表 SQL 故障必须拒绝相关写入。
- SQL 按 path_hash 精确检查,并按路径的安全前缀检查受影响后代。最长 8192 Diff 项,超限拒绝,不能无限长时间持有 Branch 锁。

## 模型与部署

新增第六张 V2 扩展表 cf_file_protection:主键为 (repo_id,path_hash),索引为 (repo_id,path 前缀)。
DDL 在 Server 仓 scripts/sql/mysql/cloudfile-v2-protection.sql;Hub Schema 验证需要使用同一份 DDL。

在 C/Go/Hub 共用的 seafile.conf 的 [cloudfile] 节中添加:

protection_repo_ids = 11111111-1111-4111-8111-111111111111

缺省未启用。不需要另外设置 Checkout 开关。

上线顺序:审查 DB DDL 和受控 schema 安装 -> 部署匹配的 Server/Hub/Docker 源码组合 -> 配置完整一致的 repo allowlist -> 全部进程重启 -> 验收。
不得在已有保护行的库撤掉 allowlist 或回滚旧版 Native Server。必要时先受控解除保护。数据库初始化不允许静默修改旧生产卷。

## API 合同

- GET /api/v2.1/cloudfile/protection/v1/status/?repo_id=...&path=/design/a.prt
- POST /api/v2.1/cloudfile/protection/v1/status/ : repo_id + paths (最多 200)
- POST /api/v2.1/cloudfile/protection/v1/protect/
- POST /api/v2.1/cloudfile/protection/v1/unprotect/

修改请求必须携带 repo_id、path、expected_file_id(小写40位原生文件 ID)。
Hub 通过权限校验、文件存在及版本 HEAD CAS,持有 native Branch(master) 锁,原子写入保护表和已有 cf_audit_event。
列表状态通过批量读取投影,不向原生 CE 标签写入 SYS_FILE_PROTECTED;普通标签复制不能传播不可变状态。

## 合并前必须通过

1. Go/C/Hub 真正连同一 MariaDB 和匹配代码运行;并发上传/定版不得跨事务竞态绕过。
2. 覆盖、删除原件、父目录删除、移动/改名、回收站恢复、整库删除均被有效拦截。
3. 普通原生复制读源、向有写权限的新路径创建副本,不会自动继承保护。
4. 旧 Agent2 已签票据、Web、API、同步、WebDAV 路径不得绕过;各类写入返回明确错误。
5. 未启用库没有额外数据库查询,受保护文件数量增加时提交耗时基准合格。
6. 合并前明确 Docker 三仓 SHA 配对和数据库迁移/回滚预案。

本地 Go 定向测试仅覆盖 SQL 逻辑/错误类型,不能替代 C/Linux 完整构建及真实 MySQL 竞态检查。
83 changes: 83 additions & 0 deletions fileserver/cf_file_protection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package main

// Independent permanent file protection. Unlike Checkout it has no owner,
// lease, renewal or publication bypass. Protect/unprotect is a Hub operation
// serialized with native Branch(master); native writes read in that transaction.
import (
"context"
"crypto/sha256"
"database/sql"
"errors"
"strings"

"github.com/haiwen/seafile-server/fileserver/diff"
"github.com/haiwen/seafile-server/fileserver/option"
)

var errCFFileProtected = errors.New("FILE_PROTECTED")
var errCFProtectionUnavailable = errors.New("FILE_PROTECTION_UNAVAILABLE")

const cfProtectionExactSQL = "SELECT 1 FROM cf_file_protection " +
"WHERE repo_id=? AND path_hash=? AND path=? LIMIT 1 FOR UPDATE"
const cfProtectionDescendantSQL = "SELECT 1 FROM cf_file_protection FORCE INDEX (cf_file_protection_prefix) " +
"WHERE repo_id=? AND path LIKE ? ESCAPE '!' LIMIT 1 FOR UPDATE"

// Escape using ! rather than MySQL backslash whose meaning depends on sql_mode.
func cfProtectionLikePattern(value string) string {
return strings.NewReplacer("!", "!!", "%", "!%", "_", "!_").Replace(value) + "/%"
}

func cfProtectionPath(ctx context.Context, tx *sql.Tx, repoID, changed string) error {
if tx == nil || changed == "" || strings.ContainsRune(changed, '\x00') {
return errCFProtectionUnavailable
}
target := "/" + strings.TrimPrefix(changed, "/")
if len(target) > 4096 || target == "/" || strings.Contains(target, "//") {
return errCFProtectionUnavailable
}
hash := sha256.Sum256([]byte(target))
var found int
err := tx.QueryRowContext(ctx, cfProtectionExactSQL, repoID, hash[:], target).Scan(&found)
if err == nil {
return errCFFileProtected
}
if err != sql.ErrNoRows {
return errCFProtectionUnavailable
}
err = tx.QueryRowContext(ctx, cfProtectionDescendantSQL, repoID, cfProtectionLikePattern(target)).Scan(&found)
if err == nil {
return errCFFileProtected
}
if err != sql.ErrNoRows {
return errCFProtectionUnavailable
}
return nil
}

func cfProtectionChanges(ctx context.Context, tx *sql.Tx, repoID string, changes []*diff.DiffEntry) error {
if !option.ProtectionEnabledForRepo(repoID) {
return nil
}
if tx == nil || changes == nil || len(changes) > 8192 {
return errCFProtectionUnavailable
}
for _, change := range changes {
if change == nil {
return errCFProtectionUnavailable
}
seen := make(map[string]struct{}, 2)
for _, name := range []string{change.Name, change.NewName} {
if name == "" {
continue
}
if _, exists := seen[name]; exists {
continue
}
seen[name] = struct{}{}
if err := cfProtectionPath(ctx, tx, repoID, name); err != nil {
return err
}
}
}
return nil
}
Loading
Loading