Files
iOSBuildServer/tests/test_build_service.py
T
shenlei 83a1db21e5 feat: 接入 iOSGuard LLVM 混淆工具链与 IPA 加固门禁,按分支策略兼容旧版本打包
- 新增 toolchain_manager:构建前自愈校验 LLVM opt 工具链,按 Xcode 版本与渠道隔离 obj_cache
- readoor31/readoor31OtherPay Archive 透传 IG_DIST_CHANNEL/IG_OBF_MODE/IG_ALL_GUARD_OFF/IG_RELEASE_SEED
- Archive 前核对分发渠道编译条件:上架包缺失 IG_APPSTORE_DISTRIBUTION 即阻断,非上架包带该条件仅告警,未接入 anti_tamper 的分支跳过
- 导出后执行 IPA 加固门禁审计,失败阻断上传;持久化 dSYM、混淆映射、诊断事件码与审计报告
- 混淆是否执行改由分支 AutoPacking/build_policy.json 声明:force_obfuscation=true 强制,否则按任务勾选,兼容旧分支/旧 Tag;恢复打包页混淆勾选框
- 分支未自带混淆脚本时回退服务端脚本并告警;同步更新服务端 L1 混淆脚本
- .gitignore 忽略 iosguard_cache 与 artifacts 运行时目录;README 补充分支打包策略说明
2026-11-24 12:03:54 +09:00

1064 lines
45 KiB
Python

"""打包服务核心逻辑测试"""
import asyncio
import json
import os
import plistlib
import time
import shutil
import tempfile
from pathlib import Path
from unittest.mock import patch, AsyncMock, MagicMock
import pytest
from backend.services.build_service import (
update_source,
copy_source_code,
prepare_source_snapshot,
build_project,
generate_config,
run_pod_install,
_patch_afnetworking_private_headers,
_cleanup_old_builds,
_mark_superseded_tasks,
_resolve_provisioning_profile,
_classify_build_error,
BuildError,
)
from backend.services.log_streamer import LogStreamer
@pytest.fixture
def log_streamer():
return LogStreamer()
@pytest.fixture
def tmp_dirs(tmp_path):
"""创建临时源码目录和打包目录"""
source_dir = tmp_path / "source"
source_dir.mkdir()
(source_dir / "readoor").mkdir()
(source_dir / "readoor" / "AppDelegate.swift").write_text("// app")
(source_dir / "readoor.xcodeproj").mkdir()
(source_dir / "Pods").mkdir()
(source_dir / "Podfile.lock").write_text("PODFILE CHECKSUM: abc")
(source_dir / "readoor.xcworkspace").mkdir()
whitelist_script = source_dir / "AutoPacking" / "obfuscation" / "generate_image_whitelist.py"
whitelist_script.parent.mkdir(parents=True)
whitelist_script.write_text("# whitelist generator")
vendor_dir = source_dir / "Vendor" / "RDEpubReaderView"
vendor_dir.mkdir(parents=True)
(vendor_dir / "RDEpubReaderView.podspec").write_text("Pod::Spec.new do |s| end")
(source_dir / "readoorTests").mkdir()
(source_dir / "Podfile").write_text("pod 'AFNetworking'")
build_dir = tmp_path / "build"
return source_dir, build_dir
def _patch_project_source(source_dir, remote_url="git@github.com:test/repo.git"):
"""让任务所属项目使用指定的远程仓库和共享源码目录"""
from backend.projects import ProjectSource
source = ProjectSource(remote_url, remote_url, source_dir)
return patch.multiple(
"backend.services.build_service",
load_task_project=MagicMock(return_value={}),
get_project_source=MagicMock(return_value=source),
)
def _make_mock_process(returncode=0, output=b"ok\n"):
"""创建 mock 进程,支持 async for stdout"""
proc = AsyncMock()
proc.returncode = returncode
proc.wait = AsyncMock(return_value=returncode)
async def iter_stdout():
yield output
proc.stdout = iter_stdout()
return proc
# ---- update_source ----
async def test_update_source_clone(tmp_path, log_streamer):
"""目录不存在时执行 clone"""
source_dir = tmp_path / "branches" / "main"
source_dir.parent.mkdir()
with patch("backend.services.build_service.get_git_remote_url", return_value="git@github.com:test/repo.git"):
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec:
await update_source("t1", source_dir, "main")
assert mock_exec.call_count == 6 # clone, set-url, fetch, checkout, reset, clean
assert mock_exec.call_args_list[0].args[:4] == ("git", "-c", "credential.helper=", "clone")
async def test_update_source_clone_no_remote(tmp_path, log_streamer):
"""目录不存在且未配置远程仓库时抛异常"""
source_dir = tmp_path / "branches" / "main"
with patch("backend.services.build_service.get_git_remote_url", return_value=""):
with pytest.raises(Exception, match="未配置 Git 仓库地址"):
await update_source("t1", source_dir, "main")
async def test_update_source_existing(tmp_path, log_streamer):
"""目录已存在时执行 fetch + checkout + reset + clean"""
source_dir = tmp_path / "branches" / "dev"
source_dir.parent.mkdir(parents=True)
source_dir.mkdir()
(source_dir / ".git").mkdir()
call_count = 0
async def mock_exec(*args, **kwargs):
nonlocal call_count
call_count += 1
return _make_mock_process()
with patch("backend.services.build_service.get_git_remote_url", return_value=""):
with patch("asyncio.create_subprocess_exec", side_effect=mock_exec):
await update_source("t1", source_dir, "dev")
assert call_count == 4 # fetch, checkout, reset, clean
async def test_update_source_tag_checks_out_detached(tmp_path, log_streamer):
"""Tag 打包:拉取 Tag 后以游离 HEAD 检出 refs/tags/<tag>,不依赖同名远程分支"""
source_dir = tmp_path / "workspace"
source_dir.mkdir()
(source_dir / ".git").mkdir()
with patch("backend.services.build_service.get_git_remote_url", return_value=""):
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec:
await update_source("t1", source_dir, "v3.2.0", "tag")
git_args = [call.args[3:] for call in mock_exec.call_args_list]
assert git_args == [
("fetch", "origin", "--tags", "--force"),
("checkout", "--detach", "refs/tags/v3.2.0"),
("reset", "--hard", "refs/tags/v3.2.0"),
("clean", "-ffdx"),
]
async def test_update_source_fetch_failure(tmp_path, log_streamer):
"""fetch 失败时抛异常"""
source_dir = tmp_path / "branches" / "dev"
source_dir.parent.mkdir(parents=True)
source_dir.mkdir()
(source_dir / ".git").mkdir()
async def mock_exec(*args, **kwargs):
return _make_mock_process(returncode=1, output=b"error\n")
with patch("backend.services.build_service.get_git_remote_url", return_value=""):
with patch("asyncio.create_subprocess_exec", side_effect=mock_exec):
with pytest.raises(Exception, match="git fetch 失败"):
await update_source("t1", source_dir, "dev")
async def test_prepare_source_snapshot_serializes_shared_source(tmp_dirs, log_streamer):
"""共享源码模式下,更新和复制必须在同一把锁内完成。"""
source_dir, build_dir_parent = tmp_dirs
task = MagicMock(branch="main")
with _patch_project_source(source_dir), \
patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \
patch("backend.services.build_service.update_source", new_callable=AsyncMock) as mock_update, \
patch("backend.services.build_service.get_source_commit", new_callable=AsyncMock, return_value="abc123"):
build_dir, commit = await prepare_source_snapshot("t1", task)
assert build_dir.exists()
assert commit == "abc123"
assert mock_update.call_args.args[2:] == ("main", "branch")
async def test_prepare_source_snapshot_passes_tag_ref_type(tmp_dirs, log_streamer):
source_dir, build_dir_parent = tmp_dirs
task = MagicMock(id="tag-task", branch="v3.2.0", ref_type="tag")
with _patch_project_source(source_dir), \
patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \
patch("backend.services.build_service.update_source", new_callable=AsyncMock) as mock_update, \
patch("backend.services.build_service.get_source_commit", new_callable=AsyncMock, return_value="abc123"):
await prepare_source_snapshot("t1", task)
assert mock_update.call_args.args[2:] == ("v3.2.0", "tag")
# ---- copy_source_code ----
async def test_copy_source_code(tmp_dirs, log_streamer):
"""正常拷贝源码"""
source_dir, build_dir_parent = tmp_dirs
task = MagicMock()
task.branch = "main"
with patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent):
result = await copy_source_code("t1", task, source_dir)
assert result.exists()
assert (result / "readoor" / "AppDelegate.swift").exists()
assert (result / "Pods").exists()
names = {entry.name for entry in result.iterdir()}
assert "Podfile" in names
assert "podfile" not in names
assert (result / "Podfile.lock").exists()
assert (result / "readoor.xcworkspace").exists()
assert (result / "Vendor" / "RDEpubReaderView" / "RDEpubReaderView.podspec").exists()
assert (result / "AutoPacking" / "obfuscation" / "generate_image_whitelist.py").exists()
async def test_legacy_copy_items_include_guard_with_relative_links(tmp_dirs):
source, builds = tmp_dirs
toolchain = source / "iOSGuardIntegration" / "toolchain"
toolchain.mkdir(parents=True)
(toolchain / "readoor-test").symlink_to("../..")
definition = {"copy_items": ["readoor"]}
with patch("backend.services.build_service.BUILD_BASE_DIR", builds):
snapshot = await copy_source_code("guard", MagicMock(), source, definition)
link = snapshot / "iOSGuardIntegration/toolchain/readoor-test"
assert link.is_symlink() and link.resolve() == snapshot
assert definition["copy_items"] == ["readoor"]
async def test_missing_guard_script_fails_before_archive(tmp_dirs):
source, _ = tmp_dirs
relative = "iOSGuardIntegration/toolchain/tools/xcode_archive/ig_guard_frameworks_phase.py"
(source / "readoor.xcodeproj/project.pbxproj").write_text(relative)
with pytest.raises(BuildError, match="ig_guard_frameworks_phase.py"):
await build_project("guard", MagicMock(), {"SCHEME": "readoor31OtherPay"}, source,
{"workspace": "readoor.xcworkspace"})
def test_missing_script_with_normal_signing_identity():
lines = ["Signing Identity: iPhone Distribution: Example",
"python3: can't open file '/tmp/guard.py': [Errno 2] No such file or directory"]
category, hint = _classify_build_error(lines, "archive")
assert category == "config" and "/tmp/guard.py" in hint
assert _classify_build_error(["No signing certificate found"], "archive")[0] == "certificate"
async def test_copy_source_code_normalizes_lowercase_podfile(tmp_dirs, log_streamer):
"""旧分支的 podfile 也必须复制为 Pods 工程引用的 Podfile。"""
source_dir, build_dir_parent = tmp_dirs
(source_dir / "Podfile").unlink()
(source_dir / "podfile").write_text("pod 'AFNetworking'")
task = MagicMock(branch="main")
with patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent):
result = await copy_source_code("t1", task, source_dir)
copied_names = {path.name for path in result.iterdir()}
assert "Podfile" in copied_names
assert "podfile" not in copied_names
async def test_copy_source_code_excludes_git(tmp_dirs, log_streamer):
"""拷贝时排除 .git 目录"""
source_dir, build_dir_parent = tmp_dirs
(source_dir / "readoor" / ".git").mkdir()
task = MagicMock()
with patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent):
result = await copy_source_code("t1", task, source_dir)
assert not (result / "readoor" / ".git").exists()
async def test_copy_source_code_overwrites_existing(tmp_dirs, log_streamer):
"""打包目录已存在时覆盖"""
source_dir, build_dir_parent = tmp_dirs
old_dir = build_dir_parent / "build_readoor_t1"
old_dir.mkdir(parents=True)
(old_dir / "old_file.txt").write_text("old")
task = MagicMock()
with patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent):
result = await copy_source_code("t1", task, source_dir)
assert not (result / "old_file.txt").exists()
assert (result / "readoor").exists()
def test_patch_afnetworking_private_headers(tmp_path):
"""pod install 后移除新版 Xcode 禁止直接引用的 netinet6 私有头。"""
source_dir = tmp_path / "Pods" / "AFNetworking" / "AFNetworking"
source_dir.mkdir(parents=True)
source_file = source_dir / "AFNetworkReachabilityManager.m"
source_file.write_text(
"#import <netinet/in.h>\n#import <netinet6/in6.h>\n#import <arpa/inet.h>\n"
)
source_file.chmod(0o444)
assert _patch_afnetworking_private_headers(tmp_path) == 1
assert "#import <netinet6/in6.h>" not in source_file.read_text()
assert "#import <netinet/in.h>" in source_file.read_text()
assert source_file.stat().st_mode & 0o777 == 0o444
async def test_run_pod_install_patches_afnetworking(tmp_path, log_streamer):
source_dir = tmp_path / "Pods" / "AFNetworking"
source_dir.mkdir(parents=True)
source_file = source_dir / "AFHTTPSessionManager.m"
source_file.write_text("#import <netinet6/in6.h>\n")
(tmp_path / "Podfile").write_text("pod 'AFNetworking'")
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()):
await run_pod_install("t1", tmp_path)
assert "netinet6/in6.h" not in source_file.read_text()
async def test_run_pod_install_uses_xcode_subdirectory(tmp_path, log_streamer):
"""工程在仓库子目录时,在 Podfile 所在的子目录执行 pod install。"""
sub = tmp_path / "Demo"
sub.mkdir()
(sub / "Podfile").write_text("pod 'SnapKit'")
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec:
await run_pod_install("t1", tmp_path, {"workspace": "Demo/App.xcworkspace", "project": ""})
assert mock_exec.call_args.kwargs["cwd"] == str(sub)
async def test_run_pod_install_retries_with_repo_update(tmp_path, log_streamer):
"""本地 Specs 索引过旧找不到版本时,带 --repo-update 重试一次。"""
(tmp_path / "Podfile").write_text("pod 'OpenSSL-Universal', '1.1.2301'")
missing = _make_mock_process(1, b"[!] Unable to find a specification for `OpenSSL-Universal (= 1.1.2301)`\n")
with patch("asyncio.create_subprocess_exec", side_effect=[missing, _make_mock_process()]) as mock_exec:
await run_pod_install("t1", tmp_path)
assert mock_exec.call_args_list[0].args == ("pod", "install")
assert mock_exec.call_args_list[1].args == ("pod", "install", "--repo-update")
async def test_run_pod_install_other_failure_not_retried(tmp_path, log_streamer):
(tmp_path / "Podfile").write_text("pod 'SnapKit'")
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process(1, b"[!] Some error\n")) as mock_exec:
with pytest.raises(Exception, match="pod install 失败"):
await run_pod_install("t1", tmp_path)
assert mock_exec.call_count == 1
async def test_build_project_passes_scheme_as_exec_argument(tmp_path, log_streamer):
"""Scheme 中的 shell 特殊字符只能作为 xcodebuild 参数,不能被执行。"""
build_dir = tmp_path / "build"
build_dir.mkdir()
task = MagicMock()
config_data = {"SCHEME": "App; touch /tmp/should-not-run"}
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec, \
patch("asyncio.create_subprocess_shell") as mock_shell:
with pytest.raises(Exception, match="未找到 IPA 文件"):
await build_project("t1", task, config_data, build_dir)
assert mock_shell.call_count == 0
archive_args = mock_exec.call_args_list[1].args
assert archive_args[0:2] == ("xcodebuild", "archive")
assert "App; touch /tmp/should-not-run" in archive_args
# ---- generate_config ----
async def test_generate_config(tmp_path, log_streamer):
"""生成打包配置"""
build_dir = tmp_path / "build"
build_dir.mkdir()
task = MagicMock()
task.app_id = "1"
task.scheme_id = "1"
task.build_type = "Ad_Hoc"
task.obfuscation = True
mock_config = {
"apps": {
"1": {
"name": "测试App",
"server": "测试环境",
"AppGuid": "guid-123",
"API": "https://test.api.com",
"certificates": {
"Ad_Hoc": {"name": "com.test.app", "cer": "cert", "pro": "pro", "theme": "t"}
},
}
},
"schemes": {"1": {"name": "testScheme", "ossFloder": "test"}},
}
with patch("backend.routers.config.load_config", return_value=mock_config), \
patch(
"backend.services.build_service._resolve_provisioning_profile",
return_value=("pro", "TEAM123"),
):
result = await generate_config("t1", task, build_dir)
assert result["APPID"] == "guid-123"
assert result["SCHEME"] == "testScheme"
assert result["BUILD_TYPE"] == "Ad_Hoc"
assert result["BUNDLE_ID"] == "com.test.app"
assert result["CERTIFICATE"] == "cert"
assert result["PROVISIONING_NAME"] == "pro"
assert result["TEAM_ID"] == "TEAM123"
config_file = build_dir / "config_output.json"
assert config_file.exists()
saved = json.loads(config_file.read_text())
assert saved["APPID"] == "guid-123"
@pytest.mark.parametrize("app_fields, appid, expected_id, expected_label", [
([{"key": "APPID", "label": "APPID"}], "1587365345", "1587365345", "APPID"),
([{"key": "APPID", "label": "APPID"}], "", "dy_app", "App 标识"),
([], "", "dy_app", "App 标识"),
])
async def test_generate_config_generic_project_identifier(
tmp_path, log_streamer, app_fields, appid, expected_id, expected_label,
):
"""通用项目没有 AppGuid,以第一个 App 字段作为产物文件名和通知中的 App 标识"""
build_dir = tmp_path / "build"
build_dir.mkdir()
task = MagicMock()
task.project_id = "dyauction"
task.app_id = "1"
task.scheme_id = "1"
task.build_type = "Ad_Hoc"
task.obfuscation = False
mock_config = {
"patcher": "generic",
"app_fields": app_fields,
"apps": {"1": {"name": "朵云轩", "server": "正式环境", "APPID": appid, "upload_key": "dy_app",
"certificates": {}}},
"schemes": {"1": {"name": "DyAuction", "ossFloder": "dy"}},
}
with patch("backend.routers.config.load_config", return_value=mock_config):
result = await generate_config("t1", task, build_dir)
assert result["APPID"] == expected_id
assert result["APPID_LABEL"] == expected_label
profile_path = tmp_path / "profile.mobileprovision"
profile_path.write_bytes(b"signed profile")
decoded = plistlib.dumps({"Name": "a4YX061_adHoc", "TeamIdentifier": ["MG4Z7FU83W"]})
with patch("backend.services.build_service.subprocess.check_output", return_value=decoded):
assert _resolve_provisioning_profile(str(profile_path)) == ("a4YX061_adHoc", "MG4Z7FU83W")
def _versions_config(tracks: dict) -> dict:
"""构造带版本轨道的配置;tracks 为 轨道名 -> {kind, app_ver, build_map}。"""
return {
"apps": {"1": {"name": "App", "certificates": {}}},
"schemes": {"1": {"name": "sch", "ossFloder": "f"}},
"versions": {"tracks": tracks},
}
def _release(app_ver: str, build_map: dict = None) -> dict:
return {"kind": "release", "app_ver": app_ver, "build_map": build_map or {}}
def _feature(app_ver: str, build_map: dict = None) -> dict:
return {"kind": "feature", "app_ver": app_ver, "build_map": build_map or {}}
async def test_generate_config_uses_saved_version(tmp_path, log_streamer):
"""从服务配置读取版本号,不依赖分支源码脚本"""
build_dir = tmp_path / "build"
build_dir.mkdir()
task = MagicMock()
task.app_id = "1"
task.scheme_id = "1"
task.build_type = "Ad_Hoc"
task.obfuscation = False
task.branch = "master"
mock_config = _versions_config({"release": _release("3.0.1"), "feature": _feature("9.9.9")})
with patch("backend.routers.config.load_config", return_value=mock_config):
result = await generate_config("t1", task, build_dir)
assert result["VERSION"] == "3.0.1"
assert result["BUILD_VERSION"] == "3.0.1.0"
async def test_generate_config_appstore_increments_per_version(tmp_path, log_streamer):
"""App_Store 打包时,按版本号在其自身已用构建号上 +1(回退旧版本号亦从自身最大值继续)"""
build_dir = tmp_path / "build"
build_dir.mkdir()
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
obfuscation=False, branch="master")
# 2.195.0 已打到 .5,切到 2.196.0 后又回退到 2.195.0
mock_config = _versions_config({
"release": _release("2.195.0", {"2.195.0": 5, "2.196.0": 3}),
"feature": _feature("2.195.0"),
})
with patch("backend.routers.config.load_config", return_value=mock_config), \
patch("backend.routers.config.save_config") as save_mock:
result = await generate_config("t1", task, build_dir)
# 从 2.195.0 自身的 5 继续到 6,不受 2.196.0 影响,也不撞已传的 .5
release_map = mock_config["versions"]["tracks"]["release"]["build_map"]
assert result["BUILD_VERSION"] == "2.195.0.6"
assert release_map["2.195.0"] == 6
assert release_map["2.196.0"] == 3
save_mock.assert_called()
async def test_generate_config_release_branches_are_independent(tmp_path, log_streamer):
"""master 与 develop 各用自己的轨道,版本号与构建号互不影响"""
build_dir = tmp_path / "build"
build_dir.mkdir()
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
obfuscation=False, branch="develop")
mock_config = _versions_config({
"release": _release("2.195.0", {"2.195.0": 5}), # master
"develop": _release("2.196.0", {"2.196.0": 1}),
"feature": _feature("2.100.0"),
})
with patch("backend.routers.config.load_config", return_value=mock_config), \
patch("backend.routers.config.save_config"):
result = await generate_config("t1", task, build_dir)
assert result["VERSION"] == "2.196.0"
assert result["BUILD_VERSION"] == "2.196.0.2"
# master 的 release 轨完全不受影响
assert mock_config["versions"]["tracks"]["release"]["build_map"] == {"2.195.0": 5}
async def test_generate_config_build_no_skips_other_release_track(tmp_path, log_streamer):
"""两个上架分支临时用同一 App_Ver 时,构建号跨轨道取最大值 +1,避免 App Store 重号"""
build_dir = tmp_path / "build"
build_dir.mkdir()
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
obfuscation=False, branch="develop")
mock_config = _versions_config({
"release": _release("2.196.0", {"2.196.0": 7}), # master
"develop": _release("2.196.0", {"2.196.0": 2}),
"feature": _feature("2.100.0"),
})
with patch("backend.routers.config.load_config", return_value=mock_config), \
patch("backend.routers.config.save_config"):
result = await generate_config("t1", task, build_dir)
assert result["BUILD_VERSION"] == "2.196.0.8"
assert mock_config["versions"]["tracks"]["develop"]["build_map"]["2.196.0"] == 8
async def test_generate_config_feature_branch_never_increments(tmp_path, log_streamer):
"""自测分支用自己那条轨道的版本号,且构建号永不自增(即使是 App_Store 打包)"""
build_dir = tmp_path / "build"
build_dir.mkdir()
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
obfuscation=False, branch="feature/login")
mock_config = _versions_config({
"release": _release("2.195.0", {"2.195.0": 5}),
"feature/login": _feature("2.100.0"),
})
with patch("backend.routers.config.load_config", return_value=mock_config), \
patch("backend.routers.config.save_config") as save_mock:
result = await generate_config("t1", task, build_dir)
assert result["VERSION"] == "2.100.0"
assert result["BUILD_VERSION"] == "2.100.0.0"
assert mock_config["versions"]["tracks"]["feature/login"]["build_map"] == {}
save_mock.assert_not_called()
async def test_generate_config_branch_track_override(tmp_path, log_streamer):
"""branch_track 中的显式配置优先于按分支名推断"""
build_dir = tmp_path / "build"
build_dir.mkdir()
task = MagicMock(app_id="1", scheme_id="1", build_type="Ad_Hoc",
obfuscation=False, branch="release/2.196")
mock_config = _versions_config({
"release": _release("2.196.0"),
"feature/login": _feature("2.100.0"),
})
# release/2.196 按名字本应是上架轨,显式指到 feature/login 那条轨道
mock_config["branch_track"] = {"release/2.196": "feature/login"}
with patch("backend.routers.config.load_config", return_value=mock_config):
result = await generate_config("t1", task, build_dir)
assert result["VERSION"] == "2.100.0"
async def test_generate_config_uses_server_theme_not_source_autopacking(tmp_path, log_streamer):
"""Web 打包不读取分支源码中的 AutoPacking 目录。"""
build_dir = tmp_path / "build"
(build_dir / "AutoPacking" / "ymh").mkdir(parents=True)
automation_dir = tmp_path / "automation"
default_theme = automation_dir / "themes" / "ymh"
default_theme.mkdir(parents=True)
task = MagicMock(app_id="1", scheme_id="1", build_type="Ad_Hoc", obfuscation=False)
mock_config = {
"apps": {
"1": {
"name": "App",
"certificates": {"Ad_Hoc": {"name": "com.example.app", "theme": "AutoPacking/ymh"}},
}
},
"schemes": {"1": {"name": "sch", "ossFloder": "f"}},
}
with patch("backend.routers.config.load_config", return_value=mock_config), \
patch("backend.services.build_service.AUTOMATION_DIR", automation_dir), \
patch("backend.services.build_service.SKINS_DIR", tmp_path / "skins"):
result = await generate_config("t1", task, build_dir)
assert result["THEME"] == str(default_theme)
# ---- _cleanup_old_builds ----
def test_cleanup_old_builds(tmp_path):
"""清理过期打包目录"""
from backend.database import SessionLocal, init_db
from backend.models import BuildConfig
init_db()
db = SessionLocal()
config = db.query(BuildConfig).filter(BuildConfig.key == "build_dir_retention_hours").first()
if config:
config.value = "1"
else:
db.add(BuildConfig(key="build_dir_retention_hours", value="1"))
db.commit()
old_dir = tmp_path / "build_readoor_old"
old_dir.mkdir()
# 设置修改时间为 24 小时前(确保超过 1 小时保留期)
old_time = time.time() - 86400
os.utime(old_dir, (old_time, old_time))
with patch("backend.services.build_service.BUILD_BASE_DIR", tmp_path):
_cleanup_old_builds(db)
assert not old_dir.exists()
db.close()
def test_cleanup_keeps_recent(tmp_path):
"""保留未过期的打包目录"""
from backend.database import SessionLocal, init_db
from backend.models import BuildConfig
init_db()
db = SessionLocal()
config = db.query(BuildConfig).filter(BuildConfig.key == "build_dir_retention_hours").first()
if config:
config.value = "24"
else:
db.add(BuildConfig(key="build_dir_retention_hours", value="24"))
db.commit()
recent_dir = tmp_path / "build_readoor_recent"
recent_dir.mkdir()
with patch("backend.services.build_service.BUILD_BASE_DIR", tmp_path):
_cleanup_old_builds(db)
assert recent_dir.exists()
db.close()
def test_mark_superseded_tasks_for_same_oss_url():
from backend.database import SessionLocal, init_db
from backend.models import Task
init_db()
db = SessionLocal()
old = Task(id="old", app_id="1", app_name="测试App", build_type="Ad_Hoc", scheme_id="1", scheme_name="readoor31", status="completed", oss_url="https://files.example.com/app.html")
latest = Task(id="latest", app_id="1", app_name="测试App", build_type="Ad_Hoc", scheme_id="1", scheme_name="readoor31", status="completed", oss_url="https://files.example.com/app.html")
db.add_all([old, latest])
db.commit()
_mark_superseded_tasks(db, latest)
assert db.get(Task, "old").superseded_at is not None
assert db.get(Task, "latest").superseded_at is None
db.close()
async def test_build_project_iosguard_require_obf_and_persistent_cache(tmp_path, monkeypatch):
"""开启 IR 混淆时调用自愈工具链校验,按版本与分发渠道隔离 obj_cache,并注入 IG_DIST_CHANNEL。"""
from backend.services.build_service import _prepare_iosguard_build_env
build_dir = tmp_path / "build_snap"
resolver = build_dir / "iOSGuardIntegration" / "toolchain" / "tools" / "llvm_obf" / "ig_toolchain_resolver.py"
resolver.parent.mkdir(parents=True)
resolver.write_text("# resolver stub\n", encoding="utf-8")
cache_root = tmp_path / "ig_cache"
tc_cache_root = cache_root / "toolchains"
stale_obj_dir = cache_root / "obj_cache" / "26A100-old1"
stale_obj_dir.mkdir(parents=True)
os.utime(stale_obj_dir, (1_600_000_000, 1_600_000_000))
for i, old_name in enumerate(("26B200-old2", "26C300-old3", "26D400-old4")):
d = cache_root / "obj_cache" / old_name
d.mkdir(parents=True)
os.utime(d, (1_700_000_000 + i * 10, 1_700_000_000 + i * 10))
monkeypatch.delenv("IG_OBF_MODE", raising=False)
monkeypatch.delenv("IG_ALL_GUARD_OFF", raising=False)
monkeypatch.delenv("IG_RELEASE_SEED", raising=False)
monkeypatch.delenv("IG_OBF_OBJ_CACHE_DIR", raising=False)
monkeypatch.delenv("IG_SDK_CACHE_DIR", raising=False)
mock_tc = {
"opt_path": "/opt/bin/opt",
"source_mode": "cached",
"xcode": {"xcode_build": "27A9275"},
"passes_hash": "b3a4000211223344",
}
with patch("backend.services.build_service.IG_CACHE_DIR", cache_root), \
patch("backend.services.build_service.IG_TOOLCHAIN_CACHE_DIR", tc_cache_root), \
patch("backend.services.build_service.ensure_toolchain", new_callable=AsyncMock, return_value=mock_tc) as mock_ensure:
env = await _prepare_iosguard_build_env(
"task-m3-1",
{"BUILD_VERSION": "3.1.0.5", "BUILD_TYPE": "App_Store"},
build_dir,
)
assert env["IG_REQUIRE_LLVM_OBF"] == "1"
assert env["IG_OBF_MODE"] == "full"
assert env["IG_DIST_CHANNEL"] == "appstore"
assert env["IG_RELEASE_SEED"] == "task-m3-1_3.1.0.5"
assert env["IG_TOOLCHAIN_CACHE_DIR"] == str(tc_cache_root)
assert env["IG_OBF_OBJ_CACHE_DIR"] == str(cache_root / "obj_cache" / "27A9275-b3a40002" / "appstore")
assert env["IG_SDK_CACHE_DIR"] == str(cache_root / "sdk_cache")
assert Path(env["IG_OBF_OBJ_CACHE_DIR"]).is_dir()
assert Path(env["IG_SDK_CACHE_DIR"]).is_dir()
assert mock_ensure.call_args.args == (resolver,)
# 超过 keep=3 的最旧 obj_cache 目录被自动清理
assert not stale_obj_dir.exists()
with patch("backend.services.build_service.IG_CACHE_DIR", cache_root), \
patch("backend.services.build_service.IG_TOOLCHAIN_CACHE_DIR", tc_cache_root), \
patch("backend.services.build_service.ensure_toolchain", new_callable=AsyncMock, side_effect=RuntimeError("hash mismatch")):
with pytest.raises(BuildError, match="LLVM IR 混淆工具链校验失败"):
await _prepare_iosguard_build_env("task-m3-1", {"BUILD_VERSION": "3.1.0.5"}, build_dir)
# IG_OBF_MODE=off 与 IG_ALL_GUARD_OFF=1 跳过 opt 校验
for extra_env in ({"IG_OBF_MODE": "off"}, {"IG_ALL_GUARD_OFF": "1"}):
for k, v in extra_env.items():
monkeypatch.setenv(k, v)
with patch("backend.services.build_service.IG_CACHE_DIR", cache_root), \
patch("backend.services.build_service.IG_TOOLCHAIN_CACHE_DIR", tc_cache_root), \
patch("backend.services.build_service.ensure_toolchain", new_callable=AsyncMock) as should_not_run:
off_env = await _prepare_iosguard_build_env("task-m3-off", {"BUILD_VERSION": "3.1.0.5"}, build_dir)
assert should_not_run.call_count == 0
assert off_env["IG_OBF_MODE"] == "off"
assert "IG_REQUIRE_LLVM_OBF" not in off_env
for k in extra_env:
monkeypatch.delenv(k, raising=False)
async def test_run_obfuscation_prefers_branch_scripts_and_falls_back(tmp_path, log_streamer):
"""L1 优先执行分支内的 AutoPacking/obfuscation,旧分支缺少时回退到服务端 AUTOMATION_DIR。"""
from backend.services.build_service import run_obfuscation
build_dir = tmp_path / "snap"
branch_obf = build_dir / "AutoPacking" / "obfuscation"
(branch_obf / "scripts").mkdir(parents=True)
branch_check = branch_obf / "scripts" / "obfuscation_self_check.sh"
branch_obf_py = branch_obf / "obfuscate_symbols.py"
branch_check.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
branch_obf_py.write_text("# branch obf\n", encoding="utf-8")
fallback_root = tmp_path / "server_auto"
(fallback_root / "obfuscation" / "scripts").mkdir(parents=True)
fb_check = fallback_root / "obfuscation" / "scripts" / "obfuscation_self_check.sh"
fb_py = fallback_root / "obfuscation" / "obfuscate_symbols.py"
fb_check.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
fb_py.write_text("# fallback obf\n", encoding="utf-8")
with patch("backend.services.build_service.AUTOMATION_DIR", fallback_root), \
patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec:
await run_obfuscation("t-branch", MagicMock(), {"SCHEME": "readoor31OtherPay", "BUILD_VERSION": "1.0.0.1"}, build_dir)
assert mock_exec.call_args_list[0].args[1] == str(branch_check)
assert mock_exec.call_args_list[1].args[1] == str(branch_obf_py)
# 移除分支脚本后回退到服务端脚本
branch_obf_py.unlink()
with patch("backend.services.build_service.AUTOMATION_DIR", fallback_root), \
patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec_fb:
await run_obfuscation("t-fb", MagicMock(), {"SCHEME": "readoor31OtherPay", "BUILD_VERSION": "1.0.0.1"}, build_dir)
assert mock_exec_fb.call_args_list[0].args[1] == str(fb_check)
assert mock_exec_fb.call_args_list[1].args[1] == str(fb_py)
async def test_build_project_passes_dist_channel_and_blocks_on_audit_failure(tmp_path, log_streamer):
"""App_Store 向 xcodebuild archive 透传 IG_DIST_CHANNEL=appstore,并在导出审计失败时阻断上传。"""
build_dir = tmp_path / "snap"
(build_dir / "readoor.xcworkspace").mkdir(parents=True)
(build_dir / "exportOptions.plist").write_text("<plist/>", encoding="utf-8")
audit_script = build_dir / "iOSGuardIntegration" / "toolchain" / "tools" / "xcode_archive" / "audit_exported_ipa.py"
audit_script.parent.mkdir(parents=True)
audit_script.write_text("# audit stub\n", encoding="utf-8")
out_dir = build_dir / "build"
out_dir.mkdir(parents=True)
(out_dir / "readoor31OtherPay.ipa").write_bytes(b"PK")
mock_audit_fail = _make_mock_process(returncode=1, output=b"StaticHygieneGate FAILED\n")
mock_audit_fail.wait = AsyncMock(return_value=1)
calls = []
async def exec_side_effect(*args, **kwargs):
calls.append(args)
if len(args) > 1 and str(audit_script) in args:
return mock_audit_fail
return _make_mock_process(0)
tc_info = {"opt_path": "/opt/bin/opt", "source_mode": "cached", "xcode": {"xcode_build": "27A9275"}, "passes_hash": "abc"}
with patch("backend.services.build_service.IG_CACHE_DIR", tmp_path / "cache"), \
patch("backend.services.build_service.IG_TOOLCHAIN_CACHE_DIR", tmp_path / "cache" / "toolchains"), \
patch("backend.services.build_service.ensure_toolchain", new_callable=AsyncMock, return_value=tc_info), \
patch("asyncio.create_subprocess_exec", side_effect=exec_side_effect):
with pytest.raises(BuildError, match="IPA 加固门禁审计失败"):
await build_project(
"t-appstore",
MagicMock(),
{"SCHEME": "readoor31OtherPay", "BUILD_TYPE": "App_Store", "BUILD_VERSION": "3.1.0.1", "BUNDLE_ID": "com.test.app"},
build_dir,
{"workspace": "readoor.xcworkspace"},
)
archive_cmd = next(c for c in calls if len(c) > 1 and c[0] == "xcodebuild" and c[1] == "archive")
assert "IG_DIST_CHANNEL=appstore" in archive_cmd
audit_cmd = next(c for c in calls if str(audit_script) in c)
assert "--archive" in audit_cmd and "--bundle-id" in audit_cmd and "--report-out" in audit_cmd
def _dist_channel_snapshot(tmp_path):
"""构造接入了 anti_tamper 的源码快照(pbxproj 引用 IGAntiTamper.c)。"""
build_dir = tmp_path / "snap"
(build_dir / "readoor.xcworkspace").mkdir(parents=True)
(build_dir / "readoor.xcodeproj").mkdir()
(build_dir / "readoor.xcodeproj" / "project.pbxproj").write_text(
"/* IGAntiTamper.c in Sources */", encoding="utf-8"
)
(build_dir / "exportOptions.plist").write_text("<plist/>", encoding="utf-8")
return build_dir
def _dist_env(channel):
return {"IG_DIST_CHANNEL": channel, "IG_OBF_MODE": "full", "IG_ALL_GUARD_OFF": "0", "IG_RELEASE_SEED": "s"}
def _dist_exec(calls, settings_output):
async def exec_side_effect(*args, **kwargs):
calls.append(args)
if len(args) > 1 and args[1] == "-showBuildSettings":
return _make_mock_process(0, settings_output)
return _make_mock_process(0)
return exec_side_effect
async def test_appstore_build_blocked_when_dist_flag_missing(tmp_path):
"""上架包 showBuildSettings 中没有 IG_APPSTORE_DISTRIBUTION 时,Archive 前阻断。"""
build_dir = _dist_channel_snapshot(tmp_path)
calls = []
output = b" OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -D TARGETTYPE_7\n"
with patch("asyncio.create_subprocess_exec", side_effect=_dist_exec(calls, output)):
with pytest.raises(BuildError, match="未注入 IG_APPSTORE_DISTRIBUTION"):
await build_project(
"t-miss", MagicMock(),
{"SCHEME": "readoor31", "BUILD_TYPE": "App_Store"},
build_dir, {"workspace": "readoor.xcworkspace"}, prepared_env=_dist_env("appstore"),
)
settings_cmd = next(c for c in calls if c[1] == "-showBuildSettings")
assert "IG_DIST_CHANNEL=appstore" in settings_cmd and "Release" in settings_cmd
assert not any(c[1] == "archive" for c in calls)
async def test_appstore_build_passes_when_dist_flag_present(tmp_path):
"""上架包已注入 -DIG_APPSTORE_DISTRIBUTION 时正常进入 Archive。"""
build_dir = _dist_channel_snapshot(tmp_path)
calls = []
output = b" OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -DIG_APPSTORE_DISTRIBUTION\n"
with patch("asyncio.create_subprocess_exec", side_effect=_dist_exec(calls, output)):
with pytest.raises(Exception, match="未找到 IPA 文件"):
await build_project(
"t-ok", MagicMock(),
{"SCHEME": "readoor31OtherPay", "BUILD_TYPE": "App_Store"},
build_dir, {"workspace": "readoor.xcworkspace"}, prepared_env=_dist_env("appstore"),
)
assert any(c[1] == "archive" for c in calls)
async def test_adhoc_build_warns_when_dist_flag_hardcoded(tmp_path):
"""非上架包仍带写死的分发条件时只告警、不阻断。"""
build_dir = _dist_channel_snapshot(tmp_path)
calls = []
output = b" SWIFT_ACTIVE_COMPILATION_CONDITIONS = TARGETTYPE_7 IG_APPSTORE_DISTRIBUTION\n"
with patch("asyncio.create_subprocess_exec", side_effect=_dist_exec(calls, output)), \
patch("backend.services.build_service.log_streamer", new=AsyncMock()) as mock_ls:
with pytest.raises(Exception, match="未找到 IPA 文件"):
await build_project(
"t-adhoc", MagicMock(),
{"SCHEME": "readoor31", "BUILD_TYPE": "Ad_Hoc"},
build_dir, {"workspace": "readoor.xcworkspace"}, prepared_env=_dist_env("dev"),
)
assert any(c[1] == "archive" for c in calls)
warning_text = " ".join(str(call.args[1]) for call in mock_ls.emit_warning.call_args_list)
assert "IG_APPSTORE_DISTRIBUTION" in warning_text
async def test_dist_flag_check_skipped_without_anti_tamper(tmp_path):
"""未接入 anti_tamper 的历史分支不做渠道核对。"""
build_dir = _dist_channel_snapshot(tmp_path)
(build_dir / "readoor.xcodeproj" / "project.pbxproj").write_text("/* legacy */", encoding="utf-8")
calls = []
with patch("asyncio.create_subprocess_exec", side_effect=_dist_exec(calls, b"")):
with pytest.raises(Exception, match="未找到 IPA 文件"):
await build_project(
"t-legacy", MagicMock(),
{"SCHEME": "readoor31", "BUILD_TYPE": "App_Store"},
build_dir, {"workspace": "readoor.xcworkspace"}, prepared_env=_dist_env("appstore"),
)
assert not any(c[1] == "-showBuildSettings" for c in calls)
def test_persist_task_artifacts_survives_build_dir_cleanup(tmp_path):
"""_cleanup_build_dir 销毁 build_dir 后,dSYM(含 IGArchiveGuard)、映射表、事件码与混淆审计仍保留在 ARTIFACTS_DIR。"""
from backend.services.build_service import persist_task_artifacts, _cleanup_build_dir
build_dir = tmp_path / "build_snap"
artifacts_root = tmp_path / "artifacts"
dsym_app = build_dir / "build" / "readoor31.xcarchive" / "dSYMs" / "readoor31.app.dSYM" / "Contents" / "Resources" / "DWARF"
dsym_fw = build_dir / "build" / "readoor31.xcarchive" / "dSYMs" / "IGArchiveGuard.framework.dSYM" / "Contents" / "Resources" / "DWARF"
dsym_app.mkdir(parents=True)
dsym_fw.mkdir(parents=True)
(dsym_app / "readoor31").write_bytes(b"app-dwarf")
(dsym_fw / "IGArchiveGuard").write_bytes(b"fw-dwarf")
maps_src = build_dir / "obfuscation_maps"
maps_src.mkdir(parents=True)
(maps_src / "symbol_map_readoor31_20261119.json").write_text('{"schema_version": 2}', encoding="utf-8")
(maps_src / "method_map_readoor31_20261119.json").write_text('{"schema_version": 2}', encoding="utf-8")
cfg_dir = build_dir / "iOSGuardIntegration" / "toolchain" / "config"
cfg_dir.mkdir(parents=True)
(cfg_dir / "ig_diag_events.json").write_text('{"events": []}', encoding="utf-8")
audit_path = build_dir / "build" / "derived_data" / "Intermediates.noindex" / "readoor31.build" / "ig-route2-audit" / "ig_obfuscation_audit.json"
audit_path.parent.mkdir(parents=True)
audit_path.write_text('{"total_flattened": 65}', encoding="utf-8")
ipa_report = build_dir / "build" / "ipa_audit_report.json"
ipa_report.write_text('{"passed": true}', encoding="utf-8")
with patch("backend.services.build_service.ARTIFACTS_DIR", artifacts_root):
p_dsym, p_maps = persist_task_artifacts("task-persist-1", build_dir, "readoor31")
_cleanup_build_dir(build_dir)
assert not build_dir.exists()
assert p_dsym is not None and p_dsym.is_dir()
assert (p_dsym / "readoor31.app.dSYM" / "Contents" / "Resources" / "DWARF" / "readoor31").is_file()
assert (p_dsym / "IGArchiveGuard.framework.dSYM" / "Contents" / "Resources" / "DWARF" / "IGArchiveGuard").is_file()
assert p_maps is not None and p_maps.is_dir()
assert (p_maps / "symbol_map_readoor31_20261119.json").is_file()
assert (p_maps / "method_map_readoor31_20261119.json").is_file()
assert (p_maps / "ig_diag_events.json").is_file()
assert (p_maps / "ig_obfuscation_audit.json").is_file()
assert (p_maps / "ipa_audit_report.json").is_file()
def test_get_definition_backfills_iosguard_integration_copy_items():
from backend.projects import get_definition
defn = get_definition("readoor", {"patcher": "readoor", "copy_items": ["readoor", "readoor.xcodeproj"]})
assert "iOSGuardIntegration" in defn["copy_items"]
# ---- 分支打包策略:是否混淆 ----
def _policy_snapshot(tmp_path, policy_text=None, with_scripts=False):
build_dir = tmp_path / "snap"
build_dir.mkdir(parents=True)
if with_scripts:
obf = build_dir / "AutoPacking" / "obfuscation"
(obf / "scripts").mkdir(parents=True)
(obf / "obfuscate_symbols.py").write_text("# obf", encoding="utf-8")
(obf / "scripts" / "obfuscation_self_check.sh").write_text("exit 0", encoding="utf-8")
if policy_text is not None:
(build_dir / "AutoPacking").mkdir(exist_ok=True)
(build_dir / "AutoPacking" / "build_policy.json").write_text(policy_text, encoding="utf-8")
return build_dir
@pytest.mark.parametrize("task_obf", [True, False])
def test_obfuscation_forced_when_branch_policy_declares(tmp_path, task_obf):
"""分支 build_policy.json 声明 force_obfuscation=true 时,无视任务勾选强制混淆。"""
from backend.services.build_service import _resolve_obfuscation_decision
build_dir = _policy_snapshot(tmp_path, '{"force_obfuscation": true}', with_scripts=True)
run, reason = _resolve_obfuscation_decision(build_dir, {"obfuscation": True}, MagicMock(obfuscation=task_obf))
assert run is True
assert "声明强制混淆" in reason
@pytest.mark.parametrize("task_obf", [True, False])
def test_old_tag_with_scripts_but_no_policy_follows_task_choice(tmp_path, task_obf):
"""2.195.0 起的旧 Tag 带混淆脚本但无策略文件:按任务勾选,不因脚本存在而强制。"""
from backend.services.build_service import _resolve_obfuscation_decision
build_dir = _policy_snapshot(tmp_path, None, with_scripts=True)
run, reason = _resolve_obfuscation_decision(build_dir, {"obfuscation": True}, MagicMock(obfuscation=task_obf))
assert run is task_obf
assert "按任务勾选" in reason
@pytest.mark.parametrize("policy_text", [
'{"force_obfuscation": false}',
'{"force_obfuscation": "true"}', # 非布尔 true 不算声明
"{broken json",
"[true]",
])
def test_non_forcing_or_invalid_policy_follows_task_choice(tmp_path, policy_text):
from backend.services.build_service import _resolve_obfuscation_decision
build_dir = _policy_snapshot(tmp_path, policy_text)
run, _ = _resolve_obfuscation_decision(build_dir, {"obfuscation": True}, MagicMock(obfuscation=False))
assert run is False
def test_unsupported_project_never_obfuscates_even_if_policy_forces(tmp_path):
from backend.services.build_service import _resolve_obfuscation_decision
build_dir = _policy_snapshot(tmp_path, '{"force_obfuscation": true}')
run, reason = _resolve_obfuscation_decision(build_dir, {"obfuscation": False}, MagicMock(obfuscation=True))
assert run is False
assert "不支持" in reason