Compare commits
9
Commits
10c39b5116
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9449155e4 | ||
|
|
dee9e3a4f2 | ||
|
|
b133b6c28d | ||
|
|
83a1db21e5 | ||
|
|
ab5793631c | ||
|
|
d13fcfcdea | ||
|
|
311234bd74 | ||
|
|
11f4035da7 | ||
|
|
a9e169b00c |
@@ -65,3 +65,19 @@ MAX_RESTART_ATTEMPTS=3
|
||||
|
||||
# 冷却时间(秒),连续重启超限后等待多久再重试
|
||||
COOLDOWN_SECONDS=300
|
||||
|
||||
# ---- iOSGuard LLVM opt 工具链自愈 ----
|
||||
# 工具链缓存目录(默认 DATA_DIR/iosguard_cache/toolchains)
|
||||
# IG_TOOLCHAIN_CACHE_DIR=./backend/data/iosguard_cache/toolchains
|
||||
# swiftlang/llvm-project 仓库地址(可直接访问 GitHub,或替换为内网镜像)
|
||||
IG_LLVM_GIT_MIRROR=https://github.com/swiftlang/llvm-project.git
|
||||
# 最多保留的旧版本 opt 目录数量
|
||||
IG_TOOLCHAIN_KEEP_VERSIONS=3
|
||||
# 每日定时检查 Xcode/opt 兼容性的时间(默认每天 00:00)
|
||||
IG_TOOLCHAIN_DAILY_CHECK_ENABLED=true
|
||||
IG_TOOLCHAIN_DAILY_HOUR=0
|
||||
IG_TOOLCHAIN_DAILY_MINUTE=0
|
||||
# 触发源码重编 opt 时的最长等待时间(秒)
|
||||
IG_TOOLCHAIN_REBUILD_TIMEOUT_SECONDS=2400
|
||||
# 可选:指定包含 iOSGuardIntegration/toolchain 的源码根目录
|
||||
# IG_TOOLCHAIN_SOURCE_DIR=
|
||||
|
||||
@@ -18,6 +18,9 @@ config.json
|
||||
backend/data/config.json
|
||||
ReadoorBranches/
|
||||
build/
|
||||
# iOSGuard 工具链 / SDK / 目标文件缓存(运行时生成,体积大)
|
||||
backend/data/iosguard_cache/
|
||||
backend/data/artifacts/
|
||||
|
||||
# 日志
|
||||
logs/
|
||||
|
||||
@@ -209,7 +209,7 @@ GIT_PASSWORD=<仅 read_repository 权限的 Personal Access Token>
|
||||
| `patcher` | `readoor`:原阅门户专用替换逻辑;`generic`:通用替换(pbxproj 中的版本号、Bundle ID、签名)+ `patch_rules` |
|
||||
| `app_fields` / `server_fields` | App / 服务器环境的自定义字段 `[{key, label, required}]`,表单中显示 |
|
||||
| `patch_rules` | `{"type": "define", "file", "name", "value"}` 替换所有未注释的 `#define name` 行;`{"type": "replace_line", "file", "keyword", "line"}` 整行替换。值可用 `${app.字段}`、`${server.字段}`、`${VERSION}` 等 |
|
||||
| `obfuscation` | 是否支持代码混淆 |
|
||||
| `obfuscation` | 是否支持代码混淆(支持时,是否实际混淆见下方「分支打包策略」) |
|
||||
|
||||
示例(DyAuction:按环境切换 `ISDEV`,`APPID` 按 App 配置):
|
||||
|
||||
@@ -259,7 +259,23 @@ GIT_PASSWORD=<仅 read_repository 权限的 Personal Access Token>
|
||||
|
||||
### 服务端自动化资源
|
||||
|
||||
项目内的 `backend/automation/` 是 Web 打包服务唯一使用的自动化资源:默认皮肤和混淆工具都在此处维护。分支源码中的 `AutoPacking/` 不会被复制、执行或修改,仍可供开发者手动打包使用。
|
||||
项目内的 `backend/automation/` 维护默认皮肤和服务端内置混淆工具。L1 混淆优先使用分支源码自带的 `AutoPacking/obfuscation`(`obfuscate_symbols.py` 与 `scripts/obfuscation_self_check.sh` 同时存在时),保证脚本与分支代码同版本;分支未自带时回退服务端内置脚本,并在打包日志中告警(内置脚本面向新版代码,旧版本混淆失败时可取消勾选混淆后重打)。
|
||||
|
||||
### 分支打包策略(`AutoPacking/build_policy.json`)
|
||||
|
||||
为了能继续打包旧分支/旧 Tag,加固相关的强制行为由**分支自己声明**,随分支代码提交,服务端不按文件是否存在推断:
|
||||
|
||||
```json
|
||||
{ "force_obfuscation": true }
|
||||
```
|
||||
|
||||
| 分支情况 | 是否执行 L1 混淆 |
|
||||
|----------|------------------|
|
||||
| 项目 `obfuscation: false` | 不混淆 |
|
||||
| 分支声明 `"force_obfuscation": true`(必须是布尔 `true`) | 强制混淆,忽略任务页勾选,并把任务记录改为已混淆 |
|
||||
| 无策略文件、未声明、值非 `true` 或 JSON 无法解析(含 2.195.0 起已带混淆脚本的旧 Tag) | 按任务页「启用混淆」勾选(默认勾选) |
|
||||
|
||||
决策结果与原因在打包日志「代码混淆: 启用/不启用(原因)」一行输出。
|
||||
|
||||
### Watchdog 配置
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
SD 鉴权 X-CT=3.2 私钥 CI 加密脚本
|
||||
|
||||
在 Xcode Run Script Build Phase 中调用(仿照同目录 generate_image_whitelist.py 的模式),
|
||||
构建期读取仓库里的原始 PEM 私钥 AutoPacking/sd_priv_ios_v1.pem,用 AES-256-GCM 加密后
|
||||
直接写入当前 target 的 app bundle(${TARGET_BUILD_DIR}/${WRAPPER_NAME}/encrypted_private_key.bin),
|
||||
不经过 Xcode 的 Copy Bundle Resources,早于 CodeSign 执行即可随包一起签名(同 whitelist 脚本的做法)。
|
||||
|
||||
产出格式为 nonce(12字节) + ciphertext + tag(16字节) 拼接,与 Swift 侧 CryptoKit
|
||||
AES.GCM.SealedBox(combined:) 的输入格式完全一致,App 运行时解密见
|
||||
readoor/3.0/Network/RDSDPrivateKeyManager.swift。
|
||||
|
||||
PBKDF2 密钥派生参数必须和 Swift 侧完全一致,见该文件里的
|
||||
pbkdf2Password / pbkdf2Salt / pbkdf2Iterations 常量。
|
||||
|
||||
依赖:cryptography(第三方 Python 包,标准库不自带 AES-GCM)。这是方案文档 §8 记录的一个已知
|
||||
风险,已在本次实现中实测确认:macOS 系统自带的 /usr/bin/openssl 是 LibreSSL 3.3.6,其 enc
|
||||
子命令对 -aes-256-gcm 直接报 "bad decrypt",openssl 命令行方案不可行;改用 cryptography 包
|
||||
经端到端验证(Xcode Run Script Build Phase 实际跑通、产出的密文能正确解密回原始 PEM)确认可行,
|
||||
但需要在每台构建机(含 iOSBuildServer)上为 Xcode 实际调用的 python3(通常是
|
||||
/usr/bin/python3,Xcode 自带的 3.9)显式安装该依赖:
|
||||
/usr/bin/python3 -m pip install --user cryptography
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
except ImportError:
|
||||
sys.stderr.write(
|
||||
"[sd_v32] 缺少 cryptography 包,无法加密私钥。\n"
|
||||
"[sd_v32] 请在构建机上执行: /usr/bin/python3 -m pip install --user cryptography\n"
|
||||
"[sd_v32] (macOS 系统自带 openssl 是 LibreSSL,不支持 aes-256-gcm,已确认不可用作替代方案)\n"
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
# 必须和 RDSDPrivateKeyManager.swift 里的同名常量保持一致
|
||||
PBKDF2_PASSWORD = b"readoor_sd_v32_ci_key_2026"
|
||||
PBKDF2_SALT = b"readoor_sd_v32_salt_fixed"
|
||||
PBKDF2_ITERATIONS = 100_000
|
||||
AES_KEY_LENGTH = 32 # AES-256
|
||||
NONCE_LENGTH = 12 # 与 CryptoKit AES.GCM 默认 nonce 长度一致
|
||||
|
||||
|
||||
def derive_key() -> bytes:
|
||||
return hashlib.pbkdf2_hmac(
|
||||
"sha256", PBKDF2_PASSWORD, PBKDF2_SALT, PBKDF2_ITERATIONS, dklen=AES_KEY_LENGTH
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
srcroot = os.environ.get("SRCROOT")
|
||||
if not srcroot:
|
||||
# 允许手动执行时退回脚本所在目录向上两级推断项目根目录
|
||||
srcroot = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
||||
|
||||
private_key_path = os.path.join(srcroot, "AutoPacking", "sd_priv_ios_v1.pem")
|
||||
if not os.path.isfile(private_key_path):
|
||||
sys.stderr.write(f"[sd_v32] 未找到私钥文件: {private_key_path}\n")
|
||||
return 1
|
||||
|
||||
with open(private_key_path, "rb") as f:
|
||||
plaintext = f.read()
|
||||
|
||||
key = derive_key()
|
||||
nonce = os.urandom(NONCE_LENGTH)
|
||||
ciphertext_with_tag = AESGCM(key).encrypt(nonce, plaintext, None)
|
||||
combined = nonce + ciphertext_with_tag
|
||||
|
||||
target_build_dir = os.environ.get("TARGET_BUILD_DIR")
|
||||
wrapper_name = os.environ.get("WRAPPER_NAME")
|
||||
if target_build_dir and wrapper_name:
|
||||
# Xcode Build Phase 场景:直接写进当前 target 的 app bundle,早于 CodeSign 执行
|
||||
output_dir = os.path.join(target_build_dir, wrapper_name)
|
||||
else:
|
||||
# 手动执行场景:写到项目根目录,方便本地验证加解密是否正确
|
||||
output_dir = srcroot
|
||||
|
||||
output_path = os.path.join(output_dir, "rd_glyph_lut_v2.dat")
|
||||
for stale_name in ("rd_net_cfg_v1.dat", "encrypted_private_key.bin"):
|
||||
stale_path = os.path.join(output_dir, stale_name)
|
||||
if os.path.isfile(stale_path):
|
||||
os.remove(stale_path)
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(combined)
|
||||
|
||||
print(f"[sd_v32] asset written: {output_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -72,9 +72,9 @@ def scan_bundled_images(app_bundle_path, executable_path):
|
||||
seen = set()
|
||||
|
||||
executable_name = Path(executable_path).name if executable_path else Path(app_bundle_path).stem
|
||||
main_key = (executable_name, executable_path or executable_name)
|
||||
main_key = (executable_name, executable_name)
|
||||
seen.add(main_key)
|
||||
known.append({'name': executable_name, 'path': executable_path or executable_name})
|
||||
known.append({'name': executable_name, 'path': executable_name})
|
||||
|
||||
for root, dirs, files in os.walk(app_bundle_path):
|
||||
dirs.sort()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -44,7 +44,12 @@ def build_canonical_symbol_tables(
|
||||
swift_signatures.update(method_data["swift_signatures"])
|
||||
|
||||
canonical = {
|
||||
"swift_symbols": sorted(swift_symbols),
|
||||
"swift_symbols": [
|
||||
name for name in sorted(swift_symbols)
|
||||
if not already_obfuscated_re.match(name)
|
||||
and name not in symbol_whitelist
|
||||
and not name.startswith(symbol_prefix_whitelist)
|
||||
],
|
||||
"objc_symbols": [
|
||||
name for name in sorted(objc_symbols)
|
||||
if any(name.startswith(prefix) for prefix in objc_symbol_prefixes)
|
||||
@@ -107,13 +112,24 @@ def build_type_mappings_from_canonical_table(canonical_tables: dict, salt: str,
|
||||
return mapping_swift, mapping_objc
|
||||
|
||||
|
||||
def build_method_mapping_from_canonical_table(canonical_tables: dict, salt: str, *, build_unique_mapping, method_prefix: str) -> dict:
|
||||
def build_method_mapping_from_canonical_table(canonical_tables: dict, salt: str, *, build_unique_mapping, method_prefix: str, build_method_entries=None) -> dict:
|
||||
swift_signature_mapping = canonical_tables.get("swift_signatures", {})
|
||||
direct_methods = list(canonical_tables.get("direct_methods", []))
|
||||
objc_selectors = list(canonical_tables.get("objc_selectors", []))
|
||||
|
||||
if build_method_entries is not None:
|
||||
return build_method_entries(
|
||||
direct_methods=direct_methods,
|
||||
objc_selectors=objc_selectors,
|
||||
swift_signatures=swift_signature_mapping,
|
||||
salt=salt,
|
||||
)
|
||||
|
||||
ordered_names = []
|
||||
seen = set()
|
||||
for bucket in (
|
||||
canonical_tables.get("direct_methods", []),
|
||||
canonical_tables.get("objc_selectors", []),
|
||||
direct_methods,
|
||||
objc_selectors,
|
||||
sorted(swift_signature_mapping.keys()),
|
||||
):
|
||||
for name in bucket:
|
||||
@@ -125,12 +141,12 @@ def build_method_mapping_from_canonical_table(canonical_tables: dict, salt: str,
|
||||
combined_tokens = build_unique_mapping(ordered_names, salt, prefix=method_prefix)
|
||||
method_mapping = {
|
||||
name: combined_tokens[name]
|
||||
for name in canonical_tables.get("direct_methods", [])
|
||||
for name in direct_methods
|
||||
if name in combined_tokens
|
||||
}
|
||||
method_mapping.update({
|
||||
name: combined_tokens[name]
|
||||
for name in canonical_tables.get("objc_selectors", [])
|
||||
for name in objc_selectors
|
||||
if name in combined_tokens
|
||||
})
|
||||
|
||||
|
||||
@@ -15,6 +15,33 @@ def should_exclude_path(path: str, exclude_path_fragments) -> bool:
|
||||
return any(fragment in path for fragment in exclude_path_fragments)
|
||||
|
||||
|
||||
def _rel_path_within_scan_dir(path: str, scan_dir: str) -> str:
|
||||
"""将 path 转为相对 scan_dir 的路径,避免上层工作目录名(如 build/)触发误排除。"""
|
||||
try:
|
||||
rel = os.path.relpath(os.path.abspath(path), os.path.abspath(scan_dir))
|
||||
except ValueError:
|
||||
return path
|
||||
if rel == ".":
|
||||
return ""
|
||||
if rel == ".." or rel.startswith(".." + os.sep):
|
||||
return path
|
||||
return rel
|
||||
|
||||
|
||||
def _rel_path_for_filter(path: str, scan_dirs: list) -> str:
|
||||
abs_path = os.path.abspath(path)
|
||||
best_rel = None
|
||||
best_len = -1
|
||||
for scan_dir in scan_dirs:
|
||||
abs_scan = os.path.abspath(scan_dir)
|
||||
prefix = abs_scan.rstrip(os.sep) + os.sep
|
||||
if abs_path == abs_scan or abs_path.startswith(prefix):
|
||||
if len(abs_scan) > best_len:
|
||||
best_len = len(abs_scan)
|
||||
best_rel = _rel_path_within_scan_dir(abs_path, abs_scan)
|
||||
return best_rel if best_rel is not None else path
|
||||
|
||||
|
||||
def _run_command_capture_stdout(args: list) -> str:
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
@@ -40,7 +67,8 @@ def _discover_files_via_os_walk(scan_dirs: list, allowed_exts: tuple, exclude_pa
|
||||
directory for directory in dirs
|
||||
if not any(fragment.strip("/") in directory for fragment in exclude_path_fragments)
|
||||
]
|
||||
if path_matches_dir_names(root, skip_dir_names):
|
||||
rel_root = _rel_path_within_scan_dir(root, scan_dir)
|
||||
if path_matches_dir_names(rel_root, skip_dir_names):
|
||||
continue
|
||||
for filename in filenames:
|
||||
ext = os.path.splitext(filename)[1]
|
||||
@@ -50,15 +78,18 @@ def _discover_files_via_os_walk(scan_dirs: list, allowed_exts: tuple, exclude_pa
|
||||
if basename_prefixes and not any(name_no_ext.startswith(prefix) for prefix in basename_prefixes):
|
||||
continue
|
||||
full_path = os.path.normpath(os.path.join(root, filename))
|
||||
if should_exclude_path(full_path, exclude_path_fragments):
|
||||
rel_file = _rel_path_within_scan_dir(full_path, scan_dir)
|
||||
if should_exclude_path(rel_file, exclude_path_fragments):
|
||||
continue
|
||||
if path_matches_dir_names(full_path, skip_dir_names):
|
||||
if path_matches_dir_names(rel_file, skip_dir_names):
|
||||
continue
|
||||
files.append(full_path)
|
||||
return sorted(set(files))
|
||||
|
||||
|
||||
def _discover_files_via_rg(scan_dirs: list, allowed_exts: tuple, exclude_path_fragments, skip_dir_names: tuple = (), basename_prefixes: tuple = ()) -> list:
|
||||
if not scan_dirs:
|
||||
return []
|
||||
rg = shutil.which("rg")
|
||||
if not rg:
|
||||
return []
|
||||
@@ -75,9 +106,12 @@ def _discover_files_via_rg(scan_dirs: list, allowed_exts: tuple, exclude_path_fr
|
||||
files = []
|
||||
for line in output.splitlines():
|
||||
path = os.path.normpath(line.strip())
|
||||
if not path or should_exclude_path(path, exclude_path_fragments):
|
||||
if not path:
|
||||
continue
|
||||
if path_matches_dir_names(path, skip_dir_names):
|
||||
rel_path = _rel_path_for_filter(path, scan_dirs)
|
||||
if should_exclude_path(rel_path, exclude_path_fragments):
|
||||
continue
|
||||
if path_matches_dir_names(rel_path, skip_dir_names):
|
||||
continue
|
||||
if basename_prefixes:
|
||||
name_no_ext = os.path.splitext(os.path.basename(path))[0]
|
||||
@@ -89,6 +123,8 @@ def _discover_files_via_rg(scan_dirs: list, allowed_exts: tuple, exclude_path_fr
|
||||
|
||||
|
||||
def discover_files(scan_dirs: list, allowed_exts: tuple, exclude_path_fragments, skip_dir_names: tuple = (), basename_prefixes: tuple = ()) -> list:
|
||||
if not scan_dirs:
|
||||
return []
|
||||
files = _discover_files_via_rg(
|
||||
scan_dirs,
|
||||
allowed_exts,
|
||||
|
||||
@@ -23,7 +23,7 @@ STAMP="$(date +%Y%m%d_%H%M%S)"
|
||||
BACKUP_DIR="${DERIVED_DIR}/rd_obf_backup_${STAMP}"
|
||||
MARKER_FILE="${DERIVED_DIR}/rd_obf_marker_${TARGET_NAME:-app}.env"
|
||||
MAP_DIR="${ROOT}/obfuscation_maps"
|
||||
MAP_PATH="${MAP_DIR}/${TARGET_NAME:-app}_${STAMP}.json"
|
||||
MAP_PATH="${MAP_DIR}/symbol_map_${TARGET_NAME:-app}_${STAMP}.json"
|
||||
METHOD_MAP_PATH="${MAP_DIR}/method_map_${TARGET_NAME:-app}_${STAMP}.json"
|
||||
PRE_SUCCESS=0
|
||||
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Scan repository for residual obfuscated tokens like RdXXXXXX and fail if any found.
|
||||
# Scan repository for residual obfuscated tokens (both legacy Rd/YMH/ymh<hex> and curated natural CamelCase stems)
|
||||
# Exits 0 when clean, non-zero when tokens are present.
|
||||
|
||||
ROOT="${1:-$(cd "$(dirname "$0")/../../.." && pwd)}"
|
||||
|
||||
echo "[obf-check] Scanning for residual obfuscated tokens in ${ROOT}"
|
||||
|
||||
EXCLUDE=("./Pods" "./.git" "./obfuscation_maps" "./build_output" "./DerivedData" "./readoorTests")
|
||||
EXCLUDE=(
|
||||
"./Pods"
|
||||
"./.git"
|
||||
"./obfuscation_maps"
|
||||
"./build_output"
|
||||
"./DerivedData"
|
||||
"./readoorTests"
|
||||
"./iOSGuardIntegration"
|
||||
"./Factorys"
|
||||
"./AutoPacking"
|
||||
)
|
||||
|
||||
GREP_EXCLUDE_ARGS=()
|
||||
for e in "${EXCLUDE[@]}"; do
|
||||
@@ -16,15 +26,23 @@ for e in "${EXCLUDE[@]}"; do
|
||||
done
|
||||
|
||||
FOUND=0
|
||||
TOKEN_SUFFIX_RE='(?:[a-f0-9]{6}|[a-f0-9]{8}|[a-f0-9]{10})'
|
||||
TOKEN_SUFFIX_RE='([a-f0-9]{6}|[a-f0-9]{8}|[a-f0-9]{10})'
|
||||
STEM_GROUP='(Breeze|Birch|Canopy|Cobalt|Harbor|Kestrel|Linden|Lumen|Meadow|Meridian|Osprey|Prism|Solace|Summit|Timber|Zephyr)'
|
||||
NATURAL_TYPE_RE="\\b${STEM_GROUP}[A-Z][a-z]+([A-Z][a-z]+)+\\b"
|
||||
NATURAL_METHOD_RE="\\b[a-z]+${STEM_GROUP}[A-Z][A-Za-z]+\\b"
|
||||
|
||||
echo "[obf-check] Looking for token pattern '\b(?:Rd|YMH)${TOKEN_SUFFIX_RE}\b' in source files..."
|
||||
if grep -R --line-number -E "\\b(?:Rd|YMH)${TOKEN_SUFFIX_RE}\\b" --include='*.swift' --include='*.m' --include='*.mm' --include='*.h' "${ROOT}" "${GREP_EXCLUDE_ARGS[@]}"; then
|
||||
echo "[obf-check] Looking for legacy token pattern '\\b(Rd|YMH|ymh)${TOKEN_SUFFIX_RE}\\b' in source files..."
|
||||
if grep -R --line-number -E "\\b(Rd|YMH|ymh)${TOKEN_SUFFIX_RE}\\b" --include='*.swift' --include='*.m' --include='*.mm' --include='*.h' "${GREP_EXCLUDE_ARGS[@]}" "${ROOT}"; then
|
||||
FOUND=1
|
||||
fi
|
||||
|
||||
echo "[obf-check] Looking for natural CamelCase obfuscated tokens in source files..."
|
||||
if grep -R --line-number -E "${NATURAL_TYPE_RE}|${NATURAL_METHOD_RE}" --include='*.swift' --include='*.m' --include='*.mm' --include='*.h' "${GREP_EXCLUDE_ARGS[@]}" "${ROOT}"; then
|
||||
FOUND=1
|
||||
fi
|
||||
|
||||
echo "[obf-check] Looking for obfuscated header imports like \"(Rd|YMH)XXXXXX.h\"..."
|
||||
if grep -R --line-number -E "#import\\s+\"(?:Rd|YMH)${TOKEN_SUFFIX_RE}\\.h\"" --include='*.pch' --include='*.h' --include='*.m' --include='*.mm' "${ROOT}" "${GREP_EXCLUDE_ARGS[@]}"; then
|
||||
if grep -R --line-number -E "#import\\s+\"(Rd|YMH)${TOKEN_SUFFIX_RE}\\.h\"" --include='*.pch' --include='*.h' --include='*.m' --include='*.mm' "${GREP_EXCLUDE_ARGS[@]}" "${ROOT}"; then
|
||||
FOUND=1
|
||||
fi
|
||||
|
||||
|
||||
@@ -44,6 +44,28 @@ CONFIG_JSON_PATH = DATA_DIR / "config.json"
|
||||
# 皮肤包存储目录(持久化,不随分支变化)
|
||||
SKINS_DIR = DATA_DIR / "skins"
|
||||
|
||||
# 构建产物的持久化归档目录(.dSYM、混淆映射表、诊断事件与混淆审计;不随 build_dir 清理销毁)
|
||||
ARTIFACTS_DIR = _resolve_server_path(os.getenv("ARTIFACTS_DIR", str(DATA_DIR / "artifacts")))
|
||||
ARTIFACTS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 跨构建持久化 LLVM IR 对象缓存与 Route 2 静态 SDK 缓存(在每任务 xcodebuild clean 下保持热缓存复用)
|
||||
IG_CACHE_DIR = _resolve_server_path(os.getenv("IG_CACHE_DIR", str(DATA_DIR / "iosguard_cache")))
|
||||
IG_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
DEFAULT_IG_OBF_MODE = os.getenv("IG_OBF_MODE", "full")
|
||||
|
||||
# 自愈 LLVM opt 工具链缓存、每日检查计划与自动重编配置
|
||||
IG_TOOLCHAIN_CACHE_DIR = _resolve_server_path(os.getenv("IG_TOOLCHAIN_CACHE_DIR", str(IG_CACHE_DIR / "toolchains")))
|
||||
IG_TOOLCHAIN_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
IG_LLVM_GIT_MIRROR = os.getenv("IG_LLVM_GIT_MIRROR", "https://github.com/swiftlang/llvm-project.git")
|
||||
IG_TOOLCHAIN_KEEP_VERSIONS = int(os.getenv("IG_TOOLCHAIN_KEEP_VERSIONS", "3"))
|
||||
IG_TOOLCHAIN_DAILY_CHECK_ENABLED = os.getenv("IG_TOOLCHAIN_DAILY_CHECK_ENABLED", "true").lower() in (
|
||||
"1", "true", "yes", "on",
|
||||
)
|
||||
IG_TOOLCHAIN_DAILY_HOUR = int(os.getenv("IG_TOOLCHAIN_DAILY_HOUR", "0"))
|
||||
IG_TOOLCHAIN_DAILY_MINUTE = int(os.getenv("IG_TOOLCHAIN_DAILY_MINUTE", "0"))
|
||||
IG_TOOLCHAIN_REBUILD_TIMEOUT_SECONDS = int(os.getenv("IG_TOOLCHAIN_REBUILD_TIMEOUT_SECONDS", "2400"))
|
||||
IG_TOOLCHAIN_SOURCE_DIR = os.getenv("IG_TOOLCHAIN_SOURCE_DIR", "").strip()
|
||||
|
||||
# 打包基础目录
|
||||
BUILD_BASE_DIR = _resolve_server_path(os.getenv("BUILD_BASE_DIR", str(SERVER_ROOT / "build")))
|
||||
|
||||
@@ -108,6 +130,7 @@ COPY_ITEMS = [
|
||||
"readoorTests",
|
||||
"Vendor",
|
||||
"AutoPacking",
|
||||
"iOSGuardIntegration",
|
||||
"Podfile",
|
||||
"Pods",
|
||||
"Podfile.lock",
|
||||
|
||||
@@ -22,6 +22,7 @@ def get_db():
|
||||
def _migrate_db():
|
||||
"""简单的数据库迁移:为旧表添加缺失的列"""
|
||||
migrations = [
|
||||
("tasks", "exclude_symbols", "BOOLEAN DEFAULT 0"),
|
||||
("tasks", "branch", "VARCHAR DEFAULT 'main'"),
|
||||
("tasks", "ref_type", "VARCHAR DEFAULT 'branch'"),
|
||||
("tasks", "error_category", "VARCHAR"),
|
||||
|
||||
+20
-3
@@ -1,5 +1,6 @@
|
||||
"""FastAPI 主入口"""
|
||||
from contextlib import asynccontextmanager
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager, suppress
|
||||
from pathlib import Path
|
||||
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, status
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
@@ -10,7 +11,14 @@ from fastapi.responses import FileResponse
|
||||
from .database import init_db
|
||||
from .routers import config, apps, tasks, auth, users, operations
|
||||
from .services.log_streamer import log_streamer
|
||||
from .config import BACKEND_PORT, CORS_ALLOWED_ORIGINS, TRUSTED_HOSTS, validate_production_security
|
||||
from .services.toolchain_manager import midnight_toolchain_scheduler
|
||||
from .config import (
|
||||
BACKEND_PORT,
|
||||
CORS_ALLOWED_ORIGINS,
|
||||
IG_TOOLCHAIN_DAILY_CHECK_ENABLED,
|
||||
TRUSTED_HOSTS,
|
||||
validate_production_security,
|
||||
)
|
||||
from .deps import decode_current_user
|
||||
from .projects import PROJECT_HEADER, current_project_id
|
||||
|
||||
@@ -22,7 +30,16 @@ async def lifespan(app: FastAPI):
|
||||
"""应用生命周期"""
|
||||
validate_production_security()
|
||||
init_db()
|
||||
yield
|
||||
scheduler_task = None
|
||||
if IG_TOOLCHAIN_DAILY_CHECK_ENABLED:
|
||||
scheduler_task = asyncio.create_task(midnight_toolchain_scheduler())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if scheduler_task is not None:
|
||||
scheduler_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await scheduler_task
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
|
||||
@@ -15,6 +15,7 @@ class Task(Base):
|
||||
build_type = Column(String, nullable=False)
|
||||
scheme_id = Column(String, nullable=False)
|
||||
scheme_name = Column(String, nullable=False)
|
||||
exclude_symbols = Column(Boolean, default=False)
|
||||
obfuscation = Column(Boolean, default=False)
|
||||
branch = Column(String, default="main") # 分支名或 Tag 名,由 ref_type 区分
|
||||
ref_type = Column(String, default="branch") # branch/tag
|
||||
|
||||
@@ -68,6 +68,16 @@ LEGACY_PROJECT_DEFINITION = {
|
||||
"dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []},
|
||||
}
|
||||
|
||||
# 英汉大词典(readoorDict,TARGETTYPE == 2)的服务器地址:Readoor 项目的服务器环境内置这些字段,
|
||||
# 打包时写入 STSConstantsMacro.h 中 TARGETTYPE == 2 段落的同名宏(字段名去掉 DICT_ 前缀即宏名)。
|
||||
READOOR_DICT_SERVER_FIELDS = [
|
||||
{"key": "DICT_SERVERURL", "label": "词典 SERVERURL", "required": False},
|
||||
{"key": "DICT_SERVERHTTPSURL", "label": "词典 SERVERHTTPSURL", "required": False},
|
||||
{"key": "DICT_UCSERVERURL", "label": "词典 UCSERVERURL", "required": False},
|
||||
{"key": "DICT_RECORDSERVERURL", "label": "词典 RECORDSERVERURL", "required": False},
|
||||
{"key": "DICT_LOGSERVERURL", "label": "词典 LOGSERVERURL", "required": False},
|
||||
]
|
||||
|
||||
# 当前请求操作的项目,由 main.py 的中间件按请求头 X-Project 设置;
|
||||
# load_config() 未显式指定项目时使用它,未设置则取第一个项目。
|
||||
PROJECT_HEADER = "X-Project"
|
||||
@@ -104,11 +114,23 @@ def get_definition(project_id: str, project: dict) -> dict:
|
||||
"""取项目定义,缺失字段用缺省值补齐(只读,不写回配置)。"""
|
||||
defaults = default_definition(project_id)
|
||||
definition = {key: project.get(key, defaults[key]) for key in DEFINITION_KEYS}
|
||||
definition["copy_items"] = list(definition.get("copy_items") or [])
|
||||
if (
|
||||
(project_id == LEGACY_PROJECT_ID or definition.get("patcher") == PATCHER_READOOR)
|
||||
and definition["copy_items"]
|
||||
and "iOSGuardIntegration" not in definition["copy_items"]
|
||||
):
|
||||
definition["copy_items"].append("iOSGuardIntegration")
|
||||
definition["git"] = {**defaults["git"], **(definition.get("git") or {})}
|
||||
definition["xcode"] = {**defaults["xcode"], **(definition.get("xcode") or {})}
|
||||
definition["dingtalk_at"] = {**defaults["dingtalk_at"], **(definition.get("dingtalk_at") or {})}
|
||||
if definition["patcher"] not in PATCHERS:
|
||||
definition["patcher"] = PATCHER_GENERIC
|
||||
if definition["patcher"] == PATCHER_READOOR:
|
||||
keys = {field.get("key") for field in definition["server_fields"]}
|
||||
definition["server_fields"] = list(definition["server_fields"]) + [
|
||||
dict(field) for field in READOOR_DICT_SERVER_FIELDS if field["key"] not in keys
|
||||
]
|
||||
return definition
|
||||
|
||||
|
||||
|
||||
@@ -1441,3 +1441,40 @@ async def delete_project(project_id: str):
|
||||
del root["projects"][project_id]
|
||||
_write_root(root)
|
||||
return {"message": "项目已删除"}
|
||||
|
||||
|
||||
@router.get("/toolchain")
|
||||
async def get_toolchain_info():
|
||||
"""查看当前打包机 Xcode 与 iOSGuard LLVM opt 工具链缓存状态(仅管理员)。"""
|
||||
from ..services.toolchain_manager import get_toolchain_status
|
||||
|
||||
return await get_toolchain_status()
|
||||
|
||||
|
||||
@router.post("/toolchain/refresh")
|
||||
async def refresh_toolchain(request: Request):
|
||||
"""手动触发 Xcode / opt 工具链校验与更新,可选传 {\"force_rebuild\": true}(仅管理员)。"""
|
||||
from ..services.toolchain_manager import discover_toolchain_resolver, ensure_toolchain
|
||||
|
||||
force_rebuild = False
|
||||
try:
|
||||
body = await request.json()
|
||||
if isinstance(body, dict):
|
||||
force_rebuild = bool(body.get("force_rebuild", False))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
resolver = discover_toolchain_resolver()
|
||||
if resolver is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="未找到 iOSGuard 工具链脚本,请先同步 Readoor 源码或配置 IG_TOOLCHAIN_SOURCE_DIR",
|
||||
)
|
||||
try:
|
||||
return await ensure_toolchain(
|
||||
resolver,
|
||||
force_rebuild=force_rebuild,
|
||||
notify_on_event=True,
|
||||
)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
@@ -12,6 +12,7 @@ from fastapi.responses import FileResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import ARTIFACTS_DIR
|
||||
from ..database import get_db
|
||||
from ..models import Task
|
||||
from ..schemas import TaskCreate, TaskResponse
|
||||
@@ -57,8 +58,11 @@ async def create_task(task: TaskCreate, request: Request, user: dict = Depends(g
|
||||
|
||||
project_id = config["_project"]
|
||||
from ..projects import get_definition
|
||||
if task.obfuscation and not get_definition(project_id, config)["obfuscation"]:
|
||||
supports_obfuscation = bool(get_definition(project_id, config)["obfuscation"])
|
||||
if task.obfuscation and not supports_obfuscation:
|
||||
raise HTTPException(status_code=400, detail="该项目不支持代码混淆")
|
||||
# 记录用户勾选;分支 build_policy.json 声明强制混淆时,打包阶段会覆盖为启用并写回。
|
||||
effective_obfuscation = bool(task.obfuscation) and supports_obfuscation
|
||||
|
||||
# 分支与 Tag 不允许重名,按名字即可确定要检出的引用类型
|
||||
from .config import get_ref_type
|
||||
@@ -73,7 +77,8 @@ async def create_task(task: TaskCreate, request: Request, user: dict = Depends(g
|
||||
build_type=task.build_type,
|
||||
scheme_id=task.scheme_id,
|
||||
scheme_name=scheme.get("displayName") or scheme_name,
|
||||
obfuscation=task.obfuscation,
|
||||
exclude_symbols=task.build_type == "App_Store" and task.exclude_symbols,
|
||||
obfuscation=effective_obfuscation,
|
||||
branch=task.branch,
|
||||
ref_type=ref_type,
|
||||
status="pending",
|
||||
@@ -177,6 +182,9 @@ async def cancel_task(task_id: str, request: Request, user: dict = Depends(get_c
|
||||
build_path = Path(task.build_dir)
|
||||
if build_path.exists():
|
||||
shutil.rmtree(build_path, ignore_errors=True)
|
||||
task_artifacts = ARTIFACTS_DIR / task_id
|
||||
if task_artifacts.exists():
|
||||
shutil.rmtree(task_artifacts, ignore_errors=True)
|
||||
|
||||
return {"message": "任务已取消"}
|
||||
|
||||
@@ -241,11 +249,14 @@ async def delete_task(task_id: str, request: Request, user: dict = Depends(get_c
|
||||
if log_path.exists():
|
||||
log_path.unlink()
|
||||
|
||||
# 删除构建目录
|
||||
# 删除构建目录及持久化产物目录
|
||||
if task.build_dir:
|
||||
build_path = Path(task.build_dir)
|
||||
if build_path.exists():
|
||||
shutil.rmtree(build_path, ignore_errors=True)
|
||||
task_artifacts = ARTIFACTS_DIR / task_id
|
||||
if task_artifacts.exists():
|
||||
shutil.rmtree(task_artifacts, ignore_errors=True)
|
||||
|
||||
from ..services.audit_log import record_operation
|
||||
record_operation(db, user, "task_deleted", request=request, task=task)
|
||||
@@ -371,16 +382,22 @@ async def download_dsym(task_id: str, request: Request, user: dict = Depends(get
|
||||
raise HTTPException(status_code=502, detail=f"生成下载链接失败:{exc}") from exc
|
||||
return {"url": download_url}
|
||||
|
||||
# .dSYM 是目录(macOS bundle),需要压缩为 zip 再下载
|
||||
# .dSYM 是目录(macOS bundle 或包含 App + IGArchiveGuard.framework 的 dSYMs 目录),需要压缩为 zip 再下载
|
||||
if os.path.isdir(dsym_path):
|
||||
zip_path = os.path.join(tempfile.gettempdir(), os.path.basename(dsym_path) + ".zip")
|
||||
fd, zip_path = tempfile.mkstemp(suffix=".zip")
|
||||
os.close(fd)
|
||||
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||
for root, dirs, files in os.walk(dsym_path):
|
||||
for f in files:
|
||||
full = os.path.join(root, f)
|
||||
arcname = os.path.relpath(full, os.path.dirname(dsym_path))
|
||||
zf.write(full, arcname)
|
||||
return FileResponse(zip_path, filename=os.path.basename(zip_path), media_type="application/zip")
|
||||
return FileResponse(
|
||||
zip_path,
|
||||
filename=os.path.basename(dsym_path) + ".zip",
|
||||
media_type="application/zip",
|
||||
background=BackgroundTask(os.remove, zip_path),
|
||||
)
|
||||
|
||||
return FileResponse(dsym_path, filename=os.path.basename(dsym_path))
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ class TaskCreate(BaseModel):
|
||||
app_id: str
|
||||
build_type: str
|
||||
scheme_id: str
|
||||
exclude_symbols: bool = False
|
||||
obfuscation: bool = False
|
||||
branch: str = "main"
|
||||
|
||||
|
||||
@@ -6,15 +6,21 @@ import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
from typing import List, Optional
|
||||
|
||||
from ..config import (
|
||||
ARTIFACTS_DIR,
|
||||
BUILD_BASE_DIR,
|
||||
DEFAULT_BUILD_DIR_RETENTION_HOURS,
|
||||
DEFAULT_IG_OBF_MODE,
|
||||
BUILD_TIMEOUT_HOURS,
|
||||
IG_CACHE_DIR,
|
||||
IG_TOOLCHAIN_CACHE_DIR,
|
||||
SKINS_DIR,
|
||||
AUTOMATION_DIR,
|
||||
get_git_remote_url,
|
||||
@@ -25,6 +31,7 @@ from .log_streamer import log_streamer
|
||||
from .distribution import DistributionError, publish_dsym, publish_ipa
|
||||
from .notification import NotificationError, merge_project_at_mobiles, send_dingtalk_notification
|
||||
from .project_patcher import ProjectPatchError, apply_project_config
|
||||
from .toolchain_manager import ensure_toolchain
|
||||
|
||||
|
||||
class BuildError(Exception):
|
||||
@@ -164,18 +171,19 @@ def _resolve_provisioning_profile(profile_reference: str) -> tuple[str, str]:
|
||||
_ERROR_RULES = [
|
||||
(["No signing certificate", "Signing certificate \"", "Code Signing Error",
|
||||
"Code Sign error", "errSecInternalComponent", "CSSMERR_TP_NOT_TRUSTED",
|
||||
"iPhone Distribution", "iPhone Developer: no identity found"],
|
||||
"iPhone Distribution: no identity found", "iPhone Developer: no identity found"],
|
||||
"certificate", "签名证书问题:证书过期、未安装或不匹配,请检查钥匙串中的证书"),
|
||||
(["Provisioning profile", "No matching provisioning profiles",
|
||||
"embedded.mobileprovision", "PROVISIONING_PROFILE_SPECIFIER",
|
||||
"provisioning profile", "No matching",
|
||||
"requires a provisioning profile"],
|
||||
(["No matching provisioning profiles", "requires a provisioning profile",
|
||||
"No profiles for", "provisioning profile has expired",
|
||||
"doesn't include signing certificate", "doesn't match the entitlements",
|
||||
"doesn't support the"],
|
||||
"provisioning", "描述文件问题:描述文件过期、不匹配或未安装,请检查 Apple Developer 后台"),
|
||||
(["Undefined symbols", "linker command failed", "ld: symbol(s) not found",
|
||||
"ld: framework not found for"],
|
||||
"compilation", "链接错误:符号未定义或框架缺失,请检查代码引用"),
|
||||
(["Swift Compiler Error", "Use of undeclared identifier",
|
||||
"cannot find type", "cannot find symbol in scope", "no such module"],
|
||||
"cannot find type", "cannot find symbol in scope", "no such module",
|
||||
"does not conform to protocol"],
|
||||
"compilation", "Swift 编译错误:请检查代码语法和类型引用"),
|
||||
([" error:", "fatal error:"],
|
||||
"compilation", "代码编译错误:请检查代码是否有语法或类型错误"),
|
||||
@@ -209,6 +217,10 @@ def _classify_build_error(output_lines: list, step: str) -> tuple:
|
||||
"""
|
||||
output_text = "\n".join(output_lines)
|
||||
|
||||
missing_script = re.search(r"""can't open file ['"]([^'"]+)['"]: \[Errno 2\] No such file or directory""", output_text)
|
||||
if missing_script:
|
||||
return "config", f"构建脚本缺失:{missing_script.group(1)},请检查源码拷贝配置"
|
||||
|
||||
for keywords, category, hint in _ERROR_RULES:
|
||||
for kw in keywords:
|
||||
if kw.lower() in output_text.lower():
|
||||
@@ -276,6 +288,9 @@ def _cleanup_superseded_tasks(db):
|
||||
log_path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
task_artifacts_dir = ARTIFACTS_DIR / task.id
|
||||
if task_artifacts_dir.exists():
|
||||
shutil.rmtree(task_artifacts_dir, ignore_errors=True)
|
||||
db.delete(task)
|
||||
if tasks:
|
||||
db.commit()
|
||||
@@ -474,7 +489,7 @@ async def run_build_task(task_id: str):
|
||||
try:
|
||||
timeout_seconds = BUILD_TIMEOUT_HOURS * 3600
|
||||
|
||||
async def _do_build():
|
||||
async def _prepare_until_obfuscation():
|
||||
nonlocal build_dir
|
||||
# 1. 串行准备源码快照;后续步骤在任务独立目录中并行执行。
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="source_prepare")
|
||||
@@ -482,6 +497,13 @@ async def run_build_task(task_id: str):
|
||||
build_dir, source_commit = await prepare_source_snapshot(task_id, task)
|
||||
await asyncio.to_thread(_db_update, db, task, build_dir=str(build_dir))
|
||||
|
||||
# 1.5 按分支自身声明决定是否混淆:分支 build_policy.json 声明强制时必混淆,
|
||||
# 否则沿用任务勾选(兼容旧分支/旧 Tag)。先于生成配置写回,保证 ENABLE_OBFUSCATION 与实际一致。
|
||||
run_obf, obf_reason = _resolve_obfuscation_decision(build_dir, definition, task)
|
||||
await log_streamer.emit(task_id, f"代码混淆: {'启用' if run_obf else '不启用'}({obf_reason})")
|
||||
if bool(task.obfuscation) != run_obf:
|
||||
await asyncio.to_thread(_db_update, db, task, obfuscation=run_obf)
|
||||
|
||||
# 2. 生成配置
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="config")
|
||||
config_data = await generate_config(task_id, task, build_dir)
|
||||
@@ -499,26 +521,43 @@ async def run_build_task(task_id: str):
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="pod_install")
|
||||
await run_pod_install(task_id, build_dir, definition["xcode"])
|
||||
|
||||
# 4. 代码混淆(可选)
|
||||
if task.obfuscation:
|
||||
# 4. 代码混淆(是否执行已在 1.5 按分支策略/任务勾选确定)
|
||||
if run_obf:
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="obfuscation")
|
||||
await run_obfuscation(task_id, task, config_data, build_dir)
|
||||
|
||||
return definition, config_data
|
||||
|
||||
definition, config_data = await asyncio.wait_for(_prepare_until_obfuscation(), timeout=timeout_seconds)
|
||||
|
||||
# 4.5 校验并按需自愈 LLVM opt 工具链(独立于构建超时预算)
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="toolchain_prepare")
|
||||
prepared_env = await _prepare_iosguard_build_env(task_id, config_data, build_dir)
|
||||
|
||||
async def _build_and_upload():
|
||||
# 5. 构建项目
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="build")
|
||||
ipa_path = await build_project(task_id, task, config_data, build_dir, definition["xcode"])
|
||||
ipa_path = await build_project(
|
||||
task_id, task, config_data, build_dir, definition["xcode"], prepared_env=prepared_env
|
||||
)
|
||||
|
||||
# 查找 dSYM
|
||||
# 查找并持久化 dSYM、混淆映射、事件码与混淆审计到 DATA_DIR/artifacts/<task_id>,防止 _cleanup_build_dir 删除
|
||||
dsym_path = await find_dsym(task_id, build_dir, config_data.get("SCHEME", ""))
|
||||
|
||||
# 查找混淆映射表
|
||||
obf_maps_path = build_dir / "obfuscation_maps"
|
||||
persisted_dsym_path, persisted_maps_path = await asyncio.to_thread(
|
||||
persist_task_artifacts,
|
||||
task_id,
|
||||
build_dir,
|
||||
config_data.get("SCHEME", ""),
|
||||
dsym_path,
|
||||
)
|
||||
if persisted_dsym_path is not None:
|
||||
dsym_path = persisted_dsym_path
|
||||
|
||||
update_fields = {"ipa_path": str(ipa_path)}
|
||||
if dsym_path:
|
||||
update_fields["dsym_path"] = str(dsym_path)
|
||||
if obf_maps_path.exists():
|
||||
update_fields["obfuscation_maps_path"] = str(obf_maps_path)
|
||||
if persisted_maps_path:
|
||||
update_fields["obfuscation_maps_path"] = str(persisted_maps_path)
|
||||
await asyncio.to_thread(_db_update, db, task, **update_fields)
|
||||
|
||||
# 6. 上传产物:Ad Hoc 发布安装页,App Store 上传 IPA 供下载提交。
|
||||
@@ -573,8 +612,8 @@ async def run_build_task(task_id: str):
|
||||
except NotificationError as exc:
|
||||
await log_streamer.emit(task_id, f"钉钉通知未发送: {exc}", level="warn")
|
||||
|
||||
# 带超时执行打包
|
||||
await asyncio.wait_for(_do_build(), timeout=timeout_seconds)
|
||||
# 带超时执行编译构建与上传
|
||||
await asyncio.wait_for(_build_and_upload(), timeout=timeout_seconds)
|
||||
|
||||
# 保存打包日志
|
||||
if build_dir and build_dir.exists():
|
||||
@@ -635,6 +674,29 @@ async def run_build_task(task_id: str):
|
||||
db.close()
|
||||
|
||||
|
||||
def _dir_contains_excluded(src: Path) -> bool:
|
||||
for _, dirs, files in os.walk(src):
|
||||
if ".git" in dirs or ".git" in files or "DerivedData" in dirs:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _copy_dir_fast(src: Path, dst: Path) -> None:
|
||||
"""macOS APFS 上优先用 cp -c -R(Copy-on-Write 零拷贝)克隆目录,含排除项或失败时回退 shutil.copytree。"""
|
||||
if sys.platform == "darwin" and not _dir_contains_excluded(src):
|
||||
proc = subprocess.run(
|
||||
["cp", "-c", "-R", str(src), str(dst)],
|
||||
check=False,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
if proc.returncode == 0:
|
||||
return
|
||||
if dst.exists():
|
||||
shutil.rmtree(dst, ignore_errors=True)
|
||||
shutil.copytree(src, dst, symlinks=True, ignore=shutil.ignore_patterns(".git", "DerivedData"))
|
||||
|
||||
|
||||
async def copy_source_code(task_id: str, task, source_dir: Path, definition: dict = None) -> Path:
|
||||
"""从分支源码目录拷贝代码到打包目录"""
|
||||
await log_streamer.emit_step(task_id, "拷贝代码")
|
||||
@@ -646,23 +708,42 @@ async def copy_source_code(task_id: str, task, source_dir: Path, definition: dic
|
||||
if build_dir.exists():
|
||||
shutil.rmtree(build_dir)
|
||||
|
||||
# 未指定拷贝条目时拷贝整个仓库(不含 Git 数据和编译缓存)
|
||||
# 未指定拷贝条目时拷贝整个仓库(不含 Git 数据、DerivedData 与根 build 目录)
|
||||
copy_items = definition.get("copy_items") or []
|
||||
if not copy_items:
|
||||
await log_streamer.emit(task_id, "拷贝整个仓库")
|
||||
root = str(source_dir)
|
||||
if sys.platform == "darwin":
|
||||
build_dir.mkdir(parents=True)
|
||||
for entry in source_dir.iterdir():
|
||||
if entry.name in (".git", "DerivedData", "build"):
|
||||
continue
|
||||
dst = build_dir / entry.name
|
||||
if entry.is_symlink():
|
||||
os.symlink(os.readlink(entry), dst)
|
||||
elif entry.is_dir():
|
||||
_copy_dir_fast(entry, dst)
|
||||
elif entry.is_file():
|
||||
shutil.copy2(entry, dst)
|
||||
else:
|
||||
root = str(source_dir)
|
||||
|
||||
def _ignore(directory, names):
|
||||
ignored = {name for name in names if name in (".git", "DerivedData")}
|
||||
# 仓库根目录的 build 与打包产物目录同名,不拷贝
|
||||
if directory == root and "build" in names:
|
||||
ignored.add("build")
|
||||
return ignored
|
||||
def _ignore(directory, names):
|
||||
ignored = {name for name in names if name in (".git", "DerivedData")}
|
||||
# 仓库根目录的 build 与打包产物目录同名,不拷贝
|
||||
if directory == root and "build" in names:
|
||||
ignored.add("build")
|
||||
return ignored
|
||||
|
||||
shutil.copytree(source_dir, build_dir, symlinks=True, ignore=_ignore)
|
||||
shutil.copytree(source_dir, build_dir, symlinks=True, ignore=_ignore)
|
||||
await log_streamer.emit(task_id, "代码拷贝完成")
|
||||
return build_dir
|
||||
|
||||
# 旧项目配置可能早于 Route 2 集成,按分支实际内容补齐快照。
|
||||
if (project_id == LEGACY_PROJECT_ID or definition.get("patcher") == PATCHER_READOOR) and (
|
||||
source_dir / "iOSGuardIntegration"
|
||||
).is_dir() and "iOSGuardIntegration" not in copy_items:
|
||||
copy_items = [*copy_items, "iOSGuardIntegration"]
|
||||
|
||||
build_dir.mkdir(parents=True)
|
||||
for item in copy_items:
|
||||
src = source_dir / item
|
||||
@@ -673,7 +754,7 @@ async def copy_source_code(task_id: str, task, source_dir: Path, definition: dic
|
||||
dst = build_dir / item
|
||||
if src.is_dir():
|
||||
await log_streamer.emit(task_id, f"拷贝目录: {item}")
|
||||
shutil.copytree(src, dst, ignore=shutil.ignore_patterns(".git", "DerivedData"))
|
||||
_copy_dir_fast(src, dst)
|
||||
elif src.is_file():
|
||||
await log_streamer.emit(task_id, f"拷贝文件: {item}")
|
||||
shutil.copy2(src, dst)
|
||||
@@ -743,6 +824,7 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
||||
"SCHEME": scheme.get("name", ""),
|
||||
"OSS_FLODER": scheme.get("ossFloder", ""),
|
||||
"BUILD_TYPE": task.build_type,
|
||||
"EXCLUDE_SYMBOLS": bool(task.exclude_symbols),
|
||||
"ENABLE_OBFUSCATION": task.obfuscation,
|
||||
}
|
||||
|
||||
@@ -860,6 +942,27 @@ def _pod_dir(build_dir: Path, xcode: dict = None) -> Path:
|
||||
return None
|
||||
|
||||
|
||||
_POD_SPEC_MISSING = "Unable to find a specification for"
|
||||
|
||||
|
||||
async def _run_pod(task_id: str, pod_dir: Path, *extra_args: str) -> tuple:
|
||||
"""执行 pod install,实时输出日志,返回 (退出码, 输出行)。"""
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"pod", "install", *extra_args,
|
||||
cwd=str(pod_dir),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
output = []
|
||||
async for line in process.stdout:
|
||||
decoded = line.decode("utf-8", errors="replace").strip()
|
||||
if decoded:
|
||||
output.append(decoded)
|
||||
await log_streamer.emit(task_id, decoded)
|
||||
await process.wait()
|
||||
return process.returncode, output
|
||||
|
||||
|
||||
async def run_pod_install(task_id: str, build_dir: Path, xcode: dict = None):
|
||||
"""安装 CocoaPods 依赖"""
|
||||
await log_streamer.emit_step(task_id, "安装依赖")
|
||||
@@ -871,21 +974,13 @@ async def run_pod_install(task_id: str, build_dir: Path, xcode: dict = None):
|
||||
if pod_dir != build_dir:
|
||||
await log_streamer.emit(task_id, f"Podfile 目录: {pod_dir.relative_to(build_dir)}")
|
||||
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"pod", "install",
|
||||
cwd=str(pod_dir),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
returncode, output = await _run_pod(task_id, pod_dir)
|
||||
# 打包机本地的 Specs 索引过旧时找不到新版本 Pod,更新索引后重试一次
|
||||
if returncode != 0 and any(_POD_SPEC_MISSING in line for line in output):
|
||||
await log_streamer.emit(task_id, "本地 Pod 索引缺少所需版本,更新索引后重试(pod install --repo-update)", level="warn")
|
||||
returncode, output = await _run_pod(task_id, pod_dir, "--repo-update")
|
||||
|
||||
async for line in process.stdout:
|
||||
decoded = line.decode("utf-8", errors="replace").strip()
|
||||
if decoded:
|
||||
await log_streamer.emit(task_id, decoded)
|
||||
|
||||
await process.wait()
|
||||
|
||||
if process.returncode != 0:
|
||||
if returncode != 0:
|
||||
raise BuildError("pod install 失败", category="config")
|
||||
|
||||
patched_files = await asyncio.to_thread(_patch_afnetworking_private_headers, pod_dir)
|
||||
@@ -898,15 +993,99 @@ async def run_pod_install(task_id: str, build_dir: Path, xcode: dict = None):
|
||||
await log_streamer.emit(task_id, "依赖安装完成")
|
||||
|
||||
|
||||
BRANCH_BUILD_POLICY = Path("AutoPacking") / "build_policy.json"
|
||||
|
||||
|
||||
def _load_branch_build_policy(build_dir: Path) -> dict:
|
||||
"""读取源码快照自带的打包策略 AutoPacking/build_policy.json。
|
||||
|
||||
策略随分支代码提交,由分支声明自身的打包契约;文件缺失、解析失败或非对象时返回空字典,
|
||||
即按旧分支处理(行为与引入该文件前一致)。
|
||||
"""
|
||||
policy_file = build_dir / BRANCH_BUILD_POLICY
|
||||
if not policy_file.is_file():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(policy_file.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _resolve_obfuscation_decision(build_dir: Path, definition: dict, task) -> tuple:
|
||||
"""决定本次是否执行 L1 混淆,返回 (是否混淆, 原因)。
|
||||
|
||||
- 项目不支持混淆:始终不混淆;
|
||||
- 分支 build_policy.json 显式声明 "force_obfuscation": true:强制混淆,忽略任务勾选;
|
||||
- 其余(含所有旧分支/旧 Tag):沿用任务勾选。
|
||||
不按混淆脚本是否存在推断:2.195.0 起的旧 Tag 已带脚本,但当时混淆为可选。
|
||||
"""
|
||||
if not definition.get("obfuscation"):
|
||||
return False, "项目不支持代码混淆"
|
||||
policy = _load_branch_build_policy(build_dir)
|
||||
if policy.get("force_obfuscation") is True:
|
||||
return True, f"分支 {BRANCH_BUILD_POLICY} 声明强制混淆"
|
||||
if (build_dir / BRANCH_BUILD_POLICY).is_file() and not policy:
|
||||
return bool(task.obfuscation), f"分支 {BRANCH_BUILD_POLICY} 无法解析,按任务勾选"
|
||||
return bool(task.obfuscation), "分支未声明强制混淆,按任务勾选"
|
||||
|
||||
|
||||
def _resolve_obfuscation_dir(build_dir: Path) -> Path:
|
||||
"""优先使用源码分支自带的 AutoPacking/obfuscation(如 feat/llvm-obf-m0),旧分支回退服务端内置脚本。"""
|
||||
branch_dir = build_dir / "AutoPacking" / "obfuscation"
|
||||
if (
|
||||
(branch_dir / "obfuscate_symbols.py").is_file()
|
||||
and (branch_dir / "scripts" / "obfuscation_self_check.sh").is_file()
|
||||
):
|
||||
return branch_dir
|
||||
return AUTOMATION_DIR / "obfuscation"
|
||||
|
||||
|
||||
def _sanitize_seed_part(raw: str, fallback: str) -> str:
|
||||
cleaned = re.sub(r"[^A-Za-z0-9]+", "_", raw).strip("_")
|
||||
return cleaned or fallback
|
||||
|
||||
|
||||
def _resolve_release_seed(task_id: str, config_data: dict) -> str:
|
||||
"""计算 L1 混淆盐值与 LLVM IR seed。
|
||||
|
||||
- 显式传入环境变量或配置 IG_RELEASE_SEED 时优先使用;
|
||||
- App_Store 上架包每次使用唯一 task_id,保证每次上架符号表不同;
|
||||
- Ad_Hoc 等非上架包按「分支 + 版本号」生成稳定 seed(仅含单下划线和字母数字,
|
||||
不含 `__` 以防破坏 `-DIG_OBF_CTL_...__$(IG_RELEASE_SEED)__...=1` 宏分隔),
|
||||
让同分支同版本连续测试包复用 L1 映射并命中 LLVM obj_cache。
|
||||
"""
|
||||
explicit = os.environ.get("IG_RELEASE_SEED", "").strip() or str(config_data.get("IG_RELEASE_SEED") or "").strip()
|
||||
if explicit:
|
||||
return explicit
|
||||
build_version = str(config_data.get("BUILD_VERSION") or "0")
|
||||
if config_data.get("BUILD_TYPE") == "App_Store":
|
||||
return f"{task_id}_{build_version}"
|
||||
branch = _sanitize_seed_part(str(config_data.get("SOURCE_BRANCH") or ""), "dev")
|
||||
ver = _sanitize_seed_part(build_version, "0")
|
||||
return f"adhoc_{branch}_{ver}"
|
||||
|
||||
|
||||
async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path):
|
||||
"""执行代码混淆"""
|
||||
await log_streamer.emit_step(task_id, "代码混淆")
|
||||
|
||||
obf_root = _resolve_obfuscation_dir(build_dir)
|
||||
await log_streamer.emit(task_id, f"L1 混淆脚本目录: {obf_root}")
|
||||
if obf_root == AUTOMATION_DIR / "obfuscation":
|
||||
await log_streamer.emit_warning(
|
||||
task_id,
|
||||
"分支未自带混淆脚本,改用服务端内置脚本混淆;该脚本面向新版代码,旧版本若混淆失败可取消勾选混淆后重打",
|
||||
)
|
||||
|
||||
env = os.environ.copy()
|
||||
env["TARGET_NAME"] = config_data.get("SCHEME", "")
|
||||
env["SKIP_OBF_PHASE"] = "1"
|
||||
env["PYTHONUNBUFFERED"] = "1"
|
||||
seed = _resolve_release_seed(task_id, config_data)
|
||||
env["OBF_SALT"] = seed
|
||||
# 自检
|
||||
self_check_script = AUTOMATION_DIR / "obfuscation" / "scripts" / "obfuscation_self_check.sh"
|
||||
self_check_script = obf_root / "scripts" / "obfuscation_self_check.sh"
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"bash", str(self_check_script), str(build_dir),
|
||||
cwd=str(build_dir),
|
||||
@@ -927,10 +1106,10 @@ async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path
|
||||
|
||||
await log_streamer.emit(task_id, "混淆自检通过")
|
||||
|
||||
# 执行混淆
|
||||
obfuscate_script = AUTOMATION_DIR / "obfuscation" / "obfuscate_symbols.py"
|
||||
# 执行混淆(-u 关闭子进程 stdout 缓冲,保证网页日志实时刷出进度)
|
||||
obfuscate_script = obf_root / "obfuscate_symbols.py"
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"python3", str(obfuscate_script), "--archive-mode",
|
||||
"python3", "-u", str(obfuscate_script), "--archive-mode", "--salt", seed,
|
||||
cwd=str(build_dir),
|
||||
env=env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
@@ -950,7 +1129,307 @@ async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path
|
||||
await log_streamer.emit(task_id, "代码混淆完成")
|
||||
|
||||
|
||||
async def build_project(task_id: str, task, config_data: dict, build_dir: Path, xcode: dict = None) -> Path:
|
||||
def _prune_old_obj_caches(obj_cache_root: Path, current_ver_dir: str, keep: int = 3) -> None:
|
||||
if not obj_cache_root.is_dir():
|
||||
return
|
||||
keep_n = max(1, int(keep))
|
||||
others = [
|
||||
d for d in obj_cache_root.iterdir()
|
||||
if d.is_dir() and d.name != current_ver_dir
|
||||
]
|
||||
others.sort(key=lambda d: d.stat().st_mtime_ns, reverse=True)
|
||||
for stale in others[max(0, keep_n - 1):]:
|
||||
shutil.rmtree(stale, ignore_errors=True)
|
||||
|
||||
|
||||
async def _prepare_iosguard_build_env(task_id: str, config_data: dict, build_dir: Path) -> dict:
|
||||
"""注入 iOSGuard LLVM IR/Route 2 模式、分渠道与版本隔离的缓存,并在构建前自愈校验 `opt` 工具链。"""
|
||||
env = os.environ.copy()
|
||||
env["SKIP_OBF_PHASE"] = "1"
|
||||
|
||||
dist_channel = "appstore" if config_data.get("BUILD_TYPE") == "App_Store" else "dev"
|
||||
all_off = "1" if os.environ.get("IG_ALL_GUARD_OFF") == "1" else "0"
|
||||
raw_mode = (os.environ.get("IG_OBF_MODE") or config_data.get("IG_OBF_MODE") or DEFAULT_IG_OBF_MODE).strip() or "full"
|
||||
effective_mode = "off" if all_off == "1" else raw_mode
|
||||
seed = _resolve_release_seed(task_id, config_data)
|
||||
|
||||
obj_cache_override = os.environ.get("IG_OBF_OBJ_CACHE_DIR", "").strip()
|
||||
sdk_cache_dir = Path(os.environ.get("IG_SDK_CACHE_DIR") or (IG_CACHE_DIR / "sdk_cache"))
|
||||
sdk_cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
env["IG_DIST_CHANNEL"] = dist_channel
|
||||
env["IG_OBF_MODE"] = effective_mode
|
||||
env["IG_ALL_GUARD_OFF"] = all_off
|
||||
env["IG_RELEASE_SEED"] = seed
|
||||
env["IG_TOOLCHAIN_CACHE_DIR"] = str(IG_TOOLCHAIN_CACHE_DIR)
|
||||
env["IG_SDK_CACHE_DIR"] = str(sdk_cache_dir)
|
||||
|
||||
resolver_path = build_dir / "iOSGuardIntegration" / "toolchain" / "tools" / "llvm_obf" / "ig_toolchain_resolver.py"
|
||||
if not resolver_path.is_file():
|
||||
default_obj_dir = Path(obj_cache_override) if obj_cache_override else (IG_CACHE_DIR / "obj_cache" / f"default-{dist_channel}")
|
||||
default_obj_dir.mkdir(parents=True, exist_ok=True)
|
||||
env["IG_OBF_OBJ_CACHE_DIR"] = str(default_obj_dir)
|
||||
return env
|
||||
|
||||
if all_off == "1" or effective_mode == "off":
|
||||
default_obj_dir = Path(obj_cache_override) if obj_cache_override else (IG_CACHE_DIR / "obj_cache")
|
||||
default_obj_dir.mkdir(parents=True, exist_ok=True)
|
||||
env["IG_OBF_OBJ_CACHE_DIR"] = str(default_obj_dir)
|
||||
await log_streamer.emit(
|
||||
task_id,
|
||||
f"iOSGuard IR 混淆已显式关闭,跳过 opt 校验(IG_OBF_MODE={effective_mode}, IG_ALL_GUARD_OFF={all_off})",
|
||||
)
|
||||
return env
|
||||
|
||||
await log_streamer.emit_step(task_id, "检查工具链")
|
||||
env["IG_REQUIRE_LLVM_OBF"] = "1"
|
||||
try:
|
||||
tc_info = await ensure_toolchain(resolver_path, task_id=task_id, notify_on_event=True)
|
||||
except Exception as exc:
|
||||
raise BuildError(f"LLVM IR 混淆工具链校验失败(IG_REQUIRE_LLVM_OBF=1): {exc}", category="config") from exc
|
||||
|
||||
if obj_cache_override:
|
||||
obj_cache_dir = Path(obj_cache_override)
|
||||
else:
|
||||
xc_build = ((tc_info or {}).get("xcode") or {}).get("xcode_build") or "unknown"
|
||||
passes_h8 = ((tc_info or {}).get("passes_hash") or "legacy")[:8]
|
||||
obj_cache_dir = IG_CACHE_DIR / "obj_cache" / f"{xc_build}-{passes_h8}" / dist_channel
|
||||
await asyncio.to_thread(_prune_old_obj_caches, IG_CACHE_DIR / "obj_cache", obj_cache_dir.parent.name, 3)
|
||||
obj_cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
env["IG_OBF_OBJ_CACHE_DIR"] = str(obj_cache_dir)
|
||||
|
||||
await log_streamer.emit(
|
||||
task_id,
|
||||
f"iOSGuard 发布模式: IG_OBF_MODE={effective_mode}, IG_DIST_CHANNEL={dist_channel}, "
|
||||
f"opt={tc_info.get('source_mode', 'ready')}, seed={seed}, obj_cache={obj_cache_dir}",
|
||||
)
|
||||
return env
|
||||
|
||||
|
||||
def persist_task_artifacts(
|
||||
task_id: str,
|
||||
build_dir: Path,
|
||||
scheme: str = "",
|
||||
dsym_path: Path = None,
|
||||
) -> tuple:
|
||||
"""将 dSYM、符号/方法映射、诊断事件码与混淆审计持久化到 ARTIFACTS_DIR/<task_id>,脱离 build_dir 生命周期。"""
|
||||
artifact_root = ARTIFACTS_DIR / task_id
|
||||
persisted_dsym = None
|
||||
persisted_maps = None
|
||||
|
||||
archive_dsyms_dir = build_dir / "build" / f"{scheme}.xcarchive" / "dSYMs" if scheme else None
|
||||
dsym_bundles = sorted(archive_dsyms_dir.glob("*.dSYM")) if archive_dsyms_dir and archive_dsyms_dir.is_dir() else []
|
||||
|
||||
if dsym_bundles:
|
||||
dsym_dest_dir = artifact_root / f"{scheme or 'app'}_dSYMs"
|
||||
dsym_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
for bundle in dsym_bundles:
|
||||
dst = dsym_dest_dir / bundle.name
|
||||
if dst.exists():
|
||||
shutil.rmtree(dst, ignore_errors=True)
|
||||
shutil.copytree(bundle, dst, symlinks=True)
|
||||
persisted_dsym = dsym_dest_dir
|
||||
elif dsym_path and Path(dsym_path).exists():
|
||||
src = Path(dsym_path)
|
||||
artifact_root.mkdir(parents=True, exist_ok=True)
|
||||
dst = artifact_root / src.name
|
||||
if src.is_dir():
|
||||
if dst.exists():
|
||||
shutil.rmtree(dst, ignore_errors=True)
|
||||
shutil.copytree(src, dst, symlinks=True)
|
||||
else:
|
||||
shutil.copy2(src, dst)
|
||||
persisted_dsym = dst
|
||||
|
||||
maps_dest_dir = artifact_root / "obfuscation_maps"
|
||||
copied_any = False
|
||||
|
||||
src_maps_dir = build_dir / "obfuscation_maps"
|
||||
if src_maps_dir.is_dir():
|
||||
for item in sorted(src_maps_dir.glob("*.json")):
|
||||
if item.is_file():
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(item, maps_dest_dir / item.name)
|
||||
copied_any = True
|
||||
|
||||
unmapped_file = build_dir / "unmapped_mappings.json"
|
||||
if unmapped_file.is_file():
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(unmapped_file, maps_dest_dir / unmapped_file.name)
|
||||
copied_any = True
|
||||
|
||||
diag_events = build_dir / "iOSGuardIntegration" / "toolchain" / "config" / "ig_diag_events.json"
|
||||
if diag_events.is_file():
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(diag_events, maps_dest_dir / "ig_diag_events.json")
|
||||
copied_any = True
|
||||
|
||||
derived_data = build_dir / "build" / "derived_data"
|
||||
if derived_data.is_dir():
|
||||
audits = sorted(derived_data.rglob("ig_obfuscation_audit.json"))
|
||||
if audits:
|
||||
chosen = next((a for a in audits if scheme and f"{scheme}.build" in str(a)), audits[0])
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(chosen, maps_dest_dir / "ig_obfuscation_audit.json")
|
||||
copied_any = True
|
||||
|
||||
ipa_audit_report = build_dir / "build" / "ipa_audit_report.json"
|
||||
if ipa_audit_report.is_file():
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(ipa_audit_report, maps_dest_dir / "ipa_audit_report.json")
|
||||
copied_any = True
|
||||
|
||||
if copied_any:
|
||||
persisted_maps = maps_dest_dir
|
||||
|
||||
return persisted_dsym, persisted_maps
|
||||
|
||||
|
||||
async def _run_exported_ipa_audit(
|
||||
task_id: str,
|
||||
audit_script: Path,
|
||||
ipa_path: Path,
|
||||
archive_path: Path,
|
||||
export_path: Path,
|
||||
config_data: dict,
|
||||
build_dir: Path,
|
||||
build_env: dict,
|
||||
) -> None:
|
||||
"""导出后执行完整 IPA 加固门禁审计(Route 2 + StaticHygieneGate + Mach-O 门禁),不通过直接阻断上传。"""
|
||||
scheme = config_data.get("SCHEME", "")
|
||||
cmd = [
|
||||
sys.executable or "python3",
|
||||
str(audit_script),
|
||||
str(ipa_path),
|
||||
"--archive",
|
||||
str(archive_path),
|
||||
"--report-out",
|
||||
str(export_path / "ipa_audit_report.json"),
|
||||
]
|
||||
if config_data.get("BUNDLE_ID"):
|
||||
cmd.extend(["--bundle-id", config_data["BUNDLE_ID"]])
|
||||
|
||||
derived_data = export_path / "derived_data"
|
||||
if derived_data.is_dir():
|
||||
audits = sorted(derived_data.rglob("ig_obfuscation_audit.json"))
|
||||
if audits:
|
||||
chosen = next((a for a in audits if scheme and f"{scheme}.build" in str(a)), audits[0])
|
||||
cmd.extend(["--audit-json", str(chosen)])
|
||||
|
||||
maps_dir = build_dir / "obfuscation_maps"
|
||||
if maps_dir.is_dir():
|
||||
sym_maps = sorted(maps_dir.glob("symbol_map_*.json"))
|
||||
if sym_maps:
|
||||
exact = [m for m in sym_maps if scheme and f"_{scheme}_" in m.name]
|
||||
chosen_sym = (exact or sym_maps)[-1]
|
||||
cmd.extend(["--symbol-map", str(chosen_sym)])
|
||||
|
||||
await log_streamer.emit(task_id, "开始 IPA 加固门禁审计...")
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
cwd=str(build_dir),
|
||||
env=build_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
audit_output = []
|
||||
async for line in process.stdout:
|
||||
decoded = line.decode("utf-8", errors="replace").strip()
|
||||
if decoded:
|
||||
audit_output.append(decoded)
|
||||
await log_streamer.emit(task_id, decoded)
|
||||
await process.wait()
|
||||
if process.returncode != 0:
|
||||
raise BuildError(
|
||||
"IPA 加固门禁审计失败,已阻止上传",
|
||||
category="build",
|
||||
detail="\n".join(audit_output[-25:]),
|
||||
)
|
||||
|
||||
|
||||
IG_APPSTORE_FLAG = "IG_APPSTORE_DISTRIBUTION"
|
||||
IG_ANTI_TAMPER_SOURCE = "IGAntiTamper.c"
|
||||
|
||||
|
||||
async def _verify_dist_channel_flag(
|
||||
task_id: str,
|
||||
container_args: tuple,
|
||||
scheme: str,
|
||||
build_dir: Path,
|
||||
build_env: dict,
|
||||
) -> None:
|
||||
"""Archive 前核对分发渠道编译条件,确保 500/501 防砸壳/重签名校验与渠道一致。
|
||||
|
||||
App 工程不再在 Release 写死 IG_APPSTORE_DISTRIBUTION,唯一来源是本服务透传的
|
||||
IG_DIST_CHANNEL=appstore。上架包缺失该条件 → 防砸壳/重签名检测整体失效,必须阻断;
|
||||
非上架包带上该条件(旧分支仍写死)→ Ad-hoc 包会被误判 500/501 而锁定敏感入口,仅告警不阻断。
|
||||
未接入 anti_tamper 的历史分支直接跳过。
|
||||
"""
|
||||
project_file = build_dir / "readoor.xcodeproj" / "project.pbxproj"
|
||||
if not project_file.is_file():
|
||||
return
|
||||
if IG_ANTI_TAMPER_SOURCE not in project_file.read_text(encoding="utf-8", errors="replace"):
|
||||
return
|
||||
|
||||
channel = build_env.get("IG_DIST_CHANNEL", "dev")
|
||||
cmd = [
|
||||
"xcodebuild", "-showBuildSettings",
|
||||
*container_args,
|
||||
"-scheme", scheme,
|
||||
"-configuration", "Release",
|
||||
"-sdk", "iphoneos",
|
||||
f"IG_DIST_CHANNEL={channel}",
|
||||
f"IG_ALL_GUARD_OFF={build_env.get('IG_ALL_GUARD_OFF', '0')}",
|
||||
]
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
cwd=str(build_dir),
|
||||
env=build_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
flag_lines = []
|
||||
tail = []
|
||||
async for line in process.stdout:
|
||||
decoded = line.decode("utf-8", errors="replace").strip()
|
||||
if not decoded:
|
||||
continue
|
||||
tail = (tail + [decoded])[-20:]
|
||||
if decoded.startswith(("OTHER_SWIFT_FLAGS =", "SWIFT_ACTIVE_COMPILATION_CONDITIONS =")) \
|
||||
and any(tok in (IG_APPSTORE_FLAG, f"-D{IG_APPSTORE_FLAG}") for tok in decoded.split()):
|
||||
flag_lines.append(decoded)
|
||||
await process.wait()
|
||||
|
||||
if channel == "appstore":
|
||||
if process.returncode != 0:
|
||||
raise BuildError(
|
||||
f"上架包分发渠道编译条件核对失败(xcodebuild -showBuildSettings 退出码 {process.returncode})",
|
||||
category="config",
|
||||
detail="\n".join(tail),
|
||||
)
|
||||
if not flag_lines:
|
||||
raise BuildError(
|
||||
f"上架包未注入 {IG_APPSTORE_FLAG}(IG_DIST_CHANNEL=appstore 未生效),"
|
||||
"防砸壳/重签名检测将失效,已阻止 Archive",
|
||||
category="config",
|
||||
)
|
||||
await log_streamer.emit(task_id, f"分发渠道核对通过:上架包已注入 {IG_APPSTORE_FLAG}")
|
||||
elif flag_lines:
|
||||
await log_streamer.emit_warning(
|
||||
task_id,
|
||||
f"非上架包仍带 {IG_APPSTORE_FLAG}(分支工程可能仍在 Release 写死该条件),"
|
||||
"安装后可能因 500/501 被锁定登录/支付并延迟退出,请升级分支工程配置",
|
||||
)
|
||||
|
||||
|
||||
async def build_project(
|
||||
task_id: str,
|
||||
task,
|
||||
config_data: dict,
|
||||
build_dir: Path,
|
||||
xcode: dict = None,
|
||||
prepared_env: Optional[dict] = None,
|
||||
) -> Path:
|
||||
"""构建项目;xcode 为项目定义中的 {workspace, project},优先使用 workspace"""
|
||||
await log_streamer.emit_step(task_id, "构建项目")
|
||||
|
||||
@@ -966,30 +1445,26 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
else:
|
||||
raise BuildError("项目未配置 Xcode workspace 或 project", category="config")
|
||||
|
||||
if scheme in ("readoor31", "readoor31OtherPay"):
|
||||
project_file = build_dir / "readoor.xcodeproj" / "project.pbxproj"
|
||||
if project_file.is_file():
|
||||
project_text = project_file.read_text(encoding="utf-8")
|
||||
for script in ("ig_ld_wrapper.py", "ig_guard_frameworks_phase.py"):
|
||||
relative = Path("iOSGuardIntegration/toolchain/tools/xcode_archive") / script
|
||||
if str(relative) in project_text and not (build_dir / relative).is_file():
|
||||
raise BuildError(f"源码快照缺少工程引用的脚本:{relative}", category="config")
|
||||
|
||||
build_env = prepared_env if prepared_env is not None else await _prepare_iosguard_build_env(task_id, config_data, build_dir)
|
||||
export_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 清理
|
||||
await log_streamer.emit(task_id, "清理项目...")
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"xcodebuild", "clean",
|
||||
*container_args,
|
||||
"-scheme", scheme,
|
||||
"-configuration", "Release",
|
||||
"-derivedDataPath", str(export_path / "derived_data"),
|
||||
cwd=str(build_dir),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
async for line in process.stdout:
|
||||
decoded = line.decode("utf-8", errors="replace").strip()
|
||||
if decoded:
|
||||
await log_streamer.emit(task_id, decoded)
|
||||
await process.wait()
|
||||
if scheme in ("readoor31", "readoor31OtherPay"):
|
||||
await _verify_dist_channel_flag(task_id, container_args, scheme, build_dir, build_env)
|
||||
|
||||
# Archive
|
||||
# Archive(每次任务的 derived_data 为全新空目录,跳过多余的 xcodebuild clean)
|
||||
await log_streamer.emit(task_id, "开始 Archive...")
|
||||
archive_started_at = time.monotonic()
|
||||
archive_output = []
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
archive_cmd = [
|
||||
"xcodebuild", "archive",
|
||||
*container_args,
|
||||
"-scheme", scheme,
|
||||
@@ -997,7 +1472,18 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
"-archivePath", str(archive_path),
|
||||
"-derivedDataPath", str(export_path / "derived_data"),
|
||||
"-destination", "generic/platform=ios",
|
||||
]
|
||||
if scheme in ("readoor31", "readoor31OtherPay"):
|
||||
archive_cmd.extend([
|
||||
f"IG_DIST_CHANNEL={build_env['IG_DIST_CHANNEL']}",
|
||||
f"IG_OBF_MODE={build_env['IG_OBF_MODE']}",
|
||||
f"IG_ALL_GUARD_OFF={build_env['IG_ALL_GUARD_OFF']}",
|
||||
f"IG_RELEASE_SEED={build_env['IG_RELEASE_SEED']}",
|
||||
])
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*archive_cmd,
|
||||
cwd=str(build_dir),
|
||||
env=build_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
@@ -1007,10 +1493,12 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
archive_output.append(decoded)
|
||||
await log_streamer.emit(task_id, decoded)
|
||||
await process.wait()
|
||||
archive_elapsed = time.monotonic() - archive_started_at
|
||||
|
||||
if process.returncode != 0:
|
||||
category, hint = _classify_build_error(archive_output, "archive")
|
||||
raise BuildError(hint, category=category, detail="\n".join(archive_output[-20:]))
|
||||
await log_streamer.emit(task_id, f"Archive 构建完成,耗时: {archive_elapsed:.1f}s")
|
||||
|
||||
# 导出 IPA
|
||||
await log_streamer.emit(task_id, "导出 IPA...")
|
||||
@@ -1022,6 +1510,7 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
"-exportPath", str(export_path),
|
||||
"-exportOptionsPlist", str(export_plist),
|
||||
cwd=str(build_dir),
|
||||
env=build_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
@@ -1043,11 +1532,47 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
|
||||
ipa_path = ipa_files[0]
|
||||
await log_streamer.emit(task_id, f"IPA 已导出: {ipa_path.name}")
|
||||
|
||||
if (
|
||||
scheme in ("readoor31", "readoor31OtherPay")
|
||||
and build_env.get("IG_ALL_GUARD_OFF") != "1"
|
||||
and build_env.get("IG_OBF_MODE") != "off"
|
||||
):
|
||||
audit_script = (
|
||||
build_dir
|
||||
/ "iOSGuardIntegration"
|
||||
/ "toolchain"
|
||||
/ "tools"
|
||||
/ "xcode_archive"
|
||||
/ "audit_exported_ipa.py"
|
||||
)
|
||||
if audit_script.is_file():
|
||||
await _run_exported_ipa_audit(
|
||||
task_id,
|
||||
audit_script,
|
||||
ipa_path,
|
||||
archive_path,
|
||||
export_path,
|
||||
config_data,
|
||||
build_dir,
|
||||
build_env,
|
||||
)
|
||||
|
||||
return ipa_path
|
||||
|
||||
|
||||
async def find_dsym(task_id: str, build_dir: Path, scheme: str = "") -> Path:
|
||||
"""查找当前 target(主 App)对应的 dSYM 文件,忽略 Extension/Framework 各自的 dSYM"""
|
||||
"""优先从 .xcarchive/dSYMs 查找全部 dSYM(含主 App 与 IGArchiveGuard.framework),否则回退 derived_data。"""
|
||||
if scheme:
|
||||
archive_dsyms = build_dir / "build" / f"{scheme}.xcarchive" / "dSYMs"
|
||||
if archive_dsyms.is_dir():
|
||||
main_dsym = archive_dsyms / f"{scheme}.app.dSYM"
|
||||
if main_dsym.exists():
|
||||
return main_dsym
|
||||
bundles = sorted(archive_dsyms.glob("*.dSYM"))
|
||||
if bundles:
|
||||
return bundles[0]
|
||||
|
||||
derived_data = build_dir / "build" / "derived_data"
|
||||
if not derived_data.exists():
|
||||
return None
|
||||
|
||||
@@ -24,6 +24,8 @@ def _artifact_stem(config: dict) -> str:
|
||||
return f"{config.get('APPID', 'app')}_{version}"
|
||||
branch = re.sub(r"[^A-Za-z0-9._-]+", "_", config.get("SOURCE_BRANCH", "main")).strip("._-")
|
||||
build_type = "appstore" if config.get("BUILD_TYPE") == "App_Store" else "adhoc"
|
||||
if build_type == "appstore" and config.get("EXCLUDE_SYMBOLS"):
|
||||
build_type += "_nosymbols"
|
||||
return f"{config.get('APPID', 'app')}_{version}_{branch or 'main'}_{build_type}"
|
||||
|
||||
|
||||
|
||||
@@ -124,3 +124,44 @@ def send_dingtalk_notification(
|
||||
if result.get("errcode", 0) != 0:
|
||||
raise NotificationError(f"钉钉通知发送失败: {result.get('errmsg', '未知错误')}")
|
||||
return True
|
||||
|
||||
|
||||
def send_toolchain_dingtalk_alert(
|
||||
dingtalk_config: dict,
|
||||
title: str,
|
||||
lines: list[str],
|
||||
) -> bool:
|
||||
"""发送 Xcode/opt 工具链状态通知(标题和正文必须保留「打包」关键词)。"""
|
||||
if not (dingtalk_config or {}).get("enabled"):
|
||||
return False
|
||||
|
||||
webhook_url = (dingtalk_config.get("webhook_url") or "").strip()
|
||||
if not webhook_url:
|
||||
raise NotificationError("钉钉通知已启用,但未配置 Webhook URL")
|
||||
|
||||
safe_title = title if "打包" in title else f"【iOS打包服务】{title}"
|
||||
mobiles = normalize_mobiles(dingtalk_config.get("at_mobiles", []))
|
||||
body_lines = [f"## {safe_title}", "", *lines]
|
||||
if mobiles:
|
||||
body_lines.extend(["", " ".join(f"@{m}" for m in mobiles)])
|
||||
|
||||
payload = {
|
||||
"msgtype": "markdown",
|
||||
"markdown": {"title": safe_title, "text": "\n\n".join(body_lines)},
|
||||
"at": {"atMobiles": mobiles, "isAtAll": False},
|
||||
}
|
||||
response = httpx.post(
|
||||
_signed_webhook_url(webhook_url, dingtalk_config.get("secret", "")),
|
||||
json=payload,
|
||||
timeout=15,
|
||||
)
|
||||
if response.status_code // 100 != 2:
|
||||
raise NotificationError(f"钉钉通知发送失败 ({response.status_code})")
|
||||
|
||||
try:
|
||||
result = response.json()
|
||||
except ValueError as exc:
|
||||
raise NotificationError("钉钉通知返回内容无效") from exc
|
||||
if result.get("errcode", 0) != 0:
|
||||
raise NotificationError(f"钉钉通知发送失败: {result.get('errmsg', '未知错误')}")
|
||||
return True
|
||||
|
||||
@@ -113,15 +113,84 @@ def _write_export_options(build_dir: Path, config: dict):
|
||||
"stripSwiftSymbols": True,
|
||||
"thinning": "<none>",
|
||||
}
|
||||
if data["method"] == "app-store-connect" and config.get("EXCLUDE_SYMBOLS"):
|
||||
data["uploadSymbols"] = False
|
||||
with (build_dir / "exportOptions.plist").open("wb") as f:
|
||||
plistlib.dump(data, f)
|
||||
|
||||
|
||||
# 词典环境宏 ← 服务器环境字段(APPID 取 App 的 AppGuid)
|
||||
DICT_SERVER_MACROS = {
|
||||
"SERVERURL": "DICT_SERVERURL",
|
||||
"SERVERHTTPSURL": "DICT_SERVERHTTPSURL",
|
||||
"UCSERVERURL": "DICT_UCSERVERURL",
|
||||
"RECORDSERVERURL": "DICT_RECORDSERVERURL",
|
||||
"LOGSERVERURL": "DICT_LOGSERVERURL",
|
||||
}
|
||||
_DICT_BLOCK_START = re.compile(r"^\s*#\s*(?:el)?if\s+TARGETTYPE\s*==\s*2\s*$")
|
||||
_PP_OPEN = re.compile(r"^\s*#\s*if")
|
||||
_PP_BRANCH = re.compile(r"^\s*#\s*(?:elif|else)\b")
|
||||
_PP_CLOSE = re.compile(r"^\s*#\s*endif\b")
|
||||
|
||||
|
||||
def _replace_dict_env_macros(content: str, values: dict) -> str:
|
||||
"""只替换 TARGETTYPE == 2 段落中未注释的 #define,其它 TARGETTYPE 的同名宏不动。"""
|
||||
lines = content.splitlines(keepends=True)
|
||||
start = next((i for i, line in enumerate(lines) if _DICT_BLOCK_START.match(line)), None)
|
||||
if start is None:
|
||||
raise ProjectPatchError("STSConstantsMacro.h 中未找到 #elif TARGETTYPE == 2 词典配置段")
|
||||
counts = {name: 0 for name in values}
|
||||
depth = 0
|
||||
for i in range(start + 1, len(lines)):
|
||||
line = lines[i]
|
||||
if _PP_OPEN.match(line):
|
||||
depth += 1
|
||||
continue
|
||||
if _PP_CLOSE.match(line) or _PP_BRANCH.match(line):
|
||||
if depth == 0:
|
||||
break
|
||||
if _PP_CLOSE.match(line):
|
||||
depth -= 1
|
||||
continue
|
||||
for name, value in values.items():
|
||||
if re.match(rf"^\s*#define\s+{name}\b", line):
|
||||
ending = "\n" if line.endswith("\n") else ""
|
||||
lines[i] = f'#define {name} @"{value}"{ending}'
|
||||
counts[name] += 1
|
||||
missing = [name for name, count in counts.items() if count == 0]
|
||||
if missing:
|
||||
raise ProjectPatchError(f"词典配置段中未找到未注释的宏: {', '.join(missing)}")
|
||||
return "".join(lines)
|
||||
|
||||
|
||||
def _dict_env_values(config: dict) -> dict:
|
||||
"""服务器环境中的词典地址;全部未配置返回空(沿用源码),部分配置视为错误。"""
|
||||
server_vars = config.get("SERVER_VARS") or {}
|
||||
values = {macro: str(server_vars.get(key, "") or "").strip() for macro, key in DICT_SERVER_MACROS.items()}
|
||||
if not any(values.values()):
|
||||
return {}
|
||||
missing = [DICT_SERVER_MACROS[macro] for macro, value in values.items() if not value]
|
||||
if missing:
|
||||
raise ProjectPatchError(f"服务器环境 {config.get('SERVER', '')} 的词典地址未配置完整: {', '.join(missing)}")
|
||||
if not str(config.get("APPID", "") or "").strip():
|
||||
raise ProjectPatchError("词典 App 未配置 AppGuid,无法写入 APPID")
|
||||
return {"APPID": str(config["APPID"]).strip(), **values}
|
||||
|
||||
|
||||
def _apply_dictionary_config(build_dir: Path, config: dict, messages: list[str]):
|
||||
macro = build_dir / "readoor" / "BookShelf" / "Classes" / "Macro" / "STSConstantsMacro.h"
|
||||
if not macro.exists():
|
||||
raise ProjectPatchError(f"词典配置文件不存在: {macro}")
|
||||
content = macro.read_text(encoding="utf-8")
|
||||
env_values = _dict_env_values(config)
|
||||
if env_values:
|
||||
content = _replace_dict_env_macros(content, env_values)
|
||||
messages.append(
|
||||
f"已替换词典环境配置({config.get('SERVER', '')}): APPID {env_values['APPID']},"
|
||||
f"SERVERURL {env_values['SERVERURL']}"
|
||||
)
|
||||
else:
|
||||
messages.append(f"服务器环境 {config.get('SERVER', '')} 未配置词典地址,沿用源码中的词典环境配置")
|
||||
version = config.get("VERSION", "")
|
||||
content, count = re.subn(
|
||||
r'^(#define\s+SOURCE_VERSION\s+)@"[^"]*"',
|
||||
@@ -135,6 +204,20 @@ def _apply_dictionary_config(build_dir: Path, config: dict, messages: list[str])
|
||||
messages.append("已替换词典版本配置")
|
||||
|
||||
|
||||
def _apply_dictionary_version(build_dir: Path, config: dict, messages: list[str]):
|
||||
"""词典包的 IPA 版本号与构建号同样按版本轨道写入工程(与 readoor31 一致,替换工程内全部构建配置)。"""
|
||||
project = build_dir / "readoor.xcodeproj" / "project.pbxproj"
|
||||
version, build_version = config.get("VERSION", ""), config.get("BUILD_VERSION", "")
|
||||
replacements = [
|
||||
("MARKETING_VERSION =", f"\t\t\t\tMARKETING_VERSION = {version};"),
|
||||
("CURRENT_PROJECT_VERSION =", f"\t\t\t\tCURRENT_PROJECT_VERSION = {build_version};"),
|
||||
]
|
||||
missing = [keyword for keyword, line in replacements if _replace_lines(project, keyword, line) == 0]
|
||||
if missing:
|
||||
raise ProjectPatchError(f"未找到待替换配置: {', '.join(missing)}")
|
||||
messages.append(f"已替换词典包版本: {version} ({build_version})")
|
||||
|
||||
|
||||
def apply_project_config(build_dir: Path, config: dict, definition: dict = None) -> list[str]:
|
||||
"""写入项目配置,返回适合实时日志展示的变更说明。
|
||||
|
||||
@@ -146,6 +229,7 @@ def apply_project_config(build_dir: Path, config: dict, definition: dict = None)
|
||||
messages: list[str] = []
|
||||
if config.get("SCHEME") == "readoorDict":
|
||||
_apply_dictionary_config(build_dir, config, messages)
|
||||
_apply_dictionary_version(build_dir, config, messages)
|
||||
_write_export_options(build_dir, config)
|
||||
return messages
|
||||
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
"""iOSGuard LLVM opt 工具链管理:并发互斥、按需校验/自愈及每日午夜巡检。"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from ..config import (
|
||||
IG_LLVM_GIT_MIRROR,
|
||||
IG_TOOLCHAIN_CACHE_DIR,
|
||||
IG_TOOLCHAIN_DAILY_CHECK_ENABLED,
|
||||
IG_TOOLCHAIN_DAILY_HOUR,
|
||||
IG_TOOLCHAIN_DAILY_MINUTE,
|
||||
IG_TOOLCHAIN_KEEP_VERSIONS,
|
||||
IG_TOOLCHAIN_REBUILD_TIMEOUT_SECONDS,
|
||||
IG_TOOLCHAIN_SOURCE_DIR,
|
||||
)
|
||||
from ..projects import LEGACY_PROJECT_ID, get_project_source
|
||||
from .log_streamer import log_streamer
|
||||
from .notification import send_toolchain_dingtalk_alert
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_toolchain_lock = asyncio.Lock()
|
||||
_update_in_progress = False
|
||||
|
||||
_RESOLVER_REL = Path("iOSGuardIntegration") / "toolchain" / "tools" / "llvm_obf" / "ig_toolchain_resolver.py"
|
||||
|
||||
|
||||
def seconds_until_next_run(now: Optional[datetime] = None, hour: int = 0, minute: int = 0) -> float:
|
||||
"""计算当前本地时间距离下一次指定时刻(默认 00:00)的秒数,最小返回 1.0。"""
|
||||
current = now or datetime.now()
|
||||
target = current.replace(hour=int(hour) % 24, minute=int(minute) % 60, second=0, microsecond=0)
|
||||
if target <= current:
|
||||
target += timedelta(days=1)
|
||||
return max(1.0, (target - current).total_seconds())
|
||||
|
||||
|
||||
def _augmented_subprocess_env() -> dict:
|
||||
env = os.environ.copy()
|
||||
path_parts = [p for p in env.get("PATH", "").split(":") if p]
|
||||
for extra in ("/opt/homebrew/bin", "/usr/local/bin"):
|
||||
if extra not in path_parts:
|
||||
path_parts.append(extra)
|
||||
env["PATH"] = ":".join(path_parts)
|
||||
env["IG_TOOLCHAIN_CACHE_DIR"] = str(IG_TOOLCHAIN_CACHE_DIR)
|
||||
env["IG_LLVM_GIT_MIRROR"] = IG_LLVM_GIT_MIRROR
|
||||
env["PYTHONUNBUFFERED"] = "1"
|
||||
return env
|
||||
|
||||
|
||||
def _load_dingtalk_config() -> dict:
|
||||
try:
|
||||
from ..routers.config import load_upload_config
|
||||
|
||||
return (load_upload_config() or {}).get("dingtalk", {}) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
async def _send_alert_best_effort(title: str, lines: list[str]) -> None:
|
||||
cfg = _load_dingtalk_config()
|
||||
if not cfg.get("enabled"):
|
||||
return
|
||||
try:
|
||||
await asyncio.to_thread(send_toolchain_dingtalk_alert, cfg, title, lines)
|
||||
except Exception as exc:
|
||||
logger.warning("发送工具链钉钉告警失败: %s", exc)
|
||||
|
||||
|
||||
def discover_toolchain_resolver(build_dir: Optional[Path] = None) -> Optional[Path]:
|
||||
"""按优先级定位 ig_toolchain_resolver.py:构建快照 > IG_TOOLCHAIN_SOURCE_DIR > Readoor 源码目录。"""
|
||||
if build_dir is not None:
|
||||
cand = Path(build_dir) / _RESOLVER_REL
|
||||
if cand.is_file():
|
||||
return cand
|
||||
|
||||
if IG_TOOLCHAIN_SOURCE_DIR:
|
||||
base = Path(IG_TOOLCHAIN_SOURCE_DIR).expanduser()
|
||||
for cand in (
|
||||
base,
|
||||
base / _RESOLVER_REL,
|
||||
base / "tools" / "llvm_obf" / "ig_toolchain_resolver.py",
|
||||
):
|
||||
if cand.is_file():
|
||||
return cand
|
||||
|
||||
try:
|
||||
from ..routers.config import load_config
|
||||
|
||||
project = load_config(LEGACY_PROJECT_ID)
|
||||
source = get_project_source(LEGACY_PROJECT_ID, project)
|
||||
candidates = []
|
||||
if source.shared_dir:
|
||||
candidates.append(source.shared_dir / _RESOLVER_REL)
|
||||
if source.manual_base and source.manual_base.is_dir():
|
||||
for branch in project.get("branches") or ("main",):
|
||||
candidates.append(source.manual_base / branch / _RESOLVER_REL)
|
||||
for child in sorted(source.manual_base.iterdir()):
|
||||
if child.is_dir():
|
||||
candidates.append(child / _RESOLVER_REL)
|
||||
for cand in candidates:
|
||||
if cand.is_file():
|
||||
return cand
|
||||
except Exception as exc:
|
||||
logger.debug("从 Readoor 项目源码定位工具链解析器失败: %s", exc)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def ensure_toolchain(
|
||||
resolver_path: Path,
|
||||
*,
|
||||
task_id: Optional[str] = None,
|
||||
force_rebuild: bool = False,
|
||||
notify_on_event: bool = False,
|
||||
) -> dict:
|
||||
"""在全局异步锁下执行 `ig_toolchain_resolver.py --ensure`,必要时自动复用或源码重编 `opt`。"""
|
||||
global _update_in_progress
|
||||
|
||||
if _toolchain_lock.locked() and task_id:
|
||||
await log_streamer.emit(task_id, "正在等待其他任务完成 LLVM 加固工具链检查/更新...")
|
||||
|
||||
async with _toolchain_lock:
|
||||
_update_in_progress = True
|
||||
try:
|
||||
cmd = [
|
||||
sys.executable or "python3",
|
||||
str(resolver_path),
|
||||
"--ensure",
|
||||
"--require-obf",
|
||||
"--json",
|
||||
"--cache-dir",
|
||||
str(IG_TOOLCHAIN_CACHE_DIR),
|
||||
"--git-remote",
|
||||
IG_LLVM_GIT_MIRROR,
|
||||
"--keep-versions",
|
||||
str(IG_TOOLCHAIN_KEEP_VERSIONS),
|
||||
]
|
||||
if force_rebuild:
|
||||
cmd.append("--force-rebuild")
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
cwd=str(Path(resolver_path).parent),
|
||||
env=_augmented_subprocess_env(),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
|
||||
stderr_tail: list[str] = []
|
||||
|
||||
async def _read_stderr():
|
||||
assert proc.stderr is not None
|
||||
while True:
|
||||
raw = await proc.stderr.readline()
|
||||
if not raw:
|
||||
break
|
||||
line = raw.decode("utf-8", errors="replace").rstrip("\r\n")
|
||||
if not line:
|
||||
continue
|
||||
stderr_tail.append(line)
|
||||
if len(stderr_tail) > 40:
|
||||
stderr_tail.pop(0)
|
||||
logger.info("[IGToolchain] %s", line)
|
||||
if task_id:
|
||||
await log_streamer.emit(task_id, f"[toolchain] {line}")
|
||||
|
||||
async def _wait_streams():
|
||||
assert proc.stdout is not None
|
||||
stdout_bytes, _ = await asyncio.gather(proc.stdout.read(), _read_stderr())
|
||||
await proc.wait()
|
||||
return stdout_bytes
|
||||
|
||||
try:
|
||||
stdout_bytes = await asyncio.wait_for(
|
||||
_wait_streams(),
|
||||
timeout=IG_TOOLCHAIN_REBUILD_TIMEOUT_SECONDS,
|
||||
)
|
||||
except asyncio.TimeoutError as exc:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
msg = f"LLVM 工具链自动更新超时(>{IG_TOOLCHAIN_REBUILD_TIMEOUT_SECONDS}s)"
|
||||
if notify_on_event:
|
||||
await _send_alert_best_effort(
|
||||
"【iOS打包服务】Xcode 工具链 (opt) 更新失败",
|
||||
[f"**原因:** {msg}", f"**日志尾部:** `{' | '.join(stderr_tail[-5:])}`"],
|
||||
)
|
||||
raise RuntimeError(msg) from exc
|
||||
|
||||
stdout_text = (stdout_bytes or b"").decode("utf-8", errors="replace").strip()
|
||||
payload = {}
|
||||
if stdout_text:
|
||||
try:
|
||||
payload = json.loads(stdout_text)
|
||||
except json.JSONDecodeError:
|
||||
payload = {"raw_stdout": stdout_text[-1000:]}
|
||||
|
||||
if proc.returncode != 0:
|
||||
detail = payload.get("error") or payload.get("warning") or "\n".join(stderr_tail[-10:]) or stdout_text[-800:]
|
||||
if notify_on_event:
|
||||
await _send_alert_best_effort(
|
||||
"【iOS打包服务】Xcode 工具链 (opt) 更新失败",
|
||||
[f"**失败原因:** {detail}"],
|
||||
)
|
||||
raise RuntimeError(f"LLVM IR 混淆工具链校验/更新失败: {detail}")
|
||||
|
||||
source_mode = payload.get("source_mode")
|
||||
if notify_on_event and source_mode in ("reused", "built"):
|
||||
xc = payload.get("xcode") or {}
|
||||
sw = payload.get("swift") or {}
|
||||
lines = [
|
||||
f"**Xcode:** {xc.get('xcode_version', '')} ({xc.get('xcode_build', '')})",
|
||||
f"**Swift:** {sw.get('swift_version', '')} (swiftlang-{sw.get('swiftlang_version', '')})",
|
||||
f"**更新方式:** {'自动冒烟复用' if source_mode == 'reused' else '自动源码重编'}",
|
||||
]
|
||||
if payload.get("llvm_branch"):
|
||||
lines.append(f"**LLVM 分支:** {payload['llvm_branch']}")
|
||||
lines.append(f"**opt SHA256:** `{(payload.get('opt_sha256') or '')[:12]}`")
|
||||
await _send_alert_best_effort("【iOS打包服务】Xcode 工具链 (opt) 已自动更新", lines)
|
||||
|
||||
return payload
|
||||
finally:
|
||||
_update_in_progress = False
|
||||
|
||||
|
||||
async def get_toolchain_status(resolver_path: Optional[Path] = None) -> dict:
|
||||
"""只读检查当前机器 Xcode 与 `opt` 缓存状态。"""
|
||||
resolved = resolver_path or discover_toolchain_resolver()
|
||||
next_run = datetime.now() + timedelta(
|
||||
seconds=seconds_until_next_run(hour=IG_TOOLCHAIN_DAILY_HOUR, minute=IG_TOOLCHAIN_DAILY_MINUTE)
|
||||
)
|
||||
base_status = {
|
||||
"update_in_progress": _update_in_progress,
|
||||
"daily_check_enabled": IG_TOOLCHAIN_DAILY_CHECK_ENABLED,
|
||||
"next_scheduled_check": next_run.isoformat(timespec="seconds"),
|
||||
"cache_dir": str(IG_TOOLCHAIN_CACHE_DIR),
|
||||
"git_mirror": IG_LLVM_GIT_MIRROR,
|
||||
"resolver_path": str(resolved) if resolved else None,
|
||||
}
|
||||
if resolved is None:
|
||||
return {
|
||||
**base_status,
|
||||
"resolver_found": False,
|
||||
"ready": False,
|
||||
}
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
sys.executable or "python3",
|
||||
str(resolved),
|
||||
"--check-only",
|
||||
"--json",
|
||||
"--cache-dir",
|
||||
str(IG_TOOLCHAIN_CACHE_DIR),
|
||||
cwd=str(resolved.parent),
|
||||
env=_augmented_subprocess_env(),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
stdout_bytes, stderr_bytes = await asyncio.wait_for(proc.communicate(), timeout=15)
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
return {**base_status, "resolver_found": True, "ready": False, "error": "检查工具链状态超时"}
|
||||
|
||||
stdout_text = (stdout_bytes or b"").decode("utf-8", errors="replace").strip()
|
||||
try:
|
||||
info = json.loads(stdout_text) if stdout_text else {}
|
||||
except json.JSONDecodeError:
|
||||
err = (stderr_bytes or b"").decode("utf-8", errors="replace").strip()
|
||||
return {**base_status, "resolver_found": True, "ready": False, "error": err or stdout_text}
|
||||
|
||||
return {**info, **base_status, "resolver_found": True}
|
||||
|
||||
|
||||
async def run_scheduled_toolchain_check() -> Optional[dict]:
|
||||
"""供每日午夜定时巡检调用;未配置 Readoor 源码目录时安静跳过。"""
|
||||
resolver = await asyncio.to_thread(discover_toolchain_resolver)
|
||||
if resolver is None:
|
||||
logger.info("每日工具链巡检跳过:尚未发现 iOSGuard 工具链解析器")
|
||||
return None
|
||||
return await ensure_toolchain(resolver, force_rebuild=False, notify_on_event=True)
|
||||
|
||||
|
||||
async def midnight_toolchain_scheduler() -> None:
|
||||
"""后台无限循环:每天本地时间 00:00(可配)跑一次 Xcode/opt 工具链巡检与自愈。"""
|
||||
while True:
|
||||
wait_seconds = seconds_until_next_run(
|
||||
datetime.now(), IG_TOOLCHAIN_DAILY_HOUR, IG_TOOLCHAIN_DAILY_MINUTE
|
||||
)
|
||||
logger.info(
|
||||
"工具链每日巡检已调度:将在 %.0f 秒后(%02d:%02d)执行下一次检查",
|
||||
wait_seconds,
|
||||
IG_TOOLCHAIN_DAILY_HOUR % 24,
|
||||
IG_TOOLCHAIN_DAILY_MINUTE % 60,
|
||||
)
|
||||
await asyncio.sleep(wait_seconds)
|
||||
try:
|
||||
res = await run_scheduled_toolchain_check()
|
||||
if res is not None:
|
||||
logger.info(
|
||||
"每日工具链巡检完成: mode=%s key=%s",
|
||||
res.get("source_mode"),
|
||||
res.get("key"),
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.exception("每日工具链巡检执行异常: %s", exc)
|
||||
@@ -50,6 +50,9 @@ describe('BuildView.vue', () => {
|
||||
expect(wrapper.text()).toContain('打包类型')
|
||||
expect(wrapper.text()).toContain('代码分支')
|
||||
expect(wrapper.text()).toContain('代码混淆')
|
||||
expect(wrapper.text()).toContain('build_policy.json')
|
||||
expect(wrapper.find('#obfuscation').exists()).toBe(true)
|
||||
expect(wrapper.find('#obfuscation').element.checked).toBe(true)
|
||||
})
|
||||
|
||||
it('加载 apps 和 schemes', async () => {
|
||||
@@ -118,7 +121,7 @@ describe('BuildView.vue', () => {
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.vm.form.build_type).toBe('')
|
||||
expect(wrapper.vm.form.obfuscation).toBe(false)
|
||||
expect(wrapper.vm.form.obfuscation).toBe(true)
|
||||
expect(wrapper.vm.form.branch).toBe('main')
|
||||
})
|
||||
|
||||
@@ -154,12 +157,41 @@ describe('BuildView.vue', () => {
|
||||
expect(fetch).toHaveBeenCalledWith('/api/tasks', expect.objectContaining({
|
||||
method: 'POST',
|
||||
}))
|
||||
const post = fetch.mock.calls.find(([url, opts]) => url === '/api/tasks' && opts?.method === 'POST')
|
||||
expect(JSON.parse(post[1].body).obfuscation).toBe(true)
|
||||
expect(wrapper.text()).toContain('打包任务已创建,正在排队,请勿重复点击。')
|
||||
expect(wrapper.vm.form.app_id).toBe('')
|
||||
expect(wrapper.vm.form.build_type).toBe('')
|
||||
expect(wrapper.vm.form.scheme_id).toBe('')
|
||||
})
|
||||
|
||||
it('取消勾选混淆时提交 obfuscation=false(旧分支按勾选执行)', async () => {
|
||||
fetch.mockImplementation((url, opts) => {
|
||||
if (url === '/api/tasks' && opts?.method === 'POST') {
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'test-id', status: 'pending' }) })
|
||||
}
|
||||
const responses = {
|
||||
'/api/apps': { '1': { name: '测试App', server: '测试环境', certificates: { Ad_Hoc: {} } } },
|
||||
'/api/schemes': { '1': { name: 'testScheme' } },
|
||||
'/api/branches': ['main', 'dev'],
|
||||
'/api/tasks': [],
|
||||
}
|
||||
return Promise.resolve({ json: () => Promise.resolve(responses[url] || {}) })
|
||||
})
|
||||
|
||||
const wrapper = mountBuildView()
|
||||
await flushPromises()
|
||||
wrapper.vm.selectedServer = '测试环境'
|
||||
await wrapper.vm.$nextTick()
|
||||
wrapper.vm.form.app_id = '1'
|
||||
await wrapper.find('#obfuscation').setValue(false)
|
||||
await wrapper.find('.btn-primary').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const post = fetch.mock.calls.find(([url, opts]) => url === '/api/tasks' && opts?.method === 'POST')
|
||||
expect(JSON.parse(post[1].body).obfuscation).toBe(false)
|
||||
})
|
||||
|
||||
it('未选择 App 时提示', async () => {
|
||||
window.alert = vi.fn()
|
||||
const wrapper = mountBuildView()
|
||||
|
||||
@@ -51,12 +51,19 @@
|
||||
</optgroup>
|
||||
</select>
|
||||
</div>
|
||||
<div v-if="form.build_type === 'App_Store'" class="form-group">
|
||||
<div class="checkbox-group">
|
||||
<input id="exclude-symbols" v-model="form.exclude_symbols" type="checkbox">
|
||||
<label for="exclude-symbols">安全送检:IPA 不包含 Symbols 目录</label>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="supportsObfuscation" class="form-group">
|
||||
<label>代码混淆</label>
|
||||
<div class="checkbox-group">
|
||||
<input type="checkbox" id="obfuscation" v-model="form.obfuscation">
|
||||
<label for="obfuscation">启用混淆</label>
|
||||
</div>
|
||||
<div class="obfuscation-hint">分支声明强制混淆(AutoPacking/build_policy.json)时始终启用,此勾选仅对旧分支/旧 Tag 生效</div>
|
||||
</div>
|
||||
<p v-if="submitNotice" class="submit-notice" role="status" aria-live="polite">{{ submitNotice }}</p>
|
||||
<button class="btn btn-primary" @click="submitTask" :disabled="submitting">
|
||||
@@ -203,7 +210,8 @@ const form = ref({
|
||||
app_id: '',
|
||||
build_type: '',
|
||||
scheme_id: '',
|
||||
obfuscation: false,
|
||||
exclude_symbols: false,
|
||||
obfuscation: true,
|
||||
branch: 'main',
|
||||
})
|
||||
const submitting = ref(false)
|
||||
@@ -380,7 +388,7 @@ const submitTask = async () => {
|
||||
const res = await authFetch('/api/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...form.value, obfuscation: supportsObfuscation.value && form.value.obfuscation }),
|
||||
body: JSON.stringify({ ...form.value, obfuscation: Boolean(supportsObfuscation.value && form.value.obfuscation) }),
|
||||
})
|
||||
if (res.ok) {
|
||||
const task = await res.json()
|
||||
@@ -392,7 +400,8 @@ const submitTask = async () => {
|
||||
app_id: '',
|
||||
build_type: '',
|
||||
scheme_id: '',
|
||||
obfuscation: false,
|
||||
exclude_symbols: false,
|
||||
obfuscation: Boolean(supportsObfuscation.value),
|
||||
branch: branches.value[0] || 'main',
|
||||
}
|
||||
} else {
|
||||
@@ -472,6 +481,7 @@ const errorCategoryHint = (cat) => {
|
||||
.form-group select:focus { outline: none; border-color: #1890ff; }
|
||||
.checkbox-group { display: flex; align-items: center; gap: 8px; }
|
||||
.checkbox-group input[type="checkbox"] { width: 16px; height: 16px; }
|
||||
.obfuscation-hint { margin-top: 6px; color: #999; font-size: 12px; line-height: 1.4; }
|
||||
.btn { padding: 10px 20px; border: none; border-radius: 6px; font-size: 14px; cursor: pointer; width: 100%; }
|
||||
.btn-primary { background: #1890ff; color: white; }
|
||||
.btn-primary:hover { background: #40a9ff; }
|
||||
|
||||
@@ -444,21 +444,21 @@ const errorCategoryLabel = (cat) => {
|
||||
.config-table th:nth-child(1) { width: 14%; }
|
||||
.config-table th:nth-child(2) { width: 12%; }
|
||||
.config-table th:nth-child(3) { width: 10%; }
|
||||
.config-table th:nth-child(4) { width: 18%; }
|
||||
.config-table th:nth-child(5) { width: 15%; }
|
||||
.config-table th:nth-child(4) { width: 15%; }
|
||||
.config-table th:nth-child(5) { width: 13%; }
|
||||
.config-table th:nth-child(6) { width: 12%; }
|
||||
.config-table th:nth-child(7) { width: 19%; }
|
||||
.config-table th:nth-child(7) { width: 24%; }
|
||||
.config-table tr:hover { background: #fafafa; }
|
||||
|
||||
.build-type-badge { padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 500; }
|
||||
.badge-adhoc { background: #e6f7ff; color: #1890ff; }
|
||||
.badge-appstore { background: #f6ffed; color: #52c41a; }
|
||||
|
||||
.action-btns { white-space: normal; }
|
||||
.action-btns .action-btn { margin-right: 6px; margin-bottom: 4px; display: inline-block; vertical-align: middle; }
|
||||
.download-cell { white-space: normal; }
|
||||
.config-table td.action-btns { white-space: normal; overflow: visible; text-overflow: clip; }
|
||||
.config-table td.action-btns .action-btn { margin-right: 6px; margin-bottom: 4px; display: inline-block; vertical-align: middle; }
|
||||
.config-table td.download-cell { white-space: normal; overflow: visible; text-overflow: clip; }
|
||||
.scheme-cell { white-space: normal !important; overflow: visible !important; text-overflow: clip !important; overflow-wrap: anywhere; }
|
||||
.action-btn { padding: 4px 12px; border: 1px solid #d9d9d9; border-radius: 4px; background: white; cursor: pointer; font-size: 12px; }
|
||||
.action-btn { padding: 4px 10px; border: 1px solid #d9d9d9; border-radius: 4px; background: white; cursor: pointer; font-size: 12px; }
|
||||
.action-btn:hover { border-color: #1890ff; color: #1890ff; }
|
||||
|
||||
.task-status { padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 500; }
|
||||
|
||||
@@ -247,3 +247,15 @@ def test_history_hides_superseded_tasks_except_for_admin(client, tmp_config):
|
||||
|
||||
assert [task["id"] for task in client.get("/api/tasks").json()] == ["visible"]
|
||||
assert {task["id"] for task in client.get("/api/tasks?include_superseded=true").json()} == {"visible", "covered"}
|
||||
|
||||
|
||||
@patch("backend.services.build_queue.build_queue")
|
||||
def test_create_task_keeps_obfuscation_choice_for_supported_project(mock_queue, client, tmp_config):
|
||||
"""任务记录用户勾选;分支声明强制混淆时由打包阶段覆盖,这里不提前强制。"""
|
||||
mock_queue.submit = AsyncMock()
|
||||
payload = {"app_id": "1", "build_type": "Ad_Hoc", "scheme_id": "1", "branch": "main"}
|
||||
off = client.post("/api/tasks", json={**payload, "obfuscation": False})
|
||||
on = client.post("/api/tasks", json={**payload, "obfuscation": True})
|
||||
assert off.status_code == 200 and on.status_code == 200
|
||||
assert off.json()["obfuscation"] is False
|
||||
assert on.json()["obfuscation"] is True
|
||||
|
||||
+493
-3
@@ -22,6 +22,8 @@ from backend.services.build_service import (
|
||||
_cleanup_old_builds,
|
||||
_mark_superseded_tasks,
|
||||
_resolve_provisioning_profile,
|
||||
_classify_build_error,
|
||||
BuildError,
|
||||
)
|
||||
from backend.services.log_streamer import LogStreamer
|
||||
|
||||
@@ -202,14 +204,45 @@ async def test_copy_source_code(tmp_dirs, log_streamer):
|
||||
assert result.exists()
|
||||
assert (result / "readoor" / "AppDelegate.swift").exists()
|
||||
assert (result / "Pods").exists()
|
||||
assert (result / "Podfile").exists()
|
||||
assert not (result / "podfile").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
|
||||
@@ -295,6 +328,28 @@ async def test_run_pod_install_uses_xcode_subdirectory(tmp_path, log_streamer):
|
||||
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"
|
||||
@@ -308,7 +363,8 @@ async def test_build_project_passes_scheme_as_exec_argument(tmp_path, log_stream
|
||||
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 not any(c.args[0:2] == ("xcodebuild", "clean") for c in mock_exec.call_args_list)
|
||||
archive_args = mock_exec.call_args_list[0].args
|
||||
assert archive_args[0:2] == ("xcodebuild", "archive")
|
||||
assert "App; touch /tmp/should-not-run" in archive_args
|
||||
|
||||
@@ -655,3 +711,437 @@ def test_mark_superseded_tasks_for_same_oss_url():
|
||||
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:3] == ("-u", str(branch_obf_py))
|
||||
assert mock_exec.call_args_list[1].kwargs["env"]["PYTHONUNBUFFERED"] == "1"
|
||||
|
||||
# 移除分支脚本后回退到服务端脚本
|
||||
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:3] == ("-u", 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
|
||||
|
||||
|
||||
# ---- 打包加速:seed 复用与 APFS CoW 回退 ----
|
||||
|
||||
def test_resolve_release_seed_reuses_for_adhoc_and_sanitizes(monkeypatch):
|
||||
"""Ad_Hoc 按分支+版本稳定复用 seed 且不含 `__`;App_Store 每次含 task_id;显式配置优先。"""
|
||||
from backend.services.build_service import _resolve_release_seed
|
||||
|
||||
monkeypatch.delenv("IG_RELEASE_SEED", raising=False)
|
||||
cfg = {"BUILD_TYPE": "Ad_Hoc", "SOURCE_BRANCH": "feat/llvm-obf__m0", "BUILD_VERSION": "2.201.0.0"}
|
||||
seed1 = _resolve_release_seed("task-a", cfg)
|
||||
seed2 = _resolve_release_seed("task-b", cfg)
|
||||
assert seed1 == seed2 == "adhoc_feat_llvm_obf_m0_2_201_0_0"
|
||||
assert "__" not in seed1
|
||||
|
||||
appstore_seed = _resolve_release_seed("task-a", {**cfg, "BUILD_TYPE": "App_Store"})
|
||||
assert appstore_seed == "task-a_2.201.0.0"
|
||||
|
||||
assert _resolve_release_seed("task-a", {**cfg, "IG_RELEASE_SEED": "cfg_seed"}) == "cfg_seed"
|
||||
monkeypatch.setenv("IG_RELEASE_SEED", "env_seed")
|
||||
assert _resolve_release_seed("task-a", {**cfg, "IG_RELEASE_SEED": "cfg_seed"}) == "env_seed"
|
||||
|
||||
|
||||
async def test_run_obfuscation_seed_matches_llvm_env_and_unbuffered(tmp_path, monkeypatch):
|
||||
"""L1 OBF_SALT 与 LLVM IG_RELEASE_SEED 对同一 Ad_Hoc 分支/版本保持一致,且开启无缓冲输出。"""
|
||||
from backend.services.build_service import run_obfuscation, _prepare_iosguard_build_env
|
||||
|
||||
monkeypatch.delenv("IG_RELEASE_SEED", raising=False)
|
||||
build_dir = tmp_path / "snap"
|
||||
obf = build_dir / "AutoPacking" / "obfuscation"
|
||||
(obf / "scripts").mkdir(parents=True)
|
||||
(obf / "scripts" / "obfuscation_self_check.sh").write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
|
||||
(obf / "obfuscate_symbols.py").write_text("# stub\n", encoding="utf-8")
|
||||
|
||||
cfg = {
|
||||
"SCHEME": "readoor31OtherPay",
|
||||
"BUILD_TYPE": "Ad_Hoc",
|
||||
"SOURCE_BRANCH": "readoor-test",
|
||||
"BUILD_VERSION": "2.201.0.0",
|
||||
}
|
||||
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec:
|
||||
await run_obfuscation("t-adhoc-1", MagicMock(), cfg, build_dir)
|
||||
obf_call = mock_exec.call_args_list[1]
|
||||
assert obf_call.args[1] == "-u"
|
||||
assert obf_call.kwargs["env"]["PYTHONUNBUFFERED"] == "1"
|
||||
obf_salt = obf_call.kwargs["env"]["OBF_SALT"]
|
||||
assert obf_salt == "adhoc_readoor_test_2_201_0_0"
|
||||
|
||||
with patch("backend.services.build_service.IG_CACHE_DIR", tmp_path / "cache"):
|
||||
llvm_env = await _prepare_iosguard_build_env("t-adhoc-2", cfg, build_dir)
|
||||
assert llvm_env["IG_RELEASE_SEED"] == obf_salt
|
||||
|
||||
|
||||
async def test_copy_source_code_falls_back_when_cow_clone_fails(tmp_dirs):
|
||||
"""APFS cp -c -R 失败时自动清理半成品并回退 shutil.copytree,且仍排除 .git。"""
|
||||
source_dir, build_dir_parent = tmp_dirs
|
||||
(source_dir / "readoor" / ".git").mkdir()
|
||||
|
||||
def failing_cp(*args, **kwargs):
|
||||
return MagicMock(returncode=1)
|
||||
|
||||
with patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \
|
||||
patch("backend.services.build_service.subprocess.run", side_effect=failing_cp):
|
||||
result = await copy_source_code("t-fallback", MagicMock(), source_dir)
|
||||
|
||||
assert (result / "readoor" / "AppDelegate.swift").exists()
|
||||
assert not (result / "readoor" / ".git").exists()
|
||||
|
||||
|
||||
def test_classify_build_error_prefers_swift_compile_over_normal_provisioning_mentions():
|
||||
"""正常构建日志含 embedded.mobileprovision / PROVISIONING_PROFILE_SPECIFIER 时,不应盖过编译错误。"""
|
||||
lines = [
|
||||
"CodeSign /tmp/build/readoor.app/embedded.mobileprovision",
|
||||
"PROVISIONING_PROFILE_SPECIFIER = abc_adhoc",
|
||||
"Foo.swift:10:1: error: type 'Bar' does not conform to protocol 'Baz'",
|
||||
]
|
||||
category, hint = _classify_build_error(lines, "archive")
|
||||
assert category == "compilation"
|
||||
assert "Swift" in hint
|
||||
|
||||
assert _classify_build_error(["error: No profiles for 'com.foo' were found"], "archive")[0] == "provisioning"
|
||||
assert _classify_build_error(["No matching provisioning profiles found"], "archive")[0] == "provisioning"
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"""服务端工程配置替换测试。"""
|
||||
import plistlib
|
||||
|
||||
from backend.services.project_patcher import apply_project_config
|
||||
import pytest
|
||||
|
||||
from backend.services.project_patcher import ProjectPatchError, _write_export_options, apply_project_config
|
||||
|
||||
|
||||
def test_apply_project_config_without_branch_autopacking(tmp_path):
|
||||
@@ -111,3 +113,109 @@ def test_wxwork_schema_removed_when_not_configured(tmp_path):
|
||||
with plist_path.open("rb") as f:
|
||||
url_types = plistlib.load(f)["CFBundleURLTypes"]
|
||||
assert all(i.get("CFBundleURLName") != "wxwork" for i in url_types)
|
||||
|
||||
|
||||
# ---- 英汉大词典(readoorDict)----
|
||||
|
||||
_DICT_MACRO = """#define SOURCE_VERSION @"1.0.0"
|
||||
#if TARGETTYPE == 1 || TARGETTYPE == 3
|
||||
#define APPID @"other"
|
||||
#define SERVERURL @"http://other/"
|
||||
#elif TARGETTYPE == 2
|
||||
//#define SERVERURL @"http://commented/"
|
||||
#define APPID @"old" //旧环境
|
||||
#define SERVERURL @"http://old/"
|
||||
#define SERVERHTTPSURL @"https://old/"
|
||||
#define UCSERVERURL @"https://uc-old/"
|
||||
#define RECORDSERVERURL @"http://record-old/"
|
||||
#define LOGSERVERURL @"http://log-old/"
|
||||
#endif
|
||||
"""
|
||||
|
||||
_DICT_SERVER_VARS = {
|
||||
"DICT_SERVERURL": "http://api-stage3/",
|
||||
"DICT_SERVERHTTPSURL": "https://api-stage3/",
|
||||
"DICT_UCSERVERURL": "https://uc-dev/",
|
||||
"DICT_RECORDSERVERURL": "http://record-dev/",
|
||||
"DICT_LOGSERVERURL": "http://log-dev/",
|
||||
}
|
||||
|
||||
|
||||
def _dict_build(tmp_path):
|
||||
macro = tmp_path / "readoor" / "BookShelf" / "Classes" / "Macro" / "STSConstantsMacro.h"
|
||||
macro.parent.mkdir(parents=True)
|
||||
macro.write_text(_DICT_MACRO, encoding="utf-8")
|
||||
project = tmp_path / "readoor.xcodeproj"
|
||||
project.mkdir()
|
||||
(project / "project.pbxproj").write_text(
|
||||
"\t\t\t\tMARKETING_VERSION = 2.192.3;\n\t\t\t\tCURRENT_PROJECT_VERSION = 2.192.3;\n", encoding="utf-8"
|
||||
)
|
||||
return macro
|
||||
|
||||
|
||||
def _dict_config(**extra):
|
||||
return {"SCHEME": "readoorDict", "VERSION": "2.0.0", "BUILD_VERSION": "2.0.0.3",
|
||||
"SERVER": "词典测试", "APPID": "1593413622",
|
||||
"NO_CERT": True, "BUILD_TYPE": "Ad_Hoc", **extra}
|
||||
|
||||
|
||||
def test_dict_env_macros_replaced_only_in_targettype_2(tmp_path):
|
||||
macro = _dict_build(tmp_path)
|
||||
apply_project_config(tmp_path, _dict_config(SERVER_VARS=_DICT_SERVER_VARS), {"patcher": "readoor"})
|
||||
content = macro.read_text()
|
||||
|
||||
assert '#define SOURCE_VERSION @"2.0.0"' in content
|
||||
pbxproj = (tmp_path / "readoor.xcodeproj" / "project.pbxproj").read_text()
|
||||
assert "MARKETING_VERSION = 2.0.0;" in pbxproj
|
||||
assert "CURRENT_PROJECT_VERSION = 2.0.0.3;" in pbxproj
|
||||
assert "2.192.3" not in pbxproj
|
||||
assert '#define APPID @"1593413622"' in content
|
||||
assert '#define SERVERURL @"http://api-stage3/"' in content
|
||||
assert '#define LOGSERVERURL @"http://log-dev/"' in content
|
||||
# 其它 TARGETTYPE 与注释行不变
|
||||
assert '#define APPID @"other"' in content
|
||||
assert '#define SERVERURL @"http://other/"' in content
|
||||
assert '//#define SERVERURL @"http://commented/"' in content
|
||||
assert "http://old/" not in content
|
||||
|
||||
|
||||
def test_dict_env_not_configured_keeps_source(tmp_path):
|
||||
macro = _dict_build(tmp_path)
|
||||
messages = apply_project_config(tmp_path, _dict_config(SERVER_VARS={}), {"patcher": "readoor"})
|
||||
content = macro.read_text()
|
||||
|
||||
assert '#define SERVERURL @"http://old/"' in content
|
||||
assert '#define APPID @"old"' in content
|
||||
assert any("沿用源码" in m for m in messages)
|
||||
|
||||
|
||||
def test_dict_env_partially_configured_fails(tmp_path):
|
||||
_dict_build(tmp_path)
|
||||
with pytest.raises(ProjectPatchError, match="DICT_LOGSERVERURL"):
|
||||
apply_project_config(
|
||||
tmp_path,
|
||||
_dict_config(SERVER_VARS={**_DICT_SERVER_VARS, "DICT_LOGSERVERURL": ""}),
|
||||
{"patcher": "readoor"},
|
||||
)
|
||||
|
||||
|
||||
def test_readoor_definition_has_dict_server_fields():
|
||||
from backend.projects import LEGACY_PROJECT_ID, get_definition
|
||||
|
||||
keys = [f["key"] for f in get_definition(LEGACY_PROJECT_ID, {"server_fields": []})["server_fields"]]
|
||||
assert keys == ["DICT_SERVERURL", "DICT_SERVERHTTPSURL", "DICT_UCSERVERURL",
|
||||
"DICT_RECORDSERVERURL", "DICT_LOGSERVERURL"]
|
||||
assert get_definition("other", {"patcher": "generic"})["server_fields"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("no_cert", [False, True])
|
||||
@pytest.mark.parametrize("build_type,exclude,expected", [
|
||||
("App_Store", True, False),
|
||||
("App_Store", False, None),
|
||||
("Ad_Hoc", True, None),
|
||||
])
|
||||
def test_export_symbols_option(tmp_path, no_cert, build_type, exclude, expected):
|
||||
config = {"NO_CERT": no_cert, "BUILD_TYPE": build_type, "EXCLUDE_SYMBOLS": exclude}
|
||||
_write_export_options(tmp_path, config)
|
||||
options = plistlib.loads((tmp_path / "exportOptions.plist").read_bytes())
|
||||
assert options.get("uploadSymbols") is expected
|
||||
|
||||
@@ -223,7 +223,8 @@ async def test_build_uses_xcodeproj_when_no_workspace(tmp_path):
|
||||
with pytest.raises(Exception, match="未找到 IPA 文件"):
|
||||
await build_project("t1", MagicMock(), {"SCHEME": "DyAuction"}, tmp_path,
|
||||
{"workspace": "", "project": "DyAuction.xcodeproj"})
|
||||
archive_args = mock_exec.call_args_list[1].args
|
||||
archive_args = mock_exec.call_args_list[0].args
|
||||
assert archive_args[0:2] == ("xcodebuild", "archive")
|
||||
assert ("-project", "DyAuction.xcodeproj") == archive_args[2:4]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"""iOSGuard 工具链管理器、午夜定时巡检及管理接口测试。"""
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.notification import send_toolchain_dingtalk_alert
|
||||
from backend.services.toolchain_manager import (
|
||||
ensure_toolchain,
|
||||
get_toolchain_status,
|
||||
seconds_until_next_run,
|
||||
)
|
||||
|
||||
|
||||
def test_seconds_until_next_run_midnight():
|
||||
assert seconds_until_next_run(datetime(2026, 11, 23, 23, 50, 0), 0, 0) == pytest.approx(600.0)
|
||||
assert seconds_until_next_run(datetime(2026, 11, 23, 0, 10, 0), 0, 0) == pytest.approx(85800.0)
|
||||
assert seconds_until_next_run(datetime(2026, 11, 23, 0, 0, 0), 0, 0) == pytest.approx(86400.0)
|
||||
|
||||
|
||||
def test_send_toolchain_dingtalk_alert_contains_required_keyword():
|
||||
mock_resp = MagicMock(status_code=200)
|
||||
mock_resp.json.return_value = {"errcode": 0}
|
||||
with patch("backend.services.notification.httpx.post", return_value=mock_resp) as mock_post:
|
||||
ok = send_toolchain_dingtalk_alert(
|
||||
{"enabled": True, "webhook_url": "https://oapi.dingtalk.com/robot/send?access_token=abc", "at_mobiles": ["13800001111"]},
|
||||
"Xcode 工具链异常",
|
||||
["**Xcode:** 28.0"],
|
||||
)
|
||||
assert ok is True
|
||||
sent_payload = mock_post.call_args.kwargs["json"]
|
||||
assert "打包" in sent_payload["markdown"]["title"]
|
||||
assert "打包" in sent_payload["markdown"]["text"]
|
||||
assert "@13800001111" in sent_payload["markdown"]["text"]
|
||||
|
||||
|
||||
def _fake_stream_proc(returncode=0, stdout_payload=None, stderr_lines=(), delay=0.0):
|
||||
proc = AsyncMock()
|
||||
proc.returncode = returncode
|
||||
|
||||
out_bytes = (json.dumps(stdout_payload or {}) + "\n").encode("utf-8")
|
||||
err_queue = list(stderr_lines)
|
||||
|
||||
async def read_stdout():
|
||||
if delay:
|
||||
await asyncio.sleep(delay)
|
||||
return out_bytes
|
||||
|
||||
async def readline_stderr():
|
||||
if err_queue:
|
||||
return (err_queue.pop(0) + "\n").encode("utf-8")
|
||||
return b""
|
||||
|
||||
proc.stdout = MagicMock()
|
||||
proc.stdout.read = AsyncMock(side_effect=read_stdout)
|
||||
proc.stderr = MagicMock()
|
||||
proc.stderr.readline = AsyncMock(side_effect=readline_stderr)
|
||||
proc.wait = AsyncMock(return_value=returncode)
|
||||
proc.kill = MagicMock()
|
||||
return proc
|
||||
|
||||
|
||||
async def test_ensure_toolchain_lock_serialization_and_alert_policy(tmp_path):
|
||||
resolver = tmp_path / "ig_toolchain_resolver.py"
|
||||
resolver.write_text("# stub\n", encoding="utf-8")
|
||||
|
||||
# 1) source_mode == "cached" 不发钉钉通知;并发调用在锁上串行
|
||||
calls = 0
|
||||
|
||||
async def fake_exec(*args, **kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
return _fake_stream_proc(
|
||||
0,
|
||||
{"opt_path": "/cache/opt", "source_mode": "cached", "xcode": {"xcode_build": "27A9275"}, "passes_hash": "abcd1234"},
|
||||
delay=0.05,
|
||||
)
|
||||
|
||||
with patch("asyncio.create_subprocess_exec", side_effect=fake_exec), \
|
||||
patch("backend.services.toolchain_manager._load_dingtalk_config", return_value={"enabled": True, "webhook_url": "https://dt"}), \
|
||||
patch("backend.services.toolchain_manager.send_toolchain_dingtalk_alert") as mock_alert, \
|
||||
patch("backend.services.toolchain_manager.log_streamer") as mock_log:
|
||||
mock_log.emit = AsyncMock()
|
||||
r1, r2 = await asyncio.gather(
|
||||
ensure_toolchain(resolver, task_id="t1", notify_on_event=True),
|
||||
ensure_toolchain(resolver, task_id="t2", notify_on_event=True),
|
||||
)
|
||||
assert calls == 2
|
||||
assert r1["source_mode"] == "cached" and r2["source_mode"] == "cached"
|
||||
mock_alert.assert_not_called()
|
||||
assert any("等待其他任务" in c.args[1] for c in mock_log.emit.call_args_list if c.args[0] == "t2")
|
||||
|
||||
# 2) source_mode == "reused" 触发钉钉成功告警;失败触发钉钉失败告警
|
||||
with patch(
|
||||
"asyncio.create_subprocess_exec",
|
||||
return_value=_fake_stream_proc(
|
||||
0,
|
||||
{
|
||||
"opt_path": "/cache/opt",
|
||||
"opt_sha256": "deadbeef12345678",
|
||||
"source_mode": "reused",
|
||||
"xcode": {"xcode_version": "27.2", "xcode_build": "27B100"},
|
||||
"swift": {"swift_version": "6.4", "swiftlang_version": "6.4.0"},
|
||||
},
|
||||
),
|
||||
), \
|
||||
patch("backend.services.toolchain_manager._load_dingtalk_config", return_value={"enabled": True, "webhook_url": "https://dt"}), \
|
||||
patch("backend.services.toolchain_manager.send_toolchain_dingtalk_alert", return_value=True) as mock_alert:
|
||||
res_reused = await ensure_toolchain(resolver, notify_on_event=True)
|
||||
assert res_reused["source_mode"] == "reused"
|
||||
assert mock_alert.call_count == 1
|
||||
assert "已自动更新" in mock_alert.call_args.args[1]
|
||||
|
||||
with patch(
|
||||
"asyncio.create_subprocess_exec",
|
||||
return_value=_fake_stream_proc(1, {"error": "cmake compile failed"}),
|
||||
), \
|
||||
patch("backend.services.toolchain_manager._load_dingtalk_config", return_value={"enabled": True, "webhook_url": "https://dt"}), \
|
||||
patch("backend.services.toolchain_manager.send_toolchain_dingtalk_alert", return_value=True) as mock_alert_fail:
|
||||
with pytest.raises(RuntimeError, match="cmake compile failed"):
|
||||
await ensure_toolchain(resolver, notify_on_event=True)
|
||||
assert mock_alert_fail.call_count == 1
|
||||
assert "更新失败" in mock_alert_fail.call_args.args[1]
|
||||
|
||||
|
||||
def test_admin_toolchain_endpoints_and_permissions(client, tmp_config, tmp_path):
|
||||
# 非管理员禁止访问 /api/config/toolchain*
|
||||
client.post("/api/users", json={"username": "dev1", "password": "dev-password-123", "is_admin": False})
|
||||
tok = client.post("/api/auth/login", json={"username": "dev1", "password": "dev-password-123"}).json()["token"]
|
||||
non_admin_headers = {"Authorization": f"Bearer {tok}"}
|
||||
|
||||
assert client.get("/api/config/toolchain", headers=non_admin_headers).status_code == 403
|
||||
assert client.post("/api/config/toolchain/refresh", headers=non_admin_headers).status_code == 403
|
||||
|
||||
with patch("backend.services.toolchain_manager.get_toolchain_status", new_callable=AsyncMock, return_value={"ready": True, "daily_check_enabled": True}):
|
||||
resp = client.get("/api/config/toolchain")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["ready"] is True
|
||||
|
||||
fake_resolver = tmp_path / "ig_toolchain_resolver.py"
|
||||
fake_resolver.write_text("# stub\n", encoding="utf-8")
|
||||
with patch("backend.services.toolchain_manager.discover_toolchain_resolver", return_value=fake_resolver), \
|
||||
patch("backend.services.toolchain_manager.ensure_toolchain", new_callable=AsyncMock, return_value={"source_mode": "built"}) as mock_ens:
|
||||
r_ref = client.post("/api/config/toolchain/refresh", json={"force_rebuild": True})
|
||||
assert r_ref.status_code == 200
|
||||
assert r_ref.json()["source_mode"] == "built"
|
||||
assert mock_ens.call_args.kwargs["force_rebuild"] is True
|
||||
|
||||
|
||||
async def test_get_toolchain_status_without_resolver():
|
||||
with patch("backend.services.toolchain_manager.discover_toolchain_resolver", return_value=None):
|
||||
st = await get_toolchain_status()
|
||||
assert st["resolver_found"] is False
|
||||
assert st["ready"] is False
|
||||
assert "next_scheduled_check" in st
|
||||
Reference in New Issue
Block a user