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
5 changes: 5 additions & 0 deletions common/branch-mgr.c
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,11 @@ test_and_update_branch (SeafBranchManager *mgr,
default:
g_return_val_if_reached (-1);
}
if (cf_v2_edit_lock_origin(trans, guard_changes) < 0) {
seaf_db_rollback(trans);
seaf_db_trans_close(trans);
return SEAF_BRANCH_UPDATE_ACL_DENIED;
}
int head_rows = seaf_db_trans_foreach_selected_row (trans, sql,
get_commit_id, commit_id,
2, "string", branch->name,
Expand Down
142 changes: 141 additions & 1 deletion common/cf-v2-edit-fence.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "common.h"
#include "commit-mgr.h"
#include "diff-simple.h"
#include "fs-mgr.h"
#include "log.h"
#include "repo-mgr.h"
#include "seafile-session.h"
Expand Down Expand Up @@ -197,14 +198,119 @@ struct _CfV2EditPrepared {
char *old_id;
char *new_id;
GList *changes;
char *origin;
char *prefix;
GHashTable *candidate_ids;
};

/* Immutable candidate proofs for origin-scoped virtual publications. */
static char *protection_prefix(const char *path);

static gboolean
virtual_mapping(SeafDBRow *row, void *data)
{
CfV2EditPrepared *p = data;
p->origin = g_strdup(seaf_db_row_get_column_text(row, 0));
p->prefix = g_strdup(seaf_db_row_get_column_text(row, 1));
return FALSE;
}

typedef struct {
CfV2EditPrepared *prepared;
struct _SeafileSession *session;
const char *root;
int version;
gboolean final;
gboolean invalid;
guint count;
} VirtualProof;

static gboolean
virtual_protected_row(SeafDBRow *row, void *data)
{
VirtualProof *proof = data;
CfV2EditPrepared *p = proof->prepared;
const char *path = seaf_db_row_get_column_text(row, 0);
const char *id = seaf_db_row_get_column_text(row, 1);
if (!path || !id || ++proof->count > 8192 ||
!g_str_has_prefix(path, p->prefix) || path[strlen(p->prefix)] != '/') {
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)) {
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(
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(""));
}
return TRUE;
}

static int
virtual_rows(SeafDBTrans *trans, VirtualProof *proof, const char *changed)
{
if (!changed || !*changed) return 0;
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 "
"WHERE repo_id=? AND (path=? OR path LIKE ? ESCAPE '!') LIMIT 8193";
char *sql = g_strconcat(query, trans ? " FOR UPDATE" : "", NULL);
proof->count = 0;
int n = trans ? seaf_db_trans_foreach_selected_row(trans, sql,
virtual_protected_row, proof, 3, "string", p->origin, "string", path, "string", pattern)
: seaf_db_statement_foreach_row(proof->session->db, sql,
virtual_protected_row, proof, 3, "string", p->origin, "string", path, "string", pattern);
g_free(sql); g_free(pattern); g_free(path);
return n < 0 || proof->invalid ? -1 : 0;
}

static gboolean
virtual_origin_head(SeafDBRow *row, void *data)
{
const char *head = seaf_db_row_get_column_text(row, 0);
*(gboolean *)data = head && strlen(head) == 40;
return FALSE;
}

int
cf_v2_edit_lock_origin(SeafDBTrans *trans, const CfV2EditPrepared *prepared)
{
if (!prepared) return -1;
if (!prepared->origin) return 0;
gboolean found = FALSE;
int n = seaf_db_trans_foreach_selected_row(trans,
"SELECT commit_id FROM Branch WHERE name='master' AND repo_id=? FOR UPDATE",
virtual_origin_head, &found, 1, "string", prepared->origin);
if (n != 1 || !found) return -1;
CfV2EditPrepared current = {0};
n = seaf_db_trans_foreach_selected_row(trans,
"SELECT origin_repo,path FROM VirtualRepo WHERE repo_id=? FOR UPDATE",
virtual_mapping, &current, 1, "string", prepared->repo_id);
int result = n == 1 && !g_strcmp0(current.origin, prepared->origin) &&
!g_strcmp0(current.prefix, prepared->prefix) ? 0 : -1;
g_free(current.origin); g_free(current.prefix);
return result;
}

void
cf_v2_edit_prepared_free(CfV2EditPrepared *prepared)
{
if (!prepared)
return;
g_list_free_full(prepared->changes, (GDestroyNotify)diff_entry_free);
g_free(prepared->origin);
g_free(prepared->prefix);
if (prepared->candidate_ids) g_hash_table_destroy(prepared->candidate_ids);
g_free(prepared->repo_id);
g_free(prepared->old_id);
g_free(prepared->new_id);
Expand All @@ -229,7 +335,24 @@ cf_v2_edit_prepare_unscoped_branch(struct _SeafileSession *session,
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))
if (g_hash_table_size(protection_repo_ids)) {
int n = seaf_db_statement_foreach_row(session->db,
"SELECT origin_repo,path FROM VirtualRepo WHERE repo_id=?",
virtual_mapping, prepared, 1, "string", repo_id);
if (n < 0) goto fail;
if (n > 0) {
if (!canonical_repo_id(prepared->origin) || !prepared->prefix ||
prepared->prefix[0] != '/' || !strcmp(prepared->origin, repo_id) ||
strlen(prepared->prefix) < 2 || g_str_has_suffix(prepared->prefix, "/")) goto fail;
if (cf_v2_file_protection_policy(session, prepared->origin) == 0) {
g_clear_pointer(&prepared->origin, g_free);
g_clear_pointer(&prepared->prefix, g_free);
} else {
prepared->candidate_ids = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
}
}
}
if ((policy == 0 && protection == 0 && !prepared->origin) || !strcmp(old_commit_id, new_commit_id))
return prepared;
if (policy == 1 && guard_available(session) <= 0)
goto fail;
Expand All @@ -245,6 +368,15 @@ cf_v2_edit_prepare_unscoped_branch(struct _SeafileSession *session,
old_commit->root_id, new_commit->root_id,
&prepared->changes, FALSE)
: -1;
if (result == 0 && prepared->origin) {
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) ||
virtual_rows(NULL, &proof, delta->new_name)) { result = -1; break; }
}
}
if (old_commit)
seaf_commit_unref(old_commit);
if (new_commit)
Expand Down Expand Up @@ -326,6 +458,14 @@ cf_v2_edit_check_unscoped_branch(SeafDBTrans *trans,
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 (prepared->origin) {
VirtualProof proof = {(CfV2EditPrepared *)prepared, session, NULL, 0, TRUE, FALSE, 0};
for (GList *entry = prepared->changes; entry; entry = entry->next) {
DiffEntry *delta = entry->data;
if (virtual_rows(trans, &proof, delta->name) || virtual_rows(trans, &proof, delta->new_name))
return -1;
}
}
if (checkout == 0 && protection == 0) return 0;
if (seaf_db_type(session->db) != SEAF_DB_TYPE_MYSQL)
return -1;
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 @@ -23,6 +23,9 @@ CfV2EditPrepared *cf_v2_edit_prepare_unscoped_branch(
void cf_v2_edit_prepared_free(CfV2EditPrepared *prepared);
G_DEFINE_AUTOPTR_CLEANUP_FUNC(CfV2EditPrepared, cf_v2_edit_prepared_free)

/* Lock origin before the virtual Branch; shared with Hub protect/unprotect. */
int cf_v2_edit_lock_origin(SeafDBTrans *trans, const CfV2EditPrepared *prepared);

/* Called only after Branch(master) FOR UPDATE, before updating Branch.
* Zero: unscoped write does not touch a reserved file.
* -1: guarded/conflicting/unverifiable; caller MUST rollback. */
Expand Down
14 changes: 14 additions & 0 deletions fileserver/cf_upload_guard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import (
// Exercise production SQL selection and row validation through database/sql.
// This fixture does not certify MySQL lock behavior or a deployed upload.
type uploadGuardFixture struct {
protectedRows map[string]string
virtualPrefix string
columns []string
paths []driver.Value
failMetadata, failGuard bool
Expand Down Expand Up @@ -76,13 +78,25 @@ func (c *uploadGuardConn) QueryContext(_ context.Context, query string, args []d
}
}
}
} else if strings.Contains(query, "FROM VirtualRepo") {
rows.names = []string{"origin", "path"}
rows.values = append(rows.values, []driver.Value{"repo", c.fixture.virtualPrefix})
} else if strings.Contains(query, "FROM Branch") {
rows.values = append(rows.values, []driver.Value{strings.Repeat("a", 40)})
} else if strings.Contains(query, "FROM cf_file_protection") {
if c.fixture.failGuard {
return nil, errors.New("protection SQL unavailable")
}
if len(args) < 2 || args[0].Value != "repo" {
return nil, errors.New("wrong protected repository")
}
if strings.Contains(query, "SELECT path,file_id") {
rows.names = []string{"path", "file_id"}
for p, id := range c.fixture.protectedRows {
rows.values = append(rows.values, []driver.Value{p, id})
}
return rows, nil
}
if (strings.Contains(query, "path LIKE") && c.fixture.protectionDescendant) ||
(strings.Contains(query, "path_hash") && c.fixture.protectionExact) {
rows.values = append(rows.values, []driver.Value{int64(1)})
Expand Down
147 changes: 147 additions & 0 deletions fileserver/cf_virtual_protection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package main

// Virtual publications serialize with protection changes on their origin.
// Resolve changed protected paths and immutable candidate objects before SQL locks.
import (
"context"
"database/sql"
"strings"

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

type cfVirtualProtection struct {
repo, origin, prefix string
paths []string
candidate map[string]string
}

type cfProtectionReader interface {
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
}

func cfVirtualProtectedRows(ctx context.Context, db cfProtectionReader, origin, path string, locked bool) (map[string]string, error) {
query := "SELECT path,file_id FROM cf_file_protection WHERE repo_id=? AND (path=? OR path LIKE ? ESCAPE '!') LIMIT 8193"
if locked {
query += " FOR UPDATE"
}
rows, err := db.QueryContext(ctx, query, origin, path, cfProtectionLikePattern(path))
if err != nil {
return nil, errCFProtectionUnavailable
}
defer rows.Close()
result := make(map[string]string)
for rows.Next() {
var p, id string
if rows.Scan(&p, &id) != nil || len(result) >= 8192 {
return nil, errCFProtectionUnavailable
}
result[p] = id
}
if rows.Err() != nil {
return nil, errCFProtectionUnavailable
}
return result, nil
}

func cfPrepareVirtualProtection(ctx context.Context, repo, oldID, newID string) (*cfVirtualProtection, error) {
if len(option.CloudFileProtectionRepos) == 0 {
return nil, nil
}
v := &cfVirtualProtection{repo: repo, candidate: make(map[string]string)}
err := seafileDB.QueryRowContext(ctx, "SELECT origin_repo,path FROM VirtualRepo WHERE repo_id=?", repo).Scan(&v.origin, &v.prefix)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, errCFProtectionUnavailable
}
if !option.ProtectionEnabledForRepo(v.origin) {
return nil, nil
}
if v.origin == repo || v.prefix == "" || !strings.HasPrefix(v.prefix, "/") || strings.Contains(v.prefix, "//") || strings.HasSuffix(v.prefix, "/") {
return nil, errCFProtectionUnavailable
}
old, err := commitmgr.Load(repo, oldID)
if err != nil {
return nil, errCFProtectionUnavailable
}
next, err := commitmgr.Load(repo, newID)
if err != nil {
return nil, errCFProtectionUnavailable
}
var changes []*diff.DiffEntry
if diff.DiffCommits(old, next, &changes, false) != nil || len(changes) > 8192 {
return nil, errCFProtectionUnavailable
}
seen := make(map[string]bool)
for _, change := range changes {
for _, name := range []string{change.Name, change.NewName} {
if name == "" {
continue
}
p := v.prefix + "/" + strings.TrimPrefix(name, "/")
if seen[p] {
continue
}
seen[p] = true
v.paths = append(v.paths, p)
protected, err := cfVirtualProtectedRows(ctx, seafileDB, v.origin, p, false)
if err != nil {
return nil, err
}
for path := range protected {
if _, ok := v.candidate[path]; ok {
continue
}
if len(v.candidate) >= 8192 {
return nil, errCFProtectionUnavailable
}
id, mode, err := fsmgr.GetObjIDByPath(v.origin, next.RootID, strings.TrimPrefix(path, v.prefix))
// Missing/invalid objects cannot prove preservation of the original.
if err != nil || !fsmgr.IsRegular(mode) {
id = ""
}
v.candidate[path] = id
}
}
}
return v, nil
}

func (v *cfVirtualProtection) lockOrigin(ctx context.Context, tx *sql.Tx) error {
if v == nil {
return nil
}
var head, origin, path string
if tx.QueryRowContext(ctx, "SELECT commit_id FROM Branch WHERE name='master' AND repo_id=? FOR UPDATE", v.origin).Scan(&head) != nil {
return errCFProtectionUnavailable
}
// A path remap invalidates the candidate proof, never silently redirects it.
if tx.QueryRowContext(ctx, "SELECT origin_repo,path FROM VirtualRepo WHERE repo_id=? FOR UPDATE", v.repo).Scan(&origin, &path) != nil || origin != v.origin || path != v.prefix {
return errCFProtectionUnavailable
}
return nil
}

func (v *cfVirtualProtection) check(ctx context.Context, tx *sql.Tx) error {
if v == nil {
return nil
}
for _, path := range v.paths {
rows, err := cfVirtualProtectedRows(ctx, tx, v.origin, path, true)
if err != nil {
return err
}
for p, id := range rows {
// Also allows native origin-to-view refresh preserving the protected ID.
if v.candidate[p] == "" || v.candidate[p] != id {
return errCFFileProtected
}
}
}
return nil
}
Loading
Loading