fix(network): 禁止公网查询持久化缓存及会话数据

This commit is contained in:
2026-11-04 14:56:06 +08:00
parent f3a571d5bc
commit 4e95ce203a
9 changed files with 98 additions and 12 deletions
+4
View File
@@ -95,3 +95,7 @@ ProcessEnergyMonitor 在相同身份、Mach 启动标记和连续有效计数间
ProcessMonitor 负责枚举、身份、CPU / 线程 / 路径;不把 RSS 写入进程内存列。SystemSampler 现有 processTask 在 utility 枚举后调用 Core/Services/ProcessMemoryServiceClient,经 SMARTServiceProtocol.readProcessMemory 请求现有签名认证的 SMARTService。ProcessMemoryReader(与能量读取器同文件编译)使用独立锁和 RUSAGE_INFO_V4,按同 UID、正 PID、启动时间及前后身份复核读取 footprint;不受 CPU 能量 arm64 能力门槛影响。 ProcessMonitor 负责枚举、身份、CPU / 线程 / 路径;不把 RSS 写入进程内存列。SystemSampler 现有 processTask 在 utility 枚举后调用 Core/Services/ProcessMemoryServiceClient,经 SMARTServiceProtocol.readProcessMemory 请求现有签名认证的 SMARTService。ProcessMemoryReader(与能量读取器同文件编译)使用独立锁和 RUSAGE_INFO_V4,按同 UID、正 PID、启动时间及前后身份复核读取 footprint;不受 CPU 能量 arm64 能力门槛影响。
批量上限 256 项、请求 64 KiB、响应 256 KiB,客户端总截止 3 秒 / 单请求 1.5 秒,服务每批 1 秒;不增加权限、不扫描 VM、不新增周期任务。ProcessSnapshot.withMemory 以完整身份合并,缺失即 nil,随后才发布列表并触发原能量调度。保留单在途、隐藏 / 重开代际校验;列表显示及排序只消费 footprintBytes。XPC 失败仍发布 CPU 等其余指标,内存显示 --;不混用 RSS。细节及验证见[内存口径修正](process-memory-alignment-plan.md)。 批量上限 256 项、请求 64 KiB、响应 256 KiB,客户端总截止 3 秒 / 单请求 1.5 秒,服务每批 1 秒;不增加权限、不扫描 VM、不新增周期任务。ProcessSnapshot.withMemory 以完整身份合并,缺失即 nil,随后才发布列表并触发原能量调度。保留单在途、隐藏 / 重开代际校验;列表显示及排序只消费 footprintBytes。XPC 失败仍发布 CPU 等其余指标,内存显示 --;不混用 RSS。细节及验证见[内存口径修正](process-memory-alignment-plan.md)。
## 网络数据持久化约束
PublicIPAddressService 默认持有专用 ephemeral URLSession,URLCache / HTTPCookieStorage / URLCredentialStorage 均为 nil,禁用 Cookie 自动处理;不使用 shared 网络会话,服务销毁时撤销自建会话,注入会话由测试调用方管理。600 秒结果 / 30 秒失败缓存仍只在 actor 内存中,路由 / 可见性 / 取消行为不变。生产查询不主动生成 HTTP 缓存、Cookie 或凭据数据库;该保证不覆盖 macOS 自身日志、崩溃报告、容器元数据,也不意味着旧版本缓存自动消失。偏好设置继续持久化。验证及旧缓存清理状态见[不持久化网络数据](no-persistent-network-data-plan.md)。
+2
View File
@@ -69,3 +69,5 @@ AppleSMC 和 GPU 驱动字段不是稳定公开的跨机型指标接口,缺失
进程表“内存”与内存排序使用 proc_pid_rusage(RUSAGE_INFO_V4).ri_phys_footprint,按 1,048,576 字节折算并沿用活动监视器的 MB 标签;不使用 PROC_PIDTASKALLINFO.pti_resident_size(RSS)。[Apple WWDC22](https://developer.apple.com/videos/play/wwdc2022/10106/) 说明 Activity Monitor 使用 footprint。RSS 包括可回收的干净驻留页,而 footprint 包含压缩等归属账目,两者无固定换算比例。 进程表“内存”与内存排序使用 proc_pid_rusage(RUSAGE_INFO_V4).ri_phys_footprint,按 1,048,576 字节折算并沿用活动监视器的 MB 标签;不使用 PROC_PIDTASKALLINFO.pti_resident_size(RSS)。[Apple WWDC22](https://developer.apple.com/videos/play/wwdc2022/10106/) 说明 Activity Monitor 使用 footprint。RSS 包括可回收的干净驻留页,而 footprint 包含压缩等归属账目,两者无固定换算比例。
沙盒主程序不能直接取得其他进程 rusage,因此通过原有签名认证只读 XPC、按完整 ProcessIdentity 请求同 UID footprint。数据合并在单在途进程任务结束前完成;读取失败显示 --,不回退 RSS 或沿用旧值。保护进程 / 其他 UID 可能不可读,辅助进程独立统计。刷新时刻不同仍允许短时波动。来源核对与边界见[修正记录](process-memory-alignment-plan.md)。系统总内存卡片口径不变。 沙盒主程序不能直接取得其他进程 rusage,因此通过原有签名认证只读 XPC、按完整 ProcessIdentity 请求同 UID footprint。数据合并在单在途进程任务结束前完成;读取失败显示 --,不回退 RSS 或沿用旧值。保护进程 / 其他 UID 可能不可读,辅助进程独立统计。刷新时刻不同仍允许短时波动。来源核对与边界见[修正记录](process-memory-alignment-plan.md)。系统总内存卡片口径不变。
公网 IP 网络会话使用 ephemeral 配置并关闭 URLCache、Cookie 与凭据存储;已有 600 秒 / 30 秒缓存是进程内数据,不写磁盘。签名沙盒网络检查直接调用生产服务,核对重复 / 新路由 HTTPS 查询后持久网络目录未新增或变更文件。
+17
View File
@@ -0,0 +1,17 @@
# 公网查询不持久化网络数据
2026-11-04。此前审计发现 URLSession.shared 生成 HTTP 缓存及 HTTPStorages SQLite 文件。目标:生产公网查询使用临时会话、关闭缓存 / Cookie / 凭据持久化,仅保留 600 秒内存结果和 30 秒失败退避;不改动视觉、采样周期、设置持久化、签名或权限。
涉及 Core/Services/PublicIPAddressService、对应独立及签名沙盒网络检查、文档。不新增依赖、清理定时器或产品设置。自建会话在服务销毁时撤销,注入测试会话仍由调用者管理。
实施:构造单一 ephemeral 配置,URLCache / HTTPCookieStorage / URLCredentialStorage 均 nil、禁用 Cookie,默认生产路径不再使用 shared;让真实沙盒 HTTPS 检查调用生产服务,检查请求后持久网络目录没有新增文件。保留路由切换、取消、错误退避和内存缓存行为回归。
旧缓存仅清理该 bundle 的 HTTP 缓存和 HTTPStorages,不删偏好、容器或系统元数据。旧程序运行时不操作 SQLite 文件,先等待退出;不创建清理后台任务,不扫描其他软件目录。清理与新数据策略分别验收。
验证:Debug / 普通 Release 构建,公网服务回归、签名沙盒真实 HTTPS 与磁盘检查;生产代码没有文件写入 API,仍不承诺 macOS 自身日志 / 崩溃 / 容器元数据零写盘。验证结果完成后补充。
## 实测结果
Debug 与普通 Release 构建均通过;公网服务回归和签名沙盒生产 HTTPS 检查通过,211 条三语言目录与 host entitlement 检查通过。真实网络检查覆盖重复查询和新路由,等待 1 秒后比较 Caches / HTTPStorages / Cookies / WebKit 的常规文件路径、大小与修改时间,无新增或变更。Debug、Release 对应的两项检查及目录 / 权限检查均通过。网络测试 runner 按本轮生成的随机 bundle ID 精确清理自己的临时沙盒容器,不触碰产品容器。未以配置断言代替实际请求。
旧版 PID 36781 仍由用户 Xcode 运行,不能在 SQLite 被使用时删除。已请用户停止旧版,当前保留旧缓存及偏好;没有退出用户进程、添加启动清理或清理定时器。新代码只保证不再由该查询持久化网络数据;不把旧缓存尚存说成已清理。
+1 -1
View File
@@ -25,7 +25,7 @@
主容器本次合计 898,998 字节(含系统元数据及偏好),XPC 容器仅见约 28.7 KB 元数据;未发现应用自行创建的外部 Application Support / Caches 数据目录。没有自行安装 LaunchAgent、常驻特权 helper、采样数据库或落盘趋势历史的代码。外部 diskutil 输出经有界管道处理,不落盘。 主容器本次合计 898,998 字节(含系统元数据及偏好),XPC 容器仅见约 28.7 KB 元数据;未发现应用自行创建的外部 Application Support / Caches 数据目录。没有自行安装 LaunchAgent、常驻特权 helper、采样数据库或落盘趋势历史的代码。外部 diskutil 输出经有界管道处理,不落盘。
公网 IP 查询当前使用 URLSession.shared,request.cachePolicy 忽略已有缓存并不禁止 HTTP 缓存 / cookies / 存储写盘。因此不能称为零缓存,也没有长期测量证明当前存储不会增长。若要求进一步收敛,应将生产公网查询切到 ephemeral 会话,并显式禁用 URLCache、cookie storage、credential storage;保留已有 10 分钟进程内结果缓存。旧数据清理需在退出相关进程后另行操作,本次未删除用户数据。 上述审计时公网 IP 查询仍使用 URLSession.shared。随后已改为专用 ephemeral 会话,显式禁用 URLCache、cookie storage、credential storage;保留已有 10 分钟进程内结果缓存。签名沙盒真实 HTTPS 短时检查确认持久网络目录未新增或变更文件。旧版生成的数据须在退出旧进程后单独清理,具体状态见[实施记录](no-persistent-network-data-plan.md)。
## 验证边界 ## 验证边界
+4
View File
@@ -325,3 +325,7 @@ Release 配置由各 Target 在签名前 strip,保留包外 dSYM;测量必
## 进程内存口径回归 ## 进程内存口径回归
ProcessEnergyReaderChecks 同时验证独立于能量能力的 ProcessMemoryReader:真实 footprint 与 TASK_VM_INFO.phys_footprint 接近、错启动时间 / 零 PID / 其他 UID 拒绝、重复 PID / 大包 / 解码 / 批量上限、完整身份合并、缺失清空和有效零。ProcessSelectionChecks 检查 footprint 双向排序及缺失置后;NativeProcessTableChecks 在真实原生表格检查活动监视器一致的二进制 MB 显示。端到端签名沙盒 → XPC → 表格及同 PID 对照记录见[内存修正记录](process-memory-alignment-plan.md)。不同时间点的截图不能要求逐字节相等。 ProcessEnergyReaderChecks 同时验证独立于能量能力的 ProcessMemoryReader:真实 footprint 与 TASK_VM_INFO.phys_footprint 接近、错启动时间 / 零 PID / 其他 UID 拒绝、重复 PID / 大包 / 解码 / 批量上限、完整身份合并、缺失清空和有效零。ProcessSelectionChecks 检查 footprint 双向排序及缺失置后;NativeProcessTableChecks 在真实原生表格检查活动监视器一致的二进制 MB 显示。端到端签名沙盒 → XPC → 表格及同 PID 对照记录见[内存修正记录](process-memory-alignment-plan.md)。不同时间点的截图不能要求逐字节相等。
## 无持久网络数据检查
PublicIPAddressChecks 使用生产 sessionConfiguration,验证缓存 / Cookie / 凭据存储禁用,保留内存缓存、错误重试、连续刷新、路由切换与取消行为。SandboxNetworkChecks 编译生产 PublicIPAddressService,使用构建产物真实 entitlement 在独立签名沙盒中执行有效 HTTPS、重复查询和新路由查询,对比请求前后 Library/Caches、HTTPStorages、Cookies、WebKit 内常规文件的路径、大小与修改时间,避免仅检查配置就声称无落盘。只输出成功 / 失败,不记录公网 IP。网络 / 网络接口测试在 finally 中清理本轮随机 bundle ID 对应的临时容器,遇到非本工具标识或符号链接拒绝删除,真实应用容器不在范围内。该短时检查不证明 macOS 系统级零写盘或长期行为。
@@ -5,20 +5,37 @@ import Darwin
actor PublicIPAddressService { actor PublicIPAddressService {
static let shared = PublicIPAddressService() static let shared = PublicIPAddressService()
private let session: URLSession private let session: URLSession
private let ownsSession: Bool
private let cacheLifetime: TimeInterval private let cacheLifetime: TimeInterval
private let retryInterval: TimeInterval private let retryInterval: TimeInterval
private let now: @Sendable () -> TimeInterval private let now: @Sendable () -> TimeInterval
private var cached: (route: String, expiresAt: TimeInterval, address: String?)? private var cached: (route: String, expiresAt: TimeInterval, address: String?)?
init(session: URLSession = .shared, cacheLifetime: TimeInterval = 600, retryInterval: TimeInterval = 30, init(session: URLSession? = nil, cacheLifetime: TimeInterval = 600, retryInterval: TimeInterval = 30,
now: @escaping @Sendable () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) { now: @escaping @Sendable () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) {
precondition(cacheLifetime.isFinite && cacheLifetime > 0 && retryInterval.isFinite && retryInterval > 0) precondition(cacheLifetime.isFinite && cacheLifetime > 0 && retryInterval.isFinite && retryInterval > 0)
self.session = session self.ownsSession = session == nil
self.session = session ?? URLSession(configuration: Self.sessionConfiguration())
self.cacheLifetime = cacheLifetime self.cacheLifetime = cacheLifetime
self.retryInterval = retryInterval self.retryInterval = retryInterval
self.now = now self.now = now
} }
/// No HTTP cache, cookies or credentials are persisted; only `cached` above retains results.
static func sessionConfiguration() -> URLSessionConfiguration {
let configuration = URLSessionConfiguration.ephemeral
configuration.urlCache = nil
configuration.httpCookieStorage = nil
configuration.urlCredentialStorage = nil
configuration.httpShouldSetCookies = false
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
return configuration
}
deinit {
if ownsSession { session.invalidateAndCancel() }
}
/// The caller owns the task lifetime; route changes and hidden views cancel both HTTP and sleep. /// The caller owns the task lifetime; route changes and hidden views cancel both HTTP and sleep.
func refreshContinuously(route: String, onUpdate: @Sendable (String?) async -> Void) async { func refreshContinuously(route: String, onUpdate: @Sendable (String?) async -> Void) async {
while !Task.isCancelled { while !Task.isCancelled {
+3 -1
View File
@@ -52,7 +52,9 @@ private actor Deliveries {
@main struct PublicIPAddressChecks { @main struct PublicIPAddressChecks {
static func main() async throws { static func main() async throws {
let config = URLSessionConfiguration.ephemeral let config = PublicIPAddressService.sessionConfiguration()
precondition(config.urlCache == nil && config.httpCookieStorage == nil && config.urlCredentialStorage == nil)
precondition(!config.httpShouldSetCookies && config.requestCachePolicy == .reloadIgnoringLocalCacheData)
config.protocolClasses = [IPResponse.self] config.protocolClasses = [IPResponse.self]
let session = URLSession(configuration: config) let session = URLSession(configuration: config)
defer { session.invalidateAndCancel() } defer { session.invalidateAndCancel() }
+29 -6
View File
@@ -5,15 +5,23 @@ import Darwin
/// This opt-in integration check contacts the same HTTPS endpoint as the app. /// This opt-in integration check contacts the same HTTPS endpoint as the app.
@main struct SandboxNetworkChecks { @main struct SandboxNetworkChecks {
static func main() async { static func main() async {
var request = URLRequest(url: URL(string: "https://api.ipify.org")!) let before = persistentNetworkFiles()
request.timeoutInterval = 5 let service = PublicIPAddressService()
do { do {
let (_, response) = try await URLSession.shared.data(for: request) guard await service.address(route: "sandbox-check") != nil else {
guard (response as? HTTPURLResponse)?.statusCode == 200 else { print("FAIL: production public-address lookup did not return a valid address")
print("FAIL: public-address endpoint did not return HTTP 200")
exit(1) exit(1)
} }
print("PASS: signed sandbox public-address HTTPS request returned HTTP 200") // Repeat both the memory-cache path and a fresh route without enabling HTTP storage.
guard await service.address(route: "sandbox-check") != nil,
await service.address(route: "sandbox-new-route") != nil else { exit(1) }
try await Task.sleep(for: .seconds(1))
let after = persistentNetworkFiles()
guard after == before else {
print("FAIL: public-address lookup created or changed persistent network files")
exit(1)
}
print("PASS: signed sandbox production HTTPS, repeat/route lookup and no persistent network files")
} catch { } catch {
// Keep the public address and potentially identifying error URLs out of logs. // Keep the public address and potentially identifying error URLs out of logs.
let error = error as NSError let error = error as NSError
@@ -21,4 +29,19 @@ import Darwin
exit(1) exit(1)
} }
} }
private static func persistentNetworkFiles() -> [String: String] {
let library = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library")
var files: [String: String] = [:]
for directory in ["Caches", "HTTPStorages", "Cookies", "WebKit"] {
let root = library.appendingPathComponent(directory)
guard let entries = FileManager.default.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey],
options: []) else { continue }
for case let url as URL in entries {
guard let value = try? url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey]), value.isRegularFile == true else { continue }
files[url.path] = "\(value.fileSize ?? 0)|\(value.contentModificationDate?.timeIntervalSince1970 ?? 0)"
}
}
return files
}
} }
+19 -2
View File
@@ -5,6 +5,7 @@ import os
import signal import signal
from pathlib import Path from pathlib import Path
import plistlib import plistlib
import re
import shutil import shutil
import subprocess import subprocess
import sys import sys
@@ -55,7 +56,7 @@ CHECKS.update({
"SettingsWindowChecks": ["kymo/Core/Services/SettingsPresentation.swift", "kymo/Features/Settings/SettingsWindowLifecycle.swift"], "SettingsWindowChecks": ["kymo/Core/Services/SettingsPresentation.swift", "kymo/Features/Settings/SettingsWindowLifecycle.swift"],
"PanelWindowChecks": ["kymo/Features/MenuBar/MenuPanelController.swift", "kymo/Features/MenuBar/PanelLayout.swift", "PanelWindowChecks": ["kymo/Features/MenuBar/MenuPanelController.swift", "kymo/Features/MenuBar/PanelLayout.swift",
"kymo/UI/Components/IntervalControl.swift"], "kymo/UI/Components/IntervalControl.swift"],
"SandboxNetworkChecks": [], "SandboxNetworkChecks": ["kymo/Core/Services/PublicIPAddressService.swift"],
}) })
GUI = {"NativeMetricDrawingChecks", "NativeProcessTableChecks", "LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks"} GUI = {"NativeMetricDrawingChecks", "NativeProcessTableChecks", "LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks"}
NETWORK = {"SandboxNetworkChecks"} NETWORK = {"SandboxNetworkChecks"}
@@ -103,6 +104,19 @@ def test_bundle(work, name, executable, host_entitlements=None, resources=None):
return app return app
def clean_test_container(bundle):
# Only the random bundle ID generated by this runner; never the real app's data.
identifier = plistlib.loads((bundle / "Contents/Info.plist").read_bytes())["CFBundleIdentifier"]
if not re.fullmatch(r"cn\.airnan\.kymo\.checks\.[a-f0-9]{32}", identifier):
raise RuntimeError("Refusing to clean an unrecognized test container")
container = Path.home() / "Library/Containers" / identifier
if container.is_symlink():
raise RuntimeError("Refusing to follow a test-container symlink")
if container.exists():
shutil.rmtree(container)
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--app", type=Path, help="Use an already built app instead of building") parser.add_argument("--app", type=Path, help="Use an already built app instead of building")
@@ -176,7 +190,10 @@ def main():
raise RuntimeError(f"{name} did not report success\n" + (error.read_text() if error.exists() else "")) raise RuntimeError(f"{name} did not report success\n" + (error.read_text() if error.exists() else ""))
elif name in NETWORK or name == "NetworkAddressChecks": elif name in NETWORK or name == "NetworkAddressChecks":
bundle = test_bundle(work, name, executable, host_entitlements) bundle = test_bundle(work, name, executable, host_entitlements)
run([bundle / "Contents/MacOS" / name], timeout=15) try:
run([bundle / "Contents/MacOS" / name], timeout=15)
finally:
clean_test_container(bundle)
else: else:
extra = [app] if name in {"LocalizationChecks", "PanelAssetChecks"} else [] extra = [app] if name in {"LocalizationChecks", "PanelAssetChecks"} else []
if name == "CodeIdentityChecks": if name == "CodeIdentityChecks":