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
25 changes: 14 additions & 11 deletions common/cf-lock.c
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* CloudFile Server Barrier for the unified cf_edit_guard. Default off. */
/* CloudFile Server Barrier for cf_edit_guard, scoped by live repository policy. */
#include <string.h>

#include "common.h"
Expand Down Expand Up @@ -110,7 +110,10 @@ cf_lock_prepare (const CfFileOp *fop, GError **error)
return 0;
const char *source_repo = fop->src_repo_id ? fop->src_repo_id : fop->repo_id;
int dest = cf_v2_edit_repo_checkout(seaf, fop->repo_id);
int source = cf_v2_edit_repo_checkout(seaf, source_repo);
/* Most file operations stay within a single library. Dynamic policy is
* a database read, so do not query the same repository twice. */
int source = !strcmp(source_repo, fop->repo_id)
? dest : cf_v2_edit_repo_checkout(seaf, source_repo);
if (dest < 0 || source < 0) {
g_set_error(error, SEAFILE_DOMAIN, SEAF_ERR_GENERAL,
"CloudFile per-repo Checkout policy invalid");
Expand Down Expand Up @@ -140,15 +143,15 @@ void
cf_lock_init (void)
{
char *backend = cf_ext_config_string ("lock_backend");
/* Checkout is unfinished and opt-in. A legacy file-lock switch alone
* must not make normal uploads depend on Guard or the retired ledger. */
lock_on = cf_ext_config_bool("checkout_enabled") &&
(!backend || strcmp(backend, "cloudfile") == 0);
/* Register at startup even with no selected repositories. A subsequent
* CloudFile feature API call can enable Checkout without process restart.
* The per-repository policy is read from SQL on every FileOp and the final
* Branch transaction; an OFF repository never scans cf_edit_guard. */
if (backend && strcmp (backend, "cloudfile") != 0)
seaf_warning ("CloudFile: unsupported lock backend '%s'.\n", backend);
seaf_warning ("CloudFile: Checkout uses the native cloudfile barrier; "
"legacy lock backend '%s' is ignored.\n", backend);
g_free (backend);
if (lock_on) {
cf_fileop_register ("file-lock", cf_lock_prepare, NULL, NULL);
seaf_message ("CloudFile: V2 Checkout write barrier enabled.\n");
}
lock_on = TRUE;
cf_fileop_register ("file-lock", cf_lock_prepare, NULL, NULL);
seaf_message ("CloudFile: V2 Checkout FileOp barrier ready for dynamic scope.\n");
}
17 changes: 4 additions & 13 deletions common/cf-v2-edit-fence.c
Original file line number Diff line number Diff line change
Expand Up @@ -118,19 +118,10 @@ cf_v2_file_protection_policy(struct _SeafileSession *session, const char *repo_i
static int
checkout_policy(struct _SeafileSession *session, SeafDBTrans *trans, const char *repo_id)
{
/* C and Go read the same deployment switch from seafile.conf. Only the
* per-repo selection is dynamic; a malformed switch cannot disable a fence. */
if (!session || !session->config)
return -1;
if (!g_key_file_has_key(session->config, "cloudfile", "checkout_enabled", NULL))
return 0;
GError *error = NULL;
gboolean enabled = g_key_file_get_boolean(session->config, "cloudfile", "checkout_enabled", &error);
if (error) {
g_clear_error(&error);
return -1;
}
return enabled ? repo_feature(session, trans, repo_id, "checkout") : 0;
/* Dynamic Checkout is authorized exclusively by cf_repo_feature.
* The former global startup switch is a migration hint, not a security
* gate; final reads still serialize under the Branch(master) lock. */
return repo_feature(session, trans, repo_id, "checkout");
}

int
Expand Down
25 changes: 25 additions & 0 deletions doc/checkout-dynamic-runtime-p0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# CloudFile Checkout / Protection 动态库能力 P0(2026-11-16)

运行期能力的唯一权威是 `cf_repo_feature(repo_id, feature)`。表行存在表示该库启用了 `checkout` 或 `protection`;不存在默认 OFF。

## 无重启启停

使用已授权 CloudFile 平台管理员会话调用已有:
`POST /api/v2.1/admin/cloudfile/repos/<repo-uuid>/features/`,body 例如 `{"checkout": true}`。
修改成功后,Hub、C Server 和 Go Fileserver 通过数据库立即读取新的库级配置,无需修改配置文件或重启。旧的 `checkout_enabled`、`checkout_repo_ids`、`protection_repo_ids` 不能覆盖运行期表值(历史配置仅用于受控迁移)。

- C FileOp 拦截器总是在原生服务启动时注册,但仅对当前选中的 Checkout 库查询 Guard。
- Go 启动时验证 `cf_edit_guard` 的结构;即使未配置任何 Checkout 库也完成就绪探测。Guard 不存在或不可用时,已选中库拒绝签出/受保护写入;普通库不查询 Guard 行。
- Hub 在发票据前查询当前功能及已安装的 Guard Schema;Checkout 不再依赖旧的全局开关。
- 最终 C/Go Branch(master) 提交采用现有事务锁与动态策略读,避免能力变更期间旧客户端绕过。Go Agent2 的旧续租请求也在该锁下重新验证能力。

## 关闭能力

- `checkout=false`:Hub 在同一 Branch(master) 事务内检查未到期的 `cf_edit_guard`;存在活动租约返回 409,且同批其他功能不发生部分更新。租约签入/释放或过期后再重试。
- `protection=false`:仍受既有保护约束,存在 `cf_file_protection` 记录时返回 409。
- 禁止对未同步虚拟库单独设置;源库能力保持最终权威。
- 数据库查询失败不视为 OFF:已选择保护的写入必须拒绝;未选择库不会扫描文件保护和 Guard 行。

## 本次验证边界

已执行本地 C FileOp Fixture(验证启动后无需再调用初始化即可开启),Go fileserver 单元测试、DEV Django 隔离进程的管理 API / 新旧编辑入口单测。真实 Windows Agent2、跨进程 HTTP 业务 E2E、生产部署仍需单独验收。服务器替换为新代码需要一次正常版本升级;**升级之后每次修改库能力无需重启**。
4 changes: 1 addition & 3 deletions fileserver/cf_repo_feature.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package main
import (
"context"
"database/sql"

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

type cfRepoFeatures struct{ checkout, protection bool }
Expand Down Expand Up @@ -35,7 +33,7 @@ func cfReadRepoFeatures(ctx context.Context, repo string, tx *sql.Tx) (features
case "protection":
features.protection = true
case "checkout":
features.checkout = option.CloudFileCheckoutEnabled
features.checkout = true
default:
return features, errCFProtectionUnavailable
}
Expand Down
60 changes: 45 additions & 15 deletions fileserver/cf_upload_guard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,27 +204,57 @@ func TestUploadGuardRefusesGuardFailures(t *testing.T) {
}
}

// Nil DB/transaction proves the disabled path performs no metadata or Guard SQL.
func TestUploadCheckoutDisabledNeverQueriesGuard(t *testing.T) {
old, enabled, oldRepos := option.V2GuardAvailable, option.CloudFileCheckoutEnabled, option.CloudFileCheckoutRepos
// The old global bool cannot authorize or disable a dynamic repository.
// OFF libraries read just one feature index; Checkout Guard is never scanned.
func TestUploadCheckoutDynamicIgnoresGlobalFlag(t *testing.T) {
previousGlobal, previousGuard, previousRepos :=
option.CloudFileCheckoutEnabled, option.V2GuardAvailable, option.CloudFileCheckoutRepos
defer func() {
option.V2GuardAvailable, option.CloudFileCheckoutEnabled, option.CloudFileCheckoutRepos = old, enabled, oldRepos
option.CloudFileCheckoutEnabled, option.V2GuardAvailable, option.CloudFileCheckoutRepos =
previousGlobal, previousGuard, previousRepos
}()
option.CloudFileCheckoutRepos = map[string]struct{}{"repo": {}}
option.CloudFileCheckoutEnabled, option.V2GuardAvailable = false, true
if available, err := loadV2GuardCapability(context.Background(), nil); err != nil || available {
t.Fatalf("disabled capability touched the database: %v", err)
}
db := sql.OpenDB(uploadGuardConnector{&uploadGuardFixture{}})
option.CloudFileCheckoutEnabled = false
option.V2GuardAvailable = true
option.CloudFileCheckoutRepos = map[string]struct{}{}
f := &uploadGuardFixture{}
db := sql.OpenDB(uploadGuardConnector{f})
defer db.Close()
tx, _ := db.Begin()
tx, err := db.Begin()
if err != nil {
t.Fatal(err)
}
defer tx.Rollback()
if err := cfV2EditCheckPreparedBranch(context.Background(), tx, "repo", nil); err != nil {
t.Fatal(err)
t.Fatalf("OFF repo changed behavior: %v", err)
}
option.CloudFileCheckoutEnabled, option.V2GuardAvailable = true, false
if err := cfV2EditCheckPreparedBranch(context.Background(), tx, "repo", []*diff.DiffEntry{}); !errors.Is(err, errCFEditGuard) {
t.Fatal(err)
if len(f.queries) != 1 || !strings.Contains(f.queries[0], "cf_repo_feature") {
t.Fatalf("OFF repository unexpectedly scanned Guard: %v", f.queries)
}
// Enable via the database fixture, without any global restart/config flip.
option.CloudFileCheckoutRepos["repo"] = struct{}{}
f.queries = nil
if err := cfV2EditCheckPreparedBranch(context.Background(), tx, "repo", []*diff.DiffEntry{}); err != nil {
t.Fatalf("dynamic Checkout with a valid Guard was rejected: %v", err)
}
if len(f.queries) != 2 || !strings.Contains(f.queries[1], "cf_edit_guard") {
t.Fatalf("dynamic Checkout skipped the Guard fence: %v", f.queries)
}
// A previously selected repo must fail closed if Guard is unavailable.
option.V2GuardAvailable = false
if err := cfV2EditCheckPreparedBranch(context.Background(), tx, "repo",
[]*diff.DiffEntry{}); !errors.Is(err, errCFEditGuard) {
t.Fatalf("missing Guard allowed dynamically selected Checkout: %v", err)
}
}

func TestCheckoutGuardSchemaProbeIsNotGloballyDisabled(t *testing.T) {
old := option.CloudFileCheckoutEnabled
option.CloudFileCheckoutEnabled = false
defer func() { option.CloudFileCheckoutEnabled = old }()
db := sql.OpenDB(uploadGuardConnector{&uploadGuardFixture{tableCount: 1, currentSchema: true}})
defer db.Close()
if available, err := loadV2GuardCapability(context.Background(), db); err != nil || !available {
t.Fatalf("guard schema was skipped by deprecated global flag: %v", err)
}
}

Expand Down
15 changes: 15 additions & 0 deletions fileserver/cf_v2_edit_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,21 @@ func cfEditGuardAction(w http.ResponseWriter, r *http.Request, c *cfEditClaims,
cfEditFail(w, 503, "SQL_UNAVAILABLE")
return
}
// A renewal can race with an administrator disabling Checkout after the
// lease expired. The policy must be current under the same master Branch
// lock; an OFF repository must not acquire a new Guard lease. Release may
// proceed as a cleanup of an already-owned Guard.
if action == "renew" {
features, policyErr := cfReadRepoFeatures(ctx, repo.ID, tx)
if policyErr != nil {
cfEditFail(w, 503, "POLICY_UNAVAILABLE")
return
}
if !features.checkout || !option.V2GuardAvailable {
cfEditFail(w, 409, "CHECKOUT_UNSUPPORTED")
return
}
}
g, err := cfEditRow(ctx, tx, c)
if err != nil || !cfEditVerified(c, g, p.cfEditProof, true) {
cfEditFail(w, 409, "STALE_GUARD")
Expand Down
15 changes: 8 additions & 7 deletions fileserver/fileserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,11 @@ func loadSeafileDB() {
seafileDB.SetMaxIdleConns(8)
}

// A capability change requires restarting Hub and native services. Disabled
// Checkout never queries a Guard table, even when the baseline DDL includes it.
// Guard schema is checked once at startup regardless of selected repositories.
// Runtime feature changes never require a restart once this schema is installed.
func loadV2GuardCapability(ctx context.Context, db *sql.DB) (bool, error) {
if !option.CloudFileCheckoutEnabled {
return false, nil
if db == nil {
return false, fmt.Errorf("Checkout schema database unavailable")
}
var count int
if err := db.QueryRowContext(ctx,
Expand All @@ -180,8 +180,8 @@ func loadV2GuardCapability(ctx context.Context, db *sql.DB) (bool, error) {
// Modification: validate the installed column/index contract before serving.
// Reason: a present table is not a usable schema. A legacy resource-keyed
// table or a missing cf_edit_guard_active index previously failed every
// upload with SQL 1176; fail once at startup with an operator instruction
// instead, without making disabled Checkout read Guard metadata at all.
// upload with SQL 1176; fail once at startup with an operator instruction.
// Non-selected libraries never scan individual Guard rows.
if err := cfV2GuardRequireCurrent(ctx, db); err != nil {
return false, fmt.Errorf("CF_EDIT_SCHEMA_MISMATCH: installed cf_edit_guard is not the reviewed V2 layout (%v); "+
"archive the legacy rows and apply the reviewed database/v2 SQL package before enabling Checkout", err)
Expand All @@ -195,7 +195,8 @@ func detectV2Guard() {
available, err := loadV2GuardCapability(ctx, seafileDB)
if err != nil {
// OFF repositories remain available on a Guard schema failure. Selected
// repositories refuse unsafe writes until the next controlled restart.
// repositories refuse guarded writes. Schema changes still require a
// controlled release, but repository feature changes do not.
log.Errorf("CloudFile optional Checkout unavailable: %v; selected repositories refuse guarded writes", err)
option.V2GuardAvailable = false
return
Expand Down
12 changes: 4 additions & 8 deletions tests/cf-lock/fixture.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,6 @@ static int cf_v2_edit_repo_checkout(struct _SeafileSession *session, const char
return checkout ? 1 : 0;
}
static int sql_calls, exact_rows, descendant_rows;
static gboolean cf_ext_config_bool(const char *key)
{
/* A stale file_lock_enabled=true must not activate Checkout. */
return !strcmp(key, "checkout_enabled") ? checkout : TRUE;
}
static char *cf_ext_config_string(const char *key)
{
return !strcmp(key, "checkout_repo_ids") && checkout ? g_strdup("fixture") : NULL;
Expand Down Expand Up @@ -50,11 +45,12 @@ int main(void)
{
GError *error = NULL;
checkout=FALSE; cf_lock_init();
g_assert_false(cf_lock_enabled());
g_assert_true(cf_lock_enabled());
g_assert_cmpint(write_path("/file",&error),==,0);
g_assert_cmpint(sql_calls,==,0);
checkout=TRUE; cf_lock_init();
g_assert_true(cf_lock_enabled());
/* Enabling the SQL feature dynamically must work without reinitializing
* the dispatcher or restarting the native server. */
checkout=TRUE;
g_assert_cmpint(write_path("/file",&error),==,0);
g_assert_cmpint(sql_calls,==,2);
exact_rows=1;
Expand Down
Loading