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
108 changes: 67 additions & 41 deletions common/cf-v2-edit-fence.c
Original file line number Diff line number Diff line change
Expand Up @@ -92,42 +92,56 @@ warn_legacy_repo_scope (struct _SeafileSession *session)

/* A final locking read serializes a feature change with publication. Never
* retain process-wide allowlists or interpret an unavailable policy as OFF. */
static int
repo_feature(struct _SeafileSession *session, SeafDBTrans *trans,
const char *repo_id, const char *feature)
typedef struct {
gboolean checkout;
gboolean protection;
gboolean invalid;
} CfRepoPolicy;

static gboolean
read_feature(SeafDBRow *row, void *data)
{
gboolean error = FALSE;
if (!session || !session->db || !canonical_repo_id(repo_id))
return -1;
gboolean present = trans ? seaf_db_trans_check_for_existence(trans,
"SELECT 1 FROM cf_repo_feature WHERE repo_id=? AND feature=? LOCK IN SHARE MODE",
&error, 2, "string", repo_id, "string", feature) :
seaf_db_statement_exists(session->db,
"SELECT 1 FROM cf_repo_feature WHERE repo_id=? AND feature=?",
&error, 2, "string", repo_id, "string", feature);
return error ? -1 : present;
CfRepoPolicy *policy = data;
const char *key = seaf_db_row_get_column_text(row, 0);
if (g_strcmp0(key, "checkout") == 0)
policy->checkout = TRUE;
else if (g_strcmp0(key, "protection") == 0)
policy->protection = TRUE;
else {
policy->invalid = TRUE;
return FALSE;
}
return TRUE;
}

int
cf_v2_file_protection_policy(struct _SeafileSession *session, const char *repo_id)
static gboolean
read_repo_policy(struct _SeafileSession *session, SeafDBTrans *trans,
const char *repo_id, CfRepoPolicy *policy)
{
warn_legacy_repo_scope (session);
return repo_feature(session, NULL, repo_id, "protection");
if (!session || !session->db || !canonical_repo_id(repo_id))
return FALSE;
warn_legacy_repo_scope(session);
const char sql[] = "SELECT feature FROM cf_repo_feature WHERE repo_id=?";
int rows = trans ? seaf_db_trans_foreach_selected_row(trans,
"SELECT feature FROM cf_repo_feature WHERE repo_id=? LOCK IN SHARE MODE",
read_feature, policy, 1, "string", repo_id) :
seaf_db_statement_foreach_row(session->db, sql, read_feature, policy,
1, "string", repo_id);
return rows >= 0 && !policy->invalid;
}

static int
checkout_policy(struct _SeafileSession *session, SeafDBTrans *trans, const char *repo_id)
int
cf_v2_file_protection_policy(struct _SeafileSession *session, const char *repo_id)
{
/* 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");
CfRepoPolicy policy = {0};
return read_repo_policy(session, NULL, repo_id, &policy) ? policy.protection : -1;
}

int
cf_v2_edit_repo_checkout(struct _SeafileSession *session, const char *repo_id)
{
return checkout_policy(session, NULL, repo_id);
CfRepoPolicy policy = {0};
return read_repo_policy(session, NULL, repo_id, &policy) ? policy.checkout : -1;
}

/* Schema is validated on guarded paths only. Its absence is a failure for an
Expand Down Expand Up @@ -159,6 +173,20 @@ guard_available(struct _SeafileSession *session)
return guard_schema_state == 2 ? 1 : -1;
}

/* Versioned local RPC. A mixed-version deployment cannot attest readiness. */
int
cf_v2_writer_capabilities(GError **error)
{
if (!seaf || !seaf->db || seaf_db_type(seaf->db) != SEAF_DB_TYPE_MYSQL)
return 0;
gboolean db_error = FALSE;
seaf_db_statement_exists(seaf->db,
"SELECT repo_id,path_hash,path,file_id,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);
}

/* The Guard policy is OFF by default. For OPTIONAL libraries, resolve the
* candidate commit's changed paths before opening the final Branch transaction.
* DiffEntry objects are immutable for this candidate: a racing HEAD is caught
Expand Down Expand Up @@ -296,18 +324,15 @@ cf_v2_edit_prepare_unscoped_branch(struct _SeafileSession *session,
{
if (!session || !repo_id || !old_commit_id || !new_commit_id)
return NULL;
int policy = cf_v2_edit_repo_checkout(session, repo_id);
if (policy < 0)
CfRepoPolicy policy = {0};
if (!read_repo_policy(session, NULL, repo_id, &policy))
return NULL;
CfV2EditPrepared *prepared = g_new0(CfV2EditPrepared, 1);
prepared->repo_id = g_strdup(repo_id);
prepared->old_id = g_strdup(old_commit_id);
prepared->new_id = g_strdup(new_commit_id);
int protection = cf_v2_file_protection_policy(session, repo_id);
if (policy < 0 || protection < 0)
goto fail;
prepared->checkout = policy;
prepared->protection = protection;
prepared->checkout = policy.checkout;
prepared->protection = policy.protection;
{
int n = seaf_db_statement_foreach_row(session->db,
"SELECT origin_repo,path FROM VirtualRepo WHERE repo_id=?",
Expand All @@ -324,9 +349,9 @@ cf_v2_edit_prepare_unscoped_branch(struct _SeafileSession *session,
}
}
}
if ((policy == 0 && protection == 0 && !prepared->origin_protection) || !strcmp(old_commit_id, new_commit_id))
if ((!policy.checkout && !policy.protection && !prepared->origin_protection) || !strcmp(old_commit_id, new_commit_id))
return prepared;
if (policy == 1 && guard_available(session) <= 0)
if (policy.checkout && guard_available(session) <= 0)
goto fail;
SeafRepo *repo = seaf_repo_manager_get_repo(session->repo_mgr, repo_id);
if (!repo)
Expand Down Expand Up @@ -427,11 +452,12 @@ 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 checkout = checkout_policy(session, trans, repo_id);
int protection = repo_feature(session, trans, repo_id, "protection");
if (checkout != prepared->checkout || protection != prepared->protection ||
(prepared->origin && repo_feature(session, trans, prepared->origin, "protection") !=
prepared->origin_protection)) return -1;
CfRepoPolicy policy = {0}, origin = {0};
if (!read_repo_policy(session, trans, repo_id, &policy) ||
policy.checkout != prepared->checkout || policy.protection != prepared->protection ||
(prepared->origin && (!read_repo_policy(session, trans, prepared->origin, &origin) ||
origin.protection != prepared->origin_protection)))
return -1;
if (prepared->origin_protection) {
VirtualProof proof = {(CfV2EditPrepared *)prepared, session, NULL, 0, TRUE, FALSE, 0};
for (GList *entry = prepared->changes; entry; entry = entry->next) {
Expand All @@ -440,10 +466,10 @@ cf_v2_edit_check_unscoped_branch(SeafDBTrans *trans,
return -1;
}
}
if (checkout == 0 && protection == 0) return 0;
if (!policy.checkout && !policy.protection) return 0;
if (seaf_db_type(session->db) != SEAF_DB_TYPE_MYSQL)
return -1;
if (protection == 1) {
if (policy.protection) {
guint count = 0;
for (GList *entry = prepared->changes; entry; entry = entry->next) {
if (++count > 8192) return -1;
Expand All @@ -453,7 +479,7 @@ cf_v2_edit_check_unscoped_branch(SeafDBTrans *trans,
return -1;
}
}
if (checkout == 0) return 0;
if (!policy.checkout) return 0;
if (guard_available(session) <= 0) return -1;

GuardPaths guards = {g_ptr_array_new_with_free_func(g_free), FALSE};
Expand Down
4 changes: 3 additions & 1 deletion common/cf-v2-edit-fence.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@

struct _SeafileSession;

int cf_v2_writer_capabilities(GError **error);

/* 0=OFF, 1=OPTIONAL, -1=invalid configuration (fail closed).
* Pure in-memory policy check; never queries Guard for OFF repositories. */
* Indexed repository 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.
Expand Down
86 changes: 86 additions & 0 deletions fileserver/cf_writer_capabilities.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package main

import (
"context"
"fmt"
"net/http"
"strings"
"time"

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

// Hub calls each direct writer endpoint with a dedicated short-lived ticket.
// A successful response covers this Go process and its paired native C server.
func cfWriterCapabilities(w http.ResponseWriter, r *http.Request) {
header := strings.Fields(r.Header.Get("Authorization"))
if len(header) != 2 || header[0] != "Bearer" || len(header[1]) > 2048 || option.JWTPrivateKey == "" {
cfEditFail(w, http.StatusForbidden, "FORBIDDEN")
return
}
_, err := jwt.Parse(header[1], func(*jwt.Token) (interface{}, error) {
return []byte(option.JWTPrivateKey), nil
}, jwt.WithValidMethods([]string{"HS256"}), jwt.WithExpirationRequired(),
jwt.WithIssuer("cloudfile-hub"), jwt.WithAudience("cf-writer-capabilities-v1"))
if err != nil {
cfEditFail(w, http.StatusForbidden, "FORBIDDEN")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
reply, err := rpcclient.CallWithTimeout(time.Second, "cf_v2_writer_capabilities_v1")
mask, valid := reply.(float64)
if err != nil || !valid || mask != float64(int(mask)) || mask < 0 || mask > 3 {
cfEditFail(w, http.StatusServiceUnavailable, "NATIVE_PROBE_UNAVAILABLE")
return
}
checkout := int(mask)&1 != 0 && option.V2GuardAvailable && cfV2GuardRequireCurrent(ctx, seafileDB) == nil
protection := int(mask)&2 != 0 && cfProtectionSchemaReady(ctx) == nil
cfEditJSON(w, http.StatusOK, map[string]bool{"checkout": checkout, "protection": protection})
}

func cfProtectionSchemaReady(ctx context.Context) error {
// The physical path must be unique and the write barrier forces the
// descendant index. Reuse the Guard metadata representation for checks.
rows, err := seafileDB.QueryContext(ctx,
"SELECT COLUMN_NAME,DATA_TYPE,COALESCE(CHARACTER_MAXIMUM_LENGTH,0),IS_NULLABLE "+
"FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='cf_file_protection'")
if err != nil {
return err
}
defer rows.Close()
want := map[string]cfGuardColumn{
"repo_id": {"char", 36, "NO", false}, "path_hash": {"binary", 32, "NO", false},
"path": {"varchar", 4096, "NO", false}, "file_id": {"char", 40, "NO", false},
"protected_by": {"varchar", 255, "NO", false}, "protected_at": {"datetime", 0, "NO", false},
}
for rows.Next() {
var name string
var got cfGuardColumn
if err := rows.Scan(&name, &got.kind, &got.length, &got.nullable); err != nil {
return err
}
if want[name] != got {
return fmt.Errorf("unexpected protection column %s", name)
}
delete(want, name)
}
if err := rows.Err(); err != nil {
return err
}
if len(want) != 0 {
return fmt.Errorf("missing protection columns")
}
var primary, prefix string
err = seafileDB.QueryRowContext(ctx, `SELECT
COALESCE(GROUP_CONCAT(IF(INDEX_NAME='PRIMARY',part,NULL) ORDER BY seq),''),
COALESCE(GROUP_CONCAT(IF(INDEX_NAME='cf_file_protection_prefix',part,NULL) ORDER BY seq),'')
FROM (SELECT INDEX_NAME,SEQ_IN_INDEX seq,CONCAT(COLUMN_NAME,':',COALESCE(SUB_PART,0)) part
FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE()
AND TABLE_NAME='cf_file_protection') AS parts`).Scan(&primary, &prefix)
if err == nil && (primary != "repo_id:0,path_hash:0" || prefix != "repo_id:0,path:191") {
return fmt.Errorf("invalid protection index")
}
return err
}
35 changes: 35 additions & 0 deletions fileserver/cf_writer_capabilities_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"net/http"
"net/http/httptest"
"testing"
"time"

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

func TestCFWriterProbeRequiresDedicatedTicket(t *testing.T) {
previous := option.JWTPrivateKey
option.JWTPrivateKey = "isolated-writer-probe-test-key"
t.Cleanup(func() { option.JWTPrivateKey = previous })
router := newHTTPRouter()
for _, audience := range []string{"", "cloudfile-edit-agent"} {
r := httptest.NewRequest(http.MethodGet, "/internal/cf-writer-capabilities/v1", nil)
if audience != "" {
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"iss": "cloudfile-hub", "aud": audience, "exp": time.Now().Add(time.Minute).Unix(),
}).SignedString([]byte(option.JWTPrivateKey))
if err != nil {
t.Fatal(err)
}
r.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Fatalf("audience %q: got %d", audience, w.Code)
}
}
}
1 change: 1 addition & 0 deletions fileserver/fileserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,7 @@ func rpcClientInit() {

func newHTTPRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/internal/cf-writer-capabilities/v1", cfWriterCapabilities).Methods(http.MethodGet)
r.HandleFunc("/protocol-version{slash:\\/?}", handleProtocolVersion)
r.Handle("/files/{.*}/{.*}", appHandler(accessCB))
r.Handle("/blks/{.*}/{.*}", appHandler(accessBlksCB))
Expand Down
6 changes: 6 additions & 0 deletions server/seaf-server.c
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include <searpc-client.h>

#include "seafile-session.h"
#include "cf-v2-edit-fence.h"
#include "seafile-rpc.h"
#include "log.h"
#include "utils.h"
Expand Down Expand Up @@ -717,6 +718,11 @@ static void start_rpc_service (const char *seafile_dir,
"cf_find_restricted_path",
searpc_signature_string__string_string_string());

searpc_server_register_function ("seafserv-threaded-rpcserver",
cf_v2_writer_capabilities,
"cf_v2_writer_capabilities_v1",
searpc_signature_int__void());

/* CloudFile write lifecycle */
searpc_server_register_function ("seafserv-threaded-rpcserver",
seafile_cf_fileop_active,
Expand Down
4 changes: 2 additions & 2 deletions tests/test_cf_checkout_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ def test_write_barrier_checks_policy_before_guard_sql(self):

def test_optional_without_guard_fails_closed(self):
source = (ROOT / 'common/cf-v2-edit-fence.c').read_text()
self.assertIn('policy = cf_v2_edit_repo_checkout', source)
self.assertIn('read_repo_policy(session, NULL, repo_id, &policy)', source)
# guard_available() must not report an absent schema as usable.
self.assertIn('return guard_schema_state == 2 ? 1 : -1;', source)

def test_dynamic_policy_uses_locked_read_for_final_publication(self):
source = (ROOT / 'common/cf-v2-edit-fence.c').read_text()
self.assertIn('SELECT 1 FROM cf_repo_feature', source)
self.assertIn('SELECT feature FROM cf_repo_feature', source)
self.assertIn('LOCK IN SHARE MODE', source)
self.assertIn('checkout != prepared->checkout', source)

Expand Down
Loading