mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-27 16:05:18 +00:00
Keep working when the network is hostile, and make the app verifiable
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: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import bitchat
|
||||
|
||||
/// The built-in relay set is four well-known hostnames, so a filter blocking
|
||||
/// four names ends internet-delivered private messages. These cover the
|
||||
/// hand-added relays that make that recoverable without shipping a build.
|
||||
struct NostrRelaySettingsTests {
|
||||
/// Each case gets its own suite so nothing touches the real preferences or
|
||||
/// races another case.
|
||||
private func makeDefaults() -> UserDefaults {
|
||||
let suite = "bitchat.tests.relays.\(UUID().uuidString)"
|
||||
return UserDefaults(suiteName: suite)!
|
||||
}
|
||||
|
||||
private let builtIn: Set<String> = [
|
||||
"wss://relay.damus.io",
|
||||
"wss://nos.lol"
|
||||
]
|
||||
|
||||
@Test func addNormalizesABareHostname() {
|
||||
let defaults = makeDefaults()
|
||||
|
||||
// A bare hostname is how relays are usually quoted; wss is the only
|
||||
// sensible assumption.
|
||||
let result = NostrRelaySettings.add("relay.example.com", builtIn: builtIn, in: defaults)
|
||||
|
||||
#expect(result == .success("wss://relay.example.com"))
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://relay.example.com"])
|
||||
}
|
||||
|
||||
@Test func addAcceptsAnOnionAddress() {
|
||||
let defaults = makeDefaults()
|
||||
|
||||
// The reason this feature exists: an onion relay is not blockable by
|
||||
// hostname or SNI filtering.
|
||||
let result = NostrRelaySettings.add(
|
||||
"wss://exampleonionaddressxyz234567.onion",
|
||||
builtIn: builtIn,
|
||||
in: defaults
|
||||
)
|
||||
|
||||
#expect(result == .success("wss://exampleonionaddressxyz234567.onion"))
|
||||
}
|
||||
|
||||
@Test func addRejectsMalformedInput() {
|
||||
let defaults = makeDefaults()
|
||||
|
||||
#expect(NostrRelaySettings.add("", builtIn: builtIn, in: defaults) == .failure(.malformed))
|
||||
#expect(NostrRelaySettings.add(" ", builtIn: builtIn, in: defaults) == .failure(.malformed))
|
||||
// A scheme the relay layer cannot dial must not be stored.
|
||||
#expect(NostrRelaySettings.add("ftp://relay.example.com", builtIn: builtIn, in: defaults) == .failure(.malformed))
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults).isEmpty)
|
||||
}
|
||||
|
||||
@Test func addRejectsDuplicatesAndBuiltIns() {
|
||||
let defaults = makeDefaults()
|
||||
#expect(NostrRelaySettings.add("wss://relay.example.com", builtIn: builtIn, in: defaults) == .success("wss://relay.example.com"))
|
||||
|
||||
// Same relay written differently still normalizes to the same URL.
|
||||
#expect(NostrRelaySettings.add("relay.example.com", builtIn: builtIn, in: defaults) == .failure(.alreadyPresent))
|
||||
#expect(NostrRelaySettings.add("WSS://Relay.Example.com", builtIn: builtIn, in: defaults) == .failure(.alreadyPresent))
|
||||
// Re-adding a built-in would double-count it in the target list.
|
||||
#expect(NostrRelaySettings.add("wss://nos.lol", builtIn: builtIn, in: defaults) == .failure(.alreadyPresent))
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://relay.example.com"])
|
||||
}
|
||||
|
||||
@Test func addStopsAtTheLimit() {
|
||||
let defaults = makeDefaults()
|
||||
for index in 0..<NostrRelaySettings.maxCustomRelays {
|
||||
#expect(NostrRelaySettings.add("relay\(index).example.com", builtIn: builtIn, in: defaults) == .success("wss://relay\(index).example.com"))
|
||||
}
|
||||
|
||||
// Unbounded growth would fan every send out across dozens of sockets.
|
||||
#expect(NostrRelaySettings.add("one.too.many.example.com", builtIn: builtIn, in: defaults) == .failure(.limitReached))
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults).count == NostrRelaySettings.maxCustomRelays)
|
||||
}
|
||||
|
||||
@Test func addPreservesInsertionOrder() {
|
||||
let defaults = makeDefaults()
|
||||
NostrRelaySettings.add("b.example.com", builtIn: builtIn, in: defaults)
|
||||
NostrRelaySettings.add("a.example.com", builtIn: builtIn, in: defaults)
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://b.example.com", "wss://a.example.com"])
|
||||
}
|
||||
|
||||
@Test func removeTakesAnyEquivalentSpelling() {
|
||||
let defaults = makeDefaults()
|
||||
NostrRelaySettings.add("wss://relay.example.com", builtIn: builtIn, in: defaults)
|
||||
NostrRelaySettings.add("wss://other.example.com", builtIn: builtIn, in: defaults)
|
||||
|
||||
NostrRelaySettings.remove("Relay.Example.com", in: defaults)
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://other.example.com"])
|
||||
}
|
||||
|
||||
@Test func resetClearsEverything() {
|
||||
let defaults = makeDefaults()
|
||||
NostrRelaySettings.add("relay.example.com", builtIn: builtIn, in: defaults)
|
||||
|
||||
// Panic wipe: an added relay names an operator someone chose to route
|
||||
// through, which is exactly the trace a wipe must not leave.
|
||||
NostrRelaySettings.reset(in: defaults)
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults).isEmpty)
|
||||
}
|
||||
|
||||
@Test func readsSkipUnusableStoredValues() {
|
||||
let defaults = makeDefaults()
|
||||
// Written by an older build, or edited outside the app: it must not
|
||||
// reach the connection layer unchecked.
|
||||
defaults.set(
|
||||
["wss://good.example.com", "ftp://bad.example.com", "", "wss://good.example.com"],
|
||||
forKey: "nostr.customRelays"
|
||||
)
|
||||
|
||||
#expect(NostrRelaySettings.customRelays(in: defaults) == ["wss://good.example.com"])
|
||||
}
|
||||
|
||||
@Test func builtInRelaysAreExposedNormalizedForDeduplication() {
|
||||
// The UI rejects re-adding a built-in by comparing against this set, so
|
||||
// it has to hold normalized URLs.
|
||||
let builtIn = NostrRelayManager.builtInRelayURLs
|
||||
#expect(!builtIn.isEmpty)
|
||||
for url in builtIn {
|
||||
#expect(NostrRelayURL.normalized(url) == url)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,9 +138,67 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
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>
|
||||
favorites: Set<Data>,
|
||||
selectedChannel: ChannelID = .mesh,
|
||||
selectedChannelSubject: CurrentValueSubject<ChannelID, Never>? = nil
|
||||
) -> NetworkActivationTestContext {
|
||||
let suiteName = "NetworkActivationServiceTests-\(UUID().uuidString)"
|
||||
let storage = UserDefaults(suiteName: suiteName)!
|
||||
@@ -148,6 +206,8 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
|
||||
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()
|
||||
@@ -159,6 +219,11 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
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,
|
||||
|
||||
@@ -1735,6 +1735,58 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertGreaterThan(Set(factors).count, 1)
|
||||
}
|
||||
|
||||
// MARK: - Hand-added relays
|
||||
|
||||
/// Adding a relay has to take effect without a restart: the whole point is
|
||||
/// recovering reachability when the built-in hostnames are blocked.
|
||||
@MainActor
|
||||
func testAddedRelayJoinsTheTargetSetOnSettingsChange() async {
|
||||
let center = NotificationCenter()
|
||||
let custom = MutableRelayList(urls: [])
|
||||
let context = makeContext(
|
||||
permission: .authorized,
|
||||
notificationCenter: center,
|
||||
customRelays: custom
|
||||
)
|
||||
|
||||
XCTAssertFalse(context.manager.relays.contains { $0.url == "wss://added.example.com" })
|
||||
|
||||
custom.urls = ["wss://added.example.com"]
|
||||
center.post(name: NostrRelaySettings.didChangeNotification, object: nil)
|
||||
|
||||
let joined = await waitUntil {
|
||||
context.manager.relays.contains { $0.url == "wss://added.example.com" }
|
||||
}
|
||||
XCTAssertTrue(joined)
|
||||
}
|
||||
|
||||
/// Removing a relay must actually close it. The teardown path iterates the
|
||||
/// current target list, and a removed relay is no longer in it, so without
|
||||
/// an explicit reconcile against the previous set its socket and queued
|
||||
/// sends would linger.
|
||||
@MainActor
|
||||
func testRemovedRelayLeavesTheTargetSet() async {
|
||||
let center = NotificationCenter()
|
||||
let custom = MutableRelayList(urls: ["wss://added.example.com"])
|
||||
let context = makeContext(
|
||||
permission: .authorized,
|
||||
notificationCenter: center,
|
||||
customRelays: custom
|
||||
)
|
||||
|
||||
XCTAssertTrue(context.manager.relays.contains { $0.url == "wss://added.example.com" })
|
||||
|
||||
custom.urls = []
|
||||
center.post(name: NostrRelaySettings.didChangeNotification, object: nil)
|
||||
|
||||
let dropped = await waitUntil {
|
||||
!context.manager.relays.contains { $0.url == "wss://added.example.com" }
|
||||
}
|
||||
XCTAssertTrue(dropped)
|
||||
// The built-in relays are untouched by a custom-relay removal.
|
||||
XCTAssertTrue(context.manager.relays.contains { $0.url == "wss://nos.lol" })
|
||||
}
|
||||
|
||||
private func makeContext(
|
||||
permission: LocationChannelManager.PermissionState,
|
||||
favorites: Set<Data> = [],
|
||||
@@ -1743,6 +1795,8 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
torEnforced: Bool = false,
|
||||
torIsReady: Bool = true,
|
||||
torIsForeground: Bool = true,
|
||||
notificationCenter: NotificationCenter = NotificationCenter(),
|
||||
customRelays: MutableRelayList = MutableRelayList(urls: []),
|
||||
jitterUnit: @escaping () -> Double = { 0.5 } // 0.5 -> jitter factor 1.0 (no jitter)
|
||||
) -> RelayManagerTestContext {
|
||||
let permissionSubject = CurrentValueSubject<LocationChannelManager.PermissionState, Never>(permission)
|
||||
@@ -1770,7 +1824,9 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
scheduler.schedule(delay: delay, action: action)
|
||||
},
|
||||
now: { clock.now },
|
||||
jitterUnit: jitterUnit
|
||||
jitterUnit: jitterUnit,
|
||||
notificationCenter: notificationCenter,
|
||||
customRelays: { customRelays.urls }
|
||||
)
|
||||
)
|
||||
return RelayManagerTestContext(
|
||||
@@ -1845,6 +1901,16 @@ private final class MutableClock {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stand-in for the persisted hand-added relay list, so tests can change it
|
||||
/// without writing to shared preferences.
|
||||
private final class MutableRelayList {
|
||||
var urls: [String]
|
||||
|
||||
init(urls: [String]) {
|
||||
self.urls = urls
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic jitter source: returns the queued values in order, then a
|
||||
/// neutral 0.5 (jitter factor 1.0) once exhausted.
|
||||
private final class JitterSequence {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import bitchat
|
||||
|
||||
/// The geo-relay directory refresh runs off the main actor and has to decide
|
||||
/// whether waiting for Tor is meaningful. It previously waited unconditionally,
|
||||
/// so with Tor switched off — and `TorManager` therefore shut down — every
|
||||
/// refresh spent the full bootstrap timeout and the directory froze on its
|
||||
/// cached copy.
|
||||
struct TorPreferenceReadTests {
|
||||
private func makeDefaults() -> UserDefaults {
|
||||
UserDefaults(suiteName: "bitchat.tests.tor.\(UUID().uuidString)")!
|
||||
}
|
||||
|
||||
@Test func defaultsToOnWhenNothingHasBeenStored() {
|
||||
// Fail safe: an unwritten preference must not read as "Tor off", which
|
||||
// would let a fetch go direct.
|
||||
#expect(NetworkActivationService.persistedTorPreference(in: makeDefaults()))
|
||||
}
|
||||
|
||||
@Test func reflectsTheStoredPreference() {
|
||||
let defaults = makeDefaults()
|
||||
|
||||
defaults.set(false, forKey: NetworkActivationService.torPreferenceKey)
|
||||
#expect(!NetworkActivationService.persistedTorPreference(in: defaults))
|
||||
|
||||
defaults.set(true, forKey: NetworkActivationService.torPreferenceKey)
|
||||
#expect(NetworkActivationService.persistedTorPreference(in: defaults))
|
||||
}
|
||||
|
||||
@Test func nonBooleanStoredValueReadsAsOn() {
|
||||
let defaults = makeDefaults()
|
||||
defaults.set("nonsense", forKey: NetworkActivationService.torPreferenceKey)
|
||||
|
||||
// Same fail-safe direction: anything unrecognized means keep using Tor.
|
||||
#expect(NetworkActivationService.persistedTorPreference(in: defaults))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user