Files
VCCPlusOSS/tests/macos/companion/TransportChecks.swift
T

151 lines
8.8 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
// Standalone authored IPC fixtures. Compile with -D VCC_COMPANION_TESTING.
import Foundation
import Darwin
@main struct TransportChecks {
actor Flag {
var started = false
var cancelled = false
func start() { started = true }
func cancel() { cancelled = true }
}
static func require(_ condition: Bool, _ message: String) throws {
if !condition { throw NSError(domain: "TransportCheck", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) }
}
static func configuration(_ root: URL, name: String = "fixture.sock", timeout: TimeInterval = 3) -> CompanionTransport.Configuration {
var config = CompanionTransport.Configuration(directory: root)
config.socketName = name; config.timeout = timeout; config.allowUnsignedTestPeers = true
return config
}
static func fixtureSocket(_ path: String, listening: Bool = false) throws -> Int32 {
let fd = socket(AF_UNIX, SOCK_STREAM, 0)
guard fd >= 0 else { throw POSIXError(.EIO) }
var address = sockaddr_un(); address.sun_family = sa_family_t(AF_UNIX)
address.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
let bytes = Array(path.utf8CString)
guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { close(fd); throw POSIXError(.ENAMETOOLONG) }
withUnsafeMutableBytes(of: &address.sun_path) { target in bytes.withUnsafeBytes { target.copyBytes(from: $0) } }
let rc = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) } }
guard rc == 0, chmod(path, 0o600) == 0 else { close(fd); throw POSIXError(.EIO) }
if listening { guard listen(fd, 2) == 0 else { close(fd); throw POSIXError(.EIO) } }
return fd
}
static func main() async throws {
let root = URL(fileURLWithPath: "/private/tmp/vcc-ipc-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let config = configuration(root)
let server = try CompanionTransport.Server(configuration: config) { method, payload in
if method == "error" { throw CompanionTransport.Failure.remote("Authored remote error") }
return payload
}
defer { server.stop() }
let client = CompanionTransport.Client(configuration: config)
let bytes = Data((0..<(1024 * 1024)).map { UInt8($0 & 255) })
let echoed = try await client.request(method: "echo", payload: bytes)
try require(echoed == bytes, "Binary round-trip differs")
print("PASS binary round-trip")
try await withThrowingTaskGroup(of: Void.self) { group in
for n in 0..<4 {
group.addTask {
let expected = Data("request-\(n)".utf8)
let actual = try await client.request(method: "echo", payload: expected)
try require(actual == expected, "Concurrent response crossed request identities")
}
}
try await group.waitForAll()
}
print("PASS concurrent request identities")
do { _ = try await client.request(method: "error"); throw POSIXError(.EIO) }
catch CompanionTransport.Failure.remote(let message) { try require(message == "Authored remote error", "Remote error differs") }
print("PASS remote errors")
do { _ = try CompanionTransport.Server(configuration: config) { _, p in p }; throw POSIXError(.EIO) }
catch CompanionTransport.Failure.busy { }
try require(try await client.request(method: "echo") == Data(), "Duplicate listener disrupted live endpoint")
print("PASS duplicate listener preserves running service")
var second = config; second.socketName = "second.sock"
let other = try CompanionTransport.Server(configuration: second) { _, _ in Data("other".utf8) }
try require(try await CompanionTransport.Client(configuration: second).request(method: "echo") == Data("other".utf8), "Second endpoint failed")
other.stop()
try require(try await client.request(method: "echo") == Data(), "Second endpoint stopped first service")
print("PASS independent app endpoints")
var signedOnly = config; signedOnly.allowUnsignedTestPeers = false
do { _ = try await CompanionTransport.Client(configuration: signedOnly).request(method: "echo"); throw POSIXError(.EIO) }
catch CompanionTransport.Failure.untrustedPeer { }
print("PASS unsigned peer rejected by production policy")
do {
try CompanionTransport.validateApplication(at: URL(fileURLWithPath: CommandLine.arguments[0]),
permittedBundleIDs: ["com.brianholman.vccplus.oss.mac"])
throw POSIXError(.EIO)
} catch CompanionTransport.Failure.untrustedPeer { }
print("PASS unsigned application rejected before launch")
do { _ = try await client.request(method: "echo", payload: Data(count: CompanionTransport.maximumPayloadBytes + 1)); throw POSIXError(.EIO) }
catch CompanionTransport.Failure.tooLarge { }
print("PASS oversized payload rejected")
let flag = Flag()
var waiting = config; waiting.socketName = "waiting.sock"
let slow = try CompanionTransport.Server(configuration: waiting) { _, _ in
await flag.start()
do { try await Task.sleep(nanoseconds: 10_000_000_000) }
catch { await flag.cancel(); throw error }
return Data()
}
let task = Task { try await CompanionTransport.Client(configuration: waiting).request(method: "wait") }
for _ in 0..<40 {
if await flag.started { break }
try await Task.sleep(nanoseconds: 25_000_000)
}
try require(await flag.started, "Handler did not start")
task.cancel()
do { _ = try await task.value; throw POSIXError(.EIO) } catch is CancellationError { }
for _ in 0..<40 {
if await flag.cancelled { break }
try await Task.sleep(nanoseconds: 25_000_000)
}
try require(await flag.cancelled, "Client cancellation did not reach handler")
slow.stop()
print("PASS cancellation propagates to server work")
var stale = config; stale.socketName = "stale.sock"
close(try fixtureSocket(stale.socketPath))
let recovered = try CompanionTransport.Server(configuration: stale) { _, p in p }
recovered.stop()
print("PASS owned stale socket recovery")
var active = config; active.socketName = "active.sock"
let foreign = try fixtureSocket(active.socketPath, listening: true)
do { _ = try CompanionTransport.Server(configuration: active) { _, p in p }; throw POSIXError(.EIO) }
catch CompanionTransport.Failure.busy { }
var activeInfo = stat(); try require(lstat(active.socketPath, &activeInfo) == 0, "Live foreign socket removed")
close(foreign); unlink(active.socketPath)
print("PASS live foreign socket preserved")
var unsafe = config; unsafe.socketName = "unsafe.sock"
let target = root.appendingPathComponent("retained.txt")
try Data("retained".utf8).write(to: target)
try FileManager.default.createSymbolicLink(atPath: unsafe.socketPath, withDestinationPath: target.path)
do { _ = try CompanionTransport.Server(configuration: unsafe) { _, p in p }; throw POSIXError(.EIO) }
catch CompanionTransport.Failure.unsafeEndpoint { }
try require(try Data(contentsOf: target) == Data("retained".utf8), "Symlink target changed")
print("PASS symlink endpoint refused without modifying target")
var replaced = config; replaced.socketName = "replaced.sock"
let old = try CompanionTransport.Server(configuration: replaced) { _, p in p }
unlink(replaced.socketPath)
let replacement = try fixtureSocket(replaced.socketPath)
old.stop()
var replacementInfo = stat()
try require(lstat(replaced.socketPath, &replacementInfo) == 0, "Replaced socket removed during stop")
close(replacement); unlink(replaced.socketPath)
print("PASS stop preserves replaced endpoint")
var timing = config; timing.socketName = "timeout.sock"; timing.timeout = 0.2
let hung = try CompanionTransport.Server(configuration: timing) { _, _ in
try await Task.sleep(nanoseconds: 10_000_000_000); return Data()
}
do { _ = try await CompanionTransport.Client(configuration: timing).request(method: "wait"); throw POSIXError(.EIO) }
catch CompanionTransport.Failure.timedOut { }
hung.stop()
print("PASS bounded operation deadline")
server.stop()
do { _ = try await client.request(method: "echo"); throw POSIXError(.EIO) }
catch CompanionTransport.Failure.unavailable { }
print("PASS stopped service unavailable")
}
}