From e4be0e173dc7fe01f855a952a502d086bdbe63de Mon Sep 17 00:00:00 2001 From: dev9-bb Date: Fri, 13 Nov 2026 14:34:12 +0800 Subject: [PATCH 1/2] feat: integrate file protection schema and repository scope --- AGENTS.md | 12 ++-- deploy/compose/docker-compose.yml | 2 + docs/file-protection-v1.md | 47 +++++++++++++++ docs/upstream-patches/cloudfile-server.txt | 2 + scripts/scripts_cf14.0/cloudfile_bootstrap.py | 19 ++++-- scripts/scripts_cf14.0/cloudfile_schema.py | 26 ++++---- tests/test_checkout_repo_config.py | 14 ++++- tests/test_fresh_schema.py | 16 ++--- tests/test_protection_migration.py | 55 +++++++++++++++++ tests/test_v2_schema_inventory.py | 2 +- tools/gates/check-sql-contracts.py | 10 ++-- tools/gates/test-bootstrap-settings.py | 2 +- tools/migrate/file-protection-v1.py | 59 +++++++++++++++++++ 13 files changed, 230 insertions(+), 36 deletions(-) create mode 100644 docs/file-protection-v1.md create mode 100644 tests/test_protection_migration.py create mode 100644 tools/migrate/file-protection-v1.py diff --git a/AGENTS.md b/AGENTS.md index a1390b5d..ea4e8003 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -156,9 +156,9 @@ V2 内置 ACL、CE 原生 Tag 和已安装 Guard 的 Checkout 不应重新受旧 不要提交 `deploy/compose/.env`、任何真实凭据、密钥、持久数据卷或镜像构建产物。文档中文,代码和 commit message 英文;上游既有风格优先。 -## 数据库唯一规则:当前五表 +## 数据库唯一规则:当前六表 -- V2 仅保留 `cf_library_storage`、`cf_dir_acl`、`cf_sso_group_map`、`cf_edit_guard`、`cf_audit_event`。新装五表一次性创建,已有卷只校验,不自动迁移或修补。 +- V2 仅保留 `cf_library_storage`、`cf_dir_acl`、`cf_sso_group_map`、`cf_edit_guard`、`cf_audit_event`、`cf_file_protection`。新装六表一次性创建,已有卷只校验,不自动迁移或修补。 - DEV 旧数据全部放弃。存储绑定从 Seafile 原生库重新发现,ACL/共享与组织角色从客户 Provider 重同步,Guard/审计从空表开始;旧 `cf_tag`/Resource/Intent/Session/Outbox 等绝不恢复。 - DEV 如需清表重建,仅允许停写后由人工管理员按当前 DDL 操作,不做产品级迁移/历史追溯/归档库;**绝不删除或改写 Seafile 原生文件版本和存储路由**。 @@ -171,12 +171,12 @@ V2 内置 ACL、CE 原生 Tag 和已安装 Guard 的 Checkout 不应重新受旧 ## 当前镜像只携带 V2 初始化及运行入口 -- 启动调用 `cloudfile_schema.py`,只创建/校验 4+1 表;历史 `cloudfile.sql`、SchemaRunner 和旧 SQL Workers 不属于产品镜像。禁止为旧代码恢复 `cf_schema_migration` 或其他旧表。 +- 启动调用 `cloudfile_schema.py`,只创建/校验 六表 表;历史 `cloudfile.sql`、SchemaRunner 和旧 SQL Workers 不属于产品镜像。禁止为旧代码恢复 `cf_schema_migration` 或其他旧表。 - 旧 DEV 修复/迁移材料不属于当前产品代码,不由构建、启动、升级或工作进程调用。禁止用测试历史脚本的成功状态声称当前 DEV 镜像已经升级。 ## 轻量跨仓运行表检查 -- `tools/gates/check-sql-contracts.py` 当前只检查 4+1 DDL 与 Server/Hub/Docker/可选 Agent2 **可运行** SQL 依赖,不再生成/更新旧 001–042 checksum 台账;DEV 数据直接舍弃重建,不提供历史数据修复工具。 +- `tools/gates/check-sql-contracts.py` 当前只检查 六表 DDL 与 Server/Hub/Docker/可选 Agent2 **可运行** SQL 依赖,不再生成/更新旧 001–042 checksum 台账;DEV 数据直接舍弃重建,不提供历史数据修复工具。 - `tools/gates/run-checks.sh` 不再将历史 001–042 数据转换、旧四表 SQL 包作为日常产品测试。禁止每次小改动启动全量编译。 ## 现行 V2 权限契约:禁止“托管库”复活(2026-10-21) @@ -185,4 +185,6 @@ V2 内置 ACL、CE 原生 Tag 和已安装 Guard 的 Checkout 不应重新受旧 - 唯一权限链: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 权限终判契约及六张扩展表为准;历史文档只用于追溯,不得作为实施依据。跨仓变更必须维护防复活的源码扫描和正反权限用例。 + +文件保护 V1 经明确授权增加第六表;已有五表卷仅通过 `tools/migrate/file-protection-v1.py` 在停写维护中显式升级,启动不自动迁移,不引入通用迁移台账。 diff --git a/deploy/compose/docker-compose.yml b/deploy/compose/docker-compose.yml index ba73475c..db536108 100644 --- a/deploy/compose/docker-compose.yml +++ b/deploy/compose/docker-compose.yml @@ -210,6 +210,7 @@ services: CF_LOCK_BACKEND: ${CF_LOCK_BACKEND:-cloudfile} CF_ENABLE_CHECKOUT: ${CF_ENABLE_CHECKOUT:-false} CF_CHECKOUT_REPOS: ${CF_CHECKOUT_REPOS:-} + CF_PROTECTION_REPOS: ${CF_PROTECTION_REPOS:-} # Keep explicit policy/transfer settings effective on both app and worker. # Native administrator policy is initialized automatically from existing SQL settings. CF_ENABLE_LOCAL_APP: ${CF_ENABLE_LOCAL_APP:-false} @@ -471,6 +472,7 @@ services: CF_LOCK_BACKEND: ${CF_LOCK_BACKEND:-cloudfile} CF_ENABLE_CHECKOUT: ${CF_ENABLE_CHECKOUT:-false} CF_CHECKOUT_REPOS: ${CF_CHECKOUT_REPOS:-} + CF_PROTECTION_REPOS: ${CF_PROTECTION_REPOS:-} # Keep explicit policy/transfer settings effective on both app and worker. # Native administrator policy is initialized automatically from existing SQL settings. CF_ENABLE_LOCAL_APP: ${CF_ENABLE_LOCAL_APP:-false} diff --git a/docs/file-protection-v1.md b/docs/file-protection-v1.md new file mode 100644 index 00000000..f8bdc847 --- /dev/null +++ b/docs/file-protection-v1.md @@ -0,0 +1,47 @@ +# 文件保护 V1 配套安装与联验 + +此组合仍为 Draft,禁止单仓合并或部署。文件原件可读、可复制;写入、删除、移动、改名和影响原件的上级目录操作拒绝。目录改名自动迁移不在 V1 内。 + +## 配置 + +Compose 各应用实例设置同一 `CF_PROTECTION_REPOS`,值为逗号分隔的小写标准 Repo UUID;缺省为空,不开启任何库。启动生成共享 `seafile.conf` 的 `[cloudfile] protection_repo_ids`,C/Go/Hub 读取同一份配置。此范围独立于 Checkout,不改变租约。 + +配置变更后所有 Server、Hub、后台工作进程必须同步重启。不得从范围移除仍有保护记录的资料库,也不得运行不包含保护屏障的旧版本。保护范围内整库删除一律拒绝。 + +## 数据库 + +新卷一次安装六表。已有卷启动只校验,缺保护表即拒绝启动,不自动补表。五表升级使用本仓 `tools/migrate/file-protection-v1.py`,读取匹配发行包内的四份 DDL 以及 Hub `FreshSchema`;先验证五张既有表精确结构,再只创建保护表,不改业务行和 CE 原生表,不引入迁移台账。 + +在独立维护进程中提供既有 `SEAFILE_MYSQL_DB_*` 环境变量,先检查: + +```sh +python3 tools/migrate/file-protection-v1.py --installdir /path/to/seafile-server +``` + +检查会使用连接级协调锁和临时表比较 DDL,不修改持久表。管理员确认全部写入已停止后显式执行: + +```sh +python3 tools/migrate/file-protection-v1.py --installdir /path/to/seafile-server --apply --writers-stopped +``` + +`--writers-stopped` 是维护人员的明确声明,不代替真实停写。DDL 在 MySQL 自动提交;中断后重跑会校验既有六表并返回无需修改。异常结构拒绝执行,不自动 DROP/ALTER。失败后保持停写,检查结构,禁止绕过校验启动旧版。存在保护记录时不得降级;解除保护、移除范围和回退须另行维护评审。 + +## 配套构建 + +沿用 `release.yaml` 默认 dev,不永久将产品源码指向功能分支。联验时对三仓选择 `feat/file-protection-v1`,由已有入口一次解析为固定 SHA 收据: + +```sh +CF_SERVER_REF=feat/file-protection-v1 CF_HUB_REF=feat/file-protection-v1 \ +CF_DOCKER_REF=feat/file-protection-v1 CF_BUILD_JOBS=2 \ +bash build/cloudfile_14.0/build-in-docker.sh 14.0.8-protection-v1-test +``` + +工作树须已提交、推送且干净;复用既有基础镜像和缓存。构建结果不等于部署验收。 + +## 合并前验收 + +- 六表新装、五表显式升级、重复执行、结构异常拒绝和启动只读校验。 +- C/Go 与 Hub 共用 MariaDB:定版与上传双向竞争,检查实际 Branch 行锁等待。 +- 覆盖、历史恢复、父目录删除/移动/改名、旧 Agent2 票据均拒绝;读取和复制到新路径可用,副本可编辑。 +- 普通库零 Protection SQL;选定库大批量提交基准和 SQL 故障拒绝。 +- Etech 真实用户 Web/API/Agent2 验收另行完成;DEV/PROD 不在本次修改范围。 diff --git a/docs/upstream-patches/cloudfile-server.txt b/docs/upstream-patches/cloudfile-server.txt index e0b87f63..bf032c21 100644 --- a/docs/upstream-patches/cloudfile-server.txt +++ b/docs/upstream-patches/cloudfile-server.txt @@ -77,3 +77,5 @@ server/web-accesstoken-mgr.h # 2026-10-21 复检修复:common/branch-mgr.c:add/del/update 三个 MySQL 分支写入口先锁 Branch(master),再执行现有最终 ACL 校验,与 ACLStore 写入锁顺序一致;允许原生新建库尚无 master。 # 2026-10-21 VirtualRepo 兼容:common/cf-v2-acl.c 公开链接复用 CE origin/path 映射;原生转存不再仅因虚拟库类型拒绝。缺少范围证明的受 ACL 限制操作仍保留现有边界。server/Makefile.am 删除已退役头文件引用。 + +# 2026-11-13 文件保护 V1:server/repo-mgr.c 对配置保护范围内资料库拒绝整库删除,避免绕过 Branch 提交屏障。fileserver/option/option.go 加载独立保护范围;最终文件写入复用 cf-v2-edit-fence。 diff --git a/scripts/scripts_cf14.0/cloudfile_bootstrap.py b/scripts/scripts_cf14.0/cloudfile_bootstrap.py index 75daa1a9..f74acbb7 100644 --- a/scripts/scripts_cf14.0/cloudfile_bootstrap.py +++ b/scripts/scripts_cf14.0/cloudfile_bootstrap.py @@ -127,11 +127,11 @@ def cf_enabled(name): return get_conf(name, default).lower() == 'true' -def _checkout_repo_ids(): +def _repo_ids(setting): """Canonical UUID allowlist for OPTIONAL Checkout; all other repos are OFF.""" - raw = get_conf('CF_CHECKOUT_REPOS', '') + raw = get_conf(setting, '') if len(raw) > 8192: - raise ValueError('CF_CHECKOUT_REPOS exceeds 8192 bytes') + raise ValueError(setting + ' exceeds 8192 bytes') if not raw.strip(): return () ids = [] @@ -141,13 +141,21 @@ def _checkout_repo_ids(): if str(uuid.UUID(value)) != value: raise ValueError('noncanonical UUID') except (ValueError, AttributeError): - raise ValueError('CF_CHECKOUT_REPOS requires canonical Repo UUIDs') + raise ValueError(setting + ' requires canonical Repo UUIDs') if value in ids: - raise ValueError('CF_CHECKOUT_REPOS contains a duplicate Repo UUID') + raise ValueError(setting + ' contains a duplicate Repo UUID') ids.append(value) return tuple(ids) +def _checkout_repo_ids(): + return _repo_ids('CF_CHECKOUT_REPOS') + + +def _protection_repo_ids(): + return _repo_ids('CF_PROTECTION_REPOS') + + def _replace_block(path, begin, end, body): """Rewrite the region between `begin` and `end`, appending it if absent. @@ -849,6 +857,7 @@ def _seafile_conf_cloudfile_lines(): lines.append('%s = %s\n' % (key, 'true' if cf_enabled(name) else 'false')) lines.append('checkout_repo_ids = %s\n' % ','.join(_checkout_repo_ids())) + lines.append('protection_repo_ids = %s\n' % ','.join(_protection_repo_ids())) if cf_enabled('CF_ENABLE_FILE_LOCK'): backend = get_conf('CF_LOCK_BACKEND', 'cloudfile').lower() diff --git a/scripts/scripts_cf14.0/cloudfile_schema.py b/scripts/scripts_cf14.0/cloudfile_schema.py index 67d0c850..4a6a510c 100644 --- a/scripts/scripts_cf14.0/cloudfile_schema.py +++ b/scripts/scripts_cf14.0/cloudfile_schema.py @@ -4,16 +4,19 @@ import sys from pathlib import Path -# Exactly five V2 extension tables; CE native tables remain independent. +# Exactly six V2 extension tables; CE native tables remain independent. # Table existence alone previously enabled an incompatible Guard on every upload. COLUMNS = { 'cf_library_storage': 'repo_key repo_id state', 'cf_sso_group_map': 'provider subject_type namespace external_id group_id', 'cf_dir_acl': 'repo_id path_hash path subject_type provider namespace external_id permission inherit share_mode revision', 'cf_edit_guard': 'repo_id path_hash path guard_id generation owner_uid owner_native_user terminal_type terminal_name checkout_ip proof_digest base_file_id lease_expires_at created_at updated_at', + 'cf_file_protection': 'repo_id path_hash path file_id protected_by protected_at', 'cf_audit_event': 'id repo_id object_type object_id operation operator source before after source_path target_path path_hash commit_id result failure_reason occurred_at', } INDEXES = { + 'cf_file_protection': {'PRIMARY': (0, ('repo_id','path_hash')), + 'cf_file_protection_prefix': (1, ('repo_id','path'))}, 'cf_library_storage': {'PRIMARY': (0, ('repo_key',)), 'library_storage_repo': (0, ('repo_id',))}, 'cf_sso_group_map': {'PRIMARY': (0, ('provider','subject_type','namespace','external_id')), 'sso_native_group': (0, ('group_id',))}, 'cf_dir_acl': {'PRIMARY': (0, ('repo_id','path_hash','subject_type','provider','namespace','external_id')), @@ -30,7 +33,7 @@ def verify_v2_schema(connection, checkout_enabled=False): """Check the installed core contract without CREATE, ALTER, DML or repair. This is a startup gate, not a replacement for release SQL/data validation. - All five tables are installed in every new V2 deployment. Checkout runtime + All six tables are installed in every new V2 deployment. Checkout runtime activation is independent from the existence of the Guard table. """ with connection.cursor() as cursor: @@ -50,7 +53,7 @@ def verify_v2_schema(connection, checkout_enabled=False): columns = {name: (kind, length) for name, kind, length in cursor.fetchall()} if set(columns) != set(names.split()): raise ValueError('core column layout mismatch') - if table in ('cf_dir_acl', 'cf_edit_guard') and columns['path_hash'] != ('binary', 32): + if table in ('cf_dir_acl', 'cf_edit_guard', 'cf_file_protection') and columns['path_hash'] != ('binary', 32): raise ValueError('core path hash must be BINARY(32)') if table == 'cf_audit_event' and columns['path_hash'] != ('binary', 32): raise ValueError('audit path hash must be BINARY(32)') @@ -62,7 +65,7 @@ def verify_v2_schema(connection, checkout_enabled=False): indexes = {} for name, non_unique, sequence, column, prefix in cursor.fetchall(): unique, parts = indexes.setdefault(name, (non_unique, [])) - if prefix is not None or unique != non_unique or sequence != len(parts) + 1: + if prefix != (191 if table == 'cf_file_protection' and name == 'cf_file_protection_prefix' and column == 'path' else None) or unique != non_unique or sequence != len(parts) + 1: raise ValueError('core index contract mismatch') parts.append(column) actual = {name: (unique, tuple(parts)) for name, (unique, parts) in indexes.items()} @@ -98,7 +101,7 @@ def _connect(environment): def inspect_v2_schema(connection, checkout_enabled=False): """Classify an installed database without writes, migrations or failures. - Inspects current five-table structure without writes. No legacy + Inspects current six-table structure without writes. No legacy layout recognition, fallback, upgrade or repair is performed. """ report = { @@ -132,7 +135,7 @@ def _classify_table(cursor, table, columns, expected_names): defects = [] if set(columns) != set(expected_names.split()): defects.append('columns') - if table in ('cf_dir_acl', 'cf_edit_guard') and columns.get('path_hash') != ('binary', 32): + if table in ('cf_dir_acl', 'cf_edit_guard', 'cf_file_protection') and columns.get('path_hash') != ('binary', 32): defects.append('path_hash') if table == 'cf_audit_event' and columns.get('path_hash') != ('binary', 32): defects.append('path_hash') @@ -148,7 +151,7 @@ def _classify_table(cursor, table, columns, expected_names): indexes = {} for name, non_unique, sequence, column, prefix in cursor.fetchall(): unique, parts = indexes.setdefault(name, (non_unique, [])) - if prefix is not None or unique != non_unique or sequence != len(parts) + 1: + if prefix != (191 if table == 'cf_file_protection' and name == 'cf_file_protection_prefix' and column == 'path' else None) or unique != non_unique or sequence != len(parts) + 1: defects.append('index_shape') continue parts.append(column) @@ -173,7 +176,7 @@ def _overall_status(report, required): def prepare_fresh_schema(shared_dir, environment=None): - """Mark a genuinely new Seafile volume for one-time five-table setup.""" + """Mark a genuinely new Seafile volume for one-time six-table setup.""" shared_dir = Path(shared_dir) marker = shared_dir / MARKER_NAME if marker.exists() or (shared_dir / 'seafile-data').exists(): @@ -205,7 +208,7 @@ def _fresh_plan(marker): def initialize_fresh_schema(marker, installdir, environment=None): """Create the reviewed V2 tables once for a new volume. - Install exactly five tables only on a new Seafile volume. No legacy + Install exactly six tables only on a new Seafile volume. No legacy layouts are recognized, upgraded or migrated. The marker is removed only after verified installation; a failed attempt remains available for retry. """ @@ -219,13 +222,14 @@ def initialize_fresh_schema(marker, installdir, environment=None): ddl = (sql_dir / 'cloudfile-v2.sql').read_text() audit_ddl = (sql_dir / 'cloudfile-v2-audit.sql').read_text() edit_ddl = (sql_dir / 'cloudfile-v2-edit.sql').read_text() + protection_ddl = (sql_dir / 'cloudfile-v2-protection.sql').read_text() sys.path.insert(0, str(Path(installdir) / 'seahub')) try: from cloudfile_ext.v2.schema import FreshSchema finally: sys.path.pop(0) connection = _connect(environment or os.environ) - FreshSchema(connection, ddl, edit_ddl=edit_ddl, audit_ddl=audit_ddl).install() + FreshSchema(connection, ddl, edit_ddl=edit_ddl, audit_ddl=audit_ddl, protection_ddl=protection_ddl).install() marker.unlink() return True except Exception: @@ -246,7 +250,7 @@ def verify_development_schema(installdir=None, environment=None): verify_v2_schema(connection, checkout_enabled=_checkout_enabled(environment)) except Exception: # No historical schema upgrade or auto-repair in current V2. - raise RuntimeError('CloudFile V2 five-table schema mismatch; stop writers and recreate the DEV extension schema before starting services') from None + raise RuntimeError('CloudFile V2 six-table schema mismatch; stop writers and run the reviewed protection migration or inspect schema drift before starting services') from None finally: if connection is not None: connection.close() diff --git a/tests/test_checkout_repo_config.py b/tests/test_checkout_repo_config.py index a3f67a27..990baaa0 100644 --- a/tests/test_checkout_repo_config.py +++ b/tests/test_checkout_repo_config.py @@ -9,7 +9,7 @@ SOURCE = Path(__file__).resolve().parents[1] / 'scripts/scripts_cf14.0/cloudfile_bootstrap.py' TREE = ast.parse(SOURCE.read_text()) -METHODS = {'_checkout_repo_ids', '_seafile_conf_cloudfile_lines'} +METHODS = {'_repo_ids', '_protection_repo_ids', '_checkout_repo_ids', '_seafile_conf_cloudfile_lines'} FUNCTIONS = [node for node in TREE.body if isinstance(node, ast.FunctionDef) and node.name in METHODS] @@ -52,6 +52,18 @@ def test_invalid_lists_rejected_before_config_write(self): with self.subTest(value=value[:40]), self.assertRaises(ValueError): self.namespace['_checkout_repo_ids']() + def test_protection_scope_is_independent_of_checkout(self): + repo = '11111111-1111-4111-8111-111111111111' + self.env['CF_PROTECTION_REPOS'] = repo + rendered = ''.join(self.namespace['_seafile_conf_cloudfile_lines']()) + self.assertIn('protection_repo_ids = ' + repo + '\n', rendered) + self.assertIn('checkout_enabled = false\n', rendered) + self.assertEqual(self.namespace['_checkout_repo_ids'](), ()) + for value in ('invalid', repo + ',' + repo, repo + ','): + self.env['CF_PROTECTION_REPOS'] = value + with self.assertRaises(ValueError): + self.namespace['_protection_repo_ids']() + if __name__ == '__main__': unittest.main() diff --git a/tests/test_fresh_schema.py b/tests/test_fresh_schema.py index 7a51e380..b8ec791d 100644 --- a/tests/test_fresh_schema.py +++ b/tests/test_fresh_schema.py @@ -35,7 +35,7 @@ def execute(self, sql, args=()): if self.defect == 'text_hash' and table == 'cf_dir_acl': self.rows = tuple((name, 'char', 64) if name == 'path_hash' else (name, kind, length) for name, kind, length in self.rows) else: - self.rows = tuple((name, unique, i+1, column, None) + self.rows = tuple((name, unique, i+1, column, 191 if table == 'cf_file_protection' and name == 'cf_file_protection_prefix' and column == 'path' else None) for name, (unique, columns) in SCHEMA.INDEXES[table].items() for i, column in enumerate(columns)) if self.defect == 'missing_index' and table == 'cf_edit_guard': self.rows = tuple(row for row in self.rows if row[0] != 'cf_edit_guard_active') @@ -47,7 +47,7 @@ def test_correct_contract_issues_only_selects(self): cursor = ReadOnlyCursor() connection = Mock(); connection.cursor.return_value = cursor SCHEMA.verify_v2_schema(connection) - self.assertEqual(len(cursor.calls), 16) + self.assertEqual(len(cursor.calls), 19) connection.commit.assert_not_called() connection.rollback.assert_not_called() @@ -57,7 +57,7 @@ def test_old_layout_hash_and_missing_index_fail_without_repair(self): with self.assertRaises(ValueError): SCHEMA.verify_v2_schema(connection, checkout_enabled=True) connection.commit.assert_not_called() - def test_all_five_tables_are_required_even_when_checkout_is_off(self): + def test_all_six_tables_are_required_even_when_checkout_is_off(self): for defect in ('old_guard', 'missing_index'): connection = Mock() connection.cursor.return_value = ReadOnlyCursor(defect) @@ -69,7 +69,7 @@ def test_connection_failure_is_sanitized_and_requires_sql(self): env = dict(SEAFILE_MYSQL_DB_HOST='db', SEAFILE_MYSQL_DB_PASSWORD='fixture') with patch.dict(sys.modules, {'pymysql': driver}): with self.assertRaises(RuntimeError) as error: SCHEMA.verify_development_schema(environment=env) - self.assertIn('five-table', str(error.exception)); self.assertNotIn('private-fixture-value', str(error.exception)) + self.assertIn('six-table', str(error.exception)); self.assertNotIn('private-fixture-value', str(error.exception)) def test_startup_initializes_fresh_volume_without_legacy_runner(self): bootstrap = ast.parse((ROOT/'scripts/scripts_cf14.0/cloudfile_bootstrap.py').read_text()) @@ -99,7 +99,8 @@ class FakeFreshSchema: calls = [] fail = False - def __init__(self, connection, ddl, *, edit_ddl=None, audit_ddl=None): + def __init__(self, connection, ddl, *, edit_ddl=None, audit_ddl=None, protection_ddl=None): + self.protection_ddl = protection_ddl self.ddl, self.edit_ddl, self.audit_ddl = ddl, edit_ddl, audit_ddl FreshInstallTest.FakeFreshSchema.calls.append(self) @@ -116,6 +117,7 @@ def _installdir(self, root): sql = installdir / 'sql' / 'mysql' sql.mkdir(parents=True, exist_ok=True) (sql / 'cloudfile-v2.sql').write_text('-- reviewed base DDL') + (sql / 'cloudfile-v2-protection.sql').write_text('-- reviewed protection DDL') (sql / 'cloudfile-v2-edit.sql').write_text('-- reviewed Guard DDL') (sql / 'cloudfile-v2-audit.sql').write_text('-- reviewed operation audit DDL') (installdir / 'seahub').mkdir(exist_ok=True) @@ -163,7 +165,7 @@ def test_fresh_volume_installs_reviewed_ddl_once(self): self.assertIsNotNone(FreshInstallTest.FakeFreshSchema.calls[0].audit_ddl) connection.close.assert_called_once() - def test_checkout_toggle_does_not_change_five_table_install(self): + def test_checkout_toggle_does_not_change_six_table_install(self): with tempfile.TemporaryDirectory() as root: shared = Path(root) / 'shared' shared.mkdir() @@ -181,7 +183,7 @@ def test_failed_install_keeps_marker_and_retry_uses_the_original_plan(self): with self.assertRaises(RuntimeError) as error: self._init(root, marker, 'false') self.assertTrue(marker.exists()) - # Changing a runtime feature switch never changes the fresh five-table schema. + # Changing a runtime feature switch never changes the fresh six-table schema. FreshInstallTest.FakeFreshSchema.fail = False result, _ = self._init(root, marker, 'true') self.assertTrue(result) diff --git a/tests/test_protection_migration.py b/tests/test_protection_migration.py new file mode 100644 index 00000000..a837aa16 --- /dev/null +++ b/tests/test_protection_migration.py @@ -0,0 +1,55 @@ +"""Migration refuses partial/drifted schemas and never changes existing data.""" +import contextlib +import importlib.util +from pathlib import Path +import sys +from types import ModuleType +import unittest +from unittest.mock import MagicMock, patch + +SPEC = importlib.util.spec_from_file_location('migration', Path(__file__).resolve().parents[1] / 'tools/migrate/file-protection-v1.py') +MIGRATION = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MIGRATION) + + +class MigrationTests(unittest.TestCase): + def setUp(self): + self.module = ModuleType('cloudfile_ext.v2.schema') + self.module.database_lock = lambda *args: contextlib.nullcontext() + self.module.SchemaError = ValueError + self.module.PROTECTION_TABLES = frozenset({'cf_file_protection'}) + self.schema = MagicMock() + self.schema.tables = frozenset({'cf_library_storage', 'cf_sso_group_map', 'cf_dir_acl', 'cf_edit_guard', 'cf_audit_event', 'cf_file_protection'}) + self.schema._tables.return_value = self.schema.tables - self.module.PROTECTION_TABLES + self.schema.ddl = {'cf_file_protection': 'CREATE TABLE cf_file_protection reviewed'} + self.cursor = self.schema.connection.cursor.return_value.__enter__.return_value + + def run_migration(self, apply=False): + with patch.dict(sys.modules, {'cloudfile_ext.v2.schema': self.module}): + return MIGRATION.migrate(self.schema, apply=apply) + + def test_plan_does_not_create_table(self): + self.assertIn('would create', self.run_migration()) + self.cursor.execute.assert_not_called() + self.assertEqual(self.schema._verify_one.call_count, 5) + + def test_apply_creates_only_protection_and_verifies(self): + self.run_migration(True) + self.cursor.execute.assert_called_once_with(self.schema.ddl['cf_file_protection']) + self.schema.verify.assert_called_once() + + def test_repeat_is_noop(self): + self.schema._tables.return_value = self.schema.tables + self.assertEqual(self.run_migration(True), 'already current') + self.cursor.execute.assert_not_called() + + def test_partial_extra_or_drifted_schema_cannot_create(self): + for present in (set(), self.schema.tables - {'cf_edit_guard'}, self.schema.tables | {'cf_resource'}): + self.schema._tables.return_value = present + with self.assertRaises(ValueError): + self.run_migration(True) + self.schema._tables.return_value = self.schema.tables - self.module.PROTECTION_TABLES + self.schema._verify_one.side_effect = ValueError('drift') + with self.assertRaises(ValueError): + self.run_migration(True) + self.cursor.execute.assert_not_called() diff --git a/tests/test_v2_schema_inventory.py b/tests/test_v2_schema_inventory.py index 700ca7f5..88d1f3ce 100644 --- a/tests/test_v2_schema_inventory.py +++ b/tests/test_v2_schema_inventory.py @@ -59,7 +59,7 @@ def execute(self, sql, args=()): self.rows = (('InnoDB', 'utf8mb4_bin'),) else: self.rows = tuple( - (name, unique, index + 1, column, None) + (name, unique, index + 1, column, 191 if table == 'cf_file_protection' and name == 'cf_file_protection_prefix' and column == 'path' else None) for name, (unique, columns) in SCHEMA.INDEXES[table].items() for index, column in enumerate(columns)) return diff --git a/tools/gates/check-sql-contracts.py b/tools/gates/check-sql-contracts.py index cd2b6f00..3cc45d9c 100644 --- a/tools/gates/check-sql-contracts.py +++ b/tools/gates/check-sql-contracts.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Fast, read-only V2 4+1 table dependency gate. +"""Fast, read-only V2 six-table table dependency gate. No historical migrations, no schema checksum ledger, no Docker/DB access. Check only code that actually ships in current V2 runtime; inert historical @@ -11,9 +11,9 @@ TABLES = frozenset({ 'cf_library_storage', 'cf_sso_group_map', 'cf_dir_acl', - 'cf_edit_guard', 'cf_audit_event', + 'cf_edit_guard', 'cf_audit_event', 'cf_file_protection', }) -DDL = ('cloudfile-v2.sql', 'cloudfile-v2-edit.sql', 'cloudfile-v2-audit.sql') +DDL = ('cloudfile-v2.sql', 'cloudfile-v2-edit.sql', 'cloudfile-v2-audit.sql', 'cloudfile-v2-protection.sql') SQL_TABLE = re.compile( r'\b(?:FROM|JOIN|INTO|UPDATE|TABLE|REFERENCES)\s+[`"]?(cf_[a-z0-9_]+)', ) @@ -29,7 +29,7 @@ def validate(server, hub, docker, agent=None): raise ValueError('missing or duplicate DDL: ' + name) observed.update(matches) if observed != TABLES: - raise ValueError('V2 DDL differs from 4+1: ' + str(sorted(observed ^ TABLES))) + raise ValueError('V2 DDL differs from six-table: ' + str(sorted(observed ^ TABLES))) if (sql_dir / 'cloudfile.sql').exists(): raise ValueError('retired CloudFile schema re-entered Server installation') if (hub / 'cloudfile_extensions/schema').exists(): @@ -59,7 +59,7 @@ def validate(server, hub, docker, agent=None): source = path.read_text() if '/api/v2.1/cloudfile/agent-sessions/claim/' in source: raise ValueError('Agent2 legacy SQL Session HTTP client: ' + path.name) - print('PASS current V2 4+1 DDL and active SQL dependencies') + print('PASS current V2 six-table DDL and active SQL dependencies') def main(): diff --git a/tools/gates/test-bootstrap-settings.py b/tools/gates/test-bootstrap-settings.py index 5d59a43e..0d79c75f 100755 --- a/tools/gates/test-bootstrap-settings.py +++ b/tools/gates/test-bootstrap-settings.py @@ -88,7 +88,7 @@ def load(func_name, env, extra=None): # Include the real Checkout parser required by the generated server config. ns['uuid'] = uuid helpers = [item for item in tree.body - if isinstance(item, ast.FunctionDef) and item.name == '_checkout_repo_ids'] + if isinstance(item, ast.FunctionDef) and item.name in ('_repo_ids', '_checkout_repo_ids', '_protection_repo_ids')] exec(compile(ast.Module(body=helpers, type_ignores=[]), BOOTSTRAP, 'exec'), ns) ns.update(extra or {}) exec(compile(ast.Module(body=[node], type_ignores=[]), BOOTSTRAP, 'exec'), ns) diff --git a/tools/migrate/file-protection-v1.py b/tools/migrate/file-protection-v1.py new file mode 100644 index 00000000..b9d15125 --- /dev/null +++ b/tools/migrate/file-protection-v1.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Explicit, additive five-to-six-table migration; never called by startup.""" +import argparse +import os +from pathlib import Path +import sys + + +def migrate(schema, *, apply=False): + from cloudfile_ext.v2.schema import database_lock, SchemaError, PROTECTION_TABLES + with database_lock(schema.connection, 'schema'): + with schema.connection.cursor() as cursor: + present = schema._tables(cursor) + if present not in (schema.tables, schema.tables - PROTECTION_TABLES): + raise SchemaError('requires the exact reviewed five- or six-table schema') + for name in sorted(present): + schema._verify_one(cursor, name) + if present == schema.tables: + return 'already current' + if not apply: + return 'ready: would create cf_file_protection only' + cursor.execute(schema.ddl['cf_file_protection']) + schema.verify() + return 'created and verified cf_file_protection' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--installdir', type=Path, required=True) + parser.add_argument('--apply', action='store_true') + parser.add_argument('--writers-stopped', action='store_true', + help='operator assertion: all Server/Hub/worker writers are stopped') + args = parser.parse_args() + if args.apply and not args.writers_stopped: + parser.error('--apply requires --writers-stopped') + sys.path.insert(0, str(args.installdir / 'seahub')) + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'scripts/scripts_cf14.0')) + from cloudfile_ext.v2.schema import FreshSchema + from cloudfile_schema import _connect + connection = None + try: + sql = args.installdir / 'sql/mysql' + connection = _connect(os.environ) + schema = FreshSchema(connection, (sql / 'cloudfile-v2.sql').read_text(), + edit_ddl=(sql / 'cloudfile-v2-edit.sql').read_text(), + audit_ddl=(sql / 'cloudfile-v2-audit.sql').read_text(), + protection_ddl=(sql / 'cloudfile-v2-protection.sql').read_text()) + print(migrate(schema, apply=args.apply)) + except Exception: + print('Protection migration failed; inspect schema and keep writers stopped. No rollback or deletion attempted.', file=sys.stderr) + return 1 + finally: + if connection is not None: + connection.close() + return 0 + + +if __name__ == '__main__': + sys.exit(main()) From bc79da247978eccf9de7fd5d8ac83062c99e4c6f Mon Sep 17 00:00:00 2001 From: dev9-bb Date: Fri, 13 Nov 2026 14:58:44 +0800 Subject: [PATCH 2/2] test: add disposable native file protection acceptance probe --- docs/file-protection-v1.md | 22 +++ tests/e2e/full/file_protection_native.py | 183 +++++++++++++++++++++++ 2 files changed, 205 insertions(+) create mode 100644 tests/e2e/full/file_protection_native.py diff --git a/docs/file-protection-v1.md b/docs/file-protection-v1.md index f8bdc847..baf0efc8 100644 --- a/docs/file-protection-v1.md +++ b/docs/file-protection-v1.md @@ -45,3 +45,25 @@ bash build/cloudfile_14.0/build-in-docker.sh 14.0.8-protection-v1-test - 覆盖、历史恢复、父目录删除/移动/改名、旧 Agent2 票据均拒绝;读取和复制到新路径可用,副本可编辑。 - 普通库零 Protection SQL;选定库大批量提交基准和 SQL 故障拒绝。 - Etech 真实用户 Web/API/Agent2 验收另行完成;DEV/PROD 不在本次修改范围。 + +## 2026-11-13 隔离验证结果 + +以下为本机 Linux ARM64 + 临时 MariaDB 11.4 验证,不是 DEV/PROD 或 Etech 真实身份验收。 + +| 构建输入 | 固定 SHA | +| --- | --- | +| Server | `88a95ac9e9f5c8612d3d3027fa6b558789a00237` | +| Hub | `c0f37682e653c2264d393522df2ddc58f40a6dc0` | +| Docker 运行配方 | `e4be0e173dc7fe01f855a952a502d086bdbe63de` | + +完整 C/Go/Web 编译、发行包校验、本地应用镜像组装通过;收据中的 local_storage、objstore 专项通过。本地镜像 `cloudfile/cloudfile:14.0.8-protection-v1-test`,ARM64 image config ID 为 `sha256:b7f1a8feeab9794357abe83a99a51b78381ca6dcf5f54a3a0e58fab635e9f95a`。未推送 Registry,这不是远端 manifest digest。后续探针与本文记录提交不改变该镜像的运行配方 SHA。 + +- Docker 30 项定向 Python 检查、bootstrap 设置检查、六表跨仓 SQL 契约通过;Hub 5 项保护单测及 1 项 Schema 序列值回归通过;Server 独立 cf-lock 夹具修复后通过。 +- 真实 MariaDB 验证六表新装、五表启动/自动新装拒绝、显式升级、重复执行、前缀索引漂移拒绝。审计表已有数据时的自增序列比较误判已修复。 +- Hub 真实 SQL 验证定版、批量状态、幂等、解除和审计失败原子回滚;Go 最终屏障与 Hub HEAD CAS 分别验证两种竞争顺序,均观察到实际 Branch 行锁等待。此组 SQL 探针的身份/原生元数据是测试替身,不代表完整并发上传验收。 +- `tests/e2e/full/file_protection_native.py` 直接使用匹配发行包的 C/Go/Hub 与随机临时数据库:16 项原生场景通过,包括真实定版、原件读取、旧独占票据 Checkout 拒绝、旧普通编辑票据发布拒绝、C 覆盖/删除/移动/改名/父目录删除改名/文件及整库历史恢复拒绝、整库删除拒绝,以及副本可编辑/恢复/改名/移动/删除。解除后同一普通编辑票据可成功发布,C 写入恢复。 +- 原生探针复用真实 ACL 计算与 CE 用户,仅以测试 `native-local` 主体和管理员对象替代登录/SSO;旧票据由测试密钥按真实协议签发,不是实际 Agent2 客户端操作。 + +原生探针必须在一次性容器中运行,显式设置 `CF_TEST_FILE_PROTECTION=1` 与 `CF_NATIVE_TEST_PACKAGE`;数据库主机 `db`、root 密码 `isolated-protection-test` 仅用于独立测试网络,不暴露宿主端口,不挂载业务卷。探针创建随机数据库并在 finally 清理,不能指向 DEV/PROD;Python 不允许 `-O`。`PYTHONPATH` 使用发行包的 `seahub`、`seahub/thirdpart`、`seafile/lib/python3/site-packages`,`LD_LIBRARY_PATH` 指向 `seafile/lib`。 + +仍未完成:Etech UI/真实用户集成、浏览器 Web/API 与实际 Agent2 客户端验收、WebDAV/同步入口矩阵、跨库/虚拟库边界完整验收、真实上传双向竞争、受保护大库性能基准及 AMD64 发布验收。因此三仓保持 Draft,不合并、不部署。 diff --git a/tests/e2e/full/file_protection_native.py b/tests/e2e/full/file_protection_native.py new file mode 100644 index 00000000..34539705 --- /dev/null +++ b/tests/e2e/full/file_protection_native.py @@ -0,0 +1,183 @@ +"""Disposable native protection probe. Identity is a test adapter, not SSO acceptance.""" +import json, os, re, subprocess, sys, tempfile, time +from pathlib import Path +from uuid import uuid4 + +ROOT = PKG = None +OWNER='owner@protection.test' + +def phase(): + from seaserv import seafile_api as api, ccnet_api + statefile=ROOT/'state.json' + local=ROOT/'input'; local.write_bytes(b'protected original content') + if sys.argv[-1]=='init': + assert ccnet_api.add_emailuser(OWNER,'!',0,1)==0 + repo=api.create_repo('isolated protection','',OWNER) + assert api.post_dir(repo,'/','design',OWNER)==0 + assert api.post_file(repo,str(local),'/design','original.prt',OWNER)==0 + old_head=api.get_repo(repo).head_cmmt_id + local.write_bytes(b'finalized original content') + assert api.put_file(repo,str(local),'/design','original.prt',OWNER,None) + statefile.write_text(json.dumps({'repo':repo,'file':api.get_file_id_by_path(repo,'/design/original.prt'),'head':api.get_repo(repo).head_cmmt_id,'old_head':old_head})) + return + state=json.loads(statefile.read_text()); repo=state['repo']; checks=[] + import django + django.setup() + from django.conf import settings + settings.CF_ACL_CACHE_TTL=0 + from cloudfile_ext.v2 import file_protection as p + from cloudfile_ext.v2.acl_runtime import Authority + from cloudfile_ext.v2.acl_policy import Principal + from cloudfile_ext.v2.acl_store import ACLStore + from django.db import connection, transaction + from unittest.mock import patch + from types import SimpleNamespace + def authority(username): + return Authority(username,principal=Principal('native-local',username,frozenset()),rules=ACLStore(connection,os.environ['SEAFILE_MYSQL_DB_SEAFILE_DB_NAME'],transaction.atomic),api=api) + admin=SimpleNamespace(username=OWNER,is_active=True,is_staff=True,admin_permissions=SimpleNamespace(can_manage_library=lambda:True)) + body={'repo_id':repo,'path':'/design/original.prt','expected_file_id':state['file']} + import jwt, requests, hashlib + def ticket(mode): + now=int(time.time()) + return jwt.encode({'uid':'test-owner','sub':OWNER,'repo_id':repo,'path':body['path'],'file_id':state['file'],'mode':mode,'iss':'cloudfile-v2-edit','aud':'cloudfile-edit-agent','iat':now-60,'exp':now+600},os.environ['JWT_PRIVATE_KEY'],algorithm='HS256') + old_optimistic, old_exclusive, read_ticket = ticket('optimistic-edit'), ticket('exclusive-edit'), ticket('local-view') + with patch.object(p,'Authority',side_effect=authority): + response=p._state_change(admin,body,True) + assert response.status_code==200,response.data + checks.append('Hub protect with real native file/head and MariaDB audit') + baseurl='http://127.0.0.1:8082/cf-edit/v1/' + response=requests.get(baseurl+'read',headers={'Authorization':'Bearer '+read_ticket},timeout=15) + assert response.status_code==200 and response.content==b'finalized original content',(response.status_code,response.text) + checks.append('Go scoped read of protected original allowed') + response=requests.post(baseurl+'checkout',headers={'Authorization':'Bearer '+old_exclusive},json={'base_file_id':state['file'],'terminal_type':'linux','terminal_name':'isolated fixture'},timeout=15) + assert response.status_code==423 and response.json()['code']=='FILE_PROTECTED',(response.status_code,response.text) + checks.append('Pre-issued exclusive Agent ticket checkout denied with FILE_PROTECTED') + content=b'old ticket publish must fail' + response=requests.post(baseurl+'publish',headers={'Authorization':'Bearer '+old_optimistic,'X-CF-Action':'optimistic','X-CF-Base-ID':state['file'],'X-CF-SHA256':hashlib.sha256(content).hexdigest()},data=content,timeout=15) + assert response.status_code==423 and response.json()['code']=='FILE_PROTECTED',(response.status_code,response.text) + checks.append('Pre-issued optimistic Agent ticket full publish denied with FILE_PROTECTED') + baseline=api.get_repo(repo).head_cmmt_id + def denied(label,action): + try:action() + except Exception:pass + assert api.get_repo(repo).head_cmmt_id==baseline,label+' changed Branch' + assert api.get_file_id_by_path(repo,'/design/original.prt')==state['file'],label+' changed original' + checks.append(label) + local.write_bytes(b'new content must be rejected') + denied('C overwrite denied',lambda:api.put_file(repo,str(local),'/design','original.prt',OWNER,None)) + denied('C historical file restore denied',lambda:api.revert_file(repo,state['old_head'],'/design/original.prt',OWNER)) + denied('C historical repo restore denied',lambda:api.revert_repo(repo,state['old_head'],OWNER)) + denied('C original delete denied',lambda:api.del_file(repo,'/design',json.dumps(['original.prt']),OWNER)) + denied('C parent delete denied',lambda:api.del_file(repo,'/',json.dumps(['design']),OWNER)) + denied('C parent rename denied',lambda:api.rename_file(repo,'/','design','renamed',OWNER)) + denied('C original rename denied',lambda:api.rename_file(repo,'/design','original.prt','renamed.prt',OWNER)) + api.copy_file(repo,'/design',json.dumps(['original.prt']),repo,'/design',json.dumps(['copy.prt']),OWNER,0,synchronous=0) + assert api.get_file_id_by_path(repo,'/design/copy.prt')==state['file'] + copy_head=api.get_repo(repo).head_cmmt_id + assert api.put_file(repo,str(local),'/design','copy.prt',OWNER,None) + assert api.get_file_id_by_path(repo,'/design/copy.prt')!=state['file'] + assert p.read_batch(repo,['/design/original.prt','/design/copy.prt'])=={'/design/original.prt':state['file']} + assert api.revert_file(repo,copy_head,'/design/copy.prt',OWNER)==0 + assert api.get_file_id_by_path(repo,'/design/copy.prt')==state['file'] + assert api.rename_file(repo,'/design','copy.prt','renamed-copy.prt',OWNER)==0 + api.move_file(repo,'/design',json.dumps(['renamed-copy.prt']),repo,'/',json.dumps(['moved-copy.prt']),0,OWNER,0,synchronous=0) + assert api.get_file_id_by_path(repo,'/moved-copy.prt')==state['file'] + assert api.del_file(repo,'/',json.dumps(['moved-copy.prt']),OWNER)==0 + assert not api.get_file_id_by_path(repo,'/moved-copy.prt') + assert api.post_dir(repo,'/','unprotected-dir',OWNER)==0 + assert api.rename_file(repo,'/','unprotected-dir','renamed-dir',OWNER)==0 + assert api.del_file(repo,'/',json.dumps(['renamed-dir']),OWNER)==0 + checks.append('C copy editable/restorable/renamable/movable/deletable; unprotected parent operations allowed') + baseline=api.get_repo(repo).head_cmmt_id + denied('C original move denied',lambda:api.move_file(repo,'/design',json.dumps(['original.prt']),repo,'/',json.dumps(['moved.prt']),0,OWNER,0,synchronous=0)) + # Entire repo deletion is blocked by configured scope, even after unprotect. + try:api.remove_repo(repo) + except Exception:pass + assert api.get_repo(repo) is not None + checks.append('C whole repo delete denied') + response=p._state_change(admin,body,False); assert response.status_code==200,response.data + response=requests.post(baseurl+'publish',headers={'Authorization':'Bearer '+old_optimistic,'X-CF-Action':'optimistic','X-CF-Base-ID':state['file'],'X-CF-SHA256':hashlib.sha256(content).hexdigest()},data=content,timeout=15) + assert response.status_code==200,(response.status_code,response.text) + checks.append('Same optimistic ticket publishes successfully after unprotect') + assert api.put_file(repo,str(local),'/design','original.prt',OWNER,None) + checks.append('Hub unprotect restores native write') + print(json.dumps({'passed':checks,'identity':'test native-local principal/admin; not Etech/SSO'},indent=2)) + +def run(): + if not __debug__: + raise SystemExit('Do not disable probe assertions with python -O') + global ROOT, PKG + if os.environ.get('CF_TEST_FILE_PROTECTION') != '1': + raise SystemExit('Requires CF_TEST_FILE_PROTECTION=1 and a disposable db host; never use a deployed database') + PKG = Path(os.environ['CF_NATIVE_TEST_PACKAGE']) + if len(sys.argv) > 1: + if sys.argv[-1] not in ('init', 'test'): + raise SystemExit('unknown probe phase') + ROOT = Path(os.environ['CF_NATIVE_TEST_ROOT']) + else: + ROOT = Path(tempfile.mkdtemp(prefix='cf-protection-native-')) + os.environ['CF_NATIVE_TEST_ROOT'] = str(ROOT) + if len(sys.argv)>1: + phase(); return + + import pymysql + admin=pymysql.connect(host='db',user='root',password='isolated-protection-test',autocommit=True,charset='utf8mb4') + schemas={k:'protection_native_'+uuid4().hex for k in ('account','files')} + process=None + go_process=None + try: + with admin.cursor() as c: + for kind,name in schemas.items(): + c.execute('CREATE DATABASE '+name); c.execute('USE '+name) + for statement in re.findall(r'CREATE TABLE[\s\S]+?;', (PKG/'sql/mysql'/('ccnet.sql' if kind=='account' else 'seafile.sql')).read_text()):c.execute(statement) + from cloudfile_ext.v2.schema import FreshSchema + admin.select_db(schemas['files']); sql=PKG/'sql/mysql' + FreshSchema(admin,(sql/'cloudfile-v2.sql').read_text(),edit_ddl=(sql/'cloudfile-v2-edit.sql').read_text(),audit_ddl=(sql/'cloudfile-v2-audit.sql').read_text(),protection_ddl=(sql/'cloudfile-v2-protection.sql').read_text()).install() + for name in ('conf','data','ccnet'): (ROOT/name).mkdir(parents=True,exist_ok=True) + config=f'''[database] + type=mysql + host=db + user=root + password=isolated-protection-test + db_name={schemas['files']} + ccnet_db_name={schemas['account']} + connection_charset=utf8mb4 + [fileserver] + use_go_fileserver=true + port=8082 + [cloudfile] + ''' + (ROOT/'conf/seafile.conf').write_text(config) + os.environ.update(SEAFILE_DATA_DIR=str(ROOT/'data'),SEAFILE_CENTRAL_CONF_DIR=str(ROOT/'conf'),SEAHUB_LOG_DIR=str(ROOT),SEAFILE_MYSQL_DB_HOST='db',SEAFILE_MYSQL_DB_USER='root',SEAFILE_MYSQL_DB_PASSWORD='isolated-protection-test',SEAFILE_MYSQL_DB_CCNET_DB_NAME=schemas['account'],SEAFILE_MYSQL_DB_SEAFILE_DB_NAME=schemas['files'],SEAFILE_MYSQL_DB_SEAHUB_DB_NAME=schemas['files'],DJANGO_SETTINGS_MODULE='seahub.settings',JWT_PRIVATE_KEY='isolated-native-protection-key-1234567890') + def start(): + nonlocal process + process=subprocess.Popen([str(PKG/'seafile/bin/seaf-server'),'-F',str(ROOT/'conf'),'-c',str(ROOT/'ccnet'),'-d',str(ROOT/'data'),'-l',str(ROOT/'native.log'),'-f'],stdout=(ROOT/'stderr').open('a'),stderr=subprocess.STDOUT) + for _ in range(200): + if process.poll() is not None:raise RuntimeError((ROOT/'stderr').read_text()+(ROOT/'native.log').read_text()) + if (ROOT/'data/seafile.sock').exists():time.sleep(.2);return + time.sleep(.05) + raise RuntimeError('native socket readiness timeout') + start(); subprocess.run([sys.executable,__file__,'init'],check=True) + process.terminate();process.wait(timeout=10) + state=json.loads((ROOT/'state.json').read_text()); (ROOT/'conf/seafile.conf').write_text(config+'protection_repo_ids = '+state['repo']+'\ncheckout_enabled = true\ncheckout_repo_ids = '+state['repo']+'\n') + start() + go_process=subprocess.Popen([str(PKG/'seafile/bin/fileserver'),'-F',str(ROOT/'conf'),'-d',str(ROOT/'data'),'-l',str(ROOT/'go.log')],stdout=(ROOT/'go.stderr').open('w'),stderr=subprocess.STDOUT) + import requests + for _ in range(200): + if go_process.poll() is not None:raise RuntimeError((ROOT/'go.stderr').read_text()+(ROOT/'go.log').read_text()) + try: + if requests.get('http://127.0.0.1:8082/protocol-version',timeout=1).status_code==200:break + except requests.RequestException:pass + time.sleep(.05) + else:raise RuntimeError('Go readiness timeout') + subprocess.run([sys.executable,__file__,'test'],check=True) + finally: + if go_process is not None and go_process.poll() is None:go_process.terminate();go_process.wait(timeout=10) + if process is not None and process.poll() is None:process.terminate();process.wait(timeout=10) + with admin.cursor() as c: + for name in schemas.values():c.execute('DROP DATABASE IF EXISTS '+name) + admin.close() + + +if __name__ == '__main__': + run()