* fix(security): 修复辅助工具鉴权降级与五处正确性缺陷
代码审查(安全/质量/性能/架构四维度)发现的问题,逐条修复。
辅助工具鉴权(High)
ad-hoc 构建下 clientRequirement 退化为只校验 bundle identifier,不含
anchor 约束,任何进程 codesign -s - 伪造同名即可连上 root 辅助工具,
驱动 DNS、睡眠、本地快照与风扇。project.yml 默认就是 ad-hoc 签名,
而 make build 是文档化的安装路径,开发机上属常态。
改为无团队签名时返回 nil 并拒绝连接,与在线升级在 ad-hoc 下直接禁用
的策略一致;此时 App 走一次性管理员授权回退,功能不丢。
卸载器批量误删
validate 只拒绝 com.apple. 前缀,包名为 "com" 的应用可通过;随后
hasPrefix("com.") 把 leftovers 扫描的十余个目录(Preferences、Caches、
Containers、Saved Application State 等)下所有 com.* 条目当成残留列出
并默认勾选,一次点击即整体移入废纸篓。前缀匹配改为要求至少三段反向
域名,精确匹配不受影响。
退出时静默跳过恢复睡眠
restoreDefaultsSynchronously 的 guard 在循环体内用 return 而非 continue,
第一步取代理失败就连带跳过第二步,Mac 保持禁止睡眠。同时把两步各等 1 秒
改为总预算 1.5 秒,避免主线程退出卡顿。
公网 IP 查询重入保护失效
isLookingUpPublic 同时承担重入锁与转圈开关两个相反职责,有缓存且非强制
刷新时恒为 false,guard 形同虚设,两个 Task 可各发三次请求并发写缓存,
失败结果可能覆盖好结果。拆出独立的 isFetchingPublic,并用 defer 确保
所有退出路径复位。
诊断导出的崩溃报告未脱敏
日志与清理记录都走了 redact,但 .ips 崩溃报告原样入包,其中可能夹带
进程内存中的 WebDAV 目录、用户名、公网 IP 与主机名,与界面“不含 IP、
序列号与硬件地址”的声明不符。改为同样脱敏后写入。
PowerSampler
channels(in:) 的 unsafeBitCast 改为 Unmanaged.fromOpaque.takeUnretainedValue。
未加 deinit 释放 IOReport 订阅:IOReport 是私有框架,无公开释放入口且
无法验证其是否为 CF 对象,而全进程只有一个 PowerSampler、订阅各只创建
一次且随进程存在,不是增长型泄漏——已就此写明注释。
补回归测试:clientRequirement 的 ad-hoc 分支与 anchor 约束、
matchesIdentifier 的过宽前缀与派生名匹配。
make test 141 项通过(新增 4 项),Release 完整构建通过。
* fix(security): 完善辅助工具升级与卸载边界校验
* fix(ui): 拆分评分条视图以解决 CI 类型检查超时
* fix(webdav): 规范化目录路径以兼容 macOS 15
193 lines
9.5 KiB
Swift
193 lines
9.5 KiB
Swift
// Copyright (C) 2026 ysicing
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
import Foundation
|
|
import Testing
|
|
@testable import WebDAVSync
|
|
|
|
private struct Transport: WebDAVTransport {
|
|
let handler: @Sendable (URLRequest) async throws -> WebDAVResponse
|
|
func send(_ request: URLRequest) async throws -> WebDAVResponse { try await handler(request) }
|
|
}
|
|
|
|
struct WebDAVClientTests {
|
|
@Test func normalizesTrailingSlashesWithoutDoubleEncoding() throws {
|
|
for base in ["https://dav.example.com", "https://dav.example.com/dav/My%20Settings", "https://dav.example.com/dav/我的设置"] {
|
|
let plain = try WebDAVConfiguration(address: base, username: "alice")
|
|
for suffix in ["/", "//", "///"] {
|
|
let other = try WebDAVConfiguration(address: base + suffix, username: "alice")
|
|
#expect(plain.fileURL == other.fileURL)
|
|
#expect(plain.credentialAccount == other.credentialAccount)
|
|
}
|
|
#expect(plain.fileURL.path.contains("//") == false)
|
|
#expect(plain.fileURL.absoluteString.contains("%2520") == false)
|
|
}
|
|
}
|
|
private func configuration() throws -> WebDAVConfiguration {
|
|
try WebDAVConfiguration(address: "https://dav.example.com/dav/我的设置", username: "alice")
|
|
}
|
|
|
|
@Test func preservesDirectoryAndEncodesFilename() throws {
|
|
let config = try configuration()
|
|
#expect(config.fileURL.path == "/dav/我的设置/xstats-settings.json")
|
|
#expect(config.fileURL.absoluteString.contains("%E6%88%91"))
|
|
#expect(config.directoryURL.hasDirectoryPath)
|
|
let slash = try WebDAVConfiguration(address: "https://dav.example.com/dav/我的设置/", username: "alice")
|
|
#expect(config.credentialAccount == slash.credentialAccount)
|
|
let other = try WebDAVConfiguration(address: "https://other.example.com/dav/", username: "alice")
|
|
#expect(config.credentialAccount != other.credentialAccount)
|
|
}
|
|
|
|
@Test(arguments: [
|
|
"http://dav.example.com/", "file:///tmp/", "https:///abc", "not-a-url",
|
|
"https://user:secret@dav.example.com/", "https://dav.example.com/?token=secret",
|
|
"https://dav.example.com/#fragment", "https://dav.example.com/a/../b/",
|
|
])
|
|
func rejectsUnsafeAddresses(_ address: String) {
|
|
#expect(throws: WebDAVError.invalidAddress) {
|
|
try WebDAVConfiguration(address: address, username: "alice")
|
|
}
|
|
}
|
|
|
|
@Test(arguments: ["", "user:name", "user\nname"])
|
|
func rejectsInvalidUsername(_ username: String) {
|
|
#expect(throws: WebDAVError.invalidUsername) {
|
|
try WebDAVConfiguration(address: "https://dav.example.com/", username: username)
|
|
}
|
|
}
|
|
|
|
@Test func downloadUsesAuthenticatedGET() async throws {
|
|
let config = try configuration()
|
|
let client = WebDAVClient(transport: Transport { request in
|
|
#expect(request.url == config.fileURL)
|
|
#expect(request.httpMethod == "GET")
|
|
#expect(request.httpBody == nil)
|
|
#expect(request.value(forHTTPHeaderField: "Authorization") == "Basic YWxpY2U6c2VjcmV0")
|
|
#expect(request.value(forHTTPHeaderField: "Accept") == "application/json")
|
|
return WebDAVResponse(data: Data("backup".utf8), status: 200)
|
|
})
|
|
let data = try await client.download(configuration: config, password: "secret")
|
|
#expect(String(decoding: data, as: UTF8.self) == "backup")
|
|
}
|
|
|
|
@Test(arguments: [200, 201, 204])
|
|
func uploadUsesPUTAndAcceptsCompletedSuccess(_ status: Int) async throws {
|
|
let data = Data("settings".utf8)
|
|
let client = WebDAVClient(transport: Transport { request in
|
|
#expect(request.httpMethod == "PUT")
|
|
#expect(request.httpBody == data)
|
|
#expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json; charset=utf-8")
|
|
return WebDAVResponse(data: Data(), status: status)
|
|
})
|
|
try await client.upload(data, configuration: configuration(), password: "secret")
|
|
}
|
|
|
|
@Test(arguments: [401, 403, 404, 409, 413, 423, 500, 507, 302, 307, 202, 204])
|
|
func rejectsUnsuccessfulDownload(_ status: Int) async throws {
|
|
let client = WebDAVClient(transport: Transport { _ in WebDAVResponse(data: Data(), status: status) })
|
|
await #expect(throws: WebDAVError.self) {
|
|
try await client.download(configuration: configuration(), password: "secret")
|
|
}
|
|
}
|
|
|
|
@Test func rejectsOversizedInputBeforeRequestAndOversizedResponse() async throws {
|
|
let data = Data(repeating: 0, count: WebDAVClient.maximumBytes + 1)
|
|
let client = WebDAVClient(transport: Transport { request in
|
|
#expect(request.httpMethod == "GET", "Oversized uploads must not reach the transport")
|
|
return WebDAVResponse(data: data, status: 200)
|
|
})
|
|
await #expect(throws: WebDAVError.tooLarge) {
|
|
try await client.upload(data, configuration: configuration(), password: "secret")
|
|
}
|
|
await #expect(throws: WebDAVError.tooLarge) {
|
|
try await client.download(configuration: configuration(), password: "secret")
|
|
}
|
|
}
|
|
|
|
@Test func preservesCancellationAndSanitizesNetworkErrors() async throws {
|
|
let cancel = WebDAVClient(transport: Transport { _ in throw URLError(.cancelled) })
|
|
await #expect(throws: CancellationError.self) {
|
|
try await cancel.download(configuration: configuration(), password: "secret")
|
|
}
|
|
let failed = WebDAVClient(transport: Transport { _ in
|
|
throw NSError(domain: "secret-password", code: 1)
|
|
})
|
|
await #expect(throws: WebDAVError.transport) {
|
|
try await failed.download(configuration: configuration(), password: "secret")
|
|
}
|
|
}
|
|
|
|
@Test func emptyPasswordNeverSendsRequestAndUploadRequiresCompletion() async throws {
|
|
let unused = WebDAVClient(transport: Transport { _ in
|
|
Issue.record("A request with no password must not be sent")
|
|
return WebDAVResponse(data: Data(), status: 200)
|
|
})
|
|
await #expect(throws: WebDAVError.missingPassword) {
|
|
try await unused.download(configuration: configuration(), password: "")
|
|
}
|
|
let accepted = WebDAVClient(transport: Transport { _ in WebDAVResponse(data: Data(), status: 202) })
|
|
await #expect(throws: WebDAVError.http(202)) {
|
|
try await accepted.upload(Data(), configuration: configuration(), password: "secret")
|
|
}
|
|
let missing = WebDAVClient(transport: Transport { _ in WebDAVResponse(data: Data(), status: 404) })
|
|
await #expect(throws: WebDAVError.directoryMissing) {
|
|
try await missing.upload(Data(), configuration: configuration(), password: "secret")
|
|
}
|
|
}
|
|
|
|
@Test func refusesRedirectsIncludingSameHost() async throws {
|
|
let url = try #require(URL(string: "https://dav.example.com/"))
|
|
let session = URLSession(configuration: .ephemeral)
|
|
defer { session.invalidateAndCancel() }
|
|
let request = URLRequest(url: url)
|
|
let task = session.dataTask(with: request) // 不启动网络请求。
|
|
let response = try #require(HTTPURLResponse(url: url, statusCode: 307, httpVersion: nil, headerFields: nil))
|
|
let redirected = await RejectRedirects().urlSession(session, task: task,
|
|
willPerformHTTPRedirection: response, newRequest: request)
|
|
#expect(redirected == nil)
|
|
}
|
|
|
|
@Test(arguments: ["small", "large", "unauthorized"])
|
|
func defaultTransportReadsBoundedResponses(_ scenario: String) async throws {
|
|
let config = try WebDAVConfiguration(address: "https://xstats-webdav-transport.test/\(scenario)/", username: "alice")
|
|
let client = WebDAVClient(transport: URLSessionWebDAVTransport {
|
|
let configuration = URLSessionConfiguration.ephemeral
|
|
configuration.protocolClasses = [FixtureProtocol.self]
|
|
return configuration
|
|
})
|
|
switch scenario {
|
|
case "large":
|
|
await #expect(throws: WebDAVError.tooLarge) {
|
|
try await client.download(configuration: config, password: "secret")
|
|
}
|
|
case "unauthorized":
|
|
await #expect(throws: WebDAVError.unauthorized) {
|
|
try await client.download(configuration: config, password: "secret")
|
|
}
|
|
default:
|
|
let data = try await client.download(configuration: config, password: "secret")
|
|
#expect(data == Data("fixture".utf8))
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 只拦截本测试的保留域名;没有共享可变响应状态,不依赖外部服务器。
|
|
private final class FixtureProtocol: URLProtocol, @unchecked Sendable {
|
|
override class func canInit(with request: URLRequest) -> Bool {
|
|
request.url?.host == "xstats-webdav-transport.test"
|
|
}
|
|
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
|
override func startLoading() {
|
|
guard let url = request.url else { return }
|
|
let unauthorized = url.path.contains("unauthorized")
|
|
let data = url.path.contains("large")
|
|
? Data(repeating: 65, count: WebDAVClient.maximumBytes + 1) : Data("fixture".utf8)
|
|
let response = HTTPURLResponse(url: url, statusCode: unauthorized ? 401 : 200,
|
|
httpVersion: "HTTP/1.1", headerFields: nil)!
|
|
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
|
client?.urlProtocol(self, didLoad: data)
|
|
client?.urlProtocolDidFinishLoading(self)
|
|
}
|
|
override func stopLoading() {}
|
|
}
|