mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-27 16:45:21 +00:00
Tier 3 of a protest-hardening review. The BLE mesh is already properly fenced off from network reachability and needs nothing here; every gap is on the internet side, or in how someone gets a build they can trust. Say when Tor is blocked. The bootstrap poll loop simply ended at its 75-second deadline, leaving isStarting true with no further state, so a network that blocks Tor was indistinguishable from a slow one and the UI said "starting tor…" indefinitely. TorManager now exposes bootstrapDidStall and posts .TorBootstrapDidStall, and the app reports that mesh messaging still works while internet delivery is paused. It is cleared on each new start or restart, so a later attempt can report again. Let relays be added by hand. The four built-in relays are well-known clearnet hostnames, which is four names for a censor to block and no recourse short of a new build. NostrRelaySettings persists up to eight additional relays, normalized, .onion accepted, with a settings editor. They join the same target set as the built-ins and are subject to the same activation policy. Removal reconciles against the previous set: the teardown path iterates the current targets, so without that a removed relay's socket and queued sends would linger — covered by a test that fails without it. The merged list is cached rather than recomputed, because allowedRelayList consults it once per candidate URL and would otherwise read UserDefaults inside that loop. Stop stranding people who denied location. The activation gate required location permission or a mutual favorite, but teleporting into a geohash requires neither, so someone with no permission and no favorites could sit in a channel that never connected while Tor and the relays stayed suppressed and nothing said why. Being in a location channel is now a third arm of the gate, in both the activation service and the relay manager's copy of the policy, and leaving the channel closes it again. Stop burning the Tor timeout when Tor is off. GeoRelayDirectory awaited Tor readiness unconditionally, but with the preference off TorManager has been shut down, so every refresh spent the full bootstrap deadline and the directory froze on its cached copy. It now keys on the preference, not on live readiness: Tor wanted but unavailable must still skip the fetch rather than fall back to clearnet. Say what turning Tor off costs. The toggle's copy described it as hiding your IP "for location channels", understating both scope and consequence. It now names private messages too, and while the toggle is off the settings screen states that every relay can see the device IP. Make builds verifiable. There was no release verification of any kind: no signatures, no checksums, no documented procedure. Post-takedown that is the acute gap, because mirrors appear and people install whatever they can find during a shutdown. source-manifest.yml publishes a per-tag SHA-256 manifest with a provenance attestation, self-checking before it publishes, and docs/VERIFYING-A-BUILD.md explains how to verify source and states plainly that compiled builds from anywhere but the App Store cannot be verified. It also records the gaps honestly: no published signing key, no reproducible build, no non-GitHub mirror. docs/TOR-INTEGRATION.md was substantially stale — it documented a torrc, SOCKSPort and ControlPort that the in-process Arti client does not use, and claimed there are no user-visible settings — so it is rewritten, including the deferred gap below. Deferred: no Tor bridges or pluggable transports. arti-client is built without pt-client or bridge-client and bootstraps from stock config, so in a country that blocks Tor outright there is still no circumvention path — only a clear report that there isn't. Closing it needs the Rust features, bridge config through the FFI, and an xcframework rebuild under the pinned toolchain with a provenance update, which is its own change. Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
337 lines
13 KiB
Swift
337 lines
13 KiB
Swift
import Combine
|
|
import XCTest
|
|
@testable import bitchat
|
|
|
|
@MainActor
|
|
final class NetworkActivationServiceTests: XCTestCase {
|
|
private let torPreferenceKey = "networkActivationService.userTorEnabled"
|
|
|
|
func test_start_leavesNetworkDisabledWithoutPermissionOrFavorites() {
|
|
let context = makeService(permission: .denied, favorites: [])
|
|
|
|
context.service.start()
|
|
|
|
XCTAssertFalse(context.service.activationAllowed)
|
|
XCTAssertEqual(context.torController.autoStartAllowedValues, [false])
|
|
XCTAssertEqual(context.proxyController.proxyModes, [false])
|
|
XCTAssertEqual(context.torController.startIfNeededCallCount, 0)
|
|
XCTAssertEqual(context.torController.shutdownCompletelyCallCount, 1)
|
|
XCTAssertEqual(context.relayController.connectCallCount, 0)
|
|
XCTAssertEqual(context.relayController.disconnectCallCount, 1)
|
|
}
|
|
|
|
func test_start_enablesTorAndRelaysWhenAuthorized() {
|
|
let context = makeService(permission: .authorized, favorites: [])
|
|
|
|
context.service.start()
|
|
|
|
XCTAssertTrue(context.service.activationAllowed)
|
|
XCTAssertEqual(context.torController.autoStartAllowedValues, [true])
|
|
XCTAssertEqual(context.proxyController.proxyModes, [true])
|
|
XCTAssertEqual(context.torController.startIfNeededCallCount, 1)
|
|
XCTAssertEqual(context.relayController.connectCallCount, 1)
|
|
XCTAssertEqual(context.relayController.disconnectCallCount, 0)
|
|
}
|
|
|
|
func test_start_respectsStoredTorPreferenceForDirectMode() {
|
|
let context = makeService(permission: .authorized, favorites: [])
|
|
context.storage.set(false, forKey: torPreferenceKey)
|
|
|
|
context.service.start()
|
|
|
|
XCTAssertTrue(context.service.activationAllowed)
|
|
XCTAssertFalse(context.service.userTorEnabled)
|
|
XCTAssertEqual(context.torController.autoStartAllowedValues, [false])
|
|
XCTAssertEqual(context.proxyController.proxyModes, [false])
|
|
XCTAssertEqual(context.torController.startIfNeededCallCount, 0)
|
|
XCTAssertEqual(context.torController.shutdownCompletelyCallCount, 1)
|
|
XCTAssertEqual(context.relayController.connectCallCount, 1)
|
|
}
|
|
|
|
func test_setUserTorEnabled_postsNotificationAndReconnectsOnTransportSwitch() {
|
|
let context = makeService(permission: .authorized, favorites: [])
|
|
let notified = expectation(description: "Tor preference notification")
|
|
let token = context.notificationCenter.addObserver(
|
|
forName: .TorUserPreferenceChanged,
|
|
object: nil,
|
|
queue: nil
|
|
) { note in
|
|
XCTAssertEqual(note.userInfo?["enabled"] as? Bool, false)
|
|
notified.fulfill()
|
|
}
|
|
|
|
context.service.start()
|
|
context.service.setUserTorEnabled(false)
|
|
|
|
wait(for: [notified], timeout: 1.0)
|
|
context.notificationCenter.removeObserver(token)
|
|
|
|
XCTAssertFalse(context.service.userTorEnabled)
|
|
XCTAssertEqual(context.storage.object(forKey: torPreferenceKey) as? Bool, false)
|
|
XCTAssertEqual(Array(context.proxyController.proxyModes.suffix(2)), [true, false])
|
|
XCTAssertEqual(Array(context.torController.autoStartAllowedValues.suffix(2)), [true, false])
|
|
XCTAssertEqual(context.relayController.disconnectCallCount, 1)
|
|
XCTAssertEqual(context.relayController.connectCallCount, 2)
|
|
}
|
|
|
|
func test_mutualFavoritesPublisher_reactivatesNetwork() async {
|
|
let context = makeService(permission: .denied, favorites: [])
|
|
|
|
context.service.start()
|
|
XCTAssertFalse(context.service.activationAllowed)
|
|
|
|
context.favoritesSubject.send([Data([0x01])])
|
|
let becameActive = await waitUntil { context.service.activationAllowed }
|
|
XCTAssertTrue(becameActive)
|
|
|
|
XCTAssertTrue(context.service.activationAllowed)
|
|
XCTAssertTrue(context.torController.autoStartAllowedValues.contains(true))
|
|
XCTAssertTrue(context.proxyController.proxyModes.contains(true))
|
|
XCTAssertGreaterThanOrEqual(context.torController.startIfNeededCallCount, 1)
|
|
XCTAssertGreaterThanOrEqual(context.relayController.connectCallCount, 1)
|
|
}
|
|
|
|
func test_stopForPanic_synchronouslyStopsAndIgnoresPublisherUpdates() async {
|
|
let context = makeService(permission: .authorized, favorites: [])
|
|
|
|
context.service.start()
|
|
context.service.stopForPanic()
|
|
let connectCountAfterStop = context.relayController.connectCallCount
|
|
let startCountAfterStop = context.torController.startIfNeededCallCount
|
|
|
|
context.favoritesSubject.send([Data([0x01])])
|
|
context.reachability.set(false)
|
|
context.reachability.set(true)
|
|
try? await Task.sleep(nanoseconds: 30_000_000)
|
|
|
|
XCTAssertFalse(context.service.activationAllowed)
|
|
XCTAssertEqual(context.reachability.stopCallCount, 1)
|
|
XCTAssertEqual(context.torController.autoStartAllowedValues.last, false)
|
|
XCTAssertEqual(context.proxyController.proxyModes.last, false)
|
|
XCTAssertGreaterThanOrEqual(
|
|
context.torController.shutdownCompletelyCallCount,
|
|
1
|
|
)
|
|
XCTAssertGreaterThanOrEqual(
|
|
context.relayController.disconnectCallCount,
|
|
1
|
|
)
|
|
XCTAssertEqual(
|
|
context.relayController.connectCallCount,
|
|
connectCountAfterStop
|
|
)
|
|
XCTAssertEqual(
|
|
context.torController.startIfNeededCallCount,
|
|
startCountAfterStop
|
|
)
|
|
}
|
|
|
|
func test_start_afterPanicStop_reestablishesSubscriptions() {
|
|
let context = makeService(permission: .authorized, favorites: [])
|
|
|
|
context.service.start()
|
|
context.service.stopForPanic()
|
|
context.service.start()
|
|
|
|
XCTAssertTrue(context.service.activationAllowed)
|
|
XCTAssertEqual(context.reachability.startCallCount, 2)
|
|
XCTAssertEqual(context.relayController.connectCallCount, 2)
|
|
}
|
|
|
|
/// Teleporting into a geohash needs no location permission, so someone who
|
|
/// denied location and has no mutual favorites could previously sit in a
|
|
/// channel that never connected: the gate suppressed Tor and the relays,
|
|
/// and nothing explained why.
|
|
func test_start_enablesNetworkForALocationChannelWithoutPermissionOrFavorites() {
|
|
let context = makeService(
|
|
permission: .denied,
|
|
favorites: [],
|
|
selectedChannel: .location(GeohashChannel(level: .city, geohash: "u4pruy"))
|
|
)
|
|
|
|
context.service.start()
|
|
|
|
XCTAssertTrue(context.service.activationAllowed)
|
|
XCTAssertEqual(context.torController.startIfNeededCallCount, 1)
|
|
XCTAssertEqual(context.relayController.connectCallCount, 1)
|
|
}
|
|
|
|
func test_selectedChannelPublisher_activatesOnEnteringALocationChannel() async {
|
|
let channelSubject = CurrentValueSubject<ChannelID, Never>(.mesh)
|
|
let context = makeService(
|
|
permission: .denied,
|
|
favorites: [],
|
|
selectedChannelSubject: channelSubject
|
|
)
|
|
|
|
context.service.start()
|
|
XCTAssertFalse(context.service.activationAllowed)
|
|
|
|
channelSubject.send(.location(GeohashChannel(level: .city, geohash: "u4pruy")))
|
|
|
|
let activated = await waitUntil { context.service.activationAllowed }
|
|
XCTAssertTrue(activated)
|
|
}
|
|
|
|
/// Leaving the channel must close the gate again, or the exception would
|
|
/// quietly become permanent for the rest of the session.
|
|
func test_selectedChannelPublisher_deactivatesOnReturningToMesh() async {
|
|
let channelSubject = CurrentValueSubject<ChannelID, Never>(
|
|
.location(GeohashChannel(level: .city, geohash: "u4pruy"))
|
|
)
|
|
let context = makeService(
|
|
permission: .denied,
|
|
favorites: [],
|
|
selectedChannelSubject: channelSubject
|
|
)
|
|
|
|
context.service.start()
|
|
XCTAssertTrue(context.service.activationAllowed)
|
|
|
|
channelSubject.send(.mesh)
|
|
|
|
let deactivated = await waitUntil { !context.service.activationAllowed }
|
|
XCTAssertTrue(deactivated)
|
|
}
|
|
|
|
private func makeService(
|
|
permission: LocationChannelManager.PermissionState,
|
|
favorites: Set<Data>,
|
|
selectedChannel: ChannelID = .mesh,
|
|
selectedChannelSubject: CurrentValueSubject<ChannelID, Never>? = nil
|
|
) -> NetworkActivationTestContext {
|
|
let suiteName = "NetworkActivationServiceTests-\(UUID().uuidString)"
|
|
let storage = UserDefaults(suiteName: suiteName)!
|
|
storage.removePersistentDomain(forName: suiteName)
|
|
|
|
let permissionSubject = CurrentValueSubject<LocationChannelManager.PermissionState, Never>(permission)
|
|
let favoritesSubject = CurrentValueSubject<Set<Data>, Never>(favorites)
|
|
let channelSubject = selectedChannelSubject
|
|
?? CurrentValueSubject<ChannelID, Never>(selectedChannel)
|
|
let torController = MockNetworkActivationTorController()
|
|
let relayController = MockNetworkActivationRelayController()
|
|
let proxyController = MockNetworkActivationProxyController()
|
|
let reachability = MockNetworkActivationReachability()
|
|
let notificationCenter = NotificationCenter()
|
|
let service = NetworkActivationService(
|
|
storage: storage,
|
|
locationPermissionPublisher: permissionSubject.eraseToAnyPublisher(),
|
|
mutualFavoritesPublisher: favoritesSubject.eraseToAnyPublisher(),
|
|
permissionProvider: { permissionSubject.value },
|
|
mutualFavoritesProvider: { favoritesSubject.value },
|
|
selectedChannelPublisher: channelSubject.eraseToAnyPublisher(),
|
|
locationChannelSelectedProvider: {
|
|
if case .location = channelSubject.value { return true }
|
|
return false
|
|
},
|
|
reachabilityMonitor: reachability,
|
|
torController: torController,
|
|
relayController: relayController,
|
|
proxyController: proxyController,
|
|
notificationCenter: notificationCenter
|
|
)
|
|
return NetworkActivationTestContext(
|
|
service: service,
|
|
storage: storage,
|
|
favoritesSubject: favoritesSubject,
|
|
reachability: reachability,
|
|
torController: torController,
|
|
relayController: relayController,
|
|
proxyController: proxyController,
|
|
notificationCenter: notificationCenter
|
|
)
|
|
}
|
|
|
|
private func waitUntil(
|
|
timeout: TimeInterval = 1.0,
|
|
condition: @escaping @MainActor () -> Bool
|
|
) async -> Bool {
|
|
let deadline = Date().addingTimeInterval(timeout)
|
|
while Date() < deadline {
|
|
if condition() {
|
|
return true
|
|
}
|
|
try? await Task.sleep(nanoseconds: 10_000_000)
|
|
}
|
|
return condition()
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
private struct NetworkActivationTestContext {
|
|
let service: NetworkActivationService
|
|
let storage: UserDefaults
|
|
let favoritesSubject: CurrentValueSubject<Set<Data>, Never>
|
|
let reachability: MockNetworkActivationReachability
|
|
let torController: MockNetworkActivationTorController
|
|
let relayController: MockNetworkActivationRelayController
|
|
let proxyController: MockNetworkActivationProxyController
|
|
let notificationCenter: NotificationCenter
|
|
}
|
|
|
|
@MainActor
|
|
private final class MockNetworkActivationReachability:
|
|
NetworkReachabilityMonitoring {
|
|
private let subject = CurrentValueSubject<Bool, Never>(true)
|
|
private(set) var startCallCount = 0
|
|
private(set) var stopCallCount = 0
|
|
|
|
var isReachable: Bool { subject.value }
|
|
var reachabilityPublisher: AnyPublisher<Bool, Never> {
|
|
subject.removeDuplicates().dropFirst().eraseToAnyPublisher()
|
|
}
|
|
|
|
func start() {
|
|
startCallCount += 1
|
|
}
|
|
|
|
func stop() {
|
|
stopCallCount += 1
|
|
}
|
|
|
|
func set(_ reachable: Bool) {
|
|
subject.send(reachable)
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
private final class MockNetworkActivationTorController: NetworkActivationTorControlling {
|
|
private(set) var autoStartAllowedValues: [Bool] = []
|
|
private(set) var startIfNeededCallCount = 0
|
|
private(set) var shutdownCompletelyCallCount = 0
|
|
|
|
func setAutoStartAllowed(_ allowed: Bool) {
|
|
autoStartAllowedValues.append(allowed)
|
|
}
|
|
|
|
func startIfNeeded() {
|
|
startIfNeededCallCount += 1
|
|
}
|
|
|
|
func shutdownCompletely() {
|
|
shutdownCompletelyCallCount += 1
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
private final class MockNetworkActivationRelayController: NetworkActivationRelayControlling {
|
|
private(set) var connectCallCount = 0
|
|
private(set) var disconnectCallCount = 0
|
|
|
|
func connect() {
|
|
connectCallCount += 1
|
|
}
|
|
|
|
func disconnect() {
|
|
disconnectCallCount += 1
|
|
}
|
|
}
|
|
|
|
private final class MockNetworkActivationProxyController: NetworkActivationProxyControlling {
|
|
private(set) var proxyModes: [Bool] = []
|
|
|
|
func setProxyMode(useTor: Bool) {
|
|
proxyModes.append(useTor)
|
|
}
|
|
}
|