From 22de8ba7702e889bd332281a11c546eecfac1eec Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 21:37:27 -0700 Subject: [PATCH 01/91] Add trusted manual host mobile pairing --- .../CMUXMobileCore/CmxManualHost.swift | 44 ++++ .../CMUXMobileCore/CmxPairingQRCode.swift | 110 +++++++--- .../Sources/CMUXMobileCore/CmxTransport.swift | 3 +- .../CMUXMobileCore/MobileSyncProtocol.swift | 1 + .../CmxManualPairingEntryTests.swift | 15 ++ .../CmxPairingQRCodeTests.swift | 56 ++++- .../CmxTransportTests.swift | 24 +++ .../CmuxMobileRPC/CmxAttachTicketInput.swift | 4 +- .../CmuxMobileRPC/MobileCoreRPCClient.swift | 19 +- .../MobileShellConnectionError.swift | 2 +- .../MobileCoreRPCClientTests.swift | 25 ++- ...ileShellComposite+ManualAttachTicket.swift | 17 +- .../MobileShellComposite.swift | 194 ++++++++++++++++- .../InMemoryMobileManualHostTrustStore.swift | 26 +++ .../MobileManualHostTrustScope.swift | 57 +++++ .../MobileManualHostTrustStoring.swift | 15 ++ .../MobileManualHostTrustWarning.swift | 25 +++ .../MobileShellRouteAuthPolicy.swift | 88 ++++---- ...erDefaultsMobileManualHostTrustStore.swift | 50 +++++ .../MobileShellRouteAuthPolicyTests.swift | 51 ++++- .../CMUXMobileRootView.swift | 10 +- .../CmuxMobileShellUI/PairingView.swift | 40 ++++ .../CmxNetworkByteTransport.swift | 4 +- .../CmxNetworkByteTransportTests.swift | 12 ++ .../Keys/MobileCatalogSection.swift | 10 + .../CuratedSettingEntry+Default.swift | 1 + .../Sections/MobileSection.swift | 57 +++++ .../SettingsRowAnchorResolutionTests.swift | 1 + Resources/Localizable.xcstrings | 204 ++++++++++++++++++ Sources/HostSettingsActions.swift | 2 + Sources/Mobile/MobileAttachTicketStore.swift | 2 +- Sources/Mobile/MobileHostService.swift | 53 ++++- Sources/Mobile/MobileRouteResolver.swift | 25 ++- .../Mobile/Pairing/MobilePairingModel.swift | 59 +++-- .../Mobile/Pairing/MobilePairingView.swift | 68 ++++-- Sources/SettingsSearchAliases.swift | 1 + cmuxTests/MobileHostAuthorizationTests.swift | 19 ++ ...bilePairingConnectionTransitionTests.swift | 1 + ios/cmux/Resources/Localizable.xcstrings | 51 +++++ ios/cmux/cmuxApp.swift | 4 +- .../cmuxFeature/CMUXMobileRuntime.swift | 2 +- .../cmuxFeatureTests/cmuxFeatureTests.swift | 164 +++++++++++--- 42 files changed, 1424 insertions(+), 192 deletions(-) create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/InMemoryMobileManualHostTrustStore.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustWarning.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift new file mode 100644 index 000000000000..071380df8312 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift @@ -0,0 +1,44 @@ +import Foundation + +/// A normalized user-entered host for explicit manual mobile pairing routes. +/// +/// Manual hosts are DNS names or IP literals that a user deliberately chooses +/// outside automatic Tailscale discovery. The value is only a host, never a URL: +/// schemes, paths, query/fragment markers, user-info markers, whitespace, and +/// control characters are rejected before the host is advertised or dialed. +public struct CmxManualHost: Equatable, Sendable { + /// The normalized bare host, with IPv6 brackets removed when present. + public let rawValue: String + + /// Creates a normalized manual host. + /// + /// - Parameter rawHost: A DNS name or IP literal. IPv6 literals may be + /// bracketed (`[fd00::1]`) or unbracketed (`fd00::1`). + public init?(_ rawHost: String) { + let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { + return nil + } + + let host: String + if trimmed.hasPrefix("[") || trimmed.hasSuffix("]") { + guard trimmed.hasPrefix("["), + trimmed.hasSuffix("]"), + trimmed.count > 2 else { + return nil + } + host = String(trimmed.dropFirst().dropLast()) + } else { + host = trimmed + } + + guard !host.isEmpty, + host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil, + host.rangeOfCharacter(from: .controlCharacters) == nil, + host.rangeOfCharacter(from: CharacterSet(charactersIn: "/?#@")) == nil, + host.range(of: "://") == nil else { + return nil + } + self.rawValue = host + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift index 25cb0f7f6456..3011b847af1c 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift @@ -1,9 +1,9 @@ import Foundation /// The minimal pairing-QR grammar: expected Mac account/build metadata plus -/// plain `host:port` routes in the URL query. +/// explicit `host:port` routes in the URL query. /// -/// `cmux-ios://attach?v=2&ub=&pc=&av=&ab=&r=:[&r=:...]` +/// `cmux-ios://attach?v=2&ub=&pc=&av=&ab=&r=:[&m=:]` /// /// A pairing QR needs to tell the phone where to dial and which non-secret /// account/build context to check before dialing. The account value is the @@ -17,16 +17,17 @@ import Foundation /// - **No display name, no device id.** Both arrive post-handshake from /// `mobile.host.status`; the decoder leaves `macDeviceID` empty and the /// shell adopts the host-reported identity once connected. -/// - **No loopback, ever.** Routes are Tailscale `host:port` only: the -/// encoder drops a DEBUG Mac's dev loopback route instead of encoding it, -/// the Mac refuses to mint a QR without a Tailscale route (it shows the -/// set-up-Tailscale guidance instead), and the decoder rejects loopback -/// hosts outright, so a scanned code can never point a phone at itself. +/// - **No loopback, ever.** The encoder drops a DEBUG Mac's dev loopback route +/// instead of encoding it, and the decoder rejects loopback hosts outright, +/// so a scanned code can never point a phone at itself. /// Loopback pairing for the simulator/dev flows uses the injected attach /// URL path, not a QR. Dropping loopback is also the pairing-latency fix: /// a scanned loopback route sorted first and made the phone dial itself /// into an `NWConnection` `.waiting` black hole for the full request /// timeout before the Tailscale route was ever tried. +/// - **Manual hosts stay explicit.** `m=` carries a user-configured LAN/DNS +/// manual-host route, decoded as ``CmxAttachTransportKind/manualHost`` so +/// the iOS app can require per-host trust before sending Stack credentials. /// /// The payload is deliberately *not* wrapped in base64 JSON: anyone can read /// the URL off the QR and see for themselves that it carries only an address. @@ -57,8 +58,9 @@ public struct CmxPairingQRCode: Sendable { /// qualify (see ``canEncode(_:)``); callers fall back to the compact v1 /// payload so every ticket still has an attach URL. /// - /// Only the ticket's Tailscale routes are encoded: a DEBUG Mac's dev - /// loopback route is dropped, never written into a scannable code. + /// Only the ticket's Tailscale and explicit manual-host routes are encoded: + /// a DEBUG Mac's dev loopback route is dropped, never written into a + /// scannable code. public func encode(_ ticket: CmxAttachTicket) -> String? { guard let routes = encodableRoutes(of: ticket) else { return nil @@ -81,7 +83,7 @@ public struct CmxPairingQRCode: Sendable { // Unreachable: `encodableRoutes` admits host/port endpoints only. return "" } - return "r=\(hostPortString(host: host, port: port))" + return "\(routeQueryName(for: route.kind))=\(hostPortString(host: host, port: port))" } items.append(contentsOf: routeItems) // The scheme is channel-specific (see ``CmxPairingURLScheme``): a dev @@ -100,31 +102,34 @@ public struct CmxPairingQRCode: Sendable { /// The route subsequence a v2 pairing URL would carry for `ticket`, or /// `nil` when the ticket is not expressible in the minimal grammar. /// - /// Expressible means: an unscoped pairing ticket whose Tailscale routes - /// are exactly the canonical `host:port` sequence the decoder - /// resynthesizes (ids `tailscale`, `tailscale_2`, ... and priorities 10, - /// 20, ...), with no loopback host and no host that needs escaping. + /// Expressible means: an unscoped pairing ticket whose Tailscale/manual-host + /// routes are exactly the canonical `host:port` sequence the decoder + /// resynthesizes (ids `tailscale`, `manual_host`, `tailscale_2`, ... and + /// priorities 10, 20, ...), with no loopback host and no host that needs + /// escaping. /// The only routes this grammar may silently drop are loopback ones (a /// DEBUG Mac's dev loopback route), which no phone may ever dial anyway. - /// Anything else (workspace-scoped tickets, custom route ids, no - /// Tailscale route at all, or a non-Tailscale fallback route such as an - /// iroh peer that the bare `host:port` grammar cannot express) keeps the - /// compact v1 payload so the mapping stays lossless. + /// Anything else (workspace-scoped tickets, custom route ids, or a fallback + /// route such as an iroh peer that the bare `host:port` grammar cannot + /// express) keeps the compact v1 payload so the mapping stays lossless. private func encodableRoutes(of ticket: CmxAttachTicket) -> [CmxAttachRoute]? { guard ticket.version == CmxAttachTicket.currentVersion, ticket.workspaceID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, ticket.terminalID?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty != false else { return nil } - guard ticket.routes.allSatisfy({ $0.kind == .tailscale || CmxLoopbackHost().matches($0) }) else { + guard ticket.routes.allSatisfy({ isMinimalQRRoute($0) || CmxLoopbackHost().matches($0) }) else { return nil } - let routes = ticket.routes.filter { $0.kind == .tailscale } + let routes = ticket.routes.filter { isMinimalQRRoute($0) } guard !routes.isEmpty, routes.count <= Self.maximumRouteCount else { return nil } + var occurrences: [String: Int] = [:] for (index, route) in routes.enumerated() { - guard route.id == synthesizedRouteID(index: index), + let occurrence = occurrences[route.kind.rawValue] ?? 0 + occurrences[route.kind.rawValue] = occurrence + 1 + guard route.id == synthesizedRouteID(kind: route.kind, occurrence: occurrence), route.priority == synthesizedRoutePriority(index: index), case let .hostPort(host, _) = route.endpoint, !CmxLoopbackHost().matches(host), @@ -179,19 +184,27 @@ public struct CmxPairingQRCode: Sendable { throw MobileSyncPairingPayloadError.invalidURL } let rawRoutes = (components.queryItems ?? []) - .filter { $0.name == "r" } - .compactMap(\.value) + .compactMap { item -> (kind: CmxAttachTransportKind, value: String)? in + guard let kind = routeKind(forQueryName: item.name), + let value = item.value else { + return nil + } + return (kind, value) + } guard !rawRoutes.isEmpty, rawRoutes.count <= Self.maximumRouteCount else { throw MobileSyncPairingPayloadError.invalidURL } + var occurrences: [String: Int] = [:] let routes = try rawRoutes.enumerated().map { index, rawRoute -> CmxAttachRoute in - let (host, port) = try parseHostPort(rawRoute) + let occurrence = occurrences[rawRoute.kind.rawValue] ?? 0 + occurrences[rawRoute.kind.rawValue] = occurrence + 1 + let (host, port) = try parseHostPort(rawRoute.value) guard !CmxLoopbackHost().matches(host) else { throw MobileSyncPairingPayloadError.loopbackRouteRejected } return try CmxAttachRoute( - id: synthesizedRouteID(index: index), - kind: .tailscale, + id: synthesizedRouteID(kind: rawRoute.kind, occurrence: occurrence), + kind: rawRoute.kind, endpoint: .hostPort(host: host, port: port), priority: synthesizedRoutePriority(index: index) ) @@ -215,12 +228,45 @@ public struct CmxPairingQRCode: Sendable { } } private extension CmxPairingQRCode { - /// The route id the Mac's route resolver mints for the route at `index` - /// (`tailscale` for the first, `tailscale_N` after). - func synthesizedRouteID(index: Int) -> String { - index == 0 - ? CmxAttachTransportKind.tailscale.rawValue - : "\(CmxAttachTransportKind.tailscale.rawValue)_\(index + 1)" + /// Whether `route` can be represented by the minimal query grammar. + func isMinimalQRRoute(_ route: CmxAttachRoute) -> Bool { + switch route.kind { + case .tailscale, .manualHost: + return true + case .debugLoopback, .iroh, .websocket: + return false + } + } + + /// The query item name for a minimal route kind. + func routeQueryName(for kind: CmxAttachTransportKind) -> String { + switch kind { + case .tailscale: + return "r" + case .manualHost: + return "m" + case .debugLoopback, .iroh, .websocket: + return "" + } + } + + /// The route kind represented by a minimal route query item name. + func routeKind(forQueryName name: String) -> CmxAttachTransportKind? { + switch name { + case "r": + return .tailscale + case "m": + return .manualHost + default: + return nil + } + } + + /// The route id the Mac's route resolver mints for this kind occurrence. + func synthesizedRouteID(kind: CmxAttachTransportKind, occurrence: Int) -> String { + occurrence == 0 + ? kind.rawValue + : "\(kind.rawValue)_\(occurrence + 1)" } /// The priority the Mac's route resolver assigns the route at `index`. diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxTransport.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxTransport.swift index 3a254ae2265c..358ec6e30cc7 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxTransport.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxTransport.swift @@ -142,7 +142,8 @@ public struct CmxAttachRoute: Codable, Equatable, Sendable { } switch (kind, endpoint) { - case (.tailscale, .hostPort), (.debugLoopback, .hostPort), (.iroh, .peer), (.websocket, .url): + case (.tailscale, .hostPort), (.manualHost, .hostPort), (.debugLoopback, .hostPort), + (.iroh, .peer), (.websocket, .url): break default: throw CmxAttachRouteError.endpointMismatch(kind: kind, endpoint: endpoint) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileSyncProtocol.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileSyncProtocol.swift index 1e2f9a606cb7..c8a76004b44f 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileSyncProtocol.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileSyncProtocol.swift @@ -13,6 +13,7 @@ public struct CmxMobileDefaults { public enum CmxAttachTransportKind: String, Codable, Sendable { case tailscale + case manualHost = "manual_host" case iroh case websocket case debugLoopback = "debug_loopback" diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualPairingEntryTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualPairingEntryTests.swift index 5733a7bd79e6..dac8641a8b96 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualPairingEntryTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualPairingEntryTests.swift @@ -39,6 +39,21 @@ import Testing #expect(entry == CmxManualPairingEntry(host: "lawrences-mac.tail1234.ts.net", port: 58465)) } + @Test func usesExplicitManualHostWhenNoTailscaleRouteExists() throws { + let entry = CmxManualPairingEntry.best(in: [ + try route(id: "manual_host", kind: .manualHost, host: "studio-mac.corp.example", priority: 10), + ]) + #expect(entry == CmxManualPairingEntry(host: "studio-mac.corp.example", port: 58465)) + } + + @Test func prefersTailscaleOverExplicitManualHostWhenBothExist() throws { + let entry = CmxManualPairingEntry.best(in: [ + try route(id: "manual_host", kind: .manualHost, host: "192.168.4.12", priority: 10), + try route(id: "tailscale", host: "100.64.0.5", priority: 20), + ]) + #expect(entry == CmxManualPairingEntry(host: "100.64.0.5", port: 58465)) + } + @Test func skipsLoopbackRoutesEntirely() throws { // A DEBUG Mac's dev loopback route must never be offered for manual // phone entry, same rule as the QR encoder. diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift index fd9d4d48dc94..96358cd7f241 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing @testable import CMUXMobileCore -/// Coverage for the minimal v2 pairing-QR grammar: bare Tailscale +/// Coverage for the minimal v2 pairing-QR grammar: bare Tailscale/manual-host /// `host:port` routes in the URL query, nothing else. @Suite struct CmxPairingQRCodeTests { private func tailscaleRoute( @@ -18,6 +18,19 @@ import Testing ) } + private func manualHostRoute( + index: Int, + host: String, + port: Int = 58465 + ) throws -> CmxAttachRoute { + try CmxAttachRoute( + id: index == 0 ? "manual_host" : "manual_host_\(index + 1)", + kind: .manualHost, + endpoint: .hostPort(host: host, port: port), + priority: 10 + index * 10 + ) + } + private func pairingTicket(routes: [CmxAttachRoute]) throws -> CmxAttachTicket { // Exactly what the Mac's ticket store mints for the pairing window: // unscoped, with identity/expiry/token fields the QR must NOT carry. @@ -75,6 +88,38 @@ import Testing #expect(decoded.routes.map(\.priority) == [10, 20]) } + @Test func roundTripsManualHostRouteExplicitly() throws { + let route = try manualHostRoute(index: 0, host: "studio-mac.corp.example") + let ticket = try pairingTicket(routes: [route]) + + let url = try #require(CmxPairingQRCode().encode(ticket)) + #expect(url == "\(CmxPairingURLScheme.current)://attach?v=2&m=studio-mac.corp.example:58465") + + let decoded = try CmxPairingQRCode().decode(try components(url)) + #expect(decoded.routes == [route]) + #expect(decoded.routes.first?.kind == .manualHost) + } + + @Test func roundTripsTailscaleAndManualHostRoutesInOrder() throws { + let routes = [ + try tailscaleRoute(index: 0, host: "100.64.0.5"), + try CmxAttachRoute( + id: "manual_host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.4.12", port: 58465), + priority: 20 + ), + ] + let ticket = try pairingTicket(routes: routes) + + let url = try #require(CmxPairingQRCode().encode(ticket)) + #expect(url == "\(CmxPairingURLScheme.current)://attach?v=2&r=100.64.0.5:58465&m=192.168.4.12:58465") + + let decoded = try CmxPairingQRCode().decode(try components(url)) + #expect(decoded.routes == routes) + #expect(decoded.routes.map(\.kind) == [.tailscale, .manualHost]) + } + @Test func roundTripsUserIDAndBuildMetadataWithoutExposingEmail() throws { let ticket = try CmxAttachTicket( workspaceID: "", @@ -121,7 +166,7 @@ import Testing @Test func encodeDropsDevLoopbackRouteFromDebugMacTicket() throws { // A DEBUG Mac's pairing ticket always carries the dev loopback route. - // The QR must encode only the Tailscale routes: a scanned code + // The QR must encode only the Tailscale/manual-host routes: a scanned code // pointing at 127.0.0.1 makes the phone dial itself (and dialing it // first added the whole request timeout to scan-to-pair latency). let loopback = try CmxAttachRoute( @@ -208,6 +253,13 @@ import Testing #expect(!CmxPairingQRCode().canEncode(withIrohFallback)) } + @Test func decodeRejectsManualHostLoopback() throws { + let url = "cmux-ios://attach?v=2&m=127.0.0.1:58465" + #expect(throws: MobileSyncPairingPayloadError.loopbackRouteRejected) { + try CmxPairingQRCode().decode(try components(url)) + } + } + @Test(arguments: [ "127.0.0.1", "127.0.0.2", diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxTransportTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxTransportTests.swift index ca2419a8cc1c..a88139d26a77 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxTransportTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxTransportTests.swift @@ -67,6 +67,11 @@ import Testing kind: .tailscale, endpoint: .hostPort(host: "100.64.1.2", port: 49831) ), + CmxAttachRoute( + id: "manual_host", + kind: .manualHost, + endpoint: .hostPort(host: "studio-mac.corp.example", port: 49831) + ), CmxAttachRoute( id: "iroh", kind: .iroh, @@ -104,6 +109,25 @@ import Testing #expect(decoded == ticket) } +@Test func attachRouteAcceptsManualHostPortEndpoint() throws { + let route = try CmxAttachRoute( + id: "manual_host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.4.12", port: 58_465) + ) + + #expect(route.kind == .manualHost) + #expect(route.endpoint == .hostPort(host: "192.168.4.12", port: 58_465)) +} + +@Test func manualHostNormalizerRejectsURLsAndAcceptsBracketedIPv6() { + #expect(CmxManualHost(" studio-mac.corp.example ")?.rawValue == "studio-mac.corp.example") + #expect(CmxManualHost("[fd00::12]")?.rawValue == "fd00::12") + #expect(CmxManualHost("https://studio-mac.corp.example") == nil) + #expect(CmxManualHost("studio-mac.corp.example/path") == nil) + #expect(CmxManualHost("studio mac") == nil) +} + @Test func attachTicketRejectsEmptyAuthToken() throws { let route = try CmxAttachRoute( id: "tailscale", diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/CmxAttachTicketInput.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/CmxAttachTicketInput.swift index 5859885f6067..0fb58d381500 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/CmxAttachTicketInput.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/CmxAttachTicketInput.swift @@ -42,8 +42,8 @@ public struct CmxAttachTicketInput { version > CmxPairingQRCode.version { throw MobileSyncPairingPayloadError.unrecognizedURLVersion(version) } - // The minimal v2 pairing-code grammar (bare Tailscale routes, loopback - // rejected). v1 URLs carry a base64 JSON `payload` item instead. + // The minimal v2 pairing-code grammar (bare Tailscale/manual-host + // routes, loopback rejected). v1 URLs carry a base64 JSON `payload` item instead. if CmxPairingQRCode().isPairingCodeURL(components) { return try CmxPairingQRCode().decode(components) } diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift index 68f31f68a989..7d8b2063af15 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift @@ -13,6 +13,7 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { private let route: CmxAttachRoute private let ticket: CmxAttachTicket private let allowsStackAuthFallback: Bool + private let allowsTrustedManualHostStackAuth: Bool // `internal` (not `private`) so `@testable import` can observe session // queue state from tests, instead of exposing a debug hook in production. let session: MobileCoreRPCSession @@ -26,11 +27,15 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { /// - ticket: The attach ticket authorizing requests. /// - allowsStackAuthFallback: When `true`, falls back to a Stack Auth token /// on routes that allow it once the attach ticket no longer covers a request. + /// - allowsTrustedManualHostStackAuth: When `true`, this client may send + /// Stack auth over its exact `.manualHost` route because the shell has + /// verified a persisted user approval for that host and port. public init( runtime: any MobileSyncRuntime, route: CmxAttachRoute, ticket: CmxAttachTicket, allowsStackAuthFallback: Bool = false, + allowsTrustedManualHostStackAuth: Bool = false, connectAttemptRegistry: MobileRPCConnectAttemptRegistry = MobileRPCConnectAttemptRegistry(), stackTokenGate: RPCStackTokenGate? = nil, stackTokenForceRefreshGate: RPCStackTokenGate? = nil, @@ -42,6 +47,7 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { self.route = route self.ticket = ticket self.allowsStackAuthFallback = allowsStackAuthFallback + self.allowsTrustedManualHostStackAuth = allowsTrustedManualHostStackAuth self.stackTokenGate = stackTokenGate ?? RPCStackTokenGate(timedOutResetNanoseconds: stackTokenGateResetNanoseconds) self.stackTokenForceRefreshGate = stackTokenForceRefreshGate @@ -215,7 +221,7 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { // expiry), so they never reach this branch. if !ticket.isExpired(at: runtime.now()) { auth["attach_token"] = attachToken - } else if !allowsStackAuthFallback || !MobileShellRouteAuthPolicy.routeAllowsStackAuth(route) { + } else if !allowsStackAuthFallback || !routeAllowsStackAuth { throw MobileShellConnectionError.attachTicketExpired } } @@ -230,7 +236,7 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { let shouldSendStackAuth = requestNeedsAuth if shouldSendStackAuth { guard allowsStackAuthFallback, - MobileShellRouteAuthPolicy.routeAllowsStackAuth(route) else { + routeAllowsStackAuth else { throw MobileShellConnectionError.insecureManualRoute } do { @@ -259,7 +265,7 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { if !requestNeedsAuth, isHostStatusRequest(request), allowsStackAuthFallback, - MobileShellRouteAuthPolicy.routeAllowsStackAuth(route), + routeAllowsStackAuth, let stackAccessToken = try await stackAccessTokenForStatus(deadline: deadline) { auth["stack_access_token"] = stackAccessToken } @@ -269,6 +275,13 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { return try JSONSerialization.data(withJSONObject: request) } + private var routeAllowsStackAuth: Bool { + MobileShellRouteAuthPolicy.routeAllowsStackAuth( + route, + manualHostTrusted: allowsTrustedManualHostStackAuth + ) + } + private func stackAccessTokenForStatus(deadline: RPCRequestDeadline) async throws -> String? { let task = Task { [runtime] in await runtime.stackAccessTokenForStatusProvider() diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift index 79eff947c753..25507428a0e6 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift @@ -9,7 +9,7 @@ public enum MobileShellConnectionError: LocalizedError { case connectionClosed /// A request exceeded its timeout deadline. case requestTimedOut - /// A manual host did not advertise a secure route. + /// A manual-host route was not approved for Stack-authenticated mobile sync. case insecureManualRoute /// The attach ticket expired and no fallback was available. case attachTicketExpired diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift index 910b1a7e5d90..bb4fdb02730d 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift @@ -317,11 +317,34 @@ import Testing // A manually-entered plain-LAN host is dialed over unencrypted TCP; // the account bearer token must never ride it, even opportunistically. // The probe itself still goes out tokenless instead of throwing. - let route = try hostPortRoute(kind: .tailscale, host: "192.168.1.20", port: 58465) + let route = try hostPortRoute(kind: .manualHost, host: "192.168.1.20", port: 58465) let probe = try await sentHostStatusProbe(route: route, stackAccessToken: "test-stack-token") #expect(probe?.hasAuth == false) } + @Test func trustedManualHostRouteCarriesStackToken() async throws { + let route = try hostPortRoute(kind: .manualHost, host: "192.168.1.20", port: 58465) + let transport = QueuedCancellationProbeTransport() + let runtime = TestMobileSyncRuntime( + transportFactory: QueuedCancellationProbeTransportFactory(transport: transport), + stackAccessToken: "trusted-manual-token" + ) + let client = MobileCoreRPCClient( + runtime: runtime, + route: route, + ticket: try qrPairingTicket(route: route), + allowsStackAuthFallback: true, + allowsTrustedManualHostStackAuth: true + ) + let request = try MobileCoreRPCClient.requestData(method: "workspace.list") + let task = Task { try await client.sendRequest(request) } + let sent = try await transport.waitForSentRequestCount(1) + task.cancel() + _ = try? await task.value + + #expect(sent.first?.stackAccessToken == "trusted-manual-token") + } + @Test func workspaceActionsCarryMacWideAttachTicketContext() async throws { let route = try hostPortRoute(kind: .tailscale, host: "100.64.0.5", port: 58465) let transport = QueuedCancellationProbeTransport() diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift index 71177e6f6888..63a2ac6dd8ed 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift @@ -36,7 +36,7 @@ extension MobileShellComposite { macDeviceID: macDeviceID, macDisplayName: displayName, routes: [route], - expiresAt: Date().addingTimeInterval(60 * 60) + expiresAt: Date.now.addingTimeInterval(60 * 60) ) } @@ -44,16 +44,21 @@ extension MobileShellComposite { name: String, host: String, port: Int, - attemptStartedAt: Date? + attemptStartedAt: Date?, + manualHostTrusted: Bool = false ) async throws -> CmxAttachTicket { let directRoute = try Self.manualHostRoute(host: host, port: port) let displayName = name.isEmpty ? host : name - if MobileShellRouteAuthPolicy.routeAllowsStackAuth(directRoute) { + if MobileShellRouteAuthPolicy.routeAllowsStackAuth( + directRoute, + manualHostTrusted: manualHostTrusted + ) { do { let ticket = try await requestManualAttachTicket( route: directRoute, displayName: displayName, - attemptStartedAt: attemptStartedAt + attemptStartedAt: attemptStartedAt, + manualHostTrusted: manualHostTrusted ) return ticket } catch { @@ -94,7 +99,8 @@ extension MobileShellComposite { func requestManualAttachTicket( route: CmxAttachRoute, displayName: String, - attemptStartedAt: Date? + attemptStartedAt: Date?, + manualHostTrusted: Bool = false ) async throws -> CmxAttachTicket { guard let runtime else { throw MobileShellConnectionError.insecureManualRoute @@ -109,6 +115,7 @@ extension MobileShellComposite { route: route, ticket: probeTicket, allowsStackAuthFallback: true, + allowsTrustedManualHostStackAuth: manualHostTrusted, connectAttemptRegistry: connectAttemptRegistry, stackTokenGate: stackTokenGate, stackTokenForceRefreshGate: stackTokenForceRefreshGate diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 8c099460f768..3d177b2d4e95 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -15,6 +15,18 @@ private let mobileShellLog = Logger( category: "mobile-shell" ) +private enum PendingManualHostTrust { + case manual( + name: String, + host: String, + port: Int, + pairedMacDeviceID: String?, + recordsPairingAttempt: Bool, + ifStillCurrent: (() -> Bool)? + ) + case pairingURL(rawURL: String, acceptedVersionWarning: Bool) +} + /// Transitional alias for the decomposed shell facade. /// /// The iOS views and push coordinator still bind to `CMUXMobileShellStore`; @@ -168,6 +180,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// A warning that must be accepted before pairing continues, currently used /// for Mac/iPhone app-version skew. public private(set) var pairingVersionWarning: String? + /// A warning that must be accepted before a non-Tailscale manual host can + /// carry Stack auth over plaintext LAN transport. + public private(set) var manualHostTrustWarning: MobileManualHostTrustWarning? public private(set) var activeTicket: CmxAttachTicket? public private(set) var activeRoute: CmxAttachRoute? @@ -574,6 +589,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private let pairingHintDefaults: UserDefaults private let multiMacAggregationDefaults: UserDefaults let forgottenMacStore: any PairedMacForgottenStoring + let manualHostTrustStore: any MobileManualHostTrustStoring let clientID: String /// Delivers the email path of Send Feedback (`/api/feedback`). `nil` when the /// web API base URL is unavailable; the email path then fails closed and the @@ -609,6 +625,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// false` and break the first-pair funnel. private var pairingAttemptIsFirstPair = false private var pendingPairingVersionWarningURL: String? + @ObservationIgnored private var pendingManualHostTrust: PendingManualHostTrust? /// The structured diagnostic log, injected from the app composition root. /// @@ -861,6 +878,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { pairingHintDefaults: UserDefaults = .standard, multiMacAggregationDefaults: UserDefaults = .standard, forgottenMacStore: any PairedMacForgottenStoring = InMemoryPairedMacForgottenStore(), + manualHostTrustStore: any MobileManualHostTrustStoring = UserDefaultsMobileManualHostTrustStore(), analytics: any AnalyticsEmitting = NoopAnalytics(), diagnosticLog: DiagnosticLog? = nil, feedbackEmailSubmitter: (any MobileFeedbackEmailSubmitting)? = nil, @@ -884,6 +902,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { self.pairingHintDefaults = pairingHintDefaults self.multiMacAggregationDefaults = multiMacAggregationDefaults self.forgottenMacStore = forgottenMacStore + self.manualHostTrustStore = manualHostTrustStore self.analytics = analytics self.diagnosticLog = diagnosticLog self.feedbackEmailSubmitter = feedbackEmailSubmitter @@ -917,6 +936,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { self.connectionError = nil self.connectionErrorGuidance = nil self.pairingVersionWarning = nil + self.manualHostTrustWarning = nil self.activeTicket = nil self.activeRoute = nil self.selectedWorkspaceID = workspaces.first?.id @@ -994,10 +1014,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } - public static func preview(runtime: (any MobileSyncRuntime)? = nil) -> CMUXMobileShellStore { + public static func preview( + runtime: (any MobileSyncRuntime)? = nil, + manualHostTrustStore: any MobileManualHostTrustStoring = InMemoryMobileManualHostTrustStore() + ) -> CMUXMobileShellStore { CMUXMobileShellStore( runtime: runtime, workspaces: PreviewMobileHost.workspaces, + manualHostTrustStore: manualHostTrustStore, deliveredNotificationClearer: NoopDeliveredNotificationClearer() ) } @@ -1577,6 +1601,22 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } let directRoute = try? Self.manualHostRoute(host: normalizedHost, port: port) + if let directRoute, + await manualHostRouteNeedsApproval(directRoute) { + queueManualHostTrustWarning( + route: directRoute, + displayHost: normalizedHost, + pending: .manual( + name: name, + host: normalizedHost, + port: port, + pairedMacDeviceID: pairedMacDeviceID, + recordsPairingAttempt: recordsPairingAttempt, + ifStillCurrent: ifStillCurrent + ) + ) + return + } activeRoute = directRoute let attemptID = recordsPairingAttempt ? beginPairingAttempt(method: "manual") : beginPairingValidationAttempt() // Fast offline preflight: fail immediately instead of stacking @@ -1584,16 +1624,23 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let manualRoutes = directRoute.map { [$0] } ?? [] guard await failPairingIfOffline(attemptID: attemptID, phase: "preflight", routes: manualRoutes) == .proceed else { return } do { + let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) let ticket = try await manualHostTicket( name: trimmedName, host: normalizedHost, port: port, - attemptStartedAt: pairingAttemptStartedAt + attemptStartedAt: pairingAttemptStartedAt, + manualHostTrusted: manualHostTrusted ) guard isCurrentPairingAttempt(attemptID) else { return } let noThrowFailure = try await connect( ticket: ticket, - allowsStackAuthFallback: true, + allowsStackAuthFallback: directRoute.map { + MobileShellRouteAuthPolicy.routeAllowsStackAuth( + $0, + manualHostTrusted: manualHostTrusted + ) + }, pairedMacDeviceID: pairedMacDeviceID, ifStillCurrent: ifStillCurrent ) @@ -3189,6 +3236,20 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return .needsUserApproval } + let candidateRoutes = Self.supportedRoutes(for: ticket, supportedKinds: runtime?.supportedRouteKinds ?? []) + if let approval = await firstManualHostRouteNeedingApproval(in: candidateRoutes), + case let .hostPort(host, _) = approval.route.endpoint { + queueManualHostTrustWarning( + route: approval.route, + displayHost: host, + pending: .pairingURL( + rawURL: rawURL, + acceptedVersionWarning: acceptedVersionWarning + ) + ) + return .needsUserApproval + } + let attemptID = beginPairingAttempt(method: "qr") // Offline preflight: fail fast instead of stacking per-route connect @@ -3198,7 +3259,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // pairing input now (expiry is enforced solely where the RPC attach // token is used), so an expired legacy code scanned offline must say // "offline", not crawl the route loop's stacked timeouts. - let candidateRoutes = Self.supportedRoutes(for: ticket, supportedKinds: runtime?.supportedRouteKinds ?? []) if !candidateRoutes.isEmpty { switch await failPairingIfOffline(attemptID: attemptID, phase: "preflight", routes: candidateRoutes) { case .failedOffline: return .failed @@ -3244,11 +3304,13 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { public func cancelPairing() { invalidatePairingAttempt() clearPairingError() - if pairingVersionWarning != nil || pendingPairingVersionWarningURL != nil { + if pairingVersionWarning != nil || pendingPairingVersionWarningURL != nil || manualHostTrustWarning != nil { clearPairingVersionWarning() + clearManualHostTrustWarning() return } clearPairingVersionWarning() + clearManualHostTrustWarning() connectionState = .disconnected macConnectionStatus = .unavailable clearRemoteConnectionContext() @@ -3377,11 +3439,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } let ticket: CmxAttachTicket do { + let directRoute = try Self.manualHostRoute(host: host, port: port) + let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) ticket = try await manualHostTicket( name: mac.displayName ?? host, host: host, port: port, - attemptStartedAt: nil + attemptStartedAt: nil, + manualHostTrusted: manualHostTrusted ) } catch { mobileShellLog.warning( @@ -3404,11 +3469,19 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { }) ?? supportedRoutes.first(where: { $0.kind != .debugLoopback }) ?? supportedRoutes.first guard let route else { return nil } + let manualHostTrusted = await manualHostStackAuthTrusted(for: route) + guard MobileShellRouteAuthPolicy.routeAllowsStackAuth( + route, + manualHostTrusted: manualHostTrusted + ) else { + return nil + } let client = MobileCoreRPCClient( runtime: runtime, route: route, ticket: ticket, - allowsStackAuthFallback: MobileShellRouteAuthPolicy.routeAllowsStackAuth(route), + allowsStackAuthFallback: true, + allowsTrustedManualHostStackAuth: manualHostTrusted, connectAttemptRegistry: connectAttemptRegistry, stackTokenGate: stackTokenGate, stackTokenForceRefreshGate: stackTokenForceRefreshGate @@ -4964,12 +5037,18 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { for route in supportedRoutes { activeRoute = route mobileShellLog.info("pairing trying route kind=\(route.kind.rawValue, privacy: .public) endpoint=\(route.endpoint.logDescription, privacy: .private)") + let manualHostTrusted = await manualHostStackAuthTrusted(for: route) + let routeAllowsStackAuth = MobileShellRouteAuthPolicy.routeAllowsStackAuth( + route, + manualHostTrusted: manualHostTrusted + ) let client = MobileCoreRPCClient( runtime: runtime, route: route, ticket: ticket, allowsStackAuthFallback: routeAllowsStackAuthFallbackOverride - ?? MobileShellRouteAuthPolicy.routeAllowsStackAuth(route), + ?? routeAllowsStackAuth, + allowsTrustedManualHostStackAuth: manualHostTrusted, connectAttemptRegistry: connectAttemptRegistry, stackTokenGate: stackTokenGate, stackTokenForceRefreshGate: stackTokenForceRefreshGate @@ -5178,7 +5257,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { generation: UUID, timeoutNanoseconds: UInt64? = nil ) async -> Bool { - guard MobileShellRouteAuthPolicy.routeAllowsStackAuth(route), + let manualHostTrusted = await manualHostStackAuthTrusted(for: route) + guard MobileShellRouteAuthPolicy.routeAllowsStackAuth( + route, + manualHostTrusted: manualHostTrusted + ), let attachToken = activeTicket?.authToken?.trimmingCharacters(in: .whitespacesAndNewlines), !attachToken.isEmpty else { return false @@ -5339,6 +5422,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { rawTerminalInputBuffer.clear() clearPairingError() clearPairingVersionWarning() + clearManualHostTrustWarning() return attemptID } @@ -5518,6 +5602,98 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { pendingPairingVersionWarningURL = nil } + private func clearManualHostTrustWarning() { + manualHostTrustWarning = nil + pendingManualHostTrust = nil + } + + private func manualHostTrustScope(for route: CmxAttachRoute?) -> MobileManualHostTrustScope? { + guard let route, + MobileShellRouteAuthPolicy.routeRequiresManualHostTrust(route) else { + return nil + } + return MobileManualHostTrustScope( + route: route, + stackUserID: identityProvider?.currentUserID + ) + } + + private func manualHostStackAuthTrusted(for route: CmxAttachRoute?) async -> Bool { + guard let scope = manualHostTrustScope(for: route) else { + return false + } + return await manualHostTrustStore.isTrusted(scope) + } + + private func manualHostRouteNeedsApproval(_ route: CmxAttachRoute) async -> Bool { + guard let scope = manualHostTrustScope(for: route) else { + return false + } + return !(await manualHostTrustStore.isTrusted(scope)) + } + + private func firstManualHostRouteNeedingApproval( + in routes: [CmxAttachRoute] + ) async -> (route: CmxAttachRoute, scope: MobileManualHostTrustScope)? { + for route in routes { + if MobileShellRouteAuthPolicy.routeAllowsStackAuth(route) { + return nil + } + guard let scope = manualHostTrustScope(for: route) else { + continue + } + if await manualHostTrustStore.isTrusted(scope) { + return nil + } + return (route, scope) + } + return nil + } + + private func queueManualHostTrustWarning( + route: CmxAttachRoute, + displayHost: String, + pending: PendingManualHostTrust + ) { + guard let scope = manualHostTrustScope(for: route) else { + return + } + clearPairingError() + pendingManualHostTrust = pending + manualHostTrustWarning = MobileManualHostTrustWarning( + scope: scope, + displayHost: displayHost + ) + } + + @discardableResult + public func acceptManualHostTrustWarning() async -> MobilePairingURLConnectionResult { + guard let warning = manualHostTrustWarning, + let pending = pendingManualHostTrust else { + clearManualHostTrustWarning() + return .failed + } + await manualHostTrustStore.trust(warning.scope) + clearManualHostTrustWarning() + switch pending { + case let .manual(name, host, port, pairedMacDeviceID, recordsPairingAttempt, ifStillCurrent): + await connectManualHost( + name: name, + host: host, + port: port, + pairedMacDeviceID: pairedMacDeviceID, + recordsPairingAttempt: recordsPairingAttempt, + ifStillCurrent: ifStillCurrent + ) + return connectionState == .connected ? .connected : .failed + case let .pairingURL(rawURL, acceptedVersionWarning): + return await connectPairingURLResult( + rawURL, + acceptedVersionWarning: acceptedVersionWarning + ) + } + } + private func versionWarning(for ticket: CmxAttachTicket) -> String? { guard let macCompatibilityVersion = ticket.macPairingCompatibilityVersion, macCompatibilityVersion != CmxMobileDefaults.pairingCompatibilityVersion else { diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/InMemoryMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/InMemoryMobileManualHostTrustStore.swift new file mode 100644 index 000000000000..e3392ac5d85f --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/InMemoryMobileManualHostTrustStore.swift @@ -0,0 +1,26 @@ +import Foundation + +/// In-memory manual-host trust store for tests and previews. +public actor InMemoryMobileManualHostTrustStore: MobileManualHostTrustStoring { + private var trustedScopes: Set = [] + + /// Creates an empty in-memory trust store. + public init() {} + + /// Returns whether the given host/port/account scope is already trusted. + /// - Parameter scope: The scope to look up. + public func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + trustedScopes.contains(scope) + } + + /// Persists trust for exactly the given host/port/account scope. + /// - Parameter scope: The scope to approve. + public func trust(_ scope: MobileManualHostTrustScope) async { + trustedScopes.insert(scope) + } + + /// Removes every stored approval. + public func removeAll() async { + trustedScopes.removeAll() + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift new file mode 100644 index 000000000000..97fd4fc17cc3 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift @@ -0,0 +1,57 @@ +import CMUXMobileCore +import Foundation + +/// A narrowly-scoped manual-host trust decision. +/// +/// Trust is keyed to the normalized host, port, and current Stack user id when +/// one is available. That keeps an approval for one LAN host from becoming a +/// global permission for unrelated plaintext routes. +public struct MobileManualHostTrustScope: Equatable, Hashable, Sendable { + /// The normalized host, lowercased for DNS/IP-literal comparisons. + public let normalizedHost: String + /// The approved TCP port. + public let port: Int + /// The Stack user id that approved this route, or `nil` when no account is known. + public let stackUserID: String? + + /// Creates a trust scope from a user-entered host and port. + /// - Parameters: + /// - host: A DNS name or IP literal. + /// - port: The TCP port in `1...65535`. + /// - stackUserID: The approving Stack user id, if known. + public init?(host: String, port: Int, stackUserID: String?) { + guard let manualHost = CmxManualHost(host), + (1...65535).contains(port) else { + return nil + } + self.normalizedHost = manualHost.rawValue.lowercased() + self.port = port + let trimmedUserID = stackUserID?.trimmingCharacters(in: .whitespacesAndNewlines) + self.stackUserID = trimmedUserID?.isEmpty == false ? trimmedUserID : nil + } + + /// Creates a trust scope from an attach route. + /// - Parameters: + /// - route: The manual-host route to scope. + /// - stackUserID: The approving Stack user id, if known. + public init?(route: CmxAttachRoute, stackUserID: String?) { + guard case let .hostPort(host, port) = route.endpoint else { + return nil + } + self.init(host: host, port: port, stackUserID: stackUserID) + } + + var storageKey: String { + [ + Self.escape(stackUserID ?? ""), + Self.escape(normalizedHost), + "\(port)", + ].joined(separator: "|") + } + + private static func escape(_ value: String) -> String { + value + .replacing("%", with: "%25") + .replacing("|", with: "%7C") + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift new file mode 100644 index 000000000000..a5aabe9d7dc3 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift @@ -0,0 +1,15 @@ +import Foundation + +/// Persistence for explicit manual-host approvals. +public protocol MobileManualHostTrustStoring: Sendable { + /// Returns whether the given host/port/account scope is already trusted. + /// - Parameter scope: The scope to look up. + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool + + /// Persists trust for exactly the given host/port/account scope. + /// - Parameter scope: The scope to approve. + func trust(_ scope: MobileManualHostTrustScope) async + + /// Removes every stored approval. + func removeAll() async +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustWarning.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustWarning.swift new file mode 100644 index 000000000000..7a1e3f5c732f --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustWarning.swift @@ -0,0 +1,25 @@ +import Foundation + +/// UI state describing a manual-host route that needs explicit trust. +public struct MobileManualHostTrustWarning: Equatable, Sendable { + /// The trust scope that will be persisted if the user approves. + public let scope: MobileManualHostTrustScope + /// The host text shown to the user. + public let displayHost: String + + /// Creates a warning for a pending manual-host approval. + /// - Parameters: + /// - scope: The narrow host/port/account trust scope. + /// - displayHost: The host string to show. Defaults to the normalized host. + public init(scope: MobileManualHostTrustScope, displayHost: String? = nil) { + self.scope = scope + self.displayHost = displayHost ?? scope.normalizedHost + } + + /// The approved endpoint, formatted for display. + public var endpoint: String { + displayHost.contains(":") + ? "[\(displayHost)]:\(scope.port)" + : "\(displayHost):\(scope.port)" + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift index 596921fc6efc..f2b351df00a7 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift @@ -8,13 +8,13 @@ import Foundation /// vs Tailscale vs LAN vs arbitrary host) can be exhaustively tested without a live /// connection. /// -/// The Stack-bearer-token gate (``routeAllowsStackAuth(_:)``) is intentionally -/// restricted to **encrypted or loopback channels only**: the Tailscale tunnel -/// (WireGuard-encrypted), iroh peer connections (encrypted), and loopback (never -/// leaves the machine). Plain private-LAN and `.local`/Bonjour hosts are dialed -/// over unencrypted TCP (``CmxNetworkByteTransport`` uses `NWParameters(tls: nil)`), -/// so they are excluded from the Stack-auth-allowed set even though they may still -/// be reachable as attach routes. +/// The Stack-bearer-token gate (``routeAllowsStackAuth(_:manualHostTrusted:)``) +/// is intentionally restricted to encrypted/loopback channels plus an explicit +/// per-host manual approval: the Tailscale tunnel (WireGuard-encrypted), iroh +/// peer connections (encrypted), loopback (never leaves the machine), and a +/// manual-host route only after the user accepts the plaintext-LAN warning. +/// Plain private-LAN and `.local`/Bonjour hosts remain excluded by default even +/// though they may still be reachable as attach routes. public struct MobileShellRouteAuthPolicy { private init() {} @@ -23,68 +23,61 @@ public struct MobileShellRouteAuthPolicy { /// - Parameter rawHost: The raw host string typed by the user. /// - Returns: The normalized bare host, or `nil` when it is not a valid host. public static func normalizedManualHost(_ rawHost: String) -> String? { - let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { - return nil - } - - let host: String - if trimmed.hasPrefix("[") || trimmed.hasSuffix("]") { - guard trimmed.hasPrefix("["), - trimmed.hasSuffix("]"), - trimmed.count > 2 else { - return nil - } - host = String(trimmed.dropFirst().dropLast()) - } else { - host = trimmed - } - - guard !host.isEmpty, - host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil, - host.rangeOfCharacter(from: .controlCharacters) == nil, - host.rangeOfCharacter(from: CharacterSet(charactersIn: "/?#@")) == nil, - host.range(of: "://") == nil else { - return nil - } - return host + CmxManualHost(rawHost)?.rawValue } /// Maps a manually typed host to the transport kind that should be used. /// - Parameter host: The host to classify. - /// - Returns: `.debugLoopback` for loopback hosts, otherwise `.tailscale`. + /// - Returns: `.debugLoopback` for loopback hosts, `.tailscale` for + /// Tailscale IP/MagicDNS hosts, otherwise `.manualHost`. public static func manualRouteKind(for host: String) -> CmxAttachTransportKind { - let normalizedHost = host.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let normalizedHost = (normalizedManualHost(host) ?? host) + .trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased() if isLoopbackHost(normalizedHost) { return .debugLoopback } - return .tailscale + if isTailscaleHost(normalizedHost) { + return .tailscale + } + return .manualHost } /// Whether the given route is trusted enough to carry the Stack bearer token. /// /// The Stack `stack_access_token` is the owner's account credential, so it must - /// only ever traverse an encrypted or loopback channel. This predicate gates - /// every Stack-token-send site and returns `true` only for: + /// only ever traverse an encrypted/loopback channel or an explicitly trusted + /// manual-host route. This predicate gates every Stack-token-send site and + /// returns `true` only for: /// /// - `.tailscale` to a Tailscale host (a `100.64.0.0/10` CGNAT address or a /// `*.ts.net` MagicDNS host), which rides the WireGuard-encrypted tunnel. /// - `.iroh` to a peer, which is an encrypted QUIC connection. /// - `.debugLoopback` to a loopback host, which never leaves the machine. + /// - `.manualHost` to a host/port that has a persisted user approval. /// /// Plain private-LAN (`192.168/16`, `10/8`, `172.16/12`, link-local) and /// `.local`/Bonjour hosts are deliberately **excluded**: they are dialed over /// unencrypted TCP (``CmxNetworkByteTransport`` uses `NWParameters(tls: nil)`), /// so sending the bearer token to such a host would disclose it in plaintext on /// the local network before the Mac proves it is the same-account host. - /// - Parameter route: The candidate attach route. - /// - Returns: `true` only for Tailscale-tunnel, iroh peer, and loopback routes. - public static func routeAllowsStackAuth(_ route: CmxAttachRoute) -> Bool { + /// - Parameters: + /// - route: The candidate attach route. + /// - manualHostTrusted: Whether this exact `.manualHost` route has an + /// explicit persisted trust approval. + /// - Returns: `true` only for Tailscale-tunnel, iroh peer, loopback, and + /// explicitly approved manual-host routes. + public static func routeAllowsStackAuth( + _ route: CmxAttachRoute, + manualHostTrusted: Bool = false + ) -> Bool { switch (route.kind, route.endpoint) { case (.debugLoopback, let .hostPort(host, _)): return isLoopbackHost(host) case (.tailscale, let .hostPort(host, _)): return isTailscaleHost(host) + case (.manualHost, .hostPort): + return manualHostTrusted case (.iroh, .peer): return true default: @@ -92,6 +85,17 @@ public struct MobileShellRouteAuthPolicy { } } + /// Whether a route is an explicit manual-host route that needs approval. + /// - Parameter route: The candidate attach route. + /// - Returns: `true` only for `.manualHost` host/port routes. + public static func routeRequiresManualHostTrust(_ route: CmxAttachRoute) -> Bool { + guard route.kind == .manualHost, + case .hostPort = route.endpoint else { + return false + } + return true + } + /// Whether a decoded pairing/attach ticket must be rejected because its /// routes dial the device itself. /// @@ -146,10 +150,10 @@ public struct MobileShellRouteAuthPolicy { /// - Parameter host: The manually typed host. /// - Returns: `true` when the host is valid but outside the loopback/Tailscale trust set. public static func manualHostNeedsTrustWarning(_ host: String) -> Bool { - guard let normalizedHost = normalizedManualNetworkHost(host) else { + guard normalizedManualNetworkHost(host) != nil else { return false } - return !isLoopbackHost(normalizedHost) && !isTailscaleHost(normalizedHost) + return manualRouteKind(for: host) == .manualHost } private static func normalizedManualNetworkHost(_ host: String) -> String? { diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift new file mode 100644 index 000000000000..94d72b4ead14 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -0,0 +1,50 @@ +import Foundation + +/// UserDefaults-backed manual-host trust store for production. +public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStoring { + private let defaults: UserDefaults + private let key: String + + /// Creates a durable manual-host trust store. + /// - Parameters: + /// - defaults: The backing defaults store. + /// - key: The defaults key that stores approved scopes. + public init( + defaults: UserDefaults = .standard, + key: String = "cmux.mobile.manualHostTrust.v1" + ) { + self.defaults = defaults + self.key = key + } + + /// Creates a durable manual-host trust store in a named defaults suite. + /// - Parameters: + /// - suiteName: The `UserDefaults` suite name. + /// - key: The defaults key that stores approved scopes. + public init( + suiteName: String, + key: String = "cmux.mobile.manualHostTrust.v1" + ) { + self.defaults = UserDefaults(suiteName: suiteName) ?? .standard + self.key = key + } + + /// Returns whether the given host/port/account scope is already trusted. + /// - Parameter scope: The scope to look up. + public func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + Set(defaults.stringArray(forKey: key) ?? []).contains(scope.storageKey) + } + + /// Persists trust for exactly the given host/port/account scope. + /// - Parameter scope: The scope to approve. + public func trust(_ scope: MobileManualHostTrustScope) async { + var trusted = Set(defaults.stringArray(forKey: key) ?? []) + trusted.insert(scope.storageKey) + defaults.set(trusted.sorted(), forKey: key) + } + + /// Removes every stored approval. + public func removeAll() async { + defaults.removeObject(forKey: key) + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index 7506ceaa8186..5b3bf935e6a7 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -43,7 +43,7 @@ import Testing #expect(!MobileShellRouteAuthPolicy.routeIsLoopback(irohPeer)) } - @Test func allowsStackAuthOnlyForEncryptedOrLoopbackRoutes() throws { + @Test func allowsStackAuthOnlyForEncryptedLoopbackOrApprovedManualHostRoutes() throws { let loopback = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: CmxMobileDefaults.defaultHostPort) let tailscaleIP = try hostPortRoute(kind: .tailscale, host: "100.71.210.41", port: CmxMobileDefaults.defaultHostPort) let lanIP = try hostPortRoute(kind: .tailscale, host: "192.168.1.77", port: CmxMobileDefaults.defaultHostPort) @@ -57,18 +57,26 @@ import Testing priority: 0 ) + let manualHostRoute = try hostPortRoute(kind: .manualHost, host: "192.168.1.77", port: CmxMobileDefaults.defaultHostPort) + #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "127.0.0.1") == .debugLoopback) - #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "127.attacker.example") == .tailscale) + #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "[::1]") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "100.71.210.41") == .tailscale) + #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "work-mac.tailnet.ts.net") == .tailscale) + #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "127.attacker.example") == .manualHost) - // Encrypted / loopback channels may carry the Stack bearer token. + // Encrypted / loopback channels and explicitly approved manual hosts may + // carry the Stack bearer token. #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(loopback)) #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(tailscaleMagicDNS)) #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(tailscaleIP)) #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(irohPeer)) + #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualHostRoute)) + #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualHostRoute, manualHostTrusted: true)) - // Plaintext-TCP routes must NOT carry the Stack bearer token: a `.tailscale` - // route to a private-LAN IP or a `.local`/Bonjour host is dialed over - // unencrypted TCP, so it is excluded from the Stack-auth-allowed set. + // Plaintext-TCP routes must NOT carry the Stack bearer token by default: + // a `.tailscale` route to a private-LAN IP or a `.local`/Bonjour host is + // dialed over unencrypted TCP, so it is excluded from the Stack-auth set. #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(lanIP)) #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(localDNS)) #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(pretendLoopback)) @@ -80,6 +88,37 @@ import Testing #expect(MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("devbox.local")) } + @Test func manualHostTrustScopeIsHostPortAndAccountScoped() async throws { + let store = InMemoryMobileManualHostTrustStore() + let approved = try #require(MobileManualHostTrustScope( + host: "Studio-Mac.local", + port: 58465, + stackUserID: "user-a" + )) + let sameHostDifferentCase = try #require(MobileManualHostTrustScope( + host: "studio-mac.local", + port: 58465, + stackUserID: "user-a" + )) + let differentPort = try #require(MobileManualHostTrustScope( + host: "studio-mac.local", + port: 58466, + stackUserID: "user-a" + )) + let differentAccount = try #require(MobileManualHostTrustScope( + host: "studio-mac.local", + port: 58465, + stackUserID: "user-b" + )) + + #expect(!await store.isTrusted(approved)) + await store.trust(approved) + + #expect(await store.isTrusted(sameHostDifferentCase)) + #expect(!await store.isTrusted(differentPort)) + #expect(!await store.isTrusted(differentAccount)) + } + @Test func physicalDeviceRejectsLoopbackTicketsInEveryGrammar() throws { // The v2 QR decoder rejects loopback itself; this policy is what stops // the LEGACY payload grammars from being a bypass on a physical phone, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 4adcaedf2553..ae075cefb0b4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -261,6 +261,7 @@ struct CMUXMobileRootView: View { connectionError: store.connectionError, connectionErrorGuidance: store.connectionErrorGuidance, versionWarning: store.pairingVersionWarning, + manualHostTrustWarning: store.manualHostTrustWarning, connectPairingCode: { await store.connectPairingInput() }, @@ -271,6 +272,13 @@ struct CMUXMobileRootView: View { dismissAddDeviceSheet() } }, + acceptManualHostTrustWarning: { + let result = await store.acceptManualHostTrustWarning() + clearAttachTicketAuthentication(after: result) + if result == .connected { + dismissAddDeviceSheet() + } + }, connectManualHost: { name, host, port in await store.connectManualHost(name: name, host: host, port: port) }, @@ -435,7 +443,7 @@ struct CMUXMobileRootView: View { private func dismissAddDeviceSheet() { isShowingAddDeviceSheet = false - if store.pairingVersionWarning != nil { + if store.pairingVersionWarning != nil || store.manualHostTrustWarning != nil { cancelPairing() } else { clearAttachTicketAuthenticationIfNeeded() diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift index 49cdad774262..5da469d8c2b4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift @@ -19,8 +19,10 @@ struct PairingView: View { /// when the headline is already the full instruction. let connectionErrorGuidance: String? let versionWarning: String? + let manualHostTrustWarning: MobileManualHostTrustWarning? let connectPairingCode: () async -> Void let acceptVersionWarning: () async -> Void + let acceptManualHostTrustWarning: () async -> Void let connectManualHost: (String, String, Int) async -> Void let cancelPairing: () -> Void let cancel: () -> Void @@ -173,6 +175,44 @@ struct PairingView: View { } } + if let manualHostTrustWarning { + Section { + VStack(alignment: .leading, spacing: 10) { + Label { + Text(L10n.string("mobile.pairing.manualHostTrustTitle", defaultValue: "Trust manual host?")) + } icon: { + Image(systemName: "exclamationmark.triangle.fill") + } + .font(.headline) + .foregroundStyle(.orange) + + Text(manualHostTrustWarning.endpoint) + .font(.subheadline) + .foregroundStyle(.primary) + .textSelection(.enabled) + .accessibilityIdentifier("MobileManualHostTrustEndpoint") + + Text(L10n.string( + "mobile.pairing.manualHostTrustBody", + defaultValue: "cmux mobile currently relies on Tailscale/WireGuard for transport encryption. With a subnet router, iPhone to router may be encrypted, but router to Mac is normal LAN traffic. Trust only this host and port if you control that network." + )) + .font(.footnote) + .foregroundStyle(.secondary) + .accessibilityIdentifier("MobileManualHostTrustWarning") + + Button(role: .destructive) { + startPairingTask { + await acceptManualHostTrustWarning() + } + } label: { + Text(L10n.string("mobile.pairing.manualHostTrustContinue", defaultValue: "Trust and Pair")) + } + .disabled(isPairing) + .accessibilityIdentifier("MobileManualHostTrustContinueButton") + } + } + } + if let errorText { Section { VStack(alignment: .leading, spacing: 8) { diff --git a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/CmxNetworkByteTransport.swift b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/CmxNetworkByteTransport.swift index ce78417452e6..9e547d8d9176 100644 --- a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/CmxNetworkByteTransport.swift +++ b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/CmxNetworkByteTransport.swift @@ -66,10 +66,10 @@ public struct CmxNetworkByteTransportFactory: CmxRouteAwareByteTransportFactory /// Creates a factory bound to the given supported route kinds. /// - Parameters: /// - supportedKinds: Route kinds this factory accepts. Defaults to - /// `tailscale` and `debugLoopback`. + /// `tailscale`, `manualHost`, and `debugLoopback`. /// - maximumReceiveLength: Per-receive byte cap for built transports. public init( - supportedKinds: [CmxAttachTransportKind] = [.tailscale, .debugLoopback], + supportedKinds: [CmxAttachTransportKind] = [.tailscale, .manualHost, .debugLoopback], maximumReceiveLength: Int = CmxNetworkByteTransport.defaultMaximumReceiveLength ) { self.supportedKinds = supportedKinds diff --git a/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/CmxNetworkByteTransportTests.swift b/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/CmxNetworkByteTransportTests.swift index b9804c003431..9be625832865 100644 --- a/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/CmxNetworkByteTransportTests.swift +++ b/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/CmxNetworkByteTransportTests.swift @@ -16,6 +16,18 @@ import Testing #expect(transport is CmxNetworkByteTransport) } +@Test func networkTransportFactoryBuildsManualHostTransportByDefault() throws { + let route = try CmxAttachRoute( + id: "manual_host", + kind: .manualHost, + endpoint: .hostPort(host: "studio-mac.local", port: 49831) + ) + + let transport = try CmxNetworkByteTransportFactory().makeTransport(for: route) + + #expect(transport is CmxNetworkByteTransport) +} + @Test func networkTransportFactoryRejectsNonNetworkRouteKind() throws { let route = try CmxAttachRoute( id: "iroh", diff --git a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/MobileCatalogSection.swift b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/MobileCatalogSection.swift index c5ecc170589f..4bc8c781d343 100644 --- a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/MobileCatalogSection.swift +++ b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/MobileCatalogSection.swift @@ -34,6 +34,16 @@ public struct MobileCatalogSection: SettingCatalogSection { userDefaultsKey: "mobile.iOSPairingHost.port" ) + /// Optional LAN IP address or DNS name advertised as an explicit manual + /// mobile pairing route. Empty keeps the default Tailscale-only route + /// advertisement. This exists for subnet-router topologies where the iPhone + /// can reach the Mac's LAN address but the Mac cannot run Tailscale. + public let iOSPairingManualHost = DefaultsKey( + id: "mobile.iOSPairingHost.manualHost", + defaultValue: "", + userDefaultsKey: "mobile.iOSPairingHost.manualHost" + ) + /// Optional override for the name the iOS app shows for this Mac during /// pairing. Empty means use the Mac's name from System Settings /// (`Host.current().localizedName`). Useful when pairing against several diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift index 7e196d440cc0..b8e9a4afcdcd 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift @@ -161,6 +161,7 @@ extension Array where Element == CuratedSettingEntry { // Mobile .init(section: .mobile, id: "pairDevice", title: "Pair a Device", synonyms: "pair pairing add device qr qr code scan iphone ipad ios mobile tailscale connect onboarding sign in"), .init(section: .mobile, id: "iOSPairingHost", title: "iOS Pairing", synonyms: "ios iphone ipad mobile pairing local network permission sync"), + .init(section: .mobile, id: "iOSPairingManualHost", title: String(localized: "settings.mobile.manualHost", defaultValue: "Manual Host"), synonyms: "mobile.iOSPairingHost.manualHost manual host lan ip dns subnet router tailscale route iphone ipad"), .init(section: .mobile, id: "iOSPairingPort", title: String(localized: "settings.mobile.port", defaultValue: "Pairing Port"), synonyms: "mobile.iOSPairingHost.port ios iphone mobile pairing port tcp listener firewall conflict"), .init(section: .mobile, id: "iOSPairingDisplayName", title: String(localized: "settings.mobile.displayName", defaultValue: "Display Name"), synonyms: "mobile.iOSPairingHost.displayName ios iphone mobile pairing display name mac hostname device label"), diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift index 744dce3c079f..c20e8f5cd834 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift @@ -1,3 +1,4 @@ +import CMUXMobileCore import CmuxFoundation import CmuxSettings import SwiftUI @@ -10,6 +11,7 @@ import SwiftUI public struct MobileSection: View { @State private var iOSPairingHost: DefaultsValueModel @State private var port: DefaultsValueModel + @State private var manualHost: DefaultsValueModel @State private var displayName: DefaultsValueModel @State private var status: MobilePairingStatusModel @@ -44,6 +46,7 @@ public struct MobileSection: View { ) { _iOSPairingHost = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.mobile.iOSPairingHost)) _port = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.mobile.iOSPairingPort)) + _manualHost = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.mobile.iOSPairingManualHost)) _displayName = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.mobile.iOSPairingDisplayName)) _status = State(initialValue: MobilePairingStatusModel(hostActions: hostActions)) self.hostActions = hostActions @@ -65,6 +68,14 @@ public struct MobileSection: View { (1...65535).contains(draftPort) } + private var trimmedManualHost: String { + manualHost.current.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var isManualHostValid: Bool { + trimmedManualHost.isEmpty || CmxManualHost(trimmedManualHost) != nil + } + /// The Mobile settings section content. public var body: some View { Group { @@ -77,6 +88,9 @@ public struct MobileSection: View { portRow boundPortStatusRow SettingsCardDivider() + manualHostRow + manualHostStatusRow + SettingsCardDivider() displayNameRow if iOSPairingHost.current { SettingsCardDivider() @@ -96,6 +110,7 @@ public struct MobileSection: View { iOSPairingHost, port, displayName, + manualHost, status, ] models.forEach { $0.startObserving() } @@ -254,6 +269,48 @@ public struct MobileSection: View { } } + @ViewBuilder + private var manualHostRow: some View { + SettingsCardRow( + configurationReview: .settingsOnly, + searchAnchorID: "setting:mobile:iOSPairingManualHost", + String(localized: "settings.mobile.manualHost", defaultValue: "Manual Host"), + subtitle: String( + localized: "settings.mobile.manualHost.subtitle", + defaultValue: "Optional LAN IP or DNS host to advertise when this Mac cannot run Tailscale." + ), + controlWidth: Self.columnWidth + ) { + TextField( + String(localized: "settings.mobile.manualHost.placeholder", defaultValue: "192.168.1.23 or mac.local"), + text: Binding(get: { manualHost.current }, set: { manualHost.set($0) }) + ) + .textFieldStyle(.roundedBorder) + .accessibilityIdentifier("SettingsMobilePairingManualHostField") + } + } + + @ViewBuilder + private var manualHostStatusRow: some View { + if !isManualHostValid { + statusCaption { + Label( + String( + localized: "settings.mobile.manualHost.invalid", + defaultValue: "Enter a host or IP address, without spaces or URL paths." + ), + systemImage: "exclamationmark.triangle.fill" + ) + .foregroundStyle(.orange) + } + } else if !trimmedManualHost.isEmpty { + SettingsCardNote(String( + localized: "settings.mobile.manualHost.warning", + defaultValue: "Manual hosts are explicit trust routes. The iOS app will ask before sending credentials. With a subnet router, iPhone to router may be encrypted, but router to Mac is normal LAN traffic." + )) + } + } + @ViewBuilder private var displayNameRow: some View { // Show this Mac's system name as the placeholder so the user sees the diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift index 53cb0b0d2109..38535e24f10b 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift @@ -143,6 +143,7 @@ struct SettingsRowAnchorResolutionTests { "setting:account:account", "setting:mobile:pairDevice", "setting:mobile:iOSPairingHost", + "setting:mobile:iOSPairingManualHost", "setting:mobile:iOSPairingPort", "setting:mobile:iOSPairingDisplayName", "setting:betaFeatures:feed", diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 73bb4104888b..9e716eece360 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -117781,6 +117781,23 @@ } } }, + "mobile.pairing.needsRoute.body": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This Mac has no Tailscale address or Manual Host, so your iPhone can't reach it. Install Tailscale on both devices, or configure a Manual Host in Settings if your iPhone can reach this Mac through a subnet router." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この Mac には Tailscale アドレスまたは手動ホストがないため、iPhone から接続できません。両方のデバイスに Tailscale をインストールするか、iPhone がサブネットルーター経由でこの Mac に到達できる場合は、設定で手動ホストを構成してください。" + } + } + } + }, "mobile.pairing.preparing": { "extractionState": "manual", "localizations": { @@ -117883,6 +117900,74 @@ } } }, + "mobile.pairing.req.manualHost.reachable": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manual host configured. Your iPhone will ask before trusting this route." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "手動ホストが設定されています。このルートを信頼する前に iPhone で確認が表示されます。" + } + } + } + }, + "mobile.pairing.req.route.hint": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Use Tailscale, or configure a Manual Host for subnet-router setups." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Tailscale を使用するか、サブネットルーター構成用に手動ホストを設定してください。" + } + } + } + }, + "mobile.pairing.req.route.missing": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No Tailscale address or manual host configured. Install Tailscale, or set a Manual Host in Settings for subnet-router setups." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Tailscale アドレスまたは手動ホストが設定されていません。Tailscale をインストールするか、サブネットルーター構成用に設定で手動ホストを指定してください。" + } + } + } + }, + "mobile.pairing.req.route.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Reachable route" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "到達可能なルート" + } + } + } + }, "mobile.pairing.req.tailscale.get": { "extractionState": "manual", "localizations": { @@ -152088,6 +152173,91 @@ } } }, + "settings.mobile.manualHost": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manual Host" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "手動ホスト" + } + } + } + }, + "settings.mobile.manualHost.invalid": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Enter a host or IP address, without spaces or URL paths." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "スペースや URL パスを含めず、ホストまたは IP アドレスを入力してください。" + } + } + } + }, + "settings.mobile.manualHost.placeholder": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 or mac.local" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 または mac.local" + } + } + } + }, + "settings.mobile.manualHost.subtitle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Optional LAN IP or DNS host to advertise when this Mac cannot run Tailscale." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この Mac で Tailscale を実行できない場合に通知する任意の LAN IP または DNS ホスト。" + } + } + } + }, + "settings.mobile.manualHost.warning": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manual hosts are explicit trust routes. The iOS app will ask before sending credentials. With a subnet router, iPhone to router may be encrypted, but router to Mac is normal LAN traffic." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "手動ホストは明示的に信頼するルートです。認証情報を送信する前に iOS アプリで確認が表示されます。サブネットルーターを使う場合、iPhone からルーターまでは暗号化されることがありますが、ルーターから Mac までは通常の LAN 通信です。" + } + } + } + }, "settings.mobile.pairDevice": { "extractionState": "manual", "localizations": { @@ -152343,6 +152513,23 @@ } } }, + "settings.mobile.route.manualHost": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manual Host" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "手動ホスト" + } + } + } + }, "settings.mobile.route.tailscale": { "extractionState": "manual", "localizations": { @@ -164039,6 +164226,23 @@ } } }, + "settings.search.alias.setting.mobile.iOSPairingManualHost": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "manual host lan ip dns subnet router tailscale route mobile pairing iphone ipad" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "手動ホスト lan ip dns サブネットルーター tailscale ルート モバイル ペアリング iphone ipad" + } + } + } + }, "settings.search.alias.setting.mobile.iOSPairingPort": { "extractionState": "manual", "localizations": { diff --git a/Sources/HostSettingsActions.swift b/Sources/HostSettingsActions.swift index 4d86d6c1de0e..6017ac4f8013 100644 --- a/Sources/HostSettingsActions.swift +++ b/Sources/HostSettingsActions.swift @@ -319,6 +319,8 @@ final class HostSettingsActions: SettingsHostActions { switch kind { case .tailscale: return String(localized: "settings.mobile.route.tailscale", defaultValue: "Tailscale") + case .manualHost: + return String(localized: "settings.mobile.route.manualHost", defaultValue: "Manual Host") case .debugLoopback: return String(localized: "settings.mobile.route.loopback", defaultValue: "Loopback") case .iroh: diff --git a/Sources/Mobile/MobileAttachTicketStore.swift b/Sources/Mobile/MobileAttachTicketStore.swift index 7bf88cd12ed0..4dbf9f1619f8 100644 --- a/Sources/Mobile/MobileAttachTicketStore.swift +++ b/Sources/Mobile/MobileAttachTicketStore.swift @@ -130,7 +130,7 @@ final class MobileAttachTicketStore { private func attachURL(for ticket: CmxAttachTicket) throws -> URL { // Preferred form: the minimal v2 pairing-code grammar — bare Tailscale - // `host:port` routes in the URL query, nothing else. Everything the + // and manual-host `host:port` routes in the URL query. Everything the // older grammars carried has a better channel: the auth token never // authorized anything (the owner's Stack access token is the host's // sole gate, `MobileHostService.authorizationError(for:)`), the diff --git a/Sources/Mobile/MobileHostService.swift b/Sources/Mobile/MobileHostService.swift index 9b40e93fa8be..b360a4c9da58 100644 --- a/Sources/Mobile/MobileHostService.swift +++ b/Sources/Mobile/MobileHostService.swift @@ -155,6 +155,10 @@ private enum MobileHostPublicStatusCache { static func update(routes nextRoutes: [CmxAttachRoute]) { lock.lock() + guard routes != nextRoutes else { + lock.unlock() + return + } routes = nextRoutes lock.unlock() NotificationCenter.default.post(name: .mobileHostStatusDidChange, object: nil) @@ -524,6 +528,20 @@ final class MobileHostService { return (1...65535).contains(raw) ? raw : nil } + /// User-default key for the explicit manual host advertised to iOS when + /// Tailscale is unavailable on this Mac. + nonisolated static let manualHostDefaultsKey = SettingCatalog().mobile.iOSPairingManualHost.userDefaultsKey + + /// The user-configured LAN/DNS host to advertise as an explicit manual route, + /// or `nil` when unset or invalid. + nonisolated static func configuredManualHost(defaults: UserDefaults = .standard) -> String? { + guard let raw = defaults.object(forKey: manualHostDefaultsKey) as? String, + let host = CmxManualHost(raw)?.rawValue else { + return nil + } + return host + } + /// Pure reconciliation between the desired settings and the live listener /// state. Factored out so the restart-on-port-change decision is unit /// testable without binding a real `NWListener`. @@ -713,7 +731,7 @@ final class MobileHostService { self?.updatePublicStatusRoutes(port: port, generation: generation, tailscaleHosts: hosts) } }) - MobileHostPublicStatusCache.update(routes: routeResolver.routes(port: port).routes) + MobileHostPublicStatusCache.update(routes: currentRoutes(port: port)) startNetworkPathMonitorIfNeeded() drainReadinessWaiters() } @@ -750,7 +768,7 @@ final class MobileHostService { listenerPort = port appliedPreferredPort = port lastErrorDescription = nil - MobileHostPublicStatusCache.update(routes: routeResolver.routes(port: port).routes) + MobileHostPublicStatusCache.update(routes: currentRoutes(port: port)) mobileHostLog.info("mobile host listener disabled; publishing XCTest routes without binding") } #endif @@ -835,10 +853,29 @@ final class MobileHostService { } func statusSnapshot() -> MobileHostServiceStatus { - let routes = listenerPort.map { routeResolver.routes(port: $0).routes } ?? [] + let routes = listenerPort.map { currentRoutes(port: $0) } ?? [] return makeStatus(routes: routes) } + private func currentRoutes(port: Int) -> [CmxAttachRoute] { + routeResolver.routes(port: port, manualHost: Self.configuredManualHost()).routes + } + + private func currentRoutes(port: Int, tailscaleHosts: [String]) -> [CmxAttachRoute] { + routeResolver.routes( + port: port, + tailscaleHosts: tailscaleHosts, + manualHost: Self.configuredManualHost() + ).routes + } + + private func refreshAdvertisedRoutesIfRunning() { + guard let listenerPort else { + return + } + MobileHostPublicStatusCache.update(routes: currentRoutes(port: listenerPort)) + } + /// Emits the current ``MobileHostServiceStatus`` immediately, then a fresh /// snapshot every time the listener or active-connection set changes (driven by /// `.mobileHostStatusDidChange`). The in-app pairing window consumes this to flip @@ -960,7 +997,7 @@ final class MobileHostService { appliedPort: appliedPreferredPort ) { case .noop: - break + refreshAdvertisedRoutesIfRunning() case .start: start() case .stop: @@ -1063,7 +1100,7 @@ final class MobileHostService { ) async throws -> [String: Any] { let routes: [CmxAttachRoute] if let listenerPort { - routes = routeResolver.routes(port: listenerPort).routes + routes = currentRoutes(port: listenerPort) } else { routes = [] } @@ -1535,7 +1572,7 @@ final class MobileHostService { ) } }) - MobileHostPublicStatusCache.update(routes: routeResolver.routes(port: listenerPort).routes) + MobileHostPublicStatusCache.update(routes: currentRoutes(port: listenerPort)) } else { MobileHostPublicStatusCache.update(routes: []) } @@ -1603,7 +1640,7 @@ final class MobileHostService { return } MobileHostPublicStatusCache.update( - routes: routeResolver.routes(port: port, tailscaleHosts: tailscaleHosts).routes + routes: currentRoutes(port: port, tailscaleHosts: tailscaleHosts) ) } @@ -1650,7 +1687,7 @@ final class MobileHostService { self?.updatePublicStatusRoutes(port: port, generation: generation, tailscaleHosts: hosts) } }) - MobileHostPublicStatusCache.update(routes: routeResolver.routes(port: port).routes) + MobileHostPublicStatusCache.update(routes: currentRoutes(port: port)) } } diff --git a/Sources/Mobile/MobileRouteResolver.swift b/Sources/Mobile/MobileRouteResolver.swift index fe0f8bcc2c08..3c9e39a76990 100644 --- a/Sources/Mobile/MobileRouteResolver.swift +++ b/Sources/Mobile/MobileRouteResolver.swift @@ -26,6 +26,7 @@ final class MobileRouteResolver: @unchecked Sendable { func routes( port: Int, + manualHost: String? = nil, now: Date = Date(), immediateHosts: () -> [String] = { MobileRouteResolver.tailscaleRouteHosts(resolveDNS: false) } ) -> MobileHostRouteSnapshot { @@ -33,17 +34,19 @@ final class MobileRouteResolver: @unchecked Sendable { let cachedHosts = resolvedTailscaleRouteHostsFromCache(now: now) ?? [] return routes( port: port, - tailscaleHosts: Self.deduplicatedHosts(cachedHosts + immediateHosts()) + tailscaleHosts: Self.deduplicatedHosts(cachedHosts + immediateHosts()), + manualHost: manualHost ) } func routesResolvingTailscaleDNS( port: Int, + manualHost: String? = nil, resolveHosts: @escaping @Sendable () -> [String] = { MobileRouteResolver.tailscaleRouteHosts(resolveDNS: true) }, now: Date = Date() ) async -> MobileHostRouteSnapshot { let hosts = await resolvedTailscaleRouteHosts(resolveHosts: resolveHosts, now: now) - return routes(port: port, tailscaleHosts: hosts) + return routes(port: port, tailscaleHosts: hosts, manualHost: manualHost) } /// Drop the resolved-host cache and orphan any in-flight resolution. @@ -64,7 +67,11 @@ final class MobileRouteResolver: @unchecked Sendable { cacheLock.unlock() } - func routes(port: Int, tailscaleHosts: [String]) -> MobileHostRouteSnapshot { + func routes( + port: Int, + tailscaleHosts: [String], + manualHost: String? = nil + ) -> MobileHostRouteSnapshot { var resolved: [CmxAttachRoute] = [] if Self.includesDebugLoopbackRoute { @@ -92,6 +99,18 @@ final class MobileRouteResolver: @unchecked Sendable { } } + if let manualHost = manualHost.flatMap({ CmxManualHost($0)?.rawValue }) { + let manualPriority = 10 + (tailscaleHosts.count * 10) + if let manualRoute = try? CmxAttachRoute( + id: CmxAttachTransportKind.manualHost.rawValue, + kind: .manualHost, + endpoint: .hostPort(host: manualHost, port: port), + priority: manualPriority + ) { + resolved.append(manualRoute) + } + } + return MobileHostRouteSnapshot(routes: resolved) } diff --git a/Sources/Mobile/Pairing/MobilePairingModel.swift b/Sources/Mobile/Pairing/MobilePairingModel.swift index b06b9d1156e9..fbd9e6ed0947 100644 --- a/Sources/Mobile/Pairing/MobilePairingModel.swift +++ b/Sources/Mobile/Pairing/MobilePairingModel.swift @@ -30,7 +30,8 @@ final class MobilePairingModel { /// instead of the QR + spinner. case connected(Ready) /// The listener is up but there is no route a phone can reach (no - /// Tailscale address on this Mac), so no ticket can be minted yet. + /// Tailscale address or manual host on this Mac), so no ticket can be + /// minted yet. case needsTailscale /// The listener could not be started or no ticket could be minted. case failed(String) @@ -42,15 +43,21 @@ final class MobilePairingModel { let attachURL: String /// The Mac's display name, shown above the code. let macName: String + /// All phone-dialable `host:port` routes carried by the pairing code. + let routeLines: [String] /// Reachable Tailscale `host:port` routes. Empty when Tailscale is not - /// detected, in which case a real iPhone cannot reach this Mac. + /// detected. let tailscaleLines: [String] /// The best route for manual phone entry, behind the "Copy IP" and /// "Copy Port" buttons. `nil` when no phone-dialable route exists. let manualEntry: CmxManualPairingEntry? - /// Whether at least one Tailscale route resolved. + /// Whether at least one phone-reachable Tailscale route resolved. var reachableViaTailscale: Bool { !tailscaleLines.isEmpty } + /// Whether the pairing code carries an explicit non-Tailscale manual route. + var hasManualHostRoute: Bool { + routeLines.contains { line in !tailscaleLines.contains(line) } + } } /// The current render state, observed by ``MobilePairingView``. @@ -124,11 +131,10 @@ final class MobilePairingModel { ) return } - // No route a phone can reach: a real iPhone needs a Tailscale address - // on this Mac. A DEBUG build's dev loopback route does not count — a - // QR pointing at 127.0.0.1 would make the phone dial itself, so the - // window shows the set-up-Tailscale guidance instead of a weak code. - // (Simulator/dev pairing uses the injected attach URL path, not the QR.) + // No route a phone can reach: a DEBUG build's dev loopback route does + // not count — a QR pointing at 127.0.0.1 would make the phone dial + // itself. Simulator/dev pairing uses the injected attach URL path, not + // the QR. guard status.routes.contains(where: Self.isPhoneReachableRoute) else { state = .needsTailscale return @@ -149,10 +155,10 @@ final class MobilePairingModel { ) return } - // Only the minimal v2 grammar (Tailscale routes only, no loopback, - // no token) may ever be displayed as a scannable code. If the mint - // raced a Tailscale route loss and fell back to the v1 payload, - // show the Tailscale guidance rather than a weak QR. + // Only the minimal v2 grammar (Tailscale/manual-host routes only, + // no loopback, no token) may ever be displayed as a scannable code. + // If the mint raced a route loss and fell back to the v1 payload, + // show route guidance rather than a weak QR. guard CmxPairingQRCode().isPairingCodeURLString(attachURL) else { state = .needsTailscale return @@ -161,6 +167,7 @@ final class MobilePairingModel { Ready( attachURL: attachURL, macName: Self.macDisplayName, + routeLines: Self.phoneReachableLines(status.routes), tailscaleLines: Self.tailscaleLines(status.routes), manualEntry: CmxManualPairingEntry.best(in: status.routes) ) @@ -257,20 +264,38 @@ final class MobilePairingModel { } /// Whether `route` is one a physical iPhone can actually dial: a - /// Tailscale route that does not point back at this Mac. The dev loopback - /// route a DEBUG build always carries must not count as reachability, or - /// the pairing window would happily display a QR no phone can use. + /// Tailscale or explicit manual-host route that does not point back at this + /// Mac. The dev loopback route a DEBUG build always carries must not count + /// as reachability, or the pairing window would happily display a QR no + /// phone can use. private static func isPhoneReachableRoute(_ route: CmxAttachRoute) -> Bool { - route.kind == .tailscale && !CmxLoopbackHost().matches(route) + (route.kind == .tailscale || route.kind == .manualHost) && !CmxLoopbackHost().matches(route) + } + + private static func phoneReachableLines(_ routes: [CmxAttachRoute]) -> [String] { + uniqueLines(routes.compactMap { route in + guard isPhoneReachableRoute(route), + case let .hostPort(host, port) = route.endpoint else { + return nil + } + return "\(host):\(port)" + }) } private static func tailscaleLines(_ routes: [CmxAttachRoute]) -> [String] { - routes.compactMap { route in + uniqueLines(routes.compactMap { route in guard route.kind == .tailscale, case let .hostPort(host, port) = route.endpoint else { return nil } return "\(host):\(port)" + }) + } + + private static func uniqueLines(_ lines: [String]) -> [String] { + var seen: Set = [] + return lines.filter { line in + seen.insert(line).inserted } } } diff --git a/Sources/Mobile/Pairing/MobilePairingView.swift b/Sources/Mobile/Pairing/MobilePairingView.swift index f1c54fbf84b4..63a624ec4eda 100644 --- a/Sources/Mobile/Pairing/MobilePairingView.swift +++ b/Sources/Mobile/Pairing/MobilePairingView.swift @@ -67,7 +67,7 @@ struct MobilePairingView: View { private var requirements: some View { VStack(alignment: .leading, spacing: 12) { signInRow - tailscaleRow + routeRow } } @@ -81,13 +81,13 @@ struct MobilePairingView: View { } } - private var tailscaleRow: some View { - let reachable = tailscaleReachable + private var routeRow: some View { + let state = routeReachability return requirementRow( - title: String(localized: "mobile.pairing.req.tailscale.title", defaultValue: "Tailscale"), - subtitle: tailscaleSubtitle(reachable: reachable) + title: String(localized: "mobile.pairing.req.route.title", defaultValue: "Reachable route"), + subtitle: routeSubtitle(state) ) { - if reachable != true { + if state == .missing || state == .unknown { Link( String(localized: "mobile.pairing.req.tailscale.get", defaultValue: "Get Tailscale"), destination: Self.tailscaleDownloadURL @@ -97,24 +97,45 @@ struct MobilePairingView: View { } } - /// `true` reachable, `false` not detected, `nil` not yet known. - private var tailscaleReachable: Bool? { + private enum RouteReachability: Equatable { + case tailscale + case manualHost + case missing + case unknown + } + + private var routeReachability: RouteReachability { switch model.state { - case let .ready(ready): return ready.reachableViaTailscale - case let .connected(ready): return ready.reachableViaTailscale - case .needsTailscale: return false - default: return nil + case let .ready(ready), let .connected(ready): + if ready.reachableViaTailscale { return .tailscale } + if ready.hasManualHostRoute { return .manualHost } + return .missing + case .needsTailscale: + return .missing + default: + return .unknown } } - private func tailscaleSubtitle(reachable: Bool?) -> String { - switch reachable { - case .some(true): + private func routeSubtitle(_ state: RouteReachability) -> String { + switch state { + case .tailscale: return String(localized: "mobile.pairing.req.tailscale.reachable", defaultValue: "Reachable over Tailscale.") - case .some(false): - return String(localized: "mobile.pairing.req.tailscale.missing", defaultValue: "Not detected. Install Tailscale on this Mac and your iPhone, signed in to the same account.") - case .none: - return String(localized: "mobile.pairing.req.tailscale.hint", defaultValue: "Your Mac and iPhone both need Tailscale to connect over the internet.") + case .manualHost: + return String( + localized: "mobile.pairing.req.manualHost.reachable", + defaultValue: "Manual host configured. Your iPhone will ask before trusting this route." + ) + case .missing: + return String( + localized: "mobile.pairing.req.route.missing", + defaultValue: "No Tailscale address or manual host configured. Install Tailscale, or set a Manual Host in Settings for subnet-router setups." + ) + case .unknown: + return String( + localized: "mobile.pairing.req.route.hint", + defaultValue: "Use Tailscale, or configure a Manual Host for subnet-router setups." + ) } } @@ -167,7 +188,10 @@ struct MobilePairingView: View { Image(systemName: "network.slash") .cmuxFont(size: 28) .foregroundStyle(.orange) - Text(String(localized: "mobile.pairing.needsTailscale.body", defaultValue: "This Mac has no Tailscale address, so your iPhone can't reach it. Install Tailscale on this Mac and your iPhone (same account), then refresh.")) + Text(String( + localized: "mobile.pairing.needsRoute.body", + defaultValue: "This Mac has no Tailscale address or Manual Host, so your iPhone can't reach it. Install Tailscale on both devices, or configure a Manual Host in Settings if your iPhone can reach this Mac through a subnet router." + )) .multilineTextAlignment(.center) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) @@ -277,7 +301,7 @@ struct MobilePairingView: View { private func readyContent(_ ready: MobilePairingModel.Ready) -> some View { // Manual entry sits above the QR so Copy IP / Copy Port are reachable // without scrolling (they used to sit below the steps, below the fold). - if ready.reachableViaTailscale { + if ready.manualEntry != nil { manualFallback(ready) } @@ -373,7 +397,7 @@ struct MobilePairingView: View { Text(String(localized: "mobile.pairing.manual.title", defaultValue: "Can't scan? Add this Mac manually:")) .cmuxFont(.caption, weight: .semibold) .foregroundStyle(.secondary) - ForEach(ready.tailscaleLines, id: \.self) { line in + ForEach(ready.routeLines, id: \.self) { line in Text(line) .cmuxFont(.caption, design: .monospaced) .textSelection(.enabled) diff --git a/Sources/SettingsSearchAliases.swift b/Sources/SettingsSearchAliases.swift index aa50e12eda4c..3d4c8d3eb62d 100644 --- a/Sources/SettingsSearchAliases.swift +++ b/Sources/SettingsSearchAliases.swift @@ -126,6 +126,7 @@ enum SettingsSearchAliasIndex { "betaFeatures:feed": localized("settings.search.alias.setting.betaFeatures.feed", defaultValue: "feed right sidebar agent decisions permissions questions approval beta unstable"), "betaFeatures:dock": localized("settings.search.alias.setting.betaFeatures.dock", defaultValue: "dock right sidebar terminal controls tui beta unstable"), "mobile:iOSPairingHost": localized("settings.search.alias.setting.mobile.iOSPairingHost", defaultValue: "ios iphone ipad mobile pairing local network permission sync"), + "mobile:iOSPairingManualHost": localized("settings.search.alias.setting.mobile.iOSPairingManualHost", defaultValue: "manual host lan ip dns subnet router tailscale route mobile pairing iphone ipad"), "mobile:iOSPairingPort": localized("settings.search.alias.setting.mobile.iOSPairingPort", defaultValue: "mobile ios iphone pairing port tcp listener firewall conflict bind"), "mobile:iOSPairingDisplayName": localized("settings.search.alias.setting.mobile.iOSPairingDisplayName", defaultValue: "mobile ios iphone pairing display name mac hostname device label"), "automation:socket-mode": localized("settings.search.alias.setting.automation.socket-mode", defaultValue: "automation.socketControlMode api socket unix domain control server auth allow password disabled"), diff --git a/cmuxTests/MobileHostAuthorizationTests.swift b/cmuxTests/MobileHostAuthorizationTests.swift index b187e8021817..055860c66a88 100644 --- a/cmuxTests/MobileHostAuthorizationTests.swift +++ b/cmuxTests/MobileHostAuthorizationTests.swift @@ -209,6 +209,25 @@ struct MobileHostAuthorizationTests { } #expect(snapshot.routes.filter { $0.kind == .debugLoopback }.count == 1) } + @Test func testMobileRouteResolverUsesManualHostWhenTailscaleIsUnavailable() throws { + let resolver = MobileRouteResolver() + + let snapshot = resolver.routes( + port: 61234, + tailscaleHosts: [], + manualHost: " studio-mac.corp.example " + ) + + let manualRoutes = snapshot.routes.filter { $0.kind == .manualHost } + #expect(manualRoutes.count == 1) + #expect(snapshot.routes.filter { $0.kind == .tailscale }.isEmpty) + if case let .hostPort(host, port) = manualRoutes.first?.endpoint { + #expect(host == "studio-mac.corp.example") + #expect(port == 61234) + } else { + #expect(Bool(false), "Expected manual host route to use a host/port endpoint") + } + } @Test func testMobileRouteResolverAwaitsMagicDNSForPublicStatusRoutes() async throws { let resolver = MobileRouteResolver() diff --git a/cmuxTests/MobilePairingConnectionTransitionTests.swift b/cmuxTests/MobilePairingConnectionTransitionTests.swift index 7c36e7b3f28c..3fcf15f98103 100644 --- a/cmuxTests/MobilePairingConnectionTransitionTests.swift +++ b/cmuxTests/MobilePairingConnectionTransitionTests.swift @@ -15,6 +15,7 @@ struct MobilePairingConnectionTransitionTests { MobilePairingModel.Ready( attachURL: "cmux-ios://attach?ticket=abc", macName: "Test Mac", + routeLines: ["100.64.0.1:7777"], tailscaleLines: ["100.64.0.1:7777"], manualEntry: CmxManualPairingEntry(host: "100.64.0.1", port: 7777) ) diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index ef80c1446033..8a8d8b7a53be 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -3758,6 +3758,57 @@ } } }, + "mobile.pairing.manualHostTrustBody": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "cmux mobile currently relies on Tailscale/WireGuard for transport encryption. With a subnet router, iPhone to router may be encrypted, but router to Mac is normal LAN traffic. Trust only this host and port if you control that network." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux mobile は現在、転送の暗号化を Tailscale/WireGuard に依存しています。サブネットルーターを使う場合、iPhone からルーターまでは暗号化されることがありますが、ルーターから Mac までは通常の LAN 通信です。そのネットワークを管理している場合のみ、このホストとポートを信頼してください。" + } + } + } + }, + "mobile.pairing.manualHostTrustContinue": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Trust and Pair" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "信頼してペアリング" + } + } + } + }, + "mobile.pairing.manualHostTrustTitle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Trust manual host?" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "手動ホストを信頼しますか?" + } + } + } + }, "mobile.pairing.versionWarningTitle": { "extractionState": "manual", "localizations": { diff --git a/ios/cmux/cmuxApp.swift b/ios/cmux/cmuxApp.swift index 574f5c0d15d5..eee3fa6c36a4 100644 --- a/ios/cmux/cmuxApp.swift +++ b/ios/cmux/cmuxApp.swift @@ -16,9 +16,9 @@ struct cmuxApp: App { // attach to an in-runner mock host; release device builds keep only // real transports. #if targetEnvironment(simulator) || DEBUG - let supportedKinds: [CmxAttachTransportKind] = [.debugLoopback, .tailscale] + let supportedKinds: [CmxAttachTransportKind] = [.debugLoopback, .tailscale, .manualHost] #else - let supportedKinds: [CmxAttachTransportKind] = [.tailscale] + let supportedKinds: [CmxAttachTransportKind] = [.tailscale, .manualHost] #endif let networkFactory = CmxNetworkByteTransportFactory(supportedKinds: supportedKinds) let registrations = supportedKinds.map { kind in diff --git a/ios/cmuxPackage/Sources/cmuxFeature/CMUXMobileRuntime.swift b/ios/cmuxPackage/Sources/cmuxFeature/CMUXMobileRuntime.swift index 55709a278312..cfec900dfb2a 100644 --- a/ios/cmuxPackage/Sources/cmuxFeature/CMUXMobileRuntime.swift +++ b/ios/cmuxPackage/Sources/cmuxFeature/CMUXMobileRuntime.swift @@ -127,7 +127,7 @@ public struct CMUXMobileRuntime: Sendable, MobileSyncRuntime { } public init( - supportedRouteKinds: [CmxAttachTransportKind] = [.tailscale, .debugLoopback], + supportedRouteKinds: [CmxAttachTransportKind] = [.tailscale, .manualHost, .debugLoopback], transportFactory: any CmxByteTransportFactory, stackAccessTokenProvider: (@Sendable () async throws -> String)? = nil, stackAccessTokenForStatusProvider: (@Sendable () async -> String?)? = nil, diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index ea680fc764e0..f78420a47436 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -665,17 +665,23 @@ final class TerminalOutputCollector { } @MainActor -@Test func manualHostPairingRejectsPrivateLANIPWithoutSendingStackToken() async throws { - // Plain private-LAN routes are dialed over unencrypted TCP, so - // routeAllowsStackAuth excludes them: pairing must fail before any RPC - // (and the Stack bearer token) leaves the device. - let responses = ScriptedTransportResponses([]) +@Test func manualHostPairingBlocksPrivateLANIPUntilApproved() async throws { + let attachRoute = try hostPortRoute( + kind: .manualHost, + host: "192.168.1.77", + port: 15432 + ) + let responses = ScriptedTransportResponses([ + try rpcAttachTicketFrame(route: attachRoute, workspaceID: "trusted-lan-workspace"), + try rpcWorkspaceListFrame(workspaceID: "trusted-lan-workspace", title: "Trusted LAN Workspace"), + ]) let runtime = testRuntime( - supportedRouteKinds: [.tailscale], + supportedRouteKinds: [.manualHost], transportFactory: ScriptedTransportFactory(responses: responses), stackAccessToken: "stack-token-for-lan" ) - let store = CMUXMobileShellStore.preview(runtime: runtime) + let trustStore = InMemoryMobileManualHostTrustStore() + let store = CMUXMobileShellStore.preview(runtime: runtime, manualHostTrustStore: trustStore) store.signIn() await store.connectManualHost(name: "Studio LAN", host: " 192.168.1.77 ", port: 15432) @@ -684,37 +690,70 @@ final class TerminalOutputCollector { #expect(store.connectionState == .disconnected) #expect(store.activeTicket == nil) #expect(store.activeRoute == nil) - #expect(store.connectionError == "This pairing route is not allowed. Enter a host and port, or pair with a QR/link from that computer.") + #expect(store.connectionError == nil) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:15432") #expect(try await responses.sentRequests().isEmpty) + + let result = await store.acceptManualHostTrustWarning() + + #expect(result == .connected) + #expect(store.phase == .workspaces) + #expect(store.connectionState == .connected) + #expect(store.manualHostTrustWarning == nil) + let route = try #require(store.activeRoute) + #expect(route.kind == .manualHost) + let requests = try await responses.sentRequests() + #expect(requests.map(\.method) == ["mobile.attach_ticket.create", "workspace.list"]) + #expect(requests.allSatisfy { $0.stackAccessToken == "stack-token-for-lan" }) } @MainActor -@Test func manualHostPairingRejectsLocalDNSNameWithoutSendingStackToken() async throws { - // `.local`/Bonjour hosts are dialed over unencrypted TCP, so - // routeAllowsStackAuth excludes them: pairing must fail before any RPC - // (and the Stack bearer token) leaves the device. - let responses = ScriptedTransportResponses([]) +@Test func manualHostTrustDoesNotCoverDifferentHost() async throws { + let approvedRoute = try hostPortRoute( + kind: .manualHost, + host: "studio-mac.local", + port: 61234 + ) + let approvedResponses = ScriptedTransportResponses([ + try rpcAttachTicketFrame(route: approvedRoute, workspaceID: "approved-workspace"), + try rpcWorkspaceListFrame(workspaceID: "approved-workspace", title: "Approved Workspace"), + ]) + let trustStore = InMemoryMobileManualHostTrustStore() + let approvedRuntime = testRuntime( + supportedRouteKinds: [.manualHost], + transportFactory: ScriptedTransportFactory(responses: approvedResponses), + stackAccessToken: "stack-token-for-local-dns" + ) + let approvedStore = CMUXMobileShellStore.preview(runtime: approvedRuntime, manualHostTrustStore: trustStore) + + approvedStore.signIn() + await approvedStore.connectManualHost(name: "", host: "studio-mac.local", port: 61234) + #expect(approvedStore.manualHostTrustWarning?.endpoint == "studio-mac.local:61234") + _ = await approvedStore.acceptManualHostTrustWarning() + #expect(approvedStore.connectionState == .connected) + + let blockedResponses = ScriptedTransportResponses([]) let runtime = testRuntime( - supportedRouteKinds: [.tailscale], - transportFactory: ScriptedTransportFactory(responses: responses), + supportedRouteKinds: [.manualHost], + transportFactory: ScriptedTransportFactory(responses: blockedResponses), stackAccessToken: "stack-token-for-local-dns" ) - let store = CMUXMobileShellStore.preview(runtime: runtime) + let store = CMUXMobileShellStore.preview(runtime: runtime, manualHostTrustStore: trustStore) store.signIn() - await store.connectManualHost(name: "", host: "devbox.local", port: 61234) + await store.connectManualHost(name: "", host: "other-mac.local", port: 61234) #expect(store.phase == .pairing) #expect(store.connectionState == .disconnected) #expect(store.activeTicket == nil) #expect(store.activeRoute == nil) - #expect(store.connectionError == "This pairing route is not allowed. Enter a host and port, or pair with a QR/link from that computer.") - #expect(try await responses.sentRequests().isEmpty) + #expect(store.manualHostTrustWarning?.endpoint == "other-mac.local:61234") + #expect(try await blockedResponses.sentRequests().isEmpty) } @MainActor @Test func manualHostPairingProbesTailscaleHostForAttachTicketBeforeStackAuthFallback() async throws { - // A trusted (Tailscale) manual host is probed for a real attach ticket + // A manually-entered Tailscale host is probed for a real attach ticket // first; an older Mac that does not implement the probe method falls back // to a synthetic ticket and Stack-authenticated workspace.list. let responses = ScriptedTransportResponses([ @@ -1825,6 +1864,49 @@ final class TerminalOutputCollector { #expect(store.connectionError != MobilePairingFailureCategory.invalidCode.message) } +@MainActor +@Test func pairingQRCodeManualHostBlocksUntilApproved() async throws { + let responses = ScriptedTransportResponses([ + try rpcWorkspaceListFrame(workspaceID: "qr-manual-workspace", title: "QR Manual Workspace"), + try rpcHostStatusFrame( + renderGrid: false, + macDeviceID: "qr-manual-mac", + macDisplayName: "QR Manual Mac" + ), + ]) + let runtime = testRuntime( + supportedRouteKinds: [.manualHost], + transportFactory: ScriptedTransportFactory(responses: responses), + stackAccessToken: "stack-token-for-qr-manual" + ) + let trustStore = InMemoryMobileManualHostTrustStore() + let store = CMUXMobileShellStore.preview(runtime: runtime, manualHostTrustStore: trustStore) + let url = "cmux-ios://attach?v=2&pc=1&m=studio-mac.local:61234" + + store.signIn() + let firstResult = await store.connectPairingURLResult(url) + + #expect(firstResult == .needsUserApproval) + #expect(store.connectionState == .disconnected) + #expect(store.activeTicket == nil) + #expect(store.activeRoute == nil) + #expect(store.manualHostTrustWarning?.endpoint == "studio-mac.local:61234") + #expect(try await responses.sentRequests().isEmpty) + + let approvedResult = await store.acceptManualHostTrustWarning() + + #expect(approvedResult == .connected) + #expect(store.connectionState == .connected) + #expect(store.manualHostTrustWarning == nil) + let route = try #require(store.activeRoute) + #expect(route.kind == .manualHost) + let requests = try await responses.sentRequests() + #expect(requests.contains { request in + request.method == "workspace.list" && + request.stackAccessToken == "stack-token-for-qr-manual" + }) +} + @MainActor @Test func pairLinkWithoutAttachTokenRejectsArbitraryHostBeforeSendingAuth() async throws { let route = try hostPortRoute(kind: .tailscale, host: "attacker.example", port: CmxMobileDefaults.defaultHostPort) @@ -1893,27 +1975,47 @@ final class TerminalOutputCollector { } @MainActor -@Test func manualHostPairingRejectsDefaultPortLANHostWithoutSendingStackToken() async throws { - // Same encrypted-routes-only contract as the explicit-port LAN test, on - // the default host port: no RPC (and no Stack bearer token) may leave the - // device for a plain-TCP private-LAN route. - let responses = ScriptedTransportResponses([]) +@Test func manualHostTrustDoesNotCoverDifferentPort() async throws { + let approvedRoute = try hostPortRoute( + kind: .manualHost, + host: "192.168.1.77", + port: CmxMobileDefaults.defaultHostPort + ) + let approvedResponses = ScriptedTransportResponses([ + try rpcAttachTicketFrame(route: approvedRoute, workspaceID: "approved-default-port"), + try rpcWorkspaceListFrame(workspaceID: "approved-default-port", title: "Approved Default Port"), + ]) + let trustStore = InMemoryMobileManualHostTrustStore() + let approvedRuntime = testRuntime( + supportedRouteKinds: [.manualHost], + transportFactory: ScriptedTransportFactory(responses: approvedResponses), + stackAccessToken: "stack-token-for-default-lan" + ) + let approvedStore = CMUXMobileShellStore.preview(runtime: approvedRuntime, manualHostTrustStore: trustStore) + + approvedStore.signIn() + await approvedStore.connectManualHost(name: "Work Mac", host: "192.168.1.77", port: CmxMobileDefaults.defaultHostPort) + #expect(approvedStore.manualHostTrustWarning?.endpoint == "192.168.1.77:\(CmxMobileDefaults.defaultHostPort)") + _ = await approvedStore.acceptManualHostTrustWarning() + #expect(approvedStore.connectionState == .connected) + + let blockedResponses = ScriptedTransportResponses([]) let runtime = testRuntime( - supportedRouteKinds: [.tailscale], - transportFactory: ScriptedTransportFactory(responses: responses), + supportedRouteKinds: [.manualHost], + transportFactory: ScriptedTransportFactory(responses: blockedResponses), stackAccessToken: "stack-token-for-default-lan" ) - let store = CMUXMobileShellStore.preview(runtime: runtime) + let store = CMUXMobileShellStore.preview(runtime: runtime, manualHostTrustStore: trustStore) store.signIn() - await store.connectManualHost(name: "Work Mac", host: "192.168.1.77", port: CmxMobileDefaults.defaultHostPort) + await store.connectManualHost(name: "Work Mac", host: "192.168.1.77", port: CmxMobileDefaults.defaultHostPort + 1) #expect(store.phase == .pairing) #expect(store.connectionState == .disconnected) #expect(store.activeTicket == nil) #expect(store.activeRoute == nil) - #expect(store.connectionError == "This pairing route is not allowed. Enter a host and port, or pair with a QR/link from that computer.") - #expect(try await responses.sentRequests().isEmpty) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:\(CmxMobileDefaults.defaultHostPort + 1)") + #expect(try await blockedResponses.sentRequests().isEmpty) } @MainActor From 9cd18dccc4f9897c266f74d362a510452f2e36f3 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 21:49:42 -0700 Subject: [PATCH 02/91] Address manual host pairing CI review --- .../CmxManualHostTests.swift | 21 ++ .../CmxTransportTests.swift | 24 -- ...MobileShellComposite+ManualHostTrust.swift | 105 ++++++++ .../MobileShellComposite+RouteSelection.swift | 116 +++++++++ .../MobileShellComposite.swift | 230 +----------------- .../CMUXMobileRootView+PairingWarnings.swift | 19 ++ .../CMUXMobileRootView.swift | 20 +- Packages/macOS/CmuxSettingsUI/Package.swift | 2 + .../MobileHostService+ManualHostRoutes.swift | 38 +++ Sources/Mobile/MobileHostService.swift | 44 +--- cmux.xcodeproj/project.pbxproj | 4 + cmuxTests/MobileHostAuthorizationTests.swift | 36 +-- .../cmuxFeatureTests/cmuxFeatureTests.swift | 23 ++ 13 files changed, 346 insertions(+), 336 deletions(-) create mode 100644 Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift create mode 100644 Sources/Mobile/MobileHostService+ManualHostRoutes.swift diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift new file mode 100644 index 000000000000..a4885e20e10f --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift @@ -0,0 +1,21 @@ +import Testing +@testable import CMUXMobileCore + +@Test func attachRouteAcceptsManualHostPortEndpoint() throws { + let route = try CmxAttachRoute( + id: "manual_host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.4.12", port: 58_465) + ) + + #expect(route.kind == .manualHost) + #expect(route.endpoint == .hostPort(host: "192.168.4.12", port: 58_465)) +} + +@Test func manualHostNormalizerRejectsURLsAndAcceptsBracketedIPv6() { + #expect(CmxManualHost(" studio-mac.corp.example ")?.rawValue == "studio-mac.corp.example") + #expect(CmxManualHost("[fd00::12]")?.rawValue == "fd00::12") + #expect(CmxManualHost("https://studio-mac.corp.example") == nil) + #expect(CmxManualHost("studio-mac.corp.example/path") == nil) + #expect(CmxManualHost("studio mac") == nil) +} diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxTransportTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxTransportTests.swift index a88139d26a77..ca2419a8cc1c 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxTransportTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxTransportTests.swift @@ -67,11 +67,6 @@ import Testing kind: .tailscale, endpoint: .hostPort(host: "100.64.1.2", port: 49831) ), - CmxAttachRoute( - id: "manual_host", - kind: .manualHost, - endpoint: .hostPort(host: "studio-mac.corp.example", port: 49831) - ), CmxAttachRoute( id: "iroh", kind: .iroh, @@ -109,25 +104,6 @@ import Testing #expect(decoded == ticket) } -@Test func attachRouteAcceptsManualHostPortEndpoint() throws { - let route = try CmxAttachRoute( - id: "manual_host", - kind: .manualHost, - endpoint: .hostPort(host: "192.168.4.12", port: 58_465) - ) - - #expect(route.kind == .manualHost) - #expect(route.endpoint == .hostPort(host: "192.168.4.12", port: 58_465)) -} - -@Test func manualHostNormalizerRejectsURLsAndAcceptsBracketedIPv6() { - #expect(CmxManualHost(" studio-mac.corp.example ")?.rawValue == "studio-mac.corp.example") - #expect(CmxManualHost("[fd00::12]")?.rawValue == "fd00::12") - #expect(CmxManualHost("https://studio-mac.corp.example") == nil) - #expect(CmxManualHost("studio-mac.corp.example/path") == nil) - #expect(CmxManualHost("studio mac") == nil) -} - @Test func attachTicketRejectsEmptyAuthToken() throws { let route = try CmxAttachRoute( id: "tailscale", diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift new file mode 100644 index 000000000000..447389a07427 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -0,0 +1,105 @@ +import CMUXMobileCore +import CmuxMobileShellModel + +enum PendingManualHostTrust { + case manual( + name: String, + host: String, + port: Int, + pairedMacDeviceID: String?, + recordsPairingAttempt: Bool, + ifStillCurrent: (() -> Bool)? + ) + case pairingURL(rawURL: String, acceptedVersionWarning: Bool) +} + +@MainActor +extension MobileShellComposite { + func clearManualHostTrustWarning() { + manualHostTrustWarning = nil + pendingManualHostTrust = nil + } + + func manualHostTrustScope(for route: CmxAttachRoute?) -> MobileManualHostTrustScope? { + guard let route, + MobileShellRouteAuthPolicy.routeRequiresManualHostTrust(route) else { + return nil + } + return MobileManualHostTrustScope( + route: route, + stackUserID: identityProvider?.currentUserID + ) + } + + func manualHostStackAuthTrusted(for route: CmxAttachRoute?) async -> Bool { + guard let scope = manualHostTrustScope(for: route) else { + return false + } + return await manualHostTrustStore.isTrusted(scope) + } + + func manualHostRouteNeedsApproval(_ route: CmxAttachRoute) async -> Bool { + guard let scope = manualHostTrustScope(for: route) else { + return false + } + return !(await manualHostTrustStore.isTrusted(scope)) + } + + func firstManualHostRouteNeedingApproval( + in routes: [CmxAttachRoute] + ) async -> (route: CmxAttachRoute, scope: MobileManualHostTrustScope)? { + for route in routes { + guard let scope = manualHostTrustScope(for: route) else { + continue + } + if !(await manualHostTrustStore.isTrusted(scope)) { + return (route, scope) + } + } + return nil + } + + func queueManualHostTrustWarning( + route: CmxAttachRoute, + displayHost: String, + pending: PendingManualHostTrust + ) { + guard let scope = manualHostTrustScope(for: route) else { + return + } + clearPairingError() + pendingManualHostTrust = pending + manualHostTrustWarning = MobileManualHostTrustWarning( + scope: scope, + displayHost: displayHost + ) + } + + @discardableResult + public func acceptManualHostTrustWarning() async -> MobilePairingURLConnectionResult { + guard let warning = manualHostTrustWarning, + let pending = pendingManualHostTrust else { + clearManualHostTrustWarning() + return .failed + } + await manualHostTrustStore.trust(warning.scope) + clearManualHostTrustWarning() + switch pending { + case let .manual(name, host, port, pairedMacDeviceID, recordsPairingAttempt, ifStillCurrent): + await connectManualHost( + name: name, + host: host, + port: port, + pairedMacDeviceID: pairedMacDeviceID, + recordsPairingAttempt: recordsPairingAttempt, + ifStillCurrent: ifStillCurrent + ) + return connectionState == .connected ? .connected : .failed + case let .pairingURL(rawURL, acceptedVersionWarning): + return await connectPairingURLResult( + rawURL, + acceptedVersionWarning: acceptedVersionWarning + ) + } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift new file mode 100644 index 000000000000..9854f9115407 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift @@ -0,0 +1,116 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import Foundation + +@MainActor +extension MobileShellComposite { + /// Whether route selection should avoid loopback routes. A loopback route + /// (`.debugLoopback`, `127.0.0.1`) names the host it runs on, so on a + /// physical device it can only ever reach the phone itself, never a remote + /// Mac. On the simulator `127.0.0.1` IS the host Mac, so loopback is valid + /// (and is how the dev/UI-test mock host attaches). + static var prefersNonLoopbackRoutes: Bool { + #if targetEnvironment(simulator) + false + #else + true + #endif + } + + /// The first reachable host/port route to a Mac, in priority order. + /// + /// When `preferNonLoopback` is set (physical devices), a real route + /// (`.tailscale` etc.) is always chosen over a `.debugLoopback` route even + /// if the loopback route has a lower (more-preferred) priority, because a + /// loopback route can never reach a remote Mac from a physical phone. A + /// loopback route is used only when it is the sole supported route - the + /// on-device XCUITest mock host, which serves a real listener on `127.0.0.1` + /// inside the test runner. This is what lets a restored Mac (whose published + /// routes include both `debug_loopback` and `tailscale`) actually connect + /// over Tailscale instead of dialing the phone's own loopback and failing. + static func firstReconnectHostPortRoute( + _ routes: [CmxAttachRoute], + supportedKinds: [CmxAttachTransportKind], + preferNonLoopback: Bool = false + ) -> (String, Int)? { + let supportedKinds = Set(supportedKinds) + let ordered = routes.sorted(by: Self.routeSortsBefore) + func firstHostPort(where predicate: (CmxAttachRoute) -> Bool) -> (String, Int)? { + for route in ordered { + if !supportedKinds.isEmpty, !supportedKinds.contains(route.kind) { + continue + } + guard predicate(route), case let .hostPort(host, port) = route.endpoint else { + continue + } + return (host, port) + } + return nil + } + if preferNonLoopback { + // Among non-loopback routes, prefer one whose host is a numeric IP: a + // raw tailscale/LAN IP is dialable without DNS, whereas a MagicDNS + // hostname depends on the client having tailscale DNS active. + if let ip = firstHostPort(where: { route in + guard route.kind != .debugLoopback, + case let .hostPort(host, _) = route.endpoint else { return false } + return Self.isIPLiteralHost(host) + }) { + return ip + } + if let real = firstHostPort(where: { $0.kind != .debugLoopback }) { + return real + } + } + return firstHostPort(where: { _ in true }) + } + + /// Whether `host` is a numeric IP literal (IPv4 or IPv6) rather than a name + /// that needs DNS resolution. Used to prefer directly-dialable IP routes over + /// MagicDNS hostnames, which fail to resolve on some clients. + static func isIPLiteralHost(_ host: String) -> Bool { + if host.contains(":") { return true } + let octets = host.split(separator: ".", omittingEmptySubsequences: false) + return octets.count == 4 && octets.allSatisfy { part in + guard let value = Int(part), (0...255).contains(value), !part.isEmpty else { return false } + return String(value) == part + } + } + + /// `true` on a physical iPhone/iPad; `false` in the simulator and in + /// macOS-hosted package tests. Drives the loopback-pairing rejection. + static var isPhysicalDevice: Bool { + #if os(iOS) && !targetEnvironment(simulator) + true + #else + false + #endif + } + + static func manualHostRoute(host: String, port: Int) throws -> CmxAttachRoute { + let routeKind = MobileShellRouteAuthPolicy.manualRouteKind(for: host) + return try CmxAttachRoute( + id: routeKind.rawValue, + kind: routeKind, + endpoint: .hostPort(host: host, port: port) + ) + } + + static func supportedRoutes( + for ticket: CmxAttachTicket, + supportedKinds: [CmxAttachTransportKind] + ) -> [CmxAttachRoute] { + let orderedRoutes = ticket.routes.sorted(by: Self.routeSortsBefore) + guard !supportedKinds.isEmpty else { + return orderedRoutes + } + let supportedKinds = Set(supportedKinds) + return orderedRoutes.filter { route in + supportedKinds.contains(route.kind) + } + } + + static func attachTicketIsUnexpired(_ ticket: CmxAttachTicket, now: Date) -> Bool { + !ticket.isExpired(at: now) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 3d177b2d4e95..413b13a89be1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -15,18 +15,6 @@ private let mobileShellLog = Logger( category: "mobile-shell" ) -private enum PendingManualHostTrust { - case manual( - name: String, - host: String, - port: Int, - pairedMacDeviceID: String?, - recordsPairingAttempt: Bool, - ifStillCurrent: (() -> Bool)? - ) - case pairingURL(rawURL: String, acceptedVersionWarning: Bool) -} - /// Transitional alias for the decomposed shell facade. /// /// The iOS views and push coordinator still bind to `CMUXMobileShellStore`; @@ -182,7 +170,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { public private(set) var pairingVersionWarning: String? /// A warning that must be accepted before a non-Tailscale manual host can /// carry Stack auth over plaintext LAN transport. - public private(set) var manualHostTrustWarning: MobileManualHostTrustWarning? + public internal(set) var manualHostTrustWarning: MobileManualHostTrustWarning? public private(set) var activeTicket: CmxAttachTicket? public private(set) var activeRoute: CmxAttachRoute? @@ -625,7 +613,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// false` and break the first-pair funnel. private var pairingAttemptIsFirstPair = false private var pendingPairingVersionWarningURL: String? - @ObservationIgnored private var pendingManualHostTrust: PendingManualHostTrust? + @ObservationIgnored var pendingManualHostTrust: PendingManualHostTrust? /// The structured diagnostic log, injected from the app composition root. /// @@ -1562,7 +1550,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// `mobile.attach_ticket.create` connects via a synthetic `manual-…` ticket; /// passing the real id keys the foreground aggregate state under it instead of /// the synthetic id. `nil` for a genuinely manual/unknown host. - private func connectManualHost( + func connectManualHost( name: String, host: String, port: Int, @@ -2769,82 +2757,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { didFinishStoredMacReconnectAttempt = false } - /// Whether route selection should avoid loopback routes. A loopback route - /// (`.debugLoopback`, `127.0.0.1`) names the host it runs on, so on a - /// physical device it can only ever reach the phone itself, never a remote - /// Mac. On the simulator `127.0.0.1` IS the host Mac, so loopback is valid - /// (and is how the dev/UI-test mock host attaches). - static var prefersNonLoopbackRoutes: Bool { - #if targetEnvironment(simulator) - false - #else - true - #endif - } - - /// The first reachable host/port route to a Mac, in priority order. - /// - /// When `preferNonLoopback` is set (physical devices), a real route - /// (`.tailscale` etc.) is always chosen over a `.debugLoopback` route even - /// if the loopback route has a lower (more-preferred) priority, because a - /// loopback route can never reach a remote Mac from a physical phone. A - /// loopback route is used only when it is the sole supported route — the - /// on-device XCUITest mock host, which serves a real listener on `127.0.0.1` - /// inside the test runner. This is what lets a restored Mac (whose published - /// routes include both `debug_loopback` and `tailscale`) actually connect - /// over Tailscale instead of dialing the phone's own loopback and failing. - static func firstReconnectHostPortRoute( - _ routes: [CmxAttachRoute], - supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool = false - ) -> (String, Int)? { - let supportedKinds = Set(supportedKinds) - let ordered = routes.sorted(by: Self.routeSortsBefore) - func firstHostPort(where predicate: (CmxAttachRoute) -> Bool) -> (String, Int)? { - for route in ordered { - if !supportedKinds.isEmpty, !supportedKinds.contains(route.kind) { - continue - } - guard predicate(route), case let .hostPort(host, port) = route.endpoint else { - continue - } - return (host, port) - } - return nil - } - if preferNonLoopback { - // Among non-loopback routes, prefer one whose host is a numeric IP: a - // raw tailscale/LAN IP is dialable without DNS, whereas a MagicDNS - // hostname (e.g. "..ts.net") depends on the client - // having tailscale DNS active and resolving it. On devices where - // MagicDNS isn't resolving, dialing the hostname times out and the Mac - // silently drops out of the list, even though its IP route is fine. - if let ip = firstHostPort(where: { route in - guard route.kind != .debugLoopback, - case let .hostPort(host, _) = route.endpoint else { return false } - return Self.isIPLiteralHost(host) - }) { - return ip - } - if let real = firstHostPort(where: { $0.kind != .debugLoopback }) { - return real - } - } - return firstHostPort(where: { _ in true }) - } - - /// Whether `host` is a numeric IP literal (IPv4 or IPv6) rather than a name - /// that needs DNS resolution. Used to prefer directly-dialable IP routes over - /// MagicDNS hostnames, which fail to resolve on some clients. - static func isIPLiteralHost(_ host: String) -> Bool { - if host.contains(":") { return true } // IPv6 literal - let octets = host.split(separator: ".", omittingEmptySubsequences: false) - return octets.count == 4 && octets.allSatisfy { part in - guard let value = Int(part), (0...255).contains(value), !part.isEmpty else { return false } - return String(value) == part // reject leading zeros / non-canonical - } - } - /// Enqueues one paired-Mac store mutation on the serialized write chain. /// /// All `markActive` writes go through here so they execute strictly in @@ -3126,28 +3038,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } - /// `true` on a physical iPhone/iPad; `false` in the simulator and in - /// macOS-hosted package tests. Drives the loopback-pairing rejection: - /// the simulator's 127.0.0.1 is the host Mac and dev auto-pair depends - /// on it, while a physical device dialing loopback only ever reaches - /// itself. - private static var isPhysicalDevice: Bool { - #if os(iOS) && !targetEnvironment(simulator) - true - #else - false - #endif - } - - static func manualHostRoute(host: String, port: Int) throws -> CmxAttachRoute { - let routeKind = MobileShellRouteAuthPolicy.manualRouteKind(for: host) - return try CmxAttachRoute( - id: routeKind.rawValue, - kind: routeKind, - endpoint: .hostPort(host: host, port: port) - ) - } - @discardableResult public func connectPairingURL(_ rawValue: String? = nil) async -> Bool { await connectPairingURLResult(rawValue).didConnect @@ -3159,7 +3049,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } @discardableResult - private func connectPairingURLResult( + func connectPairingURLResult( _ rawValue: String? = nil, acceptedVersionWarning: Bool ) async -> MobilePairingURLConnectionResult { @@ -5166,24 +5056,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { var preferActiveTicketTarget: Bool } - private static func supportedRoutes( - for ticket: CmxAttachTicket, - supportedKinds: [CmxAttachTransportKind] - ) -> [CmxAttachRoute] { - let orderedRoutes = ticket.routes.sorted(by: Self.routeSortsBefore) - guard !supportedKinds.isEmpty else { - return orderedRoutes - } - let supportedKinds = Set(supportedKinds) - return orderedRoutes.filter { route in - supportedKinds.contains(route.kind) - } - } - - private static func attachTicketIsUnexpired(_ ticket: CmxAttachTicket, now: Date) -> Bool { - !ticket.isExpired(at: now) - } - private static func initialWorkspaceListParams(for ticket: CmxAttachTicket) -> [String: Any] { guard UUID(uuidString: ticket.workspaceID) != nil else { return [:] @@ -5592,7 +5464,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// Clear the error and its guidance together (never bare `connectionError /// = nil`) so guidance cannot linger under a cleared headline. - private func clearPairingError() { + func clearPairingError() { connectionError = nil connectionErrorGuidance = nil } @@ -5602,98 +5474,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { pendingPairingVersionWarningURL = nil } - private func clearManualHostTrustWarning() { - manualHostTrustWarning = nil - pendingManualHostTrust = nil - } - - private func manualHostTrustScope(for route: CmxAttachRoute?) -> MobileManualHostTrustScope? { - guard let route, - MobileShellRouteAuthPolicy.routeRequiresManualHostTrust(route) else { - return nil - } - return MobileManualHostTrustScope( - route: route, - stackUserID: identityProvider?.currentUserID - ) - } - - private func manualHostStackAuthTrusted(for route: CmxAttachRoute?) async -> Bool { - guard let scope = manualHostTrustScope(for: route) else { - return false - } - return await manualHostTrustStore.isTrusted(scope) - } - - private func manualHostRouteNeedsApproval(_ route: CmxAttachRoute) async -> Bool { - guard let scope = manualHostTrustScope(for: route) else { - return false - } - return !(await manualHostTrustStore.isTrusted(scope)) - } - - private func firstManualHostRouteNeedingApproval( - in routes: [CmxAttachRoute] - ) async -> (route: CmxAttachRoute, scope: MobileManualHostTrustScope)? { - for route in routes { - if MobileShellRouteAuthPolicy.routeAllowsStackAuth(route) { - return nil - } - guard let scope = manualHostTrustScope(for: route) else { - continue - } - if await manualHostTrustStore.isTrusted(scope) { - return nil - } - return (route, scope) - } - return nil - } - - private func queueManualHostTrustWarning( - route: CmxAttachRoute, - displayHost: String, - pending: PendingManualHostTrust - ) { - guard let scope = manualHostTrustScope(for: route) else { - return - } - clearPairingError() - pendingManualHostTrust = pending - manualHostTrustWarning = MobileManualHostTrustWarning( - scope: scope, - displayHost: displayHost - ) - } - - @discardableResult - public func acceptManualHostTrustWarning() async -> MobilePairingURLConnectionResult { - guard let warning = manualHostTrustWarning, - let pending = pendingManualHostTrust else { - clearManualHostTrustWarning() - return .failed - } - await manualHostTrustStore.trust(warning.scope) - clearManualHostTrustWarning() - switch pending { - case let .manual(name, host, port, pairedMacDeviceID, recordsPairingAttempt, ifStillCurrent): - await connectManualHost( - name: name, - host: host, - port: port, - pairedMacDeviceID: pairedMacDeviceID, - recordsPairingAttempt: recordsPairingAttempt, - ifStillCurrent: ifStillCurrent - ) - return connectionState == .connected ? .connected : .failed - case let .pairingURL(rawURL, acceptedVersionWarning): - return await connectPairingURLResult( - rawURL, - acceptedVersionWarning: acceptedVersionWarning - ) - } - } - private func versionWarning(for ticket: CmxAttachTicket) -> String? { guard let macCompatibilityVersion = ticket.macPairingCompatibilityVersion, macCompatibilityVersion != CmxMobileDefaults.pairingCompatibilityVersion else { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift new file mode 100644 index 000000000000..da8d5d3db2d7 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift @@ -0,0 +1,19 @@ +import CmuxMobileShell + +extension CMUXMobileRootView { + func acceptPairingVersionWarning() async { + let result = await store.acceptPairingVersionWarning() + clearAttachTicketAuthentication(after: result) + if result == .connected { + dismissAddDeviceSheet() + } + } + + func acceptManualHostTrustWarning() async { + let result = await store.acceptManualHostTrustWarning() + clearAttachTicketAuthentication(after: result) + if result == .connected { + dismissAddDeviceSheet() + } + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index ae075cefb0b4..cf2b789da4e6 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -265,20 +265,8 @@ struct CMUXMobileRootView: View { connectPairingCode: { await store.connectPairingInput() }, - acceptVersionWarning: { - let result = await store.acceptPairingVersionWarning() - clearAttachTicketAuthentication(after: result) - if result == .connected { - dismissAddDeviceSheet() - } - }, - acceptManualHostTrustWarning: { - let result = await store.acceptManualHostTrustWarning() - clearAttachTicketAuthentication(after: result) - if result == .connected { - dismissAddDeviceSheet() - } - }, + acceptVersionWarning: acceptPairingVersionWarning, + acceptManualHostTrustWarning: acceptManualHostTrustWarning, connectManualHost: { name, host, port in await store.connectManualHost(name: name, host: host, port: port) }, @@ -441,7 +429,7 @@ struct CMUXMobileRootView: View { clearAttachTicketAuthenticationIfNeeded() } - private func dismissAddDeviceSheet() { + func dismissAddDeviceSheet() { isShowingAddDeviceSheet = false if store.pairingVersionWarning != nil || store.manualHostTrustWarning != nil { cancelPairing() @@ -450,7 +438,7 @@ struct CMUXMobileRootView: View { } } - private func clearAttachTicketAuthentication(after result: MobilePairingURLConnectionResult) { + func clearAttachTicketAuthentication(after result: MobilePairingURLConnectionResult) { guard MobileRootAuthGate.shouldClearAttachTicketAuthentication( pairingResult: result, connectionState: store.connectionState, diff --git a/Packages/macOS/CmuxSettingsUI/Package.swift b/Packages/macOS/CmuxSettingsUI/Package.swift index cb80de848be9..ca136140ff65 100644 --- a/Packages/macOS/CmuxSettingsUI/Package.swift +++ b/Packages/macOS/CmuxSettingsUI/Package.swift @@ -14,6 +14,7 @@ let package = Package( ), ], dependencies: [ + .package(path: "../../Shared/CMUXMobileCore"), .package(path: "../CmuxFoundation"), .package(path: "../CmuxSettings"), ], @@ -21,6 +22,7 @@ let package = Package( .target( name: "CmuxSettingsUI", dependencies: [ + .product(name: "CMUXMobileCore", package: "CMUXMobileCore"), .product(name: "CmuxFoundation", package: "CmuxFoundation"), .product(name: "CmuxSettings", package: "CmuxSettings"), ] diff --git a/Sources/Mobile/MobileHostService+ManualHostRoutes.swift b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift new file mode 100644 index 000000000000..1e632cabf0f0 --- /dev/null +++ b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift @@ -0,0 +1,38 @@ +import CMUXMobileCore +import CmuxSettings +import Foundation + +extension MobileHostService { + /// User-default key for the explicit manual host advertised to iOS when + /// Tailscale is unavailable on this Mac. + nonisolated static let manualHostDefaultsKey = SettingCatalog().mobile.iOSPairingManualHost.userDefaultsKey + + /// The user-configured LAN/DNS host to advertise as an explicit manual route, + /// or `nil` when unset or invalid. + nonisolated static func configuredManualHost(defaults: UserDefaults = .standard) -> String? { + guard let raw = defaults.object(forKey: manualHostDefaultsKey) as? String, + let host = CmxManualHost(raw)?.rawValue else { + return nil + } + return host + } + + func currentRoutes(port: Int) -> [CmxAttachRoute] { + routeResolver.routes(port: port, manualHost: Self.configuredManualHost()).routes + } + + func currentRoutes(port: Int, tailscaleHosts: [String]) -> [CmxAttachRoute] { + routeResolver.routes( + port: port, + tailscaleHosts: tailscaleHosts, + manualHost: Self.configuredManualHost() + ).routes + } + + func refreshAdvertisedRoutesIfRunning() { + guard let listenerPort else { + return + } + MobileHostPublicStatusCache.update(routes: currentRoutes(port: listenerPort)) + } +} diff --git a/Sources/Mobile/MobileHostService.swift b/Sources/Mobile/MobileHostService.swift index b360a4c9da58..9de9c0c079cd 100644 --- a/Sources/Mobile/MobileHostService.swift +++ b/Sources/Mobile/MobileHostService.swift @@ -149,16 +149,11 @@ private final class MobileHostConnectionRegistry: @unchecked Sendable { } } -private enum MobileHostPublicStatusCache { +enum MobileHostPublicStatusCache { private static let lock = NSLock() private nonisolated(unsafe) static var routes: [CmxAttachRoute] = [] - static func update(routes nextRoutes: [CmxAttachRoute]) { lock.lock() - guard routes != nextRoutes else { - lock.unlock() - return - } routes = nextRoutes lock.unlock() NotificationCenter.default.post(name: .mobileHostStatusDidChange, object: nil) @@ -373,12 +368,12 @@ final class MobileHostService { } private let callbackQueue = DispatchQueue(label: "dev.cmux.mobile.host-listener") - private let routeResolver = MobileRouteResolver() + let routeResolver = MobileRouteResolver() private let ticketStore = MobileAttachTicketStore() private var listener: NWListener? private var listenerGeneration = UUID() private var listenerUsesEphemeralFallback = false - private var listenerPort: Int? + var listenerPort: Int? /// The preferred port the active start-sequence targeted (regardless of an /// ephemeral fallback). Used to decide whether a settings change needs a /// restart. `nil` while stopped. @@ -528,20 +523,6 @@ final class MobileHostService { return (1...65535).contains(raw) ? raw : nil } - /// User-default key for the explicit manual host advertised to iOS when - /// Tailscale is unavailable on this Mac. - nonisolated static let manualHostDefaultsKey = SettingCatalog().mobile.iOSPairingManualHost.userDefaultsKey - - /// The user-configured LAN/DNS host to advertise as an explicit manual route, - /// or `nil` when unset or invalid. - nonisolated static func configuredManualHost(defaults: UserDefaults = .standard) -> String? { - guard let raw = defaults.object(forKey: manualHostDefaultsKey) as? String, - let host = CmxManualHost(raw)?.rawValue else { - return nil - } - return host - } - /// Pure reconciliation between the desired settings and the live listener /// state. Factored out so the restart-on-port-change decision is unit /// testable without binding a real `NWListener`. @@ -857,25 +838,6 @@ final class MobileHostService { return makeStatus(routes: routes) } - private func currentRoutes(port: Int) -> [CmxAttachRoute] { - routeResolver.routes(port: port, manualHost: Self.configuredManualHost()).routes - } - - private func currentRoutes(port: Int, tailscaleHosts: [String]) -> [CmxAttachRoute] { - routeResolver.routes( - port: port, - tailscaleHosts: tailscaleHosts, - manualHost: Self.configuredManualHost() - ).routes - } - - private func refreshAdvertisedRoutesIfRunning() { - guard let listenerPort else { - return - } - MobileHostPublicStatusCache.update(routes: currentRoutes(port: listenerPort)) - } - /// Emits the current ``MobileHostServiceStatus`` immediately, then a fresh /// snapshot every time the listener or active-connection set changes (driven by /// `.mobileHostStatusDidChange`). The in-app pairing window consumes this to flip diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 1e0b1e4f6525..6c71fb9197b9 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -695,6 +695,7 @@ DE71CE000000000000000006 /* MobileHostNetworkPathRefreshTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE71CE000000000000000005 /* MobileHostNetworkPathRefreshTests.swift */; }; 4E673EDE464BF3AB80E94C1D /* MobileHostRPC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47BDC06F004C02A52B05E4A0 /* MobileHostRPC.swift */; }; C7A50B000000000000000014 /* MobileHostService+Capabilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A50B000000000000000013 /* MobileHostService+Capabilities.swift */; }; + 7230A0017230A0017230A001 /* MobileHostService+ManualHostRoutes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7230B0017230B0017230B001 /* MobileHostService+ManualHostRoutes.swift */; }; F67FBC88671C40AC3A3284CE /* MobileHostService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7ACA497A6831165EA879C642 /* MobileHostService.swift */; }; C0DE10510000000000000001 /* MobileHostServiceSettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE10510000000000000002 /* MobileHostServiceSettingsTests.swift */; }; 4C1A7E10B2D34F56A8C90011 /* MobileHostStatusVerificationLimiter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C1A7E10B2D34F56A8C90012 /* MobileHostStatusVerificationLimiter.swift */; }; @@ -1976,6 +1977,7 @@ DE71CE000000000000000005 /* MobileHostNetworkPathRefreshTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileHostNetworkPathRefreshTests.swift; sourceTree = ""; }; 47BDC06F004C02A52B05E4A0 /* MobileHostRPC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileHostRPC.swift; sourceTree = ""; }; C7A50B000000000000000013 /* MobileHostService+Capabilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MobileHostService+Capabilities.swift"; sourceTree = ""; }; + 7230B0017230B0017230B001 /* MobileHostService+ManualHostRoutes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MobileHostService+ManualHostRoutes.swift"; sourceTree = ""; }; 7ACA497A6831165EA879C642 /* MobileHostService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileHostService.swift; sourceTree = ""; }; C0DE10510000000000000002 /* MobileHostServiceSettingsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileHostServiceSettingsTests.swift; sourceTree = ""; }; 4C1A7E10B2D34F56A8C90012 /* MobileHostStatusVerificationLimiter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileHostStatusVerificationLimiter.swift; sourceTree = ""; }; @@ -2746,6 +2748,7 @@ C7A50B000000000000000015 /* MobileHostBuildIdentity.swift */, 4C1A7E10B2D34F56A8C90012 /* MobileHostStatusVerificationLimiter.swift */, C7A50B000000000000000013 /* MobileHostService+Capabilities.swift */, + 7230B0017230B0017230B001 /* MobileHostService+ManualHostRoutes.swift */, DE71CE000000000000000007 /* MobileHostNetworkPathMonitor.swift */, 7A956C76162B79EC74AF9965 /* MobileRouteResolver.swift */, 04CE82AE8B39EA0C1395F696 /* MobilePairingModel.swift */, @@ -4743,6 +4746,7 @@ DE71CE000000000000000008 /* MobileHostNetworkPathMonitor.swift in Sources */, 4E673EDE464BF3AB80E94C1D /* MobileHostRPC.swift in Sources */, C7A50B000000000000000014 /* MobileHostService+Capabilities.swift in Sources */, + 7230A0017230A0017230A001 /* MobileHostService+ManualHostRoutes.swift in Sources */, F67FBC88671C40AC3A3284CE /* MobileHostService.swift in Sources */, 4C1A7E10B2D34F56A8C90011 /* MobileHostStatusVerificationLimiter.swift in Sources */, 0099C2865D9D468747D14593 /* MobilePairingModel.swift in Sources */, diff --git a/cmuxTests/MobileHostAuthorizationTests.swift b/cmuxTests/MobileHostAuthorizationTests.swift index 055860c66a88..f573b0539007 100644 --- a/cmuxTests/MobileHostAuthorizationTests.swift +++ b/cmuxTests/MobileHostAuthorizationTests.swift @@ -176,18 +176,8 @@ struct MobileHostAuthorizationTests { #expect(tailscaleRoutes.count == 2) #expect(tailscaleRoutes.first?.priority == 10) #expect(tailscaleRoutes.last?.priority == 20) - if case let .hostPort(host, port) = tailscaleRoutes.first?.endpoint { - #expect(host == "work-mac.tailnet.ts.net") - #expect(port == 61234) - } else { - #expect(Bool(false), "Expected first Tailscale route to use a host/port endpoint") - } - if case let .hostPort(host, port) = tailscaleRoutes.last?.endpoint { - #expect(host == "100.71.210.41") - #expect(port == 61234) - } else { - #expect(Bool(false), "Expected fallback Tailscale route to use a host/port endpoint") - } + #expect(tailscaleRoutes.first?.endpoint == .hostPort(host: "work-mac.tailnet.ts.net", port: 61234)) + #expect(tailscaleRoutes.last?.endpoint == .hostPort(host: "100.71.210.41", port: 61234)) } @Test func testMobileRouteResolverImmediateSnapshotUsesNumericTailscaleFallbackWithoutDNS() throws { let resolver = MobileRouteResolver() @@ -201,32 +191,18 @@ struct MobileHostAuthorizationTests { let tailscaleRoutes = snapshot.routes.filter { $0.kind == .tailscale } #expect(tailscaleRoutes.count == 1) - if case let .hostPort(host, port) = tailscaleRoutes.first?.endpoint { - #expect(host == "100.71.210.41") - #expect(port == 61234) - } else { - #expect(Bool(false), "Expected immediate snapshot to include a numeric Tailscale route") - } + #expect(tailscaleRoutes.first?.endpoint == .hostPort(host: "100.71.210.41", port: 61234)) #expect(snapshot.routes.filter { $0.kind == .debugLoopback }.count == 1) } @Test func testMobileRouteResolverUsesManualHostWhenTailscaleIsUnavailable() throws { - let resolver = MobileRouteResolver() - - let snapshot = resolver.routes( + let snapshot = MobileRouteResolver().routes( port: 61234, tailscaleHosts: [], manualHost: " studio-mac.corp.example " ) - - let manualRoutes = snapshot.routes.filter { $0.kind == .manualHost } - #expect(manualRoutes.count == 1) + let route = try #require(snapshot.routes.first { $0.kind == .manualHost }) #expect(snapshot.routes.filter { $0.kind == .tailscale }.isEmpty) - if case let .hostPort(host, port) = manualRoutes.first?.endpoint { - #expect(host == "studio-mac.corp.example") - #expect(port == 61234) - } else { - #expect(Bool(false), "Expected manual host route to use a host/port endpoint") - } + #expect(route.endpoint == .hostPort(host: "studio-mac.corp.example", port: 61234)) } @Test func testMobileRouteResolverAwaitsMagicDNSForPublicStatusRoutes() async throws { let resolver = MobileRouteResolver() diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index f78420a47436..65d00a62ae7c 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -1907,6 +1907,29 @@ final class TerminalOutputCollector { }) } +@MainActor +@Test func mixedPairingQRCodeBlocksManualFallbackUntilApproved() async throws { + let responses = ScriptedTransportResponses([]) + let runtime = testRuntime( + supportedRouteKinds: [.tailscale, .manualHost], + transportFactory: ScriptedTransportFactory(responses: responses), + stackAccessToken: "stack-token-for-mixed-manual" + ) + let store = CMUXMobileShellStore.preview( + runtime: runtime, + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + let url = "cmux-ios://attach?v=2&pc=1&r=100.71.210.41:61234&m=studio-mac.local:61234" + + store.signIn() + let result = await store.connectPairingURLResult(url) + + #expect(result == .needsUserApproval) + #expect(store.connectionState == .disconnected) + #expect(store.manualHostTrustWarning?.endpoint == "studio-mac.local:61234") + #expect(try await responses.sentRequests().isEmpty) +} + @MainActor @Test func pairLinkWithoutAttachTokenRejectsArbitraryHostBeforeSendingAuth() async throws { let route = try hostPortRoute(kind: .tailscale, host: "attacker.example", port: CmxMobileDefaults.defaultHostPort) From eb8edd64bba09b102d09bf54108818d06993ddea Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 21:53:09 -0700 Subject: [PATCH 03/91] Address manual host trust review feedback --- .../CMUXMobileCore/CmxManualHost.swift | 15 +++-- .../CMUXMobileCore/CmxPairingQRCode.swift | 13 +++- .../CmxManualHostTests.swift | 2 + .../CmxPairingQRCodeTests.swift | 7 ++ .../InMemoryMobileManualHostTrustStore.swift | 2 +- .../MobileManualHostTrustScope.swift | 15 ++++- ...erDefaultsMobileManualHostTrustStore.swift | 64 ++++++++++++++++--- .../MobileShellRouteAuthPolicyTests.swift | 50 +++++++++++++++ 8 files changed, 148 insertions(+), 20 deletions(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift index 071380df8312..7d6eb8e0f18b 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift @@ -4,16 +4,17 @@ import Foundation /// /// Manual hosts are DNS names or IP literals that a user deliberately chooses /// outside automatic Tailscale discovery. The value is only a host, never a URL: -/// schemes, paths, query/fragment markers, user-info markers, whitespace, and -/// control characters are rejected before the host is advertised or dialed. +/// schemes, paths, query/fragment markers, user-info markers, bare colon host +/// text, whitespace, and control characters are rejected before the host is +/// advertised or dialed. public struct CmxManualHost: Equatable, Sendable { /// The normalized bare host, with IPv6 brackets removed when present. public let rawValue: String /// Creates a normalized manual host. /// - /// - Parameter rawHost: A DNS name or IP literal. IPv6 literals may be - /// bracketed (`[fd00::1]`) or unbracketed (`fd00::1`). + /// - Parameter rawHost: A DNS name or IP literal. IPv6 literals must be + /// bracketed (`[fd00::1]`) so ordinary hostnames cannot hide colons. public init?(_ rawHost: String) { let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { @@ -21,6 +22,7 @@ public struct CmxManualHost: Equatable, Sendable { } let host: String + let isBracketedHost: Bool if trimmed.hasPrefix("[") || trimmed.hasSuffix("]") { guard trimmed.hasPrefix("["), trimmed.hasSuffix("]"), @@ -28,14 +30,17 @@ public struct CmxManualHost: Equatable, Sendable { return nil } host = String(trimmed.dropFirst().dropLast()) + isBracketedHost = true } else { host = trimmed + isBracketedHost = false } + let forbiddenCharacters = isBracketedHost ? "/?#@" : "/?#@:" guard !host.isEmpty, host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil, host.rangeOfCharacter(from: .controlCharacters) == nil, - host.rangeOfCharacter(from: CharacterSet(charactersIn: "/?#@")) == nil, + host.rangeOfCharacter(from: CharacterSet(charactersIn: forbiddenCharacters)) == nil, host.range(of: "://") == nil else { return nil } diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift index 3011b847af1c..f3803c6fc941 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift @@ -198,7 +198,11 @@ public struct CmxPairingQRCode: Sendable { let routes = try rawRoutes.enumerated().map { index, rawRoute -> CmxAttachRoute in let occurrence = occurrences[rawRoute.kind.rawValue] ?? 0 occurrences[rawRoute.kind.rawValue] = occurrence + 1 - let (host, port) = try parseHostPort(rawRoute.value) + let (host, port, isBracketedHost) = try parseHostPort(rawRoute.value) + if rawRoute.kind == .manualHost, + CmxManualHost(isBracketedHost ? "[\(host)]" : host) == nil { + throw MobileSyncPairingPayloadError.invalidURL + } guard !CmxLoopbackHost().matches(host) else { throw MobileSyncPairingPayloadError.loopbackRouteRejected } @@ -280,16 +284,18 @@ private extension CmxPairingQRCode { } /// Parse `host:port` (with optional IPv6 brackets) from a query value. - func parseHostPort(_ rawValue: String) throws -> (String, Int) { + func parseHostPort(_ rawValue: String) throws -> (String, Int, Bool) { let trimmed = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) let host: Substring let portText: Substring + let isBracketedHost: Bool if trimmed.hasPrefix("[") { guard let closing = trimmed.firstIndex(of: "]"), closing > trimmed.startIndex else { throw MobileSyncPairingPayloadError.invalidURL } host = trimmed[trimmed.index(after: trimmed.startIndex).. = [] diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift index 97fd4fc17cc3..5288f18e0a66 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift @@ -20,7 +20,7 @@ public struct MobileManualHostTrustScope: Equatable, Hashable, Sendable { /// - port: The TCP port in `1...65535`. /// - stackUserID: The approving Stack user id, if known. public init?(host: String, port: Int, stackUserID: String?) { - guard let manualHost = CmxManualHost(host), + guard let manualHost = Self.normalizedTrustHost(host), (1...65535).contains(port) else { return nil } @@ -54,4 +54,17 @@ public struct MobileManualHostTrustScope: Equatable, Hashable, Sendable { .replacing("%", with: "%25") .replacing("|", with: "%7C") } + + private static func normalizedTrustHost(_ host: String) -> CmxManualHost? { + if let manualHost = CmxManualHost(host) { + return manualHost + } + let trimmed = host.trimmingCharacters(in: .whitespacesAndNewlines) + let ipv6Characters = CharacterSet(charactersIn: "0123456789abcdefABCDEF:") + guard trimmed.contains(":"), + trimmed.unicodeScalars.allSatisfy({ ipv6Characters.contains($0) }) else { + return nil + } + return CmxManualHost("[\(trimmed)]") + } } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift index 94d72b4ead14..2ca76b3086d8 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -2,49 +2,93 @@ import Foundation /// UserDefaults-backed manual-host trust store for production. public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStoring { + /// Default lifetime for a manual-host approval. + public static let defaultTrustDuration: TimeInterval = 30 * 24 * 60 * 60 + private let defaults: UserDefaults private let key: String + private let trustDuration: TimeInterval + private let now: @Sendable () -> Date /// Creates a durable manual-host trust store. /// - Parameters: /// - defaults: The backing defaults store. - /// - key: The defaults key that stores approved scopes. + /// - key: The defaults key that stores approved scopes and their expiry times. + /// - trustDuration: How long a host approval remains valid. + /// - now: Clock source used to evaluate expiry. public init( defaults: UserDefaults = .standard, - key: String = "cmux.mobile.manualHostTrust.v1" + key: String = "cmux.mobile.manualHostTrust.v2", + trustDuration: TimeInterval = Self.defaultTrustDuration, + now: @escaping @Sendable () -> Date = { Date() } ) { self.defaults = defaults self.key = key + self.trustDuration = trustDuration + self.now = now } /// Creates a durable manual-host trust store in a named defaults suite. /// - Parameters: /// - suiteName: The `UserDefaults` suite name. - /// - key: The defaults key that stores approved scopes. + /// - key: The defaults key that stores approved scopes and their expiry times. + /// - trustDuration: How long a host approval remains valid. + /// - now: Clock source used to evaluate expiry. public init( suiteName: String, - key: String = "cmux.mobile.manualHostTrust.v1" + key: String = "cmux.mobile.manualHostTrust.v2", + trustDuration: TimeInterval = Self.defaultTrustDuration, + now: @escaping @Sendable () -> Date = { Date() } ) { self.defaults = UserDefaults(suiteName: suiteName) ?? .standard self.key = key + self.trustDuration = trustDuration + self.now = now } - /// Returns whether the given host/port/account scope is already trusted. + /// Returns whether the given host/port/account scope is already trusted and unexpired. /// - Parameter scope: The scope to look up. public func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { - Set(defaults.stringArray(forKey: key) ?? []).contains(scope.storageKey) + var trusted = trustedExpirations() + guard let expiresAt = trusted[scope.storageKey] else { + return false + } + guard expiresAt > now().timeIntervalSince1970 else { + trusted.removeValue(forKey: scope.storageKey) + defaults.set(trusted, forKey: key) + return false + } + return true } - /// Persists trust for exactly the given host/port/account scope. + /// Persists trust for exactly the given host/port/account scope until its expiry time. /// - Parameter scope: The scope to approve. public func trust(_ scope: MobileManualHostTrustScope) async { - var trusted = Set(defaults.stringArray(forKey: key) ?? []) - trusted.insert(scope.storageKey) - defaults.set(trusted.sorted(), forKey: key) + let currentTime = now().timeIntervalSince1970 + var trusted = trustedExpirations().filter { _, expiresAt in + expiresAt > currentTime + } + trusted[scope.storageKey] = currentTime + trustDuration + defaults.set(trusted, forKey: key) } /// Removes every stored approval. public func removeAll() async { defaults.removeObject(forKey: key) } + + private func trustedExpirations() -> [String: TimeInterval] { + guard let raw = defaults.dictionary(forKey: key) else { + return [:] + } + var trusted: [String: TimeInterval] = [:] + for (scope, expiresAt) in raw { + if let expiresAt = expiresAt as? TimeInterval { + trusted[scope] = expiresAt + } else if let expiresAt = expiresAt as? NSNumber { + trusted[scope] = expiresAt.doubleValue + } + } + return trusted + } } diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index 5b3bf935e6a7..d501ee8d85c9 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -1,4 +1,5 @@ import CMUXMobileCore +import Foundation import Testing @testable import CmuxMobileShellModel @@ -110,15 +111,64 @@ import Testing port: 58465, stackUserID: "user-b" )) + let normalizedIPv6 = try #require(MobileManualHostTrustScope( + host: "fd00::12", + port: 58465, + stackUserID: "user-a" + )) + let bracketedIPv6 = try #require(MobileManualHostTrustScope( + host: "[fd00::12]", + port: 58465, + stackUserID: "user-a" + )) #expect(!await store.isTrusted(approved)) await store.trust(approved) + await store.trust(normalizedIPv6) #expect(await store.isTrusted(sameHostDifferentCase)) + #expect(await store.isTrusted(bracketedIPv6)) #expect(!await store.isTrusted(differentPort)) #expect(!await store.isTrusted(differentAccount)) } + @Test func userDefaultsManualHostTrustExpiresApproval() async throws { + let suiteName = "cmux-manual-host-trust-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { + defaults.removePersistentDomain(forName: suiteName) + } + let scope = try #require(MobileManualHostTrustScope( + host: "studio-mac.local", + port: 58465, + stackUserID: "user-a" + )) + let key = "manual-host-trust" + let writer = UserDefaultsMobileManualHostTrustStore( + defaults: defaults, + key: key, + trustDuration: 60, + now: { Date(timeIntervalSince1970: 1_000) } + ) + let stillValidReader = UserDefaultsMobileManualHostTrustStore( + defaults: defaults, + key: key, + trustDuration: 60, + now: { Date(timeIntervalSince1970: 1_059) } + ) + let expiredReader = UserDefaultsMobileManualHostTrustStore( + defaults: defaults, + key: key, + trustDuration: 60, + now: { Date(timeIntervalSince1970: 1_061) } + ) + + await writer.trust(scope) + + #expect(await stillValidReader.isTrusted(scope)) + #expect(!await expiredReader.isTrusted(scope)) + } + @Test func physicalDeviceRejectsLoopbackTicketsInEveryGrammar() throws { // The v2 QR decoder rejects loopback itself; this policy is what stops // the LEGACY payload grammars from being a bypass on a physical phone, From c114fcd38f739f88ac03cf4363ffdc98b4404e17 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 22:04:40 -0700 Subject: [PATCH 04/91] Address manual host pairing review gaps --- .../CMUXMobileCore/CmxManualHost.swift | 2 +- .../CMUXMobileCore/CmxPairingQRCode.swift | 39 +++++++++++----- .../CmxManualHostTests.swift | 2 + .../CmxPairingQRCodeTests.swift | 26 ++++++++--- .../CmuxMobileRPC/CmxAttachTicketInput.swift | 6 +-- .../MobileHostStatusResponse.swift | 2 +- .../MobileShellConnectionError.swift | 2 +- .../CmxAttachTicketInputTests.swift | 16 ++++++- .../MobileShellComposite.swift | 8 ++-- .../MobileManualHostTrustWarning.swift | 11 +++-- .../MobileShellRouteAuthPolicyTests.swift | 13 ++++++ .../CMUXMobileRootView.swift | 13 ++++++ Sources/Mobile/MobileAttachTicketStore.swift | 2 +- .../MobileHostService+ManualHostRoutes.swift | 44 +++++++++++++++++-- Sources/Mobile/MobileHostService.swift | 28 ++++++------ .../Mobile/Pairing/MobilePairingModel.swift | 4 +- .../MobileHostServiceSettingsTests.swift | 22 ++++++++++ .../cmuxFeatureTests/cmuxFeatureTests.swift | 4 +- 18 files changed, 191 insertions(+), 53 deletions(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift index 7d6eb8e0f18b..a0e54f5024e9 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift @@ -35,7 +35,7 @@ public struct CmxManualHost: Equatable, Sendable { host = trimmed isBracketedHost = false } - let forbiddenCharacters = isBracketedHost ? "/?#@" : "/?#@:" + let forbiddenCharacters = isBracketedHost ? "/?#@[]" : "/?#@[]:" guard !host.isEmpty, host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil, diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift index f3803c6fc941..58dcc6e219ec 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift @@ -3,7 +3,8 @@ import Foundation /// The minimal pairing-QR grammar: expected Mac account/build metadata plus /// explicit `host:port` routes in the URL query. /// -/// `cmux-ios://attach?v=2&ub=&pc=&av=&ab=&r=:[&m=:]` +/// `cmux-ios://attach?v=2&ub=&pc=&av=&ab=&r=:` +/// `cmux-ios://attach?v=3&ub=&pc=&av=&ab=&r=:[&m=:]` /// /// A pairing QR needs to tell the phone where to dial and which non-secret /// account/build context to check before dialing. The account value is the @@ -41,8 +42,11 @@ import Foundation public struct CmxPairingQRCode: Sendable { /// The grammar version carried in the URL's `v` query item. Distinct from /// ``CmxAttachTicket/currentVersion`` (the ticket *structure* version): - /// `v=1` URLs carry a base64 JSON `payload`, `v=2` URLs carry bare routes. - public static let version = 2 + /// `v=1` URLs carry a base64 JSON `payload`, `v=2` URLs carry bare Tailscale + /// routes, and `v=3` adds explicit manual-host routes. + public static let version = 3 + + private static let tailscaleOnlyRouteVersion = 2 /// Defensive cap on routes accepted from a scanned code. The Mac's route /// resolver emits at most a couple (MagicDNS name + Tailscale IP); a QR @@ -51,10 +55,10 @@ public struct CmxPairingQRCode: Sendable { public static let maximumRouteCount = 8 /// Creates the codec. It is stateless: construct one inline at the call - /// site; every instance speaks the same grammar version. + /// site; every instance speaks the same grammar set. public init() {} - /// Encode `ticket` as a v2 pairing URL, or `nil` when the ticket does not + /// Encode `ticket` as a minimal pairing URL, or `nil` when the ticket does not /// qualify (see ``canEncode(_:)``); callers fall back to the compact v1 /// payload so every ticket still has an attach URL. /// @@ -65,7 +69,7 @@ public struct CmxPairingQRCode: Sendable { guard let routes = encodableRoutes(of: ticket) else { return nil } - var items: [String] = ["v=\(Self.version)"] + var items: [String] = ["v=\(grammarVersion(for: routes))"] if let userID = normalizedNonEmpty(ticket.macUserID) { items.append("ub=\(percentEncodeQueryValue(userID))") } @@ -99,7 +103,7 @@ public struct CmxPairingQRCode: Sendable { encodableRoutes(of: ticket) != nil } - /// The route subsequence a v2 pairing URL would carry for `ticket`, or + /// The route subsequence a minimal pairing URL would carry for `ticket`, or /// `nil` when the ticket is not expressible in the minimal grammar. /// /// Expressible means: an unscoped pairing ticket whose Tailscale/manual-host @@ -143,7 +147,10 @@ public struct CmxPairingQRCode: Sendable { /// Whether `components` (an already-parsed `cmux-ios://attach` URL) speaks /// this grammar. v1 URLs carry the base64 `payload` item instead. public func isPairingCodeURL(_ components: URLComponents) -> Bool { - components.queryItems?.first(where: { $0.name == "v" })?.value == "\(Self.version)" + guard let version = Self.attachURLVersion(components) else { + return false + } + return (Self.tailscaleOnlyRouteVersion...Self.version).contains(version) } /// The integer grammar version declared by an attach URL's `v` query item, @@ -157,7 +164,7 @@ public struct CmxPairingQRCode: Sendable { return Int(raw) } - /// Whether `rawValue` is a v2 pairing URL. String-level convenience for + /// Whether `rawValue` is a minimal pairing URL. String-level convenience for /// callers that hold the encoded URL (the Mac's pairing window asserting /// the code it is about to display speaks the minimal grammar). public func isPairingCodeURLString(_ rawValue: String) -> Bool { @@ -170,7 +177,7 @@ public struct CmxPairingQRCode: Sendable { return isPairingCodeURL(components) } - /// Decode a v2 pairing URL into a validated ``CmxAttachTicket``. + /// Decode a minimal pairing URL into a validated ``CmxAttachTicket``. /// /// The ticket comes back unscoped with an empty `macDeviceID`; the shell /// recovers the Mac's identity post-handshake from `mobile.host.status`. @@ -180,7 +187,8 @@ public struct CmxPairingQRCode: Sendable { /// when any route names a loopback host (a scanned code must never /// point the phone at itself). public func decode(_ components: URLComponents) throws -> CmxAttachTicket { - guard isPairingCodeURL(components) else { + guard isPairingCodeURL(components), + let version = Self.attachURLVersion(components) else { throw MobileSyncPairingPayloadError.invalidURL } let rawRoutes = (components.queryItems ?? []) @@ -194,6 +202,9 @@ public struct CmxPairingQRCode: Sendable { guard !rawRoutes.isEmpty, rawRoutes.count <= Self.maximumRouteCount else { throw MobileSyncPairingPayloadError.invalidURL } + if version < Self.version, rawRoutes.contains(where: { $0.kind == .manualHost }) { + throw MobileSyncPairingPayloadError.invalidURL + } var occurrences: [String: Int] = [:] let routes = try rawRoutes.enumerated().map { index, rawRoute -> CmxAttachRoute in let occurrence = occurrences[rawRoute.kind.rawValue] ?? 0 @@ -232,6 +243,12 @@ public struct CmxPairingQRCode: Sendable { } } private extension CmxPairingQRCode { + func grammarVersion(for routes: [CmxAttachRoute]) -> Int { + routes.contains(where: { $0.kind == .manualHost }) + ? Self.version + : Self.tailscaleOnlyRouteVersion + } + /// Whether `route` can be represented by the minimal query grammar. func isMinimalQRRoute(_ route: CmxAttachRoute) -> Bool { switch route.kind { diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift index 1f08ee3e3aa8..b92f2a82c5b2 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift @@ -19,5 +19,7 @@ import Testing #expect(CmxManualHost("studio-mac.corp.example/path") == nil) #expect(CmxManualHost("my:host") == nil) #expect(CmxManualHost("fd00::12") == nil) + #expect(CmxManualHost("[abc]def]") == nil) + #expect(CmxManualHost("studio]mac") == nil) #expect(CmxManualHost("studio mac") == nil) } diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift index 5576dd87900d..3a719f3e2b82 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift @@ -2,7 +2,7 @@ import Foundation import Testing @testable import CMUXMobileCore -/// Coverage for the minimal v2 pairing-QR grammar: bare Tailscale/manual-host +/// Coverage for the minimal pairing-QR grammar: bare Tailscale/manual-host /// `host:port` routes in the URL query, nothing else. @Suite struct CmxPairingQRCodeTests { private func tailscaleRoute( @@ -93,7 +93,7 @@ import Testing let ticket = try pairingTicket(routes: [route]) let url = try #require(CmxPairingQRCode().encode(ticket)) - #expect(url == "\(CmxPairingURLScheme.current)://attach?v=2&m=studio-mac.corp.example:58465") + #expect(url == "\(CmxPairingURLScheme.current)://attach?v=3&m=studio-mac.corp.example:58465") let decoded = try CmxPairingQRCode().decode(try components(url)) #expect(decoded.routes == [route]) @@ -113,7 +113,7 @@ import Testing let ticket = try pairingTicket(routes: routes) let url = try #require(CmxPairingQRCode().encode(ticket)) - #expect(url == "\(CmxPairingURLScheme.current)://attach?v=2&r=100.64.0.5:58465&m=192.168.4.12:58465") + #expect(url == "\(CmxPairingURLScheme.current)://attach?v=3&r=100.64.0.5:58465&m=192.168.4.12:58465") let decoded = try CmxPairingQRCode().decode(try components(url)) #expect(decoded.routes == routes) @@ -254,14 +254,28 @@ import Testing } @Test func decodeRejectsManualHostLoopback() throws { - let url = "cmux-ios://attach?v=2&m=127.0.0.1:58465" + let url = "cmux-ios://attach?v=3&m=127.0.0.1:58465" #expect(throws: MobileSyncPairingPayloadError.loopbackRouteRejected) { try CmxPairingQRCode().decode(try components(url)) } } @Test func decodeRejectsManualHostBareColonText() throws { - let url = "cmux-ios://attach?v=2&m=my:host:58465" + let url = "cmux-ios://attach?v=3&m=my:host:58465" + #expect(throws: MobileSyncPairingPayloadError.invalidURL) { + try CmxPairingQRCode().decode(try components(url)) + } + } + + @Test func decodeRejectsManualHostMalformedBrackets() throws { + let url = "cmux-ios://attach?v=3&m=[abc]def]:58465" + #expect(throws: MobileSyncPairingPayloadError.invalidURL) { + try CmxPairingQRCode().decode(try components(url)) + } + } + + @Test func decodeRejectsManualHostInVersionTwoGrammar() throws { + let url = "cmux-ios://attach?v=2&m=studio-mac.local:58465" #expect(throws: MobileSyncPairingPayloadError.invalidURL) { try CmxPairingQRCode().decode(try components(url)) } @@ -331,7 +345,9 @@ import Testing @Test func versionedURLDetectionDistinguishesGrammars() throws { #expect(CmxPairingQRCode().isPairingCodeURLString("cmux-ios://attach?v=2&r=100.64.0.5:58465")) + #expect(CmxPairingQRCode().isPairingCodeURLString("cmux-ios://attach?v=3&m=studio-mac.local:58465")) #expect(!CmxPairingQRCode().isPairingCodeURLString("cmux-ios://attach?v=1&payload=abc")) + #expect(!CmxPairingQRCode().isPairingCodeURLString("cmux-ios://attach?v=4&r=100.64.0.5:58465")) #expect(!CmxPairingQRCode().isPairingCodeURLString("cmux-ios://pair?v=1&payload=abc")) #expect(!CmxPairingQRCode().isPairingCodeURLString("https://example.com?v=2")) #expect(!CmxPairingQRCode().isPairingCodeURLString("not a url")) diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/CmxAttachTicketInput.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/CmxAttachTicketInput.swift index 0fb58d381500..6d6185dbabc7 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/CmxAttachTicketInput.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/CmxAttachTicketInput.swift @@ -16,7 +16,7 @@ public struct CmxAttachTicketInput { /// - Returns: A validated attach ticket. /// - Throws: `MobileSyncPairingPayloadError.invalidURL` or any ticket /// validation error if the input is malformed, or - /// `MobileSyncPairingPayloadError.loopbackRouteRejected` for a v2 + /// `MobileSyncPairingPayloadError.loopbackRouteRejected` for a minimal /// pairing code whose routes point at the phone itself. public static func decode(_ rawValue: String) throws -> CmxAttachTicket { guard let url = URL(string: rawValue) else { @@ -42,8 +42,8 @@ public struct CmxAttachTicketInput { version > CmxPairingQRCode.version { throw MobileSyncPairingPayloadError.unrecognizedURLVersion(version) } - // The minimal v2 pairing-code grammar (bare Tailscale/manual-host - // routes, loopback rejected). v1 URLs carry a base64 JSON `payload` item instead. + // The minimal pairing-code grammar (bare Tailscale/manual-host routes, + // loopback rejected). v1 URLs carry a base64 JSON `payload` item instead. if CmxPairingQRCode().isPairingCodeURL(components) { return try CmxPairingQRCode().decode(components) } diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileHostStatusResponse.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileHostStatusResponse.swift index 115eed888664..81b346530879 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileHostStatusResponse.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileHostStatusResponse.swift @@ -16,7 +16,7 @@ public struct MobileHostStatusResponse: Decodable, Sendable { /// so this is where a freshly paired phone learns what to call the Mac. /// `nil` from older Macs that predate the field. public let macDisplayName: String? - /// The Mac's stable pairing device id. The minimal v2 pairing QR no + /// The Mac's stable pairing device id. The minimal pairing QR no /// longer carries it, so this is where a freshly paired phone learns /// which paired-Mac record the connection belongs to (reconnect-on-launch /// and the host switcher key on it). `nil` from older Macs. diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift index 25507428a0e6..55d4b475b955 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift @@ -31,7 +31,7 @@ public enum MobileShellConnectionError: LocalizedError { case .requestTimedOut: return "Mobile sync request timed out" case .insecureManualRoute: - return "Manual host did not advertise a secure mobile sync route" + return "Manual host route needs approval before mobile sync can send account credentials" case .attachTicketExpired: return "Mobile attach ticket expired" case let .authorizationFailed(message): diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/CmxAttachTicketInputTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/CmxAttachTicketInputTests.swift index a55b6661380b..627aa1f56e06 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/CmxAttachTicketInputTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/CmxAttachTicketInputTests.swift @@ -154,7 +154,7 @@ import Testing } @Test func decodesMinimalPairingCodeURL() throws { - // New-phone-scans-new-QR: the minimal v2 grammar (bare routes, no + // New-phone-scans-new-QR: the minimal v2 Tailscale grammar (bare routes, no // payload blob) routes through the same input decoder as everything // else the scanner or a deep link can hand us. let decoded = try CmxAttachTicketInput.decode( @@ -175,6 +175,20 @@ import Testing #expect(decoded.routes.allSatisfy { $0.kind == .tailscale }) } + @Test func decodesManualHostPairingCodeOnlyInVersionThree() throws { + let decoded = try CmxAttachTicketInput.decode( + "cmux-ios://attach?v=3&ub=user_mac_123&pc=1&m=studio-mac.local:58465" + ) + #expect(decoded.routes.count == 1) + #expect(decoded.routes.first?.kind == .manualHost) + + #expect(throws: MobileSyncPairingPayloadError.invalidURL) { + try CmxAttachTicketInput.decode( + "cmux-ios://attach?v=2&ub=user_mac_123&pc=1&m=studio-mac.local:58465" + ) + } + } + @Test func minimalPairingCodeRejectsLoopback() { // A scanned v2 code must never point the phone at itself. The legacy // v1 payload grammar is intentionally NOT gated: the dev/simulator diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 413b13a89be1..9e84ed514589 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -640,7 +640,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private var terminalEventListenerTask: Task? private var terminalEventListenerID: UUID? /// Recovers the Mac's identity post-handshake for tickets that arrived - /// without one (the minimal v2 pairing QR). Owned separately from the + /// without one (the minimal pairing QR). Owned separately from the /// short capability probe; see ``scheduleHostIdentityAdoptionIfNeeded(client:)``. /// Cancelled on disconnect via ``cancelRemoteOperationTasks()``. private var hostIdentityAdoptionTask: Task? @@ -2892,7 +2892,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } /// Recovers the Mac's identity for a connection whose ticket arrived - /// without a device id (the minimal v2 pairing QR), as its own + /// without a device id (the minimal pairing QR), as its own /// `mobile.host.status` request with the default RPC timeout. /// /// Identity recovery must not depend on the terminal-output capability @@ -7642,8 +7642,8 @@ private extension MobileWorkspacePreview { private extension MobileShellComposite { /// The name shown for the Mac until `mobile.host.status` reports the real /// one: the ticket's display name, then its device id, then the dialed - /// route's host (a minimal v2 pairing code carries neither name nor id, - /// so the Tailscale hostname is the best available placeholder). + /// route's host (a minimal pairing code carries neither name nor id, so the + /// route hostname is the best available placeholder). func placeholderHostName( for ticket: CmxAttachTicket, firstRoute: CmxAttachRoute diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustWarning.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustWarning.swift index 7a1e3f5c732f..766775173127 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustWarning.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustWarning.swift @@ -18,8 +18,13 @@ public struct MobileManualHostTrustWarning: Equatable, Sendable { /// The approved endpoint, formatted for display. public var endpoint: String { - displayHost.contains(":") - ? "[\(displayHost)]:\(scope.port)" - : "\(displayHost):\(scope.port)" + let host = if displayHost.hasPrefix("[") && displayHost.hasSuffix("]") { + String(displayHost.dropFirst().dropLast()) + } else { + displayHost + } + return host.contains(":") + ? "[\(host)]:\(scope.port)" + : "\(host):\(scope.port)" } } diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index d501ee8d85c9..205efee3676c 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -169,6 +169,19 @@ import Testing #expect(!await expiredReader.isTrusted(scope)) } + @Test func manualHostTrustWarningFormatsBracketedIPv6Once() throws { + let scope = try #require(MobileManualHostTrustScope( + host: "[fd00::12]", + port: 58465, + stackUserID: "user-a" + )) + + #expect(MobileManualHostTrustWarning(scope: scope).endpoint == "[fd00::12]:58465") + #expect( + MobileManualHostTrustWarning(scope: scope, displayHost: "[fd00::12]").endpoint == "[fd00::12]:58465" + ) + } + @Test func physicalDeviceRejectsLoopbackTicketsInEveryGrammar() throws { // The v2 QR decoder rejects loopback itself; this policy is what stops // the LEGACY payload grammars from being a bypass on a physical phone, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index cf2b789da4e6..727793cabd2c 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -121,6 +121,7 @@ struct CMUXMobileRootView: View { // workspace list's initial-connection status could never resolve // because nothing updates `didFinishStoredMacReconnectAttempt`. reconnectStoredMacIfNeeded() + showManualHostTrustWarningIfNeeded() } #if os(iOS) // A notification tap can arrive before the workspace (or terminal) it @@ -187,6 +188,9 @@ struct CMUXMobileRootView: View { clearAttachTicketAuthenticationIfNeeded() } } + .onChange(of: store.manualHostTrustWarning) { _, warning in + showManualHostTrustWarningIfNeeded(warning) + } .onChange(of: store.hasActiveUnexpiredAttachTicket) { _, hasActiveUnexpiredAttachTicket in if !hasActiveUnexpiredAttachTicket { clearAttachTicketAuthenticationIfNeeded() @@ -386,6 +390,15 @@ struct CMUXMobileRootView: View { isShowingAddDeviceSheet = true } + private func showManualHostTrustWarningIfNeeded( + _ warning: MobileManualHostTrustWarning? = nil + ) { + guard warning ?? store.manualHostTrustWarning != nil else { + return + } + showAddDevice() + } + private func connectAttachURL(_ rawURL: String) { guard !authManager.isRestoringSession else { pendingAttachURL = rawURL diff --git a/Sources/Mobile/MobileAttachTicketStore.swift b/Sources/Mobile/MobileAttachTicketStore.swift index 4dbf9f1619f8..d55155f439fc 100644 --- a/Sources/Mobile/MobileAttachTicketStore.swift +++ b/Sources/Mobile/MobileAttachTicketStore.swift @@ -129,7 +129,7 @@ final class MobileAttachTicketStore { } private func attachURL(for ticket: CmxAttachTicket) throws -> URL { - // Preferred form: the minimal v2 pairing-code grammar — bare Tailscale + // Preferred form: the minimal pairing-code grammar — bare Tailscale // and manual-host `host:port` routes in the URL query. Everything the // older grammars carried has a better channel: the auth token never // authorized anything (the owner's Stack access token is the host's diff --git a/Sources/Mobile/MobileHostService+ManualHostRoutes.swift b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift index 1e632cabf0f0..dba7a37abc02 100644 --- a/Sources/Mobile/MobileHostService+ManualHostRoutes.swift +++ b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift @@ -17,22 +17,58 @@ extension MobileHostService { return host } + nonisolated static func manualHostNeedsRouteRefresh(previous: String?, current: String?) -> Bool { + previous != current + } + func currentRoutes(port: Int) -> [CmxAttachRoute] { - routeResolver.routes(port: port, manualHost: Self.configuredManualHost()).routes + currentRoutes(port: port, manualHost: Self.configuredManualHost()) + } + + func currentRoutes(port: Int, manualHost: String?) -> [CmxAttachRoute] { + routeResolver.routes(port: port, manualHost: manualHost).routes } func currentRoutes(port: Int, tailscaleHosts: [String]) -> [CmxAttachRoute] { + currentRoutes(port: port, tailscaleHosts: tailscaleHosts, manualHost: Self.configuredManualHost()) + } + + func currentRoutes(port: Int, tailscaleHosts: [String], manualHost: String?) -> [CmxAttachRoute] { routeResolver.routes( port: port, tailscaleHosts: tailscaleHosts, - manualHost: Self.configuredManualHost() + manualHost: manualHost ).routes } - func refreshAdvertisedRoutesIfRunning() { + func publishCurrentRoutes(port: Int) { + let manualHost = Self.configuredManualHost() + advertisedManualHost = manualHost + MobileHostPublicStatusCache.update(routes: currentRoutes(port: port, manualHost: manualHost)) + } + + func publishCurrentRoutes(port: Int, tailscaleHosts: [String]) { + let manualHost = Self.configuredManualHost() + advertisedManualHost = manualHost + MobileHostPublicStatusCache.update( + routes: currentRoutes(port: port, tailscaleHosts: tailscaleHosts, manualHost: manualHost) + ) + } + + func clearAdvertisedRoutes() { + advertisedManualHost = nil + MobileHostPublicStatusCache.update(routes: []) + } + + func refreshAdvertisedRoutesIfRunning(defaults: UserDefaults = .standard) { guard let listenerPort else { return } - MobileHostPublicStatusCache.update(routes: currentRoutes(port: listenerPort)) + let manualHost = Self.configuredManualHost(defaults: defaults) + guard Self.manualHostNeedsRouteRefresh(previous: advertisedManualHost, current: manualHost) else { + return + } + advertisedManualHost = manualHost + MobileHostPublicStatusCache.update(routes: currentRoutes(port: listenerPort, manualHost: manualHost)) } } diff --git a/Sources/Mobile/MobileHostService.swift b/Sources/Mobile/MobileHostService.swift index 9de9c0c079cd..f967a08a9f24 100644 --- a/Sources/Mobile/MobileHostService.swift +++ b/Sources/Mobile/MobileHostService.swift @@ -378,6 +378,7 @@ final class MobileHostService { /// ephemeral fallback). Used to decide whether a settings change needs a /// restart. `nil` while stopped. private var appliedPreferredPort: Int? + var advertisedManualHost: String? private var activeConnections: [UUID: MobileHostConnection] = [:] private var clientIDsByConnectionID: [UUID: Set] = [:] private var lastErrorDescription: String? @@ -712,7 +713,7 @@ final class MobileHostService { self?.updatePublicStatusRoutes(port: port, generation: generation, tailscaleHosts: hosts) } }) - MobileHostPublicStatusCache.update(routes: currentRoutes(port: port)) + publishCurrentRoutes(port: port) startNetworkPathMonitorIfNeeded() drainReadinessWaiters() } @@ -749,7 +750,7 @@ final class MobileHostService { listenerPort = port appliedPreferredPort = port lastErrorDescription = nil - MobileHostPublicStatusCache.update(routes: currentRoutes(port: port)) + publishCurrentRoutes(port: port) mobileHostLog.info("mobile host listener disabled; publishing XCTest routes without binding") } #endif @@ -828,7 +829,7 @@ final class MobileHostService { activeConnections.removeAll() clientIDsByConnectionID.removeAll() MobileHostEventSubscriptionTracker.reset() - MobileHostPublicStatusCache.update(routes: []) + clearAdvertisedRoutes() TerminalController.shared.clearAllMobileViewportReports(reason: "mobile.host.stopped") drainReadinessWaiters() } @@ -959,7 +960,7 @@ final class MobileHostService { appliedPort: appliedPreferredPort ) { case .noop: - refreshAdvertisedRoutesIfRunning() + refreshAdvertisedRoutesIfRunning(defaults: defaults) case .start: start() case .stop: @@ -1534,9 +1535,9 @@ final class MobileHostService { ) } }) - MobileHostPublicStatusCache.update(routes: currentRoutes(port: listenerPort)) + publishCurrentRoutes(port: listenerPort) } else { - MobileHostPublicStatusCache.update(routes: []) + clearAdvertisedRoutes() } mobileHostLog.info("mobile host listener ready on port \(self.listenerPort ?? 0)") drainReadinessWaiters() @@ -1547,7 +1548,7 @@ final class MobileHostService { listener = nil listenerUsesEphemeralFallback = false listenerPort = nil - MobileHostPublicStatusCache.update(routes: []) + clearAdvertisedRoutes() drainReadinessWaiters() case let .waiting(error): // A preferred-port bind blocked by another listener surfaces as @@ -1558,11 +1559,11 @@ final class MobileHostService { handleListenerBindFailure(error: error, context: "in use (waiting)") } else { listenerPort = nil - MobileHostPublicStatusCache.update(routes: []) + clearAdvertisedRoutes() } case .setup: listenerPort = nil - MobileHostPublicStatusCache.update(routes: []) + clearAdvertisedRoutes() @unknown default: break } @@ -1573,7 +1574,7 @@ final class MobileHostService { /// Shared by the `.failed` and `.waiting(addressUnavailable)` paths. private func handleListenerBindFailure(error: NWError, context: String) { lastErrorDescription = String(describing: error) - MobileHostPublicStatusCache.update(routes: []) + clearAdvertisedRoutes() let shouldRetryWithEphemeralPort = !listenerUsesEphemeralFallback listener?.stateUpdateHandler = nil listener?.newConnectionHandler = nil @@ -1601,9 +1602,7 @@ final class MobileHostService { guard generation == listenerGeneration, listenerPort == port else { return } - MobileHostPublicStatusCache.update( - routes: currentRoutes(port: port, tailscaleHosts: tailscaleHosts) - ) + publishCurrentRoutes(port: port, tailscaleHosts: tailscaleHosts) } // MARK: - Network path monitoring @@ -1649,7 +1648,7 @@ final class MobileHostService { self?.updatePublicStatusRoutes(port: port, generation: generation, tailscaleHosts: hosts) } }) - MobileHostPublicStatusCache.update(routes: currentRoutes(port: port)) + publishCurrentRoutes(port: port) } } @@ -1660,6 +1659,7 @@ extension MobileHostService { listenerGeneration = UUID() listenerUsesEphemeralFallback = false listenerPort = nil + advertisedManualHost = nil activeConnections.removeAll() clientIDsByConnectionID.removeAll() MobileHostRequestActivity.resetForTesting() diff --git a/Sources/Mobile/Pairing/MobilePairingModel.swift b/Sources/Mobile/Pairing/MobilePairingModel.swift index fbd9e6ed0947..6b211f347f50 100644 --- a/Sources/Mobile/Pairing/MobilePairingModel.swift +++ b/Sources/Mobile/Pairing/MobilePairingModel.swift @@ -84,7 +84,7 @@ final class MobilePairingModel { /// `MobileHostService.shared` is main-actor isolated.) /// - ticketTTL: Lifetime of the minted attach token in seconds. Defaults /// to 600. Covers only the RPC/v1 fallback token the mint produces as a - /// side effect; the displayed v2 pairing QR carries no token and never + /// side effect; the displayed pairing QR carries no token and never /// expires. init(host: MobileHostService? = nil, ticketTTL: TimeInterval = 600) { self.host = host ?? .shared @@ -155,7 +155,7 @@ final class MobilePairingModel { ) return } - // Only the minimal v2 grammar (Tailscale/manual-host routes only, + // Only the minimal QR grammar (Tailscale/manual-host routes only, // no loopback, no token) may ever be displayed as a scannable code. // If the mint raced a route loss and fell back to the v1 payload, // show route guidance rather than a weak QR. diff --git a/cmuxTests/MobileHostServiceSettingsTests.swift b/cmuxTests/MobileHostServiceSettingsTests.swift index b49f48f531ba..ccb4aa4f2b74 100644 --- a/cmuxTests/MobileHostServiceSettingsTests.swift +++ b/cmuxTests/MobileHostServiceSettingsTests.swift @@ -71,6 +71,28 @@ struct MobileHostServiceSettingsTests { #expect(MobileHostService.resolvedDesiredPort(defaults: defaults) == nil) } + @Test func manualHostRouteRefreshOnlyWhenNormalizedValueChanges() throws { + let suiteName = "MobileHostServiceSettingsTests.ManualHost.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + #expect(MobileHostService.configuredManualHost(defaults: defaults) == nil) + defaults.set(" studio-mac.corp.example ", forKey: MobileHostService.manualHostDefaultsKey) + #expect(MobileHostService.configuredManualHost(defaults: defaults) == "studio-mac.corp.example") + #expect(MobileHostService.manualHostNeedsRouteRefresh(previous: nil, current: "studio-mac.corp.example")) + #expect(!MobileHostService.manualHostNeedsRouteRefresh( + previous: "studio-mac.corp.example", + current: "studio-mac.corp.example" + )) + #expect(MobileHostService.manualHostNeedsRouteRefresh( + previous: "studio-mac.corp.example", + current: nil + )) + + defaults.set("my:host", forKey: MobileHostService.manualHostDefaultsKey) + #expect(MobileHostService.configuredManualHost(defaults: defaults) == nil) + } + @Test func portApplyPreBindClassifiesNonBindCases() { // Out of range → invalid, regardless of anything else. #expect(MobileHostService.portApplyPreBindOutcome(enabled: true, currentBoundPort: nil, requestedPort: 0) == .invalid) diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 65d00a62ae7c..28d2cea06a32 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -1881,7 +1881,7 @@ final class TerminalOutputCollector { ) let trustStore = InMemoryMobileManualHostTrustStore() let store = CMUXMobileShellStore.preview(runtime: runtime, manualHostTrustStore: trustStore) - let url = "cmux-ios://attach?v=2&pc=1&m=studio-mac.local:61234" + let url = "cmux-ios://attach?v=3&pc=1&m=studio-mac.local:61234" store.signIn() let firstResult = await store.connectPairingURLResult(url) @@ -1919,7 +1919,7 @@ final class TerminalOutputCollector { runtime: runtime, manualHostTrustStore: InMemoryMobileManualHostTrustStore() ) - let url = "cmux-ios://attach?v=2&pc=1&r=100.71.210.41:61234&m=studio-mac.local:61234" + let url = "cmux-ios://attach?v=3&pc=1&r=100.71.210.41:61234&m=studio-mac.local:61234" store.signIn() let result = await store.connectPairingURLResult(url) From 5560ec75fe458c1925135ba73091839751652d2a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 22:06:36 -0700 Subject: [PATCH 05/91] Tighten manual host edge cases --- .../MobileShellComposite+ManualHostTrust.swift | 2 +- .../MobileShellComposite+RouteSelection.swift | 18 +++++++++++++----- .../ReconnectRouteSelectionTests.swift | 3 +++ .../MobileManualHostTrustScope.swift | 2 +- .../MobileShellRouteAuthPolicyTests.swift | 12 ++++++++++++ 5 files changed, 30 insertions(+), 7 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 447389a07427..5513f803cc7a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -82,8 +82,8 @@ extension MobileShellComposite { clearManualHostTrustWarning() return .failed } - await manualHostTrustStore.trust(warning.scope) clearManualHostTrustWarning() + await manualHostTrustStore.trust(warning.scope) switch pending { case let .manual(name, host, port, pairedMacDeviceID, recordsPairingAttempt, ifStillCurrent): await connectManualHost( diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift index 9854f9115407..3eb898d381ba 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift @@ -1,5 +1,6 @@ import CMUXMobileCore import CmuxMobileShellModel +import Darwin import Foundation @MainActor @@ -69,12 +70,19 @@ extension MobileShellComposite { /// that needs DNS resolution. Used to prefer directly-dialable IP routes over /// MagicDNS hostnames, which fail to resolve on some clients. static func isIPLiteralHost(_ host: String) -> Bool { - if host.contains(":") { return true } - let octets = host.split(separator: ".", omittingEmptySubsequences: false) - return octets.count == 4 && octets.allSatisfy { part in - guard let value = Int(part), (0...255).contains(value), !part.isEmpty else { return false } - return String(value) == part + let trimmed = host.trimmingCharacters(in: .whitespacesAndNewlines) + let unbracketed = if trimmed.hasPrefix("[") && trimmed.hasSuffix("]") { + String(trimmed.dropFirst().dropLast()) + } else { + trimmed } + + var ipv4 = in_addr() + if unbracketed.withCString({ inet_pton(AF_INET, $0, &ipv4) }) == 1 { + return true + } + var ipv6 = in6_addr() + return unbracketed.withCString { inet_pton(AF_INET6, $0, &ipv6) } == 1 } /// `true` on a physical iPhone/iPad; `false` in the simulator and in diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index 05d21a1e1ae0..5a284bdd6bef 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -100,8 +100,11 @@ import Testing #expect(MobileShellComposite.isIPLiteralHost("100.82.214.112")) #expect(MobileShellComposite.isIPLiteralHost("127.0.0.1")) #expect(MobileShellComposite.isIPLiteralHost("fd7a:115c:a1e0::4b36:d670")) + #expect(MobileShellComposite.isIPLiteralHost("::ffff:192.168.0.1")) + #expect(MobileShellComposite.isIPLiteralHost("[fd7a:115c:a1e0::4b36:d670]")) #expect(!MobileShellComposite.isIPLiteralHost("lawrences-macbook-pro-2.tail137216.ts.net")) #expect(!MobileShellComposite.isIPLiteralHost("example.com")) + #expect(!MobileShellComposite.isIPLiteralHost("my:host")) #expect(!MobileShellComposite.isIPLiteralHost("100.82.214")) // too few octets #expect(!MobileShellComposite.isIPLiteralHost("256.1.1.1")) // out of range } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift index 5288f18e0a66..cd7374da1cda 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift @@ -60,7 +60,7 @@ public struct MobileManualHostTrustScope: Equatable, Hashable, Sendable { return manualHost } let trimmed = host.trimmingCharacters(in: .whitespacesAndNewlines) - let ipv6Characters = CharacterSet(charactersIn: "0123456789abcdefABCDEF:") + let ipv6Characters = CharacterSet(charactersIn: "0123456789abcdefABCDEF:.") guard trimmed.contains(":"), trimmed.unicodeScalars.allSatisfy({ ipv6Characters.contains($0) }) else { return nil diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index 205efee3676c..bb5c2e3369f4 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -121,13 +121,25 @@ import Testing port: 58465, stackUserID: "user-a" )) + let ipv4MappedIPv6 = try #require(MobileManualHostTrustScope( + host: "::ffff:192.168.0.1", + port: 58465, + stackUserID: "user-a" + )) + let bracketedIPv4MappedIPv6 = try #require(MobileManualHostTrustScope( + host: "[::ffff:192.168.0.1]", + port: 58465, + stackUserID: "user-a" + )) #expect(!await store.isTrusted(approved)) await store.trust(approved) await store.trust(normalizedIPv6) + await store.trust(ipv4MappedIPv6) #expect(await store.isTrusted(sameHostDifferentCase)) #expect(await store.isTrusted(bracketedIPv6)) + #expect(await store.isTrusted(bracketedIPv4MappedIPv6)) #expect(!await store.isTrusted(differentPort)) #expect(!await store.isTrusted(differentAccount)) } From 4f0ac49d81f0e5e4a730de1751275bacca0e00e2 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 22:08:58 -0700 Subject: [PATCH 06/91] Address manual host validation feedback --- .../UserDefaultsMobileManualHostTrustStore.swift | 13 ++++++++++++- .../CmuxSettingsUI/Sections/MobileSection.swift | 13 ++++++++++++- .../SettingsRowAnchorResolutionTests.swift | 11 +++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift index 2ca76b3086d8..aaa21a5c13ec 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -1,4 +1,7 @@ import Foundation +import OSLog + +private let manualHostTrustStoreLog = Logger(subsystem: "com.cmuxterm.app", category: "ManualHostTrust") /// UserDefaults-backed manual-host trust store for production. public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStoring { @@ -40,7 +43,15 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin trustDuration: TimeInterval = Self.defaultTrustDuration, now: @escaping @Sendable () -> Date = { Date() } ) { - self.defaults = UserDefaults(suiteName: suiteName) ?? .standard + if let suiteDefaults = UserDefaults(suiteName: suiteName) { + self.defaults = suiteDefaults + } else { + assertionFailure("Failed to resolve UserDefaults suite \(suiteName); falling back to .standard") + manualHostTrustStoreLog.error( + "failed to resolve UserDefaults suite \(suiteName, privacy: .public); falling back to standard defaults" + ) + self.defaults = .standard + } self.key = key self.trustDuration = trustDuration self.now = now diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift index c20e8f5cd834..8ab70fd042f2 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift @@ -73,7 +73,18 @@ public struct MobileSection: View { } private var isManualHostValid: Bool { - trimmedManualHost.isEmpty || CmxManualHost(trimmedManualHost) != nil + Self.isManualHostAdvertisable(trimmedManualHost) + } + + nonisolated static func isManualHostAdvertisable(_ rawHost: String) -> Bool { + let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { + return true + } + guard let host = CmxManualHost(trimmed) else { + return false + } + return !CmxLoopbackHost().matches(host.rawValue) } /// The Mobile settings section content. diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift index 38535e24f10b..a70ae276130f 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift @@ -18,6 +18,17 @@ import Testing /// single key). Together they must cover every curated setting entry. @Suite("SettingsRowAnchorResolution") struct SettingsRowAnchorResolutionTests { + @Test func mobileManualHostAdvertisableValidatorRejectsLoopback() { + #expect(MobileSection.isManualHostAdvertisable("")) + #expect(MobileSection.isManualHostAdvertisable(" 192.168.1.23 ")) + #expect(MobileSection.isManualHostAdvertisable("studio-mac.local")) + #expect(MobileSection.isManualHostAdvertisable("[fd00::12]")) + #expect(!MobileSection.isManualHostAdvertisable("127.0.0.1")) + #expect(!MobileSection.isManualHostAdvertisable("localhost")) + #expect(!MobileSection.isManualHostAdvertisable("[::1]")) + #expect(!MobileSection.isManualHostAdvertisable("my:host")) + } + /// Every singular cmux.json path declared by an *unconditionally /// rendered* settings row. Excludes rows that aren't standalone search /// results: `workspaceColors.colors` (repeated per-palette rows) and From affae04d901848870c6fe76414ea12a255b4c502 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 22:13:16 -0700 Subject: [PATCH 07/91] Keep mobile root view within line budget --- .../CMUXMobileRootView+PairingWarnings.swift | 10 ++++++++++ .../CmuxMobileShellUI/CMUXMobileRootView.swift | 11 +---------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift index da8d5d3db2d7..d4d8b82bac80 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift @@ -1,6 +1,16 @@ import CmuxMobileShell +import CmuxMobileShellModel extension CMUXMobileRootView { + func showManualHostTrustWarningIfNeeded( + _ warning: MobileManualHostTrustWarning? = nil + ) { + guard warning ?? store.manualHostTrustWarning != nil else { + return + } + showAddDevice() + } + func acceptPairingVersionWarning() async { let result = await store.acceptPairingVersionWarning() clearAttachTicketAuthentication(after: result) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 727793cabd2c..eb8f1a31f8f5 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -383,22 +383,13 @@ struct CMUXMobileRootView: View { } } - private func showAddDevice() { + func showAddDevice() { #if os(iOS) addDeviceSheetDetent = .large #endif isShowingAddDeviceSheet = true } - private func showManualHostTrustWarningIfNeeded( - _ warning: MobileManualHostTrustWarning? = nil - ) { - guard warning ?? store.manualHostTrustWarning != nil else { - return - } - showAddDevice() - } - private func connectAttachURL(_ rawURL: String) { guard !authManager.isRestoringSession else { pendingAttachURL = rawURL From 8c305ce1cac4499abea92f1c84b5aaa59f52851e Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 22:21:18 -0700 Subject: [PATCH 08/91] Tighten trusted manual host route safety --- .../MobileShellComposite+RouteSelection.swift | 16 +++++++++----- .../ReconnectRouteSelectionTests.swift | 18 +++++++++++++++ .../MobileShellRouteAuthPolicy.swift | 22 +++++-------------- .../MobileShellRouteAuthPolicyTests.swift | 13 +++++++++++ 4 files changed, 47 insertions(+), 22 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift index 3eb898d381ba..973e1dbdfcd4 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift @@ -49,15 +49,19 @@ extension MobileShellComposite { return nil } if preferNonLoopback { - // Among non-loopback routes, prefer one whose host is a numeric IP: a - // raw tailscale/LAN IP is dialable without DNS, whereas a MagicDNS - // hostname depends on the client having tailscale DNS active. - if let ip = firstHostPort(where: { route in - guard route.kind != .debugLoopback, + // Prefer a Tailscale numeric IP over MagicDNS because it dials + // without client DNS. Keep encrypted Tailscale routes ahead of + // explicit plaintext manual-host fallbacks even when the manual + // host is also a numeric IP. + if let tailscaleIP = firstHostPort(where: { route in + guard route.kind == .tailscale, case let .hostPort(host, _) = route.endpoint else { return false } return Self.isIPLiteralHost(host) }) { - return ip + return tailscaleIP + } + if let tailscale = firstHostPort(where: { $0.kind == .tailscale }) { + return tailscale } if let real = firstHostPort(where: { $0.kind != .debugLoopback }) { return real diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index 5a284bdd6bef..68759810da21 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -27,6 +27,15 @@ import Testing ) } + private func manualHost(_ port: Int = 50906) throws -> CmxAttachRoute { + try CmxAttachRoute( + id: "manual_host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: port), + priority: 2 + ) + } + @Test func physicalDevicePrefersRealRouteOverLowerPriorityLoopback() throws { let pick = MobileShellComposite.firstReconnectHostPortRoute( [try loopback(), try tailscale()], @@ -96,6 +105,15 @@ import Testing #expect(pick?.0 == "lawrences-macbook-pro-2.tail137216.ts.net") } + @Test func tailscaleDNSBeatsManualHostIPFallback() throws { + let pick = MobileShellComposite.firstReconnectHostPortRoute( + [try loopback(50922), try manualHost(50922), try magicDNS(50922)], + supportedKinds: [.debugLoopback, .manualHost, .tailscale], + preferNonLoopback: true + ) + #expect(pick?.0 == "lawrences-macbook-pro-2.tail137216.ts.net") + } + @Test func ipLiteralHostClassification() { #expect(MobileShellComposite.isIPLiteralHost("100.82.214.112")) #expect(MobileShellComposite.isIPLiteralHost("127.0.0.1")) diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift index f2b351df00a7..6f610f566d1b 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift @@ -54,7 +54,7 @@ public struct MobileShellRouteAuthPolicy { /// `*.ts.net` MagicDNS host), which rides the WireGuard-encrypted tunnel. /// - `.iroh` to a peer, which is an encrypted QUIC connection. /// - `.debugLoopback` to a loopback host, which never leaves the machine. - /// - `.manualHost` to a host/port that has a persisted user approval. + /// - `.manualHost` to a non-loopback host/port that has a persisted user approval. /// /// Plain private-LAN (`192.168/16`, `10/8`, `172.16/12`, link-local) and /// `.local`/Bonjour hosts are deliberately **excluded**: they are dialed over @@ -76,8 +76,8 @@ public struct MobileShellRouteAuthPolicy { return isLoopbackHost(host) case (.tailscale, let .hostPort(host, _)): return isTailscaleHost(host) - case (.manualHost, .hostPort): - return manualHostTrusted + case (.manualHost, let .hostPort(host, _)): + return manualHostTrusted && !isLoopbackHost(host) case (.iroh, .peer): return true default: @@ -90,10 +90,10 @@ public struct MobileShellRouteAuthPolicy { /// - Returns: `true` only for `.manualHost` host/port routes. public static func routeRequiresManualHostTrust(_ route: CmxAttachRoute) -> Bool { guard route.kind == .manualHost, - case .hostPort = route.endpoint else { + case let .hostPort(host, _) = route.endpoint else { return false } - return true + return !isLoopbackHost(host) } /// Whether a decoded pairing/attach ticket must be rejected because its @@ -161,17 +161,7 @@ public struct MobileShellRouteAuthPolicy { } private static func isLoopbackHost(_ host: String) -> Bool { - let normalizedHost = host.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - return normalizedHost == "localhost" || - normalizedHost == "::1" || - isIPv4LoopbackHost(normalizedHost) - } - - private static func isIPv4LoopbackHost(_ host: String) -> Bool { - guard let octets = ipv4Octets(host) else { - return false - } - return octets[0] == 127 + CmxLoopbackHost().matches(host) } private static func isTailscaleHost(_ host: String) -> Bool { diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index bb5c2e3369f4..bbadca80dc20 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -59,8 +59,14 @@ import Testing ) let manualHostRoute = try hostPortRoute(kind: .manualHost, host: "192.168.1.77", port: CmxMobileDefaults.defaultHostPort) + let manualLoopbackAlias = try hostPortRoute(kind: .manualHost, host: "127.1", port: CmxMobileDefaults.defaultHostPort) + let manualUnspecifiedIPv4 = try hostPortRoute(kind: .manualHost, host: "0.0.0.0", port: CmxMobileDefaults.defaultHostPort) + let manualHexLoopback = try hostPortRoute(kind: .manualHost, host: "0x7f.0.0.1", port: CmxMobileDefaults.defaultHostPort) #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "127.0.0.1") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "127.1") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "0.0.0.0") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "0x7f.0.0.1") == .debugLoopback) #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "[::1]") == .debugLoopback) #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "100.71.210.41") == .tailscale) #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "work-mac.tailnet.ts.net") == .tailscale) @@ -74,6 +80,9 @@ import Testing #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(irohPeer)) #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualHostRoute)) #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualHostRoute, manualHostTrusted: true)) + #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualLoopbackAlias, manualHostTrusted: true)) + #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualUnspecifiedIPv4, manualHostTrusted: true)) + #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualHexLoopback, manualHostTrusted: true)) // Plaintext-TCP routes must NOT carry the Stack bearer token by default: // a `.tailscale` route to a private-LAN IP or a `.local`/Bonjour host is @@ -81,8 +90,12 @@ import Testing #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(lanIP)) #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(localDNS)) #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(pretendLoopback)) + #expect(!MobileShellRouteAuthPolicy.routeRequiresManualHostTrust(manualLoopbackAlias)) #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("127.0.0.1")) + #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("127.1")) + #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("0.0.0.0")) + #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("0x7f.0.0.1")) #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("100.71.210.41")) #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("work-mac.tailnet.ts.net")) #expect(MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("192.168.1.77")) From f79692894a2a9b1e9ed74f08ae6d714d96c0033a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 22:25:33 -0700 Subject: [PATCH 09/91] Reject loopback manual host advertisements --- .../MobileHostService+ManualHostRoutes.swift | 3 ++- Sources/Mobile/MobileRouteResolver.swift | 3 ++- .../MobileHostServiceSettingsTests.swift | 23 +++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/Sources/Mobile/MobileHostService+ManualHostRoutes.swift b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift index dba7a37abc02..378e49eb175a 100644 --- a/Sources/Mobile/MobileHostService+ManualHostRoutes.swift +++ b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift @@ -11,7 +11,8 @@ extension MobileHostService { /// or `nil` when unset or invalid. nonisolated static func configuredManualHost(defaults: UserDefaults = .standard) -> String? { guard let raw = defaults.object(forKey: manualHostDefaultsKey) as? String, - let host = CmxManualHost(raw)?.rawValue else { + let host = CmxManualHost(raw)?.rawValue, + !CmxLoopbackHost().matches(host) else { return nil } return host diff --git a/Sources/Mobile/MobileRouteResolver.swift b/Sources/Mobile/MobileRouteResolver.swift index 3c9e39a76990..73117edf5119 100644 --- a/Sources/Mobile/MobileRouteResolver.swift +++ b/Sources/Mobile/MobileRouteResolver.swift @@ -99,7 +99,8 @@ final class MobileRouteResolver: @unchecked Sendable { } } - if let manualHost = manualHost.flatMap({ CmxManualHost($0)?.rawValue }) { + if let manualHost = manualHost.flatMap({ CmxManualHost($0)?.rawValue }), + !CmxLoopbackHost().matches(manualHost) { let manualPriority = 10 + (tailscaleHosts.count * 10) if let manualRoute = try? CmxAttachRoute( id: CmxAttachTransportKind.manualHost.rawValue, diff --git a/cmuxTests/MobileHostServiceSettingsTests.swift b/cmuxTests/MobileHostServiceSettingsTests.swift index ccb4aa4f2b74..244d52c4d931 100644 --- a/cmuxTests/MobileHostServiceSettingsTests.swift +++ b/cmuxTests/MobileHostServiceSettingsTests.swift @@ -1,3 +1,4 @@ +import CMUXMobileCore import CmuxSettings import Foundation import Testing @@ -93,6 +94,28 @@ struct MobileHostServiceSettingsTests { #expect(MobileHostService.configuredManualHost(defaults: defaults) == nil) } + @Test(arguments: ["127.0.0.1", "127.1", "0.0.0.0", "localhost", "[::1]"]) + func configuredManualHostRejectsLoopbackHosts(rawHost: String) throws { + let suiteName = "MobileHostServiceSettingsTests.ManualHost.Loopback.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + defaults.set(rawHost, forKey: MobileHostService.manualHostDefaultsKey) + + #expect(MobileHostService.configuredManualHost(defaults: defaults) == nil) + } + + @Test func routeResolverDoesNotAdvertiseLoopbackManualHost() { + let routes = MobileRouteResolver().routes( + port: 58_465, + tailscaleHosts: ["100.82.214.112"], + manualHost: "127.1" + ).routes + + #expect(routes.contains { $0.kind == .tailscale }) + #expect(!routes.contains { $0.kind == .manualHost }) + } + @Test func portApplyPreBindClassifiesNonBindCases() { // Out of range → invalid, regardless of anything else. #expect(MobileHostService.portApplyPreBindOutcome(enabled: true, currentBoundPort: nil, requestedPort: 0) == .invalid) From c7171dd2b93616d21796dbfb6dddbb9258e59168 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 22:41:08 -0700 Subject: [PATCH 10/91] Align manual host validation with pairing QR --- .../CMUXMobileCore/CmxManualHost.swift | 33 ++++++++++++++++--- .../CmxManualHostTests.swift | 3 ++ .../MobileShellComposite.swift | 1 + .../cmuxFeatureTests/cmuxFeatureTests.swift | 28 ++++++++++++++++ 4 files changed, 60 insertions(+), 5 deletions(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift index a0e54f5024e9..63f2fbc9f8e1 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift @@ -1,3 +1,4 @@ +import Darwin import Foundation /// A normalized user-entered host for explicit manual mobile pairing routes. @@ -5,8 +6,8 @@ import Foundation /// Manual hosts are DNS names or IP literals that a user deliberately chooses /// outside automatic Tailscale discovery. The value is only a host, never a URL: /// schemes, paths, query/fragment markers, user-info markers, bare colon host -/// text, whitespace, and control characters are rejected before the host is -/// advertised or dialed. +/// text, non-QR-safe characters, whitespace, and control characters are rejected +/// before the host is advertised or dialed. public struct CmxManualHost: Equatable, Sendable { /// The normalized bare host, with IPv6 brackets removed when present. public let rawValue: String @@ -35,15 +36,37 @@ public struct CmxManualHost: Equatable, Sendable { host = trimmed isBracketedHost = false } - let forbiddenCharacters = isBracketedHost ? "/?#@[]" : "/?#@[]:" - guard !host.isEmpty, host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil, host.rangeOfCharacter(from: .controlCharacters) == nil, - host.rangeOfCharacter(from: CharacterSet(charactersIn: forbiddenCharacters)) == nil, host.range(of: "://") == nil else { return nil } + if isBracketedHost { + guard Self.isIPv6Literal(host) else { + return nil + } + } else { + guard Self.isUnbracketedQRHost(host) else { + return nil + } + } self.rawValue = host } + + private static func isUnbracketedQRHost(_ host: String) -> Bool { + host.utf8.allSatisfy { byte in + (48...57).contains(byte) // 0-9 + || (65...90).contains(byte) // A-Z + || (97...122).contains(byte) // a-z + || byte == UInt8(ascii: ".") + || byte == UInt8(ascii: "-") + || byte == UInt8(ascii: "_") + } + } + + private static func isIPv6Literal(_ host: String) -> Bool { + var address = in6_addr() + return host.withCString { inet_pton(AF_INET6, $0, &address) } == 1 + } } diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift index b92f2a82c5b2..ceae950a5a60 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift @@ -17,8 +17,11 @@ import Testing #expect(CmxManualHost("[fd00::12]")?.rawValue == "fd00::12") #expect(CmxManualHost("https://studio-mac.corp.example") == nil) #expect(CmxManualHost("studio-mac.corp.example/path") == nil) + #expect(CmxManualHost("studio!mac.local") == nil) #expect(CmxManualHost("my:host") == nil) #expect(CmxManualHost("fd00::12") == nil) + #expect(CmxManualHost("[my:host]") == nil) + #expect(CmxManualHost("[studio-mac.local]") == nil) #expect(CmxManualHost("[abc]def]") == nil) #expect(CmxManualHost("studio]mac") == nil) #expect(CmxManualHost("studio mac") == nil) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 9e84ed514589..dae0212e797b 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -3063,6 +3063,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } clearPairingError() clearPairingVersionWarning() + clearManualHostTrustWarning() let ticket: CmxAttachTicket do { ticket = try CmxAttachTicketInput.decode(rawURL) diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 28d2cea06a32..868ac4540b4f 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -1907,6 +1907,34 @@ final class TerminalOutputCollector { }) } +@MainActor +@Test func newPairingValidationClearsStaleManualHostTrustWarning() async throws { + let responses = ScriptedTransportResponses([]) + let runtime = testRuntime( + supportedRouteKinds: [.manualHost], + transportFactory: ScriptedTransportFactory(responses: responses), + stackAccessToken: "stack-token-for-stale-manual-warning" + ) + let store = CMUXMobileShellStore.preview( + runtime: runtime, + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + + store.signIn() + let firstResult = await store.connectPairingURLResult( + "cmux-ios://attach?v=3&pc=1&m=studio-mac.local:61234" + ) + let secondResult = await store.connectPairingURLResult("not a cmux pairing url") + let staleApprovalResult = await store.acceptManualHostTrustWarning() + + #expect(firstResult == .needsUserApproval) + #expect(secondResult == .failed) + #expect(staleApprovalResult == .failed) + #expect(store.manualHostTrustWarning == nil) + #expect(store.connectionState == .disconnected) + #expect(try await responses.sentRequests().isEmpty) +} + @MainActor @Test func mixedPairingQRCodeBlocksManualFallbackUntilApproved() async throws { let responses = ScriptedTransportResponses([]) From 43c3e2aac53195fa8560d4b973c2876095b4474d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 2 Jul 2026 23:04:56 -0700 Subject: [PATCH 11/91] Preserve normalized IPv6 manual hosts --- .../CMUXMobileCore/CmxManualHost.swift | 19 ++++++++++ .../CmxManualHostTests.swift | 8 ++++ ...leShellComposite+PairedMacCoalescing.swift | 2 +- .../MobileShellComposite.swift | 8 ++-- .../MobileShellRouteAuthPolicy.swift | 10 ++++- Sources/Mobile/MobileRouteResolver.swift | 2 +- .../MobileHostServiceSettingsTests.swift | 19 ++++++++++ .../cmuxFeatureTests/cmuxFeatureTests.swift | 38 +++++++++++++++++++ 8 files changed, 99 insertions(+), 7 deletions(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift index 63f2fbc9f8e1..6ba0002ac516 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift @@ -54,6 +54,25 @@ public struct CmxManualHost: Equatable, Sendable { self.rawValue = host } + /// Normalizes a host that may already be in attach-route endpoint form. + /// + /// User-entered IPv6 must be bracketed so a typo like `my:host` is rejected + /// up front. Attach routes store IPv6 without brackets, so route/reconnect + /// paths use this helper when they are validating an already-normalized + /// endpoint host. + public static func normalizedRouteHost(_ rawHost: String) -> String? { + if let manualHost = CmxManualHost(rawHost) { + return manualHost.rawValue + } + let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.hasPrefix("["), + !trimmed.hasSuffix("]"), + Self.isIPv6Literal(trimmed) else { + return nil + } + return trimmed + } + private static func isUnbracketedQRHost(_ host: String) -> Bool { host.utf8.allSatisfy { byte in (48...57).contains(byte) // 0-9 diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift index ceae950a5a60..49c25ae9723e 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift @@ -26,3 +26,11 @@ import Testing #expect(CmxManualHost("studio]mac") == nil) #expect(CmxManualHost("studio mac") == nil) } + +@Test func manualHostRouteNormalizerAcceptsAlreadyNormalizedIPv6() { + #expect(CmxManualHost.normalizedRouteHost("[fd00::12]") == "fd00::12") + #expect(CmxManualHost.normalizedRouteHost("fd00::12") == "fd00::12") + #expect(CmxManualHost.normalizedRouteHost("studio-mac.local") == "studio-mac.local") + #expect(CmxManualHost.normalizedRouteHost("my:host") == nil) + #expect(CmxManualHost.normalizedRouteHost("[my:host]") == nil) +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift index e03f57fcc415..e16caf40fed1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift @@ -110,7 +110,7 @@ private extension MobilePairedMac { routes, supportedKinds: supportedKinds, preferNonLoopback: preferNonLoopback - ), let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualHost(host) else { + ), let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) else { return nil } return "host:\(normalizedHost.lowercased()):\(port):name:\(displayName.lowercased())" diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index dae0212e797b..a91b68546d5c 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1559,7 +1559,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ifStillCurrent: (() -> Bool)? = nil ) async { let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) - guard let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualHost(host) else { + guard let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) else { connectionError = L10n.string("mobile.addDevice.invalidHost", defaultValue: "Enter a host or IP address, without spaces or URL paths.") connectionErrorGuidance = nil connectionState = .disconnected @@ -2302,7 +2302,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { instance.routes, supportedKinds: supportedKinds, preferNonLoopback: Self.prefersNonLoopbackRoutes - ), let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualHost(host) else { + ), let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) else { mobileShellLog.error( "connectToRegistryInstance: no reconnectable route device=\(device.deviceId, privacy: .public) tag=\(instance.tag, privacy: .public)" ) @@ -2585,7 +2585,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { refreshedTarget.routes, supportedKinds: supportedKinds, preferNonLoopback: Self.prefersNonLoopbackRoutes - ), MobileShellRouteAuthPolicy.normalizedManualHost(host) != nil else { + ), MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) != nil else { mobileShellLog.error("switchToMac: no reconnectable route mac=\(macDeviceID, privacy: .private)") if !hasActiveMacConnection, await restorePreviousMacIfNeeded( @@ -2708,7 +2708,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { previousActive.routes, supportedKinds: supportedKinds, preferNonLoopback: Self.prefersNonLoopbackRoutes - ), MobileShellRouteAuthPolicy.normalizedManualHost(host) != nil else { + ), MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) != nil else { mobileShellLog.error("restorePreviousMacIfNeeded: no reconnectable route mac=\(previousActive.macDeviceID, privacy: .private)") return false } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift index 6f610f566d1b..a159fbbe2ad8 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift @@ -26,12 +26,20 @@ public struct MobileShellRouteAuthPolicy { CmxManualHost(rawHost)?.rawValue } + /// Normalizes an already-stored attach-route endpoint host. + /// + /// Unlike ``normalizedManualHost(_:)``, this accepts bare IPv6 because route + /// endpoints store IPv6 hosts without brackets. + public static func normalizedManualRouteHost(_ rawHost: String) -> String? { + CmxManualHost.normalizedRouteHost(rawHost) + } + /// Maps a manually typed host to the transport kind that should be used. /// - Parameter host: The host to classify. /// - Returns: `.debugLoopback` for loopback hosts, `.tailscale` for /// Tailscale IP/MagicDNS hosts, otherwise `.manualHost`. public static func manualRouteKind(for host: String) -> CmxAttachTransportKind { - let normalizedHost = (normalizedManualHost(host) ?? host) + let normalizedHost = (normalizedManualRouteHost(host) ?? host) .trimmingCharacters(in: .whitespacesAndNewlines) .lowercased() if isLoopbackHost(normalizedHost) { diff --git a/Sources/Mobile/MobileRouteResolver.swift b/Sources/Mobile/MobileRouteResolver.swift index 73117edf5119..5a1644149cec 100644 --- a/Sources/Mobile/MobileRouteResolver.swift +++ b/Sources/Mobile/MobileRouteResolver.swift @@ -99,7 +99,7 @@ final class MobileRouteResolver: @unchecked Sendable { } } - if let manualHost = manualHost.flatMap({ CmxManualHost($0)?.rawValue }), + if let manualHost = manualHost.flatMap({ CmxManualHost.normalizedRouteHost($0) }), !CmxLoopbackHost().matches(manualHost) { let manualPriority = 10 + (tailscaleHosts.count * 10) if let manualRoute = try? CmxAttachRoute( diff --git a/cmuxTests/MobileHostServiceSettingsTests.swift b/cmuxTests/MobileHostServiceSettingsTests.swift index 244d52c4d931..aea982d3da29 100644 --- a/cmuxTests/MobileHostServiceSettingsTests.swift +++ b/cmuxTests/MobileHostServiceSettingsTests.swift @@ -116,6 +116,25 @@ struct MobileHostServiceSettingsTests { #expect(!routes.contains { $0.kind == .manualHost }) } + @Test func routeResolverAdvertisesConfiguredIPv6ManualHost() throws { + let suiteName = "MobileHostServiceSettingsTests.ManualHost.IPv6.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + defaults.set("[fd00::12]", forKey: MobileHostService.manualHostDefaultsKey) + + let configuredHost = try #require(MobileHostService.configuredManualHost(defaults: defaults)) + let routes = MobileRouteResolver().routes( + port: 58_465, + tailscaleHosts: [], + manualHost: configuredHost + ).routes + let manualRoute = try #require(routes.first { $0.kind == .manualHost }) + + #expect(configuredHost == "fd00::12") + #expect(manualRoute.endpoint == .hostPort(host: "fd00::12", port: 58_465)) + } + @Test func portApplyPreBindClassifiesNonBindCases() { // Out of range → invalid, regardless of anything else. #expect(MobileHostService.portApplyPreBindOutcome(enabled: true, currentBoundPort: nil, requestedPort: 0) == .invalid) diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 868ac4540b4f..87df14676df0 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -707,6 +707,44 @@ final class TerminalOutputCollector { #expect(requests.allSatisfy { $0.stackAccessToken == "stack-token-for-lan" }) } +@MainActor +@Test func manualHostPairingApprovesBracketedIPv6ManualEntry() async throws { + let attachRoute = try hostPortRoute( + kind: .manualHost, + host: "fd00::12", + port: 15433 + ) + let responses = ScriptedTransportResponses([ + try rpcAttachTicketFrame(route: attachRoute, workspaceID: "trusted-ipv6-workspace"), + try rpcWorkspaceListFrame(workspaceID: "trusted-ipv6-workspace", title: "Trusted IPv6 Workspace"), + ]) + let runtime = testRuntime( + supportedRouteKinds: [.manualHost], + transportFactory: ScriptedTransportFactory(responses: responses), + stackAccessToken: "stack-token-for-ipv6" + ) + let store = CMUXMobileShellStore.preview( + runtime: runtime, + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + + store.signIn() + await store.connectManualHost(name: "IPv6 LAN", host: "[fd00::12]", port: 15433) + + #expect(store.manualHostTrustWarning?.endpoint == "[fd00::12]:15433") + #expect(try await responses.sentRequests().isEmpty) + + let result = await store.acceptManualHostTrustWarning() + + #expect(result == .connected) + let route = try #require(store.activeRoute) + #expect(route.kind == .manualHost) + #expect(route.endpoint == .hostPort(host: "fd00::12", port: 15433)) + let requests = try await responses.sentRequests() + #expect(requests.map(\.method) == ["mobile.attach_ticket.create", "workspace.list"]) + #expect(requests.allSatisfy { $0.stackAccessToken == "stack-token-for-ipv6" }) +} + @MainActor @Test func manualHostTrustDoesNotCoverDifferentHost() async throws { let approvedRoute = try hostPortRoute( From 012e2af028c1e2722ef8aeedd37a4debbf10fd5d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 01:13:24 -0700 Subject: [PATCH 12/91] Clear stale manual host approval state --- ...MobileShellComposite+ManualHostTrust.swift | 1 + .../MobileShellComposite.swift | 3 +- .../cmuxFeatureTests/cmuxFeatureTests.swift | 54 +++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 5513f803cc7a..67616af33b65 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -68,6 +68,7 @@ extension MobileShellComposite { return } clearPairingError() + clearPairingVersionWarning() pendingManualHostTrust = pending manualHostTrustWarning = MobileManualHostTrustWarning( scope: scope, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index a91b68546d5c..7207ef49dda0 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1051,6 +1051,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { connectedHostName = "" pairingCode = "" clearPairingVersionWarning() + clearManualHostTrustWarning() // Wipe every saved draft so the next account never sees the previous // user's unsent text. Guard the in-memory clear (and the selection resets // below) so the per-terminal draft hooks do not write partial state into a @@ -5470,7 +5471,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { connectionErrorGuidance = nil } - private func clearPairingVersionWarning() { + func clearPairingVersionWarning() { pairingVersionWarning = nil pendingPairingVersionWarningURL = nil } diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 87df14676df0..6ef70e62ed4e 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -1973,6 +1973,60 @@ final class TerminalOutputCollector { #expect(try await responses.sentRequests().isEmpty) } +@MainActor +@Test func signOutClearsPendingManualHostTrustWarning() async throws { + let responses = ScriptedTransportResponses([]) + let runtime = testRuntime( + supportedRouteKinds: [.manualHost], + transportFactory: ScriptedTransportFactory(responses: responses), + stackAccessToken: "stack-token-for-signout-manual-warning" + ) + let store = CMUXMobileShellStore.preview( + runtime: runtime, + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + + store.signIn() + let firstResult = await store.connectPairingURLResult( + "cmux-ios://attach?v=3&pc=1&m=studio-mac.local:61234" + ) + store.signOut() + let staleApprovalResult = await store.acceptManualHostTrustWarning() + + #expect(firstResult == .needsUserApproval) + #expect(staleApprovalResult == .failed) + #expect(store.manualHostTrustWarning == nil) + #expect(store.connectionState == .disconnected) + #expect(try await responses.sentRequests().isEmpty) +} + +@MainActor +@Test func manualHostTrustWarningSupersedesPendingVersionWarning() async throws { + let responses = ScriptedTransportResponses([]) + let runtime = testRuntime( + supportedRouteKinds: [.tailscale, .manualHost], + transportFactory: ScriptedTransportFactory(responses: responses), + stackAccessToken: "stack-token-for-version-manual-warning" + ) + let store = CMUXMobileShellStore.preview( + runtime: runtime, + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + + store.signIn() + let versionWarningResult = await store.connectPairingURLResult( + "cmux-ios://attach?v=2&pc=2&av=0.65.0&ab=9&r=100.71.210.41:\(CmxMobileDefaults.defaultHostPort)" + ) + await store.connectManualHost(name: "Studio LAN", host: "192.168.1.77", port: 15432) + let staleVersionApprovalResult = await store.acceptPairingVersionWarning() + + #expect(versionWarningResult == .needsUserApproval) + #expect(staleVersionApprovalResult == .failed) + #expect(store.pairingVersionWarning == nil) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:15432") + #expect(try await responses.sentRequests().isEmpty) +} + @MainActor @Test func mixedPairingQRCodeBlocksManualFallbackUntilApproved() async throws { let responses = ScriptedTransportResponses([]) From 5a89f638bbbbdbe5a88e09c02e84b69fe533a7cc Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 01:16:12 -0700 Subject: [PATCH 13/91] Keep mobile status routes on host service --- .../MobileHostService+ManualHostRoutes.swift | 8 ++--- Sources/Mobile/MobileHostService.swift | 30 +++++++++++-------- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/Sources/Mobile/MobileHostService+ManualHostRoutes.swift b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift index 378e49eb175a..fb14ddb8e6e9 100644 --- a/Sources/Mobile/MobileHostService+ManualHostRoutes.swift +++ b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift @@ -45,20 +45,20 @@ extension MobileHostService { func publishCurrentRoutes(port: Int) { let manualHost = Self.configuredManualHost() advertisedManualHost = manualHost - MobileHostPublicStatusCache.update(routes: currentRoutes(port: port, manualHost: manualHost)) + updatePublicStatusSnapshot(routes: currentRoutes(port: port, manualHost: manualHost)) } func publishCurrentRoutes(port: Int, tailscaleHosts: [String]) { let manualHost = Self.configuredManualHost() advertisedManualHost = manualHost - MobileHostPublicStatusCache.update( + updatePublicStatusSnapshot( routes: currentRoutes(port: port, tailscaleHosts: tailscaleHosts, manualHost: manualHost) ) } func clearAdvertisedRoutes() { advertisedManualHost = nil - MobileHostPublicStatusCache.update(routes: []) + updatePublicStatusSnapshot(routes: []) } func refreshAdvertisedRoutesIfRunning(defaults: UserDefaults = .standard) { @@ -70,6 +70,6 @@ extension MobileHostService { return } advertisedManualHost = manualHost - MobileHostPublicStatusCache.update(routes: currentRoutes(port: listenerPort, manualHost: manualHost)) + updatePublicStatusSnapshot(routes: currentRoutes(port: listenerPort, manualHost: manualHost)) } } diff --git a/Sources/Mobile/MobileHostService.swift b/Sources/Mobile/MobileHostService.swift index f967a08a9f24..467709c62002 100644 --- a/Sources/Mobile/MobileHostService.swift +++ b/Sources/Mobile/MobileHostService.swift @@ -149,17 +149,18 @@ private final class MobileHostConnectionRegistry: @unchecked Sendable { } } -enum MobileHostPublicStatusCache { - private static let lock = NSLock() - private nonisolated(unsafe) static var routes: [CmxAttachRoute] = [] - static func update(routes nextRoutes: [CmxAttachRoute]) { +private final class MobileHostPublicStatusSnapshot: @unchecked Sendable { + private let lock = NSLock() + private var routes: [CmxAttachRoute] = [] + + func update(routes nextRoutes: [CmxAttachRoute]) { lock.lock() routes = nextRoutes lock.unlock() NotificationCenter.default.post(name: .mobileHostStatusDidChange, object: nil) } - static func result(includeIdentity: Bool = false) -> MobileHostRPCResult { + func result(includeIdentity: Bool = false) -> MobileHostRPCResult { lock.lock() let cachedRoutes = routes lock.unlock() @@ -293,7 +294,7 @@ final class MobileHostService { nonisolated private static let maximumActiveConnectionCount = 10 /// The single shape every public `mobile.host.status` reply uses (the - /// public-status cache, the network status gate, and + /// public-status snapshot, the network status gate, and /// `TerminalController`'s no-private-metadata branch), so the fields /// cannot drift. Identity-free: routes, fidelity, and capabilities are a /// reachability probe any peer may ask for, but the Mac's stable identity @@ -355,21 +356,22 @@ final class MobileHostService { /// degrades to identity-free and the phone's identity-recovery retry /// picks it up later). A flood of unique garbage tokens therefore cannot /// queue unbounded Stack lookups behind this verb. - nonisolated static func networkStatusResult(for request: MobileHostRPCRequest) async -> MobileHostRPCResult { + nonisolated func networkStatusResult(for request: MobileHostRPCRequest) async -> MobileHostRPCResult { let trimmedToken = request.auth?.stackAccessToken?.trimmingCharacters(in: .whitespacesAndNewlines) guard trimmedToken?.isEmpty == false else { - return MobileHostPublicStatusCache.result(includeIdentity: false) + return publicStatusSnapshot.result(includeIdentity: false) } - let verified = await MobileHostService.shared.verifiedStackCaller(for: request) + let verified = await verifiedStackCaller(for: request) if !verified { mobileHostLog.error("mobile host status identity withheld: stack verification failed") } - return MobileHostPublicStatusCache.result(includeIdentity: verified) + return publicStatusSnapshot.result(includeIdentity: verified) } private let callbackQueue = DispatchQueue(label: "dev.cmux.mobile.host-listener") let routeResolver = MobileRouteResolver() private let ticketStore = MobileAttachTicketStore() + nonisolated private let publicStatusSnapshot = MobileHostPublicStatusSnapshot() private var listener: NWListener? private var listenerGeneration = UUID() private var listenerUsesEphemeralFallback = false @@ -936,6 +938,10 @@ final class MobileHostService { ) } + func updatePublicStatusSnapshot(routes: [CmxAttachRoute]) { + publicStatusSnapshot.update(routes: routes) + } + /// Reconcile the live listener with current settings (enable/disable and /// preferred-port changes). Safe to call on any settings change: it no-ops /// unless the enabled state or the configured port actually changed, so an @@ -1022,7 +1028,7 @@ final class MobileHostService { }, handleRequest: { request in if request.method == "mobile.host.status" { - return await MobileHostService.networkStatusResult(for: request) + return await MobileHostService.shared.networkStatusResult(for: request) } let result = await TerminalController.shared.mobileHostHandleRPC(request) await MobileHostService.shared.recordCreatedResourcesIfNeeded( @@ -1141,7 +1147,7 @@ final class MobileHostService { }, handleRequest: { request in if request.method == "mobile.host.status" { - return await MobileHostService.networkStatusResult(for: request) + return await MobileHostService.shared.networkStatusResult(for: request) } let result = await TerminalController.shared.mobileHostHandleRPC(request) await MobileHostService.shared.recordCreatedResourcesIfNeeded( From 5d06d6c0f369a73a091685d5b3f224e77c80890a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 01:21:49 -0700 Subject: [PATCH 14/91] Trim mobile host status snapshot footprint --- Sources/Mobile/MobileHostService.swift | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/Sources/Mobile/MobileHostService.swift b/Sources/Mobile/MobileHostService.swift index 467709c62002..5d4e033bc1a5 100644 --- a/Sources/Mobile/MobileHostService.swift +++ b/Sources/Mobile/MobileHostService.swift @@ -150,21 +150,15 @@ private final class MobileHostConnectionRegistry: @unchecked Sendable { } private final class MobileHostPublicStatusSnapshot: @unchecked Sendable { - private let lock = NSLock() - private var routes: [CmxAttachRoute] = [] + private let routes = OSAllocatedUnfairLock(initialState: [CmxAttachRoute]()) func update(routes nextRoutes: [CmxAttachRoute]) { - lock.lock() - routes = nextRoutes - lock.unlock() + routes.withLock { $0 = nextRoutes } NotificationCenter.default.post(name: .mobileHostStatusDidChange, object: nil) } func result(includeIdentity: Bool = false) -> MobileHostRPCResult { - lock.lock() - let cachedRoutes = routes - lock.unlock() - let routesPayload = cachedRoutes.map(\.mobileHostJSONObject) + let routesPayload = routes.withLock { $0.map(\.mobileHostJSONObject) } return .ok( includeIdentity ? MobileHostService.identityStatusPayload(routesPayload: routesPayload) @@ -938,9 +932,7 @@ final class MobileHostService { ) } - func updatePublicStatusSnapshot(routes: [CmxAttachRoute]) { - publicStatusSnapshot.update(routes: routes) - } + func updatePublicStatusSnapshot(routes: [CmxAttachRoute]) { publicStatusSnapshot.update(routes: routes) } /// Reconcile the live listener with current settings (enable/disable and /// preferred-port changes). Safe to call on any settings change: it no-ops From abfd7527e4bb0c628d66376464acbe053fb9dfe2 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 01:41:11 -0700 Subject: [PATCH 15/91] Localize manual host pairing strings --- .../MobileShellConnectionError.swift | 26 +- Resources/Localizable.xcstrings | 1296 +++++++++++++++++ ios/cmux/Resources/Localizable.xcstrings | 85 ++ 3 files changed, 1402 insertions(+), 5 deletions(-) diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift index 55d4b475b955..c4f4e4385176 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileShellConnectionError.swift @@ -1,4 +1,5 @@ public import Foundation +import CmuxMobileSupport /// Errors surfaced while connecting to or talking with a paired Mac over the /// mobile-sync RPC transport. @@ -25,15 +26,30 @@ public enum MobileShellConnectionError: LocalizedError { public var errorDescription: String? { switch self { case .invalidResponse: - return "Invalid mobile sync response" + return L10n.string( + "mobile.connection.invalidResponse", + defaultValue: "Invalid mobile sync response" + ) case .connectionClosed: - return "Mobile sync connection closed" + return L10n.string( + "mobile.connection.closed", + defaultValue: "Mobile sync connection closed" + ) case .requestTimedOut: - return "Mobile sync request timed out" + return L10n.string( + "mobile.connection.timedOut", + defaultValue: "Mobile sync request timed out" + ) case .insecureManualRoute: - return "Manual host route needs approval before mobile sync can send account credentials" + return L10n.string( + "mobile.connection.insecureManualRoute", + defaultValue: "Manual host route needs approval before mobile sync can send account credentials" + ) case .attachTicketExpired: - return "Mobile attach ticket expired" + return L10n.string( + "mobile.connection.attachTicketExpired", + defaultValue: "Mobile attach ticket expired" + ) case let .authorizationFailed(message): return message case let .accountMismatch(message): diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 9e716eece360..e5dba4add325 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -117795,6 +117795,114 @@ "state": "translated", "value": "この Mac には Tailscale アドレスまたは手動ホストがないため、iPhone から接続できません。両方のデバイスに Tailscale をインストールするか、iPhone がサブネットルーター経由でこの Mac に到達できる場合は、設定で手動ホストを構成してください。" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "لا يحتوي هذا الـ Mac على عنوان Tailscale أو مضيف يدوي، لذلك لا يمكن لـ iPhone الوصول إليه. ثبّت Tailscale على كلا الجهازين، أو اضبط مضيفًا يدويًا في الإعدادات إذا كان iPhone يستطيع الوصول إلى هذا الـ Mac عبر موجّه شبكة فرعية." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ovaj Mac nema Tailscale adresu niti ručni host, pa mu iPhone ne može pristupiti. Instalirajte Tailscale na oba uređaja ili podesite ručni host u Postavkama ako iPhone može doći do ovog Maca preko subnet rutera." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Denne Mac har ingen Tailscale-adresse eller manuel vært, så din iPhone kan ikke nå den. Installer Tailscale på begge enheder, eller konfigurer en manuel vært i Indstillinger, hvis din iPhone kan nå denne Mac via en subnet-router." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Dieser Mac hat keine Tailscale-Adresse und keinen manuellen Host, daher kann dein iPhone ihn nicht erreichen. Installiere Tailscale auf beiden Geräten oder konfiguriere in den Einstellungen einen manuellen Host, wenn dein iPhone diesen Mac über einen Subnetzrouter erreichen kann." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Este Mac no tiene una dirección de Tailscale ni un host manual, así que tu iPhone no puede alcanzarlo. Instala Tailscale en ambos dispositivos o configura un host manual en Ajustes si tu iPhone puede llegar a este Mac mediante un router de subred." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ce Mac n’a pas d’adresse Tailscale ni d’hôte manuel, votre iPhone ne peut donc pas l’atteindre. Installez Tailscale sur les deux appareils, ou configurez un hôte manuel dans les réglages si votre iPhone peut atteindre ce Mac via un routeur de sous-réseau." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Questo Mac non ha un indirizzo Tailscale né un host manuale, quindi il tuo iPhone non può raggiungerlo. Installa Tailscale su entrambi i dispositivi oppure configura un host manuale nelle Impostazioni se l’iPhone può raggiungere questo Mac tramite un router di sottorete." + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "Mac នេះមិនមានអាសយដ្ឋាន Tailscale ឬម៉ាស៊ីនបម្រើដោយដៃទេ ដូច្នេះ iPhone របស់អ្នកមិនអាចភ្ជាប់ទៅវាបានទេ។ ដំឡើង Tailscale លើឧបករណ៍ទាំងពីរ ឬកំណត់ម៉ាស៊ីនបម្រើដោយដៃនៅក្នុង Settings ប្រសិនបើ iPhone របស់អ្នកអាចទៅដល់ Mac នេះតាមរយៈរ៉ោតទ័រ subnet។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "이 Mac에는 Tailscale 주소나 수동 호스트가 없어 iPhone에서 연결할 수 없습니다. 두 기기에 Tailscale을 설치하거나, iPhone이 서브넷 라우터를 통해 이 Mac에 도달할 수 있다면 설정에서 수동 호스트를 구성하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Denne Macen har ingen Tailscale-adresse eller manuell vert, så iPhone kan ikke nå den. Installer Tailscale på begge enhetene, eller konfigurer en manuell vert i Innstillinger hvis iPhone kan nå denne Macen via en subnettruter." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Ten Mac nie ma adresu Tailscale ani hosta ręcznego, więc iPhone nie może go osiągnąć. Zainstaluj Tailscale na obu urządzeniach albo skonfiguruj host ręczny w Ustawieniach, jeśli iPhone może dotrzeć do tego Maca przez router podsieci." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Este Mac não tem um endereço do Tailscale nem um host manual, então o iPhone não consegue acessá-lo. Instale o Tailscale nos dois dispositivos ou configure um host manual nos Ajustes se o iPhone conseguir alcançar este Mac por um roteador de sub-rede." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "У этого Mac нет адреса Tailscale или ручного хоста, поэтому iPhone не может к нему подключиться. Установите Tailscale на оба устройства или настройте ручной хост в настройках, если iPhone может достичь этого Mac через маршрутизатор подсети." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "Mac เครื่องนี้ไม่มีที่อยู่ Tailscale หรือโฮสต์แบบกำหนดเอง ดังนั้น iPhone ของคุณจึงติดต่อไม่ได้ ติดตั้ง Tailscale บนอุปกรณ์ทั้งสองเครื่อง หรือกำหนดโฮสต์แบบกำหนดเองในการตั้งค่าหาก iPhone ติดต่อ Mac เครื่องนี้ผ่านเราเตอร์ซับเน็ตได้" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bu Mac’in Tailscale adresi veya manuel ana bilgisayarı yok, bu yüzden iPhone’unuz ona ulaşamıyor. Her iki aygıta Tailscale yükleyin veya iPhone’unuz bu Mac’e bir alt ağ yönlendiricisi üzerinden ulaşabiliyorsa Ayarlar’da manuel ana bilgisayar yapılandırın." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Цей Mac не має адреси Tailscale або ручного хоста, тому iPhone не може до нього під’єднатися. Установіть Tailscale на обидва пристрої або налаштуйте ручний хост у параметрах, якщо iPhone може дістатися цього Mac через маршрутизатор підмережі." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "这台 Mac 没有 Tailscale 地址或手动主机,因此你的 iPhone 无法访问它。请在两台设备上安装 Tailscale,或者如果 iPhone 可通过子网路由器访问这台 Mac,请在设置中配置手动主机。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "這部 Mac 沒有 Tailscale 位址或手動主機,因此你的 iPhone 無法連線。請在兩部裝置上安裝 Tailscale;如果 iPhone 可透過子網路路由器連到這部 Mac,請在設定中設定手動主機。" + } } } }, @@ -117914,6 +118022,114 @@ "state": "translated", "value": "手動ホストが設定されています。このルートを信頼する前に iPhone で確認が表示されます。" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "تم تكوين مضيف يدوي. سيطلب iPhone التأكيد قبل الوثوق بهذا المسار." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ručni host je podešen. iPhone će zatražiti potvrdu prije nego što povjeruje ovoj ruti." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Manuel vært er konfigureret. Din iPhone spørger, før den godkender denne rute." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Manueller Host konfiguriert. Dein iPhone fragt nach, bevor diese Route vertraut wird." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Host manual configurado. Tu iPhone preguntará antes de confiar en esta ruta." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Hôte manuel configuré. Votre iPhone demandera confirmation avant d’approuver cette route." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Host manuale configurato. L’iPhone chiederà conferma prima di considerare attendibile questo percorso." + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បានកំណត់ម៉ាស៊ីនបម្រើដោយដៃ។ iPhone របស់អ្នកនឹងសួរមុនពេលជឿទុកចិត្តលើផ្លូវនេះ។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "수동 호스트가 구성되었습니다. iPhone은 이 경로를 신뢰하기 전에 확인을 요청합니다." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Manuell vert er konfigurert. iPhone spør før den stoler på denne ruten." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Skonfigurowano host ręczny. iPhone zapyta przed zaufaniem tej trasie." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Host manual configurado. O iPhone perguntará antes de confiar nesta rota." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Ручной хост настроен. iPhone запросит подтверждение перед доверием этому маршруту." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "กำหนดโฮสต์แบบกำหนดเองแล้ว iPhone จะถามก่อนเชื่อถือเส้นทางนี้" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Manuel ana bilgisayar yapılandırıldı. iPhone’unuz bu rotaya güvenmeden önce soracak." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Ручний хост налаштовано. iPhone запитає підтвердження перед довірою цьому маршруту." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已配置手动主机。iPhone 会在信任此路由前询问。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "已設定手動主機。iPhone 會在信任此路由前詢問。" + } } } }, @@ -117931,6 +118147,114 @@ "state": "translated", "value": "Tailscale を使用するか、サブネットルーター構成用に手動ホストを設定してください。" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "استخدم Tailscale، أو كوّن مضيفًا يدويًا لإعدادات موجّه الشبكة الفرعية." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Koristite Tailscale ili podesite ručni host za subnet-router postavke." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Brug Tailscale, eller konfigurer en manuel vært til subnet-router-opsætninger." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Verwende Tailscale oder konfiguriere einen manuellen Host für Subnetzrouter-Setups." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Usa Tailscale o configura un host manual para configuraciones con router de subred." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Utilisez Tailscale, ou configurez un hôte manuel pour les configurations avec routeur de sous-réseau." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Usa Tailscale oppure configura un host manuale per configurazioni con router di sottorete." + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ប្រើ Tailscale ឬកំណត់ម៉ាស៊ីនបម្រើដោយដៃសម្រាប់ការរៀបចំ subnet-router។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Tailscale을 사용하거나 서브넷 라우터 설정을 위해 수동 호스트를 구성하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Bruk Tailscale, eller konfigurer en manuell vert for subnettruter-oppsett." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Użyj Tailscale albo skonfiguruj host ręczny dla konfiguracji z routerem podsieci." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Use o Tailscale ou configure um host manual para setups com roteador de sub-rede." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Используйте Tailscale или настройте ручной хост для схем с маршрутизатором подсети." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ใช้ Tailscale หรือกำหนดโฮสต์แบบกำหนดเองสำหรับการตั้งค่าเราเตอร์ซับเน็ต" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Tailscale kullanın veya alt ağ yönlendiricisi kurulumları için manuel ana bilgisayar yapılandırın." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Використовуйте Tailscale або налаштуйте ручний хост для конфігурацій із маршрутизатором підмережі." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "使用 Tailscale,或为子网路由器设置配置手动主机。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "使用 Tailscale,或針對子網路路由器設定手動主機。" + } } } }, @@ -117948,6 +118272,114 @@ "state": "translated", "value": "Tailscale アドレスまたは手動ホストが設定されていません。Tailscale をインストールするか、サブネットルーター構成用に設定で手動ホストを指定してください。" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "لم يتم تكوين عنوان Tailscale أو مضيف يدوي. ثبّت Tailscale أو اضبط مضيفًا يدويًا في الإعدادات لإعدادات موجّه الشبكة الفرعية." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Nije podešena Tailscale adresa niti ručni host. Instalirajte Tailscale ili postavite ručni host u Postavkama za subnet-router konfiguracije." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Ingen Tailscale-adresse eller manuel vært er konfigureret. Installer Tailscale, eller angiv en manuel vært i Indstillinger til subnet-router-opsætninger." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Keine Tailscale-Adresse und kein manueller Host konfiguriert. Installiere Tailscale oder lege in den Einstellungen einen manuellen Host für Subnetzrouter-Setups fest." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No hay dirección de Tailscale ni host manual configurados. Instala Tailscale o define un host manual en Ajustes para configuraciones con router de subred." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune adresse Tailscale ni hôte manuel n’est configuré. Installez Tailscale, ou définissez un hôte manuel dans les réglages pour les configurations avec routeur de sous-réseau." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nessun indirizzo Tailscale o host manuale configurato. Installa Tailscale oppure imposta un host manuale nelle Impostazioni per configurazioni con router di sottorete." + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "មិនបានកំណត់អាសយដ្ឋាន Tailscale ឬម៉ាស៊ីនបម្រើដោយដៃទេ។ ដំឡើង Tailscale ឬកំណត់ម៉ាស៊ីនបម្រើដោយដៃនៅក្នុង Settings សម្រាប់ការរៀបចំ subnet-router។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Tailscale 주소나 수동 호스트가 구성되지 않았습니다. Tailscale을 설치하거나 서브넷 라우터 설정을 위해 설정에서 수동 호스트를 지정하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Ingen Tailscale-adresse eller manuell vert er konfigurert. Installer Tailscale, eller angi en manuell vert i Innstillinger for subnettruter-oppsett." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Nie skonfigurowano adresu Tailscale ani hosta ręcznego. Zainstaluj Tailscale albo ustaw host ręczny w Ustawieniach dla konfiguracji z routerem podsieci." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nenhum endereço do Tailscale ou host manual configurado. Instale o Tailscale ou defina um host manual nos Ajustes para setups com roteador de sub-rede." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Адрес Tailscale или ручной хост не настроены. Установите Tailscale или задайте ручной хост в настройках для схем с маршрутизатором подсети." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ยังไม่ได้กำหนดที่อยู่ Tailscale หรือโฮสต์แบบกำหนดเอง ติดตั้ง Tailscale หรือกำหนดโฮสต์แบบกำหนดเองในการตั้งค่าสำหรับการตั้งค่าเราเตอร์ซับเน็ต" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Tailscale adresi veya manuel ana bilgisayar yapılandırılmamış. Tailscale yükleyin veya alt ağ yönlendiricisi kurulumları için Ayarlar’da manuel ana bilgisayar belirleyin." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Адресу Tailscale або ручний хост не налаштовано. Установіть Tailscale або задайте ручний хост у параметрах для конфігурацій із маршрутизатором підмережі." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "未配置 Tailscale 地址或手动主机。请安装 Tailscale,或在设置中为子网路由器设置手动主机。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "尚未設定 Tailscale 位址或手動主機。請安裝 Tailscale,或在設定中針對子網路路由器設定手動主機。" + } } } }, @@ -117965,6 +118397,114 @@ "state": "translated", "value": "到達可能なルート" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "مسار يمكن الوصول إليه" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Dostupna ruta" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Tilgængelig rute" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erreichbare Route" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Ruta alcanzable" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Route accessible" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Percorso raggiungibile" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្លូវដែលអាចទៅដល់បាន" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "도달 가능한 경로" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Tilgjengelig rute" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Osiągalna trasa" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Rota alcançável" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Доступный маршрут" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "เส้นทางที่ติดต่อได้" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Ulaşılabilir rota" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Доступний маршрут" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "可访问路由" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "可連線路由" + } } } }, @@ -152187,6 +152727,114 @@ "state": "translated", "value": "手動ホスト" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "المضيف اليدوي" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ručni host" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Manuel vært" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Manueller Host" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Host manual" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Hôte manuel" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Host manuale" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ម៉ាស៊ីនបម្រើដោយដៃ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "수동 호스트" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Manuell vert" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Host ręczny" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Host manual" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Ручной хост" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "โฮสต์แบบกำหนดเอง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Manuel ana bilgisayar" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Ручний хост" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "手动主机" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "手動主機" + } } } }, @@ -152204,6 +152852,114 @@ "state": "translated", "value": "スペースや URL パスを含めず、ホストまたは IP アドレスを入力してください。" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "أدخل مضيفًا أو عنوان IP بدون مسافات أو مسارات URL." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Unesite host ili IP adresu, bez razmaka ili URL putanja." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Indtast en vært eller IP-adresse uden mellemrum eller URL-stier." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Gib einen Host oder eine IP-Adresse ohne Leerzeichen oder URL-Pfade ein." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Introduce un host o una dirección IP, sin espacios ni rutas URL." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Saisissez un hôte ou une adresse IP, sans espaces ni chemins d’URL." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Inserisci un host o un indirizzo IP, senza spazi o percorsi URL." + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បញ្ចូលម៉ាស៊ីនបម្រើ ឬអាសយដ្ឋាន IP ដោយគ្មានចន្លោះ ឬផ្លូវ URL។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "공백이나 URL 경로 없이 호스트 또는 IP 주소를 입력하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Skriv inn en vert eller IP-adresse uten mellomrom eller URL-baner." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Wpisz host lub adres IP, bez spacji i ścieżek URL." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Insira um host ou endereço IP, sem espaços nem caminhos de URL." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Введите хост или IP-адрес без пробелов и путей URL." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ป้อนโฮสต์หรือที่อยู่ IP โดยไม่มีช่องว่างหรือพาธ URL" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Boşluk veya URL yolu olmadan bir ana bilgisayar ya da IP adresi girin." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Введіть хост або IP-адресу без пробілів чи шляхів URL." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "请输入主机或 IP 地址,不要包含空格或 URL 路径。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "請輸入主機或 IP 位址,不要包含空格或 URL 路徑。" + } } } }, @@ -152221,6 +152977,114 @@ "state": "translated", "value": "192.168.1.23 または mac.local" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 أو mac.local" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 ili mac.local" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 eller mac.local" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 oder mac.local" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 o mac.local" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 ou mac.local" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 o mac.local" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 ឬ mac.local" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 또는 mac.local" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 eller mac.local" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 lub mac.local" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 ou mac.local" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 или mac.local" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 หรือ mac.local" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 veya mac.local" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 або mac.local" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 或 mac.local" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "192.168.1.23 或 mac.local" + } } } }, @@ -152238,6 +153102,114 @@ "state": "translated", "value": "この Mac で Tailscale を実行できない場合に通知する任意の LAN IP または DNS ホスト。" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "عنوان IP للشبكة المحلية أو مضيف DNS اختياري للإعلان عنه عندما لا يستطيع هذا الـ Mac تشغيل Tailscale." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Opcionalni LAN IP ili DNS host koji se oglašava kada ovaj Mac ne može pokrenuti Tailscale." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Valgfri LAN-IP eller DNS-vært, der annonceres, når denne Mac ikke kan køre Tailscale." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Optionale LAN-IP oder DNS-Host, der angekündigt wird, wenn dieser Mac Tailscale nicht ausführen kann." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "IP de LAN u host DNS opcional para anunciar cuando este Mac no puede ejecutar Tailscale." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "IP LAN ou hôte DNS facultatif à annoncer lorsque ce Mac ne peut pas exécuter Tailscale." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "IP LAN o host DNS facoltativo da pubblicizzare quando questo Mac non può eseguire Tailscale." + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "LAN IP ឬម៉ាស៊ីនបម្រើ DNS ស្រេចចិត្ត ដើម្បីផ្សព្វផ្សាយនៅពេល Mac នេះមិនអាចដំណើរការ Tailscale បាន។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "이 Mac에서 Tailscale을 실행할 수 없을 때 알릴 선택적 LAN IP 또는 DNS 호스트입니다." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Valgfri LAN-IP eller DNS-vert som annonseres når denne Macen ikke kan kjøre Tailscale." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Opcjonalny adres IP LAN lub host DNS do ogłaszania, gdy ten Mac nie może uruchomić Tailscale." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "IP de LAN ou host DNS opcional para anunciar quando este Mac não puder executar o Tailscale." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Необязательный IP-адрес LAN или DNS-хост для объявления, когда этот Mac не может запускать Tailscale." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "LAN IP หรือโฮสต์ DNS ที่จะประกาศเมื่อ Mac เครื่องนี้ไม่สามารถเรียกใช้ Tailscale ได้" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bu Mac Tailscale çalıştıramadığında duyurulacak isteğe bağlı LAN IP veya DNS ana bilgisayarı." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Необов’язкова LAN IP-адреса або DNS-хост для оголошення, коли цей Mac не може запускати Tailscale." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "当这台 Mac 无法运行 Tailscale 时要通告的可选 LAN IP 或 DNS 主机。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "當這部 Mac 無法執行 Tailscale 時要公告的選用 LAN IP 或 DNS 主機。" + } } } }, @@ -152255,6 +153227,114 @@ "state": "translated", "value": "手動ホストは明示的に信頼するルートです。認証情報を送信する前に iOS アプリで確認が表示されます。サブネットルーターを使う場合、iPhone からルーターまでは暗号化されることがありますが、ルーターから Mac までは通常の LAN 通信です。" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "المضيفون اليدويون مسارات ثقة صريحة. سيطلب تطبيق iOS التأكيد قبل إرسال بيانات الاعتماد. مع موجّه شبكة فرعية، قد يكون الاتصال من iPhone إلى الموجّه مشفرًا، لكن الاتصال من الموجّه إلى Mac هو حركة LAN عادية." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ručni hostovi su izričito povjerljive rute. iOS aplikacija će pitati prije slanja vjerodajnica. Uz subnet ruter, iPhone do rutera može biti šifriran, ali ruter do Maca je običan LAN promet." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Manuelle værter er eksplicitte tillidsruter. iOS-appen spørger, før den sender legitimationsoplysninger. Med en subnet-router kan iPhone til router være krypteret, men router til Mac er almindelig LAN-trafik." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Manuelle Hosts sind ausdrücklich vertrauenswürdige Routen. Die iOS-App fragt nach, bevor Anmeldedaten gesendet werden. Bei einem Subnetzrouter kann iPhone-zu-Router verschlüsselt sein, Router-zu-Mac ist jedoch normaler LAN-Verkehr." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Los hosts manuales son rutas de confianza explícita. La app de iOS preguntará antes de enviar credenciales. Con un router de subred, el tramo del iPhone al router puede estar cifrado, pero del router al Mac es tráfico LAN normal." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les hôtes manuels sont des routes de confiance explicites. L’app iOS demandera confirmation avant d’envoyer des identifiants. Avec un routeur de sous-réseau, le trajet iPhone vers routeur peut être chiffré, mais le trajet routeur vers Mac est du trafic LAN normal." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Gli host manuali sono percorsi di fiducia espliciti. L’app iOS chiederà conferma prima di inviare credenziali. Con un router di sottorete, il tratto da iPhone al router può essere crittografato, ma dal router al Mac è normale traffico LAN." + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ម៉ាស៊ីនបម្រើដោយដៃគឺជាផ្លូវជឿទុកចិត្តដោយច្បាស់លាស់។ កម្មវិធី iOS នឹងសួរមុនពេលផ្ញើព័ត៌មានសម្គាល់។ ជាមួយរ៉ោតទ័រ subnet ការភ្ជាប់ពី iPhone ទៅរ៉ោតទ័រអាចត្រូវបានអ៊ិនគ្រីប ប៉ុន្តែពីរ៉ោតទ័រទៅ Mac គឺជាចរាចរណ៍ LAN ធម្មតា។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "수동 호스트는 명시적으로 신뢰한 경로입니다. iOS 앱은 자격 증명을 보내기 전에 확인을 요청합니다. 서브넷 라우터를 사용하는 경우 iPhone에서 라우터까지는 암호화될 수 있지만 라우터에서 Mac까지는 일반 LAN 트래픽입니다." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Manuelle verter er eksplisitte tillitsruter. iOS-appen spør før den sender legitimasjon. Med en subnettruter kan iPhone til ruter være kryptert, men ruter til Mac er vanlig LAN-trafikk." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Hosty ręczne to trasy jawnego zaufania. Aplikacja iOS zapyta przed wysłaniem danych logowania. Przy routerze podsieci odcinek iPhone–router może być szyfrowany, ale od routera do Maca jest to zwykły ruch LAN." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Hosts manuais são rotas de confiança explícita. O app iOS perguntará antes de enviar credenciais. Com um roteador de sub-rede, o trecho do iPhone ao roteador pode ser criptografado, mas do roteador ao Mac é tráfego LAN normal." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Ручные хосты — это явно доверенные маршруты. Приложение iOS спросит перед отправкой учетных данных. При маршрутизаторе подсети участок от iPhone до маршрутизатора может быть зашифрован, но от маршрутизатора до Mac идет обычный LAN-трафик." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "โฮสต์แบบกำหนดเองเป็นเส้นทางที่ผู้ใช้เชื่อถืออย่างชัดเจน แอป iOS จะถามก่อนส่งข้อมูลรับรอง เมื่อใช้เราเตอร์ซับเน็ต ช่วงจาก iPhone ไปยังเราเตอร์อาจเข้ารหัส แต่จากเราเตอร์ไปยัง Mac เป็นทราฟฟิก LAN ปกติ" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Manuel ana bilgisayarlar açıkça güvenilen rotalardır. iOS uygulaması kimlik bilgilerini göndermeden önce sorar. Bir alt ağ yönlendiricisiyle iPhone’dan yönlendiriciye olan kısım şifreli olabilir, ancak yönlendiriciden Mac’e olan kısım normal LAN trafiğidir." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Ручні хости — це явно довірені маршрути. Застосунок iOS запитає перед надсиланням облікових даних. За маршрутизатора підмережі ділянка iPhone–маршрутизатор може бути зашифрована, але від маршрутизатора до Mac це звичайний LAN-трафік." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "手动主机是显式信任的路由。iOS 应用会在发送凭据前询问。使用子网路由器时,iPhone 到路由器的链路可能已加密,但路由器到 Mac 是普通 LAN 流量。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "手動主機是明確信任的路由。iOS App 會在傳送憑證前詢問。使用子網路路由器時,iPhone 到路由器的連線可能已加密,但路由器到 Mac 是一般 LAN 流量。" + } } } }, @@ -152527,6 +153607,114 @@ "state": "translated", "value": "手動ホスト" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "المضيف اليدوي" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ručni host" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Manuel vært" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Manueller Host" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Host manual" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Hôte manuel" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Host manuale" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ម៉ាស៊ីនបម្រើដោយដៃ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "수동 호스트" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Manuell vert" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Host ręczny" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Host manual" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Ручной хост" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "โฮสต์แบบกำหนดเอง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Manuel ana bilgisayar" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Ручний хост" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "手动主机" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "手動主機" + } } } }, @@ -164240,6 +165428,114 @@ "state": "translated", "value": "手動ホスト lan ip dns サブネットルーター tailscale ルート モバイル ペアリング iphone ipad" } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "مضيف يدوي lan ip dns موجّه شبكة فرعية tailscale مسار جوال اقتران iphone ipad" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "ručni host lan ip dns subnet ruter tailscale ruta mobilno uparivanje iphone ipad" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "manuel vært lan ip dns subnet-router tailscale rute mobil parring iphone ipad" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "manueller host lan ip dns subnetzrouter tailscale route mobil koppeln iphone ipad" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "host manual lan ip dns router subred tailscale ruta móvil emparejar iphone ipad" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "hôte manuel lan ip dns routeur sous-réseau tailscale route mobile jumelage iphone ipad" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "host manuale lan ip dns router sottorete tailscale percorso mobile abbinamento iphone ipad" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ម៉ាស៊ីនបម្រើដោយដៃ lan ip dns រ៉ោតទ័រ subnet tailscale ផ្លូវ mobile pairing iphone ipad" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "수동 호스트 lan ip dns 서브넷 라우터 tailscale 경로 모바일 페어링 iphone ipad" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "manuell vert lan ip dns subnettruter tailscale rute mobil sammenkobling iphone ipad" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "host ręczny lan ip dns router podsieci tailscale trasa mobilne parowanie iphone ipad" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "host manual lan ip dns roteador sub-rede tailscale rota móvel pareamento iphone ipad" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "ручной хост lan ip dns маршрутизатор подсети tailscale маршрут мобильное сопряжение iphone ipad" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "โฮสต์กำหนดเอง lan ip dns เราเตอร์ซับเน็ต tailscale เส้นทาง มือถือ จับคู่ iphone ipad" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "manuel ana bilgisayar lan ip dns alt ağ yönlendiricisi tailscale rota mobil eşleştirme iphone ipad" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "ручний хост lan ip dns маршрутизатор підмережі tailscale маршрут мобільне спарення iphone ipad" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "手动主机 lan ip dns 子网路由器 tailscale 路由 移动 配对 iphone ipad" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "手動主機 lan ip dns 子網路路由器 tailscale 路由 行動 配對 iphone ipad" + } } } }, diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 8a8d8b7a53be..c58e629a0ee6 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -8279,6 +8279,91 @@ } } } + }, + "mobile.connection.invalidResponse": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Invalid mobile sync response" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "モバイル同期の応答が無効です" + } + } + } + }, + "mobile.connection.closed": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Mobile sync connection closed" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "モバイル同期接続が閉じられました" + } + } + } + }, + "mobile.connection.timedOut": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Mobile sync request timed out" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "モバイル同期リクエストがタイムアウトしました" + } + } + } + }, + "mobile.connection.insecureManualRoute": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manual host route needs approval before mobile sync can send account credentials" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "モバイル同期がアカウント認証情報を送信する前に、手動ホストルートの承認が必要です" + } + } + } + }, + "mobile.connection.attachTicketExpired": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Mobile attach ticket expired" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "モバイル接続チケットの有効期限が切れました" + } + } + } } }, "version": "1.0" From 4c5ae7f71d46b25fc885d2de21a8374e0f44c53b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 04:09:57 -0700 Subject: [PATCH 16/91] Move mobile manual host route state --- .../Mobile/MobileHostRouteAdvertisement.swift | 78 +++++++++++++++++++ .../MobileHostService+ManualHostRoutes.swift | 44 ++++------- Sources/Mobile/MobileHostService.swift | 21 ++++- cmux.xcodeproj/project.pbxproj | 4 + 4 files changed, 114 insertions(+), 33 deletions(-) create mode 100644 Sources/Mobile/MobileHostRouteAdvertisement.swift diff --git a/Sources/Mobile/MobileHostRouteAdvertisement.swift b/Sources/Mobile/MobileHostRouteAdvertisement.swift new file mode 100644 index 000000000000..718cfe59595f --- /dev/null +++ b/Sources/Mobile/MobileHostRouteAdvertisement.swift @@ -0,0 +1,78 @@ +import CMUXMobileCore +import CmuxSettings +import Foundation + +@MainActor +final class MobileHostRouteAdvertisement { + nonisolated static let manualHostDefaultsKey = SettingCatalog().mobile.iOSPairingManualHost.userDefaultsKey + + private let routeResolver: MobileRouteResolver + private var advertisedManualHost: String? + + init(routeResolver: MobileRouteResolver) { + self.routeResolver = routeResolver + } + + nonisolated static func configuredManualHost(defaults: UserDefaults = .standard) -> String? { + guard let raw = defaults.object(forKey: manualHostDefaultsKey) as? String, + let host = CmxManualHost(raw)?.rawValue, + !CmxLoopbackHost().matches(host) else { + return nil + } + return host + } + + nonisolated static func manualHostNeedsRouteRefresh(previous: String?, current: String?) -> Bool { + previous != current + } + + func currentRoutes(port: Int) -> [CmxAttachRoute] { + currentRoutes(port: port, manualHost: Self.configuredManualHost()) + } + + func currentRoutes(port: Int, manualHost: String?) -> [CmxAttachRoute] { + routeResolver.routes(port: port, manualHost: manualHost).routes + } + + func currentRoutes(port: Int, tailscaleHosts: [String]) -> [CmxAttachRoute] { + currentRoutes(port: port, tailscaleHosts: tailscaleHosts, manualHost: Self.configuredManualHost()) + } + + func currentRoutes(port: Int, tailscaleHosts: [String], manualHost: String?) -> [CmxAttachRoute] { + routeResolver.routes( + port: port, + tailscaleHosts: tailscaleHosts, + manualHost: manualHost + ).routes + } + + func publishCurrentRoutes(port: Int) -> [CmxAttachRoute] { + let manualHost = Self.configuredManualHost() + advertisedManualHost = manualHost + return currentRoutes(port: port, manualHost: manualHost) + } + + func publishCurrentRoutes(port: Int, tailscaleHosts: [String]) -> [CmxAttachRoute] { + let manualHost = Self.configuredManualHost() + advertisedManualHost = manualHost + return currentRoutes(port: port, tailscaleHosts: tailscaleHosts, manualHost: manualHost) + } + + func clearAdvertisedRoutes() -> [CmxAttachRoute] { + advertisedManualHost = nil + return [] + } + + func refreshAdvertisedRoutesIfNeeded(port: Int, defaults: UserDefaults = .standard) -> [CmxAttachRoute]? { + let manualHost = Self.configuredManualHost(defaults: defaults) + guard Self.manualHostNeedsRouteRefresh(previous: advertisedManualHost, current: manualHost) else { + return nil + } + advertisedManualHost = manualHost + return currentRoutes(port: port, manualHost: manualHost) + } + + func reset() { + advertisedManualHost = nil + } +} diff --git a/Sources/Mobile/MobileHostService+ManualHostRoutes.swift b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift index fb14ddb8e6e9..014dcbfcf756 100644 --- a/Sources/Mobile/MobileHostService+ManualHostRoutes.swift +++ b/Sources/Mobile/MobileHostService+ManualHostRoutes.swift @@ -1,75 +1,61 @@ import CMUXMobileCore -import CmuxSettings import Foundation extension MobileHostService { /// User-default key for the explicit manual host advertised to iOS when /// Tailscale is unavailable on this Mac. - nonisolated static let manualHostDefaultsKey = SettingCatalog().mobile.iOSPairingManualHost.userDefaultsKey + nonisolated static let manualHostDefaultsKey = MobileHostRouteAdvertisement.manualHostDefaultsKey /// The user-configured LAN/DNS host to advertise as an explicit manual route, /// or `nil` when unset or invalid. nonisolated static func configuredManualHost(defaults: UserDefaults = .standard) -> String? { - guard let raw = defaults.object(forKey: manualHostDefaultsKey) as? String, - let host = CmxManualHost(raw)?.rawValue, - !CmxLoopbackHost().matches(host) else { - return nil - } - return host + MobileHostRouteAdvertisement.configuredManualHost(defaults: defaults) } nonisolated static func manualHostNeedsRouteRefresh(previous: String?, current: String?) -> Bool { - previous != current + MobileHostRouteAdvertisement.manualHostNeedsRouteRefresh(previous: previous, current: current) } func currentRoutes(port: Int) -> [CmxAttachRoute] { - currentRoutes(port: port, manualHost: Self.configuredManualHost()) + routeAdvertisement.currentRoutes(port: port) } func currentRoutes(port: Int, manualHost: String?) -> [CmxAttachRoute] { - routeResolver.routes(port: port, manualHost: manualHost).routes + routeAdvertisement.currentRoutes(port: port, manualHost: manualHost) } func currentRoutes(port: Int, tailscaleHosts: [String]) -> [CmxAttachRoute] { - currentRoutes(port: port, tailscaleHosts: tailscaleHosts, manualHost: Self.configuredManualHost()) + routeAdvertisement.currentRoutes(port: port, tailscaleHosts: tailscaleHosts) } func currentRoutes(port: Int, tailscaleHosts: [String], manualHost: String?) -> [CmxAttachRoute] { - routeResolver.routes( - port: port, - tailscaleHosts: tailscaleHosts, - manualHost: manualHost - ).routes + routeAdvertisement.currentRoutes(port: port, tailscaleHosts: tailscaleHosts, manualHost: manualHost) } func publishCurrentRoutes(port: Int) { - let manualHost = Self.configuredManualHost() - advertisedManualHost = manualHost - updatePublicStatusSnapshot(routes: currentRoutes(port: port, manualHost: manualHost)) + updatePublicStatusSnapshot(routes: routeAdvertisement.publishCurrentRoutes(port: port)) } func publishCurrentRoutes(port: Int, tailscaleHosts: [String]) { - let manualHost = Self.configuredManualHost() - advertisedManualHost = manualHost updatePublicStatusSnapshot( - routes: currentRoutes(port: port, tailscaleHosts: tailscaleHosts, manualHost: manualHost) + routes: routeAdvertisement.publishCurrentRoutes(port: port, tailscaleHosts: tailscaleHosts) ) } func clearAdvertisedRoutes() { - advertisedManualHost = nil - updatePublicStatusSnapshot(routes: []) + updatePublicStatusSnapshot(routes: routeAdvertisement.clearAdvertisedRoutes()) } func refreshAdvertisedRoutesIfRunning(defaults: UserDefaults = .standard) { guard let listenerPort else { return } - let manualHost = Self.configuredManualHost(defaults: defaults) - guard Self.manualHostNeedsRouteRefresh(previous: advertisedManualHost, current: manualHost) else { + guard let routes = routeAdvertisement.refreshAdvertisedRoutesIfNeeded( + port: listenerPort, + defaults: defaults + ) else { return } - advertisedManualHost = manualHost - updatePublicStatusSnapshot(routes: currentRoutes(port: listenerPort, manualHost: manualHost)) + updatePublicStatusSnapshot(routes: routes) } } diff --git a/Sources/Mobile/MobileHostService.swift b/Sources/Mobile/MobileHostService.swift index 5d4e033bc1a5..1bbb65157f05 100644 --- a/Sources/Mobile/MobileHostService.swift +++ b/Sources/Mobile/MobileHostService.swift @@ -350,6 +350,9 @@ final class MobileHostService { /// degrades to identity-free and the phone's identity-recovery retry /// picks it up later). A flood of unique garbage tokens therefore cannot /// queue unbounded Stack lookups behind this verb. + #if compiler(>=6.2) + @concurrent + #endif nonisolated func networkStatusResult(for request: MobileHostRPCRequest) async -> MobileHostRPCResult { let trimmedToken = request.auth?.stackAccessToken?.trimmingCharacters(in: .whitespacesAndNewlines) guard trimmedToken?.isEmpty == false else { @@ -363,9 +366,10 @@ final class MobileHostService { } private let callbackQueue = DispatchQueue(label: "dev.cmux.mobile.host-listener") - let routeResolver = MobileRouteResolver() + let routeResolver: MobileRouteResolver + let routeAdvertisement: MobileHostRouteAdvertisement private let ticketStore = MobileAttachTicketStore() - nonisolated private let publicStatusSnapshot = MobileHostPublicStatusSnapshot() + nonisolated private let publicStatusSnapshot: MobileHostPublicStatusSnapshot private var listener: NWListener? private var listenerGeneration = UUID() private var listenerUsesEphemeralFallback = false @@ -374,7 +378,6 @@ final class MobileHostService { /// ephemeral fallback). Used to decide whether a settings change needs a /// restart. `nil` while stopped. private var appliedPreferredPort: Int? - var advertisedManualHost: String? private var activeConnections: [UUID: MobileHostConnection] = [:] private var clientIDsByConnectionID: [UUID: Set] = [:] private var lastErrorDescription: String? @@ -388,6 +391,16 @@ final class MobileHostService { /// listener starts accepting connections. private var auth: AuthCoordinator? private var readinessWaiters: [CheckedContinuation] = [] + + private init( + routeResolver: MobileRouteResolver = MobileRouteResolver(), + publicStatusSnapshot: MobileHostPublicStatusSnapshot = MobileHostPublicStatusSnapshot() + ) { + self.routeResolver = routeResolver + routeAdvertisement = MobileHostRouteAdvertisement(routeResolver: routeResolver) + self.publicStatusSnapshot = publicStatusSnapshot + } + private var readinessTimeoutTask: Task? #if DEBUG private var debugAcceptedStackAuthToken: String? @@ -1657,7 +1670,7 @@ extension MobileHostService { listenerGeneration = UUID() listenerUsesEphemeralFallback = false listenerPort = nil - advertisedManualHost = nil + routeAdvertisement.reset() activeConnections.removeAll() clientIDsByConnectionID.removeAll() MobileHostRequestActivity.resetForTesting() diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 6c71fb9197b9..a18735ed55f9 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -693,6 +693,7 @@ B8B056D80000000000000001 /* MobileHostIdentityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8B056D80000000000000002 /* MobileHostIdentityTests.swift */; }; DE71CE000000000000000008 /* MobileHostNetworkPathMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE71CE000000000000000007 /* MobileHostNetworkPathMonitor.swift */; }; DE71CE000000000000000006 /* MobileHostNetworkPathRefreshTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE71CE000000000000000005 /* MobileHostNetworkPathRefreshTests.swift */; }; + 7230A0027230A0027230A002 /* MobileHostRouteAdvertisement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7230B0027230B0027230B002 /* MobileHostRouteAdvertisement.swift */; }; 4E673EDE464BF3AB80E94C1D /* MobileHostRPC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47BDC06F004C02A52B05E4A0 /* MobileHostRPC.swift */; }; C7A50B000000000000000014 /* MobileHostService+Capabilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A50B000000000000000013 /* MobileHostService+Capabilities.swift */; }; 7230A0017230A0017230A001 /* MobileHostService+ManualHostRoutes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7230B0017230B0017230B001 /* MobileHostService+ManualHostRoutes.swift */; }; @@ -1975,6 +1976,7 @@ B8B056D80000000000000002 /* MobileHostIdentityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileHostIdentityTests.swift; sourceTree = ""; }; DE71CE000000000000000007 /* MobileHostNetworkPathMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileHostNetworkPathMonitor.swift; sourceTree = ""; }; DE71CE000000000000000005 /* MobileHostNetworkPathRefreshTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileHostNetworkPathRefreshTests.swift; sourceTree = ""; }; + 7230B0027230B0027230B002 /* MobileHostRouteAdvertisement.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileHostRouteAdvertisement.swift; sourceTree = ""; }; 47BDC06F004C02A52B05E4A0 /* MobileHostRPC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileHostRPC.swift; sourceTree = ""; }; C7A50B000000000000000013 /* MobileHostService+Capabilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MobileHostService+Capabilities.swift"; sourceTree = ""; }; 7230B0017230B0017230B001 /* MobileHostService+ManualHostRoutes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MobileHostService+ManualHostRoutes.swift"; sourceTree = ""; }; @@ -2744,6 +2746,7 @@ children = ( 8D6D2AC715764ECC1F6B26A2 /* MobileAttachTicketStore.swift */, 47BDC06F004C02A52B05E4A0 /* MobileHostRPC.swift */, + 7230B0027230B0027230B002 /* MobileHostRouteAdvertisement.swift */, 7ACA497A6831165EA879C642 /* MobileHostService.swift */, C7A50B000000000000000015 /* MobileHostBuildIdentity.swift */, 4C1A7E10B2D34F56A8C90012 /* MobileHostStatusVerificationLimiter.swift */, @@ -4744,6 +4747,7 @@ 284FD21ACF8BD1ED6AEBD7A0 /* MobileAttachTicketStore.swift in Sources */, C7A50B000000000000000016 /* MobileHostBuildIdentity.swift in Sources */, DE71CE000000000000000008 /* MobileHostNetworkPathMonitor.swift in Sources */, + 7230A0027230A0027230A002 /* MobileHostRouteAdvertisement.swift in Sources */, 4E673EDE464BF3AB80E94C1D /* MobileHostRPC.swift in Sources */, C7A50B000000000000000014 /* MobileHostService+Capabilities.swift in Sources */, 7230A0017230A0017230A001 /* MobileHostService+ManualHostRoutes.swift in Sources */, From 9c8a00c76f8a99e5468fa3463685e6fc714776e6 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 04:33:50 -0700 Subject: [PATCH 17/91] Fit mobile host service budget --- .../Mobile/MobileHostRouteAdvertisement.swift | 4 ++-- Sources/Mobile/MobileHostService.swift | 16 +++------------- 2 files changed, 5 insertions(+), 15 deletions(-) diff --git a/Sources/Mobile/MobileHostRouteAdvertisement.swift b/Sources/Mobile/MobileHostRouteAdvertisement.swift index 718cfe59595f..0022f6d9a56d 100644 --- a/Sources/Mobile/MobileHostRouteAdvertisement.swift +++ b/Sources/Mobile/MobileHostRouteAdvertisement.swift @@ -6,10 +6,10 @@ import Foundation final class MobileHostRouteAdvertisement { nonisolated static let manualHostDefaultsKey = SettingCatalog().mobile.iOSPairingManualHost.userDefaultsKey - private let routeResolver: MobileRouteResolver + let routeResolver: MobileRouteResolver private var advertisedManualHost: String? - init(routeResolver: MobileRouteResolver) { + init(routeResolver: MobileRouteResolver = MobileRouteResolver()) { self.routeResolver = routeResolver } diff --git a/Sources/Mobile/MobileHostService.swift b/Sources/Mobile/MobileHostService.swift index 1bbb65157f05..c660df9fe47f 100644 --- a/Sources/Mobile/MobileHostService.swift +++ b/Sources/Mobile/MobileHostService.swift @@ -366,10 +366,10 @@ final class MobileHostService { } private let callbackQueue = DispatchQueue(label: "dev.cmux.mobile.host-listener") - let routeResolver: MobileRouteResolver - let routeAdvertisement: MobileHostRouteAdvertisement + let routeAdvertisement = MobileHostRouteAdvertisement() + var routeResolver: MobileRouteResolver { routeAdvertisement.routeResolver } private let ticketStore = MobileAttachTicketStore() - nonisolated private let publicStatusSnapshot: MobileHostPublicStatusSnapshot + nonisolated private let publicStatusSnapshot = MobileHostPublicStatusSnapshot() private var listener: NWListener? private var listenerGeneration = UUID() private var listenerUsesEphemeralFallback = false @@ -391,16 +391,6 @@ final class MobileHostService { /// listener starts accepting connections. private var auth: AuthCoordinator? private var readinessWaiters: [CheckedContinuation] = [] - - private init( - routeResolver: MobileRouteResolver = MobileRouteResolver(), - publicStatusSnapshot: MobileHostPublicStatusSnapshot = MobileHostPublicStatusSnapshot() - ) { - self.routeResolver = routeResolver - routeAdvertisement = MobileHostRouteAdvertisement(routeResolver: routeResolver) - self.publicStatusSnapshot = publicStatusSnapshot - } - private var readinessTimeoutTask: Task? #if DEBUG private var debugAcceptedStackAuthToken: String? From b411a70f05a6a207e5483ecc3efd152f56af051b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 09:11:27 -0700 Subject: [PATCH 18/91] Satisfy mobile manual host policy gate --- .../CMUXMobileCore/CmxManualHost.swift | 77 +++-------------- .../CMUXMobileCore/CmxManualHostParser.swift | 59 +++++++++++++ .../CMUXMobileCore/MobileSyncProtocol.swift | 6 ++ .../CmxManualHostTests.swift | 10 +-- .../CmuxMobileRPC/MobileCoreRPCClient.swift | 2 +- ...ileShellComposite+ManualAttachTicket.swift | 4 +- ...MobileShellComposite+ManualHostTrust.swift | 4 +- ...obileShellComposite+PairedMacAliases.swift | 3 +- ...leShellComposite+PairedMacCoalescing.swift | 40 ++++++--- .../MobileShellComposite.swift | 79 +++++++++-------- ....swift => MobileShellRouteSelection.swift} | 38 ++++++--- .../MobileShellCompositePreviewTests.swift | 2 +- .../ReconnectRouteSelectionTests.swift | 32 +++---- .../MobileManualHostTrustScope.swift | 25 ++---- .../MobileShellRouteAuthPolicy.swift | 46 +++++----- .../MobileShellRouteAuthPolicyTests.swift | 84 +++++++++---------- .../CmuxMobileShellUI/PairingView.swift | 4 +- ...bilePairingManualHostAdvertisability.swift | 15 ++++ .../Sections/MobileSection.swift | 16 +--- .../SettingsRowAnchorResolutionTests.swift | 17 ++-- Sources/Cloud/RemoteRouteSpec.swift | 2 +- Sources/Mobile/MobileHostService.swift | 2 +- Sources/Mobile/MobileRouteResolver.swift | 2 +- .../MobilePairingRouteReachability.swift | 6 ++ .../Mobile/Pairing/MobilePairingView.swift | 11 +-- cmux.xcodeproj/project.pbxproj | 4 + 26 files changed, 326 insertions(+), 264 deletions(-) create mode 100644 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHostParser.swift rename Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/{MobileShellComposite+RouteSelection.swift => MobileShellRouteSelection.swift} (80%) create mode 100644 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobilePairingManualHostAdvertisability.swift create mode 100644 Sources/Mobile/Pairing/MobilePairingRouteReachability.swift diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift index 6ba0002ac516..b0b66a223894 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift @@ -1,4 +1,3 @@ -import Darwin import Foundation /// A normalized user-entered host for explicit manual mobile pairing routes. @@ -17,75 +16,25 @@ public struct CmxManualHost: Equatable, Sendable { /// - Parameter rawHost: A DNS name or IP literal. IPv6 literals must be /// bracketed (`[fd00::1]`) so ordinary hostnames cannot hide colons. public init?(_ rawHost: String) { - let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { - return nil - } - - let host: String - let isBracketedHost: Bool - if trimmed.hasPrefix("[") || trimmed.hasSuffix("]") { - guard trimmed.hasPrefix("["), - trimmed.hasSuffix("]"), - trimmed.count > 2 else { - return nil - } - host = String(trimmed.dropFirst().dropLast()) - isBracketedHost = true - } else { - host = trimmed - isBracketedHost = false - } - guard !host.isEmpty, - host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil, - host.rangeOfCharacter(from: .controlCharacters) == nil, - host.range(of: "://") == nil else { - return nil - } - if isBracketedHost { - guard Self.isIPv6Literal(host) else { - return nil - } - } else { - guard Self.isUnbracketedQRHost(host) else { - return nil - } - } + guard let host = CmxManualHostParser( + rawHost: rawHost, + acceptsBareIPv6: false + ).normalizedHost else { return nil } self.rawValue = host } - /// Normalizes a host that may already be in attach-route endpoint form. + /// Creates a manual host from attach-route endpoint form. /// /// User-entered IPv6 must be bracketed so a typo like `my:host` is rejected /// up front. Attach routes store IPv6 without brackets, so route/reconnect - /// paths use this helper when they are validating an already-normalized + /// paths use this initializer when they are validating an already-normalized /// endpoint host. - public static func normalizedRouteHost(_ rawHost: String) -> String? { - if let manualHost = CmxManualHost(rawHost) { - return manualHost.rawValue - } - let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.hasPrefix("["), - !trimmed.hasSuffix("]"), - Self.isIPv6Literal(trimmed) else { - return nil - } - return trimmed - } - - private static func isUnbracketedQRHost(_ host: String) -> Bool { - host.utf8.allSatisfy { byte in - (48...57).contains(byte) // 0-9 - || (65...90).contains(byte) // A-Z - || (97...122).contains(byte) // a-z - || byte == UInt8(ascii: ".") - || byte == UInt8(ascii: "-") - || byte == UInt8(ascii: "_") - } - } - - private static func isIPv6Literal(_ host: String) -> Bool { - var address = in6_addr() - return host.withCString { inet_pton(AF_INET6, $0, &address) } == 1 + /// - Parameter rawHost: A DNS name, IP literal, or already-normalized bare IPv6 endpoint host. + public init?(routeHost rawHost: String) { + guard let host = CmxManualHostParser( + rawHost: rawHost, + acceptsBareIPv6: true + ).normalizedHost else { return nil } + self.rawValue = host } } diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHostParser.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHostParser.swift new file mode 100644 index 000000000000..589a26883050 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHostParser.swift @@ -0,0 +1,59 @@ +import Darwin +import Foundation + +struct CmxManualHostParser { + let rawHost: String + let acceptsBareIPv6: Bool + + var normalizedHost: String? { + let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { + return nil + } + + let host: String + let isBracketedHost: Bool + if trimmed.hasPrefix("[") || trimmed.hasSuffix("]") { + guard trimmed.hasPrefix("["), + trimmed.hasSuffix("]"), + trimmed.count > 2 else { + return nil + } + host = String(trimmed.dropFirst().dropLast()) + isBracketedHost = true + } else { + host = trimmed + isBracketedHost = false + } + + guard !host.isEmpty, + host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil, + host.rangeOfCharacter(from: .controlCharacters) == nil, + host.range(of: "://") == nil else { + return nil + } + if isBracketedHost || acceptsBareIPv6, isIPv6Literal(host) { + return host + } + guard !isBracketedHost, isUnbracketedQRHost(host) else { + return nil + } + return host + } + + private func isUnbracketedQRHost(_ host: String) -> Bool { + host.utf8.allSatisfy { byte in + (48...57).contains(byte) // 0-9 + || (65...90).contains(byte) // A-Z + || (97...122).contains(byte) // a-z + || byte == UInt8(ascii: ".") + || byte == UInt8(ascii: "-") + || byte == UInt8(ascii: "_") + } + } + + private func isIPv6Literal(_ host: String) -> Bool { + var address = in6_addr() + return host.withCString { inet_pton(AF_INET6, $0, &address) } == 1 + } +} diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileSyncProtocol.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileSyncProtocol.swift index c8a76004b44f..9cf8292e0a1f 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileSyncProtocol.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileSyncProtocol.swift @@ -11,11 +11,17 @@ public struct CmxMobileDefaults { public static let pairingCompatibilityVersion = 1 } +/// Transport families that an attach route may use to reach a Mac host. public enum CmxAttachTransportKind: String, Codable, Sendable { + /// A WireGuard-encrypted Tailscale host/port route. case tailscale + /// A user-approved host/port route outside automatic Tailscale discovery. case manualHost = "manual_host" + /// An encrypted iroh peer route. case iroh + /// A websocket URL route. case websocket + /// A loopback host/port route used by local development and simulator flows. case debugLoopback = "debug_loopback" } diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift index 49c25ae9723e..8dde337c462c 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift @@ -28,9 +28,9 @@ import Testing } @Test func manualHostRouteNormalizerAcceptsAlreadyNormalizedIPv6() { - #expect(CmxManualHost.normalizedRouteHost("[fd00::12]") == "fd00::12") - #expect(CmxManualHost.normalizedRouteHost("fd00::12") == "fd00::12") - #expect(CmxManualHost.normalizedRouteHost("studio-mac.local") == "studio-mac.local") - #expect(CmxManualHost.normalizedRouteHost("my:host") == nil) - #expect(CmxManualHost.normalizedRouteHost("[my:host]") == nil) + #expect(CmxManualHost(routeHost: "[fd00::12]")?.rawValue == "fd00::12") + #expect(CmxManualHost(routeHost: "fd00::12")?.rawValue == "fd00::12") + #expect(CmxManualHost(routeHost: "studio-mac.local")?.rawValue == "studio-mac.local") + #expect(CmxManualHost(routeHost: "my:host") == nil) + #expect(CmxManualHost(routeHost: "[my:host]") == nil) } diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift index 7d8b2063af15..65729cdab35d 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift @@ -276,7 +276,7 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { } private var routeAllowsStackAuth: Bool { - MobileShellRouteAuthPolicy.routeAllowsStackAuth( + MobileShellRouteAuthPolicy().routeAllowsStackAuth( route, manualHostTrusted: allowsTrustedManualHostStackAuth ) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift index 63a2ac6dd8ed..3d3c5a96adcb 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift @@ -47,9 +47,9 @@ extension MobileShellComposite { attemptStartedAt: Date?, manualHostTrusted: Bool = false ) async throws -> CmxAttachTicket { - let directRoute = try Self.manualHostRoute(host: host, port: port) + let directRoute = try routeSelection.manualHostRoute(host: host, port: port) let displayName = name.isEmpty ? host : name - if MobileShellRouteAuthPolicy.routeAllowsStackAuth( + if MobileShellRouteAuthPolicy().routeAllowsStackAuth( directRoute, manualHostTrusted: manualHostTrusted ) { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 67616af33b65..29379e3ea9ee 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -22,7 +22,7 @@ extension MobileShellComposite { func manualHostTrustScope(for route: CmxAttachRoute?) -> MobileManualHostTrustScope? { guard let route, - MobileShellRouteAuthPolicy.routeRequiresManualHostTrust(route) else { + MobileShellRouteAuthPolicy().routeRequiresManualHostTrust(route) else { return nil } return MobileManualHostTrustScope( @@ -76,6 +76,8 @@ extension MobileShellComposite { ) } + /// Persists the queued manual-host trust approval and resumes the pending pairing attempt. + /// - Returns: The resumed pairing attempt's connection result, or `.failed` if no warning is pending. @discardableResult public func acceptManualHostTrustWarning() async -> MobilePairingURLConnectionResult { guard let warning = manualHostTrustWarning, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacAliases.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacAliases.swift index ccf9dd211ba3..8081ce7219c1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacAliases.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacAliases.swift @@ -8,7 +8,8 @@ extension MobileShellComposite { Self.coalescePairedMacsByDialEndpoint( pairedMacs, supportedKinds: runtime?.supportedRouteKinds ?? [], - preferNonLoopback: Self.prefersNonLoopbackRoutes + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, + routeSelection: routeSelection ) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift index e16caf40fed1..b5f034f60b2b 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift @@ -15,7 +15,8 @@ extension MobileShellComposite { static func coalescePairedMacsByDialEndpoint( _ macs: [MobilePairedMac], supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool + preferNonLoopback: Bool, + routeSelection: MobileShellRouteSelection ) -> [MobilePairedMac] { var selectedByKey: [String: MobilePairedMac] = [:] var orderByKey: [String: Int] = [:] @@ -23,7 +24,8 @@ extension MobileShellComposite { for (index, mac) in macs.enumerated() { let key = mac.dialEndpointKey( supportedKinds: supportedKinds, - preferNonLoopback: preferNonLoopback + preferNonLoopback: preferNonLoopback, + routeSelection: routeSelection ) ?? "device:\(mac.macDeviceID)" orderByKey[key] = min(orderByKey[key] ?? index, index) guard let existing = selectedByKey[key] else { @@ -48,14 +50,23 @@ extension MobileShellComposite { _ macDeviceID: String, in macs: [MobilePairedMac], supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool + preferNonLoopback: Bool, + routeSelection: MobileShellRouteSelection ) -> [String] { guard let target = macs.first(where: { $0.macDeviceID == macDeviceID }), - let key = target.dialEndpointKey(supportedKinds: supportedKinds, preferNonLoopback: preferNonLoopback) else { + let key = target.dialEndpointKey( + supportedKinds: supportedKinds, + preferNonLoopback: preferNonLoopback, + routeSelection: routeSelection + ) else { return [macDeviceID] } let matching = macs.filter { - $0.dialEndpointKey(supportedKinds: supportedKinds, preferNonLoopback: preferNonLoopback) == key + $0.dialEndpointKey( + supportedKinds: supportedKinds, + preferNonLoopback: preferNonLoopback, + routeSelection: routeSelection + ) == key }.map(\.macDeviceID) return matching.isEmpty ? [macDeviceID] : matching } @@ -63,26 +74,30 @@ extension MobileShellComposite { func macDeviceIDAliasSetsByPairedMacID( in macs: [MobilePairedMac], supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool + preferNonLoopback: Bool, + routeSelection: MobileShellRouteSelection ) -> [String: Set] { macDeviceIDAliasesByPairedMacID( in: macs, supportedKinds: supportedKinds, - preferNonLoopback: preferNonLoopback + preferNonLoopback: preferNonLoopback, + routeSelection: routeSelection ).mapValues(Set.init) } func macDeviceIDAliasesByPairedMacID( in macs: [MobilePairedMac], supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool + preferNonLoopback: Bool, + routeSelection: MobileShellRouteSelection ) -> [String: [String]] { var groupKeyByMacID: [String: String] = [:] var idsByGroupKey: [String: [String]] = [:] for mac in macs { let key = mac.dialEndpointKey( supportedKinds: supportedKinds, - preferNonLoopback: preferNonLoopback + preferNonLoopback: preferNonLoopback, + routeSelection: routeSelection ) ?? "device:\(mac.macDeviceID)" groupKeyByMacID[mac.macDeviceID] = key idsByGroupKey[key, default: []].append(mac.macDeviceID) @@ -100,17 +115,18 @@ private extension MobilePairedMac { @MainActor func dialEndpointKey( supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool + preferNonLoopback: Bool, + routeSelection: MobileShellRouteSelection ) -> String? { guard let displayName = displayName?.trimmingCharacters(in: .whitespacesAndNewlines), !displayName.isEmpty else { return nil } - guard let (host, port) = MobileShellComposite.firstReconnectHostPortRoute( + guard let (host, port) = routeSelection.firstReconnectHostPortRoute( routes, supportedKinds: supportedKinds, preferNonLoopback: preferNonLoopback - ), let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) else { + ), let normalizedHost = MobileShellRouteAuthPolicy().normalizedManualRouteHost(host) else { return nil } return "host:\(normalizedHost.lowercased()):\(port):name:\(displayName.lowercased())" diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 7207ef49dda0..136d0dec70b2 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -223,7 +223,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { activeTicket.authToken?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { return false } - return Self.attachTicketIsUnexpired(activeTicket, now: runtime?.now() ?? Date()) + return routeSelection.attachTicketIsUnexpired(activeTicket, now: runtime?.now() ?? Date()) } /// User-entered pairing code or pairing URL text for the current connection attempt. public var pairingCode: String @@ -288,6 +288,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// stateless infrastructure, not observed state. @ObservationIgnored private let routePinger: any CmxRoutePinging + @ObservationIgnored + let routeSelection = MobileShellRouteSelection() /// Probe whether the phone can reach this route right now (a direct TCP /// connect, independent of the live subscription). See ``CmxRoutePinging``. @@ -1002,6 +1004,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } + /// Creates a preview shell store with in-memory manual-host trust. + /// - Parameters: + /// - runtime: Optional runtime used by previews or package tests. + /// - manualHostTrustStore: Store used to persist manual-host approvals in the preview shell. + /// - Returns: A shell store seeded with preview workspaces. public static func preview( runtime: (any MobileSyncRuntime)? = nil, manualHostTrustStore: any MobileManualHostTrustStoring = InMemoryMobileManualHostTrustStore() @@ -1560,7 +1567,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ifStillCurrent: (() -> Bool)? = nil ) async { let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) - guard let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) else { + guard let normalizedHost = MobileShellRouteAuthPolicy().normalizedManualRouteHost(host) else { connectionError = L10n.string("mobile.addDevice.invalidHost", defaultValue: "Enter a host or IP address, without spaces or URL paths.") connectionErrorGuidance = nil connectionState = .disconnected @@ -1589,7 +1596,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return } - let directRoute = try? Self.manualHostRoute(host: normalizedHost, port: port) + let directRoute = try? routeSelection.manualHostRoute(host: normalizedHost, port: port) if let directRoute, await manualHostRouteNeedsApproval(directRoute) { queueManualHostTrustWarning( @@ -1625,7 +1632,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let noThrowFailure = try await connect( ticket: ticket, allowsStackAuthFallback: directRoute.map { - MobileShellRouteAuthPolicy.routeAllowsStackAuth( + MobileShellRouteAuthPolicy().routeAllowsStackAuth( $0, manualHostTrusted: manualHostTrusted ) @@ -1699,10 +1706,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard await isScopeCurrent(scope) else { finishStoredMacReconnectAttempt(generation: generation); return false } let supportedKinds = runtime?.supportedRouteKinds ?? [] func reachableRoute(_ mac: MobilePairedMac) -> (String, Int)? { - Self.firstReconnectHostPortRoute( + routeSelection.firstReconnectHostPortRoute( mac.routes, supportedKinds: supportedKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes ) } let loadedActiveMac: MobilePairedMac? @@ -2213,7 +2220,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { activeMacID, in: knownMacs, supportedKinds: self.runtime?.supportedRouteKinds ?? [], - preferNonLoopback: Self.prefersNonLoopbackRoutes + preferNonLoopback: self.routeSelection.prefersNonLoopbackRoutes, + routeSelection: self.routeSelection )) { self.recoverMobileConnection(trigger: .presencePush) } @@ -2299,11 +2307,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { instance: RegistryAppInstance ) async { let supportedKinds = runtime?.supportedRouteKinds ?? [] - guard let (host, port) = Self.firstReconnectHostPortRoute( + guard let (host, port) = routeSelection.firstReconnectHostPortRoute( instance.routes, supportedKinds: supportedKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes - ), let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) else { + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes + ), let normalizedHost = MobileShellRouteAuthPolicy().normalizedManualRouteHost(host) else { mobileShellLog.error( "connectToRegistryInstance: no reconnectable route device=\(device.deviceId, privacy: .public) tag=\(instance.tag, privacy: .public)" ) @@ -2404,12 +2412,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let coalesced = Self.coalescePairedMacsByDialEndpoint( visibleLoaded, supportedKinds: supportedRouteKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, + routeSelection: routeSelection ) let aliasIDsByMacID = macDeviceIDAliasesByPairedMacID( in: visibleLoaded, supportedKinds: supportedRouteKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, + routeSelection: routeSelection ) pairedMacAliasIDsByRepresentativeID = coalesced.reduce(into: [String: [String]]()) { result, mac in result[mac.macDeviceID] = aliasIDsByMacID[mac.macDeviceID] ?? [mac.macDeviceID] @@ -2582,11 +2592,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { macSwitchRestoreBaseline = nil } let supportedKinds = runtime?.supportedRouteKinds ?? [] - guard let (host, port) = Self.firstReconnectHostPortRoute( + guard let (host, port) = routeSelection.firstReconnectHostPortRoute( refreshedTarget.routes, supportedKinds: supportedKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes - ), MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) != nil else { + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes + ), MobileShellRouteAuthPolicy().normalizedManualRouteHost(host) != nil else { mobileShellLog.error("switchToMac: no reconnectable route mac=\(macDeviceID, privacy: .private)") if !hasActiveMacConnection, await restorePreviousMacIfNeeded( @@ -2672,7 +2682,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let aliasSetsByMacID = macDeviceIDAliasSetsByPairedMacID( in: candidates, supportedKinds: supportedKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, + routeSelection: routeSelection ) return candidates.first { candidate in guard candidate.macDeviceID != macDeviceID else { return false } @@ -2705,11 +2716,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { && foregroundMacDeviceID.map { previousIDs.contains($0) } == true guard !previousStillForeground else { return true } let supportedKinds = runtime?.supportedRouteKinds ?? [] - guard let (host, port) = Self.firstReconnectHostPortRoute( + guard let (host, port) = routeSelection.firstReconnectHostPortRoute( previousActive.routes, supportedKinds: supportedKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes - ), MobileShellRouteAuthPolicy.normalizedManualRouteHost(host) != nil else { + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes + ), MobileShellRouteAuthPolicy().normalizedManualRouteHost(host) != nil else { mobileShellLog.error("restorePreviousMacIfNeeded: no reconnectable route mac=\(previousActive.macDeviceID, privacy: .private)") return false } @@ -3076,9 +3087,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // would be handed to whatever local process answers. Pure policy, // unit tested for both device values; only this wiring is // compile-time. - if MobileShellRouteAuthPolicy.ticketRejectsLoopbackRoutes( + if MobileShellRouteAuthPolicy().ticketRejectsLoopbackRoutes( ticket.routes, - isPhysicalDevice: Self.isPhysicalDevice + isPhysicalDevice: routeSelection.isPhysicalDevice ) { throw MobileSyncPairingPayloadError.loopbackRouteRejected } @@ -3128,7 +3139,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return .needsUserApproval } - let candidateRoutes = Self.supportedRoutes(for: ticket, supportedKinds: runtime?.supportedRouteKinds ?? []) + let candidateRoutes = routeSelection.supportedRoutes(for: ticket, supportedKinds: runtime?.supportedRouteKinds ?? []) if let approval = await firstManualHostRouteNeedingApproval(in: candidateRoutes), case let .hostPort(host, _) = approval.route.endpoint { queueManualHostTrustWarning( @@ -3322,16 +3333,16 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func makeSecondaryClient(for mac: MobilePairedMac) async -> SecondaryClientHandle? { guard let runtime else { return nil } let supportedKinds = runtime.supportedRouteKinds - guard let (host, port) = Self.firstReconnectHostPortRoute( + guard let (host, port) = routeSelection.firstReconnectHostPortRoute( mac.routes, supportedKinds: supportedKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes ) else { return nil } let ticket: CmxAttachTicket do { - let directRoute = try Self.manualHostRoute(host: host, port: port) + let directRoute = try routeSelection.manualHostRoute(host: host, port: port) let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) ticket = try await manualHostTicket( name: mac.displayName ?? host, @@ -3346,7 +3357,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) return nil } - let supportedRoutes = Self.supportedRoutes(for: ticket, supportedKinds: supportedKinds) + let supportedRoutes = routeSelection.supportedRoutes(for: ticket, supportedKinds: supportedKinds) // Dial the route we PROVED reachable above (the non-loopback host/port the // ticket was built from), NOT `supportedRoutes.first`: on a physical phone a // Mac ticket can advertise a higher-priority `debugLoopback` (127.0.0.1) @@ -3362,7 +3373,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ?? supportedRoutes.first guard let route else { return nil } let manualHostTrusted = await manualHostStackAuthTrusted(for: route) - guard MobileShellRouteAuthPolicy.routeAllowsStackAuth( + guard MobileShellRouteAuthPolicy().routeAllowsStackAuth( route, manualHostTrusted: manualHostTrusted ) else { @@ -3555,12 +3566,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let macs = Self.coalescePairedMacsByDialEndpoint( visibleLoadedMacs, supportedKinds: supportedRouteKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, + routeSelection: routeSelection ) let aliasIDsByMacID = macDeviceIDAliasesByPairedMacID( in: visibleLoadedMacs, supportedKinds: supportedRouteKinds, - preferNonLoopback: Self.prefersNonLoopbackRoutes + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, + routeSelection: routeSelection ) let foregroundMacDeviceIDs = foregroundMacDeviceID.map { aliasIDsByMacID[$0] ?? [$0] @@ -4890,7 +4903,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { cancelRemoteOperationTasks() rawTerminalInputBuffer.clear() let supportedKinds = runtime?.supportedRouteKinds ?? [] - let supportedRoutes = Self.supportedRoutes(for: ticket, supportedKinds: supportedKinds) + let supportedRoutes = routeSelection.supportedRoutes(for: ticket, supportedKinds: supportedKinds) guard let firstRoute = supportedRoutes.first else { // No route kind this build can dial: set the specific category; // the caller records the matching analytics reason from it. @@ -4930,7 +4943,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { activeRoute = route mobileShellLog.info("pairing trying route kind=\(route.kind.rawValue, privacy: .public) endpoint=\(route.endpoint.logDescription, privacy: .private)") let manualHostTrusted = await manualHostStackAuthTrusted(for: route) - let routeAllowsStackAuth = MobileShellRouteAuthPolicy.routeAllowsStackAuth( + let routeAllowsStackAuth = MobileShellRouteAuthPolicy().routeAllowsStackAuth( route, manualHostTrusted: manualHostTrusted ) @@ -5132,7 +5145,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { timeoutNanoseconds: UInt64? = nil ) async -> Bool { let manualHostTrusted = await manualHostStackAuthTrusted(for: route) - guard MobileShellRouteAuthPolicy.routeAllowsStackAuth( + guard MobileShellRouteAuthPolicy().routeAllowsStackAuth( route, manualHostTrusted: manualHostTrusted ), @@ -5547,7 +5560,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { phase: String, routes: [CmxAttachRoute] ) async -> PairingPreflightOutcome { - if routes.contains(where: MobileShellRouteAuthPolicy.routeIsLoopback) { return .proceed } + if routes.contains(where: MobileShellRouteAuthPolicy().routeIsLoopback) { return .proceed } guard await reachability.isOnline == false else { return .proceed } guard isCurrentPairingAttempt(attemptID) else { return .superseded } mobileShellLog.info("pairing preflight: device offline, short-circuiting") diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift similarity index 80% rename from Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift rename to Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift index 973e1dbdfcd4..7ee39b5bd0bd 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift @@ -3,14 +3,19 @@ import CmuxMobileShellModel import Darwin import Foundation -@MainActor -extension MobileShellComposite { +struct MobileShellRouteSelection: Sendable { + let routeAuthPolicy: MobileShellRouteAuthPolicy + + init(routeAuthPolicy: MobileShellRouteAuthPolicy = MobileShellRouteAuthPolicy()) { + self.routeAuthPolicy = routeAuthPolicy + } + /// Whether route selection should avoid loopback routes. A loopback route /// (`.debugLoopback`, `127.0.0.1`) names the host it runs on, so on a /// physical device it can only ever reach the phone itself, never a remote /// Mac. On the simulator `127.0.0.1` IS the host Mac, so loopback is valid /// (and is how the dev/UI-test mock host attaches). - static var prefersNonLoopbackRoutes: Bool { + var prefersNonLoopbackRoutes: Bool { #if targetEnvironment(simulator) false #else @@ -29,13 +34,13 @@ extension MobileShellComposite { /// inside the test runner. This is what lets a restored Mac (whose published /// routes include both `debug_loopback` and `tailscale`) actually connect /// over Tailscale instead of dialing the phone's own loopback and failing. - static func firstReconnectHostPortRoute( + func firstReconnectHostPortRoute( _ routes: [CmxAttachRoute], supportedKinds: [CmxAttachTransportKind], preferNonLoopback: Bool = false ) -> (String, Int)? { let supportedKinds = Set(supportedKinds) - let ordered = routes.sorted(by: Self.routeSortsBefore) + let ordered = routes.sorted(by: routeSortsBefore) func firstHostPort(where predicate: (CmxAttachRoute) -> Bool) -> (String, Int)? { for route in ordered { if !supportedKinds.isEmpty, !supportedKinds.contains(route.kind) { @@ -56,7 +61,7 @@ extension MobileShellComposite { if let tailscaleIP = firstHostPort(where: { route in guard route.kind == .tailscale, case let .hostPort(host, _) = route.endpoint else { return false } - return Self.isIPLiteralHost(host) + return isIPLiteralHost(host) }) { return tailscaleIP } @@ -73,7 +78,7 @@ extension MobileShellComposite { /// Whether `host` is a numeric IP literal (IPv4 or IPv6) rather than a name /// that needs DNS resolution. Used to prefer directly-dialable IP routes over /// MagicDNS hostnames, which fail to resolve on some clients. - static func isIPLiteralHost(_ host: String) -> Bool { + func isIPLiteralHost(_ host: String) -> Bool { let trimmed = host.trimmingCharacters(in: .whitespacesAndNewlines) let unbracketed = if trimmed.hasPrefix("[") && trimmed.hasSuffix("]") { String(trimmed.dropFirst().dropLast()) @@ -91,7 +96,7 @@ extension MobileShellComposite { /// `true` on a physical iPhone/iPad; `false` in the simulator and in /// macOS-hosted package tests. Drives the loopback-pairing rejection. - static var isPhysicalDevice: Bool { + var isPhysicalDevice: Bool { #if os(iOS) && !targetEnvironment(simulator) true #else @@ -99,8 +104,8 @@ extension MobileShellComposite { #endif } - static func manualHostRoute(host: String, port: Int) throws -> CmxAttachRoute { - let routeKind = MobileShellRouteAuthPolicy.manualRouteKind(for: host) + func manualHostRoute(host: String, port: Int) throws -> CmxAttachRoute { + let routeKind = routeAuthPolicy.manualRouteKind(for: host) return try CmxAttachRoute( id: routeKind.rawValue, kind: routeKind, @@ -108,11 +113,11 @@ extension MobileShellComposite { ) } - static func supportedRoutes( + func supportedRoutes( for ticket: CmxAttachTicket, supportedKinds: [CmxAttachTransportKind] ) -> [CmxAttachRoute] { - let orderedRoutes = ticket.routes.sorted(by: Self.routeSortsBefore) + let orderedRoutes = ticket.routes.sorted(by: routeSortsBefore) guard !supportedKinds.isEmpty else { return orderedRoutes } @@ -122,7 +127,14 @@ extension MobileShellComposite { } } - static func attachTicketIsUnexpired(_ ticket: CmxAttachTicket, now: Date) -> Bool { + func attachTicketIsUnexpired(_ ticket: CmxAttachTicket, now: Date) -> Bool { !ticket.isExpired(at: now) } + + private func routeSortsBefore(_ left: CmxAttachRoute, _ right: CmxAttachRoute) -> Bool { + if left.priority == right.priority { + return left.id < right.id + } + return left.priority < right.priority + } } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift index 49eb38c8fdd0..81ea86c44c37 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePreviewTests.swift @@ -463,7 +463,7 @@ import Testing port: CmxMobileDefaults.defaultHostPort ) - let route = MobileShellComposite.firstReconnectHostPortRoute( + let route = MobileShellRouteSelection().firstReconnectHostPortRoute( [loopback, tailscale], supportedKinds: [.tailscale] ) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index 68759810da21..fdff3c05c618 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -37,7 +37,7 @@ import Testing } @Test func physicalDevicePrefersRealRouteOverLowerPriorityLoopback() throws { - let pick = MobileShellComposite.firstReconnectHostPortRoute( + let pick = MobileShellRouteSelection().firstReconnectHostPortRoute( [try loopback(), try tailscale()], supportedKinds: [.debugLoopback, .tailscale], preferNonLoopback: true @@ -47,7 +47,7 @@ import Testing @Test func physicalDeviceFallsBackToLoopbackWhenItIsTheOnlyRoute() throws { // The on-device XCUITest mock host serves a real listener on 127.0.0.1. - let pick = MobileShellComposite.firstReconnectHostPortRoute( + let pick = MobileShellRouteSelection().firstReconnectHostPortRoute( [try loopback()], supportedKinds: [.debugLoopback, .tailscale], preferNonLoopback: true @@ -57,7 +57,7 @@ import Testing @Test func simulatorKeepsLoopbackPriorityOrder() throws { // On the simulator 127.0.0.1 IS the host Mac, so priority order stands. - let pick = MobileShellComposite.firstReconnectHostPortRoute( + let pick = MobileShellRouteSelection().firstReconnectHostPortRoute( [try loopback(), try tailscale()], supportedKinds: [.debugLoopback, .tailscale], preferNonLoopback: false @@ -86,7 +86,7 @@ import Testing endpoint: .hostPort(host: "100.82.214.112", port: 50922), priority: 10 ) - let pick = MobileShellComposite.firstReconnectHostPortRoute( + let pick = MobileShellRouteSelection().firstReconnectHostPortRoute( [try loopback(50922), try magicDNS(50922), ip], supportedKinds: [.debugLoopback, .tailscale], preferNonLoopback: true @@ -97,7 +97,7 @@ import Testing @Test func magicDNSHostnameStillUsedWhenNoIPRouteExists() throws { // If the only non-loopback route is a hostname, still prefer it over // loopback on device (better than dialing the phone's own 127.0.0.1). - let pick = MobileShellComposite.firstReconnectHostPortRoute( + let pick = MobileShellRouteSelection().firstReconnectHostPortRoute( [try loopback(50922), try magicDNS(50922)], supportedKinds: [.debugLoopback, .tailscale], preferNonLoopback: true @@ -106,7 +106,7 @@ import Testing } @Test func tailscaleDNSBeatsManualHostIPFallback() throws { - let pick = MobileShellComposite.firstReconnectHostPortRoute( + let pick = MobileShellRouteSelection().firstReconnectHostPortRoute( [try loopback(50922), try manualHost(50922), try magicDNS(50922)], supportedKinds: [.debugLoopback, .manualHost, .tailscale], preferNonLoopback: true @@ -115,15 +115,15 @@ import Testing } @Test func ipLiteralHostClassification() { - #expect(MobileShellComposite.isIPLiteralHost("100.82.214.112")) - #expect(MobileShellComposite.isIPLiteralHost("127.0.0.1")) - #expect(MobileShellComposite.isIPLiteralHost("fd7a:115c:a1e0::4b36:d670")) - #expect(MobileShellComposite.isIPLiteralHost("::ffff:192.168.0.1")) - #expect(MobileShellComposite.isIPLiteralHost("[fd7a:115c:a1e0::4b36:d670]")) - #expect(!MobileShellComposite.isIPLiteralHost("lawrences-macbook-pro-2.tail137216.ts.net")) - #expect(!MobileShellComposite.isIPLiteralHost("example.com")) - #expect(!MobileShellComposite.isIPLiteralHost("my:host")) - #expect(!MobileShellComposite.isIPLiteralHost("100.82.214")) // too few octets - #expect(!MobileShellComposite.isIPLiteralHost("256.1.1.1")) // out of range + #expect(MobileShellRouteSelection().isIPLiteralHost("100.82.214.112")) + #expect(MobileShellRouteSelection().isIPLiteralHost("127.0.0.1")) + #expect(MobileShellRouteSelection().isIPLiteralHost("fd7a:115c:a1e0::4b36:d670")) + #expect(MobileShellRouteSelection().isIPLiteralHost("::ffff:192.168.0.1")) + #expect(MobileShellRouteSelection().isIPLiteralHost("[fd7a:115c:a1e0::4b36:d670]")) + #expect(!MobileShellRouteSelection().isIPLiteralHost("lawrences-macbook-pro-2.tail137216.ts.net")) + #expect(!MobileShellRouteSelection().isIPLiteralHost("example.com")) + #expect(!MobileShellRouteSelection().isIPLiteralHost("my:host")) + #expect(!MobileShellRouteSelection().isIPLiteralHost("100.82.214")) // too few octets + #expect(!MobileShellRouteSelection().isIPLiteralHost("256.1.1.1")) // out of range } } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift index cd7374da1cda..3e85183f5451 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift @@ -20,7 +20,7 @@ public struct MobileManualHostTrustScope: Equatable, Hashable, Sendable { /// - port: The TCP port in `1...65535`. /// - stackUserID: The approving Stack user id, if known. public init?(host: String, port: Int, stackUserID: String?) { - guard let manualHost = Self.normalizedTrustHost(host), + guard let manualHost = CmxManualHost(routeHost: host), (1...65535).contains(port) else { return nil } @@ -43,28 +43,17 @@ public struct MobileManualHostTrustScope: Equatable, Hashable, Sendable { var storageKey: String { [ - Self.escape(stackUserID ?? ""), - Self.escape(normalizedHost), + (stackUserID ?? "").mobileManualHostTrustStorageEscaped, + normalizedHost.mobileManualHostTrustStorageEscaped, "\(port)", ].joined(separator: "|") } +} - private static func escape(_ value: String) -> String { - value +private extension String { + var mobileManualHostTrustStorageEscaped: String { + self .replacing("%", with: "%25") .replacing("|", with: "%7C") } - - private static func normalizedTrustHost(_ host: String) -> CmxManualHost? { - if let manualHost = CmxManualHost(host) { - return manualHost - } - let trimmed = host.trimmingCharacters(in: .whitespacesAndNewlines) - let ipv6Characters = CharacterSet(charactersIn: "0123456789abcdefABCDEF:.") - guard trimmed.contains(":"), - trimmed.unicodeScalars.allSatisfy({ ipv6Characters.contains($0) }) else { - return nil - } - return CmxManualHost("[\(trimmed)]") - } } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift index a159fbbe2ad8..ff48cc6dbc65 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift @@ -15,14 +15,20 @@ import Foundation /// manual-host route only after the user accepts the plaintext-LAN warning. /// Plain private-LAN and `.local`/Bonjour hosts remain excluded by default even /// though they may still be reachable as attach routes. -public struct MobileShellRouteAuthPolicy { - private init() {} +public struct MobileShellRouteAuthPolicy: Sendable { + private let loopbackHost: CmxLoopbackHost + + /// Creates a route-auth policy with an injectable loopback host matcher. + /// - Parameter loopbackHost: Matcher used to recognize loopback aliases. + public init(loopbackHost: CmxLoopbackHost = CmxLoopbackHost()) { + self.loopbackHost = loopbackHost + } /// Normalizes a raw, user-entered host string, stripping IPv6 brackets and /// rejecting anything that contains scheme/path/whitespace characters. /// - Parameter rawHost: The raw host string typed by the user. /// - Returns: The normalized bare host, or `nil` when it is not a valid host. - public static func normalizedManualHost(_ rawHost: String) -> String? { + public func normalizedManualHost(_ rawHost: String) -> String? { CmxManualHost(rawHost)?.rawValue } @@ -30,15 +36,15 @@ public struct MobileShellRouteAuthPolicy { /// /// Unlike ``normalizedManualHost(_:)``, this accepts bare IPv6 because route /// endpoints store IPv6 hosts without brackets. - public static func normalizedManualRouteHost(_ rawHost: String) -> String? { - CmxManualHost.normalizedRouteHost(rawHost) + public func normalizedManualRouteHost(_ rawHost: String) -> String? { + CmxManualHost(routeHost: rawHost)?.rawValue } /// Maps a manually typed host to the transport kind that should be used. /// - Parameter host: The host to classify. /// - Returns: `.debugLoopback` for loopback hosts, `.tailscale` for /// Tailscale IP/MagicDNS hosts, otherwise `.manualHost`. - public static func manualRouteKind(for host: String) -> CmxAttachTransportKind { + public func manualRouteKind(for host: String) -> CmxAttachTransportKind { let normalizedHost = (normalizedManualRouteHost(host) ?? host) .trimmingCharacters(in: .whitespacesAndNewlines) .lowercased() @@ -75,7 +81,7 @@ public struct MobileShellRouteAuthPolicy { /// explicit persisted trust approval. /// - Returns: `true` only for Tailscale-tunnel, iroh peer, loopback, and /// explicitly approved manual-host routes. - public static func routeAllowsStackAuth( + public func routeAllowsStackAuth( _ route: CmxAttachRoute, manualHostTrusted: Bool = false ) -> Bool { @@ -96,7 +102,7 @@ public struct MobileShellRouteAuthPolicy { /// Whether a route is an explicit manual-host route that needs approval. /// - Parameter route: The candidate attach route. /// - Returns: `true` only for `.manualHost` host/port routes. - public static func routeRequiresManualHostTrust(_ route: CmxAttachRoute) -> Bool { + public func routeRequiresManualHostTrust(_ route: CmxAttachRoute) -> Bool { guard route.kind == .manualHost, case let .hostPort(host, _) = route.endpoint else { return false @@ -121,18 +127,18 @@ public struct MobileShellRouteAuthPolicy { /// simulator and on other platforms. /// - Returns: `true` when the ticket must fail with the loopback-rejected /// error instead of connecting. - public static func ticketRejectsLoopbackRoutes( + public func ticketRejectsLoopbackRoutes( _ routes: [CmxAttachRoute], isPhysicalDevice: Bool ) -> Bool { - isPhysicalDevice && routes.contains(where: CmxLoopbackHost().matches) + isPhysicalDevice && routes.contains(where: routeIsLoopback) } /// Whether the given route may carry Stack auth when reached via an implicit /// pair-link (no explicit attach token), restricted to loopback only. /// - Parameter route: The candidate attach route. /// - Returns: `true` only for loopback host/port routes. - public static func routeAllowsImplicitPairLinkStackAuth(_ route: CmxAttachRoute) -> Bool { + public func routeAllowsImplicitPairLinkStackAuth(_ route: CmxAttachRoute) -> Bool { switch (route.kind, route.endpoint) { case (.debugLoopback, let .hostPort(host, _)): return isLoopbackHost(host) @@ -147,7 +153,7 @@ public struct MobileShellRouteAuthPolicy { /// dial it. /// - Parameter route: The candidate attach route. /// - Returns: `true` when the route's host/port endpoint is a loopback host. - public static func routeIsLoopback(_ route: CmxAttachRoute) -> Bool { + public func routeIsLoopback(_ route: CmxAttachRoute) -> Bool { guard case let .hostPort(host, _) = route.endpoint else { return false } @@ -157,34 +163,34 @@ public struct MobileShellRouteAuthPolicy { /// Whether a manual host should warn the user that it is neither loopback nor Tailscale. /// - Parameter host: The manually typed host. /// - Returns: `true` when the host is valid but outside the loopback/Tailscale trust set. - public static func manualHostNeedsTrustWarning(_ host: String) -> Bool { + public func manualHostNeedsTrustWarning(_ host: String) -> Bool { guard normalizedManualNetworkHost(host) != nil else { return false } return manualRouteKind(for: host) == .manualHost } - private static func normalizedManualNetworkHost(_ host: String) -> String? { + private func normalizedManualNetworkHost(_ host: String) -> String? { normalizedManualHost(host)?.lowercased() } - private static func isLoopbackHost(_ host: String) -> Bool { - CmxLoopbackHost().matches(host) + private func isLoopbackHost(_ host: String) -> Bool { + loopbackHost.matches(host) } - private static func isTailscaleHost(_ host: String) -> Bool { + private func isTailscaleHost(_ host: String) -> Bool { let normalizedHost = host.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() return isTailscaleDNSHost(normalizedHost) || isTailscaleIPv4Host(normalizedHost) } - private static func isTailscaleIPv4Host(_ host: String) -> Bool { + private func isTailscaleIPv4Host(_ host: String) -> Bool { guard let octets = ipv4Octets(host) else { return false } return octets[0] == 100 && (64...127).contains(octets[1]) } - private static func ipv4Octets(_ host: String) -> [Int]? { + private func ipv4Octets(_ host: String) -> [Int]? { let parts = host.split(separator: ".", omittingEmptySubsequences: false) guard parts.count == 4 else { return nil @@ -204,7 +210,7 @@ public struct MobileShellRouteAuthPolicy { return octets } - private static func isTailscaleDNSHost(_ host: String) -> Bool { + private func isTailscaleDNSHost(_ host: String) -> Bool { host.trimmingCharacters(in: .whitespacesAndNewlines) .lowercased() .hasSuffix(".ts.net") diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index bbadca80dc20..6cb8514b44d1 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -35,13 +35,13 @@ import Testing priority: 0 ) - #expect(MobileShellRouteAuthPolicy.routeIsLoopback(loopbackIP)) - #expect(MobileShellRouteAuthPolicy.routeIsLoopback(localhost)) - #expect(MobileShellRouteAuthPolicy.routeIsLoopback(ipv6Loopback)) - #expect(MobileShellRouteAuthPolicy.routeIsLoopback(loopbackOnNetworkKind)) - #expect(!MobileShellRouteAuthPolicy.routeIsLoopback(pretendLoopback)) - #expect(!MobileShellRouteAuthPolicy.routeIsLoopback(tailscaleIP)) - #expect(!MobileShellRouteAuthPolicy.routeIsLoopback(irohPeer)) + #expect(MobileShellRouteAuthPolicy().routeIsLoopback(loopbackIP)) + #expect(MobileShellRouteAuthPolicy().routeIsLoopback(localhost)) + #expect(MobileShellRouteAuthPolicy().routeIsLoopback(ipv6Loopback)) + #expect(MobileShellRouteAuthPolicy().routeIsLoopback(loopbackOnNetworkKind)) + #expect(!MobileShellRouteAuthPolicy().routeIsLoopback(pretendLoopback)) + #expect(!MobileShellRouteAuthPolicy().routeIsLoopback(tailscaleIP)) + #expect(!MobileShellRouteAuthPolicy().routeIsLoopback(irohPeer)) } @Test func allowsStackAuthOnlyForEncryptedLoopbackOrApprovedManualHostRoutes() throws { @@ -63,43 +63,43 @@ import Testing let manualUnspecifiedIPv4 = try hostPortRoute(kind: .manualHost, host: "0.0.0.0", port: CmxMobileDefaults.defaultHostPort) let manualHexLoopback = try hostPortRoute(kind: .manualHost, host: "0x7f.0.0.1", port: CmxMobileDefaults.defaultHostPort) - #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "127.0.0.1") == .debugLoopback) - #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "127.1") == .debugLoopback) - #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "0.0.0.0") == .debugLoopback) - #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "0x7f.0.0.1") == .debugLoopback) - #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "[::1]") == .debugLoopback) - #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "100.71.210.41") == .tailscale) - #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "work-mac.tailnet.ts.net") == .tailscale) - #expect(MobileShellRouteAuthPolicy.manualRouteKind(for: "127.attacker.example") == .manualHost) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "127.0.0.1") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "127.1") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "0.0.0.0") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "0x7f.0.0.1") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "[::1]") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "100.71.210.41") == .tailscale) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "work-mac.tailnet.ts.net") == .tailscale) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "127.attacker.example") == .manualHost) // Encrypted / loopback channels and explicitly approved manual hosts may // carry the Stack bearer token. - #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(loopback)) - #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(tailscaleMagicDNS)) - #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(tailscaleIP)) - #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(irohPeer)) - #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualHostRoute)) - #expect(MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualHostRoute, manualHostTrusted: true)) - #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualLoopbackAlias, manualHostTrusted: true)) - #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualUnspecifiedIPv4, manualHostTrusted: true)) - #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(manualHexLoopback, manualHostTrusted: true)) + #expect(MobileShellRouteAuthPolicy().routeAllowsStackAuth(loopback)) + #expect(MobileShellRouteAuthPolicy().routeAllowsStackAuth(tailscaleMagicDNS)) + #expect(MobileShellRouteAuthPolicy().routeAllowsStackAuth(tailscaleIP)) + #expect(MobileShellRouteAuthPolicy().routeAllowsStackAuth(irohPeer)) + #expect(!MobileShellRouteAuthPolicy().routeAllowsStackAuth(manualHostRoute)) + #expect(MobileShellRouteAuthPolicy().routeAllowsStackAuth(manualHostRoute, manualHostTrusted: true)) + #expect(!MobileShellRouteAuthPolicy().routeAllowsStackAuth(manualLoopbackAlias, manualHostTrusted: true)) + #expect(!MobileShellRouteAuthPolicy().routeAllowsStackAuth(manualUnspecifiedIPv4, manualHostTrusted: true)) + #expect(!MobileShellRouteAuthPolicy().routeAllowsStackAuth(manualHexLoopback, manualHostTrusted: true)) // Plaintext-TCP routes must NOT carry the Stack bearer token by default: // a `.tailscale` route to a private-LAN IP or a `.local`/Bonjour host is // dialed over unencrypted TCP, so it is excluded from the Stack-auth set. - #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(lanIP)) - #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(localDNS)) - #expect(!MobileShellRouteAuthPolicy.routeAllowsStackAuth(pretendLoopback)) - #expect(!MobileShellRouteAuthPolicy.routeRequiresManualHostTrust(manualLoopbackAlias)) - - #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("127.0.0.1")) - #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("127.1")) - #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("0.0.0.0")) - #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("0x7f.0.0.1")) - #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("100.71.210.41")) - #expect(!MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("work-mac.tailnet.ts.net")) - #expect(MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("192.168.1.77")) - #expect(MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning("devbox.local")) + #expect(!MobileShellRouteAuthPolicy().routeAllowsStackAuth(lanIP)) + #expect(!MobileShellRouteAuthPolicy().routeAllowsStackAuth(localDNS)) + #expect(!MobileShellRouteAuthPolicy().routeAllowsStackAuth(pretendLoopback)) + #expect(!MobileShellRouteAuthPolicy().routeRequiresManualHostTrust(manualLoopbackAlias)) + + #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("127.0.0.1")) + #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("127.1")) + #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("0.0.0.0")) + #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("0x7f.0.0.1")) + #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("100.71.210.41")) + #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("work-mac.tailnet.ts.net")) + #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("192.168.1.77")) + #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("devbox.local")) } @Test func manualHostTrustScopeIsHostPortAndAccountScoped() async throws { @@ -216,22 +216,22 @@ import Testing let loopbackUnderTailscaleKind = try hostPortRoute(kind: .tailscale, host: "127.0.0.1", port: 56577) let tailscale = try hostPortRoute(kind: .tailscale, host: "100.71.210.41", port: 56577) - #expect(MobileShellRouteAuthPolicy.ticketRejectsLoopbackRoutes( + #expect(MobileShellRouteAuthPolicy().ticketRejectsLoopbackRoutes( [loopback], isPhysicalDevice: true )) - #expect(MobileShellRouteAuthPolicy.ticketRejectsLoopbackRoutes( + #expect(MobileShellRouteAuthPolicy().ticketRejectsLoopbackRoutes( [loopbackUnderTailscaleKind], isPhysicalDevice: true )) // One loopback route poisons the ticket even when a real route rides along. - #expect(MobileShellRouteAuthPolicy.ticketRejectsLoopbackRoutes( + #expect(MobileShellRouteAuthPolicy().ticketRejectsLoopbackRoutes( [tailscale, loopback], isPhysicalDevice: true )) - #expect(!MobileShellRouteAuthPolicy.ticketRejectsLoopbackRoutes( + #expect(!MobileShellRouteAuthPolicy().ticketRejectsLoopbackRoutes( [tailscale], isPhysicalDevice: true )) // The simulator flow legitimately pairs over loopback (127.0.0.1 IS // the host Mac there), so the policy never fires off-device. - #expect(!MobileShellRouteAuthPolicy.ticketRejectsLoopbackRoutes( + #expect(!MobileShellRouteAuthPolicy().ticketRejectsLoopbackRoutes( [loopback], isPhysicalDevice: false )) } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift index 5da469d8c2b4..a20b4ee4b50d 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift @@ -320,7 +320,7 @@ struct PairingView: View { let trimmedHost = host.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedHost.isEmpty, !CmxPairingURLScheme.hasPairingScheme(trimmedHost), - MobileShellRouteAuthPolicy.manualHostNeedsTrustWarning(trimmedHost) else { + MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning(trimmedHost) else { return nil } return L10n.string( @@ -364,7 +364,7 @@ struct PairingView: View { } return } - guard MobileShellRouteAuthPolicy.normalizedManualHost(trimmedHost) != nil else { + guard MobileShellRouteAuthPolicy().normalizedManualHost(trimmedHost) != nil else { validationError = L10n.string("mobile.addDevice.invalidHost", defaultValue: "Enter a host or IP address, without spaces or URL paths.") return } diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobilePairingManualHostAdvertisability.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobilePairingManualHostAdvertisability.swift new file mode 100644 index 000000000000..1b0cfd63bd36 --- /dev/null +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobilePairingManualHostAdvertisability.swift @@ -0,0 +1,15 @@ +import CMUXMobileCore +import Foundation + +struct MobilePairingManualHostAdvertisability: Sendable { + func isAdvertisable(_ rawHost: String) -> Bool { + let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { + return true + } + guard let host = CmxManualHost(trimmed) else { + return false + } + return !CmxLoopbackHost().matches(host.rawValue) + } +} diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift index 8ab70fd042f2..f1ce2aa97f13 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift @@ -1,4 +1,3 @@ -import CMUXMobileCore import CmuxFoundation import CmuxSettings import SwiftUI @@ -15,6 +14,8 @@ public struct MobileSection: View { @State private var displayName: DefaultsValueModel @State private var status: MobilePairingStatusModel + private let manualHostAdvertisability = MobilePairingManualHostAdvertisability() + /// The user's in-progress port edit, or `nil` when the field should track /// the persisted value. Local so editing does not rebind the listener; only /// the **Apply** button does, after checking the port is free. `nil` lets the @@ -73,18 +74,7 @@ public struct MobileSection: View { } private var isManualHostValid: Bool { - Self.isManualHostAdvertisable(trimmedManualHost) - } - - nonisolated static func isManualHostAdvertisable(_ rawHost: String) -> Bool { - let trimmed = rawHost.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { - return true - } - guard let host = CmxManualHost(trimmed) else { - return false - } - return !CmxLoopbackHost().matches(host.rawValue) + manualHostAdvertisability.isAdvertisable(trimmedManualHost) } /// The Mobile settings section content. diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift index a70ae276130f..952ffe928933 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift @@ -19,14 +19,15 @@ import Testing @Suite("SettingsRowAnchorResolution") struct SettingsRowAnchorResolutionTests { @Test func mobileManualHostAdvertisableValidatorRejectsLoopback() { - #expect(MobileSection.isManualHostAdvertisable("")) - #expect(MobileSection.isManualHostAdvertisable(" 192.168.1.23 ")) - #expect(MobileSection.isManualHostAdvertisable("studio-mac.local")) - #expect(MobileSection.isManualHostAdvertisable("[fd00::12]")) - #expect(!MobileSection.isManualHostAdvertisable("127.0.0.1")) - #expect(!MobileSection.isManualHostAdvertisable("localhost")) - #expect(!MobileSection.isManualHostAdvertisable("[::1]")) - #expect(!MobileSection.isManualHostAdvertisable("my:host")) + let validator = MobilePairingManualHostAdvertisability() + #expect(validator.isAdvertisable("")) + #expect(validator.isAdvertisable(" 192.168.1.23 ")) + #expect(validator.isAdvertisable("studio-mac.local")) + #expect(validator.isAdvertisable("[fd00::12]")) + #expect(!validator.isAdvertisable("127.0.0.1")) + #expect(!validator.isAdvertisable("localhost")) + #expect(!validator.isAdvertisable("[::1]")) + #expect(!validator.isAdvertisable("my:host")) } /// Every singular cmux.json path declared by an *unconditionally diff --git a/Sources/Cloud/RemoteRouteSpec.swift b/Sources/Cloud/RemoteRouteSpec.swift index 1f715311adc8..5c22b9699b8b 100644 --- a/Sources/Cloud/RemoteRouteSpec.swift +++ b/Sources/Cloud/RemoteRouteSpec.swift @@ -75,7 +75,7 @@ struct RemoteRouteSpec: Equatable { /// Whether a signed-in phone could authenticate to this host from the /// registry. Manual routes are stored as `.tailscale`, and the iOS attach - /// path (`MobileShellRouteAuthPolicy.routeAllowsStackAuth`) only sends the + /// path (`MobileShellRouteAuthPolicy().routeAllowsStackAuth`) only sends the /// Stack token over a `.tailscale` route whose host is a Tailscale address: /// a CGNAT `100.64.0.0/10` IP or a `*.ts.net` MagicDNS name. Any other host /// (LAN IP, bare hostname, Tailscale IPv6 ULA) would show in the device list diff --git a/Sources/Mobile/MobileHostService.swift b/Sources/Mobile/MobileHostService.swift index c660df9fe47f..d1ac5aa2aef5 100644 --- a/Sources/Mobile/MobileHostService.swift +++ b/Sources/Mobile/MobileHostService.swift @@ -149,9 +149,9 @@ private final class MobileHostConnectionRegistry: @unchecked Sendable { } } +// `routes` protects every mutation/copy so nonisolated status RPCs avoid a main-actor hop. private final class MobileHostPublicStatusSnapshot: @unchecked Sendable { private let routes = OSAllocatedUnfairLock(initialState: [CmxAttachRoute]()) - func update(routes nextRoutes: [CmxAttachRoute]) { routes.withLock { $0 = nextRoutes } NotificationCenter.default.post(name: .mobileHostStatusDidChange, object: nil) diff --git a/Sources/Mobile/MobileRouteResolver.swift b/Sources/Mobile/MobileRouteResolver.swift index 5a1644149cec..72164ae6d402 100644 --- a/Sources/Mobile/MobileRouteResolver.swift +++ b/Sources/Mobile/MobileRouteResolver.swift @@ -99,7 +99,7 @@ final class MobileRouteResolver: @unchecked Sendable { } } - if let manualHost = manualHost.flatMap({ CmxManualHost.normalizedRouteHost($0) }), + if let manualHost = manualHost.flatMap({ CmxManualHost(routeHost: $0)?.rawValue }), !CmxLoopbackHost().matches(manualHost) { let manualPriority = 10 + (tailscaleHosts.count * 10) if let manualRoute = try? CmxAttachRoute( diff --git a/Sources/Mobile/Pairing/MobilePairingRouteReachability.swift b/Sources/Mobile/Pairing/MobilePairingRouteReachability.swift new file mode 100644 index 000000000000..48045c4e1d54 --- /dev/null +++ b/Sources/Mobile/Pairing/MobilePairingRouteReachability.swift @@ -0,0 +1,6 @@ +enum MobilePairingRouteReachability: Equatable { + case tailscale + case manualHost + case missing + case unknown +} diff --git a/Sources/Mobile/Pairing/MobilePairingView.swift b/Sources/Mobile/Pairing/MobilePairingView.swift index 63a624ec4eda..a1a1fa68133e 100644 --- a/Sources/Mobile/Pairing/MobilePairingView.swift +++ b/Sources/Mobile/Pairing/MobilePairingView.swift @@ -97,14 +97,7 @@ struct MobilePairingView: View { } } - private enum RouteReachability: Equatable { - case tailscale - case manualHost - case missing - case unknown - } - - private var routeReachability: RouteReachability { + private var routeReachability: MobilePairingRouteReachability { switch model.state { case let .ready(ready), let .connected(ready): if ready.reachableViaTailscale { return .tailscale } @@ -117,7 +110,7 @@ struct MobilePairingView: View { } } - private func routeSubtitle(_ state: RouteReachability) -> String { + private func routeSubtitle(_ state: MobilePairingRouteReachability) -> String { switch state { case .tailscale: return String(localized: "mobile.pairing.req.tailscale.reachable", defaultValue: "Reachable over Tailscale.") diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index a18735ed55f9..8b2407488c17 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -704,6 +704,7 @@ 9B08F916D7FF7626C6820727 /* MobilePairingConnectionTransitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4880BD05924400E5279D632 /* MobilePairingConnectionTransitionTests.swift */; }; 0099C2865D9D468747D14593 /* MobilePairingModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04CE82AE8B39EA0C1395F696 /* MobilePairingModel.swift */; }; 325AF8814443BDA97AC3CC98 /* MobilePairingQRImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B76EC5E03C345BEAC25828A7 /* MobilePairingQRImageView.swift */; }; + 7230A0037230A0037230A003 /* MobilePairingRouteReachability.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7230B0037230B0037230B003 /* MobilePairingRouteReachability.swift */; }; A2538FE83AE79539E3BF9248 /* MobilePairingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9BC53FA4991A6EBFB930EDF /* MobilePairingView.swift */; }; 18A8E29E9BD87E184983527C /* MobilePairingWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AE701F43A0B49F08835191C /* MobilePairingWindowController.swift */; }; 9916B44C7A9914E172D112D4 /* MobileRouteResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A956C76162B79EC74AF9965 /* MobileRouteResolver.swift */; }; @@ -1987,6 +1988,7 @@ A4880BD05924400E5279D632 /* MobilePairingConnectionTransitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobilePairingConnectionTransitionTests.swift; sourceTree = ""; }; 04CE82AE8B39EA0C1395F696 /* MobilePairingModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Pairing/MobilePairingModel.swift"; sourceTree = ""; }; B76EC5E03C345BEAC25828A7 /* MobilePairingQRImageView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Pairing/MobilePairingQRImageView.swift"; sourceTree = ""; }; + 7230B0037230B0037230B003 /* MobilePairingRouteReachability.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Pairing/MobilePairingRouteReachability.swift"; sourceTree = ""; }; F9BC53FA4991A6EBFB930EDF /* MobilePairingView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Pairing/MobilePairingView.swift"; sourceTree = ""; }; 5AE701F43A0B49F08835191C /* MobilePairingWindowController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Pairing/MobilePairingWindowController.swift"; sourceTree = ""; }; 7A956C76162B79EC74AF9965 /* MobileRouteResolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MobileRouteResolver.swift; sourceTree = ""; }; @@ -2756,6 +2758,7 @@ 7A956C76162B79EC74AF9965 /* MobileRouteResolver.swift */, 04CE82AE8B39EA0C1395F696 /* MobilePairingModel.swift */, B76EC5E03C345BEAC25828A7 /* MobilePairingQRImageView.swift */, + 7230B0037230B0037230B003 /* MobilePairingRouteReachability.swift */, F9BC53FA4991A6EBFB930EDF /* MobilePairingView.swift */, 5AE701F43A0B49F08835191C /* MobilePairingWindowController.swift */, C9F14137954A34DFFA05C88C /* MobileWorkspaceListObserver.swift */, @@ -4755,6 +4758,7 @@ 4C1A7E10B2D34F56A8C90011 /* MobileHostStatusVerificationLimiter.swift in Sources */, 0099C2865D9D468747D14593 /* MobilePairingModel.swift in Sources */, 325AF8814443BDA97AC3CC98 /* MobilePairingQRImageView.swift in Sources */, + 7230A0037230A0037230A003 /* MobilePairingRouteReachability.swift in Sources */, A2538FE83AE79539E3BF9248 /* MobilePairingView.swift in Sources */, 18A8E29E9BD87E184983527C /* MobilePairingWindowController.swift in Sources */, 9916B44C7A9914E172D112D4 /* MobileRouteResolver.swift in Sources */, From 3c3420f6ca23e0df1be4e9f3452692eb509b9c24 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 09:57:46 -0700 Subject: [PATCH 19/91] Defer manual host fallback approval --- .../MobileShellComposite+ManualHostTrust.swift | 14 ++++++++++---- .../MobilePairingAttemptDeadlineTests.swift | 13 +++++++------ 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 29379e3ea9ee..a8661cebb77d 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -48,12 +48,18 @@ extension MobileShellComposite { func firstManualHostRouteNeedingApproval( in routes: [CmxAttachRoute] ) async -> (route: CmxAttachRoute, scope: MobileManualHostTrustScope)? { + let routeAuthPolicy = MobileShellRouteAuthPolicy() for route in routes { - guard let scope = manualHostTrustScope(for: route) else { - continue + if let scope = manualHostTrustScope(for: route) { + if !(await manualHostTrustStore.isTrusted(scope)) { + return (route, scope) + } + return nil } - if !(await manualHostTrustStore.isTrusted(scope)) { - return (route, scope) + if routeAuthPolicy.routeAllowsStackAuth(route) { + // A safer route will be selected before any later manual-host fallback. + // Do not train the user to approve plaintext LAN unless it is needed. + return nil } } return nil diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 5c8f3ba9cf5a..bd6cc2059416 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -50,7 +50,7 @@ import Testing let runtime = LivenessTestRuntime( transportFactory: LivenessTransportFactory(router: router, box: box), now: { clock.now }, - supportedRouteKinds: [.tailscale] + supportedRouteKinds: [.tailscale, .manualHost] ) let store = makeStore(runtime: runtime) let trustedRoute = try CmxAttachRoute( @@ -59,10 +59,10 @@ import Testing endpoint: .hostPort(host: "100.64.0.5", port: 58_465), priority: 0 ) - let untrustedRoute = try CmxAttachRoute( - id: "b-public-fallback", - kind: .tailscale, - endpoint: .hostPort(host: "203.0.113.10", port: 58_465), + let manualFallbackRoute = try CmxAttachRoute( + id: "b-manual-fallback", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465), priority: 1 ) let ticket = try CmxAttachTicket( @@ -71,7 +71,7 @@ import Testing macDeviceID: "test-mac", macDisplayName: "Test Mac", macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, - routes: [trustedRoute, untrustedRoute], + routes: [trustedRoute, manualFallbackRoute], expiresAt: clock.now.addingTimeInterval(3600) ) @@ -79,6 +79,7 @@ import Testing #expect(result == .connected) #expect(store.connectionState == .connected) + #expect(store.manualHostTrustWarning == nil) #expect(store.selectedWorkspace?.id.rawValue == "live-workspace") } From abdc2d32ed4b0a1135ed2b14f71d3efc1cf99f1a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 10:07:25 -0700 Subject: [PATCH 20/91] Address manual host trust review feedback --- .../MobileShellComposite.swift | 1 + ...erDefaultsMobileManualHostTrustStore.swift | 2 +- .../CMUXMobileRootView+PairingWarnings.swift | 6 ++++- .../CMUXMobileRootView.swift | 18 ++++++------- .../cmuxFeatureTests/cmuxFeatureTests.swift | 26 +++++++++++++++++++ 5 files changed, 42 insertions(+), 11 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 136d0dec70b2..b54181ba6723 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1194,6 +1194,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// lists" behavior). public func currentTeamDidChange() { secondaryAggregationScopeGeneration &+= 1 + clearManualHostTrustWarning() // Presence: cancel + re-subscribe so the online dots reflect the new team // (the subscribe reads the team live). Cheap live socket; the only eager bit. presenceTask?.cancel() diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift index aaa21a5c13ec..f17e475b2cc3 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -1,7 +1,7 @@ import Foundation import OSLog -private let manualHostTrustStoreLog = Logger(subsystem: "com.cmuxterm.app", category: "ManualHostTrust") +nonisolated private let manualHostTrustStoreLog = Logger(subsystem: "com.cmuxterm.app", category: "ManualHostTrust") /// UserDefaults-backed manual-host trust store for production. public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStoring { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift index d4d8b82bac80..29f8b98cfa3f 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift @@ -5,7 +5,11 @@ extension CMUXMobileRootView { func showManualHostTrustWarningIfNeeded( _ warning: MobileManualHostTrustWarning? = nil ) { - guard warning ?? store.manualHostTrustWarning != nil else { + guard warning ?? store.manualHostTrustWarning != nil, + isAuthenticated, + !authManager.isRestoringSession, + !shouldShowOnboarding, + !isShowingAddDeviceSheet else { return } showAddDevice() diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index eb8f1a31f8f5..3dc6554794b7 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -14,7 +14,7 @@ import AppKit struct CMUXMobileRootView: View { @Bindable var store: CMUXMobileShellStore @Environment(\.scenePhase) private var scenePhase - @Environment(AuthCoordinator.self) private var authManager + @Environment(AuthCoordinator.self) var authManager #if os(iOS) @Environment(MobilePushCoordinator.self) private var pushCoordinator /// The persisted first-run onboarding "seen" flag store. The one-time @@ -30,7 +30,7 @@ struct CMUXMobileRootView: View { @State private var pendingAttachURL: String? @State private var didConsumeUITestAttachURL = false @State private var didAuthenticateWithAttachTicket = false - @State private var isShowingAddDeviceSheet = false + @State var isShowingAddDeviceSheet = false #if os(iOS) @State private var addDeviceSheetDetent: PresentationDetent = .large #endif @@ -171,15 +171,15 @@ struct CMUXMobileRootView: View { guard isAuthenticated else { return } - if consumePendingURLIfReady() { - return + if !consumePendingURLIfReady() { + showManualHostTrustWarningIfNeeded() + reconnectStoredMacIfNeeded() } - reconnectStoredMacIfNeeded() } .onChange(of: authManager.isRestoringSession) { _, isRestoringSession in syncShellAuthentication(isAuthenticated, isRestoringSession: isRestoringSession) guard !isRestoringSession else { return } - _ = consumePendingURLIfReady() + if !consumePendingURLIfReady() { showManualHostTrustWarningIfNeeded() } } .onChange(of: store.connectionState) { _, connectionState in if connectionState == .connected { @@ -301,7 +301,7 @@ struct CMUXMobileRootView: View { /// Whether the one-time first-run onboarding should be presented. Always /// `false` off iOS (onboarding is iOS-only). - private var shouldShowOnboarding: Bool { + var shouldShowOnboarding: Bool { #if os(iOS) return MobileOnboardingGate.shouldShowOnboarding( hasSeenOnboarding: hasSeenOnboarding @@ -327,10 +327,10 @@ struct CMUXMobileRootView: View { private func completeOnboarding() { onboardingStore.markSeen() hasSeenOnboarding = true + showManualHostTrustWarningIfNeeded() } #endif - - private var isAuthenticated: Bool { + var isAuthenticated: Bool { MobileRootAuthGate.isAuthenticated( stackAuthenticated: authManager.isAuthenticated, attachTicketAuthenticated: hasActiveAttachTicketAuthentication diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 6ef70e62ed4e..4379f1393b4d 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -2000,6 +2000,32 @@ final class TerminalOutputCollector { #expect(try await responses.sentRequests().isEmpty) } +@MainActor +@Test func teamSwitchClearsPendingManualHostTrustWarning() async throws { + let responses = ScriptedTransportResponses([]) + let runtime = testRuntime( + supportedRouteKinds: [.manualHost], + transportFactory: ScriptedTransportFactory(responses: responses), + stackAccessToken: "stack-token-for-team-switch-manual-warning" + ) + let store = CMUXMobileShellStore.preview( + runtime: runtime, + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + + store.signIn() + let firstResult = await store.connectPairingURLResult( + "cmux-ios://attach?v=3&pc=1&m=studio-mac.local:61234" + ) + store.currentTeamDidChange() + let staleApprovalResult = await store.acceptManualHostTrustWarning() + + #expect(firstResult == .needsUserApproval) + #expect(staleApprovalResult == .failed) + #expect(store.manualHostTrustWarning == nil) + #expect(try await responses.sentRequests().isEmpty) +} + @MainActor @Test func manualHostTrustWarningSupersedesPendingVersionWarning() async throws { let responses = ScriptedTransportResponses([]) From 859e947a673e24131581fb82fdb5dc3499e57289 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 10:41:17 -0700 Subject: [PATCH 21/91] Prompt when manual fallback is selected --- ...MobileShellComposite+ManualHostTrust.swift | 4 ++ .../MobileShellComposite.swift | 22 +++++- .../MobilePairingAttemptDeadlineTests.swift | 69 ++++++++++++++++++- 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index a8661cebb77d..c7aca39b8ba1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -13,6 +13,10 @@ enum PendingManualHostTrust { case pairingURL(rawURL: String, acceptedVersionWarning: Bool) } +enum ManualHostTrustApprovalQueued: Error { + case required +} + @MainActor extension MobileShellComposite { func clearManualHostTrustWarning() { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index b54181ba6723..a50a13357113 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -3173,7 +3173,13 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { do { guard isCurrentPairingAttempt(attemptID) else { return .superseded } - let noThrowFailure = try await connect(ticket: ticket) + let noThrowFailure = try await connect( + ticket: ticket, + pendingManualHostTrust: .pairingURL( + rawURL: rawURL, + acceptedVersionWarning: acceptedVersionWarning + ) + ) guard isCurrentPairingAttempt(attemptID) else { return .superseded } if connectionState == .connected && activeTicket != nil { recordPairingSucceeded() @@ -3189,6 +3195,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { macConnectionStatus = .unavailable clearRemoteConnectionContext() return .failed + } catch is ManualHostTrustApprovalQueued { + guard isCurrentPairingAttempt(attemptID) else { return .superseded } + return .needsUserApproval } catch { guard isCurrentPairingAttempt(attemptID) else { return .superseded } mobileShellLog.error("pairing failed: \(String(describing: error), privacy: .private)") @@ -4891,6 +4900,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func connect( ticket: CmxAttachTicket, allowsStackAuthFallback: Bool? = nil, + pendingManualHostTrust: PendingManualHostTrust? = nil, pairedMacDeviceID: String? = nil, ifStillCurrent: (() -> Bool)? = nil ) async throws -> MobilePairingFailureCategory? { @@ -4943,6 +4953,16 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { for route in supportedRoutes { activeRoute = route mobileShellLog.info("pairing trying route kind=\(route.kind.rawValue, privacy: .public) endpoint=\(route.endpoint.logDescription, privacy: .private)") + if let pendingManualHostTrust, + await manualHostRouteNeedsApproval(route), + case let .hostPort(host, _) = route.endpoint { + queueManualHostTrustWarning( + route: route, + displayHost: host, + pending: pendingManualHostTrust + ) + throw ManualHostTrustApprovalQueued.required + } let manualHostTrusted = await manualHostStackAuthTrusted(for: route) let routeAllowsStackAuth = MobileShellRouteAuthPolicy().routeAllowsStackAuth( route, diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index bd6cc2059416..e7f19691933d 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -1,5 +1,6 @@ import CMUXMobileCore import CmuxMobileRPC +import CmuxMobileShellModel import Foundation import Testing @testable import CmuxMobileShell @@ -83,18 +84,82 @@ import Testing #expect(store.selectedWorkspace?.id.rawValue == "live-workspace") } + @Test func manualFallbackPromptsOnlyAfterTrustedRouteFails() async throws { + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: ManualFallbackApprovalTransportFactory(router: router, box: box), + now: { clock.now }, + supportedRouteKinds: [.tailscale, .manualHost] + ) + let store = makeStore(runtime: runtime) + let trustedRoute = try CmxAttachRoute( + id: "a-trusted-tailscale", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.5", port: 58_465), + priority: 0 + ) + let manualFallbackRoute = try CmxAttachRoute( + id: "b-manual-fallback", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465), + priority: 1 + ) + let ticket = try CmxAttachTicket( + workspaceID: "live-workspace", + terminalID: "live-terminal", + macDeviceID: "test-mac", + macDisplayName: "Test Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [trustedRoute, manualFallbackRoute], + expiresAt: clock.now.addingTimeInterval(3600) + ) + + let result = await store.connectPairingURLResult(try attachURL(for: ticket)) + + #expect(result == .needsUserApproval) + #expect(store.connectionState != .connected) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + #expect(await router.count(of: "workspace.list") == 0) + + let approvedResult = await store.acceptManualHostTrustWarning() + + #expect(approvedResult == .connected) + #expect(store.connectionState == .connected) + #expect(store.manualHostTrustWarning == nil) + #expect(store.selectedWorkspace?.id.rawValue == "live-workspace") + #expect(await router.count(of: "workspace.list") >= 1) + } + private static let qrURL = "cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465" private func makeStore( runtime: any MobileSyncRuntime = PairingDeadlineRuntime(), - pairingCode: String = "" + pairingCode: String = "", + manualHostTrustStore: any MobileManualHostTrustStoring = InMemoryMobileManualHostTrustStore() ) -> MobileShellComposite { MobileShellComposite( runtime: runtime, isSignedIn: true, pairingCode: pairingCode, reachability: AlwaysOnlineReachability(), - pairingHintDefaults: UserDefaults(suiteName: "pairing-deadline-\(UUID().uuidString)")! + pairingHintDefaults: UserDefaults(suiteName: "pairing-deadline-\(UUID().uuidString)")!, + manualHostTrustStore: manualHostTrustStore ) } } + +private struct ManualFallbackApprovalTransportFactory: CmxByteTransportFactory { + let router: LivenessHostRouter + let box: TransportBox + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + if route.kind == .tailscale { + return SlowIgnoringCancellationTransport() + } + let transport = LivenessTransport(router: router) + box.set(transport) + return transport + } +} From f2d334f92e2c9fc1b9c0b7e95e64b493f43f4913 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 17:07:25 -0700 Subject: [PATCH 22/91] Fix manual host SwiftPM package checks --- .../MobileShellComposite+ManualHostTrust.swift | 2 +- .../CmuxMobileShell/MobileShellComposite.swift | 4 ++-- .../MobileManualHostTrustScope.swift | 2 +- ...UserDefaultsMobileManualHostTrustStore.swift | 6 +++--- .../MobileShellRouteAuthPolicyTests.swift | 17 ++++++++--------- 5 files changed, 15 insertions(+), 16 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index c7aca39b8ba1..2047053b8712 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -1,5 +1,5 @@ import CMUXMobileCore -import CmuxMobileShellModel +public import CmuxMobileShellModel enum PendingManualHostTrust { case manual( diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index a50a13357113..74d0a20314c5 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1016,8 +1016,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { CMUXMobileShellStore( runtime: runtime, workspaces: PreviewMobileHost.workspaces, - manualHostTrustStore: manualHostTrustStore, - deliveredNotificationClearer: NoopDeliveredNotificationClearer() + deliveredNotificationClearer: NoopDeliveredNotificationClearer(), + manualHostTrustStore: manualHostTrustStore ) } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift index 3e85183f5451..f993b61baff4 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift @@ -1,4 +1,4 @@ -import CMUXMobileCore +public import CMUXMobileCore import Foundation /// A narrowly-scoped manual-host trust decision. diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift index f17e475b2cc3..bd56acc7df7f 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -1,4 +1,4 @@ -import Foundation +public import Foundation import OSLog nonisolated private let manualHostTrustStoreLog = Logger(subsystem: "com.cmuxterm.app", category: "ManualHostTrust") @@ -22,7 +22,7 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin public init( defaults: UserDefaults = .standard, key: String = "cmux.mobile.manualHostTrust.v2", - trustDuration: TimeInterval = Self.defaultTrustDuration, + trustDuration: TimeInterval = UserDefaultsMobileManualHostTrustStore.defaultTrustDuration, now: @escaping @Sendable () -> Date = { Date() } ) { self.defaults = defaults @@ -40,7 +40,7 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin public init( suiteName: String, key: String = "cmux.mobile.manualHostTrust.v2", - trustDuration: TimeInterval = Self.defaultTrustDuration, + trustDuration: TimeInterval = UserDefaultsMobileManualHostTrustStore.defaultTrustDuration, now: @escaping @Sendable () -> Date = { Date() } ) { if let suiteDefaults = UserDefaults(suiteName: suiteName) { diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index 6cb8514b44d1..8079b977fb8c 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -145,7 +145,7 @@ import Testing stackUserID: "user-a" )) - #expect(!await store.isTrusted(approved)) + #expect(await store.isTrusted(approved) == false) await store.trust(approved) await store.trust(normalizedIPv6) await store.trust(ipv4MappedIPv6) @@ -153,15 +153,14 @@ import Testing #expect(await store.isTrusted(sameHostDifferentCase)) #expect(await store.isTrusted(bracketedIPv6)) #expect(await store.isTrusted(bracketedIPv4MappedIPv6)) - #expect(!await store.isTrusted(differentPort)) - #expect(!await store.isTrusted(differentAccount)) + #expect(await store.isTrusted(differentPort) == false) + #expect(await store.isTrusted(differentAccount) == false) } @Test func userDefaultsManualHostTrustExpiresApproval() async throws { let suiteName = "cmux-manual-host-trust-\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suiteName)) defer { - defaults.removePersistentDomain(forName: suiteName) + UserDefaults(suiteName: suiteName)?.removePersistentDomain(forName: suiteName) } let scope = try #require(MobileManualHostTrustScope( host: "studio-mac.local", @@ -170,19 +169,19 @@ import Testing )) let key = "manual-host-trust" let writer = UserDefaultsMobileManualHostTrustStore( - defaults: defaults, + suiteName: suiteName, key: key, trustDuration: 60, now: { Date(timeIntervalSince1970: 1_000) } ) let stillValidReader = UserDefaultsMobileManualHostTrustStore( - defaults: defaults, + suiteName: suiteName, key: key, trustDuration: 60, now: { Date(timeIntervalSince1970: 1_059) } ) let expiredReader = UserDefaultsMobileManualHostTrustStore( - defaults: defaults, + suiteName: suiteName, key: key, trustDuration: 60, now: { Date(timeIntervalSince1970: 1_061) } @@ -191,7 +190,7 @@ import Testing await writer.trust(scope) #expect(await stillValidReader.isTrusted(scope)) - #expect(!await expiredReader.isTrusted(scope)) + #expect(await expiredReader.isTrusted(scope) == false) } @Test func manualHostTrustWarningFormatsBracketedIPv6Once() throws { From 73b58e4576cef238bd3962960a77b2ebefe01262 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 17:28:54 -0700 Subject: [PATCH 23/91] Address manual host autoreview findings --- ...leShellComposite+PlaceholderHostName.swift | 23 +++++++ .../MobileShellComposite.swift | 63 +++++++++---------- .../MobilePairingAttemptDeadlineTests.swift | 53 ++++++++++++++++ .../Mobile/Pairing/MobilePairingModel.swift | 8 ++- ...bilePairingConnectionTransitionTests.swift | 6 ++ 5 files changed, 118 insertions(+), 35 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PlaceholderHostName.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PlaceholderHostName.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PlaceholderHostName.swift new file mode 100644 index 000000000000..6d6fa9237aca --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PlaceholderHostName.swift @@ -0,0 +1,23 @@ +import CMUXMobileCore + +extension MobileShellComposite { + /// The name shown for the Mac until `mobile.host.status` reports the real + /// one: the ticket's display name, then its device id, then the dialed + /// route's host (a minimal pairing code carries neither name nor id, so the + /// route hostname is the best available placeholder). + func placeholderHostName( + for ticket: CmxAttachTicket, + firstRoute: CmxAttachRoute + ) -> String { + if let name = ticket.macDisplayName, !name.isEmpty { + return name + } + if !ticket.macDeviceID.isEmpty { + return ticket.macDeviceID + } + if case let .hostPort(host, _) = firstRoute.endpoint { + return host + } + return "" + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 74d0a20314c5..1e57492b7448 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -4908,11 +4908,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { func isConnectCurrent() -> Bool { isCurrentConnectionAttempt(generation) && (ifStillCurrent?() ?? true) } + let preservesActiveConnection = hasActiveMacConnection connectionAttemptGeneration = generation - connectionGeneration = generation diagnosticLog?.record(DiagnosticEvent(.connect)) - cancelRemoteOperationTasks() - rawTerminalInputBuffer.clear() + if !preservesActiveConnection { + connectionGeneration = generation + cancelRemoteOperationTasks() + rawTerminalInputBuffer.clear() + } let supportedKinds = runtime?.supportedRouteKinds ?? [] let supportedRoutes = routeSelection.supportedRoutes(for: ticket, supportedKinds: supportedKinds) guard let firstRoute = supportedRoutes.first else { @@ -4929,10 +4932,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // carry no expiry at all), and the host authorizes by Stack account, // not ticket age. Expiry still gates the RPC-minted attach token at // its point of use (`MobileCoreRPCClient.requestDataWithAuth`). - activeTicket = ticket - activeRoute = firstRoute - connectedHostName = placeholderHostName(for: ticket, firstRoute: firstRoute) - replaceRemoteClient(with: nil) + if !preservesActiveConnection { + activeTicket = ticket + activeRoute = firstRoute + connectedHostName = placeholderHostName(for: ticket, firstRoute: firstRoute) + replaceRemoteClient(with: nil) + } guard let runtime else { guard isConnectCurrent() else { return nil } @@ -4951,7 +4956,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let connectionAttemptStartedAt = pairingAttemptStartedAt var lastError: (any Error)? for route in supportedRoutes { - activeRoute = route + if !preservesActiveConnection { + activeRoute = route + } mobileShellLog.info("pairing trying route kind=\(route.kind.rawValue, privacy: .public) endpoint=\(route.endpoint.logDescription, privacy: .private)") if let pendingManualHostTrust, await manualHostRouteNeedsApproval(route), @@ -5001,6 +5008,15 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard isConnectCurrent() else { return nil } await persistPairedMacFromTicket(ticket, ifStillCurrent: isConnectCurrent) guard isConnectCurrent() else { return nil } + if preservesActiveConnection { + connectionGeneration = generation + cancelRemoteOperationTasks() + rawTerminalInputBuffer.clear() + resetTerminalOutputTracking() + } + activeTicket = ticket + activeRoute = route + connectedHostName = placeholderHostName(for: ticket, firstRoute: route) replaceRemoteClient(with: client) startTerminalRefreshPolling() // The connect seam guarantees identity recovery for an @@ -5052,7 +5068,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { connections[resolvedForegroundMacID] = MacConnection( macDeviceID: resolvedForegroundMacID, ticket: ticket, - route: firstRoute, + route: route, client: client, generation: generation ) @@ -5324,10 +5340,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// `attach_url`; pass `nil` for non-instrumented internal flows (preview). private func beginPairingAttempt(method: String? = nil) -> UUID { let attemptID = beginPairingValidationAttempt(method: method) - connectionGeneration = UUID() connectionAttemptGeneration = UUID() - cancelRemoteOperationTasks() - rawTerminalInputBuffer.clear() + if !hasActiveMacConnection { + connectionGeneration = UUID() + cancelRemoteOperationTasks() + rawTerminalInputBuffer.clear() + } clearPairingError() clearPairingVersionWarning() clearManualHostTrustWarning() @@ -7675,24 +7693,3 @@ private extension MobileWorkspacePreview { terminals.contains(where: \.isReady) } } -private extension MobileShellComposite { - /// The name shown for the Mac until `mobile.host.status` reports the real - /// one: the ticket's display name, then its device id, then the dialed - /// route's host (a minimal pairing code carries neither name nor id, so the - /// route hostname is the best available placeholder). - func placeholderHostName( - for ticket: CmxAttachTicket, - firstRoute: CmxAttachRoute - ) -> String { - if let name = ticket.macDisplayName, !name.isEmpty { - return name - } - if !ticket.macDeviceID.isEmpty { - return ticket.macDeviceID - } - if case let .hostPort(host, _) = firstRoute.endpoint { - return host - } - return "" - } -} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index e7f19691933d..d274f672452b 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -132,16 +132,69 @@ import Testing #expect(await router.count(of: "workspace.list") >= 1) } + @Test func manualFallbackApprovalKeepsExistingConnectionUntilConsent() async throws { + let clock = TestClock() + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let newRouter = LivenessHostRouter() + let newBox = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: ManualFallbackApprovalTransportFactory(router: newRouter, box: newBox), + now: { clock.now }, + supportedRouteKinds: [.tailscale, .manualHost] + ) + let store = makeStore(runtime: runtime, connectionState: .connected) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + let originalClient = try #require(store.remoteClient) + let trustedRoute = try CmxAttachRoute( + id: "a-trusted-tailscale", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.5", port: 58_465), + priority: 0 + ) + let manualFallbackRoute = try CmxAttachRoute( + id: "b-manual-fallback", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465), + priority: 1 + ) + let ticket = try CmxAttachTicket( + workspaceID: "live-workspace", + terminalID: "live-terminal", + macDeviceID: "test-mac", + macDisplayName: "Test Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [trustedRoute, manualFallbackRoute], + expiresAt: clock.now.addingTimeInterval(3600) + ) + + let result = await store.connectPairingURLResult(try attachURL(for: ticket)) + + #expect(result == .needsUserApproval) + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + #expect(await newRouter.count(of: "workspace.list") == 0) + + store.cancelPairing() + + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + #expect(store.manualHostTrustWarning == nil) + } + private static let qrURL = "cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465" private func makeStore( runtime: any MobileSyncRuntime = PairingDeadlineRuntime(), pairingCode: String = "", + connectionState: MobileConnectionState = .disconnected, manualHostTrustStore: any MobileManualHostTrustStoring = InMemoryMobileManualHostTrustStore() ) -> MobileShellComposite { MobileShellComposite( runtime: runtime, isSignedIn: true, + connectionState: connectionState, pairingCode: pairingCode, reachability: AlwaysOnlineReachability(), pairingHintDefaults: UserDefaults(suiteName: "pairing-deadline-\(UUID().uuidString)")!, diff --git a/Sources/Mobile/Pairing/MobilePairingModel.swift b/Sources/Mobile/Pairing/MobilePairingModel.swift index 6b211f347f50..4484e5830564 100644 --- a/Sources/Mobile/Pairing/MobilePairingModel.swift +++ b/Sources/Mobile/Pairing/MobilePairingModel.swift @@ -278,7 +278,7 @@ final class MobilePairingModel { case let .hostPort(host, port) = route.endpoint else { return nil } - return "\(host):\(port)" + return endpointLine(host: host, port: port) }) } @@ -288,10 +288,14 @@ final class MobilePairingModel { case let .hostPort(host, port) = route.endpoint else { return nil } - return "\(host):\(port)" + return endpointLine(host: host, port: port) }) } + static func endpointLine(host: String, port: Int) -> String { + host.contains(":") ? "[\(host)]:\(port)" : "\(host):\(port)" + } + private static func uniqueLines(_ lines: [String]) -> [String] { var seen: Set = [] return lines.filter { line in diff --git a/cmuxTests/MobilePairingConnectionTransitionTests.swift b/cmuxTests/MobilePairingConnectionTransitionTests.swift index 3fcf15f98103..7b4dc782865e 100644 --- a/cmuxTests/MobilePairingConnectionTransitionTests.swift +++ b/cmuxTests/MobilePairingConnectionTransitionTests.swift @@ -104,4 +104,10 @@ struct MobilePairingConnectionTransitionTests { ) #expect(next == .signedOut) } + + @Test("Route display lines bracket IPv6 hosts") + func routeDisplayLinesBracketIPv6Hosts() { + #expect(MobilePairingModel.endpointLine(host: "fd00::12", port: 58465) == "[fd00::12]:58465") + #expect(MobilePairingModel.endpointLine(host: "100.64.0.1", port: 7777) == "100.64.0.1:7777") + } } From 5b20ddf2f00c6d121998c8edf658897b4429fe3c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 18:58:38 -0700 Subject: [PATCH 24/91] Fix mobile feature route selection test --- ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 4379f1393b4d..8db04a5d1a36 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -110,7 +110,7 @@ final class TerminalOutputCollector { let loopback = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: CmxMobileDefaults.defaultHostPort) let tailscale = try hostPortRoute(kind: .tailscale, host: "100.71.210.41", port: CmxMobileDefaults.defaultHostPort) - let route = CMUXMobileShellStore.firstReconnectHostPortRoute( + let route = MobileShellRouteSelection().firstReconnectHostPortRoute( [loopback, tailscale], supportedKinds: [.tailscale] ) From 1f6b9d9a47fe24fbcc4a64b36c68389807d69f50 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 19:16:44 -0700 Subject: [PATCH 25/91] Address manual host autoreview gaps --- .../Sources/CMUXMobileCore/CmxPairingQRCode.swift | 3 ++- .../CMUXMobileCoreTests/CmxPairingQRCodeTests.swift | 9 +++++++++ .../Tests/cmuxFeatureTests/cmuxFeatureTests.swift | 2 +- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift index 58dcc6e219ec..b6a2308b0da6 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxPairingQRCode.swift @@ -137,7 +137,8 @@ public struct CmxPairingQRCode: Sendable { route.priority == synthesizedRoutePriority(index: index), case let .hostPort(host, _) = route.endpoint, !CmxLoopbackHost().matches(host), - isPlainHost(host) else { + isPlainHost(host), + route.kind != .manualHost || CmxManualHost(routeHost: host) != nil else { return nil } } diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift index 3a719f3e2b82..921820e60775 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxPairingQRCodeTests.swift @@ -236,6 +236,15 @@ import Testing ]) #expect(CmxPairingQRCode().encode(loopbackTailscale) == nil) + // Manual-host routes must use the same route-host grammar on encode + // that the v3 decoder enforces, otherwise the codec can emit QR URLs + // it later refuses to scan. + let invalidManualHost = try pairingTicket(routes: [ + try manualHostRoute(index: 0, host: "my:host"), + ]) + #expect(CmxPairingQRCode().encode(invalidManualHost) == nil) + #expect(!CmxPairingQRCode().canEncode(invalidManualHost)) + // A non-Tailscale fallback route the bare host:port grammar cannot // express (an iroh peer) must NOT be silently dropped: the ticket // keeps the lossless compact payload instead. Only loopback routes, diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 8db04a5d1a36..010695b4792e 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -2058,7 +2058,7 @@ final class TerminalOutputCollector { let responses = ScriptedTransportResponses([]) let runtime = testRuntime( supportedRouteKinds: [.tailscale, .manualHost], - transportFactory: ScriptedTransportFactory(responses: responses), + transportFactory: FailingRouteTransportFactory(failingRouteID: "tailscale", responses: responses, attempts: RouteAttemptRecorder()), stackAccessToken: "stack-token-for-mixed-manual" ) let store = CMUXMobileShellStore.preview( From 73282bc518fde99c84827bcfb889402efa04c6ef Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 19:35:46 -0700 Subject: [PATCH 26/91] Preserve active mobile sessions on pairing failure --- .../MobileShellComposite.swift | 64 ++++++++++--------- .../MobilePairingAttemptDeadlineTests.swift | 16 +++++ .../cmuxFeatureTests/cmuxFeatureTests.swift | 10 ++- 3 files changed, 55 insertions(+), 35 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 1e57492b7448..bd17659b2b8e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1568,12 +1568,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ifStillCurrent: (() -> Bool)? = nil ) async { let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) + let preservesActiveConnection = hasActiveMacConnection guard let normalizedHost = MobileShellRouteAuthPolicy().normalizedManualRouteHost(host) else { connectionError = L10n.string("mobile.addDevice.invalidHost", defaultValue: "Enter a host or IP address, without spaces or URL paths.") connectionErrorGuidance = nil - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() + clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) analytics.capture("ios_pairing_failed", [ "method": .string("manual"), "reason": .string("invalid_host"), @@ -1585,9 +1584,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard (1...65535).contains(port) else { connectionError = L10n.string("mobile.addDevice.invalidPort", defaultValue: "Enter a port from 1 to 65535.") connectionErrorGuidance = nil - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() + clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) analytics.capture("ios_pairing_failed", [ "method": .string("manual"), "reason": .string("invalid_port"), @@ -1614,12 +1611,19 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) return } - activeRoute = directRoute + if !preservesActiveConnection { + activeRoute = directRoute + } let attemptID = recordsPairingAttempt ? beginPairingAttempt(method: "manual") : beginPairingValidationAttempt() // Fast offline preflight: fail immediately instead of stacking // per-route timeouts into the opaque ~60s blob. let manualRoutes = directRoute.map { [$0] } ?? [] - guard await failPairingIfOffline(attemptID: attemptID, phase: "preflight", routes: manualRoutes) == .proceed else { return } + guard await failPairingIfOffline( + attemptID: attemptID, + phase: "preflight", + routes: manualRoutes, + preservesActiveConnection: preservesActiveConnection + ) == .proceed else { return } do { let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) let ticket = try await manualHostTicket( @@ -1642,7 +1646,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ifStillCurrent: ifStillCurrent ) guard isCurrentPairingAttempt(attemptID) else { return } - if connectionState == .connected { + if noThrowFailure == nil, connectionState == .connected { recordPairingSucceeded() } else { // `connect()` returned without connecting and already set a @@ -1651,9 +1655,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } catch is CancellationError { guard isCurrentPairingAttempt(attemptID) else { return } - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() + clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) } catch { guard isCurrentPairingAttempt(attemptID) else { return } mobileShellLog.error("manual host pairing failed: \(String(describing: error), privacy: .private)") @@ -1663,11 +1665,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { if disconnectForAuthorizationFailureIfNeeded(error) { return } - let category = MobilePairingFailureCategory.classify(error: error, route: activeRoute ?? directRoute) + let category = MobilePairingFailureCategory.classify(error: error, route: directRoute ?? activeRoute) applyPairingFailure(category, phase: "connect") - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() + clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) } } @@ -3068,6 +3068,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) async -> MobilePairingURLConnectionResult { let rawURL = Self.normalizedPairingURL(rawValue ?? pairingCode) _ = beginPairingValidationAttempt() + let preservesActiveConnection = hasActiveMacConnection connectionAttemptGeneration = UUID() if connectionState != .connected { clearActiveConnectionContext() @@ -3164,7 +3165,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // token is used), so an expired legacy code scanned offline must say // "offline", not crawl the route loop's stacked timeouts. if !candidateRoutes.isEmpty { - switch await failPairingIfOffline(attemptID: attemptID, phase: "preflight", routes: candidateRoutes) { + switch await failPairingIfOffline( + attemptID: attemptID, + phase: "preflight", + routes: candidateRoutes, + preservesActiveConnection: preservesActiveConnection + ) { case .failedOffline: return .failed case .superseded: return .superseded case .proceed: break @@ -3181,7 +3187,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) ) guard isCurrentPairingAttempt(attemptID) else { return .superseded } - if connectionState == .connected && activeTicket != nil { + if noThrowFailure == nil, connectionState == .connected && activeTicket != nil { recordPairingSucceeded() return .connected } @@ -3191,9 +3197,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return .failed } catch is CancellationError { guard isCurrentPairingAttempt(attemptID) else { return .superseded } - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() + clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) return .failed } catch is ManualHostTrustApprovalQueued { guard isCurrentPairingAttempt(attemptID) else { return .superseded } @@ -3207,9 +3211,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { if disconnectForAuthorizationFailureIfNeeded(error) { return .failed } let category = MobilePairingFailureCategory.classify(error: error, route: activeRoute) applyPairingFailure(category, phase: "connect") - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() + clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) return .failed } } @@ -4923,9 +4925,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // the caller records the matching analytics reason from it. connectionError = MobilePairingFailureCategory.noSupportedRoute.message connectionErrorGuidance = MobilePairingFailureCategory.noSupportedRoute.guidance - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() + clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) return .noSupportedRoute } // No connect-time expiry gate: a pairing QR never expires (new QRs @@ -5597,7 +5597,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func failPairingIfOffline( attemptID: UUID, phase: String, - routes: [CmxAttachRoute] + routes: [CmxAttachRoute], + preservesActiveConnection: Bool = false ) async -> PairingPreflightOutcome { if routes.contains(where: MobileShellRouteAuthPolicy().routeIsLoopback) { return .proceed } guard await reachability.isOnline == false else { return .proceed } @@ -5605,10 +5606,15 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { mobileShellLog.info("pairing preflight: device offline, short-circuiting") diagnosticLog?.record(DiagnosticEvent(.pairUnreachable)) applyPairingFailure(.offline, phase: phase) + clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) + return .failedOffline + } + + private func clearFailedPairingConnection(preservingActiveConnection: Bool) { + guard !preservingActiveConnection else { return } connectionState = .disconnected macConnectionStatus = .unavailable clearRemoteConnectionContext() - return .failedOffline } private func clearCreateWorkspaceTask(id: UUID) { diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index d274f672452b..a00345de1c7c 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -183,6 +183,22 @@ import Testing #expect(store.manualHostTrustWarning == nil) } + @Test func failedManualHostAttemptKeepsExistingConnection() async throws { + let clock = TestClock() + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let runtime = PairingDeadlineRuntime() + let store = makeStore(runtime: runtime, connectionState: .connected) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + let originalClient = try #require(store.remoteClient) + + await store.connectManualHost(name: "Bad Route", host: "100.64.0.5", port: 58_465) + + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + #expect(store.connectionError?.isEmpty == false) + } + private static let qrURL = "cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465" private func makeStore( diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 010695b4792e..a9ee1fe2c055 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -1064,7 +1064,7 @@ final class TerminalOutputCollector { } @MainActor -@Test func unsupportedAttachTicketClearsPreviousRemoteClient() async throws { +@Test func unsupportedAttachTicketPreservesPreviousRemoteClient() async throws { let supportedRoute = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: CmxMobileDefaults.defaultHostPort) let supportedTicket = try CmxAttachTicket( workspaceID: "live-workspace", @@ -1090,6 +1090,7 @@ final class TerminalOutputCollector { store.signIn() await store.connectPairingURL(try attachURL(for: supportedTicket).absoluteString) #expect(store.phase == .workspaces) + let originalClient = try #require(store.remoteClient) let unsupportedRoute = try CmxAttachRoute( id: "iroh", @@ -1106,15 +1107,12 @@ final class TerminalOutputCollector { ) await store.connectPairingURL(try attachURL(for: unsupportedTicket).absoluteString) - #expect(store.connectionState == .disconnected) + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) #expect(store.connectionError == "This pairing code is not supported.") - store.terminalInputText = "echo should-not-hit-old-host" - await store.submitTerminalInput() - let requests = try await responses.sentRequests() #expect(requests.contains { $0.method == "workspace.list" }) - #expect(!requests.contains { $0.method == "terminal.input" }) } @MainActor From c3340405f11b19330aa29581c36a07b3ea3943a4 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 20:05:08 -0700 Subject: [PATCH 27/91] Return explicit manual host approval result --- ...MobileShellComposite+ManualHostTrust.swift | 3 +- .../MobileShellComposite.swift | 43 +++++++++++-------- .../MobilePairingAttemptDeadlineTests.swift | 18 ++++++++ 3 files changed, 43 insertions(+), 21 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 2047053b8712..a82be2c604a6 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -99,7 +99,7 @@ extension MobileShellComposite { await manualHostTrustStore.trust(warning.scope) switch pending { case let .manual(name, host, port, pairedMacDeviceID, recordsPairingAttempt, ifStillCurrent): - await connectManualHost( + return await connectManualHost( name: name, host: host, port: port, @@ -107,7 +107,6 @@ extension MobileShellComposite { recordsPairingAttempt: recordsPairingAttempt, ifStillCurrent: ifStillCurrent ) - return connectionState == .connected ? .connected : .failed case let .pairingURL(rawURL, acceptedVersionWarning): return await connectPairingURLResult( rawURL, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index bd17659b2b8e..0bfe4c5af23d 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1559,6 +1559,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// `mobile.attach_ticket.create` connects via a synthetic `manual-…` ticket; /// passing the real id keys the foreground aggregate state under it instead of /// the synthetic id. `nil` for a genuinely manual/unknown host. + @discardableResult func connectManualHost( name: String, host: String, @@ -1566,7 +1567,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { pairedMacDeviceID: String? = nil, recordsPairingAttempt: Bool, ifStillCurrent: (() -> Bool)? = nil - ) async { + ) async -> MobilePairingURLConnectionResult { let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) let preservesActiveConnection = hasActiveMacConnection guard let normalizedHost = MobileShellRouteAuthPolicy().normalizedManualRouteHost(host) else { @@ -1579,7 +1580,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } guard (1...65535).contains(port) else { connectionError = L10n.string("mobile.addDevice.invalidPort", defaultValue: "Enter a port from 1 to 65535.") @@ -1591,7 +1592,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } let directRoute = try? routeSelection.manualHostRoute(host: normalizedHost, port: port) @@ -1609,7 +1610,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ifStillCurrent: ifStillCurrent ) ) - return + return .needsUserApproval } if !preservesActiveConnection { activeRoute = directRoute @@ -1617,13 +1618,16 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let attemptID = recordsPairingAttempt ? beginPairingAttempt(method: "manual") : beginPairingValidationAttempt() // Fast offline preflight: fail immediately instead of stacking // per-route timeouts into the opaque ~60s blob. - let manualRoutes = directRoute.map { [$0] } ?? [] - guard await failPairingIfOffline( + switch await failPairingIfOffline( attemptID: attemptID, phase: "preflight", - routes: manualRoutes, + routes: directRoute.map { [$0] } ?? [], preservesActiveConnection: preservesActiveConnection - ) == .proceed else { return } + ) { + case .failedOffline: return .failed + case .superseded: return .superseded + case .proceed: break + } do { let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) let ticket = try await manualHostTicket( @@ -1633,7 +1637,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { attemptStartedAt: pairingAttemptStartedAt, manualHostTrusted: manualHostTrusted ) - guard isCurrentPairingAttempt(attemptID) else { return } + guard isCurrentPairingAttempt(attemptID) else { return .superseded } let noThrowFailure = try await connect( ticket: ticket, allowsStackAuthFallback: directRoute.map { @@ -1645,29 +1649,30 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { pairedMacDeviceID: pairedMacDeviceID, ifStillCurrent: ifStillCurrent ) - guard isCurrentPairingAttempt(attemptID) else { return } + guard isCurrentPairingAttempt(attemptID) else { return .superseded } if noThrowFailure == nil, connectionState == .connected { recordPairingSucceeded() - } else { - // `connect()` returned without connecting and already set a - // specific error; record without overwriting that message. - recordFailureForCurrentConnectionError(phase: "connect", category: noThrowFailure) + return .connected } + // `connect()` returned without connecting and already set a + // specific error; record without overwriting that message. + recordFailureForCurrentConnectionError(phase: "connect", category: noThrowFailure) + return .failed } catch is CancellationError { - guard isCurrentPairingAttempt(attemptID) else { return } + guard isCurrentPairingAttempt(attemptID) else { return .superseded } clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) + return .failed } catch { - guard isCurrentPairingAttempt(attemptID) else { return } + guard isCurrentPairingAttempt(attemptID) else { return .superseded } mobileShellLog.error("manual host pairing failed: \(String(describing: error), privacy: .private)") // A definitive auth failure (expired/invalid token after the // refresh-then-retry in the RPC layer already gave up) must drive the // re-auth prompt, not the generic "could not connect / Retry" banner. - if disconnectForAuthorizationFailureIfNeeded(error) { - return - } + if disconnectForAuthorizationFailureIfNeeded(error) { return .failed } let category = MobilePairingFailureCategory.classify(error: error, route: directRoute ?? activeRoute) applyPairingFailure(category, phase: "connect") clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) + return .failed } } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index a00345de1c7c..cb7e199842ca 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -199,6 +199,24 @@ import Testing #expect(store.connectionError?.isEmpty == false) } + @Test func failedManualHostApprovalReportsFailureWhileKeepingExistingConnection() async throws { + let clock = TestClock() + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let runtime = PairingDeadlineRuntime(supportedRouteKinds: [.manualHost]) + let store = makeStore(runtime: runtime, connectionState: .connected) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + let originalClient = try #require(store.remoteClient) + + await store.connectManualHost(name: "Bad LAN", host: "192.168.1.77", port: 58_465) + let result = await store.acceptManualHostTrustWarning() + + #expect(result == .failed) + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + #expect(store.connectionError?.isEmpty == false) + } + private static let qrURL = "cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465" private func makeStore( From 2d494f18a97bba3cc9cdc54de5ab46930e23783e Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 20:14:17 -0700 Subject: [PATCH 28/91] Keep workspace detail within line budget --- .../Sources/CmuxMobileShellUI/WorkspaceDetailView.swift | 3 --- 1 file changed, 3 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift index 9c6cffb705cd..46bf4917c7c4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift @@ -13,7 +13,6 @@ import SwiftUI #elseif os(macOS) import AppKit #endif - struct WorkspaceDetailView: View { let host: String let connectionStatus: MobileMacConnectionStatus @@ -75,12 +74,10 @@ struct WorkspaceDetailView: View { private var activeBrowser: BrowserSurfaceState? { browserStore.activeBrowser(for: workspace.id.rawValue) } - var body: some View { let content = Group { detailSurfaceContent } - #if os(iOS) content .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { contentWidth = $0 } From 172fe3ef3e1f4f1f4c5aaaabc6e28cfce668025b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 20:30:56 -0700 Subject: [PATCH 29/91] Satisfy manual host policy closeout --- .../ManualHostTrustApprovalQueued.swift | 3 ++ ...MobileShellComposite+ManualHostTrust.swift | 16 --------- .../MobileShellComposite.swift | 17 ++------- .../MobileShellPreviewFactory.swift | 32 +++++++++++++++++ .../PendingManualHostTrust.swift | 11 ++++++ ...nualFallbackApprovalTransportFactory.swift | 15 ++++++++ .../MobilePairingAttemptDeadlineTests.swift | 14 -------- Sources/Mobile/MobileHostService.swift | 22 ++++++------ .../cmuxFeatureTests/cmuxFeatureTests.swift | 36 +++++++++---------- 9 files changed, 92 insertions(+), 74 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/ManualHostTrustApprovalQueued.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/ManualHostTrustApprovalQueued.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/ManualHostTrustApprovalQueued.swift new file mode 100644 index 000000000000..854ebec9dc63 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/ManualHostTrustApprovalQueued.swift @@ -0,0 +1,3 @@ +enum ManualHostTrustApprovalQueued: Error { + case required +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index a82be2c604a6..3a587a5f36d6 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -1,22 +1,6 @@ import CMUXMobileCore public import CmuxMobileShellModel -enum PendingManualHostTrust { - case manual( - name: String, - host: String, - port: Int, - pairedMacDeviceID: String?, - recordsPairingAttempt: Bool, - ifStillCurrent: (() -> Bool)? - ) - case pairingURL(rawURL: String, acceptedVersionWarning: Bool) -} - -enum ManualHostTrustApprovalQueued: Error { - case required -} - @MainActor extension MobileShellComposite { func clearManualHostTrustWarning() { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 0bfe4c5af23d..1f3f4b9c7334 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1004,21 +1004,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } - /// Creates a preview shell store with in-memory manual-host trust. - /// - Parameters: - /// - runtime: Optional runtime used by previews or package tests. - /// - manualHostTrustStore: Store used to persist manual-host approvals in the preview shell. - /// - Returns: A shell store seeded with preview workspaces. - public static func preview( - runtime: (any MobileSyncRuntime)? = nil, - manualHostTrustStore: any MobileManualHostTrustStoring = InMemoryMobileManualHostTrustStore() - ) -> CMUXMobileShellStore { - CMUXMobileShellStore( - runtime: runtime, - workspaces: PreviewMobileHost.workspaces, - deliveredNotificationClearer: NoopDeliveredNotificationClearer(), - manualHostTrustStore: manualHostTrustStore - ) + public static func preview(runtime: (any MobileSyncRuntime)? = nil) -> CMUXMobileShellStore { + MobileShellPreviewFactory(runtime: runtime).makeStore() } public func signIn() { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift new file mode 100644 index 000000000000..f04bdef48ea0 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift @@ -0,0 +1,32 @@ +public import CMUXMobileCore +public import CmuxMobileShellModel + +/// Builds preview and test shell stores with explicit preview-only dependencies. +public struct MobileShellPreviewFactory { + private let runtime: (any MobileSyncRuntime)? + private let manualHostTrustStore: any MobileManualHostTrustStoring + + /// Creates a preview shell factory. + /// - Parameters: + /// - runtime: Optional runtime used by previews or package tests. + /// - manualHostTrustStore: Store used to persist manual-host approvals in the preview shell. + public init( + runtime: (any MobileSyncRuntime)? = nil, + manualHostTrustStore: any MobileManualHostTrustStoring = InMemoryMobileManualHostTrustStore() + ) { + self.runtime = runtime + self.manualHostTrustStore = manualHostTrustStore + } + + /// Creates a shell store seeded with preview workspaces. + /// - Returns: A shell store configured for previews or package tests. + @MainActor + public func makeStore() -> CMUXMobileShellStore { + CMUXMobileShellStore( + runtime: runtime, + workspaces: PreviewMobileHost.workspaces, + deliveredNotificationClearer: NoopDeliveredNotificationClearer(), + manualHostTrustStore: manualHostTrustStore + ) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift new file mode 100644 index 000000000000..c337a068c32a --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift @@ -0,0 +1,11 @@ +enum PendingManualHostTrust { + case manual( + name: String, + host: String, + port: Int, + pairedMacDeviceID: String?, + recordsPairingAttempt: Bool, + ifStillCurrent: (() -> Bool)? + ) + case pairingURL(rawURL: String, acceptedVersionWarning: Bool) +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift new file mode 100644 index 000000000000..77a2e1c7bb01 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift @@ -0,0 +1,15 @@ +import CMUXMobileCore + +struct ManualFallbackApprovalTransportFactory: CmxByteTransportFactory { + let router: LivenessHostRouter + let box: TransportBox + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + if route.kind == .tailscale { + return SlowIgnoringCancellationTransport() + } + let transport = LivenessTransport(router: router) + box.set(transport) + return transport + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index cb7e199842ca..7525e741ebc6 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -236,17 +236,3 @@ import Testing ) } } - -private struct ManualFallbackApprovalTransportFactory: CmxByteTransportFactory { - let router: LivenessHostRouter - let box: TransportBox - - func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { - if route.kind == .tailscale { - return SlowIgnoringCancellationTransport() - } - let transport = LivenessTransport(router: router) - box.set(transport) - return transport - } -} diff --git a/Sources/Mobile/MobileHostService.swift b/Sources/Mobile/MobileHostService.swift index d1ac5aa2aef5..d34741ca0f29 100644 --- a/Sources/Mobile/MobileHostService.swift +++ b/Sources/Mobile/MobileHostService.swift @@ -149,16 +149,17 @@ private final class MobileHostConnectionRegistry: @unchecked Sendable { } } -// `routes` protects every mutation/copy so nonisolated status RPCs avoid a main-actor hop. -private final class MobileHostPublicStatusSnapshot: @unchecked Sendable { - private let routes = OSAllocatedUnfairLock(initialState: [CmxAttachRoute]()) - func update(routes nextRoutes: [CmxAttachRoute]) { - routes.withLock { $0 = nextRoutes } +private enum MobileHostPublicStatusCache { + private static let lock = NSLock() + private nonisolated(unsafe) static var routes: [CmxAttachRoute] = [] + + static func update(routes nextRoutes: [CmxAttachRoute]) { + lock.withLock { routes = nextRoutes } NotificationCenter.default.post(name: .mobileHostStatusDidChange, object: nil) } - func result(includeIdentity: Bool = false) -> MobileHostRPCResult { - let routesPayload = routes.withLock { $0.map(\.mobileHostJSONObject) } + static func result(includeIdentity: Bool = false) -> MobileHostRPCResult { + let routesPayload = lock.withLock { routes.map(\.mobileHostJSONObject) } return .ok( includeIdentity ? MobileHostService.identityStatusPayload(routesPayload: routesPayload) @@ -356,20 +357,19 @@ final class MobileHostService { nonisolated func networkStatusResult(for request: MobileHostRPCRequest) async -> MobileHostRPCResult { let trimmedToken = request.auth?.stackAccessToken?.trimmingCharacters(in: .whitespacesAndNewlines) guard trimmedToken?.isEmpty == false else { - return publicStatusSnapshot.result(includeIdentity: false) + return MobileHostPublicStatusCache.result(includeIdentity: false) } let verified = await verifiedStackCaller(for: request) if !verified { mobileHostLog.error("mobile host status identity withheld: stack verification failed") } - return publicStatusSnapshot.result(includeIdentity: verified) + return MobileHostPublicStatusCache.result(includeIdentity: verified) } private let callbackQueue = DispatchQueue(label: "dev.cmux.mobile.host-listener") let routeAdvertisement = MobileHostRouteAdvertisement() var routeResolver: MobileRouteResolver { routeAdvertisement.routeResolver } private let ticketStore = MobileAttachTicketStore() - nonisolated private let publicStatusSnapshot = MobileHostPublicStatusSnapshot() private var listener: NWListener? private var listenerGeneration = UUID() private var listenerUsesEphemeralFallback = false @@ -935,7 +935,7 @@ final class MobileHostService { ) } - func updatePublicStatusSnapshot(routes: [CmxAttachRoute]) { publicStatusSnapshot.update(routes: routes) } + func updatePublicStatusSnapshot(routes: [CmxAttachRoute]) { MobileHostPublicStatusCache.update(routes: routes) } /// Reconcile the live listener with current settings (enable/disable and /// preferred-port changes). Safe to call on any settings change: it no-ops diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index a9ee1fe2c055..4b70e95dcddf 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -681,7 +681,7 @@ final class TerminalOutputCollector { stackAccessToken: "stack-token-for-lan" ) let trustStore = InMemoryMobileManualHostTrustStore() - let store = CMUXMobileShellStore.preview(runtime: runtime, manualHostTrustStore: trustStore) + let store = MobileShellPreviewFactory(runtime: runtime, manualHostTrustStore: trustStore).makeStore() store.signIn() await store.connectManualHost(name: "Studio LAN", host: " 192.168.1.77 ", port: 15432) @@ -723,10 +723,10 @@ final class TerminalOutputCollector { transportFactory: ScriptedTransportFactory(responses: responses), stackAccessToken: "stack-token-for-ipv6" ) - let store = CMUXMobileShellStore.preview( + let store = MobileShellPreviewFactory( runtime: runtime, manualHostTrustStore: InMemoryMobileManualHostTrustStore() - ) + ).makeStore() store.signIn() await store.connectManualHost(name: "IPv6 LAN", host: "[fd00::12]", port: 15433) @@ -762,7 +762,7 @@ final class TerminalOutputCollector { transportFactory: ScriptedTransportFactory(responses: approvedResponses), stackAccessToken: "stack-token-for-local-dns" ) - let approvedStore = CMUXMobileShellStore.preview(runtime: approvedRuntime, manualHostTrustStore: trustStore) + let approvedStore = MobileShellPreviewFactory(runtime: approvedRuntime, manualHostTrustStore: trustStore).makeStore() approvedStore.signIn() await approvedStore.connectManualHost(name: "", host: "studio-mac.local", port: 61234) @@ -776,7 +776,7 @@ final class TerminalOutputCollector { transportFactory: ScriptedTransportFactory(responses: blockedResponses), stackAccessToken: "stack-token-for-local-dns" ) - let store = CMUXMobileShellStore.preview(runtime: runtime, manualHostTrustStore: trustStore) + let store = MobileShellPreviewFactory(runtime: runtime, manualHostTrustStore: trustStore).makeStore() store.signIn() await store.connectManualHost(name: "", host: "other-mac.local", port: 61234) @@ -1916,7 +1916,7 @@ final class TerminalOutputCollector { stackAccessToken: "stack-token-for-qr-manual" ) let trustStore = InMemoryMobileManualHostTrustStore() - let store = CMUXMobileShellStore.preview(runtime: runtime, manualHostTrustStore: trustStore) + let store = MobileShellPreviewFactory(runtime: runtime, manualHostTrustStore: trustStore).makeStore() let url = "cmux-ios://attach?v=3&pc=1&m=studio-mac.local:61234" store.signIn() @@ -1951,10 +1951,10 @@ final class TerminalOutputCollector { transportFactory: ScriptedTransportFactory(responses: responses), stackAccessToken: "stack-token-for-stale-manual-warning" ) - let store = CMUXMobileShellStore.preview( + let store = MobileShellPreviewFactory( runtime: runtime, manualHostTrustStore: InMemoryMobileManualHostTrustStore() - ) + ).makeStore() store.signIn() let firstResult = await store.connectPairingURLResult( @@ -1979,10 +1979,10 @@ final class TerminalOutputCollector { transportFactory: ScriptedTransportFactory(responses: responses), stackAccessToken: "stack-token-for-signout-manual-warning" ) - let store = CMUXMobileShellStore.preview( + let store = MobileShellPreviewFactory( runtime: runtime, manualHostTrustStore: InMemoryMobileManualHostTrustStore() - ) + ).makeStore() store.signIn() let firstResult = await store.connectPairingURLResult( @@ -2006,10 +2006,10 @@ final class TerminalOutputCollector { transportFactory: ScriptedTransportFactory(responses: responses), stackAccessToken: "stack-token-for-team-switch-manual-warning" ) - let store = CMUXMobileShellStore.preview( + let store = MobileShellPreviewFactory( runtime: runtime, manualHostTrustStore: InMemoryMobileManualHostTrustStore() - ) + ).makeStore() store.signIn() let firstResult = await store.connectPairingURLResult( @@ -2032,10 +2032,10 @@ final class TerminalOutputCollector { transportFactory: ScriptedTransportFactory(responses: responses), stackAccessToken: "stack-token-for-version-manual-warning" ) - let store = CMUXMobileShellStore.preview( + let store = MobileShellPreviewFactory( runtime: runtime, manualHostTrustStore: InMemoryMobileManualHostTrustStore() - ) + ).makeStore() store.signIn() let versionWarningResult = await store.connectPairingURLResult( @@ -2059,10 +2059,10 @@ final class TerminalOutputCollector { transportFactory: FailingRouteTransportFactory(failingRouteID: "tailscale", responses: responses, attempts: RouteAttemptRecorder()), stackAccessToken: "stack-token-for-mixed-manual" ) - let store = CMUXMobileShellStore.preview( + let store = MobileShellPreviewFactory( runtime: runtime, manualHostTrustStore: InMemoryMobileManualHostTrustStore() - ) + ).makeStore() let url = "cmux-ios://attach?v=3&pc=1&r=100.71.210.41:61234&m=studio-mac.local:61234" store.signIn() @@ -2158,7 +2158,7 @@ final class TerminalOutputCollector { transportFactory: ScriptedTransportFactory(responses: approvedResponses), stackAccessToken: "stack-token-for-default-lan" ) - let approvedStore = CMUXMobileShellStore.preview(runtime: approvedRuntime, manualHostTrustStore: trustStore) + let approvedStore = MobileShellPreviewFactory(runtime: approvedRuntime, manualHostTrustStore: trustStore).makeStore() approvedStore.signIn() await approvedStore.connectManualHost(name: "Work Mac", host: "192.168.1.77", port: CmxMobileDefaults.defaultHostPort) @@ -2172,7 +2172,7 @@ final class TerminalOutputCollector { transportFactory: ScriptedTransportFactory(responses: blockedResponses), stackAccessToken: "stack-token-for-default-lan" ) - let store = CMUXMobileShellStore.preview(runtime: runtime, manualHostTrustStore: trustStore) + let store = MobileShellPreviewFactory(runtime: runtime, manualHostTrustStore: trustStore).makeStore() store.signIn() await store.connectManualHost(name: "Work Mac", host: "192.168.1.77", port: CmxMobileDefaults.defaultHostPort + 1) From 82340e21399c7864bf14b89acb77e60fc01a4cb9 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 20:49:42 -0700 Subject: [PATCH 30/91] Add stale manual host approval reconnect test --- .../AttachTicketReconnectTransport.swift | 101 ++++++++++++++++++ .../MobileShellManualHostReconnectTests.swift | 70 ++++++++++++ 2 files changed, 171 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AttachTicketReconnectTransport.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AttachTicketReconnectTransport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AttachTicketReconnectTransport.swift new file mode 100644 index 000000000000..b4f296ead4f4 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AttachTicketReconnectTransport.swift @@ -0,0 +1,101 @@ +import CMUXMobileCore +import CmuxMobileRPC +import Foundation + +actor AttachTicketReconnectTransport: CmxByteTransportFactory, CmxByteTransport { + private let ticketRoute: CmxAttachRoute + private var pendingFrames: [Data] = [] + private var receiveWaiters: [CheckedContinuation] = [] + + init(ticketRoute: CmxAttachRoute) { + self.ticketRoute = ticketRoute + } + + nonisolated func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + self + } + + func connect() async throws {} + + func receive() async throws -> Data? { + if !pendingFrames.isEmpty { + return pendingFrames.removeFirst() + } + return await withCheckedContinuation { continuation in + receiveWaiters.append(continuation) + } + } + + func send(_ data: Data) async throws { + var buffer = data + let payloads = try MobileSyncFrameCodec.decodeFrames(from: &buffer) + for payload in payloads { + guard let parsed = (try? JSONSerialization.jsonObject(with: payload)) as? [String: Any], + let response = try response(method: parsed["method"] as? String, id: parsed["id"] as? String) else { + continue + } + deliver(response) + } + } + + func close() async {} + + private func response(method: String?, id: String?) throws -> Data? { + switch method { + case "mobile.attach_ticket.create": + return try Self.resultFrame(id: id, result: ["ticket": ticketObject()]) + case "workspace.list", "mobile.workspace.list": + return try Self.resultFrame(id: id, result: [ + "workspaces": [ + [ + "id": "trusted-workspace", + "title": "Trusted Workspace", + "is_selected": true, + "terminals": [], + ], + ], + ]) + case "mobile.host.status": + return try Self.resultFrame(id: id, result: [ + "terminal_fidelity": "render_grid", + "capabilities": [:], + ]) + default: + return nil + } + } + + private func ticketObject() throws -> Any { + let ticket = try CmxAttachTicket( + workspaceID: "trusted-workspace", + terminalID: nil, + macDeviceID: "trusted-mac", + macDisplayName: "Trusted Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [ticketRoute], + expiresAt: Date().addingTimeInterval(3600), + authToken: "ticket-secret" + ) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + return try JSONSerialization.jsonObject(with: encoder.encode(ticket)) + } + + private func deliver(_ frame: Data) { + if receiveWaiters.isEmpty { + pendingFrames.append(frame) + return + } + let waiter = receiveWaiters.removeFirst() + waiter.resume(returning: frame) + } + + private static func resultFrame(id: String?, result: [String: Any]) throws -> Data { + let envelope: [String: Any] = [ + "id": id ?? UUID().uuidString, + "ok": true, + "result": result, + ] + return try MobileSyncFrameCodec.encodeFrame(JSONSerialization.data(withJSONObject: envelope)) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift new file mode 100644 index 000000000000..3dde11b25af0 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift @@ -0,0 +1,70 @@ +import CMUXMobileCore +import CmuxMobilePairedMac +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct MobileShellManualHostReconnectTests { + @Test func successfulLaterReconnectCandidateClearsQueuedManualHostApproval() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let manualRoute = try hostPortRoute(kind: .manualHost, host: "192.168.1.77") + let trustedRoute = try hostPortRoute(kind: .tailscale, host: "100.64.0.5") + let now = Date() + try await pairedMacStore.upsert( + macDeviceID: "manual-mac", + displayName: "Manual Mac", + routes: [manualRoute], + markActive: true, + stackUserID: "phone-user", + teamID: nil, + now: now.addingTimeInterval(-10) + ) + try await pairedMacStore.upsert( + macDeviceID: "trusted-mac", + displayName: "Trusted Mac", + routes: [trustedRoute], + markActive: false, + stackUserID: "phone-user", + teamID: nil, + now: now + ) + let clock = TestClock() + let runtime = LivenessTestRuntime( + transportFactory: AttachTicketReconnectTransport(ticketRoute: trustedRoute), + now: { clock.now }, + supportedRouteKinds: [.manualHost, .tailscale], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + + store.signIn() + let connected = await store.reconnectActiveMacIfAvailable(stackUserID: "phone-user") + + #expect(connected) + #expect(store.connectionState == .connected) + #expect(store.connectedMacDeviceID == "trusted-mac") + #expect(store.manualHostTrustWarning == nil) + } + + private func hostPortRoute(kind: CmxAttachTransportKind, host: String) throws -> CmxAttachRoute { + try CmxAttachRoute( + id: kind.rawValue, + kind: kind, + endpoint: .hostPort(host: host, port: CmxMobileDefaults.defaultHostPort) + ) + } +} From 7b4ce794f4bfb78f696f70a7b792cfcd19a7a62e Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 20:50:40 -0700 Subject: [PATCH 31/91] Clear stale manual host approval after reconnect --- .../Sources/CmuxMobileShell/MobileShellComposite.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 1f3f4b9c7334..cba085748bb8 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -4937,6 +4937,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { applyPreviewTicket(ticket, route: firstRoute) connectionState = .connected markMacConnectionHealthy() + clearManualHostTrustWarning() return nil } @@ -5072,6 +5073,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { self.scheduleSecondaryAggregation() } diagnosticLog?.record(DiagnosticEvent(.pairOk)) + clearManualHostTrustWarning() if workspaceListRequest.isScoped { scheduleFullWorkspaceListRefreshIfAvailable( client: client, From 20ac5f4c66f002e734d5a67c7e426981c7270657 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 21:04:23 -0700 Subject: [PATCH 32/91] Fix manual host closeout blockers --- .../MobileShellComposite.swift | 34 ++++++++++--------- .../MobileShellPreviewFactory.swift | 2 +- .../MobileShellRouteSelection.swift | 11 ++++-- .../ReconnectRouteSelectionTests.swift | 10 ++++++ .../MobileShellRouteAuthPolicy.swift | 27 +++++++++++---- .../MobileShellRouteAuthPolicyTests.swift | 28 +++++++++++++++ .../ComposerDictationController.swift | 2 +- 7 files changed, 87 insertions(+), 27 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index cba085748bb8..6c892b0665bf 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -985,22 +985,24 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { self.pairingAttemptID = UUID() } - isolated deinit { - presenceTask?.cancel() - networkPathObservationTask?.cancel() - terminalEventListenerTask?.cancel() - terminalSubscriptionStartTask?.cancel() - renderGridLivenessTimer?.cancel() - renderGridLivenessProbeTask?.cancel() - terminalSubscriptionRefreshTask?.cancel() - createWorkspaceTask?.cancel() - createTerminalTask?.cancel() - workspaceListRefreshTask?.cancel() - pullToRefreshTask?.cancel() - cancelAllTerminalReplayTasks() - teardownSecondaryMacSubscriptions() - if let remoteClient { - Task { await remoteClient.disconnect() } + deinit { + MainActor.assumeIsolated { + presenceTask?.cancel() + networkPathObservationTask?.cancel() + terminalEventListenerTask?.cancel() + terminalSubscriptionStartTask?.cancel() + renderGridLivenessTimer?.cancel() + renderGridLivenessProbeTask?.cancel() + terminalSubscriptionRefreshTask?.cancel() + createWorkspaceTask?.cancel() + createTerminalTask?.cancel() + workspaceListRefreshTask?.cancel() + pullToRefreshTask?.cancel() + cancelAllTerminalReplayTasks() + teardownSecondaryMacSubscriptions() + if let remoteClient { + Task { await remoteClient.disconnect() } + } } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift index f04bdef48ea0..656f03d0cd8a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift @@ -1,4 +1,4 @@ -public import CMUXMobileCore +public import CmuxMobileRPC public import CmuxMobileShellModel /// Builds preview and test shell stores with explicit preview-only dependencies. diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift index 7ee39b5bd0bd..be9cbda20955 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift @@ -104,8 +104,15 @@ struct MobileShellRouteSelection: Sendable { #endif } - func manualHostRoute(host: String, port: Int) throws -> CmxAttachRoute { - let routeKind = routeAuthPolicy.manualRouteKind(for: host) + func manualHostRoute( + host: String, + port: Int, + isPhysicalDevice: Bool? = nil + ) throws -> CmxAttachRoute { + let routeKind = routeAuthPolicy.manualRouteKind( + for: host, + allowsDebugLoopback: !(isPhysicalDevice ?? self.isPhysicalDevice) + ) return try CmxAttachRoute( id: routeKind.rawValue, kind: routeKind, diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index fdff3c05c618..349d9dcfab82 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -65,6 +65,16 @@ import Testing #expect(pick?.0 == "127.0.0.1") } + @Test func physicalManualHostEntryDoesNotTrustLoopbackAlias() throws { + let route = try MobileShellRouteSelection().manualHostRoute( + host: "127.1", + port: 50906, + isPhysicalDevice: true + ) + #expect(route.kind == .manualHost) + #expect(!MobileShellRouteAuthPolicy().routeAllowsStackAuth(route)) + } + private func magicDNS(_ port: Int = 50906) throws -> CmxAttachRoute { // A MagicDNS hostname route, advertised BEFORE the IP route by priority. try CmxAttachRoute( diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift index ff48cc6dbc65..cf658a81f729 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift @@ -41,14 +41,21 @@ public struct MobileShellRouteAuthPolicy: Sendable { } /// Maps a manually typed host to the transport kind that should be used. - /// - Parameter host: The host to classify. - /// - Returns: `.debugLoopback` for loopback hosts, `.tailscale` for + /// - Parameters: + /// - host: The host to classify. + /// - allowsDebugLoopback: Whether loopback aliases should become + /// `.debugLoopback`. Keep this `false` for physical-device manual entry: + /// loopback dials the phone itself there, not the Mac. + /// - Returns: `.debugLoopback` for allowed loopback hosts, `.tailscale` for /// Tailscale IP/MagicDNS hosts, otherwise `.manualHost`. - public func manualRouteKind(for host: String) -> CmxAttachTransportKind { + public func manualRouteKind( + for host: String, + allowsDebugLoopback: Bool = true + ) -> CmxAttachTransportKind { let normalizedHost = (normalizedManualRouteHost(host) ?? host) .trimmingCharacters(in: .whitespacesAndNewlines) .lowercased() - if isLoopbackHost(normalizedHost) { + if allowsDebugLoopback, isLoopbackHost(normalizedHost) { return .debugLoopback } if isTailscaleHost(normalizedHost) { @@ -161,13 +168,19 @@ public struct MobileShellRouteAuthPolicy: Sendable { } /// Whether a manual host should warn the user that it is neither loopback nor Tailscale. - /// - Parameter host: The manually typed host. + /// - Parameters: + /// - host: The manually typed host. + /// - allowsDebugLoopback: Whether loopback aliases are trusted debug hosts + /// for this caller. /// - Returns: `true` when the host is valid but outside the loopback/Tailscale trust set. - public func manualHostNeedsTrustWarning(_ host: String) -> Bool { + public func manualHostNeedsTrustWarning( + _ host: String, + allowsDebugLoopback: Bool = true + ) -> Bool { guard normalizedManualNetworkHost(host) != nil else { return false } - return manualRouteKind(for: host) == .manualHost + return manualRouteKind(for: host, allowsDebugLoopback: allowsDebugLoopback) == .manualHost } private func normalizedManualNetworkHost(_ host: String) -> String? { diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index 8079b977fb8c..56f6ec0be94c 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -68,6 +68,22 @@ import Testing #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "0.0.0.0") == .debugLoopback) #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "0x7f.0.0.1") == .debugLoopback) #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "[::1]") == .debugLoopback) + #expect(MobileShellRouteAuthPolicy().manualRouteKind( + for: "127.1", + allowsDebugLoopback: false + ) == .manualHost) + #expect(MobileShellRouteAuthPolicy().manualRouteKind( + for: "0.0.0.0", + allowsDebugLoopback: false + ) == .manualHost) + #expect(MobileShellRouteAuthPolicy().manualRouteKind( + for: "0x7f.0.0.1", + allowsDebugLoopback: false + ) == .manualHost) + #expect(MobileShellRouteAuthPolicy().manualRouteKind( + for: "[::1]", + allowsDebugLoopback: false + ) == .manualHost) #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "100.71.210.41") == .tailscale) #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "work-mac.tailnet.ts.net") == .tailscale) #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "127.attacker.example") == .manualHost) @@ -96,6 +112,18 @@ import Testing #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("127.1")) #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("0.0.0.0")) #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("0x7f.0.0.1")) + #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning( + "127.1", + allowsDebugLoopback: false + )) + #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning( + "0.0.0.0", + allowsDebugLoopback: false + )) + #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning( + "0x7f.0.0.1", + allowsDebugLoopback: false + )) #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("100.71.210.41")) #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("work-mac.tailnet.ts.net")) #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("192.168.1.77")) diff --git a/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/ComposerDictationController.swift b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/ComposerDictationController.swift index 98ffde4baebf..fca25912efed 100644 --- a/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/ComposerDictationController.swift +++ b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/ComposerDictationController.swift @@ -395,7 +395,7 @@ public final class ComposerDictationController { request: SFSpeechAudioBufferRecognitionRequest ) -> @Sendable (AVAudioPCMBuffer, AVAudioTime) -> Void { // `nonisolated(unsafe)`-safe: `append(_:)` is thread-safe, weak, never outlives the request. - nonisolated(unsafe) weak let weakRequest: SFSpeechAudioBufferRecognitionRequest? = request + nonisolated(unsafe) weak var weakRequest: SFSpeechAudioBufferRecognitionRequest? = request return { buffer, _ in weakRequest?.append(buffer) } From 46f6d587cd1dfeca8d1a5625daf5cd41e389a15e Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 21:24:59 -0700 Subject: [PATCH 33/91] Address manual host autoreview findings --- .../CmxManualPairingEntry.swift | 11 ++ .../CmxManualPairingEntryTests.swift | 6 + ...eShellComposite+AuthorizationFailure.swift | 55 +++++++ .../MobileShellComposite.swift | 134 ++++++++---------- .../MobileShellRoutedConnectionError.swift | 6 + .../BlockingManualHostTrustStore.swift | 42 ++++++ .../MobilePairingAttemptDeadlineTests.swift | 49 +++++++ .../Mobile/Pairing/MobilePairingView.swift | 2 +- 8 files changed, 226 insertions(+), 79 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRoutedConnectionError.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingManualHostTrustStore.swift diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualPairingEntry.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualPairingEntry.swift index ba26f2786e64..e5ff42e88f99 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualPairingEntry.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualPairingEntry.swift @@ -16,6 +16,17 @@ public struct CmxManualPairingEntry: Equatable, Sendable { /// The port the user types into the phone's port field. public let port: Int + /// The host value copied into the phone's manual-entry field. + /// + /// IPv6 endpoint hosts are stored bare in attach routes, but the iOS manual + /// host parser requires brackets so the host/port boundary stays + /// unambiguous. + public var hostFieldValue: String { + host.contains(":") && !(host.hasPrefix("[") && host.hasSuffix("]")) + ? "[\(host)]" + : host + } + /// Creates a manual-entry pair. /// - Parameters: /// - host: The address for the phone's host field. diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualPairingEntryTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualPairingEntryTests.swift index dac8641a8b96..e39abf3671d9 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualPairingEntryTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualPairingEntryTests.swift @@ -81,6 +81,12 @@ import Testing #expect(entry == CmxManualPairingEntry(host: "100.64.0.5", port: 58465)) } + @Test func hostFieldValueBracketsIPv6ForPhoneManualEntry() { + #expect(CmxManualPairingEntry(host: "fd00::12", port: 58465).hostFieldValue == "[fd00::12]") + #expect(CmxManualPairingEntry(host: "[fd00::12]", port: 58465).hostFieldValue == "[fd00::12]") + #expect(CmxManualPairingEntry(host: "100.64.0.5", port: 58465).hostFieldValue == "100.64.0.5") + } + @Test func emptyRoutesYieldNothing() { #expect(CmxManualPairingEntry.best(in: []) == nil) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift new file mode 100644 index 000000000000..776f51db7ed8 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift @@ -0,0 +1,55 @@ +import CMUXMobileCore +import CmuxMobileRPC +import CmuxMobileSupport +import Foundation + +@MainActor +extension MobileShellComposite { + func disconnectForAuthorizationFailureIfNeeded(_ error: any Error, route: CmxAttachRoute? = nil) -> Bool { + guard Self.shouldDisconnectForAuthorizationFailure(error) else { + return false + } + let category = MobilePairingFailureCategory.classify(error: error, route: route ?? activeRoute) + // Not `applyPairingFailure`: this path also sets `connectionRequiresReauth`, + // uses fallback-if-empty, and gates analytics on `pairingAttemptMethod` so + // live-connection auth evictions never emit `ios_pairing_failed`. + connectionError = category.message.isEmpty + ? L10n.string("mobile.pairing.runtimeUnavailable", defaultValue: "Could not connect to your computer.") + : category.message + connectionErrorGuidance = category.guidance + connectionRequiresReauth = true + connectionState = .disconnected + macConnectionStatus = .unavailable + clearRemoteConnectionContext() + // Only emits while a pairing attempt is in flight: `recordPairingFailed` + // no-ops once `pairingAttemptMethod` is nil (cleared on success and by + // `invalidatePairingAttempt`), so live-connection auth failures that + // also route through here never emit `ios_pairing_failed`. + recordPairingFailed(reason: category.analyticsReason, phase: "auth") + return true + } + + private static func shouldDisconnectForAuthorizationFailure(_ error: any Error) -> Bool { + guard let connectionError = error as? MobileShellConnectionError else { + return false + } + switch connectionError { + case .attachTicketExpired, .authorizationFailed, .accountMismatch, .insecureManualRoute: + return true + case let .rpcError(code, message): + let normalizedCode = code?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + if let normalizedCode, + ["unauthorized", "forbidden", "invalid_token", "token_expired", "expired_token", "auth_required"].contains(normalizedCode) { + return true + } + let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + return normalizedMessage.contains("unauthorized") + || normalizedMessage.contains("forbidden") + || normalizedMessage.contains("invalid token") + || normalizedMessage.contains("expired token") + || normalizedMessage.contains("token expired") + case .invalidResponse, .connectionClosed, .requestTimedOut: + return false + } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 6c892b0665bf..3f918413fe8c 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1585,26 +1585,36 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } let directRoute = try? routeSelection.manualHostRoute(host: normalizedHost, port: port) - if let directRoute, - await manualHostRouteNeedsApproval(directRoute) { - queueManualHostTrustWarning( - route: directRoute, - displayHost: normalizedHost, - pending: .manual( - name: name, - host: normalizedHost, - port: port, - pairedMacDeviceID: pairedMacDeviceID, - recordsPairingAttempt: recordsPairingAttempt, - ifStillCurrent: ifStillCurrent + let approvalAttemptID = beginPairingValidationAttempt() + if let directRoute { + let needsApproval = await manualHostRouteNeedsApproval(directRoute) + guard isCurrentPairingAttempt(approvalAttemptID) else { return .superseded } + if needsApproval { + queueManualHostTrustWarning( + route: directRoute, + displayHost: normalizedHost, + pending: .manual( + name: name, + host: normalizedHost, + port: port, + pairedMacDeviceID: pairedMacDeviceID, + recordsPairingAttempt: recordsPairingAttempt, + ifStillCurrent: ifStillCurrent + ) ) - ) - return .needsUserApproval + return .needsUserApproval + } + } + let attemptID: UUID + if recordsPairingAttempt { + attemptID = beginPairingAttempt(method: "manual") + } else { + attemptID = approvalAttemptID } + guard isCurrentPairingAttempt(attemptID) else { return .superseded } if !preservesActiveConnection { activeRoute = directRoute } - let attemptID = recordsPairingAttempt ? beginPairingAttempt(method: "manual") : beginPairingValidationAttempt() // Fast offline preflight: fail immediately instead of stacking // per-route timeouts into the opaque ~60s blob. switch await failPairingIfOffline( @@ -1653,12 +1663,15 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return .failed } catch { guard isCurrentPairingAttempt(attemptID) else { return .superseded } + let routedError = error as? MobileShellRoutedConnectionError + let underlyingError = routedError?.underlying ?? error + let failureRoute = routedError?.route ?? directRoute ?? activeRoute mobileShellLog.error("manual host pairing failed: \(String(describing: error), privacy: .private)") // A definitive auth failure (expired/invalid token after the // refresh-then-retry in the RPC layer already gave up) must drive the // re-auth prompt, not the generic "could not connect / Retry" banner. - if disconnectForAuthorizationFailureIfNeeded(error) { return .failed } - let category = MobilePairingFailureCategory.classify(error: error, route: directRoute ?? activeRoute) + if disconnectForAuthorizationFailureIfNeeded(underlyingError, route: failureRoute) { return .failed } + let category = MobilePairingFailureCategory.classify(error: underlyingError, route: failureRoute) applyPairingFailure(category, phase: "connect") clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) return .failed @@ -3198,12 +3211,15 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return .needsUserApproval } catch { guard isCurrentPairingAttempt(attemptID) else { return .superseded } + let routedError = error as? MobileShellRoutedConnectionError + let underlyingError = routedError?.underlying ?? error + let failureRoute = routedError?.route ?? activeRoute mobileShellLog.error("pairing failed: \(String(describing: error), privacy: .private)") // Definitive auth failures drive the re-auth prompt rather than a // generic connection error (matches the manual-host path); the // helper records the analytics failure + guidance. - if disconnectForAuthorizationFailureIfNeeded(error) { return .failed } - let category = MobilePairingFailureCategory.classify(error: error, route: activeRoute) + if disconnectForAuthorizationFailureIfNeeded(underlyingError, route: failureRoute) { return .failed } + let category = MobilePairingFailureCategory.classify(error: underlyingError, route: failureRoute) applyPairingFailure(category, phase: "connect") clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) return .failed @@ -4950,20 +4966,23 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let routeAllowsStackAuthFallbackOverride = allowsStackAuthFallback let connectionAttemptStartedAt = pairingAttemptStartedAt var lastError: (any Error)? + var lastErrorRoute: CmxAttachRoute? for route in supportedRoutes { if !preservesActiveConnection { activeRoute = route } mobileShellLog.info("pairing trying route kind=\(route.kind.rawValue, privacy: .public) endpoint=\(route.endpoint.logDescription, privacy: .private)") - if let pendingManualHostTrust, - await manualHostRouteNeedsApproval(route), - case let .hostPort(host, _) = route.endpoint { - queueManualHostTrustWarning( - route: route, - displayHost: host, - pending: pendingManualHostTrust - ) - throw ManualHostTrustApprovalQueued.required + if let pendingManualHostTrust { + let needsApproval = await manualHostRouteNeedsApproval(route) + guard isConnectCurrent() else { return nil } + if needsApproval, case let .hostPort(host, _) = route.endpoint { + queueManualHostTrustWarning( + route: route, + displayHost: host, + pending: pendingManualHostTrust + ) + throw ManualHostTrustApprovalQueued.required + } } let manualHostTrusted = await manualHostStackAuthTrusted(for: route) let routeAllowsStackAuth = MobileShellRouteAuthPolicy().routeAllowsStackAuth( @@ -5086,6 +5105,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return nil } catch { lastError = error + lastErrorRoute = route guard isConnectCurrent() else { return nil } mobileShellLog.error( "pairing route failed kind=\(route.kind.rawValue, privacy: .public) endpoint=\(route.endpoint.logDescription, privacy: .private) scoped=\(workspaceListRequest.isScoped ? 1 : 0, privacy: .public): \(String(describing: error), privacy: .private)" @@ -5095,6 +5115,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } diagnosticLog?.record(DiagnosticEvent(.pairFail)) + if let lastError, let lastErrorRoute { + if lastError is CancellationError { + throw lastError + } + throw MobileShellRoutedConnectionError(underlying: lastError, route: lastErrorRoute) + } throw lastError ?? MobileShellConnectionError.connectionClosed } @@ -5219,7 +5245,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { connectedHostName = "" } - private func clearRemoteConnectionContext(preservingOtherMacWorkspaceState: Bool = false) { + func clearRemoteConnectionContext(preservingOtherMacWorkspaceState: Bool = false) { connectionGeneration = UUID() connectionAttemptGeneration = UUID() cancelRemoteOperationTasks() @@ -5392,7 +5418,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// Emits `ios_pairing_failed` once for the in-flight attempt with a reason + /// phase, then clears the attempt timing so it can't double-fire. - private func recordPairingFailed(reason: String, phase: String) { + func recordPairingFailed(reason: String, phase: String) { guard let method = pairingAttemptMethod else { return } var props: [String: AnalyticsValue] = [ "method": .string(method), @@ -7612,54 +7638,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return true } - func disconnectForAuthorizationFailureIfNeeded(_ error: any Error) -> Bool { - guard Self.shouldDisconnectForAuthorizationFailure(error) else { - return false - } - let category = MobilePairingFailureCategory.classify(error: error, route: activeRoute) - // Not `applyPairingFailure`: this path also sets `connectionRequiresReauth`, - // uses fallback-if-empty, and gates analytics on `pairingAttemptMethod` so - // live-connection auth evictions never emit `ios_pairing_failed`. - connectionError = category.message.isEmpty - ? L10n.string("mobile.pairing.runtimeUnavailable", defaultValue: "Could not connect to your computer.") - : category.message - connectionErrorGuidance = category.guidance - connectionRequiresReauth = true - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() - // Only emits while a pairing attempt is in flight: `recordPairingFailed` - // no-ops once `pairingAttemptMethod` is nil (cleared on success and by - // `invalidatePairingAttempt`), so live-connection auth failures that - // also route through here never emit `ios_pairing_failed`. - recordPairingFailed(reason: category.analyticsReason, phase: "auth") - return true - } - - private static func shouldDisconnectForAuthorizationFailure(_ error: any Error) -> Bool { - guard let connectionError = error as? MobileShellConnectionError else { - return false - } - switch connectionError { - case .attachTicketExpired, .authorizationFailed, .accountMismatch, .insecureManualRoute: - return true - case let .rpcError(code, message): - let normalizedCode = code?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - if let normalizedCode, - ["unauthorized", "forbidden", "invalid_token", "token_expired", "expired_token", "auth_required"].contains(normalizedCode) { - return true - } - let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - return normalizedMessage.contains("unauthorized") - || normalizedMessage.contains("forbidden") - || normalizedMessage.contains("invalid token") - || normalizedMessage.contains("expired token") - || normalizedMessage.contains("token expired") - case .invalidResponse, .connectionClosed, .requestTimedOut: - return false - } - } - private func applyPreviewTicket(_ ticket: CmxAttachTicket, route: CmxAttachRoute) { let terminalID = ticket.terminalID ?? "attached-terminal" setForegroundWorkspaceState( diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRoutedConnectionError.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRoutedConnectionError.swift new file mode 100644 index 000000000000..43e2b186c04b --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRoutedConnectionError.swift @@ -0,0 +1,6 @@ +import CMUXMobileCore + +struct MobileShellRoutedConnectionError: Error { + let underlying: any Error + let route: CmxAttachRoute +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingManualHostTrustStore.swift new file mode 100644 index 000000000000..ad17ecf7b8ec --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingManualHostTrustStore.swift @@ -0,0 +1,42 @@ +import CmuxMobileShellModel + +actor BlockingManualHostTrustStore: MobileManualHostTrustStoring { + private var didBlockFirstLookup = false + private var didEnterFirstLookup = false + private var enteredContinuation: CheckedContinuation? + private var releaseContinuation: CheckedContinuation? + + func waitUntilFirstLookupIsBlocked() async { + if didEnterFirstLookup { + return + } + await withCheckedContinuation { continuation in + enteredContinuation = continuation + } + } + + func releaseFirstLookup() { + releaseContinuation?.resume() + releaseContinuation = nil + } + + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + _ = scope + if !didBlockFirstLookup { + didBlockFirstLookup = true + didEnterFirstLookup = true + enteredContinuation?.resume() + enteredContinuation = nil + await withCheckedContinuation { continuation in + releaseContinuation = continuation + } + } + return false + } + + func trust(_ scope: MobileManualHostTrustScope) async { + _ = scope + } + + func removeAll() async {} +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 7525e741ebc6..3ac135b8ecff 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -217,6 +217,55 @@ import Testing #expect(store.connectionError?.isEmpty == false) } + @Test func staleManualHostApprovalLookupCannotReplaceCurrentPrompt() async throws { + let trustStore = BlockingManualHostTrustStore() + let store = makeStore( + runtime: PairingDeadlineRuntime(supportedRouteKinds: [.manualHost]), + manualHostTrustStore: trustStore + ) + + let first = Task { @MainActor in + await store.connectManualHost( + name: "Old LAN", + host: "192.168.1.77", + port: 58_465, + recordsPairingAttempt: true + ) + } + await trustStore.waitUntilFirstLookupIsBlocked() + + let second = await store.connectManualHost( + name: "New LAN", + host: "192.168.1.88", + port: 58_465, + recordsPairingAttempt: true + ) + + #expect(second == .needsUserApproval) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.88:58465") + + await trustStore.releaseFirstLookup() + let firstResult = await first.value + + #expect(firstResult == .superseded) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.88:58465") + } + + @Test func failedPairingWhileConnectedReportsAttemptedRoute() async throws { + let clock = TestClock() + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let runtime = PairingDeadlineRuntime() + let store = makeStore(runtime: runtime, connectionState: .connected) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + + let result = await store.connectPairingURLResult(Self.qrURL) + + #expect(result == .failed) + #expect(store.connectionState == .connected) + #expect(store.connectionError?.contains("100.64.0.5") == true) + } + private static let qrURL = "cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465" private func makeStore( diff --git a/Sources/Mobile/Pairing/MobilePairingView.swift b/Sources/Mobile/Pairing/MobilePairingView.swift index a1a1fa68133e..9d8ad2495c75 100644 --- a/Sources/Mobile/Pairing/MobilePairingView.swift +++ b/Sources/Mobile/Pairing/MobilePairingView.swift @@ -400,7 +400,7 @@ struct MobilePairingView: View { HStack(spacing: 8) { copyButton( label: String(localized: "mobile.pairing.manual.copyIP", defaultValue: "Copy IP"), - value: entry.host + value: entry.hostFieldValue ) copyButton( label: String(localized: "mobile.pairing.manual.copyPort", defaultValue: "Copy Port"), From 43ae450a9be0eca8d2aafadeb5c6d8e64cb09d22 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 3 Jul 2026 21:39:04 -0700 Subject: [PATCH 34/91] Fix manual host pairing review follow-ups --- ...eShellComposite+AuthorizationFailure.swift | 23 +++++-- .../MobileShellComposite.swift | 18 ++++-- .../AuthorizationFailingTransport.swift | 18 ++++++ ...AuthorizationFailingTransportFactory.swift | 9 +++ .../MobilePairingAttemptDeadlineTests.swift | 64 +++++++++++++++++++ 5 files changed, 122 insertions(+), 10 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransport.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransportFactory.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift index 776f51db7ed8..037ea4b137b1 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift @@ -5,18 +5,29 @@ import Foundation @MainActor extension MobileShellComposite { - func disconnectForAuthorizationFailureIfNeeded(_ error: any Error, route: CmxAttachRoute? = nil) -> Bool { - guard Self.shouldDisconnectForAuthorizationFailure(error) else { + func disconnectForAuthorizationFailureIfNeeded( + _ error: any Error, + route: CmxAttachRoute? = nil, + preservingActiveConnection: Bool = false + ) -> Bool { + guard shouldDisconnectForAuthorizationFailure(error) else { return false } let category = MobilePairingFailureCategory.classify(error: error, route: route ?? activeRoute) - // Not `applyPairingFailure`: this path also sets `connectionRequiresReauth`, - // uses fallback-if-empty, and gates analytics on `pairingAttemptMethod` so - // live-connection auth evictions never emit `ios_pairing_failed`. + // Not `applyPairingFailure`: this path can also set + // `connectionRequiresReauth`, uses fallback-if-empty, and gates analytics + // on `pairingAttemptMethod` so live-connection auth evictions never emit + // `ios_pairing_failed`. connectionError = category.message.isEmpty ? L10n.string("mobile.pairing.runtimeUnavailable", defaultValue: "Could not connect to your computer.") : category.message connectionErrorGuidance = category.guidance + // Auth failures from a new pairing attempt should report that attempt's + // failure without evicting the already-connected Mac. + guard !preservingActiveConnection else { + recordPairingFailed(reason: category.analyticsReason, phase: "auth") + return true + } connectionRequiresReauth = true connectionState = .disconnected macConnectionStatus = .unavailable @@ -29,7 +40,7 @@ extension MobileShellComposite { return true } - private static func shouldDisconnectForAuthorizationFailure(_ error: any Error) -> Bool { + private func shouldDisconnectForAuthorizationFailure(_ error: any Error) -> Bool { guard let connectionError = error as? MobileShellConnectionError else { return false } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 3f918413fe8c..4864dbc01bda 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1670,7 +1670,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // A definitive auth failure (expired/invalid token after the // refresh-then-retry in the RPC layer already gave up) must drive the // re-auth prompt, not the generic "could not connect / Retry" banner. - if disconnectForAuthorizationFailureIfNeeded(underlyingError, route: failureRoute) { return .failed } + if disconnectForAuthorizationFailureIfNeeded( + underlyingError, + route: failureRoute, + preservingActiveConnection: preservesActiveConnection + ) { return .failed } let category = MobilePairingFailureCategory.classify(error: underlyingError, route: failureRoute) applyPairingFailure(category, phase: "connect") clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) @@ -3074,7 +3078,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { acceptedVersionWarning: Bool ) async -> MobilePairingURLConnectionResult { let rawURL = Self.normalizedPairingURL(rawValue ?? pairingCode) - _ = beginPairingValidationAttempt() + let validationAttemptID = beginPairingValidationAttempt() let preservesActiveConnection = hasActiveMacConnection connectionAttemptGeneration = UUID() if connectionState != .connected { @@ -3149,7 +3153,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } let candidateRoutes = routeSelection.supportedRoutes(for: ticket, supportedKinds: runtime?.supportedRouteKinds ?? []) - if let approval = await firstManualHostRouteNeedingApproval(in: candidateRoutes), + let manualHostApproval = await firstManualHostRouteNeedingApproval(in: candidateRoutes) + guard isCurrentPairingAttempt(validationAttemptID) else { return .superseded } + if let approval = manualHostApproval, case let .hostPort(host, _) = approval.route.endpoint { queueManualHostTrustWarning( route: approval.route, @@ -3218,7 +3224,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // Definitive auth failures drive the re-auth prompt rather than a // generic connection error (matches the manual-host path); the // helper records the analytics failure + guidance. - if disconnectForAuthorizationFailureIfNeeded(underlyingError, route: failureRoute) { return .failed } + if disconnectForAuthorizationFailureIfNeeded( + underlyingError, + route: failureRoute, + preservingActiveConnection: preservesActiveConnection + ) { return .failed } let category = MobilePairingFailureCategory.classify(error: underlyingError, route: failureRoute) applyPairingFailure(category, phase: "connect") clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransport.swift new file mode 100644 index 000000000000..66437cadff44 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransport.swift @@ -0,0 +1,18 @@ +import CmuxMobileRPC +import Foundation + +actor AuthorizationFailingTransport: CmxByteTransport { + func connect() async throws { + throw MobileShellConnectionError.authorizationFailed("Authorization failed") + } + + func receive() async throws -> Data? { + nil + } + + func send(_ data: Data) async throws { + _ = data + } + + func close() async {} +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransportFactory.swift new file mode 100644 index 000000000000..40530b044239 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransportFactory.swift @@ -0,0 +1,9 @@ +import CMUXMobileCore +import CmuxMobileRPC + +struct AuthorizationFailingTransportFactory: CmxByteTransportFactory { + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + _ = route + return AuthorizationFailingTransport() + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 3ac135b8ecff..39e2549e26a5 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -251,6 +251,32 @@ import Testing #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.88:58465") } + @Test func stalePairingURLManualHostApprovalLookupCannotReplaceCurrentPrompt() async throws { + let trustStore = BlockingManualHostTrustStore() + let store = makeStore( + runtime: PairingDeadlineRuntime(supportedRouteKinds: [.manualHost]), + manualHostTrustStore: trustStore + ) + let firstURL = try attachURL(for: manualHostTicket(host: "192.168.1.77")) + let secondURL = try attachURL(for: manualHostTicket(host: "192.168.1.88")) + + let first = Task { @MainActor in + await store.connectPairingURLResult(firstURL) + } + await trustStore.waitUntilFirstLookupIsBlocked() + + let second = await store.connectPairingURLResult(secondURL) + + #expect(second == .needsUserApproval) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.88:58465") + + await trustStore.releaseFirstLookup() + let firstResult = await first.value + + #expect(firstResult == .superseded) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.88:58465") + } + @Test func failedPairingWhileConnectedReportsAttemptedRoute() async throws { let clock = TestClock() let oldRouter = LivenessHostRouter() @@ -266,8 +292,46 @@ import Testing #expect(store.connectionError?.contains("100.64.0.5") == true) } + @Test func authFailureDuringPairingWhileConnectedKeepsExistingConnection() async throws { + let clock = TestClock() + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let runtime = PairingDeadlineRuntime( + transportFactory: AuthorizationFailingTransportFactory() + ) + let store = makeStore(runtime: runtime, connectionState: .connected) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + let originalClient = try #require(store.remoteClient) + + let result = await store.connectPairingURLResult(Self.qrURL) + + #expect(result == .failed) + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + #expect(store.connectionRequiresReauth == false) + #expect(store.connectionError?.isEmpty == false) + } + private static let qrURL = "cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465" + private func manualHostTicket(host: String) throws -> CmxAttachTicket { + let route = try CmxAttachRoute( + id: "manual-\(host)", + kind: .manualHost, + endpoint: .hostPort(host: host, port: 58_465), + priority: 0 + ) + return try CmxAttachTicket( + workspaceID: "live-workspace", + terminalID: "live-terminal", + macDeviceID: "test-mac", + macDisplayName: "Test Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [route], + expiresAt: Date().addingTimeInterval(3600) + ) + } + private func makeStore( runtime: any MobileSyncRuntime = PairingDeadlineRuntime(), pairingCode: String = "", From 8dcf1f152fdc899d34ca8ca84f29fbd9db6da131 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 8 Jul 2026 22:53:51 -0700 Subject: [PATCH 35/91] Fix mobile shell reconnect CI closeout --- ...eShellComposite+AuthorizationFailure.swift | 25 +------------------ .../MobileShellComposite.swift | 25 ++++++++++++++++--- .../AttachTicketReconnectTransport.swift | 4 +-- .../AuthorizationFailingTransport.swift | 1 + .../ReconnectRouteSelectionTests.swift | 1 + 5 files changed, 26 insertions(+), 30 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift index 037ea4b137b1..e8baff179048 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift @@ -1,6 +1,5 @@ import CMUXMobileCore import CmuxMobileRPC -import CmuxMobileSupport import Foundation @MainActor @@ -14,29 +13,7 @@ extension MobileShellComposite { return false } let category = MobilePairingFailureCategory.classify(error: error, route: route ?? activeRoute) - // Not `applyPairingFailure`: this path can also set - // `connectionRequiresReauth`, uses fallback-if-empty, and gates analytics - // on `pairingAttemptMethod` so live-connection auth evictions never emit - // `ios_pairing_failed`. - connectionError = category.message.isEmpty - ? L10n.string("mobile.pairing.runtimeUnavailable", defaultValue: "Could not connect to your computer.") - : category.message - connectionErrorGuidance = category.guidance - // Auth failures from a new pairing attempt should report that attempt's - // failure without evicting the already-connected Mac. - guard !preservingActiveConnection else { - recordPairingFailed(reason: category.analyticsReason, phase: "auth") - return true - } - connectionRequiresReauth = true - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() - // Only emits while a pairing attempt is in flight: `recordPairingFailed` - // no-ops once `pairingAttemptMethod` is nil (cleared on success and by - // `invalidatePairingAttempt`), so live-connection auth failures that - // also route through here never emit `ios_pairing_failed`. - recordPairingFailed(reason: category.analyticsReason, phase: "auth") + applyAuthorizationFailure(category, preservingActiveConnection: preservingActiveConnection) return true } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 892515c411c2..f00059a169ee 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1576,7 +1576,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { port: Int, pairedMacDeviceID: String, ifStillCurrent: (() -> Bool)? = nil - ) async { + ) async -> MobilePairingURLConnectionResult { await connectManualHost( name: name, host: host, @@ -1848,10 +1848,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard generation == storedMacReconnectGeneration, await isScopeCurrent(scope), !latestForgottenIDs.contains(mac.macDeviceID) else { break } // Best-effort registry refresh for this Mac in the background. refreshRoutesFromRegistry(for: mac, scope: scope) - await connectStoredMacHost( + let result = await connectStoredMacHost( name: mac.displayName ?? host, host: host, port: port, pairedMacDeviceID: mac.macDeviceID) - if connectionState == .connected { break } + if result == .connected || result == .superseded { break } } restoringDeadline.cancel() // A newer attempt may have started during the connect; it now owns the flags. @@ -2781,7 +2781,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return false } guard await isScopeCurrent(restoreScope), isRestoreCurrent() else { return false } - await connectStoredMacHost( + _ = await connectStoredMacHost( name: previousActive.displayName ?? host, host: host, port: port, @@ -5671,6 +5671,23 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { connectionErrorGuidance = category.guidance } + func applyAuthorizationFailure( + _ category: MobilePairingFailureCategory, + preservingActiveConnection: Bool + ) { + connectionError = category.message.isEmpty + ? L10n.string("mobile.pairing.runtimeUnavailable", defaultValue: "Could not connect to your computer.") + : category.message + connectionErrorGuidance = category.guidance + if !preservingActiveConnection { + connectionRequiresReauth = true + connectionState = .disconnected + macConnectionStatus = .unavailable + clearRemoteConnectionContext() + } + recordPairingFailed(reason: category.analyticsReason, phase: "auth") + } + /// How the preflight resolved: proceed, ``.offline`` applied, or superseded. private enum PairingPreflightOutcome { case proceed diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AttachTicketReconnectTransport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AttachTicketReconnectTransport.swift index b4f296ead4f4..51659cce696c 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AttachTicketReconnectTransport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AttachTicketReconnectTransport.swift @@ -3,7 +3,7 @@ import CmuxMobileRPC import Foundation actor AttachTicketReconnectTransport: CmxByteTransportFactory, CmxByteTransport { - private let ticketRoute: CmxAttachRoute + private nonisolated let ticketRoute: CmxAttachRoute private var pendingFrames: [Data] = [] private var receiveWaiters: [CheckedContinuation] = [] @@ -12,7 +12,7 @@ actor AttachTicketReconnectTransport: CmxByteTransportFactory, CmxByteTransport } nonisolated func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { - self + AttachTicketReconnectTransport(ticketRoute: ticketRoute) } func connect() async throws {} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransport.swift index 66437cadff44..8c282b7c5df7 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationFailingTransport.swift @@ -1,3 +1,4 @@ +import CMUXMobileCore import CmuxMobileRPC import Foundation diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index 349d9dcfab82..cd4ef00aecae 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -1,4 +1,5 @@ import CMUXMobileCore +import CmuxMobileShellModel import Testing @testable import CmuxMobileShell From 16cf3ed1b60f1f5db1e2ef004b8e8c6d99458689 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 8 Jul 2026 23:20:38 -0700 Subject: [PATCH 36/91] Fix mobile shell deinit isolation --- .../MobileShellComposite.swift | 40 ++++++++++--------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index f00059a169ee..56ab6dbb6296 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1023,24 +1023,28 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { self.pairingAttemptID = UUID() } - deinit { - MainActor.assumeIsolated { - presenceTask?.cancel() - networkPathObservationTask?.cancel() - terminalEventListenerTask?.cancel() - terminalSubscriptionStartTask?.cancel() - renderGridLivenessTimer?.cancel() - renderGridLivenessProbeTask?.cancel() - terminalSubscriptionRefreshTask?.cancel() - createWorkspaceTask?.cancel() - createTerminalTask?.cancel() - workspaceListRefreshTask?.cancel() - pullToRefreshTask?.cancel() - cancelAllTerminalReplayTasks() - teardownSecondaryMacSubscriptions() - if let remoteClient { - Task { await remoteClient.disconnect() } - } + #if compiler(>=6.2) + isolated deinit { cleanupForDeinit() } + #else + deinit { cleanupForDeinit() } + #endif + + private func cleanupForDeinit() { + presenceTask?.cancel() + networkPathObservationTask?.cancel() + terminalEventListenerTask?.cancel() + terminalSubscriptionStartTask?.cancel() + renderGridLivenessTimer?.cancel() + renderGridLivenessProbeTask?.cancel() + terminalSubscriptionRefreshTask?.cancel() + createWorkspaceTask?.cancel() + createTerminalTask?.cancel() + workspaceListRefreshTask?.cancel() + pullToRefreshTask?.cancel() + cancelAllTerminalReplayTasks() + teardownSecondaryMacSubscriptions() + if let remoteClient { + Task { await remoteClient.disconnect() } } } From 5d4ded00e05e4b1d832fb297d77ed05541948f75 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 8 Jul 2026 23:44:33 -0700 Subject: [PATCH 37/91] Add manual host approval race regressions --- .../MobilePairingAttemptDeadlineTests.swift | 39 +++++++++++++++++++ .../ReconnectRouteSelectionTests.swift | 18 +++++++++ 2 files changed, 57 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 464406f4ddd9..94b1d2b9b21d 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -219,6 +219,45 @@ import Testing #expect(store.connectionError?.isEmpty == false) } + @Test func staleManualHostApprovalDoesNotPersistTrustOrRequestTicket() async throws { + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: box), + now: { clock.now }, + supportedRouteKinds: [.manualHost] + ) + let trustStore = InMemoryMobileManualHostTrustStore() + let store = makeStore(runtime: runtime, manualHostTrustStore: trustStore) + var isCurrent = true + + let queued = await store.connectManualHost( + name: "Stale LAN", + host: "192.168.1.77", + port: 58_465, + recordsPairingAttempt: true, + ifStillCurrent: { isCurrent } + ) + + #expect(queued == .needsUserApproval) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + + isCurrent = false + let approved = await store.acceptManualHostTrustWarning() + let route = try CmxAttachRoute( + id: "manual_host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465) + ) + let scope = try #require(MobileManualHostTrustScope(route: route, stackUserID: nil)) + + #expect(approved == .superseded) + #expect(store.manualHostTrustWarning == nil) + #expect(await trustStore.isTrusted(scope) == false) + #expect(await router.count(of: "mobile.attach_ticket.create") == 0) + } + @Test func staleManualHostApprovalLookupCannotReplaceCurrentPrompt() async throws { let trustStore = BlockingManualHostTrustStore() let store = makeStore( diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index cd4ef00aecae..a57c1b4e4e51 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -37,6 +37,15 @@ import Testing ) } + private func legacyLANStoredAsTailscale(_ port: Int = 50906) throws -> CmxAttachRoute { + try CmxAttachRoute( + id: "legacy_lan", + kind: .tailscale, + endpoint: .hostPort(host: "192.168.1.77", port: port), + priority: 1 + ) + } + @Test func physicalDevicePrefersRealRouteOverLowerPriorityLoopback() throws { let pick = MobileShellRouteSelection().firstReconnectHostPortRoute( [try loopback(), try tailscale()], @@ -125,6 +134,15 @@ import Testing #expect(pick?.0 == "lawrences-macbook-pro-2.tail137216.ts.net") } + @Test func tailscaleDNSBeatsLegacyLANRouteStoredAsTailscale() throws { + let pick = MobileShellRouteSelection().firstReconnectHostPortRoute( + [try loopback(50922), try legacyLANStoredAsTailscale(50922), try magicDNS(50922)], + supportedKinds: [.debugLoopback, .manualHost, .tailscale], + preferNonLoopback: true + ) + #expect(pick?.0 == "lawrences-macbook-pro-2.tail137216.ts.net") + } + @Test func ipLiteralHostClassification() { #expect(MobileShellRouteSelection().isIPLiteralHost("100.82.214.112")) #expect(MobileShellRouteSelection().isIPLiteralHost("127.0.0.1")) From 6816449fd315773e069c17ac272d224b2ef4bf1a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Wed, 8 Jul 2026 23:44:45 -0700 Subject: [PATCH 38/91] Fix manual host approval closeout races --- .../MobileShellComposite+ManualHostTrust.swift | 6 ++++++ .../CmuxMobileShell/MobileShellComposite.swift | 11 +++++------ .../CmuxMobileShell/MobileShellRouteSelection.swift | 4 ++-- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 3a587a5f36d6..9a55fb9a5f57 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -79,10 +79,16 @@ extension MobileShellComposite { clearManualHostTrustWarning() return .failed } + if case let .manual(_, _, _, _, _, ifStillCurrent) = pending, + ifStillCurrent?() == false { + clearManualHostTrustWarning() + return .superseded + } clearManualHostTrustWarning() await manualHostTrustStore.trust(warning.scope) switch pending { case let .manual(name, host, port, pairedMacDeviceID, recordsPairingAttempt, ifStillCurrent): + guard ifStillCurrent?() != false else { return .superseded } return await connectManualHost( name: name, host: host, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 56ab6dbb6296..f3490c3c6180 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1653,12 +1653,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return .needsUserApproval } } - let attemptID: UUID - if recordsPairingAttempt { - attemptID = beginPairingAttempt(method: "manual") - } else { - attemptID = approvalAttemptID - } + let attemptID = recordsPairingAttempt + ? beginPairingAttempt(method: "manual") + : approvalAttemptID guard isCurrentPairingAttempt(attemptID) else { return .superseded } if !preservesActiveConnection { activeRoute = directRoute @@ -1676,7 +1673,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { case .proceed: break } do { + guard ifStillCurrent?() != false else { return .superseded } let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) + guard isCurrentPairingAttempt(attemptID), ifStillCurrent?() != false else { return .superseded } let ticket = try await manualHostTicket( name: trimmedName, host: normalizedHost, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift index be9cbda20955..7ca39e6d6289 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift @@ -61,11 +61,11 @@ struct MobileShellRouteSelection: Sendable { if let tailscaleIP = firstHostPort(where: { route in guard route.kind == .tailscale, case let .hostPort(host, _) = route.endpoint else { return false } - return isIPLiteralHost(host) + return routeAuthPolicy.routeAllowsStackAuth(route) && isIPLiteralHost(host) }) { return tailscaleIP } - if let tailscale = firstHostPort(where: { $0.kind == .tailscale }) { + if let tailscale = firstHostPort(where: { $0.kind == .tailscale && routeAuthPolicy.routeAllowsStackAuth($0) }) { return tailscale } if let real = firstHostPort(where: { $0.kind != .debugLoopback }) { From e0f7d6fe1792b2efc8a7e06cdb27f0932bea6700 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 00:10:39 -0700 Subject: [PATCH 39/91] Add pairing view stale approval regression --- .../CmuxMobileShellUI/PairingView.swift | 2 +- .../PairingViewPendingApprovalTests.swift | 37 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift index a20b4ee4b50d..36aefbc5ec51 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift @@ -350,7 +350,7 @@ struct PairingView: View { return String(format: format, email) } - private func pair() { + func pair() { validationError = nil let trimmedHost = host.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedHost.isEmpty else { diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift new file mode 100644 index 000000000000..3017b87d464d --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift @@ -0,0 +1,37 @@ +import CmuxMobileShellModel +import SwiftUI +import Testing +@testable import CmuxMobileShellUI + +@Suite struct PairingViewPendingApprovalTests { + @MainActor + @Test func pairClearsPendingManualHostApprovalBeforeLocalValidationReturns() { + var cancelCount = 0 + let view = PairingView( + pairingCode: .constant(""), + connectionError: nil, + connectionErrorGuidance: nil, + versionWarning: nil, + manualHostTrustWarning: warning(), + connectPairingCode: {}, + acceptVersionWarning: {}, + acceptManualHostTrustWarning: {}, + connectManualHost: { _, _, _ in }, + cancelPairing: { cancelCount += 1 }, + cancel: {} + ) + + view.pair() + + #expect(cancelCount == 1) + } + + private func warning() -> MobileManualHostTrustWarning { + let scope = MobileManualHostTrustScope( + host: "192.168.1.77", + port: 58_465, + stackUserID: "user_123" + )! + return MobileManualHostTrustWarning(scope: scope) + } +} From 02f43370746032f4660e4d6c02cef5f62cb5a069 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 00:13:16 -0700 Subject: [PATCH 40/91] Clear stale pairing approvals before validation --- .../Sources/CmuxMobileShellUI/PairingView.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift index 36aefbc5ec51..7238e06e33fd 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift @@ -352,6 +352,9 @@ struct PairingView: View { func pair() { validationError = nil + if versionWarning != nil || manualHostTrustWarning != nil { + cancelPairing() + } let trimmedHost = host.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedHost.isEmpty else { validationError = L10n.string("mobile.addDevice.invalidHost", defaultValue: "Enter a host or IP address, without spaces or URL paths.") From 08870c0511d09d9edfe2a623cdcfc24cd229478f Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 00:31:35 -0700 Subject: [PATCH 41/91] Add cancelled manual host approval regression --- ...ckingManualHostTrustPersistenceStore.swift | 41 +++++++++++++++++++ .../MobilePairingAttemptDeadlineTests.swift | 37 +++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingManualHostTrustPersistenceStore.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingManualHostTrustPersistenceStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingManualHostTrustPersistenceStore.swift new file mode 100644 index 000000000000..215892a78fba --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingManualHostTrustPersistenceStore.swift @@ -0,0 +1,41 @@ +import CmuxMobileShellModel + +actor BlockingManualHostTrustPersistenceStore: MobileManualHostTrustStoring { + private var trustedScopes: Set = [] + private var didEnterTrust = false + private var enteredContinuation: CheckedContinuation? + private var releaseContinuation: CheckedContinuation? + + func waitUntilTrustIsBlocked() async { + if didEnterTrust { + return + } + await withCheckedContinuation { continuation in + enteredContinuation = continuation + } + } + + func releaseTrust() { + releaseContinuation?.resume() + releaseContinuation = nil + } + + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + trustedScopes.contains(scope) + } + + func trust(_ scope: MobileManualHostTrustScope) async { + didEnterTrust = true + enteredContinuation?.resume() + enteredContinuation = nil + await withCheckedContinuation { continuation in + releaseContinuation = continuation + } + guard !Task.isCancelled else { return } + trustedScopes.insert(scope) + } + + func removeAll() async { + trustedScopes.removeAll() + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 94b1d2b9b21d..1462c7356df5 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -318,6 +318,43 @@ import Testing #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.88:58465") } + @Test func cancelledPairingURLApprovalDoesNotPersistTrustOrConnect() async throws { + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: box), + now: { clock.now }, + supportedRouteKinds: [.manualHost] + ) + let trustStore = BlockingManualHostTrustPersistenceStore() + let store = makeStore(runtime: runtime, manualHostTrustStore: trustStore) + let route = try CmxAttachRoute( + id: "manual", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465) + ) + let scope = try #require(MobileManualHostTrustScope(route: route, stackUserID: nil)) + let url = try attachURL(for: manualHostTicket(host: "192.168.1.77")) + + let queued = await store.connectPairingURLResult(url) + #expect(queued == .needsUserApproval) + + let approval = Task { @MainActor in + await store.acceptManualHostTrustWarning() + } + await trustStore.waitUntilTrustIsBlocked() + approval.cancel() + store.cancelPairing() + await trustStore.releaseTrust() + let result = await approval.value + + #expect(result == .superseded) + #expect(store.manualHostTrustWarning == nil) + #expect(await trustStore.isTrusted(scope) == false) + #expect(await router.count(of: "workspace.list") == 0) + } + @Test func failedPairingWhileConnectedReportsAttemptedRoute() async throws { let clock = TestClock() let oldRouter = LivenessHostRouter() From a21f6672edb4e37a1f1729c26a33f9784308ff5c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 00:36:58 -0700 Subject: [PATCH 42/91] Fix cancelled manual host approvals --- ...MobileShellComposite+ManualHostTrust.swift | 18 +++++++++++---- .../MobileShellComposite.swift | 13 ++++++----- .../PendingManualHostTrust.swift | 23 ++++++++++++++++++- .../InMemoryMobileManualHostTrustStore.swift | 1 + ...erDefaultsMobileManualHostTrustStore.swift | 1 + 5 files changed, 44 insertions(+), 12 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 9a55fb9a5f57..60f4429b70c9 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -79,16 +79,15 @@ extension MobileShellComposite { clearManualHostTrustWarning() return .failed } - if case let .manual(_, _, _, _, _, ifStillCurrent) = pending, - ifStillCurrent?() == false { + guard isPendingManualHostTrustCurrent(pending) else { clearManualHostTrustWarning() return .superseded } clearManualHostTrustWarning() await manualHostTrustStore.trust(warning.scope) + guard isPendingManualHostTrustCurrent(pending) else { return .superseded } switch pending { - case let .manual(name, host, port, pairedMacDeviceID, recordsPairingAttempt, ifStillCurrent): - guard ifStillCurrent?() != false else { return .superseded } + case let .manual(_, name, host, port, pairedMacDeviceID, recordsPairingAttempt, ifStillCurrent): return await connectManualHost( name: name, host: host, @@ -97,11 +96,20 @@ extension MobileShellComposite { recordsPairingAttempt: recordsPairingAttempt, ifStillCurrent: ifStillCurrent ) - case let .pairingURL(rawURL, acceptedVersionWarning): + case let .pairingURL(_, rawURL, acceptedVersionWarning): return await connectPairingURLResult( rawURL, acceptedVersionWarning: acceptedVersionWarning ) } } + + private func isPendingManualHostTrustCurrent(_ pending: PendingManualHostTrust) -> Bool { + guard !Task.isCancelled, + isCurrentPairingAttempt(pending.attemptID), + pending.ifStillCurrent?() != false else { + return false + } + return true + } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index f3490c3c6180..0ac255d6fe34 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1642,6 +1642,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { route: directRoute, displayHost: normalizedHost, pending: .manual( + attemptID: approvalAttemptID, name: name, host: normalizedHost, port: port, @@ -3216,6 +3217,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { route: approval.route, displayHost: host, pending: .pairingURL( + attemptID: validationAttemptID, rawURL: rawURL, acceptedVersionWarning: acceptedVersionWarning ) @@ -3250,6 +3252,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let noThrowFailure = try await connect( ticket: ticket, pendingManualHostTrust: .pairingURL( + attemptID: attemptID, rawURL: rawURL, acceptedVersionWarning: acceptedVersionWarning ) @@ -3291,16 +3294,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } + /// Cancels the active pairing attempt and clears transient pairing prompts. public func cancelPairing() { invalidatePairingAttempt() clearPairingError() - if pairingVersionWarning != nil || pendingPairingVersionWarningURL != nil || manualHostTrustWarning != nil { - clearPairingVersionWarning() - clearManualHostTrustWarning() - return - } + let hadBlockingPrompt = pairingVersionWarning != nil || pendingPairingVersionWarningURL != nil || manualHostTrustWarning != nil clearPairingVersionWarning() clearManualHostTrustWarning() + if hadBlockingPrompt { return } connectionState = .disconnected macConnectionStatus = .unavailable clearRemoteConnectionContext() @@ -5506,7 +5507,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { pairingAttemptMethod = nil } - private func isCurrentPairingAttempt(_ attemptID: UUID) -> Bool { + func isCurrentPairingAttempt(_ attemptID: UUID) -> Bool { pairingAttemptID == attemptID && isSignedIn } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift index c337a068c32a..7a56b193f7b4 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift @@ -1,5 +1,8 @@ +import Foundation + enum PendingManualHostTrust { case manual( + attemptID: UUID, name: String, host: String, port: Int, @@ -7,5 +10,23 @@ enum PendingManualHostTrust { recordsPairingAttempt: Bool, ifStillCurrent: (() -> Bool)? ) - case pairingURL(rawURL: String, acceptedVersionWarning: Bool) + case pairingURL(attemptID: UUID, rawURL: String, acceptedVersionWarning: Bool) + + var attemptID: UUID { + switch self { + case let .manual(attemptID, _, _, _, _, _, _): + attemptID + case let .pairingURL(attemptID, _, _): + attemptID + } + } + + var ifStillCurrent: (() -> Bool)? { + switch self { + case let .manual(_, _, _, _, _, _, ifStillCurrent): + ifStillCurrent + case .pairingURL: + nil + } + } } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/InMemoryMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/InMemoryMobileManualHostTrustStore.swift index 307f51210f08..00140b9e3f57 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/InMemoryMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/InMemoryMobileManualHostTrustStore.swift @@ -16,6 +16,7 @@ public actor InMemoryMobileManualHostTrustStore: MobileManualHostTrustStoring { /// Persists trust for exactly the given host/port/account scope. /// - Parameter scope: The scope to approve. public func trust(_ scope: MobileManualHostTrustScope) async { + guard !Task.isCancelled else { return } trustedScopes.insert(scope) } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift index bd56acc7df7f..b203ba22d810 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -75,6 +75,7 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin /// Persists trust for exactly the given host/port/account scope until its expiry time. /// - Parameter scope: The scope to approve. public func trust(_ scope: MobileManualHostTrustScope) async { + guard !Task.isCancelled else { return } let currentTime = now().timeIntervalSince1970 var trusted = trustedExpirations().filter { _, expiresAt in expiresAt > currentTime From 5fa6edc8125ff1e3f134c00184ddb0773c07421b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 11:43:48 -0700 Subject: [PATCH 43/91] Fix manual host switch approval lifecycle --- ...MobileShellComposite+ManualHostTrust.swift | 17 +++++- .../MobileShellComposite.swift | 19 ++++-- .../PendingManualHostTrust.swift | 14 ++++- .../MobileShellManualHostReconnectTests.swift | 61 ++++++++++++++++++- 4 files changed, 97 insertions(+), 14 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 60f4429b70c9..f6df619a5f52 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -80,15 +80,19 @@ extension MobileShellComposite { return .failed } guard isPendingManualHostTrustCurrent(pending) else { + finishPendingManualHostSwitchAttempt(pending) clearManualHostTrustWarning() return .superseded } clearManualHostTrustWarning() await manualHostTrustStore.trust(warning.scope) - guard isPendingManualHostTrustCurrent(pending) else { return .superseded } + guard isPendingManualHostTrustCurrent(pending) else { + finishPendingManualHostSwitchAttempt(pending) + return .superseded + } switch pending { - case let .manual(_, name, host, port, pairedMacDeviceID, recordsPairingAttempt, ifStillCurrent): - return await connectManualHost( + case let .manual(_, name, host, port, pairedMacDeviceID, recordsPairingAttempt, _, ifStillCurrent): + let result = await connectManualHost( name: name, host: host, port: port, @@ -96,6 +100,8 @@ extension MobileShellComposite { recordsPairingAttempt: recordsPairingAttempt, ifStillCurrent: ifStillCurrent ) + finishPendingManualHostSwitchAttempt(pending) + return result case let .pairingURL(_, rawURL, acceptedVersionWarning): return await connectPairingURLResult( rawURL, @@ -112,4 +118,9 @@ extension MobileShellComposite { } return true } + + private func finishPendingManualHostSwitchAttempt(_ pending: PendingManualHostTrust) { + guard let attemptID = pending.macSwitchAttemptID else { return } + finishMacSwitchAttempt(attemptID) + } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 33b548dcc5d9..4bab453b64a6 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1592,6 +1592,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { port: Int, pairedMacDeviceID: String? = nil, recordsPairingAttempt: Bool, + pendingMacSwitchAttemptID: UUID? = nil, ifStillCurrent: (() -> Bool)? = nil ) async -> MobilePairingURLConnectionResult { let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) @@ -1637,6 +1638,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { port: port, pairedMacDeviceID: pairedMacDeviceID, recordsPairingAttempt: recordsPairingAttempt, + macSwitchAttemptID: pendingMacSwitchAttemptID, ifStillCurrent: ifStillCurrent ) ) @@ -2602,7 +2604,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { public func switchToMac(macDeviceID: String) async -> Bool { guard let pairedMacStore else { return false } let switchAttemptID = beginMacSwitchAttempt() - defer { finishMacSwitchAttempt(switchAttemptID) } + var shouldFinishSwitchAttempt = true + defer { if shouldFinishSwitchAttempt { finishMacSwitchAttempt(switchAttemptID) } } // FAST PATH: if a live read-only connection to this Mac already exists, // promote it to the foreground (reuse the client) instead of re-dialing. if await promoteSecondaryToForeground(macDeviceID, switchAttemptID: switchAttemptID) { @@ -2699,11 +2702,16 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { port: route.port, pairedMacDeviceID: macDeviceID, recordsPairingAttempt: true, + pendingMacSwitchAttemptID: switchAttemptID, ifStillCurrent: { [weak self] in self?.isCurrentMacSwitchAttempt(switchAttemptID) == true } ) - if result == .needsUserApproval || result == .superseded { + if result == .needsUserApproval { + shouldFinishSwitchAttempt = false + return false + } + if result == .superseded { return false } guard isCurrentMacSwitchAttempt(switchAttemptID) else { @@ -2741,9 +2749,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // The switch did not connect and the destructive connect path dropped // the previous session; reconnect to the still-active previous Mac so // the user is not left stranded on a failed switch. - // Keep the attempt alive through the restore so a rapid follow-up - // picker selection can either cancel this rollback while preserving - // its baseline, or replace it with a new live foreground baseline. let restoreTarget = macSwitchRestoreBaseline ?? previousForegroundMac if await restorePreviousMacIfNeeded(restoreTarget, switchAttemptID: switchAttemptID) { macSwitchRestoreBaseline = nil @@ -3319,8 +3324,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { invalidatePairingAttempt() clearPairingError() let hadBlockingPrompt = pairingVersionWarning != nil || pendingPairingVersionWarningURL != nil || manualHostTrustWarning != nil + let pendingSwitchAttemptID = pendingManualHostTrust?.macSwitchAttemptID clearPairingVersionWarning() clearManualHostTrustWarning() + if let pendingSwitchAttemptID { finishMacSwitchAttempt(pendingSwitchAttemptID) } if hadBlockingPrompt { return } connectionState = .disconnected macConnectionStatus = .unavailable @@ -5543,7 +5550,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { && isSignedIn } - private func finishMacSwitchAttempt(_ attemptID: UUID) { + func finishMacSwitchAttempt(_ attemptID: UUID) { if macSwitchAttemptID == attemptID { macSwitchAttemptID = nil macSwitchAttemptSignInGeneration = nil diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift index 7a56b193f7b4..55f2ae555f95 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift @@ -8,22 +8,32 @@ enum PendingManualHostTrust { port: Int, pairedMacDeviceID: String?, recordsPairingAttempt: Bool, + macSwitchAttemptID: UUID?, ifStillCurrent: (() -> Bool)? ) case pairingURL(attemptID: UUID, rawURL: String, acceptedVersionWarning: Bool) var attemptID: UUID { switch self { - case let .manual(attemptID, _, _, _, _, _, _): + case let .manual(attemptID, _, _, _, _, _, _, _): attemptID case let .pairingURL(attemptID, _, _): attemptID } } + var macSwitchAttemptID: UUID? { + switch self { + case let .manual(_, _, _, _, _, _, macSwitchAttemptID, _): + macSwitchAttemptID + case .pairingURL: + nil + } + } + var ifStillCurrent: (() -> Bool)? { switch self { - case let .manual(_, _, _, _, _, _, ifStillCurrent): + case let .manual(_, _, _, _, _, _, _, ifStillCurrent): ifStillCurrent case .pairingURL: nil diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift index 3dde11b25af0..e3788a4ac3a5 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift @@ -7,7 +7,7 @@ import Testing @MainActor @Suite struct MobileShellManualHostReconnectTests { - @Test func successfulLaterReconnectCandidateClearsQueuedManualHostApproval() async throws { + @Test func activeManualHostReconnectWaitsForApprovalInsteadOfSwitchingMacs() async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } @@ -54,10 +54,65 @@ import Testing store.signIn() let connected = await store.reconnectActiveMacIfAvailable(stackUserID: "phone-user") - #expect(connected) + #expect(!connected) + #expect(store.connectionState == .disconnected) + #expect(store.connectedMacDeviceID == nil) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + } + + @Test func switchToManualHostMacResumesAfterApproval() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let manualRoute = try hostPortRoute(kind: .manualHost, host: "192.168.89.1") + try await pairedMacStore.upsert( + macDeviceID: "manual-mac", + displayName: "Manual Mac", + routes: [manualRoute], + markActive: false, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: box), + now: { clock.now }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + store.signIn() + await store.loadPairedMacs() + + let switched = await store.switchToMac(macDeviceID: "manual-mac") + + #expect(!switched) + #expect(store.isMacSwitchInFlight) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.89.1:58465") + #expect(await router.count(of: "mobile.attach_ticket.create") == 0) + #expect(await router.count(of: "workspace.list") == 0) + + let approved = await store.acceptManualHostTrustWarning() + + #expect(approved == .connected) + #expect(!store.isMacSwitchInFlight) #expect(store.connectionState == .connected) - #expect(store.connectedMacDeviceID == "trusted-mac") #expect(store.manualHostTrustWarning == nil) + #expect(await router.count(of: "mobile.attach_ticket.create") == 1) + #expect(await router.count(of: "workspace.list") >= 1) } private func hostPortRoute(kind: CmxAttachTransportKind, host: String) throws -> CmxAttachRoute { From f59fbd52cfd61ebcd0bfd9ae69ca1a1f5248ac8d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 11:53:31 -0700 Subject: [PATCH 44/91] Keep mobile shell composite under budget --- .../MobileShellComposite.swift | 37 +------------------ 1 file changed, 2 insertions(+), 35 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 4bab453b64a6..6a9817a72c32 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -2577,15 +2577,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { dropStalePreviousForeground(previousForegroundKey) connectionState = .connected markMacConnectionHealthy() - // Tear down the OLD foreground's terminal event listener before starting a - // fresh one. `cancelRemoteOperationTasks()` above does NOT clear - // `terminalEventListenerTask`/`terminalEventListenerID`, and - // `startTerminalRefreshPolling()` no-ops while a listener task is still - // installed — so without this the promoted client would never get its - // terminal/workspace/notification push stream and output would stall until - // some other path restarted it. The stop+start mirrors `restartEventStream`; - // the old listener's `== listenerID` defer guard keeps its async teardown - // from clobbering the new listener/watchdog. + // Restart the event stream for the promoted foreground client. stopTerminalRefreshPolling() startTerminalRefreshPolling() syncSelectedTerminalForWorkspace() @@ -2606,8 +2598,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let switchAttemptID = beginMacSwitchAttempt() var shouldFinishSwitchAttempt = true defer { if shouldFinishSwitchAttempt { finishMacSwitchAttempt(switchAttemptID) } } - // FAST PATH: if a live read-only connection to this Mac already exists, - // promote it to the foreground (reuse the client) instead of re-dialing. if await promoteSecondaryToForeground(macDeviceID, switchAttemptID: switchAttemptID) { macSwitchRestoreBaseline = nil return true @@ -2616,13 +2606,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { await restoreMacSwitchBaselineIfCancelled(switchAttemptID) return false } - // Refresh routes from the per-user backup so a Mac that relaunched on a - // new port is reachable — the same freshness guarantee auto-connect and - // aggregation use — then resolve the target from the STORE (authoritative). - // The multi-Mac aggregation reads Macs straight from the store and can - // surface a Mac (a freshly restored secondary) that the in-memory - // `pairedMacs` cache has not loaded yet; gating on that cache would no-op - // the open and strand the user on a workspace whose Mac never connected. + // Refresh routes and resolve the target from the store before dialing. if let refresher = pairedMacStore as? any PairedMacBackupRefreshing { await refresher.refreshFromBackup(stackUserID: identityProvider?.currentUserID) guard isCurrentMacSwitchAttempt(switchAttemptID) else { @@ -2651,21 +2635,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } return false } - // Already foreground on this exact Mac: skip the re-dial. Gate on the LIVE - // foreground identity, not the persisted `isActive` flag — `isActive` is - // stored preference state that can lag the real connection (e.g. - // `promoteSecondaryToForeground` writes it via an unawaited Task, and it is - // stale during reconnect/switch races). Trusting it could make `openWorkspace` - // proceed without switching and route input/mutations to the wrong Mac. if foregroundMacDeviceID == macDeviceID, connectionState == .connected, remoteClient != nil { macSwitchRestoreBaseline = nil return true } - // The LIVE foreground Mac to fall back to if the destructive switch fails. - // Persisted `isActive` can lag the connection, so use the foreground id - // captured before `connectManualHost` clears/replaces the live context. let previousForegroundMacDeviceID = foregroundMacDeviceID let previousForegroundMac = previousForegroundMacForSwitchRestore( previousForegroundMacDeviceID: previousForegroundMacDeviceID, @@ -2724,11 +2699,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { break } } - // The switch succeeded only if the live foreground identity is THIS Mac. - // `connect(..., pairedMacDeviceID:)` stamps the foreground state with the - // target id after a successful connection, while a superseding switch leaves - // a different foreground id. Trust that identity instead of exact host/port - // text equality, which can differ across normalized routes. let switched = connectionState == .connected && remoteClient != nil && foregroundMacDeviceID == macDeviceID @@ -2746,9 +2716,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { && remoteClient != nil && foregroundMacDeviceID == macDeviceID } else if macSwitchRestoreBaseline != nil || previousForegroundMac != nil, !hasActiveMacConnection { - // The switch did not connect and the destructive connect path dropped - // the previous session; reconnect to the still-active previous Mac so - // the user is not left stranded on a failed switch. let restoreTarget = macSwitchRestoreBaseline ?? previousForegroundMac if await restorePreviousMacIfNeeded(restoreTarget, switchAttemptID: switchAttemptID) { macSwitchRestoreBaseline = nil From 476aec4aeebe02e27891e7664aee9e2e1016ff58 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 12:16:22 -0700 Subject: [PATCH 45/91] Preserve trusted manual host route semantics --- ...ileShellComposite+ManualAttachTicket.swift | 3 +- ...MobileShellComposite+ManualHostTrust.swift | 5 +- ...MobileShellComposite+ReconnectRoutes.swift | 6 +- .../MobileShellComposite.swift | 131 ++++++++---------- .../MobileShellRouteSelection.swift | 30 +++- .../PendingManualHostTrust.swift | 24 +++- ...nualFallbackApprovalTransportFactory.swift | 16 +++ .../MobilePairingAttemptDeadlineTests.swift | 22 ++- .../MobileShellManualHostReconnectTests.swift | 44 ++++++ 9 files changed, 191 insertions(+), 90 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift index 3d3c5a96adcb..5e0eab838a21 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift @@ -44,10 +44,11 @@ extension MobileShellComposite { name: String, host: String, port: Int, + route: CmxAttachRoute? = nil, attemptStartedAt: Date?, manualHostTrusted: Bool = false ) async throws -> CmxAttachTicket { - let directRoute = try routeSelection.manualHostRoute(host: host, port: port) + let directRoute = try routeSelection.manualHostRoute(host: host, port: port, preserving: route) let displayName = name.isEmpty ? host : name if MobileShellRouteAuthPolicy().routeAllowsStackAuth( directRoute, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index f6df619a5f52..28c2286f6f0d 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -102,10 +102,11 @@ extension MobileShellComposite { ) finishPendingManualHostSwitchAttempt(pending) return result - case let .pairingURL(_, rawURL, acceptedVersionWarning): + case let .pairingURL(_, rawURL, acceptedVersionWarning, approvedRouteID): return await connectPairingURLResult( rawURL, - acceptedVersionWarning: acceptedVersionWarning + acceptedVersionWarning: acceptedVersionWarning, + approvedManualRouteID: approvedRouteID ) } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift index 8b3f2cba6b79..9307e09767b6 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift @@ -54,8 +54,8 @@ extension MobileShellComposite { func freshReconnectRoutesAfterLocalFailure( for mac: MobilePairedMac, scope: MobileShellScopeSnapshot, - triedRoutes: [(host: String, port: Int, routeID: String)] - ) async -> [(host: String, port: Int, routeID: String)]? { + triedRoutes: [MobileShellReconnectRouteCandidate] + ) async -> [MobileShellReconnectRouteCandidate]? { guard let deviceRegistry, await isScopeCurrent(scope), await !isForgottenMacDeviceID(mac.macDeviceID, scope: scope), @@ -165,7 +165,7 @@ extension MobileShellComposite { _ routes: [CmxAttachRoute], supportedKinds: [CmxAttachTransportKind], preferNonLoopback: Bool = false - ) -> [(host: String, port: Int, routeID: String)] { + ) -> [MobileShellReconnectRouteCandidate] { MobileShellRouteSelection().reconnectHostPortRoutes( routes, supportedKinds: supportedKinds, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 6a9817a72c32..e32aabf78c06 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1568,6 +1568,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { host: String, port: Int, pairedMacDeviceID: String, + route: CmxAttachRoute? = nil, ifStillCurrent: (() -> Bool)? = nil ) async -> MobilePairingURLConnectionResult { await connectManualHost( @@ -1576,6 +1577,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { port: port, pairedMacDeviceID: pairedMacDeviceID, recordsPairingAttempt: false, + route: route, ifStillCurrent: ifStillCurrent ) } @@ -1592,6 +1594,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { port: Int, pairedMacDeviceID: String? = nil, recordsPairingAttempt: Bool, + route: CmxAttachRoute? = nil, pendingMacSwitchAttemptID: UUID? = nil, ifStillCurrent: (() -> Bool)? = nil ) async -> MobilePairingURLConnectionResult { @@ -1622,7 +1625,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return .failed } - let directRoute = try? routeSelection.manualHostRoute(host: normalizedHost, port: port) + let directRoute = try? routeSelection.manualHostRoute(host: normalizedHost, port: port, preserving: route) let approvalAttemptID = beginPairingValidationAttempt() if let directRoute { let needsApproval = await manualHostRouteNeedsApproval(directRoute) @@ -1672,6 +1675,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { name: trimmedName, host: normalizedHost, port: port, + route: directRoute, attemptStartedAt: pairingAttemptStartedAt, manualHostTrusted: manualHostTrusted ) @@ -1756,7 +1760,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } guard await isScopeCurrent(scope) else { finishStoredMacReconnectAttempt(generation: generation); return false } let supportedKinds = runtime?.supportedRouteKinds ?? [] - func reachableRoutes(_ mac: MobilePairedMac) -> [(host: String, port: Int, routeID: String)] { + func reachableRoutes(_ mac: MobilePairedMac) -> [MobileShellReconnectRouteCandidate] { routeSelection.reconnectHostPortRoutes( mac.routes, supportedKinds: supportedKinds, @@ -1851,7 +1855,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { name: mac.displayName ?? route.host, host: route.host, port: route.port, - pairedMacDeviceID: mac.macDeviceID) + pairedMacDeviceID: mac.macDeviceID, + route: route.route + ) if result == .superseded || result == .needsUserApproval { shouldStopRouteIteration = true break @@ -1873,7 +1879,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { name: mac.displayName ?? route.host, host: route.host, port: route.port, - pairedMacDeviceID: mac.macDeviceID) + pairedMacDeviceID: mac.macDeviceID, + route: route.route + ) if result == .superseded || result == .needsUserApproval { shouldStopRouteIteration = true break @@ -2403,14 +2411,16 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // switch failure. let previousActive = pairedMacs.first { $0.isActive } let scope = await currentScopeSnapshot() - var connectedRoute: (host: String, port: Int, routeID: String)? + var connectedRoute: MobileShellReconnectRouteCandidate? for route in candidateRoutes { let result = await connectManualHost( name: device.displayName ?? route.host, host: route.host, port: route.port, pairedMacDeviceID: device.deviceId, - recordsPairingAttempt: true) + recordsPairingAttempt: true, + route: route.route + ) if result == .needsUserApproval || result == .superseded { return } @@ -2677,6 +2687,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { port: route.port, pairedMacDeviceID: macDeviceID, recordsPairingAttempt: true, + route: route.route, pendingMacSwitchAttemptID: switchAttemptID, ifStillCurrent: { [weak self] in self?.isCurrentMacSwitchAttempt(switchAttemptID) == true @@ -2767,6 +2778,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { host: route.host, port: route.port, pairedMacDeviceID: previousActive.macDeviceID, + route: route.route, ifStillCurrent: isRestoreCurrent ) let restoreScopeIsCurrent = await isScopeCurrent(restoreScope) @@ -3123,7 +3135,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { @discardableResult func connectPairingURLResult( _ rawValue: String? = nil, - acceptedVersionWarning: Bool + acceptedVersionWarning: Bool, + approvedManualRouteID: String? = nil ) async -> MobilePairingURLConnectionResult { let rawURL = Self.normalizedPairingURL(rawValue ?? pairingCode) let validationAttemptID = beginPairingValidationAttempt() @@ -3140,14 +3153,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let ticket: CmxAttachTicket do { ticket = try CmxAttachTicketInput.decode(rawURL) - // The v2 grammar rejects loopback inside the decoder; the legacy - // grammars must keep decoding loopback for the simulator dev flow - // (where 127.0.0.1 IS the host Mac). On a physical phone no - // grammar may pair to loopback: the route would dial the phone - // itself, and loopback is Stack-auth-trusted, so the bearer token - // would be handed to whatever local process answers. Pure policy, - // unit tested for both device values; only this wiring is - // compile-time. if MobileShellRouteAuthPolicy().ticketRejectsLoopbackRoutes( ticket.routes, isPhysicalDevice: routeSelection.isPhysicalDevice @@ -3156,15 +3161,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } catch { if case MobileSyncPairingPayloadError.loopbackRouteRejected = error { - // A scanned/pasted code that only points back at the Mac - // itself (127.0.0.1) would make the phone dial itself. Name - // the actual fix (Tailscale on the Mac) instead of the - // generic invalid-code copy. applyPairingValidationFailure(.loopbackRejected) } else if case MobileSyncPairingPayloadError.unrecognizedURLVersion = error { - // A real cmux QR whose grammar version this build predates: the - // fix is updating the app, not re-scanning, so say so instead of - // the generic "not a valid code" copy. applyPairingValidationFailure(.unrecognizedVersion) } else { applyPairingValidationFailure(.invalidCode) @@ -3201,7 +3199,21 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } let candidateRoutes = routeSelection.supportedRoutes(for: ticket, supportedKinds: runtime?.supportedRouteKinds ?? []) - let manualHostApproval = await firstManualHostRouteNeedingApproval(in: candidateRoutes) + let routesForAttempt: [CmxAttachRoute] + if let approvedManualRouteID, + let approvedIndex = candidateRoutes.firstIndex(where: { $0.id == approvedManualRouteID }) { + routesForAttempt = Array(candidateRoutes[approvedIndex...]) + } else { + routesForAttempt = candidateRoutes + } + let ticketForAttempt = (routesForAttempt == candidateRoutes) + ? ticket + : try? ticket.constrainingRoutes(to: routesForAttempt, fallbackDisplayName: ticket.macDisplayName ?? "") + guard let ticketForAttempt else { + applyPairingValidationFailure(.invalidCode) + return .failed + } + let manualHostApproval = await firstManualHostRouteNeedingApproval(in: routesForAttempt) guard isCurrentPairingAttempt(validationAttemptID) else { return .superseded } if let approval = manualHostApproval, case let .hostPort(host, _) = approval.route.endpoint { @@ -3211,7 +3223,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { pending: .pairingURL( attemptID: validationAttemptID, rawURL: rawURL, - acceptedVersionWarning: acceptedVersionWarning + acceptedVersionWarning: acceptedVersionWarning, + approvedRouteID: approval.route.id ) ) return .needsUserApproval @@ -3219,18 +3232,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let attemptID = beginPairingAttempt(method: "qr") - // Offline preflight: fail fast instead of stacking per-route connect - // timeouts into the opaque ~60s wait. Skipped only when no route is - // dialable so `connect()` classifies that as `no_supported_route`. - // Ticket expiry deliberately does NOT gate this: a stale QR is a valid - // pairing input now (expiry is enforced solely where the RPC attach - // token is used), so an expired legacy code scanned offline must say - // "offline", not crawl the route loop's stacked timeouts. - if !candidateRoutes.isEmpty { + if !routesForAttempt.isEmpty { switch await failPairingIfOffline( attemptID: attemptID, phase: "preflight", - routes: candidateRoutes, + routes: routesForAttempt, preservesActiveConnection: preservesActiveConnection ) { case .failedOffline: return .failed @@ -3242,11 +3248,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { do { guard isCurrentPairingAttempt(attemptID) else { return .superseded } let noThrowFailure = try await connect( - ticket: ticket, + ticket: ticketForAttempt, pendingManualHostTrust: .pairingURL( attemptID: attemptID, rawURL: rawURL, - acceptedVersionWarning: acceptedVersionWarning + acceptedVersionWarning: acceptedVersionWarning, + approvedRouteID: approvedManualRouteID ) ) guard isCurrentPairingAttempt(attemptID) else { return .superseded } @@ -3415,21 +3422,28 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func makeSecondaryClient(for mac: MobilePairedMac) async -> SecondaryClientHandle? { guard let runtime else { return nil } let supportedKinds = runtime.supportedRouteKinds - guard let (host, port) = routeSelection.firstReconnectHostPortRoute( + guard let candidate = routeSelection.reconnectHostPortRoutes( mac.routes, supportedKinds: supportedKinds, preferNonLoopback: routeSelection.prefersNonLoopbackRoutes - ) else { + ).first else { return nil } + let host = candidate.host + let port = candidate.port let ticket: CmxAttachTicket do { - let directRoute = try routeSelection.manualHostRoute(host: host, port: port) + let directRoute = try routeSelection.manualHostRoute( + host: host, + port: port, + preserving: candidate.route + ) let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) ticket = try await manualHostTicket( name: mac.displayName ?? host, host: host, port: port, + route: directRoute, attemptStartedAt: nil, manualHostTrusted: manualHostTrusted ) @@ -4984,17 +4998,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let supportedKinds = runtime?.supportedRouteKinds ?? [] let supportedRoutes = routeSelection.supportedRoutes(for: ticket, supportedKinds: supportedKinds) guard let firstRoute = supportedRoutes.first else { - // No route kind this build can dial: set the specific category; - // the caller records the matching analytics reason from it. connectionError = MobilePairingFailureCategory.noSupportedRoute.message connectionErrorGuidance = MobilePairingFailureCategory.noSupportedRoute.guidance clearFailedPairingConnection(preservingActiveConnection: preservesActiveConnection) return .noSupportedRoute } - // No connect-time expiry gate: a pairing QR never expires (new QRs - // carry no expiry at all), and the host authorizes by Stack account, - // not ticket age. Expiry still gates the RPC-minted attach token at - // its point of use (`MobileCoreRPCClient.requestDataWithAuth`). if !preservesActiveConnection { activeTicket = ticket activeRoute = firstRoute @@ -5013,9 +5021,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } let workspaceListRequests = try Self.initialWorkspaceListRequests(for: ticket) - // Stack auth is now the authorization gate for every request. Decide the - // fallback per attempted route so an untrusted fallback route cannot - // disable auth for a trusted Tailscale/loopback/iroh route. let routeAllowsStackAuthFallbackOverride = allowsStackAuthFallback let connectionAttemptStartedAt = pairingAttemptStartedAt var lastError: (any Error)? @@ -5032,7 +5037,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { queueManualHostTrustWarning( route: route, displayHost: host, - pending: pendingManualHostTrust + pending: pendingManualHostTrust.approving(route: route) ) throw ManualHostTrustApprovalQueued.required } @@ -5078,6 +5083,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { if preservesActiveConnection { connectionGeneration = generation cancelRemoteOperationTasks() + stopTerminalRefreshPolling() rawTerminalInputBuffer.clear() resetTerminalOutputTracking() } @@ -5086,27 +5092,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { connectedHostName = placeholderHostName(for: ticket, firstRoute: route) replaceRemoteClient(with: client) startTerminalRefreshPolling() - // The connect seam guarantees identity recovery for an - // anonymous (v2 QR) ticket on every supported runtime, not - // just push-event ones: when the event-listener task starts, - // its status probe performs the recovery (one shared status - // request); when the runtime has no server-push events that - // task never runs, so recovery is scheduled directly here. - // Without this, pairing succeeded but the Mac was never - // persisted (no reconnect-on-launch, no host switcher entry). - // The schedule is a no-op for tickets that carry a device id. if !(runtime.supportsServerPushEvents) { scheduleHostIdentityAdoptionIfNeeded(client: client) } clearPairingError() - // Set the foreground Mac id BEFORE applying the list so the - // per-Mac state is keyed to THIS Mac, not the previously- - // foreground Mac (or the anonymous key). Otherwise switching - // from Mac A to Mac B writes B's workspaces under A's key, and - // once the id flips the derived list reads a stale/empty B - // snapshot. Anonymous (empty-id) tickets keep the anonymous key. A - // manual fallback ticket carries a synthetic `manual-…` id, so - // prefer the caller's real paired-Mac id when it is known. let resolvedForegroundMacID = ticket.foregroundMacID(hint: pairedMacDeviceID) let previousForegroundKey = foregroundMacKey if !resolvedForegroundMacID.isEmpty { @@ -5115,22 +5104,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { applyRemoteWorkspaceList( response, preferActiveTicketTarget: workspaceListRequest.preferActiveTicketTarget, - // Scoped requests omit groups; only a non-scoped (full) list - // is authoritative for the device-local collapse store. groupsAreAuthoritative: !workspaceListRequest.isScoped ) - // Drop the now-stale previous-foreground/anonymous snapshot so it - // doesn't linger in the aggregate (it's re-added as a secondary - // below if still reachable). dropStalePreviousForeground(previousForegroundKey) syncSelectedTerminalForWorkspace() connectionState = .connected markMacConnectionHealthy() - // Record this as the foreground entry in the per-Mac - // connection pool (P2). Anonymous (empty-id) tickets are not - // pooled, since a per-Mac key is required to aggregate. Keyed by - // the resolved real id (not the synthetic manual ticket id) so the - // pool entry matches the foreground/aggregation key. if !resolvedForegroundMacID.isEmpty { connections[resolvedForegroundMacID] = MacConnection( macDeviceID: resolvedForegroundMacID, @@ -5140,8 +5119,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { generation: generation ) } - // Aggregate the user's other Macs' workspaces in the background. - // Best-effort; never blocks the foreground connect. if multiMacAggregationEnabled { self.scheduleSecondaryAggregation() } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift index 44a1d06c64eb..58ce5bb39a42 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift @@ -3,6 +3,13 @@ import CmuxMobileShellModel import Darwin import Foundation +struct MobileShellReconnectRouteCandidate: Equatable, Sendable { + let route: CmxAttachRoute + let host: String + let port: Int + var routeID: String { route.id } +} + struct MobileShellRouteSelection: Sendable { let routeAuthPolicy: MobileShellRouteAuthPolicy @@ -59,14 +66,14 @@ struct MobileShellRouteSelection: Sendable { _ routes: [CmxAttachRoute], supportedKinds: [CmxAttachTransportKind], preferNonLoopback: Bool = false - ) -> [(host: String, port: Int, routeID: String)] { + ) -> [MobileShellReconnectRouteCandidate] { let supportedKinds = Set(supportedKinds) let ordered = routes.sorted(by: routeSortsBefore) var seenEndpoints = Set() func appendCandidates( where predicate: (CmxAttachRoute) -> Bool, - to candidates: inout [(host: String, port: Int, routeID: String)] + to candidates: inout [MobileShellReconnectRouteCandidate] ) { for route in ordered { if !supportedKinds.isEmpty, !supportedKinds.contains(route.kind) { @@ -77,11 +84,11 @@ struct MobileShellRouteSelection: Sendable { } let endpointKey = "\(host)\u{1F}\(port)" guard seenEndpoints.insert(endpointKey).inserted else { continue } - candidates.append((host: host, port: port, routeID: route.id)) + candidates.append(MobileShellReconnectRouteCandidate(route: route, host: host, port: port)) } } - var candidates: [(host: String, port: Int, routeID: String)] = [] + var candidates: [MobileShellReconnectRouteCandidate] = [] if preferNonLoopback { // Prefer a Tailscale numeric IP over MagicDNS because it dials // without client DNS. Keep encrypted Tailscale routes ahead of @@ -147,6 +154,21 @@ struct MobileShellRouteSelection: Sendable { ) } + func manualHostRoute( + host: String, + port: Int, + preserving sourceRoute: CmxAttachRoute?, + isPhysicalDevice: Bool? = nil + ) throws -> CmxAttachRoute { + if let sourceRoute, + case let .hostPort(sourceHost, sourcePort) = sourceRoute.endpoint, + sourcePort == port, + routeAuthPolicy.normalizedManualRouteHost(sourceHost) == routeAuthPolicy.normalizedManualRouteHost(host) { + return sourceRoute + } + return try manualHostRoute(host: host, port: port, isPhysicalDevice: isPhysicalDevice) + } + func supportedRoutes( for ticket: CmxAttachTicket, supportedKinds: [CmxAttachTransportKind] diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift index 55f2ae555f95..16be1ca8b799 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift @@ -1,3 +1,4 @@ +import CMUXMobileCore import Foundation enum PendingManualHostTrust { @@ -11,13 +12,18 @@ enum PendingManualHostTrust { macSwitchAttemptID: UUID?, ifStillCurrent: (() -> Bool)? ) - case pairingURL(attemptID: UUID, rawURL: String, acceptedVersionWarning: Bool) + case pairingURL( + attemptID: UUID, + rawURL: String, + acceptedVersionWarning: Bool, + approvedRouteID: String? + ) var attemptID: UUID { switch self { case let .manual(attemptID, _, _, _, _, _, _, _): attemptID - case let .pairingURL(attemptID, _, _): + case let .pairingURL(attemptID, _, _, _): attemptID } } @@ -39,4 +45,18 @@ enum PendingManualHostTrust { nil } } + + func approving(route: CmxAttachRoute) -> PendingManualHostTrust { + switch self { + case .manual: + self + case let .pairingURL(attemptID, rawURL, acceptedVersionWarning, _): + .pairingURL( + attemptID: attemptID, + rawURL: rawURL, + acceptedVersionWarning: acceptedVersionWarning, + approvedRouteID: route.id + ) + } + } } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift index 77a2e1c7bb01..beb146e3ae25 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift @@ -1,10 +1,26 @@ import CMUXMobileCore +import Foundation + +final class RouteAttemptRecorder: @unchecked Sendable { + private let lock = NSLock() + private var counts: [CmxAttachTransportKind: Int] = [:] + + func record(_ kind: CmxAttachTransportKind) { + lock.withLock { counts[kind, default: 0] += 1 } + } + + func count(_ kind: CmxAttachTransportKind) -> Int { + lock.withLock { counts[kind, default: 0] } + } +} struct ManualFallbackApprovalTransportFactory: CmxByteTransportFactory { let router: LivenessHostRouter let box: TransportBox + var attempts: RouteAttemptRecorder? func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + attempts?.record(route.kind) if route.kind == .tailscale { return SlowIgnoringCancellationTransport() } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 1462c7356df5..a860ee5b87ae 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -90,8 +90,9 @@ import Testing let clock = TestClock() let router = LivenessHostRouter() let box = TransportBox() + let attempts = RouteAttemptRecorder() let runtime = LivenessTestRuntime( - transportFactory: ManualFallbackApprovalTransportFactory(router: router, box: box), + transportFactory: ManualFallbackApprovalTransportFactory(router: router, box: box, attempts: attempts), now: { clock.now }, supportedRouteKinds: [.tailscale, .manualHost] ) @@ -124,6 +125,8 @@ import Testing #expect(store.connectionState != .connected) #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") #expect(await router.count(of: "workspace.list") == 0) + #expect(attempts.count(.tailscale) == 1) + #expect(attempts.count(.manualHost) == 0) let approvedResult = await store.acceptManualHostTrustWarning() @@ -131,6 +134,8 @@ import Testing #expect(store.connectionState == .connected) #expect(store.manualHostTrustWarning == nil) #expect(store.selectedWorkspace?.id.rawValue == "live-workspace") + #expect(attempts.count(.tailscale) == 1) + #expect(attempts.count(.manualHost) == 1) #expect(await router.count(of: "workspace.list") >= 1) } @@ -390,6 +395,21 @@ import Testing #expect(store.connectionError?.isEmpty == false) } + @Test func successfulPairingWhileConnectedStartsReplacementEventStream() async throws { + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let store = try await makeConnectedStore(router: router, box: box, clock: clock) + await router.waitForCount(of: "mobile.events.subscribe", atLeast: 1) + let initialSubscribeCount = await router.count(of: "mobile.events.subscribe") + let ticket = try makeTicket(clock: clock) + + let result = await store.connectPairingURLResult(try attachURL(for: ticket)) + + #expect(result == .connected) + await router.waitForCount(of: "mobile.events.subscribe", atLeast: initialSubscribeCount + 1) + } + private static let qrURL = "cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465" private func manualHostTicket(host: String) throws -> CmxAttachTicket { diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift index e3788a4ac3a5..2f37de0611ed 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift @@ -115,6 +115,50 @@ import Testing #expect(await router.count(of: "workspace.list") >= 1) } + @Test func tailscaleLookingStoredManualHostStillRequiresApprovalBeforeReconnect() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let manualRoute = try hostPortRoute(kind: .manualHost, host: "100.64.0.5") + try await pairedMacStore.upsert( + macDeviceID: "manual-mac", + displayName: "Manual Mac", + routes: [manualRoute], + markActive: true, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: box), + now: { clock.now }, + supportedRouteKinds: [.manualHost, .tailscale], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + + store.signIn() + let connected = await store.reconnectActiveMacIfAvailable(stackUserID: "phone-user") + + #expect(!connected) + #expect(store.manualHostTrustWarning?.endpoint == "100.64.0.5:58465") + #expect(await router.count(of: "mobile.attach_ticket.create") == 0) + #expect(await router.count(of: "workspace.list") == 0) + } + private func hostPortRoute(kind: CmxAttachTransportKind, host: String) throws -> CmxAttachRoute { try CmxAttachRoute( id: kind.rawValue, From dc0150560da1932b5fd07c9c2b7e92b08c2b5377 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 12:54:16 -0700 Subject: [PATCH 46/91] Preserve manual host approval route context --- ...MobileShellComposite+ManualHostTrust.swift | 3 +- .../MobileShellComposite.swift | 3 +- .../PendingManualHostTrust.swift | 7 +-- .../MobilePairingAttemptDeadlineTests.swift | 50 ++++++++++++++++++ .../MobileShellManualHostReconnectTests.swift | 52 +++++++++++++++++++ 5 files changed, 110 insertions(+), 5 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 28c2286f6f0d..5bf1493d84b3 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -91,13 +91,14 @@ extension MobileShellComposite { return .superseded } switch pending { - case let .manual(_, name, host, port, pairedMacDeviceID, recordsPairingAttempt, _, ifStillCurrent): + case let .manual(_, name, host, port, route, pairedMacDeviceID, recordsPairingAttempt, _, ifStillCurrent): let result = await connectManualHost( name: name, host: host, port: port, pairedMacDeviceID: pairedMacDeviceID, recordsPairingAttempt: recordsPairingAttempt, + route: route, ifStillCurrent: ifStillCurrent ) finishPendingManualHostSwitchAttempt(pending) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index e32aabf78c06..b17164ed3c16 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1639,6 +1639,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { name: name, host: normalizedHost, port: port, + route: directRoute, pairedMacDeviceID: pairedMacDeviceID, recordsPairingAttempt: recordsPairingAttempt, macSwitchAttemptID: pendingMacSwitchAttemptID, @@ -3302,7 +3303,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { clearPairingVersionWarning() clearManualHostTrustWarning() if let pendingSwitchAttemptID { finishMacSwitchAttempt(pendingSwitchAttemptID) } - if hadBlockingPrompt { return } + if hadBlockingPrompt, hasActiveMacConnection { return } connectionState = .disconnected macConnectionStatus = .unavailable clearRemoteConnectionContext() diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift index 16be1ca8b799..4e203fa5ef00 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift @@ -7,6 +7,7 @@ enum PendingManualHostTrust { name: String, host: String, port: Int, + route: CmxAttachRoute, pairedMacDeviceID: String?, recordsPairingAttempt: Bool, macSwitchAttemptID: UUID?, @@ -21,7 +22,7 @@ enum PendingManualHostTrust { var attemptID: UUID { switch self { - case let .manual(attemptID, _, _, _, _, _, _, _): + case let .manual(attemptID, _, _, _, _, _, _, _, _): attemptID case let .pairingURL(attemptID, _, _, _): attemptID @@ -30,7 +31,7 @@ enum PendingManualHostTrust { var macSwitchAttemptID: UUID? { switch self { - case let .manual(_, _, _, _, _, _, macSwitchAttemptID, _): + case let .manual(_, _, _, _, _, _, _, macSwitchAttemptID, _): macSwitchAttemptID case .pairingURL: nil @@ -39,7 +40,7 @@ enum PendingManualHostTrust { var ifStillCurrent: (() -> Bool)? { switch self { - case let .manual(_, _, _, _, _, _, _, ifStillCurrent): + case let .manual(_, _, _, _, _, _, _, _, ifStillCurrent): ifStillCurrent case .pairingURL: nil diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index a860ee5b87ae..10e242fbf8c6 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -190,6 +190,56 @@ import Testing #expect(store.manualHostTrustWarning == nil) } + @Test func manualFallbackCancelClearsDisconnectedStagedContext() async throws { + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: ManualFallbackApprovalTransportFactory(router: router, box: box), + now: { clock.now }, + supportedRouteKinds: [.tailscale, .manualHost] + ) + let store = makeStore(runtime: runtime) + let trustedRoute = try CmxAttachRoute( + id: "a-trusted-tailscale", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.5", port: 58_465), + priority: 0 + ) + let manualFallbackRoute = try CmxAttachRoute( + id: "b-manual-fallback", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465), + priority: 1 + ) + let ticket = try CmxAttachTicket( + workspaceID: "live-workspace", + terminalID: "live-terminal", + macDeviceID: "test-mac", + macDisplayName: "Test Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [trustedRoute, manualFallbackRoute], + expiresAt: clock.now.addingTimeInterval(3600), + authToken: "ticket-secret" + ) + + let result = await store.connectPairingURLResult(try attachURL(for: ticket)) + + #expect(result == .needsUserApproval) + #expect(store.connectionState == .disconnected) + #expect(store.activeTicket != nil) + #expect(store.activeRoute?.kind == .manualHost) + #expect(store.hasActiveUnexpiredAttachTicket) + + store.cancelPairing() + + #expect(store.connectionState == .disconnected) + #expect(store.manualHostTrustWarning == nil) + #expect(store.activeTicket == nil) + #expect(store.activeRoute == nil) + #expect(!store.hasActiveUnexpiredAttachTicket) + } + @Test func failedManualHostAttemptKeepsExistingConnection() async throws { let clock = TestClock() let oldRouter = LivenessHostRouter() diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift index 2f37de0611ed..9cdc131d4772 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift @@ -159,6 +159,58 @@ import Testing #expect(await router.count(of: "workspace.list") == 0) } + @Test func approvedTailscaleLookingStoredManualHostKeepsManualRouteKind() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let manualRoute = try hostPortRoute(kind: .manualHost, host: "100.64.0.5") + try await pairedMacStore.upsert( + macDeviceID: "manual-mac", + displayName: "Manual Mac", + routes: [manualRoute], + markActive: true, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let attempts = RouteAttemptRecorder() + let runtime = LivenessTestRuntime( + transportFactory: ManualFallbackApprovalTransportFactory(router: router, box: box, attempts: attempts), + now: { clock.now }, + supportedRouteKinds: [.manualHost, .tailscale], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + + store.signIn() + let queued = await store.reconnectActiveMacIfAvailable(stackUserID: "phone-user") + + #expect(!queued) + #expect(store.manualHostTrustWarning?.endpoint == "100.64.0.5:58465") + #expect(attempts.count(.manualHost) == 0) + #expect(attempts.count(.tailscale) == 0) + + let approved = await store.acceptManualHostTrustWarning() + + #expect(approved == .connected) + #expect(store.activeRoute?.kind == .manualHost) + #expect(attempts.count(.manualHost) >= 1) + #expect(attempts.count(.tailscale) == 0) + } + private func hostPortRoute(kind: CmxAttachTransportKind, host: String) throws -> CmxAttachRoute { try CmxAttachRoute( id: kind.rawValue, From fe517331cc7ace1dae40e81dc96d9460213c495c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 13:16:13 -0700 Subject: [PATCH 47/91] Harden manual host approval lifecycle --- ...MobileShellComposite+ManualHostTrust.swift | 13 ++++++ .../MobileShellComposite.swift | 20 +++++---- .../MobileShellRouteSelection.swift | 14 +++--- .../MobileShellManualHostReconnectTests.swift | 43 +++++++++++++++++++ .../ReconnectRouteSelectionTests.swift | 11 +++++ ...erDefaultsMobileManualHostTrustStore.swift | 41 ++++++++++++++---- .../MobileShellRouteAuthPolicyTests.swift | 13 +++++- .../Sections/MobileSection.swift | 42 +++++++++++++++--- 8 files changed, 167 insertions(+), 30 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 5bf1493d84b3..0fb90e6a34d7 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -8,6 +8,14 @@ extension MobileShellComposite { pendingManualHostTrust = nil } + func clearSupersededManualHostTrustWarning() { + let pending = pendingManualHostTrust + clearManualHostTrustWarning() + if let pending { + finishPendingManualHostSwitchAttempt(pending) + } + } + func manualHostTrustScope(for route: CmxAttachRoute?) -> MobileManualHostTrustScope? { guard let route, MobileShellRouteAuthPolicy().routeRequiresManualHostTrust(route) else { @@ -63,6 +71,10 @@ extension MobileShellComposite { } clearPairingError() clearPairingVersionWarning() + if let currentPending = pendingManualHostTrust, + currentPending.attemptID != pending.attemptID { + finishPendingManualHostSwitchAttempt(currentPending) + } pendingManualHostTrust = pending manualHostTrustWarning = MobileManualHostTrustWarning( scope: scope, @@ -99,6 +111,7 @@ extension MobileShellComposite { pairedMacDeviceID: pairedMacDeviceID, recordsPairingAttempt: recordsPairingAttempt, route: route, + approvedManualRouteID: route.id, ifStillCurrent: ifStillCurrent ) finishPendingManualHostSwitchAttempt(pending) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index b17164ed3c16..2c96101ee108 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1094,7 +1094,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { connectedHostName = "" pairingCode = "" clearPairingVersionWarning() - clearManualHostTrustWarning() + clearSupersededManualHostTrustWarning() // Wipe every saved draft so the next account never sees the previous // user's unsent text. Guard the in-memory clear (and the selection resets // below) so the per-terminal draft hooks do not write partial state into a @@ -1214,7 +1214,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// lists" behavior). public func currentTeamDidChange() { secondaryAggregationScopeGeneration &+= 1 - clearManualHostTrustWarning() + clearSupersededManualHostTrustWarning() // Presence: cancel + re-subscribe so the online dots reflect the new team // (the subscribe reads the team live). Cheap live socket; the only eager bit. presenceTask?.cancel() @@ -1464,6 +1464,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // connection so a moving network repaints instead of going stale. for await _ in reachability.pathChanges() { guard let self, !Task.isCancelled else { return } + await self.manualHostTrustStore.removeAll() self.recoverMobileConnection(trigger: .networkChange) } } @@ -1595,6 +1596,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { pairedMacDeviceID: String? = nil, recordsPairingAttempt: Bool, route: CmxAttachRoute? = nil, + approvedManualRouteID: String? = nil, pendingMacSwitchAttemptID: UUID? = nil, ifStillCurrent: (() -> Bool)? = nil ) async -> MobilePairingURLConnectionResult { @@ -1626,11 +1628,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } let directRoute = try? routeSelection.manualHostRoute(host: normalizedHost, port: port, preserving: route) + let directRouteIsApproved = approvedManualRouteID != nil && directRoute?.id == approvedManualRouteID let approvalAttemptID = beginPairingValidationAttempt() if let directRoute { let needsApproval = await manualHostRouteNeedsApproval(directRoute) guard isCurrentPairingAttempt(approvalAttemptID) else { return .superseded } - if needsApproval { + if needsApproval && !directRouteIsApproved { queueManualHostTrustWarning( route: directRoute, displayHost: normalizedHost, @@ -1670,7 +1673,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } do { guard ifStillCurrent?() != false else { return .superseded } - let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) + let manualHostTrusted = directRouteIsApproved + ? true + : await manualHostStackAuthTrusted(for: directRoute) guard isCurrentPairingAttempt(attemptID), ifStillCurrent?() != false else { return .superseded } let ticket = try await manualHostTicket( name: trimmedName, @@ -1734,6 +1739,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { public func reconnectActiveMacIfAvailable(stackUserID: String?) async -> Bool { lastReconnectStackUserID = stackUserID startObservingNetworkPathChanges() + await manualHostTrustStore.removeAll() // Claim this attempt's generation. Only the current generation may resolve // the restoring-gate flags, so an older superseded attempt can't clear the // gate (or clobber the hint) while a newer reconnect is still running. @@ -3150,7 +3156,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } clearPairingError() clearPairingVersionWarning() - clearManualHostTrustWarning() + clearSupersededManualHostTrustWarning() let ticket: CmxAttachTicket do { ticket = try CmxAttachTicketInput.decode(rawURL) @@ -3299,10 +3305,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { invalidatePairingAttempt() clearPairingError() let hadBlockingPrompt = pairingVersionWarning != nil || pendingPairingVersionWarningURL != nil || manualHostTrustWarning != nil - let pendingSwitchAttemptID = pendingManualHostTrust?.macSwitchAttemptID clearPairingVersionWarning() - clearManualHostTrustWarning() - if let pendingSwitchAttemptID { finishMacSwitchAttempt(pendingSwitchAttemptID) } + clearSupersededManualHostTrustWarning() if hadBlockingPrompt, hasActiveMacConnection { return } connectionState = .disconnected macConnectionStatus = .unavailable diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift index 58ce5bb39a42..eae49abfa217 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift @@ -160,13 +160,17 @@ struct MobileShellRouteSelection: Sendable { preserving sourceRoute: CmxAttachRoute?, isPhysicalDevice: Bool? = nil ) throws -> CmxAttachRoute { - if let sourceRoute, - case let .hostPort(sourceHost, sourcePort) = sourceRoute.endpoint, - sourcePort == port, - routeAuthPolicy.normalizedManualRouteHost(sourceHost) == routeAuthPolicy.normalizedManualRouteHost(host) { + let inferredRoute = try manualHostRoute(host: host, port: port, isPhysicalDevice: isPhysicalDevice) + guard let sourceRoute, + case let .hostPort(sourceHost, sourcePort) = sourceRoute.endpoint, + sourcePort == port, + routeAuthPolicy.normalizedManualRouteHost(sourceHost) == routeAuthPolicy.normalizedManualRouteHost(host) else { + return inferredRoute + } + if sourceRoute.kind == .manualHost || sourceRoute.kind == inferredRoute.kind { return sourceRoute } - return try manualHostRoute(host: host, port: port, isPhysicalDevice: isPhysicalDevice) + return inferredRoute } func supportedRoutes( diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift index 9cdc131d4772..4ab7b9755d89 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift @@ -115,6 +115,49 @@ import Testing #expect(await router.count(of: "workspace.list") >= 1) } + @Test func newPairingURLSupersedesPendingManualHostSwitchApproval() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let manualRoute = try hostPortRoute(kind: .manualHost, host: "192.168.89.1") + try await pairedMacStore.upsert( + macDeviceID: "manual-mac", + displayName: "Manual Mac", + routes: [manualRoute], + markActive: false, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: LivenessHostRouter(), box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + store.signIn() + await store.loadPairedMacs() + + let switched = await store.switchToMac(macDeviceID: "manual-mac") + let supersedingResult = await store.connectPairingURLResult("not a cmux pairing url") + + #expect(!switched) + #expect(supersedingResult == .failed) + #expect(store.manualHostTrustWarning == nil) + #expect(!store.isMacSwitchInFlight) + } + @Test func tailscaleLookingStoredManualHostStillRequiresApprovalBeforeReconnect() async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index 077a64afa3f4..fdf74a10f097 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -88,6 +88,17 @@ import Testing #expect(!MobileShellRouteAuthPolicy().routeAllowsStackAuth(route)) } + @Test func legacyLANRouteStoredAsTailscaleBecomesManualHost() throws { + let route = try MobileShellRouteSelection().manualHostRoute( + host: "192.168.1.77", + port: 50906, + preserving: legacyLANStoredAsTailscale() + ) + + #expect(route.kind == .manualHost) + #expect(route.endpoint == .hostPort(host: "192.168.1.77", port: 50906)) + } + @Test func reconnectCandidatesKeepFallbackRoutesAfterPreferredRoute() throws { let candidates = MobileShellComposite.reconnectHostPortRoutes( [try loopback(), try tailscale()], diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift index b203ba22d810..878314c733a8 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -5,41 +5,47 @@ nonisolated private let manualHostTrustStoreLog = Logger(subsystem: "com.cmuxter /// UserDefaults-backed manual-host trust store for production. public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStoring { - /// Default lifetime for a manual-host approval. - public static let defaultTrustDuration: TimeInterval = 30 * 24 * 60 * 60 + /// Default lifetime for a same-app-session manual-host approval. + public static let defaultTrustDuration: TimeInterval = 10 * 60 private let defaults: UserDefaults private let key: String + private let sessionIdentifier: String private let trustDuration: TimeInterval private let now: @Sendable () -> Date - /// Creates a durable manual-host trust store. + /// Creates a same-session manual-host trust store. /// - Parameters: /// - defaults: The backing defaults store. /// - key: The defaults key that stores approved scopes and their expiry times. - /// - trustDuration: How long a host approval remains valid. + /// - sessionIdentifier: The app-session boundary for approvals. + /// - trustDuration: How long a host approval remains valid within this session. /// - now: Clock source used to evaluate expiry. public init( defaults: UserDefaults = .standard, key: String = "cmux.mobile.manualHostTrust.v2", + sessionIdentifier: String = UUID().uuidString, trustDuration: TimeInterval = UserDefaultsMobileManualHostTrustStore.defaultTrustDuration, now: @escaping @Sendable () -> Date = { Date() } ) { self.defaults = defaults self.key = key + self.sessionIdentifier = sessionIdentifier self.trustDuration = trustDuration self.now = now } - /// Creates a durable manual-host trust store in a named defaults suite. + /// Creates a same-session manual-host trust store in a named defaults suite. /// - Parameters: /// - suiteName: The `UserDefaults` suite name. /// - key: The defaults key that stores approved scopes and their expiry times. - /// - trustDuration: How long a host approval remains valid. + /// - sessionIdentifier: The app-session boundary for approvals. + /// - trustDuration: How long a host approval remains valid within this session. /// - now: Clock source used to evaluate expiry. public init( suiteName: String, key: String = "cmux.mobile.manualHostTrust.v2", + sessionIdentifier: String = UUID().uuidString, trustDuration: TimeInterval = UserDefaultsMobileManualHostTrustStore.defaultTrustDuration, now: @escaping @Sendable () -> Date = { Date() } ) { @@ -53,6 +59,7 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin self.defaults = .standard } self.key = key + self.sessionIdentifier = sessionIdentifier self.trustDuration = trustDuration self.now = now } @@ -61,11 +68,12 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin /// - Parameter scope: The scope to look up. public func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { var trusted = trustedExpirations() - guard let expiresAt = trusted[scope.storageKey] else { + let scopedKey = sessionStorageKey(for: scope) + guard let expiresAt = trusted[scopedKey] else { return false } guard expiresAt > now().timeIntervalSince1970 else { - trusted.removeValue(forKey: scope.storageKey) + trusted.removeValue(forKey: scopedKey) defaults.set(trusted, forKey: key) return false } @@ -80,7 +88,7 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin var trusted = trustedExpirations().filter { _, expiresAt in expiresAt > currentTime } - trusted[scope.storageKey] = currentTime + trustDuration + trusted[sessionStorageKey(for: scope)] = currentTime + trustDuration defaults.set(trusted, forKey: key) } @@ -103,4 +111,19 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin } return trusted } + + private func sessionStorageKey(for scope: MobileManualHostTrustScope) -> String { + [ + sessionIdentifier.mobileManualHostTrustStorageEscaped, + scope.storageKey, + ].joined(separator: "|") + } +} + +private extension String { + var mobileManualHostTrustStorageEscaped: String { + self + .replacing("%", with: "%25") + .replacing("|", with: "%7C") + } } diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index 56f6ec0be94c..8ad2bdc6b58c 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -185,7 +185,7 @@ import Testing #expect(await store.isTrusted(differentAccount) == false) } - @Test func userDefaultsManualHostTrustExpiresApproval() async throws { + @Test func userDefaultsManualHostTrustIsSessionScopedAndExpires() async throws { let suiteName = "cmux-manual-host-trust-\(UUID().uuidString)" defer { UserDefaults(suiteName: suiteName)?.removePersistentDomain(forName: suiteName) @@ -199,18 +199,28 @@ import Testing let writer = UserDefaultsMobileManualHostTrustStore( suiteName: suiteName, key: key, + sessionIdentifier: "session-a", trustDuration: 60, now: { Date(timeIntervalSince1970: 1_000) } ) let stillValidReader = UserDefaultsMobileManualHostTrustStore( suiteName: suiteName, key: key, + sessionIdentifier: "session-a", + trustDuration: 60, + now: { Date(timeIntervalSince1970: 1_059) } + ) + let differentSessionReader = UserDefaultsMobileManualHostTrustStore( + suiteName: suiteName, + key: key, + sessionIdentifier: "session-b", trustDuration: 60, now: { Date(timeIntervalSince1970: 1_059) } ) let expiredReader = UserDefaultsMobileManualHostTrustStore( suiteName: suiteName, key: key, + sessionIdentifier: "session-a", trustDuration: 60, now: { Date(timeIntervalSince1970: 1_061) } ) @@ -218,6 +228,7 @@ import Testing await writer.trust(scope) #expect(await stillValidReader.isTrusted(scope)) + #expect(await differentSessionReader.isTrusted(scope) == false) #expect(await expiredReader.isTrusted(scope) == false) } diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift index f1ce2aa97f13..33ac89726177 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobileSection.swift @@ -26,6 +26,8 @@ public struct MobileSection: View { @State private var applyResult: MobilePairingPortApplyResult? /// Guards against overlapping Apply taps while a probe is in flight. @State private var isApplying = false + /// User's in-progress manual-host edit. `nil` tracks the persisted setting. + @State private var editedManualHost: String? /// Host bridge: opens the pairing window, applies the port (availability /// checked), and supplies the live pairing status and default display name. @@ -70,6 +72,14 @@ public struct MobileSection: View { } private var trimmedManualHost: String { + draftManualHost.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var draftManualHost: String { + editedManualHost ?? manualHost.current + } + + private var persistedManualHost: String { manualHost.current.trimmingCharacters(in: .whitespacesAndNewlines) } @@ -77,6 +87,10 @@ public struct MobileSection: View { manualHostAdvertisability.isAdvertisable(trimmedManualHost) } + private var canApplyManualHost: Bool { + isManualHostValid && trimmedManualHost != persistedManualHost + } + /// The Mobile settings section content. public var body: some View { Group { @@ -280,14 +294,22 @@ public struct MobileSection: View { localized: "settings.mobile.manualHost.subtitle", defaultValue: "Optional LAN IP or DNS host to advertise when this Mac cannot run Tailscale." ), - controlWidth: Self.columnWidth + controlWidth: Self.columnWidth + 68 ) { - TextField( - String(localized: "settings.mobile.manualHost.placeholder", defaultValue: "192.168.1.23 or mac.local"), - text: Binding(get: { manualHost.current }, set: { manualHost.set($0) }) - ) - .textFieldStyle(.roundedBorder) - .accessibilityIdentifier("SettingsMobilePairingManualHostField") + HStack(spacing: 8) { + TextField( + String(localized: "settings.mobile.manualHost.placeholder", defaultValue: "192.168.1.23 or mac.local"), + text: Binding(get: { draftManualHost }, set: { editedManualHost = $0 }) + ) + .textFieldStyle(.roundedBorder) + .accessibilityIdentifier("SettingsMobilePairingManualHostField") + .onSubmit { applyManualHostIfNeeded() } + + Button(String(localized: "settings.mobile.port.apply", defaultValue: "Apply")) { + applyManualHostIfNeeded() + } + .disabled(!canApplyManualHost) + } } } @@ -336,6 +358,12 @@ public struct MobileSection: View { } } + private func applyManualHostIfNeeded() { + guard canApplyManualHost else { return } + manualHost.set(trimmedManualHost) + editedManualHost = nil + } + /// Read-only connection count and the reachable routes the phone can use. @ViewBuilder private var diagnostics: some View { From 13b5c8d6bb9e3583a1642e9eca6477e373085950 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 13:53:42 -0700 Subject: [PATCH 48/91] Add failing manual host trust lifecycle regressions --- .../MobileCoreRPCClientTests.swift | 23 ------- .../MobileCoreRPCManualHostTrustTests.swift | 62 +++++++++++++++++++ ...obileManualHostTrustPersistenceTests.swift | 54 ++++++++++++++++ .../PairingViewPendingApprovalTests.swift | 24 +++++++ 4 files changed, 140 insertions(+), 23 deletions(-) create mode 100644 Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift index efb2e266e733..028f7164cb9c 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift @@ -377,29 +377,6 @@ import Testing #expect(probe?.hasAuth == false) } - @Test func trustedManualHostRouteCarriesStackToken() async throws { - let route = try hostPortRoute(kind: .manualHost, host: "192.168.1.20", port: 58465) - let transport = QueuedCancellationProbeTransport() - let runtime = TestMobileSyncRuntime( - transportFactory: QueuedCancellationProbeTransportFactory(transport: transport), - stackAccessToken: "trusted-manual-token" - ) - let client = MobileCoreRPCClient( - runtime: runtime, - route: route, - ticket: try qrPairingTicket(route: route), - allowsStackAuthFallback: true, - allowsTrustedManualHostStackAuth: true - ) - let request = try MobileCoreRPCClient.requestData(method: "workspace.list") - let task = Task { try await client.sendRequest(request) } - let sent = try await transport.waitForSentRequestCount(1) - task.cancel() - _ = try? await task.value - - #expect(sent.first?.stackAccessToken == "trusted-manual-token") - } - @Test func workspaceActionsCarryMacWideAttachTicketContext() async throws { let route = try hostPortRoute(kind: .tailscale, host: "100.64.0.5", port: 58465) let transport = QueuedCancellationProbeTransport() diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift new file mode 100644 index 000000000000..aa4d2aaf55f4 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift @@ -0,0 +1,62 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileRPC + +@Suite struct MobileCoreRPCManualHostTrustTests { + @Test func revokingTrustBlocksNextRequestOnExistingManualHostClient() async throws { + let route = try hostPortRoute(kind: .manualHost, host: "192.168.1.20", port: 58_465) + let scope = try #require( + MobileManualHostTrustScope(route: route, stackUserID: "phone-user") + ) + let trustStore = InMemoryMobileManualHostTrustStore() + await trustStore.trust(scope) + let transport = QueuedCancellationProbeTransport() + let runtime = TestMobileSyncRuntime( + transportFactory: QueuedCancellationProbeTransportFactory(transport: transport), + stackAccessToken: "trusted-manual-token" + ) + let client = MobileCoreRPCClient( + runtime: runtime, + route: route, + ticket: try qrPairingTicket(route: route), + allowsStackAuthFallback: true, + manualHostStackAuthTrustProvider: { + await trustStore.isTrusted(scope) + } + ) + let request = try MobileCoreRPCClient.requestData(method: "workspace.list") + let trustedRequest = Task { try await client.sendRequest(request) } + let sentWhileTrusted = try await transport.waitForSentRequestCount(1) + trustedRequest.cancel() + _ = try? await trustedRequest.value + + #expect(sentWhileTrusted.first?.stackAccessToken == "trusted-manual-token") + + await trustStore.removeAll() + + do { + _ = try await client.sendRequest(request) + Issue.record("Expected revoked manual-host trust to block Stack auth") + } catch let error as MobileShellConnectionError { + guard case .insecureManualRoute = error else { + Issue.record("Expected insecureManualRoute, got \(error)") + return + } + } + #expect(try await transport.sentRequests().count == 1) + } + + private func qrPairingTicket(route: CmxAttachRoute) throws -> CmxAttachTicket { + try CmxAttachTicket( + workspaceID: "", + terminalID: nil, + macDeviceID: "", + macDisplayName: nil, + routes: [route], + expiresAt: nil, + authToken: nil + ) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift new file mode 100644 index 000000000000..8fd094979878 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift @@ -0,0 +1,54 @@ +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct MobileManualHostTrustPersistenceTests { + @Test func approvalThatWasNotPersistedPromptsAgainWithoutSendingCredentials() async { + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory( + router: router, + box: TransportBox() + ), + now: { Date() }, + supportedRouteKinds: [.manualHost] + ) + let store = MobileShellComposite( + runtime: runtime, + isSignedIn: true, + reachability: AlwaysOnlineReachability(), + pairingHintDefaults: UserDefaults( + suiteName: "manual-host-refused-trust-\(UUID().uuidString)" + )!, + manualHostTrustStore: RefusingManualHostTrustStore() + ) + + let queued = await store.connectManualHost( + name: "LAN Mac", + host: "192.168.1.77", + port: 58_465 + ) + let resumed = await store.acceptManualHostTrustWarning() + + #expect(queued == .needsUserApproval) + #expect(resumed == .needsUserApproval) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + #expect(await router.count(of: "mobile.attach_ticket.create") == 0) + #expect(await router.count(of: "workspace.list") == 0) + } +} + +private actor RefusingManualHostTrustStore: MobileManualHostTrustStoring { + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + _ = scope + return false + } + + func trust(_ scope: MobileManualHostTrustScope) async { + _ = scope + } + + func removeAll() async {} +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift index 3017b87d464d..7339357c6bfe 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift @@ -26,6 +26,30 @@ import Testing #expect(cancelCount == 1) } + @MainActor + @Test func idleCancelDismissesWithoutTearingDownStoreConnection() { + var cancelPairingCount = 0 + var dismissCount = 0 + let view = PairingView( + pairingCode: .constant(""), + connectionError: nil, + connectionErrorGuidance: nil, + versionWarning: nil, + manualHostTrustWarning: nil, + connectPairingCode: {}, + acceptVersionWarning: {}, + acceptManualHostTrustWarning: {}, + connectManualHost: { _, _, _ in }, + cancelPairing: { cancelPairingCount += 1 }, + cancel: { dismissCount += 1 } + ) + + view.cancelAndDismiss() + + #expect(cancelPairingCount == 0) + #expect(dismissCount == 1) + } + private func warning() -> MobileManualHostTrustWarning { let scope = MobileManualHostTrustScope( host: "192.168.1.77", From 4264ce985544c142205e49eea1496e5f623ee0a6 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 13:59:46 -0700 Subject: [PATCH 49/91] Revalidate manual host trust per request --- .../CmuxMobileRPC/MobileCoreRPCClient.swift | 44 +++++++++++++------ ...ileShellComposite+ManualAttachTicket.swift | 8 ++-- ...MobileShellComposite+ManualHostTrust.swift | 13 +++++- .../MobileShellComposite.swift | 24 +++++----- .../CMUXMobileRootView+PairingWarnings.swift | 16 ++++--- .../CMUXMobileRootView.swift | 20 +++++---- .../CmuxMobileShellUI/PairingView.swift | 21 ++++++--- 7 files changed, 93 insertions(+), 53 deletions(-) diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift index 1bcdbcf1dae3..a2dd9b31ece3 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift @@ -15,7 +15,7 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { /// The attach ticket this client uses to authorize RPC requests. public var attachTicket: CmxAttachTicket { ticket } private let allowsStackAuthFallback: Bool - private let allowsTrustedManualHostStackAuth: Bool + private let manualHostStackAuthTrustProvider: @Sendable () async -> Bool // `internal` (not `private`) so `@testable import` can observe session // queue state from tests, instead of exposing a debug hook in production. let session: MobileCoreRPCSession @@ -29,15 +29,16 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { /// - ticket: The attach ticket authorizing requests. /// - allowsStackAuthFallback: When `true`, falls back to a Stack Auth token /// on routes that allow it once the attach ticket no longer covers a request. - /// - allowsTrustedManualHostStackAuth: When `true`, this client may send - /// Stack auth over its exact `.manualHost` route because the shell has - /// verified a persisted user approval for that host and port. + /// - manualHostStackAuthTrustProvider: Revalidates whether this client's + /// exact `.manualHost` route may carry Stack auth. The provider is called + /// for every token-bearing request so approval expiry or revocation takes + /// effect without replacing the client. public init( runtime: any MobileSyncRuntime, route: CmxAttachRoute, ticket: CmxAttachTicket, allowsStackAuthFallback: Bool = false, - allowsTrustedManualHostStackAuth: Bool = false, + manualHostStackAuthTrustProvider: @escaping @Sendable () async -> Bool = { false }, connectAttemptRegistry: MobileRPCConnectAttemptRegistry = MobileRPCConnectAttemptRegistry(), stackTokenGate: RPCStackTokenGate? = nil, stackTokenForceRefreshGate: RPCStackTokenGate? = nil, @@ -49,7 +50,7 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { self.route = route self.ticket = ticket self.allowsStackAuthFallback = allowsStackAuthFallback - self.allowsTrustedManualHostStackAuth = allowsTrustedManualHostStackAuth + self.manualHostStackAuthTrustProvider = manualHostStackAuthTrustProvider self.stackTokenGate = stackTokenGate ?? RPCStackTokenGate(timedOutResetNanoseconds: stackTokenGateResetNanoseconds) self.stackTokenForceRefreshGate = stackTokenForceRefreshGate @@ -141,6 +142,10 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { /// not trip the re-auth prompt; a definitive failure surfaces as /// `.authorizationFailed` to drive re-auth. private func forceRefreshStackTokenForRetry(deadline: RPCRequestDeadline) async throws { + guard allowsStackAuthFallback, + await routeAllowsStackAuth() else { + throw MobileShellConnectionError.insecureManualRoute + } do { _ = try await stackTokenForceRefreshGate.token( timeoutNanoseconds: try deadline.remainingNanoseconds() @@ -223,7 +228,9 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { // expiry), so they never reach this branch. if !ticket.isExpired(at: runtime.now()) { auth["attach_token"] = attachToken - } else if !allowsStackAuthFallback || !routeAllowsStackAuth { + } else if !allowsStackAuthFallback { + throw MobileShellConnectionError.attachTicketExpired + } else if !(await routeAllowsStackAuth()) { throw MobileShellConnectionError.attachTicketExpired } } @@ -238,11 +245,15 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { let shouldSendStackAuth = requestNeedsAuth if shouldSendStackAuth { guard allowsStackAuthFallback, - routeAllowsStackAuth else { + await routeAllowsStackAuth() else { throw MobileShellConnectionError.insecureManualRoute } do { - auth["stack_access_token"] = try await stackAccessToken(deadline: deadline) + let stackAccessToken = try await stackAccessToken(deadline: deadline) + guard await routeAllowsStackAuth() else { + throw MobileShellConnectionError.insecureManualRoute + } + auth["stack_access_token"] = stackAccessToken } catch let error as MobileShellConnectionError { // The provider already classified the failure: a transient // token-fetch failure (offline / refresh server hiccup, session @@ -267,8 +278,9 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { if !requestNeedsAuth, isHostStatusRequest(request), allowsStackAuthFallback, - routeAllowsStackAuth, - let stackAccessToken = try await stackAccessTokenForStatus(deadline: deadline) { + await routeAllowsStackAuth(), + let stackAccessToken = try await stackAccessTokenForStatus(deadline: deadline), + await routeAllowsStackAuth() { auth["stack_access_token"] = stackAccessToken } if !auth.isEmpty { @@ -277,10 +289,14 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { return try JSONSerialization.data(withJSONObject: request) } - private var routeAllowsStackAuth: Bool { - MobileShellRouteAuthPolicy().routeAllowsStackAuth( + private func routeAllowsStackAuth() async -> Bool { + let policy = MobileShellRouteAuthPolicy() + guard policy.routeRequiresManualHostTrust(route) else { + return policy.routeAllowsStackAuth(route) + } + return policy.routeAllowsStackAuth( route, - manualHostTrusted: allowsTrustedManualHostStackAuth + manualHostTrusted: await manualHostStackAuthTrustProvider() ) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift index 5e0eab838a21..5d79c9a0d439 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift @@ -58,8 +58,7 @@ extension MobileShellComposite { let ticket = try await requestManualAttachTicket( route: directRoute, displayName: displayName, - attemptStartedAt: attemptStartedAt, - manualHostTrusted: manualHostTrusted + attemptStartedAt: attemptStartedAt ) return ticket } catch { @@ -100,8 +99,7 @@ extension MobileShellComposite { func requestManualAttachTicket( route: CmxAttachRoute, displayName: String, - attemptStartedAt: Date?, - manualHostTrusted: Bool = false + attemptStartedAt: Date? ) async throws -> CmxAttachTicket { guard let runtime else { throw MobileShellConnectionError.insecureManualRoute @@ -116,7 +114,7 @@ extension MobileShellComposite { route: route, ticket: probeTicket, allowsStackAuthFallback: true, - allowsTrustedManualHostStackAuth: manualHostTrusted, + manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider(for: route), connectAttemptRegistry: connectAttemptRegistry, stackTokenGate: stackTokenGate, stackTokenForceRefreshGate: stackTokenForceRefreshGate diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 0fb90e6a34d7..aa20edcee9cd 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -34,6 +34,18 @@ extension MobileShellComposite { return await manualHostTrustStore.isTrusted(scope) } + func manualHostStackAuthTrustProvider( + for route: CmxAttachRoute? + ) -> @Sendable () async -> Bool { + guard let scope = manualHostTrustScope(for: route) else { + return { false } + } + let trustStore = manualHostTrustStore + return { + await trustStore.isTrusted(scope) + } + } + func manualHostRouteNeedsApproval(_ route: CmxAttachRoute) async -> Bool { guard let scope = manualHostTrustScope(for: route) else { return false @@ -111,7 +123,6 @@ extension MobileShellComposite { pairedMacDeviceID: pairedMacDeviceID, recordsPairingAttempt: recordsPairingAttempt, route: route, - approvedManualRouteID: route.id, ifStillCurrent: ifStillCurrent ) finishPendingManualHostSwitchAttempt(pending) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 2c96101ee108..9a9d6a59d170 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1535,26 +1535,28 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } /// Connect using the current pairing input, accepting either a code or pairing URL. - public func connectPairingInput() async { + @discardableResult + public func connectPairingInput() async -> MobilePairingURLConnectionResult { let trimmedCode = pairingCode.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedCode.isEmpty else { - return + return .failed } if CmxPairingURLScheme.hasPairingScheme(trimmedCode) { - await connectPairingURL(trimmedCode) - return + return await connectPairingURLResult(trimmedCode) } connectPreviewHost() + return connectionState == .connected ? .connected : .failed } /// Connect to a manually-entered Mac host and optionally associate the /// resulting session with an existing paired-Mac device id. + @discardableResult public func connectManualHost( name: String, host: String, port: Int, pairedMacDeviceID: String? = nil - ) async { + ) async -> MobilePairingURLConnectionResult { await connectManualHost( name: name, host: host, @@ -1596,7 +1598,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { pairedMacDeviceID: String? = nil, recordsPairingAttempt: Bool, route: CmxAttachRoute? = nil, - approvedManualRouteID: String? = nil, pendingMacSwitchAttemptID: UUID? = nil, ifStillCurrent: (() -> Bool)? = nil ) async -> MobilePairingURLConnectionResult { @@ -1628,12 +1629,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } let directRoute = try? routeSelection.manualHostRoute(host: normalizedHost, port: port, preserving: route) - let directRouteIsApproved = approvedManualRouteID != nil && directRoute?.id == approvedManualRouteID let approvalAttemptID = beginPairingValidationAttempt() if let directRoute { let needsApproval = await manualHostRouteNeedsApproval(directRoute) guard isCurrentPairingAttempt(approvalAttemptID) else { return .superseded } - if needsApproval && !directRouteIsApproved { + if needsApproval { queueManualHostTrustWarning( route: directRoute, displayHost: normalizedHost, @@ -1673,9 +1673,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } do { guard ifStillCurrent?() != false else { return .superseded } - let manualHostTrusted = directRouteIsApproved - ? true - : await manualHostStackAuthTrusted(for: directRoute) + let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) guard isCurrentPairingAttempt(attemptID), ifStillCurrent?() != false else { return .superseded } let ticket = try await manualHostTicket( name: trimmedName, @@ -3485,7 +3483,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { route: route, ticket: ticket, allowsStackAuthFallback: true, - allowsTrustedManualHostStackAuth: manualHostTrusted, + manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider(for: route), connectAttemptRegistry: connectAttemptRegistry, stackTokenGate: stackTokenGate, stackTokenForceRefreshGate: stackTokenForceRefreshGate @@ -5058,7 +5056,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ticket: ticket, allowsStackAuthFallback: routeAllowsStackAuthFallbackOverride ?? routeAllowsStackAuth, - allowsTrustedManualHostStackAuth: manualHostTrusted, + manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider(for: route), connectAttemptRegistry: connectAttemptRegistry, stackTokenGate: stackTokenGate, stackTokenForceRefreshGate: stackTokenForceRefreshGate diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift index 29f8b98cfa3f..42732c05ee19 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView+PairingWarnings.swift @@ -17,17 +17,23 @@ extension CMUXMobileRootView { func acceptPairingVersionWarning() async { let result = await store.acceptPairingVersionWarning() - clearAttachTicketAuthentication(after: result) - if result == .connected { - dismissAddDeviceSheet() - } + finishPairingPresentation(after: result) } func acceptManualHostTrustWarning() async { let result = await store.acceptManualHostTrustWarning() + finishPairingPresentation(after: result) + } + + func finishPairingPresentation(after result: MobilePairingURLConnectionResult) { clearAttachTicketAuthentication(after: result) - if result == .connected { + switch result { + case .connected: dismissAddDeviceSheet() + case .needsUserApproval: + showAddDevice() + case .failed, .superseded: + break } } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 58328d3af408..41f6edc0ccc5 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -163,7 +163,8 @@ struct CMUXMobileRootView: View { return } Task { - await store.connectPairingURL(rawURL) + let result = await store.connectPairingURLResult(rawURL) + finishPairingPresentation(after: result) } } .onChange(of: isAuthenticated) { _, isAuthenticated in @@ -267,12 +268,14 @@ struct CMUXMobileRootView: View { versionWarning: store.pairingVersionWarning, manualHostTrustWarning: store.manualHostTrustWarning, connectPairingCode: { - await store.connectPairingInput() + let result = await store.connectPairingInput() + finishPairingPresentation(after: result) }, acceptVersionWarning: acceptPairingVersionWarning, acceptManualHostTrustWarning: acceptManualHostTrustWarning, connectManualHost: { name, host, port in - await store.connectManualHost(name: name, host: host, port: port) + let result = await store.connectManualHost(name: name, host: host, port: port) + finishPairingPresentation(after: result) }, cancelPairing: cancelPairing, cancel: dismissAddDeviceSheet @@ -399,10 +402,7 @@ struct CMUXMobileRootView: View { syncShellAuthentication(true) Task { let result = await store.connectPairingURLResult(rawURL) - if result == .needsUserApproval { - isShowingAddDeviceSheet = true - } - clearAttachTicketAuthentication(after: result) + finishPairingPresentation(after: result) } } @@ -418,7 +418,8 @@ struct CMUXMobileRootView: View { guard isAuthenticated else { return false } pendingAttachURL = nil Task { - await store.connectPairingURL(rawURL) + let result = await store.connectPairingURLResult(rawURL) + finishPairingPresentation(after: result) } return true } @@ -508,7 +509,8 @@ struct CMUXMobileRootView: View { } didConsumeUITestAttachURL = true Task { - await store.connectPairingURL(attachURL) + let result = await store.connectPairingURLResult(attachURL) + finishPairingPresentation(after: result) } return true #else diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift index 7238e06e33fd..0a56d5a82bc1 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift @@ -293,17 +293,26 @@ struct PairingView: View { private var cancelButton: some View { Button { - pairingTask?.cancel() - pairingTaskID = nil - pairingTask = nil - isPairing = false - cancelPairing() - cancel() + cancelAndDismiss() } label: { Text(L10n.string("mobile.common.cancel", defaultValue: "Cancel")) } } + func cancelAndDismiss() { + let shouldCancelStoreAttempt = pairingTask != nil + || versionWarning != nil + || manualHostTrustWarning != nil + pairingTask?.cancel() + pairingTaskID = nil + pairingTask = nil + isPairing = false + if shouldCancelStoreAttempt { + cancelPairing() + } + cancel() + } + private var errorText: String? { validationError ?? connectionError } From 991e61720bbe562e7f1b9adb2b0d1a9bc95018c3 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 14:52:00 -0700 Subject: [PATCH 50/91] Add failing manual host authorization ownership regressions --- ...anualHostAuthorizationOwnershipTests.swift | 162 ++++++++++++++++++ .../MobileShellManualHostReconnectTests.swift | 63 +++++++ .../MobileShellRouteAuthPolicyTests.swift | 27 ++- 3 files changed, 250 insertions(+), 2 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift new file mode 100644 index 000000000000..546b1001e0fe --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift @@ -0,0 +1,162 @@ +import CMUXMobileCore +import CmuxMobileRPC +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct MobileShellManualHostAuthorizationOwnershipTests { + @Test func revokedForegroundTrustQueuesHostApprovalWithoutAccountReauth() async throws { + let route = try hostPortRoute(kind: .manualHost, host: "192.168.1.77", port: 58_465) + let trustStore = InMemoryMobileManualHostTrustStore() + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: trustStore + ) + store.signIn() + + let queued = await store.connectManualHost( + name: "Studio Mac", + host: "192.168.1.77", + port: 58_465 + ) + let connected = await store.acceptManualHostTrustWarning() + #expect(queued == .needsUserApproval) + #expect(connected == .connected) + #expect(store.activeRoute?.kind == route.kind) + + await trustStore.removeAll() + store.terminalInputText = "pwd" + await store.submitTerminalInput() + + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + #expect(!store.connectionRequiresReauth) + #expect(store.connectionState == .disconnected) + + let reconnected = await store.acceptManualHostTrustWarning() + #expect(reconnected == .connected) + #expect(!store.connectionRequiresReauth) + } + + @Test func secondaryTrustFailureDoesNotDisconnectForegroundConnection() async throws { + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.debugLoopback, .manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite.preview(runtime: runtime) + store.signIn() + let foregroundRoute = try hostPortRoute( + kind: .debugLoopback, + host: "127.0.0.1", + port: 56_584 + ) + let foregroundTicket = try CmxAttachTicket( + workspaceID: "live-workspace", + terminalID: "live-terminal", + macDeviceID: "foreground-mac", + macDisplayName: "Foreground Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [foregroundRoute], + expiresAt: Date().addingTimeInterval(3_600), + authToken: "foreground-ticket" + ) + #expect(await store.connectPairingURL(try attachURL(for: foregroundTicket))) + let foregroundClient = try #require(store.remoteClient) + + let secondaryRoute = try hostPortRoute( + kind: .manualHost, + host: "192.168.1.88", + port: 58_465 + ) + let secondaryTicket = try CmxAttachTicket( + workspaceID: "", + terminalID: nil, + macDeviceID: "secondary-mac", + macDisplayName: "Secondary Mac", + routes: [secondaryRoute], + expiresAt: Date().addingTimeInterval(3_600) + ) + let secondaryClient = MobileCoreRPCClient( + runtime: runtime, + route: secondaryRoute, + ticket: secondaryTicket, + allowsStackAuthFallback: true, + manualHostStackAuthTrustProvider: { false } + ) + let actionCapabilities = MobileWorkspaceActionCapabilities(supportsWorkspaceActions: true) + store.secondaryMacSubscriptions["secondary-mac"] = SecondaryMacSubscription( + macDeviceID: "secondary-mac", + client: secondaryClient, + route: secondaryRoute, + ticket: secondaryTicket, + supportedHostCapabilities: ["workspace.actions.v1"], + actionCapabilities: actionCapabilities + ) + let foregroundWorkspace = MobileWorkspacePreview( + id: "live-workspace", + macDeviceID: "foreground-mac", + name: "Foreground Workspace", + terminals: [] + ) + let secondaryWorkspace = MobileWorkspacePreview( + id: "secondary-workspace", + macDeviceID: "secondary-mac", + name: "Secondary Workspace", + terminals: [] + ) + store.setWorkspaceStatesForTesting([ + "foreground-mac": MacWorkspaceState( + macDeviceID: "foreground-mac", + workspaces: [foregroundWorkspace], + status: .connected + ), + "secondary-mac": MacWorkspaceState( + macDeviceID: "secondary-mac", + workspaces: [secondaryWorkspace], + status: .connected, + actionCapabilities: actionCapabilities + ), + ], foregroundMacDeviceID: "foreground-mac") + let secondaryRowID = try #require( + store.workspaces.first(where: { $0.macDeviceID == "secondary-mac" })?.id + ) + + let result = await store.renameWorkspace(id: secondaryRowID, title: "Renamed") + + guard case .failure(.authorizationFailed) = result else { + Issue.record("Expected the secondary mutation to report authorization failure") + return + } + #expect(store.connectionState == .connected) + #expect(store.remoteClient === foregroundClient) + #expect(store.connectedMacDeviceID == "foreground-mac") + #expect(!store.connectionRequiresReauth) + #expect(store.secondaryMacSubscriptions["secondary-mac"] == nil) + } + + private func hostPortRoute( + kind: CmxAttachTransportKind, + host: String, + port: Int + ) throws -> CmxAttachRoute { + try CmxAttachRoute( + id: "\(kind.rawValue)-\(host)-\(port)", + kind: kind, + endpoint: .hostPort(host: host, port: port) + ) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift index 4ab7b9755d89..e5d8d4eba346 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift @@ -115,6 +115,69 @@ import Testing #expect(await router.count(of: "workspace.list") >= 1) } + @Test func workspaceOpenWaitsForManualHostApprovalAndResumesTheOriginalSelection() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let manualRoute = try hostPortRoute(kind: .manualHost, host: "192.168.89.2") + try await pairedMacStore.upsert( + macDeviceID: "manual-mac", + displayName: "Manual Mac", + routes: [manualRoute], + markActive: false, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + store.signIn() + await store.loadPairedMacs() + store.setWorkspaceStatesForTesting([ + "manual-mac": MacWorkspaceState( + macDeviceID: "manual-mac", + displayName: "Manual Mac", + workspaces: [ + MobileWorkspacePreview( + id: "live-workspace", + macDeviceID: "manual-mac", + name: "Requested Workspace", + terminals: [] + ), + ], + status: .connected + ), + ], foregroundMacDeviceID: "other-mac") + let requestedWorkspaceID = try #require(store.workspaces.first?.id) + store.selectedWorkspaceID = requestedWorkspaceID + + await store.openWorkspace(requestedWorkspaceID) + + #expect(store.manualHostTrustWarning?.endpoint == "192.168.89.2:58465") + #expect(store.selectedWorkspaceID == requestedWorkspaceID) + + let approved = await store.acceptManualHostTrustWarning() + + #expect(approved == .connected) + #expect(store.selectedWorkspace?.rpcWorkspaceID == "live-workspace") + } + @Test func newPairingURLSupersedesPendingManualHostSwitchApproval() async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index 8ad2bdc6b58c..81be148810de 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -203,6 +203,8 @@ import Testing trustDuration: 60, now: { Date(timeIntervalSince1970: 1_000) } ) + await writer.trust(scope) + let stillValidReader = UserDefaultsMobileManualHostTrustStore( suiteName: suiteName, key: key, @@ -225,13 +227,34 @@ import Testing now: { Date(timeIntervalSince1970: 1_061) } ) - await writer.trust(scope) - #expect(await stillValidReader.isTrusted(scope)) #expect(await differentSessionReader.isTrusted(scope) == false) #expect(await expiredReader.isTrusted(scope) == false) } + @Test func userDefaultsManualHostTrustUsesItsInitializedCacheForValidation() async throws { + let suiteName = "cmux-manual-host-trust-cache-\(UUID().uuidString)" + defer { UserDefaults(suiteName: suiteName)?.removePersistentDomain(forName: suiteName) } + let scope = try #require(MobileManualHostTrustScope( + host: "studio-mac.local", + port: 58_465, + stackUserID: "user-a" + )) + let key = "manual-host-trust" + let store = UserDefaultsMobileManualHostTrustStore( + suiteName: suiteName, + key: key, + sessionIdentifier: "session-a", + trustDuration: 60, + now: { Date(timeIntervalSince1970: 1_000) } + ) + await store.trust(scope) + + UserDefaults(suiteName: suiteName)?.removeObject(forKey: key) + + #expect(await store.isTrusted(scope)) + } + @Test func manualHostTrustWarningFormatsBracketedIPv6Once() throws { let scope = try #require(MobileManualHostTrustScope( host: "[fd00::12]", From ee589ca26f26fca64802740888a60d1eda4f0923 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 15:03:16 -0700 Subject: [PATCH 51/91] Scope manual host trust recovery to connection owners --- ...MobileShellAuthorizationFailureOwner.swift | 29 ++++ ...eShellComposite+AuthorizationFailure.swift | 79 +++++++++- ...MobileShellComposite+ManualHostTrust.swift | 18 ++- ...obileShellComposite+WorkspaceActions.swift | 15 +- ...hellComposite+WorkspaceCreateRequest.swift | 5 +- ...obileShellComposite+WorkspaceOpening.swift | 120 +++++++++++++++ .../MobileShellComposite.swift | 139 +++++++++--------- .../PendingManualHostTrust.swift | 9 ++ .../PendingWorkspaceOpenIntent.swift | 13 ++ .../WorkspaceMutationTarget.swift | 1 + ...erDefaultsMobileManualHostTrustStore.swift | 79 ++++++++-- 11 files changed, 415 insertions(+), 92 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellAuthorizationFailureOwner.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceOpening.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingWorkspaceOpenIntent.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellAuthorizationFailureOwner.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellAuthorizationFailureOwner.swift new file mode 100644 index 000000000000..bf687cd78104 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellAuthorizationFailureOwner.swift @@ -0,0 +1,29 @@ +import CMUXMobileCore +import CmuxMobileRPC + +/// The connection whose request produced an authorization failure. +enum MobileShellAuthorizationFailureOwner { + case foreground(route: CmxAttachRoute?) + case connectionAttempt(route: CmxAttachRoute?, preservingActiveConnection: Bool) + case secondary(macDeviceID: String, client: MobileCoreRPCClient, route: CmxAttachRoute) + + var route: CmxAttachRoute? { + switch self { + case let .foreground(route), let .connectionAttempt(route, _): + route + case let .secondary(_, _, route): + route + } + } + + var preservesActiveConnection: Bool { + switch self { + case .foreground: + false + case let .connectionAttempt(_, preservingActiveConnection): + preservingActiveConnection + case .secondary: + true + } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift index e8baff179048..375d5496db9f 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift @@ -1,22 +1,91 @@ import CMUXMobileCore import CmuxMobileRPC +import CmuxMobileShellModel import Foundation @MainActor extension MobileShellComposite { - func disconnectForAuthorizationFailureIfNeeded( + func handleAuthorizationFailureIfNeeded( _ error: any Error, - route: CmxAttachRoute? = nil, - preservingActiveConnection: Bool = false + owner: MobileShellAuthorizationFailureOwner ) -> Bool { guard shouldDisconnectForAuthorizationFailure(error) else { return false } - let category = MobilePairingFailureCategory.classify(error: error, route: route ?? activeRoute) - applyAuthorizationFailure(category, preservingActiveConnection: preservingActiveConnection) + if let connectionError = error as? MobileShellConnectionError, + case .insecureManualRoute = connectionError { + switch owner { + case let .foreground(route): + if queueForegroundManualHostReapproval(route: route) { + return true + } + case let .connectionAttempt(route, preservingActiveConnection): + if !preservingActiveConnection, + queueForegroundManualHostReapproval(route: route) { + return true + } + case let .secondary(macDeviceID, client, _): + invalidateSecondaryConnection(macDeviceID: macDeviceID, client: client) + return true + } + } + if case let .secondary(macDeviceID, client, _) = owner { + invalidateSecondaryConnection(macDeviceID: macDeviceID, client: client) + return true + } + let category = MobilePairingFailureCategory.classify(error: error, route: owner.route) + applyAuthorizationFailure( + category, + preservingActiveConnection: owner.preservesActiveConnection + ) + return true + } + + private func queueForegroundManualHostReapproval(route: CmxAttachRoute?) -> Bool { + guard let route, + MobileShellRouteAuthPolicy().routeRequiresManualHostTrust(route), + case let .hostPort(host, port) = route.endpoint else { + return false + } + let displayName = connectedHostName.trimmingCharacters(in: .whitespacesAndNewlines) + let pairedMacDeviceID = foregroundMacDeviceID ?? activeTicket?.macDeviceID + let attemptID = beginPairingValidationAttempt() + queueManualHostTrustWarning( + route: route, + displayHost: host, + pending: .manual( + attemptID: attemptID, + name: displayName.isEmpty ? host : displayName, + host: host, + port: port, + route: route, + pairedMacDeviceID: pairedMacDeviceID, + recordsPairingAttempt: false, + macSwitchAttemptID: nil, + ifStillCurrent: nil + ) + ) + disconnectForegroundForManualHostReapproval() return true } + private func invalidateSecondaryConnection( + macDeviceID: String, + client: MobileCoreRPCClient + ) { + guard let subscription = secondaryMacSubscriptions[macDeviceID], + subscription.client === client else { + return + } + subscription.cancel() + secondaryMacSubscriptions[macDeviceID] = nil + removeSecondaryConnectionFromPool(macDeviceID: macDeviceID) + if var state = workspacesByMac[macDeviceID] { + state.status = .unavailable + workspacesByMac[macDeviceID] = state + } + } + private func shouldDisconnectForAuthorizationFailure(_ error: any Error) -> Bool { guard let connectionError = error as? MobileShellConnectionError else { return false diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index aa20edcee9cd..7df94d67f469 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -4,6 +4,7 @@ public import CmuxMobileShellModel @MainActor extension MobileShellComposite { func clearManualHostTrustWarning() { + cancelPendingWorkspaceOpenIntent() manualHostTrustWarning = nil pendingManualHostTrust = nil } @@ -85,6 +86,7 @@ extension MobileShellComposite { clearPairingVersionWarning() if let currentPending = pendingManualHostTrust, currentPending.attemptID != pending.attemptID { + cancelPendingWorkspaceOpenIntent() finishPendingManualHostSwitchAttempt(currentPending) } pendingManualHostTrust = pending @@ -108,14 +110,18 @@ extension MobileShellComposite { clearManualHostTrustWarning() return .superseded } + let workspaceOpenIntent = takePendingWorkspaceOpenIntent(for: pending) clearManualHostTrustWarning() await manualHostTrustStore.trust(warning.scope) guard isPendingManualHostTrustCurrent(pending) else { + if let workspaceOpenIntent { + cancelWorkspaceOpen(workspaceOpenIntent) + } finishPendingManualHostSwitchAttempt(pending) return .superseded } switch pending { - case let .manual(_, name, host, port, route, pairedMacDeviceID, recordsPairingAttempt, _, ifStillCurrent): + case let .manual(_, name, host, port, route, pairedMacDeviceID, recordsPairingAttempt, macSwitchAttemptID, ifStillCurrent): let result = await connectManualHost( name: name, host: host, @@ -123,9 +129,19 @@ extension MobileShellComposite { pairedMacDeviceID: pairedMacDeviceID, recordsPairingAttempt: recordsPairingAttempt, route: route, + pendingMacSwitchAttemptID: macSwitchAttemptID, ifStillCurrent: ifStillCurrent ) + if result == .needsUserApproval { + pendingWorkspaceOpenIntent = workspaceOpenIntent + return result + } finishPendingManualHostSwitchAttempt(pending) + if result == .connected, let workspaceOpenIntent { + await resumePendingWorkspaceOpen(workspaceOpenIntent) + } else if let workspaceOpenIntent { + cancelWorkspaceOpen(workspaceOpenIntent) + } return result case let .pairingURL(_, rawURL, acceptedVersionWarning, approvedRouteID): return await connectPairingURLResult( diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift index ffc717786a57..e0ed129d5494 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift @@ -328,7 +328,19 @@ extension MobileShellComposite { let request = try MobileCoreRPCClient.requestData(method: method, params: params) _ = try await client.sendRequest(request) } catch { - if disconnectForAuthorizationFailureIfNeeded(error) { + let failureOwner: MobileShellAuthorizationFailureOwner + if !target.isForeground, + let macDeviceID = target.macDeviceID, + let route = target.route { + failureOwner = .secondary( + macDeviceID: macDeviceID, + client: client, + route: route + ) + } else { + failureOwner = .foreground(route: target.route) + } + if handleAuthorizationFailureIfNeeded(error, owner: failureOwner) { return .failure(.authorizationFailed(hostDisplayName: hostDisplayName)) } // Only the foreground connection's health drives the foreground @@ -361,6 +373,7 @@ extension MobileShellComposite { guard let anchorWorkspaceID = workspaceGroups.first(where: { $0.id == id })?.anchorWorkspaceID else { return WorkspaceMutationTarget( client: remoteClient, + route: activeRoute, isForeground: true, macDeviceID: foregroundMacDeviceID ) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceCreateRequest.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceCreateRequest.swift index b1be5463c0db..a6a2b434b240 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceCreateRequest.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceCreateRequest.swift @@ -79,7 +79,10 @@ extension MobileShellComposite { return .success(()) } catch { guard generation == connectionGeneration, !Task.isCancelled else { return .success(()) } - if disconnectForAuthorizationFailureIfNeeded(error) { + if handleAuthorizationFailureIfNeeded( + error, + owner: .foreground(route: activeRoute) + ) { return .failure(.authorizationFailed(hostDisplayName: connectedHostName)) } markMacConnectionUnavailableIfNeeded(after: error) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceOpening.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceOpening.swift new file mode 100644 index 000000000000..fca6de3f5a6b --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceOpening.swift @@ -0,0 +1,120 @@ +public import CmuxMobileShellModel +import Foundation +internal import OSLog + +private let mobileShellWorkspaceOpeningLog = Logger( + subsystem: "com.cmuxterm.app", + category: "mobile-shell" +) + +@MainActor +extension MobileShellComposite { + /// Opens a workspace preview, switching the foreground Mac first when needed. + /// - Parameter id: The aggregated workspace-row identifier to open. + public func openWorkspace(_ id: MobileWorkspacePreview.ID) async { + let workspace = workspaces.first { $0.id == id } + let remoteWorkspaceID = workspace?.rpcWorkspaceID ?? id + let ownerMacDeviceID = workspace?.macDeviceID + let workspaceHadUnread = workspace?.hasUnread == true + if multiMacAggregationEnabled, + let macDeviceID = ownerMacDeviceID, + !macDeviceID.isEmpty, + macDeviceID != foregroundMacDeviceID { + guard await switchToMac(macDeviceID: macDeviceID) else { + // Approval is a suspended switch, not a failed switch. Keep the + // selected row and bind its navigation intent to that exact attempt. + if let pending = pendingManualHostTrust, + pending.pairedMacDeviceID == macDeviceID, + let macSwitchAttemptID = pending.macSwitchAttemptID { + pendingWorkspaceOpenIntent = PendingWorkspaceOpenIntent( + rowWorkspaceID: id, + remoteWorkspaceID: remoteWorkspaceID, + ownerMacDeviceID: ownerMacDeviceID, + workspaceHadUnread: workspaceHadUnread, + terminalCount: workspace?.terminals.count ?? 0, + isPinned: workspace?.isPinned ?? false, + macSwitchAttemptID: macSwitchAttemptID + ) + return + } + mobileShellWorkspaceOpeningLog.error("openWorkspace: switch to mac failed, popping mac=\(macDeviceID, privacy: .public)") + rollbackPendingWorkspaceOpen(rowWorkspaceID: id) + return + } + } + await finishWorkspaceOpen( + requestedRowID: id, + remoteWorkspaceID: remoteWorkspaceID, + ownerMacDeviceID: ownerMacDeviceID, + workspaceHadUnread: workspaceHadUnread, + terminalCount: workspace?.terminals.count ?? 0, + isPinned: workspace?.isPinned ?? false + ) + } + + func takePendingWorkspaceOpenIntent( + for pending: PendingManualHostTrust + ) -> PendingWorkspaceOpenIntent? { + guard let intent = pendingWorkspaceOpenIntent, + pending.macSwitchAttemptID == intent.macSwitchAttemptID else { + return nil + } + pendingWorkspaceOpenIntent = nil + return intent + } + + func cancelPendingWorkspaceOpenIntent() { + guard let intent = pendingWorkspaceOpenIntent else { return } + cancelWorkspaceOpen(intent) + } + + func cancelWorkspaceOpen(_ intent: PendingWorkspaceOpenIntent) { + pendingWorkspaceOpenIntent = nil + rollbackPendingWorkspaceOpen(rowWorkspaceID: intent.rowWorkspaceID) + } + + func resumePendingWorkspaceOpen(_ intent: PendingWorkspaceOpenIntent) async { + await finishWorkspaceOpen( + requestedRowID: intent.rowWorkspaceID, + remoteWorkspaceID: intent.remoteWorkspaceID, + ownerMacDeviceID: intent.ownerMacDeviceID, + workspaceHadUnread: intent.workspaceHadUnread, + terminalCount: intent.terminalCount, + isPinned: intent.isPinned + ) + } + + private func finishWorkspaceOpen( + requestedRowID: MobileWorkspacePreview.ID, + remoteWorkspaceID: MobileWorkspacePreview.ID, + ownerMacDeviceID: String?, + workspaceHadUnread: Bool, + terminalCount: Int, + isPinned: Bool + ) async { + let resolvedRowID = rowWorkspaceID( + forRemoteWorkspaceID: remoteWorkspaceID, + macDeviceID: ownerMacDeviceID + ) ?? (workspaces.contains(where: { $0.id == requestedRowID }) ? requestedRowID : nil) + guard let resolvedRowID else { + mobileShellWorkspaceOpeningLog.error("openWorkspace: workspace disappeared after switch id=\(remoteWorkspaceID.rawValue, privacy: .private) mac=\(ownerMacDeviceID ?? "", privacy: .public)") + rollbackPendingWorkspaceOpen(rowWorkspaceID: requestedRowID) + return + } + analytics.capture("ios_workspace_opened", [ + "terminal_count": .int(terminalCount), + "is_pinned": .bool(isPinned), + "source": .string("list_tap"), + ]) + setSelectedWorkspaceID(resolvedRowID) + if supportsWorkspaceReadStateActions, workspaceHadUnread { + await setWorkspaceUnread(id: resolvedRowID, false) + } + } + + private func rollbackPendingWorkspaceOpen(rowWorkspaceID: MobileWorkspacePreview.ID) { + if selectedWorkspaceID == rowWorkspaceID { + setSelectedWorkspaceID(nil) + } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 9a9d6a59d170..4ee65fef0657 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -627,7 +627,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private let feedbackStampProvider: @MainActor () -> MobileFeedbackStamp /// The injected, fire-and-forget product-analytics emitter. Defaults to /// ``NoopAnalytics`` so previews/tests inject nothing. - private let analytics: any AnalyticsEmitting + let analytics: any AnalyticsEmitting let connectAttemptRegistry = MobileRPCConnectAttemptRegistry() let stackTokenGate = RPCStackTokenGate() let stackTokenForceRefreshGate = RPCStackTokenGate() @@ -652,6 +652,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private var pairingAttemptIsFirstPair = false private var pendingPairingVersionWarningURL: String? @ObservationIgnored var pendingManualHostTrust: PendingManualHostTrust? + @ObservationIgnored var pendingWorkspaceOpenIntent: PendingWorkspaceOpenIntent? /// The structured diagnostic log, injected from the app composition root. /// @@ -1717,10 +1718,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // A definitive auth failure (expired/invalid token after the // refresh-then-retry in the RPC layer already gave up) must drive the // re-auth prompt, not the generic "could not connect / Retry" banner. - if disconnectForAuthorizationFailureIfNeeded( + if handleAuthorizationFailureIfNeeded( underlyingError, - route: failureRoute, - preservingActiveConnection: preservesActiveConnection + owner: .connectionAttempt( + route: failureRoute, + preservingActiveConnection: preservesActiveConnection + ) ) { return .failed } let category = MobilePairingFailureCategory.classify(error: underlyingError, route: failureRoute) applyPairingFailure(category, phase: "connect") @@ -3286,10 +3289,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // Definitive auth failures drive the re-auth prompt rather than a // generic connection error (matches the manual-host path); the // helper records the analytics failure + guidance. - if disconnectForAuthorizationFailureIfNeeded( + if handleAuthorizationFailureIfNeeded( underlyingError, - route: failureRoute, - preservingActiveConnection: preservesActiveConnection + owner: .connectionAttempt( + route: failureRoute, + preservingActiveConnection: preservesActiveConnection + ) ) { return .failed } let category = MobilePairingFailureCategory.classify(error: underlyingError, route: failureRoute) applyPairingFailure(category, phase: "connect") @@ -3835,12 +3840,21 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let owner = workspaces.first(where: { $0.id == id })?.macDeviceID if owner == nil || owner == foregroundMacDeviceID || owner == Self.foregroundAnonymousKey { return WorkspaceMutationTarget( - client: remoteClient, isForeground: true, macDeviceID: foregroundMacDeviceID) + client: remoteClient, + route: activeRoute, + isForeground: true, + macDeviceID: foregroundMacDeviceID + ) } if let owner, let sub = secondaryMacSubscriptions[owner] { - return WorkspaceMutationTarget(client: sub.client, isForeground: false, macDeviceID: owner) + return WorkspaceMutationTarget( + client: sub.client, + route: sub.route, + isForeground: false, + macDeviceID: owner + ) } - return WorkspaceMutationTarget(client: nil, isForeground: false, macDeviceID: owner) + return WorkspaceMutationTarget(client: nil, route: nil, isForeground: false, macDeviceID: owner) } /// Re-sync the authoritative workspace list for the Mac a mutation actually hit: @@ -4270,61 +4284,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { reportedViewportSizesByTerminalKey[key] = viewportSize } - /// Open the workspace preview, switching the foreground Mac first when the workspace belongs to another paired Mac. - public func openWorkspace(_ id: MobileWorkspacePreview.ID) async { - let workspace = workspaces.first { $0.id == id } - let remoteWorkspaceID = workspace?.rpcWorkspaceID ?? id - let ownerMacDeviceID = workspace?.macDeviceID - let workspaceHadUnread = workspace?.hasUnread == true - // Cross-Mac open (P5): a workspace from the aggregated list may belong to - // a Mac other than the current foreground connection. Switch the - // foreground to that Mac first so the terminal attaches to the right one. - if multiMacAggregationEnabled, - let macDeviceID = ownerMacDeviceID, - !macDeviceID.isEmpty, - macDeviceID != foregroundMacDeviceID { - // Only proceed if that Mac actually became the foreground connection. - // The tap already selected this workspace and pushed its detail - // synchronously (this runs from the detail's task), so on a failed - // switch ROLL BACK the selection — popping the compact stack back to the - // list — instead of leaving the user in a workspace whose Mac is not the - // live connection (terminal input would route to the wrong client). The - // offline row's Reconnect / the next aggregation pass recovers it. - guard await switchToMac(macDeviceID: macDeviceID) else { - mobileShellLog.error("openWorkspace: switch to mac failed, popping mac=\(macDeviceID, privacy: .public)") - if selectedWorkspaceID == id { - setSelectedWorkspaceID(nil) - } - return - } - } - let resolvedRowID = rowWorkspaceID( - forRemoteWorkspaceID: remoteWorkspaceID, - macDeviceID: ownerMacDeviceID - ) ?? (workspaces.contains(where: { $0.id == id }) ? id : nil) - guard let resolvedRowID else { - mobileShellLog.error("openWorkspace: workspace disappeared after switch id=\(remoteWorkspaceID.rawValue, privacy: .private) mac=\(ownerMacDeviceID ?? "", privacy: .public)") - if selectedWorkspaceID == id { - setSelectedWorkspaceID(nil) - } - return - } - analytics.capture("ios_workspace_opened", [ - "terminal_count": .int(workspace?.terminals.count ?? 0), - "is_pinned": .bool(workspace?.isPinned ?? false), - "source": .string("list_tap"), - ]) - setSelectedWorkspaceID(resolvedRowID) - // Tapping into a workspace is a read receipt: clear its unread on the Mac - // (like opening a thread marks it read), so it drops out of the unread - // list and the back-button count. Only when the Mac advertises read-state - // actions and the workspace is actually unread, so older Macs and - // already-read workspaces send nothing. - if supportsWorkspaceReadStateActions, workspaceHadUnread { - await setWorkspaceUnread(id: resolvedRowID, false) - } - } - /// Submit the current terminal input text from a synchronous UI action. public func sendTerminalInput() { Task { @MainActor [weak self] in @@ -5265,7 +5224,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } catch { mobileShellLog.info("full mobile workspace list unavailable after scoped attach: \(String(describing: error), privacy: .private)") if isCurrentRemoteConnection(client: client, generation: generation) { - _ = disconnectForAuthorizationFailureIfNeeded(error) + _ = handleAuthorizationFailureIfNeeded( + error, + owner: .foreground(route: activeRoute) + ) } return false } @@ -5277,6 +5239,19 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { connectedHostName = "" } + /// Tears down only the foreground session while keeping account auth valid for host reapproval. + func disconnectForegroundForManualHostReapproval() { + connectionRequiresReauth = false + connectionState = .disconnected + macConnectionStatus = .unavailable + clearRemoteConnectionContext() + } + + /// Removes a failed secondary client from the internal connection pool. + func removeSecondaryConnectionFromPool(macDeviceID: String) { + connections[macDeviceID] = nil + } + func clearRemoteConnectionContext(preservingOtherMacWorkspaceState: Bool = false) { connectionGeneration = UUID() connectionAttemptGeneration = UUID() @@ -5407,7 +5382,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return attemptID } - private func beginPairingValidationAttempt(method: String? = nil) -> UUID { + func beginPairingValidationAttempt(method: String? = nil) -> UUID { let attemptID = UUID() pairingAttemptID = attemptID if let method { @@ -5925,7 +5900,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } catch { guard generation == connectionGeneration, !Task.isCancelled else { return } - guard !disconnectForAuthorizationFailureIfNeeded(error) else { return } + guard !handleAuthorizationFailureIfNeeded( + error, + owner: .foreground(route: activeRoute) + ) else { return } markMacConnectionUnavailableIfNeeded(after: error) applyOperationalError(error) } @@ -5986,7 +5964,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { handleTerminalInputResponse(responseData, surfaceID: terminalID.rawValue) } catch { guard generation == connectionGeneration else { return } - guard !disconnectForAuthorizationFailureIfNeeded(error) else { return } + guard !handleAuthorizationFailureIfNeeded( + error, + owner: .foreground(route: activeRoute) + ) else { return } markMacConnectionUnavailableIfNeeded(after: error) applyOperationalError(error) } @@ -6070,7 +6051,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return true } catch { guard generation == connectionGeneration else { return false } - guard !disconnectForAuthorizationFailureIfNeeded(error) else { return false } + guard !handleAuthorizationFailureIfNeeded( + error, + owner: .foreground(route: activeRoute) + ) else { return false } markMacConnectionUnavailableIfNeeded(after: error) applyOperationalError(error) return false @@ -6167,7 +6151,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return true } catch { guard generation == connectionGeneration else { return false } - guard !disconnectForAuthorizationFailureIfNeeded(error) else { return false } + guard !handleAuthorizationFailureIfNeeded( + error, + owner: .foreground(route: activeRoute) + ) else { return false } markMacConnectionUnavailableIfNeeded(after: error) applyOperationalError(error) return false @@ -6230,7 +6217,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // force-refresh + retry) must drive the re-auth prompt instead of a // silently stale live frame. if remoteClient === client { - _ = disconnectForAuthorizationFailureIfNeeded(error) + _ = handleAuthorizationFailureIfNeeded( + error, + owner: .foreground(route: activeRoute) + ) } return .failed } @@ -7273,7 +7263,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // definitive auth failure here (after the RPC layer's // force-refresh-and-retry already gave up) must drive the re-auth // prompt instead of silently leaving a stale frame. - guard !self.disconnectForAuthorizationFailureIfNeeded(error) else { return } + guard !self.handleAuthorizationFailureIfNeeded( + error, + owner: .foreground(route: self.activeRoute) + ) else { return } if let retryToken = self.prepareTerminalReplayFailureRetry( surfaceID: surfaceID, replayBarrierToken: replayBarrierTokenForRequest diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift index 4e203fa5ef00..64296f51c822 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingManualHostTrust.swift @@ -47,6 +47,15 @@ enum PendingManualHostTrust { } } + var pairedMacDeviceID: String? { + switch self { + case let .manual(_, _, _, _, _, pairedMacDeviceID, _, _, _): + pairedMacDeviceID + case .pairingURL: + nil + } + } + func approving(route: CmxAttachRoute) -> PendingManualHostTrust { switch self { case .manual: diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingWorkspaceOpenIntent.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingWorkspaceOpenIntent.swift new file mode 100644 index 000000000000..cd537844c663 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/PendingWorkspaceOpenIntent.swift @@ -0,0 +1,13 @@ +import CmuxMobileShellModel +import Foundation + +/// A workspace tap suspended while its owning Mac waits for manual-host approval. +struct PendingWorkspaceOpenIntent { + let rowWorkspaceID: MobileWorkspacePreview.ID + let remoteWorkspaceID: MobileWorkspacePreview.ID + let ownerMacDeviceID: String? + let workspaceHadUnread: Bool + let terminalCount: Int + let isPinned: Bool + let macSwitchAttemptID: UUID +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/WorkspaceMutationTarget.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/WorkspaceMutationTarget.swift index 045fb796fc1f..39a76d3aadba 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/WorkspaceMutationTarget.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/WorkspaceMutationTarget.swift @@ -5,6 +5,7 @@ import CmuxMobileShellModel /// Routing target for a workspace mutation in the aggregated multi-Mac list. struct WorkspaceMutationTarget { let client: MobileCoreRPCClient? + let route: CmxAttachRoute? let isForeground: Bool let macDeviceID: String? } diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift index 878314c733a8..cd4d801c8c58 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -13,6 +13,8 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin private let sessionIdentifier: String private let trustDuration: TimeInterval private let now: @Sendable () -> Date + private var persistedExpirations: [String: TimeInterval] + private var trustedScopes: [MobileManualHostTrustScope: TimeInterval] /// Creates a same-session manual-host trust store. /// - Parameters: @@ -33,6 +35,12 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin self.sessionIdentifier = sessionIdentifier self.trustDuration = trustDuration self.now = now + let persistedExpirations = Self.loadTrustedExpirations(defaults: defaults, key: key) + self.persistedExpirations = persistedExpirations + self.trustedScopes = Self.loadTrustedScopes( + from: persistedExpirations, + sessionIdentifier: sessionIdentifier + ) } /// Creates a same-session manual-host trust store in a named defaults suite. @@ -49,32 +57,39 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin trustDuration: TimeInterval = UserDefaultsMobileManualHostTrustStore.defaultTrustDuration, now: @escaping @Sendable () -> Date = { Date() } ) { + let resolvedDefaults: UserDefaults if let suiteDefaults = UserDefaults(suiteName: suiteName) { - self.defaults = suiteDefaults + resolvedDefaults = suiteDefaults } else { assertionFailure("Failed to resolve UserDefaults suite \(suiteName); falling back to .standard") manualHostTrustStoreLog.error( "failed to resolve UserDefaults suite \(suiteName, privacy: .public); falling back to standard defaults" ) - self.defaults = .standard + resolvedDefaults = .standard } + self.defaults = resolvedDefaults self.key = key self.sessionIdentifier = sessionIdentifier self.trustDuration = trustDuration self.now = now + let persistedExpirations = Self.loadTrustedExpirations(defaults: resolvedDefaults, key: key) + self.persistedExpirations = persistedExpirations + self.trustedScopes = Self.loadTrustedScopes( + from: persistedExpirations, + sessionIdentifier: sessionIdentifier + ) } /// Returns whether the given host/port/account scope is already trusted and unexpired. /// - Parameter scope: The scope to look up. public func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { - var trusted = trustedExpirations() - let scopedKey = sessionStorageKey(for: scope) - guard let expiresAt = trusted[scopedKey] else { + guard let expiresAt = trustedScopes[scope] else { return false } guard expiresAt > now().timeIntervalSince1970 else { - trusted.removeValue(forKey: scopedKey) - defaults.set(trusted, forKey: key) + trustedScopes.removeValue(forKey: scope) + persistedExpirations.removeValue(forKey: sessionStorageKey(for: scope)) + defaults.set(persistedExpirations, forKey: key) return false } return true @@ -85,19 +100,29 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin public func trust(_ scope: MobileManualHostTrustScope) async { guard !Task.isCancelled else { return } let currentTime = now().timeIntervalSince1970 - var trusted = trustedExpirations().filter { _, expiresAt in + persistedExpirations = persistedExpirations.filter { _, expiresAt in expiresAt > currentTime } - trusted[sessionStorageKey(for: scope)] = currentTime + trustDuration - defaults.set(trusted, forKey: key) + trustedScopes = trustedScopes.filter { _, expiresAt in + expiresAt > currentTime + } + let expiresAt = currentTime + trustDuration + trustedScopes[scope] = expiresAt + persistedExpirations[sessionStorageKey(for: scope)] = expiresAt + defaults.set(persistedExpirations, forKey: key) } /// Removes every stored approval. public func removeAll() async { + persistedExpirations.removeAll() + trustedScopes.removeAll() defaults.removeObject(forKey: key) } - private func trustedExpirations() -> [String: TimeInterval] { + nonisolated private static func loadTrustedExpirations( + defaults: UserDefaults, + key: String + ) -> [String: TimeInterval] { guard let raw = defaults.dictionary(forKey: key) else { return [:] } @@ -112,6 +137,32 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin return trusted } + nonisolated private static func loadTrustedScopes( + from persistedExpirations: [String: TimeInterval], + sessionIdentifier: String + ) -> [MobileManualHostTrustScope: TimeInterval] { + let sessionPrefix = sessionIdentifier.mobileManualHostTrustStorageEscaped + "|" + var trustedScopes: [MobileManualHostTrustScope: TimeInterval] = [:] + for (storageKey, expiresAt) in persistedExpirations { + guard storageKey.hasPrefix(sessionPrefix) else { continue } + let components = storageKey.dropFirst(sessionPrefix.count).split( + separator: "|", + omittingEmptySubsequences: false + ) + guard components.count == 3, + let port = Int(components[2]), + let scope = MobileManualHostTrustScope( + host: String(components[1]).mobileManualHostTrustStorageUnescaped, + port: port, + stackUserID: String(components[0]).mobileManualHostTrustStorageUnescaped + ) else { + continue + } + trustedScopes[scope] = expiresAt + } + return trustedScopes + } + private func sessionStorageKey(for scope: MobileManualHostTrustScope) -> String { [ sessionIdentifier.mobileManualHostTrustStorageEscaped, @@ -126,4 +177,10 @@ private extension String { .replacing("%", with: "%25") .replacing("|", with: "%7C") } + + var mobileManualHostTrustStorageUnescaped: String { + self + .replacing("%7C", with: "|") + .replacing("%25", with: "%") + } } From fd3e691b9748bc805bc37c84c7426de457a9801c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 15:32:00 -0700 Subject: [PATCH 52/91] test(ios): cover manual host connection ownership races --- .../MobilePairingAttemptDeadlineTests.swift | 27 ++++++ ...anualHostAuthorizationOwnershipTests.swift | 67 ++++++++++++++ .../MobileShellManualHostReconnectTests.swift | 87 +++++++++++++++++++ ...leShellRenderGridLivenessTestSupport.swift | 11 +++ ...outeSelectiveFailureTransportFactory.swift | 17 ++++ 5 files changed, 209 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RouteSelectiveFailureTransportFactory.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 10e242fbf8c6..9844dc2b38c4 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -46,6 +46,33 @@ import Testing #expect(store.connectionState == .disconnected) } + @Test func cancelInFlightPairingKeepsExistingConnection() async throws { + let clock = TestClock() + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let transport = CountingSlowIgnoringCancellationTransport() + let runtime = PairingDeadlineRuntime( + transportFactory: CountingSlowIgnoringCancellationTransportFactory(transport: transport) + ) + let store = makeStore(runtime: runtime, connectionState: .connected) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + let originalClient = try #require(store.remoteClient) + + let pairing = Task { @MainActor in + await store.connectPairingURLResult(Self.qrURL) + } + let started = try await pollUntil { + await transport.connectCount() == 1 + } + #expect(started) + store.cancelPairing() + await transport.releaseStuckConnects() + _ = await pairing.value + + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + } + @Test func mixedTrustedAndUntrustedRoutesStillConnectOverTrustedRoute() async throws { let clock = TestClock() let router = LivenessHostRouter() diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift index 546b1001e0fe..c94dc77a0660 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift @@ -148,6 +148,73 @@ import Testing #expect(store.secondaryMacSubscriptions["secondary-mac"] == nil) } + @Test func staleForegroundAuthorizationFailureDoesNotDisconnectReplacementClient() async throws { + let oldRouter = LivenessHostRouter() + let oldRuntime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: oldRouter, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.debugLoopback], + supportsServerPushEvents: false + ) + let oldRoute = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: 56_584) + let newRoute = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: 56_585) + let oldTicket = try ticket(route: oldRoute, macDeviceID: "old-mac", authToken: "old-ticket") + let newTicket = try ticket(route: newRoute, macDeviceID: "new-mac", authToken: "new-ticket") + let newClient = MobileCoreRPCClient(runtime: oldRuntime, route: newRoute, ticket: newTicket) + let store = MobileShellComposite.preview(runtime: oldRuntime) + store.signIn() + #expect(await store.connectPairingURL(try attachURL(for: oldTicket))) + let capabilities = MobileWorkspaceActionCapabilities(supportsWorkspaceActions: true) + let workspace = MobileWorkspacePreview( + id: "old-workspace", + macDeviceID: "old-mac", + name: "Old Workspace", + terminals: [] + ) + store.setWorkspaceStatesForTesting([ + "old-mac": MacWorkspaceState( + macDeviceID: "old-mac", + workspaces: [workspace], + status: .connected, + actionCapabilities: capabilities + ), + ], foregroundMacDeviceID: "old-mac") + let rowID = try #require(store.workspaces.first?.id) + await oldRouter.holdAuthorizationFailure(for: "workspace.action") + + let rename = Task { @MainActor in + await store.renameWorkspace(id: rowID, title: "Renamed") + } + await oldRouter.waitForCount(of: "workspace.action", atLeast: 1) + store.remoteClient = newClient + store.setWorkspaceStatesForTesting([:], foregroundMacDeviceID: "new-mac") + await oldRouter.releaseAllHeld() + _ = await rename.value + + #expect(store.connectionState == .connected) + #expect(store.remoteClient === newClient) + #expect(store.foregroundMacDeviceIDForTesting() == "new-mac") + #expect(store.manualHostTrustWarning == nil) + #expect(!store.connectionRequiresReauth) + } + + private func ticket( + route: CmxAttachRoute, + macDeviceID: String, + authToken: String + ) throws -> CmxAttachTicket { + try CmxAttachTicket( + workspaceID: "", + terminalID: nil, + macDeviceID: macDeviceID, + macDisplayName: macDeviceID, + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [route], + expiresAt: Date().addingTimeInterval(3_600), + authToken: authToken + ) + } + private func hostPortRoute( kind: CmxAttachTransportKind, host: String, diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift index e5d8d4eba346..3d296347e52a 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift @@ -317,6 +317,93 @@ import Testing #expect(attempts.count(.tailscale) == 0) } + @Test func failedRegistryConnectDoesNotAcceptExistingConnectionAtSameEndpoint() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let oldRoute = try CmxAttachRoute( + id: "old-route", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.5", port: CmxMobileDefaults.defaultHostPort) + ) + let targetRoute = try CmxAttachRoute( + id: "target-route", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.5", port: CmxMobileDefaults.defaultHostPort) + ) + try await pairedMacStore.upsert( + macDeviceID: "old-mac", + displayName: "Old Mac", + routes: [oldRoute], + markActive: true, + stackUserID: "phone-user", + teamID: nil, + now: Date().addingTimeInterval(-10) + ) + try await pairedMacStore.upsert( + macDeviceID: "target-mac", + displayName: "Target Mac", + routes: [targetRoute], + markActive: false, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: RouteSelectiveFailureTransportFactory( + failingRouteID: targetRoute.id, + router: router, + box: TransportBox() + ), + now: { Date() }, + supportedRouteKinds: [.tailscale], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + store.signIn() + await store.loadPairedMacs() + let oldTicket = try CmxAttachTicket( + workspaceID: "", + terminalID: nil, + macDeviceID: "old-mac", + macDisplayName: "Old Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [oldRoute], + expiresAt: Date().addingTimeInterval(3_600), + authToken: "old-ticket" + ) + #expect(await store.connectPairingURL(try attachURL(for: oldTicket))) + let device = RegistryDevice( + deviceId: "target-mac", + platform: "mac", + displayName: "Target Mac", + lastSeenAt: Date(), + instances: [] + ) + let instance = RegistryAppInstance(tag: "stale", routes: [targetRoute], lastSeenAt: Date()) + + await store.connectToRegistryInstance(device: device, instance: instance) + + let activeIDs = try await pairedMacStore + .loadAll(stackUserID: "phone-user", teamID: nil) + .filter(\.isActive) + .map(\.macDeviceID) + #expect(activeIDs == ["old-mac"]) + #expect(store.connectionState == .connected) + #expect(store.foregroundMacDeviceIDForTesting() == "old-mac") + } + private func hostPortRoute(kind: CmxAttachTransportKind, host: String) throws -> CmxAttachRoute { try CmxAttachRoute( id: kind.rawValue, diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift index 9165439ff8b6..de8ae69e2d40 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift @@ -83,6 +83,7 @@ actor LivenessHostRouter { private var replayTexts: [String] = [] private var replayFailuresRemaining = 0 private var emptyReplayResponsesRemaining = 0; private var viewportEffectiveGridOverride: LivenessViewportReport?; private var emptyViewportResponsesRemaining = 0 + private var heldAuthorizationFailureMethods: Set = [] func record(method: String?, topics: [String]?) { recorded.append(RecordedRequest(method: method, topics: topics)) @@ -237,6 +238,11 @@ actor LivenessHostRouter { heldReplayResponsesRemaining += count } + /// Hold the next request for `method`, then answer it as unauthorized once released. + func holdAuthorizationFailure(for method: String) { + heldAuthorizationFailureMethods.insert(method) + } + /// Hold the Nth `mobile.terminal.viewport` response (1-based), allowing a /// later viewport report to acknowledge before an older one. func holdViewportRequest(number: Int) { @@ -267,6 +273,11 @@ actor LivenessHostRouter { } func response(method: String?, id: String?, viewportReport: LivenessViewportReport? = nil) async -> Data? { + if let method, + heldAuthorizationFailureMethods.remove(method) != nil { + await park() + return try? Self.errorFrame(id: id, message: "Unauthorized") + } switch method { case "mobile.attach_ticket.create": return try? Self.resultFrame(id: id, result: ["ticket": Self.attachTicketObject()]) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RouteSelectiveFailureTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RouteSelectiveFailureTransportFactory.swift new file mode 100644 index 000000000000..dddebcf76b6f --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RouteSelectiveFailureTransportFactory.swift @@ -0,0 +1,17 @@ +import CMUXMobileCore +import CmuxMobileRPC + +struct RouteSelectiveFailureTransportFactory: CmxByteTransportFactory { + let failingRouteID: String + let router: LivenessHostRouter + let box: TransportBox + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + if route.id == failingRouteID { + return SlowIgnoringCancellationTransport() + } + let transport = LivenessTransport(router: router) + box.set(transport) + return transport + } +} From 84796c1cd959bc6bd4cf113994fcd5c42aad521d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 15:37:35 -0700 Subject: [PATCH 53/91] Add failing manual host security regressions --- .../ControllablePathChangeReachability.swift | 46 ++++++++ .../HeldAuthorizationFailureTransport.swift | 110 ++++++++++++++++++ ...nualFallbackApprovalTransportFactory.swift | 2 + .../MobilePairingAttemptDeadlineTests.swift | 27 ----- ...CancellationPreservesForegroundTests.swift | 40 +++++++ .../MobileShellAuthScopeIsolationTests.swift | 76 ++++++++++++ ...anualHostAuthorizationOwnershipTests.swift | 13 ++- ...bileShellManualHostNetworkEpochTests.swift | 68 +++++++++++ ...leShellRenderGridLivenessTestSupport.swift | 11 -- .../ReconnectRouteSelectionTests.swift | 10 ++ .../RecordedAuthLivenessTransport.swift | 109 +++++++++++++++++ 11 files changed, 469 insertions(+), 43 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ControllablePathChangeReachability.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransport.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransport.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ControllablePathChangeReachability.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ControllablePathChangeReachability.swift new file mode 100644 index 000000000000..5096e1131587 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ControllablePathChangeReachability.swift @@ -0,0 +1,46 @@ +import CmuxMobileShellModel +import CmuxMobileTransport + +struct ControllablePathChangeReachability: ReachabilityProviding, Sendable { + private let stream: AsyncStream + private let continuation: AsyncStream.Continuation + + init() { + let pair = AsyncStream.makeStream() + stream = pair.stream + continuation = pair.continuation + } + + var isOnline: Bool { get async { true } } + + func pathChanges() -> AsyncStream { stream } + + func emitPathChange() { continuation.yield(()) } +} + +actor NetworkEpochManualHostTrustStore: MobileManualHostTrustStoring { + private var scopes: Set = [] + private var didRemoveAll = false + private var removeWaiters: [CheckedContinuation] = [] + + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + scopes.contains(scope) + } + + func trust(_ scope: MobileManualHostTrustScope) async { + scopes.insert(scope) + } + + func removeAll() async { + scopes.removeAll() + didRemoveAll = true + let waiters = removeWaiters + removeWaiters.removeAll() + for waiter in waiters { waiter.resume() } + } + + func waitUntilRemoved() async { + if didRemoveAll { return } + await withCheckedContinuation { removeWaiters.append($0) } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransport.swift new file mode 100644 index 000000000000..666c2b94f927 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransport.swift @@ -0,0 +1,110 @@ +import CMUXMobileCore +import CmuxMobileRPC +import Foundation + +actor HeldAuthorizationFailureGate { + private var didReachHeldRequest = false + private var reachedWaiters: [CheckedContinuation] = [] + private var releaseWaiters: [CheckedContinuation] = [] + + func waitUntilReached() async { + if didReachHeldRequest { return } + await withCheckedContinuation { reachedWaiters.append($0) } + } + + func holdUntilReleased() async { + didReachHeldRequest = true + let waiters = reachedWaiters + reachedWaiters.removeAll() + for waiter in waiters { waiter.resume() } + await withCheckedContinuation { releaseWaiters.append($0) } + } + + func release() { + let waiters = releaseWaiters + releaseWaiters.removeAll() + for waiter in waiters { waiter.resume() } + } +} + +struct HeldAuthorizationFailureTransportFactory: CmxByteTransportFactory { + let method: String + let gate: HeldAuthorizationFailureGate + let router: LivenessHostRouter + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + _ = route + return HeldAuthorizationFailureTransport(method: method, gate: gate, router: router) + } +} + +actor HeldAuthorizationFailureTransport: CmxByteTransport { + private let method: String + private let gate: HeldAuthorizationFailureGate + private let router: LivenessHostRouter + private var pendingFrames: [Data] = [] + private var receiveWaiters: [CheckedContinuation] = [] + private var isClosed = false + + init(method: String, gate: HeldAuthorizationFailureGate, router: LivenessHostRouter) { + self.method = method + self.gate = gate + self.router = router + } + + func connect() async throws {} + + func receive() async throws -> Data? { + if !pendingFrames.isEmpty { return pendingFrames.removeFirst() } + if isClosed { return nil } + return await withCheckedContinuation { receiveWaiters.append($0) } + } + + func send(_ data: Data) async throws { + var buffer = data + let payloads = try MobileSyncFrameCodec.decodeFrames(from: &buffer) + for payload in payloads { + let request = (try? JSONSerialization.jsonObject(with: payload)) as? [String: Any] + let requestMethod = request?["method"] as? String + let requestID = request?["id"] as? String + let params = request?["params"] as? [String: Any] + let topics = params?["topics"] as? [String] + await router.record(method: requestMethod, topics: topics) + Task { [method, gate, router, weak self] in + let response: Data? + if requestMethod == method { + await gate.holdUntilReleased() + response = try? Self.errorFrame(id: requestID, message: "Unauthorized") + } else { + response = await router.response(method: requestMethod, id: requestID) + } + guard let response else { return } + await self?.deliver(response) + } + } + } + + func close() async { + isClosed = true + let waiters = receiveWaiters + receiveWaiters.removeAll() + for waiter in waiters { waiter.resume(returning: nil) } + } + + private func deliver(_ frame: Data) { + if !receiveWaiters.isEmpty { + receiveWaiters.removeFirst().resume(returning: frame) + } else { + pendingFrames.append(frame) + } + } + + private static func errorFrame(id: String?, message: String) throws -> Data { + let envelope: [String: Any] = [ + "id": id ?? UUID().uuidString, + "ok": false, + "error": ["message": message], + ] + return try MobileSyncFrameCodec.encodeFrame(JSONSerialization.data(withJSONObject: envelope)) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift index beb146e3ae25..2b9f2060eb67 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift @@ -1,6 +1,8 @@ import CMUXMobileCore import Foundation +/// Synchronous test probe: every access to mutable state is serialized by `lock`, +/// and no locked region crosses an async suspension point. final class RouteAttemptRecorder: @unchecked Sendable { private let lock = NSLock() private var counts: [CmxAttachTransportKind: Int] = [:] diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 9844dc2b38c4..10e242fbf8c6 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -46,33 +46,6 @@ import Testing #expect(store.connectionState == .disconnected) } - @Test func cancelInFlightPairingKeepsExistingConnection() async throws { - let clock = TestClock() - let oldRouter = LivenessHostRouter() - let oldBox = TransportBox() - let transport = CountingSlowIgnoringCancellationTransport() - let runtime = PairingDeadlineRuntime( - transportFactory: CountingSlowIgnoringCancellationTransportFactory(transport: transport) - ) - let store = makeStore(runtime: runtime, connectionState: .connected) - try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) - let originalClient = try #require(store.remoteClient) - - let pairing = Task { @MainActor in - await store.connectPairingURLResult(Self.qrURL) - } - let started = try await pollUntil { - await transport.connectCount() == 1 - } - #expect(started) - store.cancelPairing() - await transport.releaseStuckConnects() - _ = await pairing.value - - #expect(store.connectionState == .connected) - #expect(store.remoteClient === originalClient) - } - @Test func mixedTrustedAndUntrustedRoutesStillConnectOverTrustedRoute() async throws { let clock = TestClock() let router = LivenessHostRouter() diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift new file mode 100644 index 000000000000..926c456f0dbb --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift @@ -0,0 +1,40 @@ +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct MobilePairingCancellationPreservesForegroundTests { + @Test func cancelInFlightPairingKeepsExistingConnection() async throws { + let clock = TestClock() + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let transport = CountingSlowIgnoringCancellationTransport() + let runtime = PairingDeadlineRuntime( + transportFactory: CountingSlowIgnoringCancellationTransportFactory(transport: transport) + ) + let store = MobileShellComposite( + runtime: runtime, + isSignedIn: true, + connectionState: .connected, + reachability: AlwaysOnlineReachability(), + pairingHintDefaults: UserDefaults(suiteName: "pairing-cancel-\(UUID().uuidString)")! + ) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + let originalClient = try #require(store.remoteClient) + + let pairing = Task { @MainActor in + await store.connectPairingURLResult("cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465") + } + let started = try await pollUntil { + await transport.connectCount() == 1 + } + #expect(started) + store.cancelPairing() + await transport.releaseStuckConnects() + _ = await pairing.value + + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift new file mode 100644 index 000000000000..be5b489fdba7 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift @@ -0,0 +1,76 @@ +import CMUXMobileCore +import CmuxMobilePairedMac +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct MobileShellAuthScopeIsolationTests { + @Test func accountSwitchDuringDirectSecondaryRefreshNeverSendsNewTokenToOldManualHost() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString, + isDirectory: true + ) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let route = try CmxAttachRoute( + id: "manual-host-a", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465) + ) + try await pairedMacStore.upsert( + macDeviceID: "user-a-mac", + displayName: "User A Mac", + routes: [route], + markActive: false, + stackUserID: "user-a", + teamID: nil, + now: Date() + ) + let trustStore = InMemoryMobileManualHostTrustStore() + let trustScope = try #require(MobileManualHostTrustScope(route: route, stackUserID: "user-a")) + await trustStore.trust(trustScope) + let tokenProvider = BlockingAccountSwitchTokenProvider() + let tokenSink = RecordedAuthTokenSink() + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: RecordedAuthLivenessTransportFactory( + router: router, + tokenSink: tokenSink + ), + stackAccessTokenProvider: { try await tokenProvider.tokenIgnoringCancellation() }, + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let identity = StaticIdentityProvider(userID: "user-a") + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: identity, + reachability: AlwaysOnlineReachability(), + pairingHintDefaults: UserDefaults(suiteName: "auth-scope-pairing-\(UUID().uuidString)")!, + multiMacAggregationDefaults: UserDefaults(suiteName: "auth-scope-aggregation-\(UUID().uuidString)")!, + manualHostTrustStore: trustStore + ) + store.signIn() + + let refresh = Task { @MainActor in + await store.refreshSecondaryMacWorkspaces() + } + await tokenProvider.waitUntilRequested() + store.signOut() + identity.currentUserID = "user-b" + store.signIn() + await tokenProvider.release(with: "user-b-token") + await refresh.value + + #expect(await tokenSink.recordedTokens().isEmpty) + #expect(store.secondaryMacSubscriptions["user-a-mac"] == nil) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift index c94dc77a0660..1825bf2283a8 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift @@ -150,8 +150,13 @@ import Testing @Test func staleForegroundAuthorizationFailureDoesNotDisconnectReplacementClient() async throws { let oldRouter = LivenessHostRouter() + let failureGate = HeldAuthorizationFailureGate() let oldRuntime = LivenessTestRuntime( - transportFactory: LivenessTransportFactory(router: oldRouter, box: TransportBox()), + transportFactory: HeldAuthorizationFailureTransportFactory( + method: "workspace.action", + gate: failureGate, + router: oldRouter + ), now: { Date() }, supportedRouteKinds: [.debugLoopback], supportsServerPushEvents: false @@ -180,15 +185,13 @@ import Testing ), ], foregroundMacDeviceID: "old-mac") let rowID = try #require(store.workspaces.first?.id) - await oldRouter.holdAuthorizationFailure(for: "workspace.action") - let rename = Task { @MainActor in await store.renameWorkspace(id: rowID, title: "Renamed") } - await oldRouter.waitForCount(of: "workspace.action", atLeast: 1) + await failureGate.waitUntilReached() store.remoteClient = newClient store.setWorkspaceStatesForTesting([:], foregroundMacDeviceID: "new-mac") - await oldRouter.releaseAllHeld() + await failureGate.release() _ = await rename.value #expect(store.connectionState == .connected) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift new file mode 100644 index 000000000000..b0b4b7ef1dd8 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift @@ -0,0 +1,68 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct MobileShellManualHostNetworkEpochTests { + @Test func pathChangeSupersedesPendingManualHostApprovalWithoutTouchingForeground() async throws { + let reachability = ControllablePathChangeReachability() + let trustStore = NetworkEpochManualHostTrustStore() + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.debugLoopback, .manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: reachability, + manualHostTrustStore: trustStore + ) + store.signIn() + let foregroundRoute = try CmxAttachRoute( + id: "foreground", + kind: .debugLoopback, + endpoint: .hostPort(host: "127.0.0.1", port: 56_584) + ) + let foregroundTicket = try CmxAttachTicket( + workspaceID: "live-workspace", + terminalID: "live-terminal", + macDeviceID: "foreground-mac", + macDisplayName: "Foreground Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [foregroundRoute], + expiresAt: Date().addingTimeInterval(3_600), + authToken: "foreground-ticket" + ) + #expect(await store.connectPairingURL(try attachURL(for: foregroundTicket))) + let foregroundClient = try #require(store.remoteClient) + let queued = await store.connectManualHost( + name: "LAN Mac", + host: "192.168.1.77", + port: 58_465 + ) + let scope = try #require(MobileManualHostTrustScope( + host: "192.168.1.77", + port: 58_465, + stackUserID: "phone-user" + )) + #expect(queued == .needsUserApproval) + store.startObservingNetworkPathChanges() + + reachability.emitPathChange() + await trustStore.waitUntilRemoved() + let result = await store.acceptManualHostTrustWarning() + + #expect(result == .superseded) + #expect(store.manualHostTrustWarning == nil) + #expect(await trustStore.isTrusted(scope) == false) + #expect(await router.count(of: "mobile.attach_ticket.create") == 0) + #expect(store.connectionState == .connected) + #expect(store.remoteClient === foregroundClient) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift index de8ae69e2d40..9165439ff8b6 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift @@ -83,7 +83,6 @@ actor LivenessHostRouter { private var replayTexts: [String] = [] private var replayFailuresRemaining = 0 private var emptyReplayResponsesRemaining = 0; private var viewportEffectiveGridOverride: LivenessViewportReport?; private var emptyViewportResponsesRemaining = 0 - private var heldAuthorizationFailureMethods: Set = [] func record(method: String?, topics: [String]?) { recorded.append(RecordedRequest(method: method, topics: topics)) @@ -238,11 +237,6 @@ actor LivenessHostRouter { heldReplayResponsesRemaining += count } - /// Hold the next request for `method`, then answer it as unauthorized once released. - func holdAuthorizationFailure(for method: String) { - heldAuthorizationFailureMethods.insert(method) - } - /// Hold the Nth `mobile.terminal.viewport` response (1-based), allowing a /// later viewport report to acknowledge before an older one. func holdViewportRequest(number: Int) { @@ -273,11 +267,6 @@ actor LivenessHostRouter { } func response(method: String?, id: String?, viewportReport: LivenessViewportReport? = nil) async -> Data? { - if let method, - heldAuthorizationFailureMethods.remove(method) != nil { - await park() - return try? Self.errorFrame(id: id, message: "Unauthorized") - } switch method { case "mobile.attach_ticket.create": return try? Self.resultFrame(id: id, result: ["ticket": Self.attachTicketObject()]) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index fdf74a10f097..62ee52574684 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -99,6 +99,16 @@ import Testing #expect(route.endpoint == .hostPort(host: "192.168.1.77", port: 50906)) } + @Test func invalidManualHostCannotConstructRoute() { + do { + _ = try MobileShellRouteSelection().manualHostRoute( + host: "https://studio-mac.local/path", + port: 50_906 + ) + Issue.record("Expected invalid manual host route construction to fail closed") + } catch {} + } + @Test func reconnectCandidatesKeepFallbackRoutesAfterPreferredRoute() throws { let candidates = MobileShellComposite.reconnectHostPortRoutes( [try loopback(), try tailscale()], diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransport.swift new file mode 100644 index 000000000000..0f6e2baaca6e --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransport.swift @@ -0,0 +1,109 @@ +import CMUXMobileCore +import CmuxMobileRPC +import Foundation + +actor RecordedAuthTokenSink { + private var tokens: [String] = [] + + func record(_ token: String?) { + guard let token else { return } + tokens.append(token) + } + + func recordedTokens() -> [String] { tokens } +} + +struct RecordedAuthLivenessTransportFactory: CmxByteTransportFactory { + let router: LivenessHostRouter + let tokenSink: RecordedAuthTokenSink + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + _ = route + return RecordedAuthLivenessTransport(router: router, tokenSink: tokenSink) + } +} + +actor RecordedAuthLivenessTransport: CmxByteTransport { + private let router: LivenessHostRouter + private let tokenSink: RecordedAuthTokenSink + private var pendingFrames: [Data] = [] + private var receiveWaiters: [CheckedContinuation] = [] + private var isClosed = false + + init(router: LivenessHostRouter, tokenSink: RecordedAuthTokenSink) { + self.router = router + self.tokenSink = tokenSink + } + + func connect() async throws {} + + func receive() async throws -> Data? { + if !pendingFrames.isEmpty { return pendingFrames.removeFirst() } + if isClosed { return nil } + return await withCheckedContinuation { receiveWaiters.append($0) } + } + + func send(_ data: Data) async throws { + var buffer = data + let payloads = try MobileSyncFrameCodec.decodeFrames(from: &buffer) + for payload in payloads { + let request = (try? JSONSerialization.jsonObject(with: payload)) as? [String: Any] + let requestMethod = request?["method"] as? String + let requestID = request?["id"] as? String + let params = request?["params"] as? [String: Any] + let topics = params?["topics"] as? [String] + let auth = request?["auth"] as? [String: Any] + await tokenSink.record(auth?["stack_access_token"] as? String) + await router.record(method: requestMethod, topics: topics) + Task { [router, weak self] in + guard let response = await router.response(method: requestMethod, id: requestID) else { + return + } + await self?.deliver(response) + } + } + } + + func close() async { + isClosed = true + let waiters = receiveWaiters + receiveWaiters.removeAll() + for waiter in waiters { waiter.resume(returning: nil) } + } + + private func deliver(_ frame: Data) { + if !receiveWaiters.isEmpty { + receiveWaiters.removeFirst().resume(returning: frame) + } else { + pendingFrames.append(frame) + } + } +} + +actor BlockingAccountSwitchTokenProvider { + private var didEnter = false + private var enteredWaiters: [CheckedContinuation] = [] + private var releaseWaiters: [CheckedContinuation] = [] + private var token = "user-a-token" + + func waitUntilRequested() async { + if didEnter { return } + await withCheckedContinuation { enteredWaiters.append($0) } + } + + func tokenIgnoringCancellation() async throws -> String { + didEnter = true + let waiters = enteredWaiters + enteredWaiters.removeAll() + for waiter in waiters { waiter.resume() } + await withCheckedContinuation { releaseWaiters.append($0) } + return token + } + + func release(with token: String) { + self.token = token + let waiters = releaseWaiters + releaseWaiters.removeAll() + for waiter in waiters { waiter.resume() } + } +} From dc019a604f74d704478d9de055da7e30fc684f03 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 15:51:07 -0700 Subject: [PATCH 54/91] test(ios): cover manual host scope generations --- ...ingSlowIgnoringCancellationTransport.swift | 11 +++ ...CancellationPreservesForegroundTests.swift | 5 +- .../MobileShellAuthScopeIsolationTests.swift | 21 +++++- ...anualHostAuthorizationOwnershipTests.swift | 75 +++++++++++++++++++ 4 files changed, 106 insertions(+), 6 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/CountingSlowIgnoringCancellationTransport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/CountingSlowIgnoringCancellationTransport.swift index 666509bf6069..81576bd750c6 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/CountingSlowIgnoringCancellationTransport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/CountingSlowIgnoringCancellationTransport.swift @@ -4,11 +4,17 @@ import Foundation actor CountingSlowIgnoringCancellationTransport: CmxByteTransport { private var connects = 0 + private var connectWaiters: [CheckedContinuation] = [] private var releaseContinuations: [CheckedContinuation] = [] private var isReleased = false func connect() async throws { connects += 1 + let waiters = connectWaiters + connectWaiters.removeAll() + for waiter in waiters { + waiter.resume() + } await waitUntilReleased() throw MobileShellConnectionError.requestTimedOut } @@ -25,6 +31,11 @@ actor CountingSlowIgnoringCancellationTransport: CmxByteTransport { connects } + func waitUntilConnectStarted() async { + if connects > 0 { return } + await withCheckedContinuation { connectWaiters.append($0) } + } + func releaseStuckConnects() { isReleased = true let continuations = releaseContinuations diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift index 926c456f0dbb..c28bc41ce006 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift @@ -26,10 +26,7 @@ import Testing let pairing = Task { @MainActor in await store.connectPairingURLResult("cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465") } - let started = try await pollUntil { - await transport.connectCount() == 1 - } - #expect(started) + await transport.waitUntilConnectStarted() store.cancelPairing() await transport.releaseStuckConnects() _ = await pairing.value diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift index be5b489fdba7..102bc9998f37 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift @@ -8,6 +8,23 @@ import Testing @MainActor @Suite struct MobileShellAuthScopeIsolationTests { @Test func accountSwitchDuringDirectSecondaryRefreshNeverSendsNewTokenToOldManualHost() async throws { + try await assertSessionChangeNeverSendsNewToken( + replacementUserID: "user-b", + replacementToken: "user-b-token" + ) + } + + @Test func sameAccountSignOutAndSignInInvalidatesOldSecondaryRefresh() async throws { + try await assertSessionChangeNeverSendsNewToken( + replacementUserID: "user-a", + replacementToken: "new-user-a-session-token" + ) + } + + private func assertSessionChangeNeverSendsNewToken( + replacementUserID: String, + replacementToken: String + ) async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent( UUID().uuidString, isDirectory: true @@ -65,9 +82,9 @@ import Testing } await tokenProvider.waitUntilRequested() store.signOut() - identity.currentUserID = "user-b" + identity.currentUserID = replacementUserID store.signIn() - await tokenProvider.release(with: "user-b-token") + await tokenProvider.release(with: replacementToken) await refresh.value #expect(await tokenSink.recordedTokens().isEmpty) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift index 1825bf2283a8..7aa47d444735 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift @@ -36,6 +36,31 @@ import Testing #expect(connected == .connected) #expect(store.activeRoute?.kind == route.kind) + let secondaryRoute = try hostPortRoute( + kind: .debugLoopback, + host: "127.0.0.1", + port: 56_585 + ) + let secondaryTicket = try ticket( + route: secondaryRoute, + macDeviceID: "secondary-mac", + authToken: "secondary-ticket" + ) + let secondaryClient = MobileCoreRPCClient( + runtime: runtime, + route: secondaryRoute, + ticket: secondaryTicket + ) + let secondarySubscription = SecondaryMacSubscription( + macDeviceID: "secondary-mac", + client: secondaryClient, + route: secondaryRoute, + ticket: secondaryTicket, + supportedHostCapabilities: [], + actionCapabilities: MobileWorkspaceActionCapabilities() + ) + store.secondaryMacSubscriptions["secondary-mac"] = secondarySubscription + await trustStore.removeAll() store.terminalInputText = "pwd" await store.submitTerminalInput() @@ -43,6 +68,7 @@ import Testing #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") #expect(!store.connectionRequiresReauth) #expect(store.connectionState == .disconnected) + #expect(store.secondaryMacSubscriptions["secondary-mac"] === secondarySubscription) let reconnected = await store.acceptManualHostTrustWarning() #expect(reconnected == .connected) @@ -201,6 +227,55 @@ import Testing #expect(!store.connectionRequiresReauth) } + @Test func staleForegroundAuthorizationFailureDoesNotDisconnectNewConnectionGeneration() async throws { + let router = LivenessHostRouter() + let failureGate = HeldAuthorizationFailureGate() + let runtime = LivenessTestRuntime( + transportFactory: HeldAuthorizationFailureTransportFactory( + method: "workspace.action", + gate: failureGate, + router: router + ), + now: { Date() }, + supportedRouteKinds: [.debugLoopback], + supportsServerPushEvents: false + ) + let route = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: 56_584) + let attachTicket = try ticket(route: route, macDeviceID: "foreground-mac", authToken: "ticket") + let store = MobileShellComposite.preview(runtime: runtime) + store.signIn() + #expect(await store.connectPairingURL(try attachURL(for: attachTicket))) + let client = try #require(store.remoteClient) + let capabilities = MobileWorkspaceActionCapabilities(supportsWorkspaceActions: true) + let workspace = MobileWorkspacePreview( + id: "workspace", + macDeviceID: "foreground-mac", + name: "Workspace", + terminals: [] + ) + store.setWorkspaceStatesForTesting([ + "foreground-mac": MacWorkspaceState( + macDeviceID: "foreground-mac", + workspaces: [workspace], + status: .connected, + actionCapabilities: capabilities + ), + ], foregroundMacDeviceID: "foreground-mac") + let rowID = try #require(store.workspaces.first?.id) + let rename = Task { @MainActor in + await store.renameWorkspace(id: rowID, title: "Renamed") + } + await failureGate.waitUntilReached() + store.connectionGeneration = UUID() + await failureGate.release() + _ = await rename.value + + #expect(store.connectionState == .connected) + #expect(store.remoteClient === client) + #expect(store.foregroundMacDeviceIDForTesting() == "foreground-mac") + #expect(!store.connectionRequiresReauth) + } + private func ticket( route: CmxAttachRoute, macDeviceID: String, From 5b9915e89f681a3cd90a3b76be7c3494e6785ac2 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 16:48:26 -0700 Subject: [PATCH 55/91] test(ios): cover final manual-host auth races --- .../MobileCoreRPCManualHostTrustTests.swift | 60 ++++++++++++ .../AccountReplacementTokenProvider.swift | 36 ++++++++ .../MobileShellAuthScopeIsolationTests.swift | 91 +++++++++++++++++++ ...bileShellManualHostNetworkEpochTests.swift | 57 ++++++++++++ .../SignalingManualHostTrustStore.swift | 40 ++++++++ .../MobileRootAuthGateShellSyncTests.swift | 49 ++++++++++ 6 files changed, 333 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AccountReplacementTokenProvider.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SignalingManualHostTrustStore.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootAuthGateShellSyncTests.swift diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift index aa4d2aaf55f4..ae6c3db16047 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift @@ -5,6 +5,66 @@ import Testing @testable import CmuxMobileRPC @Suite struct MobileCoreRPCManualHostTrustTests { + @Test func revokingTrustBlocksTokenBearingWriteAlreadyQueuedBehindBlockedSend() async throws { + let route = try hostPortRoute(kind: .manualHost, host: "192.168.1.20", port: 58_465) + let scope = try #require( + MobileManualHostTrustScope(route: route, stackUserID: "phone-user") + ) + let trustStore = InMemoryMobileManualHostTrustStore() + await trustStore.trust(scope) + let transport = QueuedCancellationProbeTransport() + let runtime = TestMobileSyncRuntime( + transportFactory: QueuedCancellationProbeTransportFactory(transport: transport), + stackAccessToken: "trusted-manual-token", + rpcRequestTimeoutNanoseconds: 60 * 1_000_000_000 + ) + let client = MobileCoreRPCClient( + runtime: runtime, + route: route, + ticket: try qrPairingTicket(route: route), + allowsStackAuthFallback: true, + manualHostStackAuthTrustProvider: { + await trustStore.isTrusted(scope) + } + ) + let blockingID = "trusted-blocking-write" + let queuedID = "revoked-queued-write" + let blockingRequest = try MobileCoreRPCClient.requestData( + method: "workspace.list", + id: blockingID + ) + let queuedRequest = try MobileCoreRPCClient.requestData( + method: "workspace.list", + id: queuedID + ) + + let blockingTask = Task { try await client.sendRequest(blockingRequest) } + let initiallySent = try await transport.waitForSentRequestCount(1) + #expect(initiallySent.map(\.id) == [blockingID]) + + let queuedTask = Task { try await client.sendRequest(queuedRequest) } + for _ in 0..<1_000 { + if await client.session.queuedRequestIDs.contains(queuedID) { break } + await Task.yield() + } + #expect(await client.session.queuedRequestIDs.contains(queuedID)) + + await trustStore.removeAll() + await transport.releaseFirstSend() + for _ in 0..<1_000 { + if !(await client.session.queuedRequestIDs.contains(queuedID)) { break } + await Task.yield() + } + + #expect(!(await client.session.queuedRequestIDs.contains(queuedID))) + #expect(try await transport.sentRequests().map(\.id) == [blockingID]) + + queuedTask.cancel() + blockingTask.cancel() + _ = try? await queuedTask.value + _ = try? await blockingTask.value + } + @Test func revokingTrustBlocksNextRequestOnExistingManualHostClient() async throws { let route = try hostPortRoute(kind: .manualHost, host: "192.168.1.20", port: 58_465) let scope = try #require( diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AccountReplacementTokenProvider.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AccountReplacementTokenProvider.swift new file mode 100644 index 000000000000..636b54dfdd2c --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AccountReplacementTokenProvider.swift @@ -0,0 +1,36 @@ +actor AccountReplacementTokenProvider { + private var requestCount = 0 + private var requestCountWaiters: [( + expected: Int, + continuation: CheckedContinuation + )] = [] + private var releaseContinuations: [Int: CheckedContinuation] = [:] + + func token() async throws -> String { + requestCount += 1 + let requestIndex = requestCount + let readyWaiters = requestCountWaiters.filter { $0.expected <= requestCount } + requestCountWaiters.removeAll { $0.expected <= requestCount } + for waiter in readyWaiters { + waiter.continuation.resume() + } + return await withCheckedContinuation { continuation in + releaseContinuations[requestIndex] = continuation + } + } + + func waitUntilRequestCount(_ expected: Int) async { + if requestCount >= expected { return } + await withCheckedContinuation { continuation in + requestCountWaiters.append((expected, continuation)) + } + } + + func currentRequestCount() -> Int { + requestCount + } + + func releaseRequest(_ requestIndex: Int, with token: String) { + releaseContinuations.removeValue(forKey: requestIndex)?.resume(returning: token) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift index 102bc9998f37..ade685590b80 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift @@ -21,6 +21,97 @@ import Testing ) } + @Test func authenticatedUserReplacementNeverSharesPreviousAccountsTokenTask() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString, + isDirectory: true + ) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let route = try CmxAttachRoute( + id: "shared-manual-host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465) + ) + try await pairedMacStore.upsert( + macDeviceID: "user-a-mac", + displayName: "User A Mac", + routes: [route], + markActive: false, + stackUserID: "user-a", + teamID: nil, + now: Date() + ) + let trustStore = SignalingManualHostTrustStore() + let userAScope = try #require( + MobileManualHostTrustScope(route: route, stackUserID: "user-a") + ) + let userBScope = try #require( + MobileManualHostTrustScope(route: route, stackUserID: "user-b") + ) + await trustStore.trust(userAScope) + await trustStore.trust(userBScope) + let tokenProvider = AccountReplacementTokenProvider() + let tokenSink = RecordedAuthTokenSink() + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: RecordedAuthLivenessTransportFactory( + router: router, + tokenSink: tokenSink + ), + stackAccessTokenProvider: { try await tokenProvider.token() }, + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let identity = StaticIdentityProvider(userID: "user-a") + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: identity, + reachability: AlwaysOnlineReachability(), + pairingHintDefaults: UserDefaults(suiteName: "replacement-pairing-\(UUID().uuidString)")!, + multiMacAggregationDefaults: UserDefaults(suiteName: "replacement-aggregation-\(UUID().uuidString)")!, + manualHostTrustStore: trustStore + ) + store.signIn() + + let oldAccountRefresh = Task { @MainActor in + await store.refreshSecondaryMacWorkspaces() + } + await tokenProvider.waitUntilRequestCount(1) + + identity.currentUserID = "user-b" + store.signIn() + let replacementConnect = Task { @MainActor in + await store.connectManualHost( + name: "User B Mac", + host: "192.168.1.77", + port: 58_465 + ) + } + await trustStore.waitUntilChecked(userBScope, count: 3) + for _ in 0..<1_000 { await Task.yield() } + + await tokenProvider.releaseRequest(1, with: "user-a-token") + for _ in 0..<1_000 { + if await tokenProvider.currentRequestCount() >= 2 { break } + if await tokenSink.recordedTokens().contains("user-a-token") { break } + await Task.yield() + } + #expect(await tokenProvider.currentRequestCount() == 2) + await tokenProvider.releaseRequest(2, with: "user-b-token") + _ = await replacementConnect.value + await oldAccountRefresh.value + + #expect(!(await tokenSink.recordedTokens().contains("user-a-token"))) + #expect(await tokenSink.recordedTokens().contains("user-b-token")) + } + private func assertSessionChangeNeverSendsNewToken( replacementUserID: String, replacementToken: String diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift index b0b4b7ef1dd8..2128f4164e6f 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift @@ -6,6 +6,63 @@ import Testing @MainActor @Suite struct MobileShellManualHostNetworkEpochTests { + @Test func pathChangeDisconnectsActiveManualHostAndQueuesExactRouteForReapproval() async throws { + let reachability = ControllablePathChangeReachability() + let trustStore = NetworkEpochManualHostTrustStore() + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let route = try CmxAttachRoute( + id: "active-manual-host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465) + ) + let trustScope = try #require( + MobileManualHostTrustScope(route: route, stackUserID: "phone-user") + ) + await trustStore.trust(trustScope) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: reachability, + manualHostTrustStore: trustStore + ) + store.signIn() + let ticket = try CmxAttachTicket( + workspaceID: "live-workspace", + terminalID: "live-terminal", + macDeviceID: "manual-mac", + macDisplayName: "LAN Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [route], + expiresAt: Date().addingTimeInterval(3_600), + authToken: "manual-ticket" + ) + #expect(await store.connectPairingURL(try attachURL(for: ticket))) + #expect(store.connectionState == .connected) + #expect(store.remoteClient != nil) + store.startObservingNetworkPathChanges() + + reachability.emitPathChange() + await trustStore.waitUntilRemoved() + + #expect(store.connectionState == .disconnected) + #expect(store.remoteClient == nil) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + #expect(await trustStore.isTrusted(trustScope) == false) + + let resumed = await store.acceptManualHostTrustWarning() + + #expect(resumed == .connected) + #expect(store.connectionState == .connected) + #expect(store.remoteClient != nil) + } + @Test func pathChangeSupersedesPendingManualHostApprovalWithoutTouchingForeground() async throws { let reachability = ControllablePathChangeReachability() let trustStore = NetworkEpochManualHostTrustStore() diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SignalingManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SignalingManualHostTrustStore.swift new file mode 100644 index 000000000000..e468e3e7b3c6 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SignalingManualHostTrustStore.swift @@ -0,0 +1,40 @@ +import CmuxMobileShellModel + +actor SignalingManualHostTrustStore: MobileManualHostTrustStoring { + private var trustedScopes: Set = [] + private var checkCounts: [MobileManualHostTrustScope: Int] = [:] + private var checkWaiters: [MobileManualHostTrustScope: [( + expected: Int, + continuation: CheckedContinuation + )]] = [:] + + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + checkCounts[scope, default: 0] += 1 + let currentCount = checkCounts[scope, default: 0] + let waiters = checkWaiters.removeValue(forKey: scope) ?? [] + let readyWaiters = waiters.filter { $0.expected <= currentCount } + let remainingWaiters = waiters.filter { $0.expected > currentCount } + if !remainingWaiters.isEmpty { + checkWaiters[scope] = remainingWaiters + } + for waiter in readyWaiters { + waiter.continuation.resume() + } + return trustedScopes.contains(scope) + } + + func trust(_ scope: MobileManualHostTrustScope) async { + trustedScopes.insert(scope) + } + + func removeAll() async { + trustedScopes.removeAll() + } + + func waitUntilChecked(_ scope: MobileManualHostTrustScope, count: Int) async { + if checkCounts[scope, default: 0] >= count { return } + await withCheckedContinuation { continuation in + checkWaiters[scope, default: []].append((count, continuation)) + } + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootAuthGateShellSyncTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootAuthGateShellSyncTests.swift new file mode 100644 index 000000000000..436f669c462b --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootAuthGateShellSyncTests.swift @@ -0,0 +1,49 @@ +import CmuxMobileShell +import CmuxMobileShellModel +import CmuxMobileWorkspace +import Foundation +import Testing +@testable import CmuxMobileShellUI + +@MainActor +@Suite struct MobileRootAuthGateShellSyncTests { + @Test func authenticatedUserReplacementClearsPreviousAccountsShellState() { + let identity = WorkspaceMacSelectionIdentityProvider(userID: "user-a") + let privateWorkspace = MobileWorkspacePreview( + id: "user-a-private-workspace", + name: "User A Private Workspace", + terminals: [ + MobileTerminalPreview( + id: "user-a-private-terminal", + name: "Private Terminal" + ), + ] + ) + let defaults = UserDefaults( + suiteName: "MobileRootAuthGateShellSyncTests-\(UUID().uuidString)" + )! + let store = MobileShellComposite( + workspaces: [privateWorkspace], + clientIDRepository: MobileClientIDRepository(defaults: defaults), + identityProvider: identity, + pairingHintDefaults: defaults, + multiMacAggregationDefaults: defaults + ) + MobileRootAuthGate.syncShellAuthentication( + stackAuthenticated: true, + store: store + ) + store.terminalInputText = "user-a-unsent-secret" + + identity.currentUserID = "user-b" + MobileRootAuthGate.syncShellAuthentication( + stackAuthenticated: true, + store: store + ) + + #expect(store.terminalInputText.isEmpty) + #expect(!store.workspaces.contains(where: { $0.id == privateWorkspace.id })) + #expect(store.selectedWorkspaceID != privateWorkspace.id) + #expect(store.selectedTerminalID != privateWorkspace.terminals.first?.id) + } +} From 523b20ae508cc7e3ed8dfb278729ffadfdbcaf70 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 17:00:08 -0700 Subject: [PATCH 56/91] Secure manual host authorization epochs --- .../CMUXMobileCore/CmxManualHost.swift | 8 + .../CmxManualHostTests.swift | 3 + .../CmuxMobileRPC/MobileCoreRPCClient.swift | 87 ++++++-- .../MobileCoreRPCEventListener.swift | 6 + .../MobileCoreRPCEventSubscription.swift | 6 + .../MobileCoreRPCPendingWrite.swift | 8 + .../CmuxMobileRPC/MobileCoreRPCSession.swift | 92 ++++----- .../CmuxMobileRPC/MobileRPCAuthScope.swift | 46 +++++ .../CmuxMobileRPC/RPCStackTokenGate.swift | 99 +++++++--- .../ImmediateResponseRecordingTransport.swift | 56 ++++++ .../MobileCoreRPCAbandonedConnectTests.swift | 14 +- .../MobileCoreRPCAuthScopeTests.swift | 164 +++++++++++++++ .../MobileCoreRPCClient+TestFactory.swift | 38 ++++ .../MobileCoreRPCClientTests.swift | 8 +- .../MobileCoreRPCConnectWaiterTests.swift | 2 +- .../MobileCoreRPCGroupActionAuthTests.swift | 6 +- ...leCoreRPCHostStatusTokenTimeoutTests.swift | 4 +- .../MobileCoreRPCManualHostTrustTests.swift | 4 +- .../MobileCoreRPCRequestQueueTests.swift | 6 +- .../MobileCoreRPCTokenTimeoutTests.swift | 15 +- .../ScopedRPCValidationGate.swift | 36 ++++ .../MobileDeleteComputersVerifier.swift | 3 +- ...MobileShellAuthorizationFailureOwner.swift | 5 +- ...eShellComposite+AuthorizationFailure.swift | 8 +- ...ileShellComposite+ManualAttachTicket.swift | 16 +- ...MobileShellComposite+ManualHostTrust.swift | 46 +++-- ...obileShellComposite+PairedMacAliases.swift | 1 - ...leShellComposite+PairedMacCoalescing.swift | 12 +- ...MobileShellComposite+ReconnectRoutes.swift | 1 - .../MobileShellComposite+Scope.swift | 116 ++++++++++- ...obileShellComposite+WorkspaceActions.swift | 9 +- ...hellComposite+WorkspaceCreateRequest.swift | 6 +- ...ellComposite+WorkspaceMutationTarget.swift | 34 ++++ .../MobileShellComposite.swift | 186 ++++++++++++------ .../MobileShellRPCAuthContext.swift | 13 ++ .../MobileShellRouteSelection.swift | 13 +- .../MobileShellScopeSnapshot.swift | 2 + .../WorkspaceMutationTarget.swift | 2 + .../ComposerSubmitRoutingTestSupport.swift | 12 +- .../MobilePairingAttemptDeadlineTests.swift | 12 +- ...CancellationPreservesForegroundTests.swift | 3 +- .../MobileShellAuthScopeIsolationTests.swift | 20 ++ .../MobileShellComposite+TestState.swift} | 7 +- ...ellCompositePairedMacCoalescingTests.swift | 24 ++- ...anualHostAuthorizationOwnershipTests.swift | 16 +- ...bileShellManualHostNetworkEpochTests.swift | 4 + ...leShellRenderGridLivenessTestSupport.swift | 4 +- ...ileShellTeamSwitchAuthorizationTests.swift | 21 ++ .../MobileManualHostTrustScope.swift | 20 +- .../MobileShellRouteAuthPolicy.swift | 11 +- .../MobileShellRouteAuthPolicyTests.swift | 14 ++ .../CMUXMobileRootView.swift | 5 + .../CmuxMobileShellUI/PairingView.swift | 2 +- ...bilePairingManualHostAdvertisability.swift | 2 +- .../Mobile/MobileHostRouteAdvertisement.swift | 6 +- Sources/Mobile/MobileRouteResolver.swift | 6 +- ios/cmux/Resources/Localizable.xcstrings | 4 +- 57 files changed, 1102 insertions(+), 272 deletions(-) create mode 100644 Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCEventListener.swift create mode 100644 Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCEventSubscription.swift create mode 100644 Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCPendingWrite.swift create mode 100644 Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCAuthScope.swift create mode 100644 Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/ImmediateResponseRecordingTransport.swift create mode 100644 Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCAuthScopeTests.swift create mode 100644 Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClient+TestFactory.swift create mode 100644 Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/ScopedRPCValidationGate.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceMutationTarget.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRPCAuthContext.swift rename Packages/iOS/CmuxMobileShell/{Sources/CmuxMobileShell/MobileShellComposite+Testing.swift => Tests/CmuxMobileShellTests/MobileShellComposite+TestState.swift} (67%) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellTeamSwitchAuthorizationTests.swift diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift index b0b66a223894..f25a180a8a45 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/CmxManualHost.swift @@ -11,6 +11,14 @@ public struct CmxManualHost: Equatable, Sendable { /// The normalized bare host, with IPv6 brackets removed when present. public let rawValue: String + /// Whether this host may be published as a remote manual pairing route. + /// + /// Loopback names the publishing machine itself, so advertising it to a + /// phone would make the phone dial its own local process instead of the Mac. + public var isAdvertisable: Bool { + !CmxLoopbackHost().matches(rawValue) + } + /// Creates a normalized manual host. /// /// - Parameter rawHost: A DNS name or IP literal. IPv6 literals must be diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift index 8dde337c462c..17d8b0d92814 100644 --- a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/CmxManualHostTests.swift @@ -25,6 +25,9 @@ import Testing #expect(CmxManualHost("[abc]def]") == nil) #expect(CmxManualHost("studio]mac") == nil) #expect(CmxManualHost("studio mac") == nil) + #expect(CmxManualHost("studio-mac.local")?.isAdvertisable == true) + #expect(CmxManualHost("127.0.0.1")?.isAdvertisable == false) + #expect(CmxManualHost("localhost")?.isAdvertisable == false) } @Test func manualHostRouteNormalizerAcceptsAlreadyNormalizedIPv6() { diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift index a2dd9b31ece3..0608787b8a75 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift @@ -16,6 +16,8 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { public var attachTicket: CmxAttachTicket { ticket } private let allowsStackAuthFallback: Bool private let manualHostStackAuthTrustProvider: @Sendable () async -> Bool + private let authScope: MobileRPCAuthScope + private let authScopeValidator: @Sendable () async -> Bool // `internal` (not `private`) so `@testable import` can observe session // queue state from tests, instead of exposing a debug hook in production. let session: MobileCoreRPCSession @@ -33,12 +35,16 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { /// exact `.manualHost` route may carry Stack auth. The provider is called /// for every token-bearing request so approval expiry or revocation takes /// effect without replacing the client. + /// - authScope: Immutable signed-in authorization epoch for token-task isolation. + /// - authScopeValidator: Revalidates that `authScope` still owns the live session. public init( runtime: any MobileSyncRuntime, route: CmxAttachRoute, ticket: CmxAttachTicket, allowsStackAuthFallback: Bool = false, manualHostStackAuthTrustProvider: @escaping @Sendable () async -> Bool = { false }, + authScope: MobileRPCAuthScope, + authScopeValidator: @escaping @Sendable () async -> Bool, connectAttemptRegistry: MobileRPCConnectAttemptRegistry = MobileRPCConnectAttemptRegistry(), stackTokenGate: RPCStackTokenGate? = nil, stackTokenForceRefreshGate: RPCStackTokenGate? = nil, @@ -51,6 +57,8 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { self.ticket = ticket self.allowsStackAuthFallback = allowsStackAuthFallback self.manualHostStackAuthTrustProvider = manualHostStackAuthTrustProvider + self.authScope = authScope + self.authScopeValidator = authScopeValidator self.stackTokenGate = stackTokenGate ?? RPCStackTokenGate(timedOutResetNanoseconds: stackTokenGateResetNanoseconds) self.stackTokenForceRefreshGate = stackTokenForceRefreshGate @@ -142,16 +150,22 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { /// not trip the re-auth prompt; a definitive failure surfaces as /// `.authorizationFailed` to drive re-auth. private func forceRefreshStackTokenForRetry(deadline: RPCRequestDeadline) async throws { + try await validateAuthScope() guard allowsStackAuthFallback, await routeAllowsStackAuth() else { throw MobileShellConnectionError.insecureManualRoute } do { _ = try await stackTokenForceRefreshGate.token( + scope: authScope, timeoutNanoseconds: try deadline.remainingNanoseconds() ) { [runtime] in try await runtime.stackAccessTokenForceRefresher() } + try await validateAuthScope() + guard await routeAllowsStackAuth() else { + throw MobileShellConnectionError.insecureManualRoute + } } catch let error as MobileShellConnectionError { throw error } catch is CancellationError { @@ -185,10 +199,25 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { deadline: deadline ) try Task.checkCancellation() + let preEnqueueValidator: MobileCoreRPCSession.PreEnqueueValidator? + let sendAuthorizer: MobileCoreRPCSession.SendAuthorizer? + if authenticated.containsStackAccessToken { + preEnqueueValidator = { @Sendable [self] in + try await validateTokenBearingRequestBeforeEnqueue() + } + sendAuthorizer = { @Sendable [self] in + try await authorizeTokenBearingSend() + } + } else { + preEnqueueValidator = nil + sendAuthorizer = nil + } return try await session.send( - payload: authenticated, + payload: authenticated.data, requestID: id, - deadlineUptimeNanoseconds: deadline.uptimeNanoseconds + deadlineUptimeNanoseconds: deadline.uptimeNanoseconds, + preEnqueueValidator: preEnqueueValidator, + sendAuthorizer: sendAuthorizer ) } @@ -210,9 +239,12 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { return (id, data) } - private func requestDataWithAuth(_ requestData: Data, deadline: RPCRequestDeadline) async throws -> Data { + private func requestDataWithAuth( + _ requestData: Data, + deadline: RPCRequestDeadline + ) async throws -> (data: Data, containsStackAccessToken: Bool) { guard var request = try JSONSerialization.jsonObject(with: requestData) as? [String: Any] else { - return requestData + return (requestData, false) } let requestNeedsAuth = Self.requestRequiresAuth(request) let requestIsCoveredByAttachTicket = !Self.requestNeedsStackAuthFallback(request, ticket: ticket) @@ -244,12 +276,14 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { // supplementary route/workspace context. let shouldSendStackAuth = requestNeedsAuth if shouldSendStackAuth { + try await validateAuthScope() guard allowsStackAuthFallback, await routeAllowsStackAuth() else { throw MobileShellConnectionError.insecureManualRoute } do { let stackAccessToken = try await stackAccessToken(deadline: deadline) + try await validateAuthScope() guard await routeAllowsStackAuth() else { throw MobileShellConnectionError.insecureManualRoute } @@ -277,16 +311,24 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { } if !requestNeedsAuth, isHostStatusRequest(request), - allowsStackAuthFallback, - await routeAllowsStackAuth(), - let stackAccessToken = try await stackAccessTokenForStatus(deadline: deadline), - await routeAllowsStackAuth() { - auth["stack_access_token"] = stackAccessToken + allowsStackAuthFallback { + try await validateAuthScope() + if await routeAllowsStackAuth(), + let stackAccessToken = try await stackAccessTokenForStatus(deadline: deadline) { + try await validateAuthScope() + guard await routeAllowsStackAuth() else { + throw MobileShellConnectionError.insecureManualRoute + } + auth["stack_access_token"] = stackAccessToken + } } if !auth.isEmpty { request["auth"] = auth } - return try JSONSerialization.data(withJSONObject: request) + return ( + try JSONSerialization.data(withJSONObject: request), + auth["stack_access_token"] != nil + ) } private func routeAllowsStackAuth() async -> Bool { @@ -316,11 +358,34 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { } private func stackAccessToken(deadline: RPCRequestDeadline) async throws -> String { - try await stackTokenGate.token(timeoutNanoseconds: try deadline.remainingNanoseconds()) { [runtime] in + try await stackTokenGate.token( + scope: authScope, + timeoutNanoseconds: try deadline.remainingNanoseconds() + ) { [runtime] in try await runtime.stackAccessTokenProvider() } } + private func validateAuthScope() async throws { + guard await authScopeValidator() else { throw CancellationError() } + } + + private func validateTokenBearingRequestBeforeEnqueue() async throws { + try await validateAuthScope() + guard await routeAllowsStackAuth() else { + throw MobileShellConnectionError.insecureManualRoute + } + try await validateAuthScope() + } + + private func authorizeTokenBearingSend() async throws -> MobileRPCAuthScope.SendLease { + try await validateTokenBearingRequestBeforeEnqueue() + guard let lease = authScope.beginSend() else { + throw CancellationError() + } + return lease + } + private static func requestNeedsStackAuthFallback(_ request: [String: Any], ticket: CmxAttachTicket) -> Bool { guard requestRequiresAuth(request) else { return false diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCEventListener.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCEventListener.swift new file mode 100644 index 000000000000..a940994c9d81 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCEventListener.swift @@ -0,0 +1,6 @@ +import Foundation + +struct MobileCoreRPCEventListener { + let topics: Set + let continuation: AsyncStream.Continuation +} diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCEventSubscription.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCEventSubscription.swift new file mode 100644 index 000000000000..3f60f5f5f128 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCEventSubscription.swift @@ -0,0 +1,6 @@ +import Foundation + +struct MobileCoreRPCEventSubscription { + let id: UUID + let stream: AsyncStream +} diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCPendingWrite.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCPendingWrite.swift new file mode 100644 index 000000000000..bfac977b2aa0 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCPendingWrite.swift @@ -0,0 +1,8 @@ +import Foundation + +struct MobileCoreRPCPendingWrite: Sendable { + let id: UUID + let requestID: String + let frame: Data + let authorizeSend: (@Sendable () async throws -> MobileRPCAuthScope.SendLease)? +} diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift index f202d7e10666..73ac085cffc2 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift @@ -1,30 +1,15 @@ internal import CMUXMobileCore import Foundation - actor MobileCoreRPCSession { typealias TransportFactory = @Sendable () throws -> any CmxByteTransport typealias ConnectedCandidateHook = @Sendable (_ candidate: any CmxByteTransport) async -> Void + typealias PreEnqueueValidator = @Sendable () async throws -> Void + typealias SendAuthorizer = @Sendable () async throws -> MobileRPCAuthScope.SendLease typealias PendingContinuation = CheckedContinuation, Never> typealias ConnectingTask = (id: UUID, lease: MobileRPCConnectAttemptLease?, task: Task, waiters: Set, completed: Bool) static let defaultAbandonedConnectCleanupTimeoutNanoseconds: UInt64 = 1_000_000_000 static let defaultLateAbandonedConnectCloseTimeoutNanoseconds: UInt64 = 5_000_000_000 - struct EventSubscription { - let id: UUID - let stream: AsyncStream - } - - private struct EventListener { - let topics: Set - let continuation: AsyncStream.Continuation - } - - private struct PendingWrite: Sendable { - let id: UUID - let requestID: String - let frame: Data - } - private let taskTimeout = RPCTaskTimeout() private let connectAttemptKey: String? let connectAttemptRegistry: MobileRPCConnectAttemptRegistry @@ -43,9 +28,9 @@ actor MobileCoreRPCSession { // `internal` so cancellation tests can observe the writer-queue gate via // `@testable import` without adding a production debug hook. var queuedRequestIDs: Set { Set(queuedWriteIDs.keys) } - private var listeners: [UUID: EventListener] = [:] + private var listeners: [UUID: MobileCoreRPCEventListener] = [:] private var isTearingDown: Bool = false - private var writeQueue: AsyncStream.Continuation? + private var writeQueue: AsyncStream.Continuation? private var writerTask: Task? init( @@ -71,10 +56,20 @@ actor MobileCoreRPCSession { writeQueue?.finish() } - func send(payload: Data, requestID: String, deadlineUptimeNanoseconds: UInt64) async throws -> Data { - _ = try await ensureConnected( - timeoutNanoseconds: try taskTimeout.remainingNanoseconds(until: deadlineUptimeNanoseconds) - ) + func send( + payload: Data, + requestID: String, + deadlineUptimeNanoseconds: UInt64, + preEnqueueValidator: PreEnqueueValidator? = nil, + sendAuthorizer: SendAuthorizer? = nil + ) async throws -> Data { + _ = try await ensureConnected(timeoutNanoseconds: try taskTimeout.remainingNanoseconds( + until: deadlineUptimeNanoseconds + )) + if let preEnqueueValidator { + try await preEnqueueValidator() + } + try Task.checkCancellation() let frame = try MobileSyncFrameCodec.encodeFrame(payload) let responseTimeoutNanoseconds = try taskTimeout.remainingNanoseconds(until: deadlineUptimeNanoseconds) @@ -88,11 +83,7 @@ actor MobileCoreRPCSession { pending[requestID] = continuation requestTimeoutTasks[requestID]?.cancel() requestTimeoutTasks[requestID] = Task { [weak self, taskTimeout] in - do { - try await taskTimeout.sleep(nanoseconds: responseTimeoutNanoseconds) - } catch { - return - } + do { try await taskTimeout.sleep(nanoseconds: responseTimeoutNanoseconds) } catch { return } guard let self else { return } await self.timeoutPendingRequest(requestID: requestID) } @@ -103,36 +94,31 @@ actor MobileCoreRPCSession { return } queuedWriteIDs[requestID] = queuedWriteID - _ = queue.yield(PendingWrite(id: queuedWriteID, requestID: requestID, frame: frame)) + _ = queue.yield(MobileCoreRPCPendingWrite( + id: queuedWriteID, requestID: requestID, frame: frame, authorizeSend: sendAuthorizer + )) } } onCancel: { - Task { - await self.cancelPendingRequest(requestID: requestID) - } + Task { await self.cancelPendingRequest(requestID: requestID) } } if Task.isCancelled { throw CancellationError() } - switch result { - case .success(let data): - return data - case .failure(let error): - throw error - } + return try result.get() } - func addEventListener(topics: Set) -> EventSubscription { + func addEventListener(topics: Set) -> MobileCoreRPCEventSubscription { let id = UUID() var continuation: AsyncStream.Continuation! let stream = AsyncStream(bufferingPolicy: .bufferingNewest(256)) { cont in continuation = cont } - listeners[id] = EventListener(topics: topics, continuation: continuation) + listeners[id] = MobileCoreRPCEventListener(topics: topics, continuation: continuation) continuation.onTermination = { [weak self] _ in guard let self else { return } Task { await self.removeListener(id: id) } } - return EventSubscription(id: id, stream: stream) + return MobileCoreRPCEventSubscription(id: id, stream: stream) } func removeListener(id: UUID) { @@ -288,7 +274,7 @@ actor MobileCoreRPCSession { readerTask = Task { [weak self] in await self?.readLoop(transport: candidate) } - let (stream, continuation) = AsyncStream.makeStream(bufferingPolicy: .unbounded) + let (stream, continuation) = AsyncStream.makeStream(bufferingPolicy: .unbounded) writeQueue = continuation writerTask = Task { [weak self] in await self?.writeLoop(transport: candidate, frames: stream) @@ -371,12 +357,18 @@ actor MobileCoreRPCSession { } } - private func writeLoop(transport: any CmxByteTransport, frames: AsyncStream) async { + private func writeLoop(transport: any CmxByteTransport, frames: AsyncStream) async { for await write in frames { if Task.isCancelled { return } - guard shouldSendQueuedWrite(write) else { - continue + if let authorizeSend = write.authorizeSend { + do { + _ = try await authorizeSend() + } catch { + failQueuedWriteAuthorization(write, error: error) + continue + } } + guard shouldSendQueuedWrite(write) else { continue } do { try await transport.send(write.frame) } catch { @@ -386,6 +378,14 @@ actor MobileCoreRPCSession { } } + private func failQueuedWriteAuthorization(_ write: MobileCoreRPCPendingWrite, error: any Error) { + if cancelledQueuedWriteIDs.remove(write.id) != nil { return } + guard queuedWriteIDs[write.requestID] == write.id else { return } + queuedWriteIDs[write.requestID] = nil + let connectionError = error as? MobileShellConnectionError ?? .connectionClosed + failPending(requestID: write.requestID, error: connectionError) + } + private func readLoop(transport: any CmxByteTransport) async { var buffer = Data() while !Task.isCancelled { @@ -486,7 +486,7 @@ actor MobileCoreRPCSession { cont.resume(returning: .failure(.requestTimedOut)) } - private func shouldSendQueuedWrite(_ write: PendingWrite) -> Bool { + private func shouldSendQueuedWrite(_ write: MobileCoreRPCPendingWrite) -> Bool { if cancelledQueuedWriteIDs.remove(write.id) != nil { return false } diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCAuthScope.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCAuthScope.swift new file mode 100644 index 000000000000..f44490f0402d --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCAuthScope.swift @@ -0,0 +1,46 @@ +import Foundation +import os + +/// Revocable identity for one signed-in RPC authorization epoch. +/// +/// The shell rotates the relevant value synchronously when the signed-in account +/// or manual-host network trust epoch changes. Token acquisition and transport enqueue use +/// it as a non-secret key so requests from different auth epochs never share an +/// in-flight credential task. +// `rawValue` is immutable and the only mutable field is accessed exclusively +// through `isRevokedLock`, so cross-task references cannot race. +public final class MobileRPCAuthScope: @unchecked Sendable, Hashable { + /// A one-send capability acquired at the writer's authorization linearization point. + struct SendLease: Sendable {} + + private let rawValue: UUID + // lint:allow lock - scope revocation and writer admission must be synchronous; + // an actor hop would recreate the authorization TOCTOU this flag closes. + private let isRevokedLock = OSAllocatedUnfairLock(initialState: false) + + /// Creates a fresh authorization-scope identity. + public init() { + rawValue = UUID() + } + + /// Revokes this epoch synchronously so no later queued write can begin sending. + public func revoke() { + isRevokedLock.withLock { $0 = true } + } + + /// Acquires authorization for one send if revocation has not linearized first. + func beginSend() -> SendLease? { + isRevokedLock.withLock { isRevoked in + guard !isRevoked else { return nil } + return SendLease() + } + } + + public static func == (lhs: MobileRPCAuthScope, rhs: MobileRPCAuthScope) -> Bool { + lhs.rawValue == rhs.rawValue + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(rawValue) + } +} diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenGate.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenGate.swift index b700957d41fc..b68d35254088 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenGate.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenGate.swift @@ -2,8 +2,20 @@ import Foundation /// Deduplicates Stack access-token acquisition across mobile RPC clients owned by the same shell. public actor RPCStackTokenGate { - private var current: (id: UUID, task: Task, waiters: Int, timedOutUntil: UInt64?)? - private var abandoned: [UUID: Task] = [:] + private enum ScopeKey: Hashable, Sendable { + case unscoped + case scoped(MobileRPCAuthScope) + } + + private struct CurrentTokenTask { + let id: UUID + let task: Task + var waiters: Int + var timedOutUntil: UInt64? + } + + private var currentByScope: [ScopeKey: CurrentTokenTask] = [:] + private var abandonedByScope: [ScopeKey: [UUID: Task]] = [:] private let taskTimeout = RPCTaskTimeout() private let timedOutResetNanoseconds: UInt64 @@ -13,85 +25,108 @@ public actor RPCStackTokenGate { } func token( + scope: MobileRPCAuthScope? = nil, timeoutNanoseconds: UInt64, provider: @escaping @Sendable () async throws -> String ) async throws -> String { + let scopeKey = scope.map(ScopeKey.scoped) ?? .unscoped let id: UUID let task: Task - if let existing = current, let timedOutUntil = existing.timedOutUntil { + if let existing = currentByScope[scopeKey], let timedOutUntil = existing.timedOutUntil { guard DispatchTime.now().uptimeNanoseconds >= timedOutUntil else { throw MobileShellConnectionError.requestTimedOut } - guard abandoned.isEmpty else { + guard abandonedByScope[scopeKey]?.isEmpty != false else { throw MobileShellConnectionError.requestTimedOut } - abandoned[existing.id] = existing.task - current = nil + abandonedByScope[scopeKey, default: [:]][existing.id] = existing.task + currentByScope[scopeKey] = nil } - if let existing = current { + if var existing = currentByScope[scopeKey] { id = existing.id task = existing.task - current?.waiters += 1 + existing.waiters += 1 + currentByScope[scopeKey] = existing } else { id = UUID() task = Task { try await provider() } - current = (id: id, task: task, waiters: 1, timedOutUntil: nil) + currentByScope[scopeKey] = CurrentTokenTask( + id: id, + task: task, + waiters: 1, + timedOutUntil: nil + ) Task.detached { [weak self] in _ = await task.result - await self?.clear(id: id) + await self?.clear(scopeKey: scopeKey, id: id) } } do { let token = try await taskTimeout.value(task, timeoutNanoseconds: timeoutNanoseconds) - clear(id: id) + clear(scopeKey: scopeKey, id: id) return token } catch MobileShellConnectionError.requestTimedOut { - timeoutWaiter(id: id) + timeoutWaiter(scopeKey: scopeKey, id: id) throw MobileShellConnectionError.requestTimedOut } catch is CancellationError { - cancelWaiter(id: id) + cancelWaiter(scopeKey: scopeKey, id: id) throw CancellationError() } catch { - clear(id: id) + clear(scopeKey: scopeKey, id: id) throw error } } - private func timeoutWaiter(id: UUID) { - guard current?.id == id, let task = current?.task else { return } - current?.waiters -= 1 - guard let waiters = current?.waiters, waiters <= 0 else { + /// Cancels credential work owned by one invalidated auth scope without + /// disturbing requests from another signed-in scope. + public func invalidate(scope: MobileRPCAuthScope) { + scope.revoke() + let scopeKey = ScopeKey.scoped(scope) + currentByScope.removeValue(forKey: scopeKey)?.task.cancel() + let abandoned = abandonedByScope.removeValue(forKey: scopeKey)?.values ?? [:].values + for task in abandoned { task.cancel() } + } + + private func timeoutWaiter(scopeKey: ScopeKey, id: UUID) { + guard var current = currentByScope[scopeKey], current.id == id else { return } + current.waiters -= 1 + guard current.waiters <= 0 else { + currentByScope[scopeKey] = current return } - current = ( + currentByScope[scopeKey] = CurrentTokenTask( id: id, - task: task, + task: current.task, waiters: 0, timedOutUntil: DispatchTime.now().uptimeNanoseconds &+ timedOutResetNanoseconds ) - task.cancel() + current.task.cancel() } - private func cancelWaiter(id: UUID) { - guard current?.id == id, let task = current?.task else { return } - current?.waiters -= 1 - guard let waiters = current?.waiters, waiters <= 0 else { + private func cancelWaiter(scopeKey: ScopeKey, id: UUID) { + guard var current = currentByScope[scopeKey], current.id == id else { return } + current.waiters -= 1 + guard current.waiters <= 0 else { + currentByScope[scopeKey] = current return } - current = ( + currentByScope[scopeKey] = CurrentTokenTask( id: id, - task: task, + task: current.task, waiters: 0, timedOutUntil: DispatchTime.now().uptimeNanoseconds &+ timedOutResetNanoseconds ) - task.cancel() + current.task.cancel() } - private func clear(id: UUID) { - if current?.id == id { - current = nil + private func clear(scopeKey: ScopeKey, id: UUID) { + if currentByScope[scopeKey]?.id == id { + currentByScope[scopeKey] = nil + } + abandonedByScope[scopeKey]?[id] = nil + if abandonedByScope[scopeKey]?.isEmpty == true { + abandonedByScope[scopeKey] = nil } - abandoned[id] = nil } } diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/ImmediateResponseRecordingTransport.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/ImmediateResponseRecordingTransport.swift new file mode 100644 index 000000000000..3a3e4c6be87d --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/ImmediateResponseRecordingTransport.swift @@ -0,0 +1,56 @@ +import CMUXMobileCore +import Foundation +@testable import CmuxMobileRPC + +actor ImmediateResponseRecordingTransport: CmxByteTransport { + private var sentPayloads: [Data] = [] + private var queuedResponses: [Data] = [] + private var receiveWaiters: [CheckedContinuation] = [] + private var isClosed = false + + func connect() async throws {} + + func receive() async throws -> Data? { + if !queuedResponses.isEmpty { + return queuedResponses.removeFirst() + } + if isClosed { return nil } + return await withCheckedContinuation { receiveWaiters.append($0) } + } + + func send(_ data: Data) async throws { + var buffer = data + let payloads = try MobileSyncFrameCodec.decodeFrames(from: &buffer) + sentPayloads.append(contentsOf: payloads) + for payload in payloads { + let request = try recordedRPCRequest(from: payload) + try deliverResponse(id: request.id) + } + } + + func close() async { + isClosed = true + let waiters = receiveWaiters + receiveWaiters.removeAll() + for waiter in waiters { waiter.resume(returning: nil) } + } + + func sentRequests() throws -> [RecordedRPCRequest] { + try sentPayloads.map(recordedRPCRequest(from:)) + } + + private func deliverResponse(id: String?) throws { + let response: [String: Any] = [ + "id": id ?? "", + "ok": true, + "result": ["status": "ok"], + ] + let payload = try JSONSerialization.data(withJSONObject: response) + let frame = try MobileSyncFrameCodec.encodeFrame(payload) + if !receiveWaiters.isEmpty { + receiveWaiters.removeFirst().resume(returning: frame) + } else { + queuedResponses.append(frame) + } + } +} diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCAbandonedConnectTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCAbandonedConnectTests.swift index d5aa8794149e..dadf787b54aa 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCAbandonedConnectTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCAbandonedConnectTests.swift @@ -20,7 +20,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -64,7 +64,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -132,7 +132,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -188,7 +188,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -235,7 +235,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -305,7 +305,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -460,7 +460,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCAuthScopeTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCAuthScopeTests.swift new file mode 100644 index 000000000000..481b06bf5f72 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCAuthScopeTests.swift @@ -0,0 +1,164 @@ +import CMUXMobileCore +import Foundation +import Testing +@testable import CmuxMobileRPC + +@Suite struct MobileCoreRPCAuthScopeTests { + @Test func sharedTokenGateDoesNotJoinDifferentScopes() async throws { + let gate = RPCStackTokenGate() + let provider = CancellationIgnoringTokenProvider() + let firstScope = MobileRPCAuthScope() + let secondScope = MobileRPCAuthScope() + let first = Task { + try await gate.token(scope: firstScope, timeoutNanoseconds: 30_000_000_000) { + try await provider.token() + } + } + await provider.waitUntilStartCount(1) + let second = Task { + try await gate.token(scope: secondScope, timeoutNanoseconds: 30_000_000_000) { + try await provider.token() + } + } + await provider.waitUntilStartCount(2) + + #expect(await provider.startCount == 2) + await provider.release() + #expect(try await first.value == "released-token") + #expect(try await second.value == "released-token") + } + + @Test func invalidatedScopeCannotReuseItsOldTokenTask() async throws { + let gate = RPCStackTokenGate() + let provider = CancellationIgnoringTokenProvider() + let scope = MobileRPCAuthScope() + let first = Task { + try await gate.token(scope: scope, timeoutNanoseconds: 30_000_000_000) { + try await provider.token() + } + } + await provider.waitUntilStartCount(1) + await gate.invalidate(scope: scope) + let second = Task { + try await gate.token(scope: scope, timeoutNanoseconds: 30_000_000_000) { + try await provider.token() + } + } + await provider.waitUntilStartCount(2) + + #expect(await provider.startCount == 2) + await provider.release() + _ = try? await first.value + #expect(try await second.value == "released-token") + } + + @Test(arguments: ["workspace.list", "mobile.host.status"]) + func invalidatedAuthScopeBeforeSessionEnqueueSendsNothing(method: String) async throws { + let validation = ScopedRPCValidationGate(blockedCall: 3) + let transport = ImmediateResponseRecordingTransport() + let route = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: 58_465) + let runtime = TestMobileSyncRuntime( + transportFactory: FixedTransportFactory(transport: transport), + stackAccessToken: "scoped-token", + stackAccessTokenForStatus: "status-token" + ) + let client = MobileCoreRPCClient.testClient( + runtime: runtime, + route: route, + ticket: try ticket(route: route), + allowsStackAuthFallback: true, + authScope: MobileRPCAuthScope(), + authScopeValidator: { await validation.validate() } + ) + let request = try MobileCoreRPCClient.requestData(method: method) + let send = Task { try await client.sendRequest(request) } + await validation.waitUntilBlocked() + await validation.invalidateAndRelease() + + do { + _ = try await send.value + Issue.record("Expected invalid auth scope to cancel before enqueue") + } catch is CancellationError { + } catch { + Issue.record("Expected CancellationError, got \(error)") + } + #expect(try await transport.sentRequests().isEmpty) + } + + @Test func invalidatedAuthScopeWhileConnectionEstablishesSendsNothing() async throws { + let validation = ScopedRPCValidationGate(blockedCall: .max) + let transport = ReleasableConnectTransport() + let route = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: 58_465) + let client = MobileCoreRPCClient.testClient( + runtime: TestMobileSyncRuntime( + transportFactory: ReleasableConnectTransportFactory(transport: transport), + stackAccessToken: "scoped-token" + ), + route: route, + ticket: try ticket(route: route), + allowsStackAuthFallback: true, + authScope: MobileRPCAuthScope(), + authScopeValidator: { await validation.validate() } + ) + let request = try MobileCoreRPCClient.requestData(method: "workspace.list") + let send = Task { try await client.sendRequest(request) } + #expect(await transport.waitUntilConnectStarted()) + + await validation.invalidateAndRelease() + await transport.releaseConnect() + + do { + _ = try await send.value + Issue.record("Expected invalid auth scope to cancel before enqueue") + } catch is CancellationError { + } catch { + Issue.record("Expected CancellationError, got \(error)") + } + #expect(try await transport.sentRequests().isEmpty) + } + + @Test func revokedManualTrustBeforeSessionEnqueueSendsNothing() async throws { + let trust = ScopedRPCValidationGate(blockedCall: 3) + let transport = ImmediateResponseRecordingTransport() + let route = try hostPortRoute(kind: .manualHost, host: "192.168.1.77", port: 58_465) + let client = MobileCoreRPCClient.testClient( + runtime: TestMobileSyncRuntime( + transportFactory: FixedTransportFactory(transport: transport), + supportedRouteKinds: [.manualHost], + stackAccessToken: "manual-token" + ), + route: route, + ticket: try ticket(route: route), + allowsStackAuthFallback: true, + manualHostStackAuthTrustProvider: { await trust.validate() }, + authScope: MobileRPCAuthScope() + ) + let request = try MobileCoreRPCClient.requestData(method: "workspace.list") + let send = Task { try await client.sendRequest(request) } + await trust.waitUntilBlocked() + await trust.invalidateAndRelease() + + do { + _ = try await send.value + Issue.record("Expected revoked trust to block session enqueue") + } catch let error as MobileShellConnectionError { + guard case .insecureManualRoute = error else { + Issue.record("Expected insecureManualRoute, got \(error)") + return + } + } + #expect(try await transport.sentRequests().isEmpty) + } + + private func ticket(route: CmxAttachRoute) throws -> CmxAttachTicket { + try CmxAttachTicket( + workspaceID: "", + terminalID: nil, + macDeviceID: "", + macDisplayName: nil, + routes: [route], + expiresAt: nil, + authToken: nil + ) + } +} diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClient+TestFactory.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClient+TestFactory.swift new file mode 100644 index 000000000000..b478c50d984d --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClient+TestFactory.swift @@ -0,0 +1,38 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import Foundation +@testable import CmuxMobileRPC + +extension MobileCoreRPCClient { + static func testClient( + runtime: any MobileSyncRuntime, + route: CmxAttachRoute, + ticket: CmxAttachTicket, + allowsStackAuthFallback: Bool = false, + manualHostStackAuthTrustProvider: @escaping @Sendable () async -> Bool = { false }, + authScope: MobileRPCAuthScope = MobileRPCAuthScope(), + authScopeValidator: @escaping @Sendable () async -> Bool = { true }, + connectAttemptRegistry: MobileRPCConnectAttemptRegistry = MobileRPCConnectAttemptRegistry(), + stackTokenGate: RPCStackTokenGate? = nil, + stackTokenForceRefreshGate: RPCStackTokenGate? = nil, + abandonedConnectCleanupTimeoutNanoseconds: UInt64 = 1_000_000_000, + lateAbandonedConnectCloseTimeoutNanoseconds: UInt64 = 5_000_000_000, + stackTokenGateResetNanoseconds: UInt64 = 30_000_000_000 + ) -> MobileCoreRPCClient { + MobileCoreRPCClient( + runtime: runtime, + route: route, + ticket: ticket, + allowsStackAuthFallback: allowsStackAuthFallback, + manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider, + authScope: authScope, + authScopeValidator: authScopeValidator, + connectAttemptRegistry: connectAttemptRegistry, + stackTokenGate: stackTokenGate, + stackTokenForceRefreshGate: stackTokenForceRefreshGate, + abandonedConnectCleanupTimeoutNanoseconds: abandonedConnectCleanupTimeoutNanoseconds, + lateAbandonedConnectCloseTimeoutNanoseconds: lateAbandonedConnectCloseTimeoutNanoseconds, + stackTokenGateResetNanoseconds: stackTokenGateResetNanoseconds + ) + } +} diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift index 028f7164cb9c..04a100213bd8 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCClientTests.swift @@ -27,7 +27,7 @@ import Testing // Stack token unconditionally and would otherwise throw `insecureManualRoute` // before reaching the transport. This is a transport queue/cancellation test, // so enable fallback to match the real trusted-route path. - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -330,7 +330,7 @@ import Testing stackAccessToken: stackAccessToken, stackAccessTokenForStatus: stackAccessTokenForStatus ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: try qrPairingTicket(route: route), @@ -393,7 +393,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -435,7 +435,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCConnectWaiterTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCConnectWaiterTests.swift index a2eada753245..4cd48b6614e1 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCConnectWaiterTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCConnectWaiterTests.swift @@ -20,7 +20,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCGroupActionAuthTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCGroupActionAuthTests.swift index 909a589521ac..557777461166 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCGroupActionAuthTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCGroupActionAuthTests.swift @@ -20,7 +20,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -61,7 +61,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -103,7 +103,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCHostStatusTokenTimeoutTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCHostStatusTokenTimeoutTests.swift index 444ab90e258b..d2045a723da4 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCHostStatusTokenTimeoutTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCHostStatusTokenTimeoutTests.swift @@ -24,7 +24,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -70,7 +70,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift index ae6c3db16047..df481578e0e3 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCManualHostTrustTests.swift @@ -18,7 +18,7 @@ import Testing stackAccessToken: "trusted-manual-token", rpcRequestTimeoutNanoseconds: 60 * 1_000_000_000 ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: try qrPairingTicket(route: route), @@ -77,7 +77,7 @@ import Testing transportFactory: QueuedCancellationProbeTransportFactory(transport: transport), stackAccessToken: "trusted-manual-token" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: try qrPairingTicket(route: route), diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift index fc8e31597d72..97ae88a8541b 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift @@ -20,7 +20,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -97,7 +97,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -154,7 +154,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCTokenTimeoutTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCTokenTimeoutTests.swift index e6dfaa80cf5c..1299c50ebcc1 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCTokenTimeoutTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCTokenTimeoutTests.swift @@ -26,7 +26,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -74,7 +74,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -128,7 +128,8 @@ import Testing authToken: "ticket-secret" ) let sharedGate = RPCStackTokenGate(timedOutResetNanoseconds: 30_000_000_000) - let firstClient = MobileCoreRPCClient( + let sharedScope = MobileRPCAuthScope() + let firstClient = MobileCoreRPCClient.testClient( runtime: TestMobileSyncRuntime( transportFactory: QueuedCancellationProbeTransportFactory(transport: firstTransport), stackAccessTokenProvider: { try await tokenProvider.token() }, @@ -137,9 +138,10 @@ import Testing route: route, ticket: ticket, allowsStackAuthFallback: true, + authScope: sharedScope, stackTokenGate: sharedGate ) - let secondClient = MobileCoreRPCClient( + let secondClient = MobileCoreRPCClient.testClient( runtime: TestMobileSyncRuntime( transportFactory: QueuedCancellationProbeTransportFactory(transport: secondTransport), stackAccessTokenProvider: { try await tokenProvider.token() }, @@ -148,6 +150,7 @@ import Testing route: route, ticket: ticket, allowsStackAuthFallback: true, + authScope: sharedScope, stackTokenGate: sharedGate ) let request = try MobileCoreRPCClient.requestData( @@ -246,7 +249,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, @@ -325,7 +328,7 @@ import Testing expiresAt: Date().addingTimeInterval(60), authToken: "ticket-secret" ) - let client = MobileCoreRPCClient( + let client = MobileCoreRPCClient.testClient( runtime: runtime, route: route, ticket: ticket, diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/ScopedRPCValidationGate.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/ScopedRPCValidationGate.swift new file mode 100644 index 000000000000..56e1e4ff7ddc --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/ScopedRPCValidationGate.swift @@ -0,0 +1,36 @@ +import Foundation + +actor ScopedRPCValidationGate { + private let blockedCall: Int + private var callCount = 0 + private var isValid = true + private var blockedWaiters: [CheckedContinuation] = [] + private var releaseWaiters: [CheckedContinuation] = [] + + init(blockedCall: Int) { + self.blockedCall = blockedCall + } + + func validate() async -> Bool { + callCount += 1 + if callCount == blockedCall { + let waiters = blockedWaiters + blockedWaiters.removeAll() + for waiter in waiters { waiter.resume() } + await withCheckedContinuation { releaseWaiters.append($0) } + } + return isValid + } + + func waitUntilBlocked() async { + if callCount >= blockedCall { return } + await withCheckedContinuation { blockedWaiters.append($0) } + } + + func invalidateAndRelease() { + isValid = false + let waiters = releaseWaiters + releaseWaiters.removeAll() + for waiter in waiters { waiter.resume() } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileDeleteComputersVerifier.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileDeleteComputersVerifier.swift index 1e7f68f4fba2..8a87c71436c7 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileDeleteComputersVerifier.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileDeleteComputersVerifier.swift @@ -92,7 +92,8 @@ public struct MobileDeleteComputersVerifier { ) await shell.loadPairedMacs() - shell.setWorkspaceStatesForTesting(seededWorkspaceStates(), foregroundMacDeviceID: "mac-a") + shell.foregroundMacDeviceID = "mac-a" + shell.workspacesByMac = seededWorkspaceStates() let initial = checkpoint("initial", shell: shell) let halfDeleteIDs = ["mac-a", "mac-b"] diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellAuthorizationFailureOwner.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellAuthorizationFailureOwner.swift index bf687cd78104..d2812ec0f4ba 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellAuthorizationFailureOwner.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellAuthorizationFailureOwner.swift @@ -1,15 +1,16 @@ import CMUXMobileCore import CmuxMobileRPC +import Foundation /// The connection whose request produced an authorization failure. enum MobileShellAuthorizationFailureOwner { - case foreground(route: CmxAttachRoute?) + case foreground(client: MobileCoreRPCClient, generation: UUID, route: CmxAttachRoute?) case connectionAttempt(route: CmxAttachRoute?, preservingActiveConnection: Bool) case secondary(macDeviceID: String, client: MobileCoreRPCClient, route: CmxAttachRoute) var route: CmxAttachRoute? { switch self { - case let .foreground(route), let .connectionAttempt(route, _): + case let .foreground(_, _, route), let .connectionAttempt(route, _): route case let .secondary(_, _, route): route diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift index 375d5496db9f..cf31ac455941 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift @@ -12,10 +12,14 @@ extension MobileShellComposite { guard shouldDisconnectForAuthorizationFailure(error) else { return false } + if case let .foreground(client, generation, _) = owner, + (remoteClient !== client || connectionGeneration != generation) { + return true + } if let connectionError = error as? MobileShellConnectionError, case .insecureManualRoute = connectionError { switch owner { - case let .foreground(route): + case let .foreground(_, _, route): if queueForegroundManualHostReapproval(route: route) { return true } @@ -41,7 +45,7 @@ extension MobileShellComposite { return true } - private func queueForegroundManualHostReapproval(route: CmxAttachRoute?) -> Bool { + func queueForegroundManualHostReapproval(route: CmxAttachRoute?) -> Bool { guard let route, MobileShellRouteAuthPolicy().routeRequiresManualHostTrust(route), case let .hostPort(host, port) = route.endpoint else { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift index 5d79c9a0d439..fe0fbeecc0f4 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualAttachTicket.swift @@ -46,7 +46,8 @@ extension MobileShellComposite { port: Int, route: CmxAttachRoute? = nil, attemptStartedAt: Date?, - manualHostTrusted: Bool = false + manualHostTrusted: Bool = false, + authContext: MobileShellRPCAuthContext ) async throws -> CmxAttachTicket { let directRoute = try routeSelection.manualHostRoute(host: host, port: port, preserving: route) let displayName = name.isEmpty ? host : name @@ -58,7 +59,8 @@ extension MobileShellComposite { let ticket = try await requestManualAttachTicket( route: directRoute, displayName: displayName, - attemptStartedAt: attemptStartedAt + attemptStartedAt: attemptStartedAt, + authContext: authContext ) return ticket } catch { @@ -99,7 +101,8 @@ extension MobileShellComposite { func requestManualAttachTicket( route: CmxAttachRoute, displayName: String, - attemptStartedAt: Date? + attemptStartedAt: Date?, + authContext: MobileShellRPCAuthContext ) async throws -> CmxAttachTicket { guard let runtime else { throw MobileShellConnectionError.insecureManualRoute @@ -114,7 +117,12 @@ extension MobileShellComposite { route: route, ticket: probeTicket, allowsStackAuthFallback: true, - manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider(for: route), + manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider( + for: route, + stackUserID: authContext.stackUserID + ), + authScope: rpcAuthScopeForRoute(for: route, context: authContext), + authScopeValidator: rpcAuthScopeValidator(for: route, context: authContext), connectAttemptRegistry: connectAttemptRegistry, stackTokenGate: stackTokenGate, stackTokenForceRefreshGate: stackTokenForceRefreshGate diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 7df94d67f469..f687665e0924 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -17,28 +17,35 @@ extension MobileShellComposite { } } - func manualHostTrustScope(for route: CmxAttachRoute?) -> MobileManualHostTrustScope? { + func manualHostTrustScope( + for route: CmxAttachRoute?, + stackUserID: String? = nil + ) -> MobileManualHostTrustScope? { guard let route, MobileShellRouteAuthPolicy().routeRequiresManualHostTrust(route) else { return nil } return MobileManualHostTrustScope( route: route, - stackUserID: identityProvider?.currentUserID + stackUserID: stackUserID ?? identityProvider?.currentUserID ) } - func manualHostStackAuthTrusted(for route: CmxAttachRoute?) async -> Bool { - guard let scope = manualHostTrustScope(for: route) else { + func manualHostStackAuthTrusted( + for route: CmxAttachRoute?, + stackUserID: String? = nil + ) async -> Bool { + guard let scope = manualHostTrustScope(for: route, stackUserID: stackUserID) else { return false } return await manualHostTrustStore.isTrusted(scope) } func manualHostStackAuthTrustProvider( - for route: CmxAttachRoute? + for route: CmxAttachRoute?, + stackUserID: String? = nil ) -> @Sendable () async -> Bool { - guard let scope = manualHostTrustScope(for: route) else { + guard let scope = manualHostTrustScope(for: route, stackUserID: stackUserID) else { return { false } } let trustStore = manualHostTrustStore @@ -47,19 +54,23 @@ extension MobileShellComposite { } } - func manualHostRouteNeedsApproval(_ route: CmxAttachRoute) async -> Bool { - guard let scope = manualHostTrustScope(for: route) else { + func manualHostRouteNeedsApproval( + _ route: CmxAttachRoute, + stackUserID: String? = nil + ) async -> Bool { + guard let scope = manualHostTrustScope(for: route, stackUserID: stackUserID) else { return false } return !(await manualHostTrustStore.isTrusted(scope)) } func firstManualHostRouteNeedingApproval( - in routes: [CmxAttachRoute] + in routes: [CmxAttachRoute], + stackUserID: String? ) async -> (route: CmxAttachRoute, scope: MobileManualHostTrustScope)? { let routeAuthPolicy = MobileShellRouteAuthPolicy() for route in routes { - if let scope = manualHostTrustScope(for: route) { + if let scope = manualHostTrustScope(for: route, stackUserID: stackUserID) { if !(await manualHostTrustStore.isTrusted(scope)) { return (route, scope) } @@ -97,13 +108,13 @@ extension MobileShellComposite { } /// Persists the queued manual-host trust approval and resumes the pending pairing attempt. - /// - Returns: The resumed pairing attempt's connection result, or `.failed` if no warning is pending. + /// - Returns: The resumed result, or `.superseded` when the warning is no longer current. @discardableResult public func acceptManualHostTrustWarning() async -> MobilePairingURLConnectionResult { guard let warning = manualHostTrustWarning, let pending = pendingManualHostTrust else { clearManualHostTrustWarning() - return .failed + return .superseded } guard isPendingManualHostTrustCurrent(pending) else { finishPendingManualHostSwitchAttempt(pending) @@ -111,8 +122,19 @@ extension MobileShellComposite { return .superseded } let workspaceOpenIntent = takePendingWorkspaceOpenIntent(for: pending) + let approvalAuthScope = manualHostRPCAuthScope clearManualHostTrustWarning() await manualHostTrustStore.trust(warning.scope) + guard approvalAuthScope == manualHostRPCAuthScope else { + // A path change can race persistence. Remove again after the write so + // trust from the previous network epoch cannot survive the boundary. + await manualHostTrustStore.removeAll() + if let workspaceOpenIntent { + cancelWorkspaceOpen(workspaceOpenIntent) + } + finishPendingManualHostSwitchAttempt(pending) + return .superseded + } guard isPendingManualHostTrustCurrent(pending) else { if let workspaceOpenIntent { cancelWorkspaceOpen(workspaceOpenIntent) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacAliases.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacAliases.swift index 8081ce7219c1..a814a2350bea 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacAliases.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacAliases.swift @@ -8,7 +8,6 @@ extension MobileShellComposite { Self.coalescePairedMacsByDialEndpoint( pairedMacs, supportedKinds: runtime?.supportedRouteKinds ?? [], - preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, routeSelection: routeSelection ) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift index b5f034f60b2b..1c279dfa6494 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacCoalescing.swift @@ -15,7 +15,6 @@ extension MobileShellComposite { static func coalescePairedMacsByDialEndpoint( _ macs: [MobilePairedMac], supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool, routeSelection: MobileShellRouteSelection ) -> [MobilePairedMac] { var selectedByKey: [String: MobilePairedMac] = [:] @@ -24,7 +23,6 @@ extension MobileShellComposite { for (index, mac) in macs.enumerated() { let key = mac.dialEndpointKey( supportedKinds: supportedKinds, - preferNonLoopback: preferNonLoopback, routeSelection: routeSelection ) ?? "device:\(mac.macDeviceID)" orderByKey[key] = min(orderByKey[key] ?? index, index) @@ -50,13 +48,11 @@ extension MobileShellComposite { _ macDeviceID: String, in macs: [MobilePairedMac], supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool, routeSelection: MobileShellRouteSelection ) -> [String] { guard let target = macs.first(where: { $0.macDeviceID == macDeviceID }), let key = target.dialEndpointKey( supportedKinds: supportedKinds, - preferNonLoopback: preferNonLoopback, routeSelection: routeSelection ) else { return [macDeviceID] @@ -64,7 +60,6 @@ extension MobileShellComposite { let matching = macs.filter { $0.dialEndpointKey( supportedKinds: supportedKinds, - preferNonLoopback: preferNonLoopback, routeSelection: routeSelection ) == key }.map(\.macDeviceID) @@ -74,13 +69,11 @@ extension MobileShellComposite { func macDeviceIDAliasSetsByPairedMacID( in macs: [MobilePairedMac], supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool, routeSelection: MobileShellRouteSelection ) -> [String: Set] { macDeviceIDAliasesByPairedMacID( in: macs, supportedKinds: supportedKinds, - preferNonLoopback: preferNonLoopback, routeSelection: routeSelection ).mapValues(Set.init) } @@ -88,7 +81,6 @@ extension MobileShellComposite { func macDeviceIDAliasesByPairedMacID( in macs: [MobilePairedMac], supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool, routeSelection: MobileShellRouteSelection ) -> [String: [String]] { var groupKeyByMacID: [String: String] = [:] @@ -96,7 +88,6 @@ extension MobileShellComposite { for mac in macs { let key = mac.dialEndpointKey( supportedKinds: supportedKinds, - preferNonLoopback: preferNonLoopback, routeSelection: routeSelection ) ?? "device:\(mac.macDeviceID)" groupKeyByMacID[mac.macDeviceID] = key @@ -115,7 +106,6 @@ private extension MobilePairedMac { @MainActor func dialEndpointKey( supportedKinds: [CmxAttachTransportKind], - preferNonLoopback: Bool, routeSelection: MobileShellRouteSelection ) -> String? { guard let displayName = displayName?.trimmingCharacters(in: .whitespacesAndNewlines), @@ -125,7 +115,7 @@ private extension MobilePairedMac { guard let (host, port) = routeSelection.firstReconnectHostPortRoute( routes, supportedKinds: supportedKinds, - preferNonLoopback: preferNonLoopback + preferNonLoopback: routeSelection.prefersNonLoopbackRoutes ), let normalizedHost = MobileShellRouteAuthPolicy().normalizedManualRouteHost(host) else { return nil } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift index 9307e09767b6..24b4c16ae5e4 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift @@ -133,7 +133,6 @@ extension MobileShellComposite { let aliasSetsByMacID = macDeviceIDAliasSetsByPairedMacID( in: candidates, supportedKinds: supportedKinds, - preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, routeSelection: routeSelection ) return candidates.first { candidate in diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift index e3b59807066d..afbcb7e9d0a6 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift @@ -1,7 +1,93 @@ +import CMUXMobileCore +import CmuxMobileRPC +import CmuxMobileShellModel import Foundation @MainActor extension MobileShellComposite { + /// Resets the complete shell boundary if Stack replaces A with B without a signed-out edge. + func prepareRPCAuthForSignIn() -> Bool { + let currentUserID = identityProvider?.currentUserID?.trimmingCharacters(in: .whitespacesAndNewlines) + let normalizedUserID = currentUserID?.isEmpty == false ? currentUserID : nil + let replacedAuthenticatedUser = isSignedIn && rpcAuthStackUserID != normalizedUserID + if replacedAuthenticatedUser { + signOut() + } + rpcAuthStackUserID = normalizedUserID + return replacedAuthenticatedUser + } + + func rotateRPCAuthScope() { + let invalidatedScopes = [rpcAuthScope, manualHostRPCAuthScope] + for scope in invalidatedScopes { scope.revoke() } + rpcAuthScope = MobileRPCAuthScope() + manualHostRPCAuthScope = MobileRPCAuthScope() + let tokenGate = stackTokenGate + let forceRefreshGate = stackTokenForceRefreshGate + Task { + for scope in invalidatedScopes { + await tokenGate.invalidate(scope: scope) + await forceRefreshGate.invalidate(scope: scope) + } + } + } + + /// Invalidates only plaintext manual-host credentials after a network-path change. + func rotateManualHostRPCAuthScope() { + let invalidatedScope = manualHostRPCAuthScope + invalidatedScope.revoke() + manualHostRPCAuthScope = MobileRPCAuthScope() + let tokenGate = stackTokenGate + let forceRefreshGate = stackTokenForceRefreshGate + Task { + await tokenGate.invalidate(scope: invalidatedScope) + await forceRefreshGate.invalidate(scope: invalidatedScope) + } + } + + func currentRPCAuthContext() -> MobileShellRPCAuthContext { + MobileShellRPCAuthContext( + stackUserID: identityProvider?.currentUserID, + accountScope: rpcAuthScope, + manualHostScope: manualHostRPCAuthScope + ) + } + + func isRPCAuthContextCurrent( + _ context: MobileShellRPCAuthContext, + requiresManualHostScope: Bool = true + ) -> Bool { + guard isSignedIn, + identityProvider?.currentUserID == context.stackUserID, + rpcAuthScope == context.accountScope else { + return false + } + return !requiresManualHostScope || manualHostRPCAuthScope == context.manualHostScope + } + + func rpcAuthScopeForRoute( + for route: CmxAttachRoute, + context: MobileShellRPCAuthContext + ) -> MobileRPCAuthScope { + MobileShellRouteAuthPolicy().routeRequiresManualHostTrust(route) + ? context.manualHostScope + : context.accountScope + } + + func rpcAuthScopeValidator( + for route: CmxAttachRoute, + context: MobileShellRPCAuthContext + ) -> @Sendable () async -> Bool { + let requiresManualHostScope = MobileShellRouteAuthPolicy().routeRequiresManualHostTrust(route) + return { [weak self] in + guard let self else { return false } + return await self.isRPCAuthContextCurrent( + context, + requiresManualHostScope: requiresManualHostScope + ) + } + } + /// Capture the current signed-in account/team scope for async list loads and /// route writes. func currentScopeSnapshot(userID explicitUserID: String? = nil) async -> MobileShellScopeSnapshot? { @@ -14,10 +100,23 @@ extension MobileShellComposite { currentUserID != userID { return nil } + let generation = secondaryAggregationScopeGeneration + let signInGeneration = currentSessionGeneration + let rpcAuthContext = currentRPCAuthContext() + let teamID = await teamIDProvider() + guard isSignedIn, + identityProvider?.currentUserID == userID, + generation == secondaryAggregationScopeGeneration, + signInGeneration == currentSessionGeneration, + isRPCAuthContextCurrent(rpcAuthContext) else { + return nil + } return MobileShellScopeSnapshot( userID: userID, - teamID: await teamIDProvider(), - generation: secondaryAggregationScopeGeneration + teamID: teamID, + generation: generation, + signInGeneration: signInGeneration, + rpcAuthContext: rpcAuthContext ) } @@ -30,13 +129,21 @@ extension MobileShellComposite { } func userWideScope(from scope: MobileShellScopeSnapshot) -> MobileShellScopeSnapshot { - MobileShellScopeSnapshot(userID: scope.userID, teamID: nil, generation: scope.generation) + MobileShellScopeSnapshot( + userID: scope.userID, + teamID: nil, + generation: scope.generation, + signInGeneration: scope.signInGeneration, + rpcAuthContext: scope.rpcAuthContext + ) } /// Whether a previously-captured list-load scope is still current. func isScopeCurrent(_ scope: MobileShellScopeSnapshot) async -> Bool { guard isSignedIn, - secondaryAggregationScopeGeneration == scope.generation else { + secondaryAggregationScopeGeneration == scope.generation, + currentSessionGeneration == scope.signInGeneration, + isRPCAuthContextCurrent(scope.rpcAuthContext) else { return false } if let currentUserID = identityProvider?.currentUserID, @@ -45,4 +152,5 @@ extension MobileShellComposite { } return await teamIDProvider() == scope.teamID } + } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift index e0ed129d5494..34725c1b8313 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceActions.swift @@ -337,8 +337,14 @@ extension MobileShellComposite { client: client, route: route ) + } else if let generation = target.connectionGeneration { + failureOwner = .foreground( + client: client, + generation: generation, + route: target.route + ) } else { - failureOwner = .foreground(route: target.route) + return .failure(.notConnected(hostDisplayName: hostDisplayName)) } if handleAuthorizationFailureIfNeeded(error, owner: failureOwner) { return .failure(.authorizationFailed(hostDisplayName: hostDisplayName)) @@ -374,6 +380,7 @@ extension MobileShellComposite { return WorkspaceMutationTarget( client: remoteClient, route: activeRoute, + connectionGeneration: connectionGeneration, isForeground: true, macDeviceID: foregroundMacDeviceID ) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceCreateRequest.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceCreateRequest.swift index a6a2b434b240..0ae781d869bc 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceCreateRequest.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceCreateRequest.swift @@ -81,7 +81,11 @@ extension MobileShellComposite { guard generation == connectionGeneration, !Task.isCancelled else { return .success(()) } if handleAuthorizationFailureIfNeeded( error, - owner: .foreground(route: activeRoute) + owner: .foreground( + client: client, + generation: generation, + route: activeRoute + ) ) { return .failure(.authorizationFailed(hostDisplayName: connectedHostName)) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceMutationTarget.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceMutationTarget.swift new file mode 100644 index 000000000000..5a6237bf49fb --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+WorkspaceMutationTarget.swift @@ -0,0 +1,34 @@ +import CmuxMobileShellModel + +@MainActor +extension MobileShellComposite { + /// Returns the live client that owns a workspace row in the aggregated list. + func workspaceMutationTarget(for id: MobileWorkspacePreview.ID) -> WorkspaceMutationTarget { + let owner = workspaces.first(where: { $0.id == id })?.macDeviceID + if owner == nil || owner == foregroundMacDeviceID || owner == Self.foregroundAnonymousKey { + return WorkspaceMutationTarget( + client: remoteClient, + route: activeRoute, + connectionGeneration: connectionGeneration, + isForeground: true, + macDeviceID: foregroundMacDeviceID + ) + } + if let owner, let subscription = secondaryMacSubscriptions[owner] { + return WorkspaceMutationTarget( + client: subscription.client, + route: subscription.route, + connectionGeneration: nil, + isForeground: false, + macDeviceID: owner + ) + } + return WorkspaceMutationTarget( + client: nil, + route: nil, + connectionGeneration: nil, + isForeground: false, + macDeviceID: owner + ) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 4ee65fef0657..eea0c3c2456e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -631,6 +631,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let connectAttemptRegistry = MobileRPCConnectAttemptRegistry() let stackTokenGate = RPCStackTokenGate() let stackTokenForceRefreshGate = RPCStackTokenGate() + var rpcAuthScope = MobileRPCAuthScope() + var manualHostRPCAuthScope = MobileRPCAuthScope() + var rpcAuthStackUserID: String? /// Collapses connection-state edges into one-per-outage lost/recovered events. private var connectionOutageThrottle = ConnectionOutageThrottle() /// When the current outage began, for the recovered event's duration. @@ -1059,7 +1062,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } public func signIn() { + let replacedAuthenticatedUser = prepareRPCAuthForSignIn() let wasSignedIn = isSignedIn + if !wasSignedIn && !replacedAuthenticatedUser { + rotateRPCAuthScope() + } isSignedIn = true clearPairingError() // Fire only on the signed-out→signed-in edge (this is called on every @@ -1078,6 +1085,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } public func signOut() { + rotateRPCAuthScope() + rpcAuthStackUserID = nil // Reset analytics identity to anonymous on the signed-in→signed-out edge // only (this is called on every unauthenticated auth-state sync). if isSignedIn { @@ -1465,7 +1474,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // connection so a moving network repaints instead of going stale. for await _ in reachability.pathChanges() { guard let self, !Task.isCancelled else { return } + self.rotateManualHostRPCAuthScope() + self.invalidatePairingAttempt() + self.clearSupersededManualHostTrustWarning() await self.manualHostTrustStore.removeAll() + if self.remoteClient != nil, + self.queueForegroundManualHostReapproval(route: self.activeRoute) { + continue + } self.recoverMobileConnection(trigger: .networkChange) } } @@ -1604,6 +1620,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) async -> MobilePairingURLConnectionResult { let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) let preservesActiveConnection = hasActiveMacConnection + let authContext = currentRPCAuthContext() guard let normalizedHost = MobileShellRouteAuthPolicy().normalizedManualRouteHost(host) else { connectionError = L10n.string("mobile.addDevice.invalidHost", defaultValue: "Enter a host or IP address, without spaces or URL paths.") connectionErrorGuidance = nil @@ -1629,11 +1646,19 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return .failed } + guard authContext.hasStackUserID else { + applyAuthorizationFailure(.authFailed, preservingActiveConnection: preservesActiveConnection) + return .failed + } let directRoute = try? routeSelection.manualHostRoute(host: normalizedHost, port: port, preserving: route) let approvalAttemptID = beginPairingValidationAttempt() if let directRoute { - let needsApproval = await manualHostRouteNeedsApproval(directRoute) - guard isCurrentPairingAttempt(approvalAttemptID) else { return .superseded } + let needsApproval = await manualHostRouteNeedsApproval( + directRoute, + stackUserID: authContext.stackUserID + ) + guard isCurrentPairingAttempt(approvalAttemptID), + isRPCAuthContextCurrent(authContext) else { return .superseded } if needsApproval { queueManualHostTrustWarning( route: directRoute, @@ -1674,19 +1699,26 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } do { guard ifStillCurrent?() != false else { return .superseded } - let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) - guard isCurrentPairingAttempt(attemptID), ifStillCurrent?() != false else { return .superseded } + let manualHostTrusted = await manualHostStackAuthTrusted( + for: directRoute, + stackUserID: authContext.stackUserID + ) + guard isCurrentPairingAttempt(attemptID), + isRPCAuthContextCurrent(authContext), + ifStillCurrent?() != false else { return .superseded } let ticket = try await manualHostTicket( name: trimmedName, host: normalizedHost, port: port, route: directRoute, attemptStartedAt: pairingAttemptStartedAt, - manualHostTrusted: manualHostTrusted + manualHostTrusted: manualHostTrusted, + authContext: authContext ) guard isCurrentPairingAttempt(attemptID) else { return .superseded } let noThrowFailure = try await connect( ticket: ticket, + authContext: authContext, allowsStackAuthFallback: directRoute.map { MobileShellRouteAuthPolicy().routeAllowsStackAuth( $0, @@ -2300,7 +2332,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { activeMacID, in: knownMacs, supportedKinds: self.runtime?.supportedRouteKinds ?? [], - preferNonLoopback: self.routeSelection.prefersNonLoopbackRoutes, routeSelection: self.routeSelection )) { self.recoverMobileConnection(trigger: .presencePush) @@ -2432,7 +2463,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { if result == .needsUserApproval || result == .superseded { return } - guard connectionState == .connected, + guard result == .connected, connectionState == .connected, + foregroundMacDeviceID == device.deviceId, case let .hostPort(liveHost, livePort)? = activeRoute?.endpoint, routeAuthPolicy.normalizedManualRouteHost(liveHost) == routeAuthPolicy.normalizedManualRouteHost(route.host), livePort == route.port else { @@ -2515,13 +2547,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let coalesced = Self.coalescePairedMacsByDialEndpoint( visibleLoaded, supportedKinds: supportedRouteKinds, - preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, routeSelection: routeSelection ) let aliasIDsByMacID = macDeviceIDAliasesByPairedMacID( in: visibleLoaded, supportedKinds: supportedRouteKinds, - preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, routeSelection: routeSelection ) pairedMacAliasIDsByRepresentativeID = coalesced.reduce(into: [String: [String]]()) { result, mac in @@ -3147,6 +3177,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { approvedManualRouteID: String? = nil ) async -> MobilePairingURLConnectionResult { let rawURL = Self.normalizedPairingURL(rawValue ?? pairingCode) + let authContext = currentRPCAuthContext() let validationAttemptID = beginPairingValidationAttempt() let preservesActiveConnection = hasActiveMacConnection connectionAttemptGeneration = UUID() @@ -3221,8 +3252,17 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { applyPairingValidationFailure(.invalidCode) return .failed } - let manualHostApproval = await firstManualHostRouteNeedingApproval(in: routesForAttempt) - guard isCurrentPairingAttempt(validationAttemptID) else { return .superseded } + if routesForAttempt.first.map(MobileShellRouteAuthPolicy().routeRequiresManualHostTrust) == true, + !authContext.hasStackUserID { + applyAuthorizationFailure(.authFailed, preservingActiveConnection: preservesActiveConnection) + return .failed + } + let manualHostApproval = await firstManualHostRouteNeedingApproval( + in: routesForAttempt, + stackUserID: authContext.stackUserID + ) + guard isCurrentPairingAttempt(validationAttemptID), + isRPCAuthContextCurrent(authContext) else { return .superseded } if let approval = manualHostApproval, case let .hostPort(host, _) = approval.route.endpoint { queueManualHostTrustWarning( @@ -3257,6 +3297,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard isCurrentPairingAttempt(attemptID) else { return .superseded } let noThrowFailure = try await connect( ticket: ticketForAttempt, + authContext: authContext, pendingManualHostTrust: .pairingURL( attemptID: attemptID, rawURL: rawURL, @@ -3305,12 +3346,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// Cancels the active pairing attempt and clears transient pairing prompts. public func cancelPairing() { + let preservesActiveConnection = hasActiveMacConnection invalidatePairingAttempt() clearPairingError() - let hadBlockingPrompt = pairingVersionWarning != nil || pendingPairingVersionWarningURL != nil || manualHostTrustWarning != nil clearPairingVersionWarning() clearSupersededManualHostTrustWarning() - if hadBlockingPrompt, hasActiveMacConnection { return } + if preservesActiveConnection { return } connectionState = .disconnected macConnectionStatus = .unavailable clearRemoteConnectionContext() @@ -3427,8 +3468,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// ticket), or nil if it has no reachable route / the ticket fails. The caller /// owns disconnecting it. Routes are loopback-deprioritized on device. Never /// touches the foreground connection. - private func makeSecondaryClient(for mac: MobilePairedMac) async -> SecondaryClientHandle? { + private func makeSecondaryClient(for mac: MobilePairedMac, scope: MobileShellScopeSnapshot) async -> SecondaryClientHandle? { guard let runtime else { return nil } + guard await isScopeCurrent(scope) else { return nil } let supportedKinds = runtime.supportedRouteKinds guard let candidate = routeSelection.reconnectHostPortRoutes( mac.routes, @@ -3446,14 +3488,19 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { port: port, preserving: candidate.route ) - let manualHostTrusted = await manualHostStackAuthTrusted(for: directRoute) + let manualHostTrusted = await manualHostStackAuthTrusted( + for: directRoute, + stackUserID: scope.userID + ) + guard await isScopeCurrent(scope) else { return nil } ticket = try await manualHostTicket( name: mac.displayName ?? host, host: host, port: port, route: directRoute, attemptStartedAt: nil, - manualHostTrusted: manualHostTrusted + manualHostTrusted: manualHostTrusted, + authContext: scope.rpcAuthContext ) } catch { mobileShellLog.warning( @@ -3476,7 +3523,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { }) ?? supportedRoutes.first(where: { $0.kind != .debugLoopback }) ?? supportedRoutes.first guard let route else { return nil } - let manualHostTrusted = await manualHostStackAuthTrusted(for: route) + let manualHostTrusted = await manualHostStackAuthTrusted( + for: route, + stackUserID: scope.userID + ) + guard await isScopeCurrent(scope) else { return nil } guard MobileShellRouteAuthPolicy().routeAllowsStackAuth( route, manualHostTrusted: manualHostTrusted @@ -3488,7 +3539,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { route: route, ticket: ticket, allowsStackAuthFallback: true, - manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider(for: route), + manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider( + for: route, + stackUserID: scope.userID + ), + authScope: rpcAuthScopeForRoute(for: route, context: scope.rpcAuthContext), + authScopeValidator: rpcAuthScopeValidator(for: route, context: scope.rpcAuthContext), connectAttemptRegistry: connectAttemptRegistry, stackTokenGate: stackTokenGate, stackTokenForceRefreshGate: stackTokenForceRefreshGate @@ -3572,10 +3628,21 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// write). Replaces any prior in-flight pass. func scheduleSecondaryAggregation() { secondaryAggregationTask?.cancel() - secondaryAggregationTask = Task { [weak self] in await self?.refreshSecondaryMacWorkspaces() } + secondaryAggregationTask = Task { [weak self] in + await self?.performSecondaryMacWorkspaceRefresh() + } } func refreshSecondaryMacWorkspaces() async { + secondaryAggregationTask?.cancel() + secondaryAggregationTask = Task { [weak self] in + guard let self else { return } + await self.performSecondaryMacWorkspaceRefresh() + } + await secondaryAggregationTask?.value + } + + private func performSecondaryMacWorkspaceRefresh() async { guard let pairedMacStore, multiMacAggregationEnabled else { return } // Require a concrete signed-in user before any load/connection: a nil/empty // account would make `loadAll(stackUserID: nil)` read EVERY locally stored @@ -3674,13 +3741,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let macs = Self.coalescePairedMacsByDialEndpoint( visibleLoadedMacs, supportedKinds: supportedRouteKinds, - preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, routeSelection: routeSelection ) let aliasIDsByMacID = macDeviceIDAliasesByPairedMacID( in: visibleLoadedMacs, supportedKinds: supportedRouteKinds, - preferNonLoopback: routeSelection.prefersNonLoopbackRoutes, routeSelection: routeSelection ) let foregroundMacDeviceIDs = foregroundMacDeviceID.map { @@ -3701,7 +3766,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) async { let macID = mac.macDeviceID guard secondaryMacSubscriptions[macID] == nil else { return } - guard let handle = await makeSecondaryClient(for: mac) else { + guard let handle = await makeSecondaryClient(for: mac, scope: scope) else { guard await isSecondaryMacStillVisible(macID, scope: scope) else { return } markSecondaryMacUnavailable(macID) return @@ -3827,36 +3892,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } - /// Routing target for a workspace mutation (rename / pin / unread / close): the - /// connection that owns `id` in the aggregated multi-Mac list. - /// - /// - `client == remoteClient`, `isForeground == true` for a foreground-owned - /// row, a single-Mac session, or an anonymous/manual host (owner unknown). - /// - the live secondary connection for a row owned by another aggregated Mac. - /// - `client == nil` when the owner is a known non-foreground Mac that has no - /// live connection right now, so the caller must NOT fall back to the - /// foreground client (that is exactly the wrong-Mac bug this avoids). - func workspaceMutationTarget(for id: MobileWorkspacePreview.ID) -> WorkspaceMutationTarget { - let owner = workspaces.first(where: { $0.id == id })?.macDeviceID - if owner == nil || owner == foregroundMacDeviceID || owner == Self.foregroundAnonymousKey { - return WorkspaceMutationTarget( - client: remoteClient, - route: activeRoute, - isForeground: true, - macDeviceID: foregroundMacDeviceID - ) - } - if let owner, let sub = secondaryMacSubscriptions[owner] { - return WorkspaceMutationTarget( - client: sub.client, - route: sub.route, - isForeground: false, - macDeviceID: owner - ) - } - return WorkspaceMutationTarget(client: nil, route: nil, isForeground: false, macDeviceID: owner) - } - /// Re-sync the authoritative workspace list for the Mac a mutation actually hit: /// the foreground's coalesced refresh, or the owning secondary's coalesced /// re-fetch (so a pin/close on a secondary row snaps to the Mac's real state). @@ -4940,6 +4975,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { @discardableResult private func connect( ticket: CmxAttachTicket, + authContext: MobileShellRPCAuthContext, allowsStackAuthFallback: Bool? = nil, pendingManualHostTrust: PendingManualHostTrust? = nil, pairedMacDeviceID: String? = nil, @@ -4993,8 +5029,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } mobileShellLog.info("pairing trying route kind=\(route.kind.rawValue, privacy: .public) endpoint=\(route.endpoint.logDescription, privacy: .private)") if let pendingManualHostTrust { - let needsApproval = await manualHostRouteNeedsApproval(route) - guard isConnectCurrent() else { return nil } + let needsApproval = await manualHostRouteNeedsApproval( + route, + stackUserID: authContext.stackUserID + ) + guard isConnectCurrent(), + isRPCAuthContextCurrent(authContext) else { return nil } if needsApproval, case let .hostPort(host, _) = route.endpoint { queueManualHostTrustWarning( route: route, @@ -5004,7 +5044,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { throw ManualHostTrustApprovalQueued.required } } - let manualHostTrusted = await manualHostStackAuthTrusted(for: route) + let manualHostTrusted = await manualHostStackAuthTrusted( + for: route, + stackUserID: authContext.stackUserID + ) + guard isConnectCurrent(), + isRPCAuthContextCurrent(authContext) else { return nil } let routeAllowsStackAuth = MobileShellRouteAuthPolicy().routeAllowsStackAuth( route, manualHostTrusted: manualHostTrusted @@ -5015,7 +5060,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ticket: ticket, allowsStackAuthFallback: routeAllowsStackAuthFallbackOverride ?? routeAllowsStackAuth, - manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider(for: route), + manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider( + for: route, + stackUserID: authContext.stackUserID + ), + authScope: rpcAuthScopeForRoute(for: route, context: authContext), + authScopeValidator: rpcAuthScopeValidator(for: route, context: authContext), connectAttemptRegistry: connectAttemptRegistry, stackTokenGate: stackTokenGate, stackTokenForceRefreshGate: stackTokenForceRefreshGate @@ -5226,7 +5276,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { if isCurrentRemoteConnection(client: client, generation: generation) { _ = handleAuthorizationFailureIfNeeded( error, - owner: .foreground(route: activeRoute) + owner: .foreground(client: client, generation: generation, route: activeRoute) ) } return false @@ -5244,7 +5294,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { connectionRequiresReauth = false connectionState = .disconnected macConnectionStatus = .unavailable - clearRemoteConnectionContext() + clearRemoteConnectionContext(preservingOtherMacWorkspaceState: true) } /// Removes a failed secondary client from the internal connection pool. @@ -5902,7 +5952,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard generation == connectionGeneration, !Task.isCancelled else { return } guard !handleAuthorizationFailureIfNeeded( error, - owner: .foreground(route: activeRoute) + owner: .foreground(client: client, generation: generation, route: activeRoute) ) else { return } markMacConnectionUnavailableIfNeeded(after: error) applyOperationalError(error) @@ -5966,7 +6016,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard generation == connectionGeneration else { return } guard !handleAuthorizationFailureIfNeeded( error, - owner: .foreground(route: activeRoute) + owner: .foreground(client: client, generation: generation, route: activeRoute) ) else { return } markMacConnectionUnavailableIfNeeded(after: error) applyOperationalError(error) @@ -6053,7 +6103,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard generation == connectionGeneration else { return false } guard !handleAuthorizationFailureIfNeeded( error, - owner: .foreground(route: activeRoute) + owner: .foreground(client: client, generation: generation, route: activeRoute) ) else { return false } markMacConnectionUnavailableIfNeeded(after: error) applyOperationalError(error) @@ -6153,7 +6203,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard generation == connectionGeneration else { return false } guard !handleAuthorizationFailureIfNeeded( error, - owner: .foreground(route: activeRoute) + owner: .foreground(client: client, generation: generation, route: activeRoute) ) else { return false } markMacConnectionUnavailableIfNeeded(after: error) applyOperationalError(error) @@ -6186,6 +6236,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { reason: String, topics: [String] ) async -> TerminalEventSubscriptionAck { + let generation = connectionGeneration let requestData: Data do { requestData = try MobileCoreRPCClient.requestData( @@ -6216,10 +6267,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // A definitive auth failure here (RPC layer already tried a // force-refresh + retry) must drive the re-auth prompt instead of a // silently stale live frame. - if remoteClient === client { + if isCurrentRemoteConnection(client: client, generation: generation) { _ = handleAuthorizationFailureIfNeeded( error, - owner: .foreground(route: activeRoute) + owner: .foreground(client: client, generation: generation, route: activeRoute) ) } return .failed @@ -6955,6 +7006,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { #endif return } + let generation = connectionGeneration guard let workspaceID = workspaceID(forTerminalID: surfaceID) else { clearTerminalReplayBarrierIfCurrent( surfaceID: surfaceID, @@ -7265,7 +7317,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // prompt instead of silently leaving a stale frame. guard !self.handleAuthorizationFailureIfNeeded( error, - owner: .foreground(route: self.activeRoute) + owner: .foreground( + client: client, + generation: generation, + route: self.activeRoute + ) ) else { return } if let retryToken = self.prepareTerminalReplayFailureRetry( surfaceID: surfaceID, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRPCAuthContext.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRPCAuthContext.swift new file mode 100644 index 000000000000..d344cdb735db --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRPCAuthContext.swift @@ -0,0 +1,13 @@ +import CmuxMobileRPC +import Foundation + +/// Immutable credential owner captured before an asynchronous mobile RPC flow begins. +struct MobileShellRPCAuthContext: Equatable, Sendable { + let stackUserID: String? + let accountScope: MobileRPCAuthScope + let manualHostScope: MobileRPCAuthScope + + var hasStackUserID: Bool { + stackUserID?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift index eae49abfa217..ecd51ed9de48 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift @@ -143,14 +143,19 @@ struct MobileShellRouteSelection: Sendable { port: Int, isPhysicalDevice: Bool? = nil ) throws -> CmxAttachRoute { - let routeKind = routeAuthPolicy.manualRouteKind( - for: host, + guard let normalizedHost = routeAuthPolicy.normalizedManualRouteHost(host) else { + throw URLError(.badURL) + } + guard let routeKind = routeAuthPolicy.manualRouteKind( + for: normalizedHost, allowsDebugLoopback: !(isPhysicalDevice ?? self.isPhysicalDevice) - ) + ) else { + throw URLError(.badURL) + } return try CmxAttachRoute( id: routeKind.rawValue, kind: routeKind, - endpoint: .hostPort(host: host, port: port) + endpoint: .hostPort(host: normalizedHost, port: port) ) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellScopeSnapshot.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellScopeSnapshot.swift index 2d1bb8390130..a2146cc89741 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellScopeSnapshot.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellScopeSnapshot.swift @@ -6,4 +6,6 @@ struct MobileShellScopeSnapshot: Equatable, Sendable { let userID: String let teamID: String? let generation: Int + let signInGeneration: Int + let rpcAuthContext: MobileShellRPCAuthContext } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/WorkspaceMutationTarget.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/WorkspaceMutationTarget.swift index 39a76d3aadba..c35d615a8bc6 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/WorkspaceMutationTarget.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/WorkspaceMutationTarget.swift @@ -1,11 +1,13 @@ import CMUXMobileCore import CmuxMobileRPC import CmuxMobileShellModel +import Foundation /// Routing target for a workspace mutation in the aggregated multi-Mac list. struct WorkspaceMutationTarget { let client: MobileCoreRPCClient? let route: CmxAttachRoute? + let connectionGeneration: UUID? let isForeground: Bool let macDeviceID: String? } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ComposerSubmitRoutingTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ComposerSubmitRoutingTestSupport.swift index 550aa6cde020..714015d39987 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ComposerSubmitRoutingTestSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ComposerSubmitRoutingTestSupport.swift @@ -406,7 +406,9 @@ func makeRoutingConnectedStore( runtime: runtime, route: route, ticket: ticket, - allowsStackAuthFallback: true + allowsStackAuthFallback: true, + authScope: MobileRPCAuthScope(), + authScopeValidator: { true } ) store.foregroundMacDeviceID = "test-mac" return store @@ -438,7 +440,9 @@ func installFreshRemoteClient(on store: MobileShellComposite, router: RoutingHos runtime: runtime, route: route, ticket: ticket, - allowsStackAuthFallback: true + allowsStackAuthFallback: true, + authScope: MobileRPCAuthScope(), + authScopeValidator: { true } ) store.foregroundMacDeviceID = "test-mac-2" } @@ -470,7 +474,9 @@ func installSecondaryClient( runtime: runtime, route: route, ticket: ticket, - allowsStackAuthFallback: true + allowsStackAuthFallback: true, + authScope: MobileRPCAuthScope(), + authScopeValidator: { true } ) store.secondaryMacSubscriptions[macDeviceID] = SecondaryMacSubscription( macDeviceID: macDeviceID, diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 10e242fbf8c6..c10e036c6b29 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -34,8 +34,9 @@ import Testing transportFactory: CountingSlowIgnoringCancellationTransportFactory(transport: transport) ) let store = makeStore(runtime: runtime) - - let first = await store.connectPairingURLResult(Self.qrURL) + let firstTask = Task { @MainActor in await store.connectPairingURLResult(Self.qrURL) } + await transport.waitUntilConnectStarted() + let first = await firstTask.value let second = await store.connectPairingURLResult(Self.qrURL) let connectCount = await transport.connectCount() await transport.releaseStuckConnects() @@ -45,7 +46,6 @@ import Testing #expect(connectCount == 1) #expect(store.connectionState == .disconnected) } - @Test func mixedTrustedAndUntrustedRoutesStillConnectOverTrustedRoute() async throws { let clock = TestClock() let router = LivenessHostRouter() @@ -305,14 +305,13 @@ import Testing kind: .manualHost, endpoint: .hostPort(host: "192.168.1.77", port: 58_465) ) - let scope = try #require(MobileManualHostTrustScope(route: route, stackUserID: nil)) + let scope = try #require(MobileManualHostTrustScope(route: route, stackUserID: "test-user")) #expect(approved == .superseded) #expect(store.manualHostTrustWarning == nil) #expect(await trustStore.isTrusted(scope) == false) #expect(await router.count(of: "mobile.attach_ticket.create") == 0) } - @Test func staleManualHostApprovalLookupCannotReplaceCurrentPrompt() async throws { let trustStore = BlockingManualHostTrustStore() let store = makeStore( @@ -389,7 +388,7 @@ import Testing kind: .manualHost, endpoint: .hostPort(host: "192.168.1.77", port: 58_465) ) - let scope = try #require(MobileManualHostTrustScope(route: route, stackUserID: nil)) + let scope = try #require(MobileManualHostTrustScope(route: route, stackUserID: "test-user")) let url = try attachURL(for: manualHostTicket(host: "192.168.1.77")) let queued = await store.connectPairingURLResult(url) @@ -491,6 +490,7 @@ import Testing isSignedIn: true, connectionState: connectionState, pairingCode: pairingCode, + identityProvider: StaticIdentityProvider(userID: "test-user"), reachability: AlwaysOnlineReachability(), pairingHintDefaults: UserDefaults(suiteName: "pairing-deadline-\(UUID().uuidString)")!, manualHostTrustStore: manualHostTrustStore diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift index c28bc41ce006..1cf0ed92d612 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift @@ -11,7 +11,8 @@ import Testing let oldBox = TransportBox() let transport = CountingSlowIgnoringCancellationTransport() let runtime = PairingDeadlineRuntime( - transportFactory: CountingSlowIgnoringCancellationTransportFactory(transport: transport) + transportFactory: CountingSlowIgnoringCancellationTransportFactory(transport: transport), + pairingAttemptTimeoutNanoseconds: 30 * 1_000_000_000 ) let store = MobileShellComposite( runtime: runtime, diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift index ade685590b80..920881d89642 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellAuthScopeIsolationTests.swift @@ -7,6 +7,26 @@ import Testing @MainActor @Suite struct MobileShellAuthScopeIsolationTests { + @Test func manualHostApprovalFailsClosedWithoutConcreteAccount() async { + let store = MobileShellComposite( + runtime: PairingDeadlineRuntime(supportedRouteKinds: [.manualHost]), + isSignedIn: true, + identityProvider: StaticIdentityProvider(userID: nil), + reachability: AlwaysOnlineReachability(), + pairingHintDefaults: UserDefaults(suiteName: "nil-auth-scope-\(UUID().uuidString)")! + ) + + let result = await store.connectManualHost( + name: "LAN Mac", + host: "192.168.1.77", + port: 58_465 + ) + + #expect(result == .failed) + #expect(store.manualHostTrustWarning == nil) + #expect(store.connectionRequiresReauth) + } + @Test func accountSwitchDuringDirectSecondaryRefreshNeverSendsNewTokenToOldManualHost() async throws { try await assertSessionChangeNeverSendsNewToken( replacementUserID: "user-b", diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Testing.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellComposite+TestState.swift similarity index 67% rename from Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Testing.swift rename to Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellComposite+TestState.swift index 6bad32f82242..5fd0b89eec0e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Testing.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellComposite+TestState.swift @@ -1,10 +1,8 @@ -#if DEBUG -internal import CmuxMobileShellModel +import CmuxMobileShellModel +@testable import CmuxMobileShell @MainActor extension MobileShellComposite { - /// Test seam: seed the full per-Mac workspace source of truth so aggregation - /// edge cases can be tested without opening live secondary transports. func setWorkspaceStatesForTesting( _ states: [String: MacWorkspaceState], foregroundMacDeviceID: String? @@ -16,4 +14,3 @@ extension MobileShellComposite { func foregroundMacDeviceIDForTesting() -> String? { foregroundMacDeviceID } func storedMacReconnectGenerationForTesting() -> Int { storedMacReconnectGeneration } } -#endif diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePairedMacCoalescingTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePairedMacCoalescingTests.swift index c9c7b00803d4..3e3eaa60ec6e 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePairedMacCoalescingTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositePairedMacCoalescingTests.swift @@ -163,7 +163,13 @@ import Testing lastSeenAt: 1_000, routes: [freshRoute] )), - scope: MobileShellScopeSnapshot(userID: "user-1", teamID: "team-a", generation: 0) + scope: MobileShellScopeSnapshot( + userID: "user-1", + teamID: "team-a", + generation: 0, + signInGeneration: store.currentSessionGeneration, + rpcAuthContext: store.currentRPCAuthContext() + ) ) await pairedStore.waitUntilUpsertCount(1) @@ -267,7 +273,13 @@ import Testing lastSeenAt: 1_000, routes: [freshRoute] )), - scope: MobileShellScopeSnapshot(userID: "user-1", teamID: "team-a", generation: 0) + scope: MobileShellScopeSnapshot( + userID: "user-1", + teamID: "team-a", + generation: 0, + signInGeneration: store.currentSessionGeneration, + rpcAuthContext: store.currentRPCAuthContext() + ) ) await pairedStore.waitUntilUpsertStarted(macDeviceID: "mac-a") await store.forgetMac(macDeviceID: "mac-a") @@ -364,7 +376,13 @@ import Testing ), ] )), - scope: MobileShellScopeSnapshot(userID: "user-1", teamID: "team-a", generation: 0) + scope: MobileShellScopeSnapshot( + userID: "user-1", + teamID: "team-a", + generation: 0, + signInGeneration: store.currentSessionGeneration, + rpcAuthContext: store.currentRPCAuthContext() + ) ) await store.waitForPushedRouteSyncForTesting() diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift index 7aa47d444735..b9645cc4b65e 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift @@ -49,7 +49,9 @@ import Testing let secondaryClient = MobileCoreRPCClient( runtime: runtime, route: secondaryRoute, - ticket: secondaryTicket + ticket: secondaryTicket, + authScope: MobileRPCAuthScope(), + authScopeValidator: { true } ) let secondarySubscription = SecondaryMacSubscription( macDeviceID: "secondary-mac", @@ -121,7 +123,9 @@ import Testing route: secondaryRoute, ticket: secondaryTicket, allowsStackAuthFallback: true, - manualHostStackAuthTrustProvider: { false } + manualHostStackAuthTrustProvider: { false }, + authScope: MobileRPCAuthScope(), + authScopeValidator: { true } ) let actionCapabilities = MobileWorkspaceActionCapabilities(supportsWorkspaceActions: true) store.secondaryMacSubscriptions["secondary-mac"] = SecondaryMacSubscription( @@ -191,7 +195,13 @@ import Testing let newRoute = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: 56_585) let oldTicket = try ticket(route: oldRoute, macDeviceID: "old-mac", authToken: "old-ticket") let newTicket = try ticket(route: newRoute, macDeviceID: "new-mac", authToken: "new-ticket") - let newClient = MobileCoreRPCClient(runtime: oldRuntime, route: newRoute, ticket: newTicket) + let newClient = MobileCoreRPCClient( + runtime: oldRuntime, + route: newRoute, + ticket: newTicket, + authScope: MobileRPCAuthScope(), + authScopeValidator: { true } + ) let store = MobileShellComposite.preview(runtime: oldRuntime) store.signIn() #expect(await store.connectPairingURL(try attachURL(for: oldTicket))) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift index 2128f4164e6f..b93225080a58 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift @@ -121,5 +121,9 @@ import Testing #expect(await router.count(of: "mobile.attach_ticket.create") == 0) #expect(store.connectionState == .connected) #expect(store.remoteClient === foregroundClient) + + store.terminalInputText = "pwd" + await store.submitTerminalInput() + #expect(await router.count(of: "terminal.input") == 1) } } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift index 9165439ff8b6..10a6eb26b56a 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellRenderGridLivenessTestSupport.swift @@ -632,6 +632,8 @@ func installFreshLivenessRemoteClient( runtime: runtime, route: route, ticket: ticket, - allowsStackAuthFallback: true + allowsStackAuthFallback: true, + authScope: MobileRPCAuthScope(), + authScopeValidator: { true } ) } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellTeamSwitchAuthorizationTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellTeamSwitchAuthorizationTests.swift new file mode 100644 index 000000000000..844fb71c29d2 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellTeamSwitchAuthorizationTests.swift @@ -0,0 +1,21 @@ +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct MobileShellTeamSwitchAuthorizationTests { + @Test func teamSwitchKeepsForegroundAuthorizationUsable() async throws { + let router = LivenessHostRouter() + let store = try await makeConnectedStore( + router: router, + box: TransportBox(), + clock: TestClock() + ) + let requestsBeforeSwitch = await router.count(of: "mobile.workspace.list") + + store.currentTeamDidChange() + await store.refreshWorkspaces() + + #expect(store.connectionState == .connected) + #expect(await router.count(of: "mobile.workspace.list") == requestsBeforeSwitch + 1) + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift index f993b61baff4..1ec46081980f 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift @@ -3,31 +3,33 @@ import Foundation /// A narrowly-scoped manual-host trust decision. /// -/// Trust is keyed to the normalized host, port, and current Stack user id when -/// one is available. That keeps an approval for one LAN host from becoming a +/// Trust is keyed to the normalized host, port, and current Stack user id. +/// That keeps an approval for one LAN host from becoming a /// global permission for unrelated plaintext routes. public struct MobileManualHostTrustScope: Equatable, Hashable, Sendable { /// The normalized host, lowercased for DNS/IP-literal comparisons. public let normalizedHost: String /// The approved TCP port. public let port: Int - /// The Stack user id that approved this route, or `nil` when no account is known. - public let stackUserID: String? + /// The nonempty Stack user id that approved this route. + public let stackUserID: String /// Creates a trust scope from a user-entered host and port. /// - Parameters: /// - host: A DNS name or IP literal. /// - port: The TCP port in `1...65535`. - /// - stackUserID: The approving Stack user id, if known. + /// - stackUserID: The approving Stack user id. Empty or missing ids fail closed. public init?(host: String, port: Int, stackUserID: String?) { + let trimmedUserID = stackUserID?.trimmingCharacters(in: .whitespacesAndNewlines) guard let manualHost = CmxManualHost(routeHost: host), - (1...65535).contains(port) else { + (1...65535).contains(port), + let trimmedUserID, + !trimmedUserID.isEmpty else { return nil } self.normalizedHost = manualHost.rawValue.lowercased() self.port = port - let trimmedUserID = stackUserID?.trimmingCharacters(in: .whitespacesAndNewlines) - self.stackUserID = trimmedUserID?.isEmpty == false ? trimmedUserID : nil + self.stackUserID = trimmedUserID } /// Creates a trust scope from an attach route. @@ -43,7 +45,7 @@ public struct MobileManualHostTrustScope: Equatable, Hashable, Sendable { var storageKey: String { [ - (stackUserID ?? "").mobileManualHostTrustStorageEscaped, + stackUserID.mobileManualHostTrustStorageEscaped, normalizedHost.mobileManualHostTrustStorageEscaped, "\(port)", ].joined(separator: "|") diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift index cf658a81f729..2d23888d5855 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift @@ -47,14 +47,15 @@ public struct MobileShellRouteAuthPolicy: Sendable { /// `.debugLoopback`. Keep this `false` for physical-device manual entry: /// loopback dials the phone itself there, not the Mac. /// - Returns: `.debugLoopback` for allowed loopback hosts, `.tailscale` for - /// Tailscale IP/MagicDNS hosts, otherwise `.manualHost`. + /// Tailscale IP/MagicDNS hosts, `.manualHost` otherwise, or `nil` for an + /// invalid host. public func manualRouteKind( for host: String, allowsDebugLoopback: Bool = true - ) -> CmxAttachTransportKind { - let normalizedHost = (normalizedManualRouteHost(host) ?? host) - .trimmingCharacters(in: .whitespacesAndNewlines) - .lowercased() + ) -> CmxAttachTransportKind? { + guard let normalizedHost = normalizedManualRouteHost(host)?.lowercased() else { + return nil + } if allowsDebugLoopback, isLoopbackHost(normalizedHost) { return .debugLoopback } diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index 81be148810de..225bcc678902 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -87,6 +87,7 @@ import Testing #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "100.71.210.41") == .tailscale) #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "work-mac.tailnet.ts.net") == .tailscale) #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "127.attacker.example") == .manualHost) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "https://bad.example") == nil) // Encrypted / loopback channels and explicitly approved manual hosts may // carry the Stack bearer token. @@ -185,6 +186,19 @@ import Testing #expect(await store.isTrusted(differentAccount) == false) } + @Test func manualHostTrustScopeRequiresConcreteAccount() { + #expect(MobileManualHostTrustScope( + host: "studio-mac.local", + port: 58_465, + stackUserID: nil + ) == nil) + #expect(MobileManualHostTrustScope( + host: "studio-mac.local", + port: 58_465, + stackUserID: " " + ) == nil) + } + @Test func userDefaultsManualHostTrustIsSessionScopedAndExpires() async throws { let suiteName = "cmux-manual-host-trust-\(UUID().uuidString)" defer { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 41f6edc0ccc5..1486bc8117fb 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -177,6 +177,11 @@ struct CMUXMobileRootView: View { reconnectStoredMacIfNeeded() } } + .onChange(of: authManager.currentUser?.id) { _, _ in + // Stack Auth can replace one authenticated user with another without + // toggling `isAuthenticated`; resynchronize the shell on that edge. + syncShellAuthentication(isAuthenticated) + } .onChange(of: authManager.isRestoringSession) { _, isRestoringSession in syncShellAuthentication(isAuthenticated, isRestoringSession: isRestoringSession) guard !isRestoringSession else { return } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift index 0a56d5a82bc1..248d578cfdfa 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift @@ -194,7 +194,7 @@ struct PairingView: View { Text(L10n.string( "mobile.pairing.manualHostTrustBody", - defaultValue: "cmux mobile currently relies on Tailscale/WireGuard for transport encryption. With a subnet router, iPhone to router may be encrypted, but router to Mac is normal LAN traffic. Trust only this host and port if you control that network." + defaultValue: "cmux does not encrypt this direct connection end to end. Account credentials are sent through it and can be intercepted on an untrusted network. Trust this host and port only on a network you control." )) .font(.footnote) .foregroundStyle(.secondary) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobilePairingManualHostAdvertisability.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobilePairingManualHostAdvertisability.swift index 1b0cfd63bd36..bf7631205158 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobilePairingManualHostAdvertisability.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/MobilePairingManualHostAdvertisability.swift @@ -10,6 +10,6 @@ struct MobilePairingManualHostAdvertisability: Sendable { guard let host = CmxManualHost(trimmed) else { return false } - return !CmxLoopbackHost().matches(host.rawValue) + return host.isAdvertisable } } diff --git a/Sources/Mobile/MobileHostRouteAdvertisement.swift b/Sources/Mobile/MobileHostRouteAdvertisement.swift index 0022f6d9a56d..4805e0ee91ee 100644 --- a/Sources/Mobile/MobileHostRouteAdvertisement.swift +++ b/Sources/Mobile/MobileHostRouteAdvertisement.swift @@ -15,11 +15,11 @@ final class MobileHostRouteAdvertisement { nonisolated static func configuredManualHost(defaults: UserDefaults = .standard) -> String? { guard let raw = defaults.object(forKey: manualHostDefaultsKey) as? String, - let host = CmxManualHost(raw)?.rawValue, - !CmxLoopbackHost().matches(host) else { + let manualHost = CmxManualHost(raw), + manualHost.isAdvertisable else { return nil } - return host + return manualHost.rawValue } nonisolated static func manualHostNeedsRouteRefresh(previous: String?, current: String?) -> Bool { diff --git a/Sources/Mobile/MobileRouteResolver.swift b/Sources/Mobile/MobileRouteResolver.swift index 72164ae6d402..e77b6811e3e0 100644 --- a/Sources/Mobile/MobileRouteResolver.swift +++ b/Sources/Mobile/MobileRouteResolver.swift @@ -99,13 +99,13 @@ final class MobileRouteResolver: @unchecked Sendable { } } - if let manualHost = manualHost.flatMap({ CmxManualHost(routeHost: $0)?.rawValue }), - !CmxLoopbackHost().matches(manualHost) { + if let manualHost = manualHost.flatMap(CmxManualHost.init(routeHost:)), + manualHost.isAdvertisable { let manualPriority = 10 + (tailscaleHosts.count * 10) if let manualRoute = try? CmxAttachRoute( id: CmxAttachTransportKind.manualHost.rawValue, kind: .manualHost, - endpoint: .hostPort(host: manualHost, port: port), + endpoint: .hostPort(host: manualHost.rawValue, port: port), priority: manualPriority ) { resolved.append(manualRoute) diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 5eefcdf30068..ff02fc4e3291 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -3764,13 +3764,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "cmux mobile currently relies on Tailscale/WireGuard for transport encryption. With a subnet router, iPhone to router may be encrypted, but router to Mac is normal LAN traffic. Trust only this host and port if you control that network." + "value": "cmux does not encrypt this direct connection end to end. Account credentials are sent through it and can be intercepted on an untrusted network. Trust this host and port only on a network you control." } }, "ja": { "stringUnit": { "state": "translated", - "value": "cmux mobile は現在、転送の暗号化を Tailscale/WireGuard に依存しています。サブネットルーターを使う場合、iPhone からルーターまでは暗号化されることがありますが、ルーターから Mac までは通常の LAN 通信です。そのネットワークを管理している場合のみ、このホストとポートを信頼してください。" + "value": "cmux は、この直接接続をエンドツーエンドで暗号化しません。アカウントの認証情報はこの接続を通じて送信され、信頼できないネットワークでは傍受される可能性があります。管理しているネットワーク上でのみ、このホストとポートを信頼してください。" } } } From 8c7a8549a133ad4450895e2b385160ef37d69d48 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 17:01:21 -0700 Subject: [PATCH 57/91] Preserve main dictation capture semantics --- .../Sources/CmuxMobileSupport/ComposerDictationController.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/ComposerDictationController.swift b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/ComposerDictationController.swift index fca25912efed..98ffde4baebf 100644 --- a/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/ComposerDictationController.swift +++ b/Packages/iOS/CmuxMobileSupport/Sources/CmuxMobileSupport/ComposerDictationController.swift @@ -395,7 +395,7 @@ public final class ComposerDictationController { request: SFSpeechAudioBufferRecognitionRequest ) -> @Sendable (AVAudioPCMBuffer, AVAudioTime) -> Void { // `nonisolated(unsafe)`-safe: `append(_:)` is thread-safe, weak, never outlives the request. - nonisolated(unsafe) weak var weakRequest: SFSpeechAudioBufferRecognitionRequest? = request + nonisolated(unsafe) weak let weakRequest: SFSpeechAudioBufferRecognitionRequest? = request return { buffer, _ in weakRequest?.append(buffer) } From e43754e88c62689b5c0ec4617f5594748daacbf8 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 17:05:26 -0700 Subject: [PATCH 58/91] Extract mobile pairing entry points --- ...ileShellComposite+PairingEntryPoints.swift | 37 +++++++++++++++++++ .../MobileShellComposite.swift | 32 ---------------- 2 files changed, 37 insertions(+), 32 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairingEntryPoints.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairingEntryPoints.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairingEntryPoints.swift new file mode 100644 index 000000000000..4ce25d0b1912 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairingEntryPoints.swift @@ -0,0 +1,37 @@ +import CMUXMobileCore +public import CmuxMobileShellModel +import Foundation + +extension MobileShellComposite { + /// Connect using the current pairing input, accepting either a code or pairing URL. + @discardableResult + public func connectPairingInput() async -> MobilePairingURLConnectionResult { + let trimmedCode = pairingCode.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedCode.isEmpty else { + return .failed + } + if CmxPairingURLScheme.hasPairingScheme(trimmedCode) { + return await connectPairingURLResult(trimmedCode) + } + connectPreviewHost() + return connectionState == .connected ? .connected : .failed + } + + /// Connect to a manually-entered Mac host and optionally associate the + /// resulting session with an existing paired-Mac device id. + @discardableResult + public func connectManualHost( + name: String, + host: String, + port: Int, + pairedMacDeviceID: String? = nil + ) async -> MobilePairingURLConnectionResult { + await connectManualHost( + name: name, + host: host, + port: port, + pairedMacDeviceID: pairedMacDeviceID, + recordsPairingAttempt: true + ) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index eea0c3c2456e..9b5dd59c6f3b 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1551,38 +1551,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { syncSelectedTerminalForWorkspace() } - /// Connect using the current pairing input, accepting either a code or pairing URL. - @discardableResult - public func connectPairingInput() async -> MobilePairingURLConnectionResult { - let trimmedCode = pairingCode.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmedCode.isEmpty else { - return .failed - } - if CmxPairingURLScheme.hasPairingScheme(trimmedCode) { - return await connectPairingURLResult(trimmedCode) - } - connectPreviewHost() - return connectionState == .connected ? .connected : .failed - } - - /// Connect to a manually-entered Mac host and optionally associate the - /// resulting session with an existing paired-Mac device id. - @discardableResult - public func connectManualHost( - name: String, - host: String, - port: Int, - pairedMacDeviceID: String? = nil - ) async -> MobilePairingURLConnectionResult { - await connectManualHost( - name: name, - host: host, - port: port, - pairedMacDeviceID: pairedMacDeviceID, - recordsPairingAttempt: true - ) - } - private func connectStoredMacHost( name: String, host: String, From b14f15f18c3c0730e72bf42bc053930d109bc6d3 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 17:08:01 -0700 Subject: [PATCH 59/91] Fix manual host persistence test identity --- .../MobileManualHostTrustPersistenceTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift index 8fd094979878..323fa85cd973 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift @@ -18,6 +18,7 @@ import Testing let store = MobileShellComposite( runtime: runtime, isSignedIn: true, + identityProvider: StaticIdentityProvider(userID: "phone-user"), reachability: AlwaysOnlineReachability(), pairingHintDefaults: UserDefaults( suiteName: "manual-host-refused-trust-\(UUID().uuidString)" From be9806478a5f58d94bc139bfdb7e66052d941a5c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 17:19:19 -0700 Subject: [PATCH 60/91] Avoid main actor deadlock in pairing retry test --- .../MobilePairingAttemptDeadlineTests.swift | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index c10e036c6b29..6ea2ac914458 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -34,9 +34,7 @@ import Testing transportFactory: CountingSlowIgnoringCancellationTransportFactory(transport: transport) ) let store = makeStore(runtime: runtime) - let firstTask = Task { @MainActor in await store.connectPairingURLResult(Self.qrURL) } - await transport.waitUntilConnectStarted() - let first = await firstTask.value + let first = await store.connectPairingURLResult(Self.qrURL) let second = await store.connectPairingURLResult(Self.qrURL) let connectCount = await transport.connectCount() await transport.releaseStuckConnects() From d68830468f8b6edcd3b9d056698a90d7707cbd04 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 17:21:23 -0700 Subject: [PATCH 61/91] Stabilize terminal replay barrier test --- .../TerminalMissingBaselineReplayBudgetTests.swift | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalMissingBaselineReplayBudgetTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalMissingBaselineReplayBudgetTests.swift index 1a28be058978..431088123dc3 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalMissingBaselineReplayBudgetTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalMissingBaselineReplayBudgetTests.swift @@ -99,12 +99,19 @@ import Testing let fullChunk = try #require(await iterator.next()) #expect(String(decoding: fullChunk.data, as: UTF8.self).contains("live-full-takes-over")) + let droppedOutputCountBeforePartial = + store.terminalReplayBarrierDroppedOutputCountsBySurfaceID[surfaceID] ?? 0 await transport.deliver(try renderGridEventFrame( surfaceID: surfaceID, seq: 11, text: "partial-dropped-before-full-ack", full: false )) + let partialWasDropped = try await pollUntil { + (store.terminalReplayBarrierDroppedOutputCountsBySurfaceID[surfaceID] ?? 0) + > droppedOutputCountBeforePartial + } + #expect(partialWasDropped) await router.enqueueReplayPayload(text: "stale-held-replay", sequence: 5) await router.releaseAllHeld() store.terminalOutputDidProcess(surfaceID: surfaceID, streamToken: fullChunk.streamToken) From e741dfb8471e52e122cd989e3001c335f55f2c8b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 17:25:36 -0700 Subject: [PATCH 62/91] Stabilize pairing retry deadline test --- .../MobilePairingAttemptDeadlineTests.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 6ea2ac914458..6bfbcdf5ddce 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -31,7 +31,8 @@ import Testing @Test func immediatePairingRetryDoesNotStartSecondStuckConnect() async throws { let transport = CountingSlowIgnoringCancellationTransport() let runtime = PairingDeadlineRuntime( - transportFactory: CountingSlowIgnoringCancellationTransportFactory(transport: transport) + transportFactory: CountingSlowIgnoringCancellationTransportFactory(transport: transport), + pairingAttemptTimeoutNanoseconds: 1_000_000_000 ) let store = makeStore(runtime: runtime) let first = await store.connectPairingURLResult(Self.qrURL) From 284b4284ef56425993c048236d1a35977e468d2d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 19:47:15 -0700 Subject: [PATCH 63/91] test(ios): cover same-interface manual host resume --- ...bileShellManualHostNetworkEpochTests.swift | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift index b93225080a58..3726b29c9ac2 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift @@ -6,6 +6,56 @@ import Testing @MainActor @Suite struct MobileShellManualHostNetworkEpochTests { + @Test func foregroundResumeDisconnectsActiveManualHostWithoutAPathEvent() async throws { + let reachability = ControllablePathChangeReachability() + let trustStore = NetworkEpochManualHostTrustStore() + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let route = try CmxAttachRoute( + id: "foreground-resume-manual-host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465) + ) + let trustScope = try #require( + MobileManualHostTrustScope(route: route, stackUserID: "phone-user") + ) + await trustStore.trust(trustScope) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: reachability, + manualHostTrustStore: trustStore + ) + store.signIn() + let ticket = try CmxAttachTicket( + workspaceID: "live-workspace", + terminalID: "live-terminal", + macDeviceID: "manual-mac", + macDisplayName: "LAN Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [route], + expiresAt: Date().addingTimeInterval(3_600), + authToken: "manual-ticket" + ) + #expect(await store.connectPairingURL(try attachURL(for: ticket))) + #expect(store.connectionState == .connected) + + store.suspendForegroundRefresh() + store.resumeForegroundRefresh() + + try #require(store.connectionState == .disconnected) + #expect(store.remoteClient == nil) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + await trustStore.waitUntilRemoved() + #expect(await trustStore.isTrusted(trustScope) == false) + } + @Test func pathChangeDisconnectsActiveManualHostAndQueuesExactRouteForReapproval() async throws { let reachability = ControllablePathChangeReachability() let trustStore = NetworkEpochManualHostTrustStore() From 916175c1a9b7ea6f690d46f80124f06ad58d216f Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 19:50:57 -0700 Subject: [PATCH 64/91] Revoke manual host trust on foreground resume --- ...MobileShellComposite+ManualHostTrust.swift | 43 ++++++++++++++++--- ...MobileShellComposite+ReconnectRoutes.swift | 4 +- .../MobileShellComposite.swift | 12 +++--- 3 files changed, 45 insertions(+), 14 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index f687665e0924..d3bb0f8e1dfb 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -38,7 +38,7 @@ extension MobileShellComposite { guard let scope = manualHostTrustScope(for: route, stackUserID: stackUserID) else { return false } - return await manualHostTrustStore.isTrusted(scope) + return await manualHostTrustIsAvailable(scope) } func manualHostStackAuthTrustProvider( @@ -48,9 +48,9 @@ extension MobileShellComposite { guard let scope = manualHostTrustScope(for: route, stackUserID: stackUserID) else { return { false } } - let trustStore = manualHostTrustStore - return { - await trustStore.isTrusted(scope) + return { [weak self] in + guard let self else { return false } + return await self.manualHostTrustIsAvailable(scope) } } @@ -61,7 +61,7 @@ extension MobileShellComposite { guard let scope = manualHostTrustScope(for: route, stackUserID: stackUserID) else { return false } - return !(await manualHostTrustStore.isTrusted(scope)) + return !(await manualHostTrustIsAvailable(scope)) } func firstManualHostRouteNeedingApproval( @@ -71,7 +71,7 @@ extension MobileShellComposite { let routeAuthPolicy = MobileShellRouteAuthPolicy() for route in routes { if let scope = manualHostTrustScope(for: route, stackUserID: stackUserID) { - if !(await manualHostTrustStore.isTrusted(scope)) { + if !(await manualHostTrustIsAvailable(scope)) { return (route, scope) } return nil @@ -111,6 +111,9 @@ extension MobileShellComposite { /// - Returns: The resumed result, or `.superseded` when the warning is no longer current. @discardableResult public func acceptManualHostTrustWarning() async -> MobilePairingURLConnectionResult { + if let resetTask = manualHostTrustResetTask { + await resetTask.value + } guard let warning = manualHostTrustWarning, let pending = pendingManualHostTrust else { clearManualHostTrustWarning() @@ -187,4 +190,32 @@ extension MobileShellComposite { guard let attemptID = pending.macSwitchAttemptID else { return } finishMacSwitchAttempt(attemptID) } + + private func manualHostTrustIsAvailable(_ scope: MobileManualHostTrustScope) async -> Bool { + guard manualHostTrustResetTask == nil else { return false } + return await manualHostTrustStore.isTrusted(scope) + } + + /// Revokes plaintext-route credentials at any boundary that may represent a new network. + /// - Returns: Whether an active manual-host connection was queued for reapproval. + @discardableResult + func invalidateManualHostTrustForNetworkBoundary() -> Bool { + rotateManualHostRPCAuthScope() + invalidatePairingAttempt() + clearSupersededManualHostTrustWarning() + + manualHostTrustResetGeneration &+= 1 + let resetGeneration = manualHostTrustResetGeneration + manualHostTrustResetTask?.cancel() + let trustStore = manualHostTrustStore + manualHostTrustResetTask = Task { @MainActor [weak self] in + await trustStore.removeAll() + guard let self, + self.manualHostTrustResetGeneration == resetGeneration else { return } + self.manualHostTrustResetTask = nil + } + + guard remoteClient != nil else { return false } + return queueForegroundManualHostReapproval(route: activeRoute) + } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift index 24b4c16ae5e4..65f9cf4b3293 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift @@ -27,13 +27,15 @@ extension MobileShellComposite { /// Resume foreground-only refresh loops after the app becomes active. public func resumeForegroundRefresh() { + let queuedManualHostReapproval = lastBackgroundedAt != nil + && invalidateManualHostTrustForNetworkBoundary() startObservingNetworkPathChanges() // Covers stores constructed already-signed-in (no isSignedIn edge) and // restarts a subscription torn down while backgrounded. evaluatePresenceSubscription() let shouldResync = shouldResyncTerminalOutputOnForeground() lastBackgroundedAt = nil - if shouldResync { + if shouldResync, !queuedManualHostReapproval { resyncTerminalOutput(reason: "foreground", restartEventStream: true) } // The foreground Mac's workspace list updates live over the sync stream, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 9b5dd59c6f3b..59535d9cf22e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -633,6 +633,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let stackTokenForceRefreshGate = RPCStackTokenGate() var rpcAuthScope = MobileRPCAuthScope() var manualHostRPCAuthScope = MobileRPCAuthScope() + var manualHostTrustResetTask: Task? + var manualHostTrustResetGeneration = 0 var rpcAuthStackUserID: String? /// Collapses connection-state edges into one-per-outage lost/recovered events. private var connectionOutageThrottle = ConnectionOutageThrottle() @@ -1041,6 +1043,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func cleanupForDeinit() { presenceTask?.cancel() networkPathObservationTask?.cancel() + manualHostTrustResetTask?.cancel() terminalEventListenerTask?.cancel() terminalSubscriptionStartTask?.cancel() renderGridLivenessTimer?.cancel() @@ -1474,12 +1477,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // connection so a moving network repaints instead of going stale. for await _ in reachability.pathChanges() { guard let self, !Task.isCancelled else { return } - self.rotateManualHostRPCAuthScope() - self.invalidatePairingAttempt() - self.clearSupersededManualHostTrustWarning() - await self.manualHostTrustStore.removeAll() - if self.remoteClient != nil, - self.queueForegroundManualHostReapproval(route: self.activeRoute) { + if self.invalidateManualHostTrustForNetworkBoundary() { continue } self.recoverMobileConnection(trigger: .networkChange) @@ -5533,7 +5531,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// Invalidate the in-flight attempt outside ``beginPairingAttempt(method:)`` /// (cancel, sign-out, live-connection teardown), dropping its instrumentation /// so a stale attempt can never emit `ios_pairing_*` via a later auth eviction. - private func invalidatePairingAttempt() { + func invalidatePairingAttempt() { pairingAttemptID = UUID() pairingAttemptStartedAt = nil pairingAttemptMethod = nil From 471eb39abc822626a030834de7cb3800fdc47811 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 20:15:16 -0700 Subject: [PATCH 65/91] test(ios): cover path and secondary route fallbacks --- .../SecondaryRouteFallbackTests.swift | 72 +++++++++++++++++++ ...condaryRouteFallbackTransportFactory.swift | 21 ++++++ .../ReachabilityService.swift | 4 +- .../ReachabilityServiceTests.swift | 27 +++++++ 4 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTests.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTransportFactory.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTests.swift new file mode 100644 index 000000000000..3761ab8075c0 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTests.swift @@ -0,0 +1,72 @@ +import CMUXMobileCore +import CmuxMobilePairedMac +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct SecondaryRouteFallbackTests { + @Test func secondaryAggregationFallsBackFromTailscaleToApprovedManualHost() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let tailscaleRoute = try CmxAttachRoute( + id: "preferred-tailscale", + kind: .tailscale, + endpoint: .hostPort(host: "100.82.214.112", port: 50_922), + priority: 0 + ) + let manualRoute = try CmxAttachRoute( + id: "approved-manual-host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 50_923), + priority: 10 + ) + try await pairedMacStore.upsert( + macDeviceID: "secondary-mac", + displayName: "Secondary Mac", + routes: [tailscaleRoute, manualRoute], + markActive: false, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let trustStore = InMemoryMobileManualHostTrustStore() + let trustScope = try #require( + MobileManualHostTrustScope(route: manualRoute, stackUserID: "phone-user") + ) + await trustStore.trust(trustScope) + let attempts = RouteAttemptRecorder() + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: SecondaryRouteFallbackTransportFactory( + router: router, + box: TransportBox(), + attempts: attempts + ), + now: { Date() }, + supportedRouteKinds: [.tailscale, .manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + isSignedIn: true, + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: trustStore + ) + await store.loadPairedMacs() + + await store.refreshSecondaryMacWorkspaces() + + #expect(attempts.count(.tailscale) == 1) + #expect(attempts.count(.manualHost) >= 1) + #expect(store.secondaryMacSubscriptions["secondary-mac"]?.route.kind == .manualHost) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTransportFactory.swift new file mode 100644 index 000000000000..bc5e4fad52b3 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTransportFactory.swift @@ -0,0 +1,21 @@ +import CMUXMobileCore + +struct SecondaryRouteFallbackTransportFactory: CmxByteTransportFactory { + enum Failure: Error { + case unreachablePreferredRoute + } + + let router: LivenessHostRouter + let box: TransportBox + let attempts: RouteAttemptRecorder + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + attempts.record(route.kind) + guard route.kind != .tailscale else { + throw Failure.unreachablePreferredRoute + } + let transport = LivenessTransport(router: router) + box.set(transport) + return transport + } +} diff --git a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift index a3616ae28a3a..7487bbf661f6 100644 --- a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift +++ b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift @@ -103,7 +103,7 @@ public actor ReachabilityService: ReachabilityProviding { } } - private func register(_ continuation: AsyncStream.Continuation) -> Int { + func register(_ continuation: AsyncStream.Continuation) -> Int { startIfNeeded() let id = nextSubscriptionID nextSubscriptionID += 1 @@ -128,7 +128,7 @@ public actor ReachabilityService: ReachabilityProviding { monitor.start(queue: queue) } - private func apply(online: Bool, primaryType: NWInterface.InterfaceType?) { + func apply(online: Bool, primaryType: NWInterface.InterfaceType?) { let wasOnline = self.online let previousType = lastInterfaceType self.online = online diff --git a/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/ReachabilityServiceTests.swift b/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/ReachabilityServiceTests.swift index b9120a79890c..be650cbfbd74 100644 --- a/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/ReachabilityServiceTests.swift +++ b/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/ReachabilityServiceTests.swift @@ -1,4 +1,5 @@ import Foundation +import Network import Testing @testable import CmuxMobileTransport @@ -30,6 +31,32 @@ import Testing _ = await secondTask.value } +@Test func reachabilityServiceEmitsForASecondPathOnTheSameInterface() async { + let service = ReachabilityService() + let (stream, continuation) = AsyncStream.makeStream() + _ = await service.register(continuation) + defer { continuation.finish() } + + await service.apply(online: true, primaryType: .wifi) + await service.apply(online: true, primaryType: .wifi) + + let emitted = await withTaskGroup(of: Bool.self) { group in + group.addTask { + var iterator = stream.makeAsyncIterator() + return await iterator.next() != nil + } + group.addTask { + // Assertion deadline only; stream delivery is signaled by `apply`. + try? await Task.sleep(for: .milliseconds(100)) + return false + } + let first = await group.next() ?? false + group.cancelAll() + return first + } + #expect(emitted) +} + @Test func transitionalNetworkReachabilityShimMirrorsAServiceOnMainActor() async { let shim = await NetworkReachability(service: ReachabilityService()) From 89edd58676417704d7204e9943abb5bf6c981b25 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 20:18:24 -0700 Subject: [PATCH 66/91] Handle same-interface paths and secondary fallbacks --- .../MobileShellComposite.swift | 175 +++++++++--------- .../NetworkReachability.swift | 2 +- .../ReachabilityProviding.swift | 18 +- .../ReachabilityService.swift | 13 +- 4 files changed, 106 insertions(+), 102 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 59535d9cf22e..20e3d2af05a8 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -3431,116 +3431,123 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } /// Build a persistent read-only client to one OTHER Mac (route + manual - /// ticket), or nil if it has no reachable route / the ticket fails. The caller + /// ticket), trying every reconnect candidate until one succeeds. The caller /// owns disconnecting it. Routes are loopback-deprioritized on device. Never /// touches the foreground connection. private func makeSecondaryClient(for mac: MobilePairedMac, scope: MobileShellScopeSnapshot) async -> SecondaryClientHandle? { guard let runtime else { return nil } guard await isScopeCurrent(scope) else { return nil } let supportedKinds = runtime.supportedRouteKinds - guard let candidate = routeSelection.reconnectHostPortRoutes( + let candidates = routeSelection.reconnectHostPortRoutes( mac.routes, supportedKinds: supportedKinds, preferNonLoopback: routeSelection.prefersNonLoopbackRoutes - ).first else { - return nil - } - let host = candidate.host - let port = candidate.port - let ticket: CmxAttachTicket - do { - let directRoute = try routeSelection.manualHostRoute( - host: host, - port: port, - preserving: candidate.route - ) + ) + for candidate in candidates { + guard await isScopeCurrent(scope) else { return nil } + let host = candidate.host + let port = candidate.port + let ticket: CmxAttachTicket + do { + let directRoute = try routeSelection.manualHostRoute( + host: host, + port: port, + preserving: candidate.route + ) + let manualHostTrusted = await manualHostStackAuthTrusted( + for: directRoute, + stackUserID: scope.userID + ) + guard await isScopeCurrent(scope) else { return nil } + ticket = try await manualHostTicket( + name: mac.displayName ?? host, + host: host, + port: port, + route: directRoute, + attemptStartedAt: nil, + manualHostTrusted: manualHostTrusted, + authContext: scope.rpcAuthContext + ) + } catch { + mobileShellLog.warning( + "secondary client: ticket failed mac=\(mac.macDeviceID, privacy: .public) route=\(candidate.routeID, privacy: .public) error=\(String(describing: error), privacy: .public)" + ) + continue + } + let supportedRoutes = routeSelection.supportedRoutes(for: ticket, supportedKinds: supportedKinds) + // Dial the route proved reachable by the ticket request, not + // `supportedRoutes.first`: on a physical phone a Mac ticket can + // advertise a higher-priority debug loopback route that reaches the + // phone itself. Prefer the exact route, then another non-loopback. + let route = supportedRoutes.first(where: { route in + if case let .hostPort(routeHost, routePort) = route.endpoint { + return routeHost == host && routePort == port + } + return false + }) ?? supportedRoutes.first(where: { $0.kind != .debugLoopback }) + ?? supportedRoutes.first + guard let route else { continue } let manualHostTrusted = await manualHostStackAuthTrusted( - for: directRoute, + for: route, stackUserID: scope.userID ) guard await isScopeCurrent(scope) else { return nil } - ticket = try await manualHostTicket( - name: mac.displayName ?? host, - host: host, - port: port, - route: directRoute, - attemptStartedAt: nil, - manualHostTrusted: manualHostTrusted, - authContext: scope.rpcAuthContext - ) - } catch { - mobileShellLog.warning( - "secondary client: ticket failed mac=\(mac.macDeviceID, privacy: .public) error=\(String(describing: error), privacy: .public)" + guard MobileShellRouteAuthPolicy().routeAllowsStackAuth( + route, + manualHostTrusted: manualHostTrusted + ) else { + continue + } + let client = MobileCoreRPCClient( + runtime: runtime, + route: route, + ticket: ticket, + allowsStackAuthFallback: true, + manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider( + for: route, + stackUserID: scope.userID + ), + authScope: rpcAuthScopeForRoute(for: route, context: scope.rpcAuthContext), + authScopeValidator: rpcAuthScopeValidator(for: route, context: scope.rpcAuthContext), + connectAttemptRegistry: connectAttemptRegistry, + stackTokenGate: stackTokenGate, + stackTokenForceRefreshGate: stackTokenForceRefreshGate ) - return nil - } - let supportedRoutes = routeSelection.supportedRoutes(for: ticket, supportedKinds: supportedKinds) - // Dial the route we PROVED reachable above (the non-loopback host/port the - // ticket was built from), NOT `supportedRoutes.first`: on a physical phone a - // Mac ticket can advertise a higher-priority `debugLoopback` (127.0.0.1) - // route, and dialing that makes every secondary subscription connect to the - // phone itself — so the Mac is unreachable and silently drops out of the - // aggregate. Prefer the exact matching route, then any non-loopback, then any. - let route = supportedRoutes.first(where: { route in - if case let .hostPort(routeHost, routePort) = route.endpoint { - return routeHost == host && routePort == port + guard let capabilities = await fetchSecondaryHostCapabilities(on: client) else { + await client.disconnect() + continue } - return false - }) ?? supportedRoutes.first(where: { $0.kind != .debugLoopback }) - ?? supportedRoutes.first - guard let route else { return nil } - let manualHostTrusted = await manualHostStackAuthTrusted( - for: route, - stackUserID: scope.userID - ) - guard await isScopeCurrent(scope) else { return nil } - guard MobileShellRouteAuthPolicy().routeAllowsStackAuth( - route, - manualHostTrusted: manualHostTrusted - ) else { - return nil - } - let client = MobileCoreRPCClient( - runtime: runtime, - route: route, - ticket: ticket, - allowsStackAuthFallback: true, - manualHostStackAuthTrustProvider: manualHostStackAuthTrustProvider( - for: route, - stackUserID: scope.userID - ), - authScope: rpcAuthScopeForRoute(for: route, context: scope.rpcAuthContext), - authScopeValidator: rpcAuthScopeValidator(for: route, context: scope.rpcAuthContext), - connectAttemptRegistry: connectAttemptRegistry, - stackTokenGate: stackTokenGate, - stackTokenForceRefreshGate: stackTokenForceRefreshGate - ) - let capabilities = await fetchSecondaryHostCapabilities(on: client) - return SecondaryClientHandle( - client: client, - route: route, - ticket: ticket, - supportedHostCapabilities: capabilities, - actionCapabilities: Self.workspaceActionCapabilities( - from: capabilities, - allowsMacScopedMutations: MobileShellWorkspaceMutationTicketPolicy(now: runtime.now()) - .allowsMacScopedWorkspaceMutations(ticket) + guard await isScopeCurrent(scope) else { + await client.disconnect() + return nil + } + return SecondaryClientHandle( + client: client, + route: route, + ticket: ticket, + supportedHostCapabilities: capabilities, + actionCapabilities: Self.workspaceActionCapabilities( + from: capabilities, + allowsMacScopedMutations: MobileShellWorkspaceMutationTicketPolicy(now: runtime.now()) + .allowsMacScopedWorkspaceMutations(ticket) + ) ) - ) + } + return nil } - private func fetchSecondaryHostCapabilities(on client: MobileCoreRPCClient) async -> Set { - guard let runtime else { return [] } + private func fetchSecondaryHostCapabilities(on client: MobileCoreRPCClient) async -> Set? { + guard let runtime else { return nil } do { let data = try await client.sendRequest( MobileCoreRPCClient.requestData(method: "mobile.host.status", params: [:]), timeoutNanoseconds: runtime.pairingRequestTimeoutNanoseconds ) - guard let payload = try? MobileHostStatusResponse.decode(data) else { return [] } + guard let payload = try? MobileHostStatusResponse.decode(data) else { return nil } return Set(payload.capabilities) } catch { mobileShellLog.warning("secondary host status failed: \(String(describing: error), privacy: .private)") - return [] + return nil } } diff --git a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/NetworkReachability.swift b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/NetworkReachability.swift index b2c8589c5028..389c9c1b557e 100644 --- a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/NetworkReachability.swift +++ b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/NetworkReachability.swift @@ -31,7 +31,7 @@ public final class NetworkReachability { /// Convenience inverse of ``isOnline``. public var isOffline: Bool { !isOnline } - /// Monotonic counter that increments on each meaningful path change. + /// Monotonic counter that increments on each post-initial path update. /// /// Observe it via `withObservationTracking` to drive reconnect/resync when /// the underlying network moves out from under a live connection. It mirrors diff --git a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityProviding.swift b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityProviding.swift index d5edb49de54c..b8e505319e98 100644 --- a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityProviding.swift +++ b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityProviding.swift @@ -3,10 +3,11 @@ import Foundation /// A network-reachability seam other layers depend on instead of a singleton. /// /// Conformers report whether the system currently has a satisfied network path -/// and emit a value on every *meaningful* path change (regaining connectivity -/// after being offline, or the primary interface switching while online), so a -/// live connection can resync or reconnect when the network moves out from -/// under it. +/// and emit a value on every path update after the initial snapshot, so a live +/// connection can resync or reconnect when the network moves out from under it. +/// This deliberately includes updates that keep the same primary interface +/// type: Wi-Fi roaming can move to a different LAN without a `.wifi`→cellular +/// transition. /// /// The concrete ``ReachabilityService`` is constructed once at the app /// composition root and injected as `any ReachabilityProviding`. @@ -14,12 +15,11 @@ public protocol ReachabilityProviding: Sendable { /// Whether the system currently has a satisfied network path. var isOnline: Bool { get async } - /// A stream that yields once per meaningful path change. + /// A stream that yields once per path update after the initial snapshot. /// - /// Each element marks a change worth recovering from: connectivity returning - /// after an offline window, or the primary interface type changing (for - /// example Wi-Fi to cellular) while online. It deliberately does not emit on - /// the first path delivery, so observers don't recover spuriously at startup. + /// Same-interface updates are included so Wi-Fi→Wi-Fi roaming invalidates + /// network-scoped trust. The first path delivery is omitted so observers do + /// not recover spuriously at startup. /// - Returns: An `AsyncStream` that completes when the provider is torn down. func pathChanges() -> AsyncStream } diff --git a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift index 7487bbf661f6..dc27ece2c4a3 100644 --- a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift +++ b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift @@ -5,7 +5,7 @@ import Foundation /// /// Owns the path monitor and its callback queue, tracks the current online /// state and primary interface type as actor-isolated state, and fans -/// meaningful path changes out to any number of subscribers through +/// post-initial path updates out to any number of subscribers through /// ``pathChanges()``. /// /// Construct it once at the app composition root and inject it as @@ -90,7 +90,7 @@ public actor ReachabilityService: ReachabilityProviding { } } - /// A stream that yields once per meaningful path change. + /// A stream that yields once per path update after the initial snapshot. /// - Returns: An `AsyncStream` removed from the registry when its consumer /// stops iterating or the task is cancelled. public nonisolated func pathChanges() -> AsyncStream { @@ -129,11 +129,10 @@ public actor ReachabilityService: ReachabilityProviding { } func apply(online: Bool, primaryType: NWInterface.InterfaceType?) { - let wasOnline = self.online - let previousType = lastInterfaceType + let isInitialPath = !receivedFirstPath self.online = online if online { lastInterfaceType = primaryType } - if !receivedFirstPath { + if isInitialPath { receivedFirstPath = true for waiter in firstPathWaiters.values { waiter.resume() @@ -141,9 +140,7 @@ public actor ReachabilityService: ReachabilityProviding { firstPathWaiters.removeAll() cancelledFirstPathWaiterIDs.removeAll() } - let regainedOnline = online && !wasOnline - let interfaceChanged = online && previousType != nil && primaryType != previousType - guard regainedOnline || interfaceChanged else { return } + guard !isInitialPath else { return } for continuation in subscribers.values { continuation.yield(()) } From e6751773a14ffbca25cecf12b2df6ace5bab0362 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 20:45:17 -0700 Subject: [PATCH 67/91] test(ios): cover final network trust lifecycle --- .../BlockingNetworkEpochTrustStore.swift | 39 +++++++ ...bileShellManualHostNetworkEpochTests.swift | 106 ++++++++++++++++++ .../PairingViewPendingApprovalTests.swift | 24 ++++ 3 files changed, 169 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift new file mode 100644 index 000000000000..f13dcd023cb7 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift @@ -0,0 +1,39 @@ +import CmuxMobileShellModel + +actor BlockingNetworkEpochTrustStore: MobileManualHostTrustStoring { + private var removeCount = 0 + private var removeWaiters: [CheckedContinuation] = [] + private var releaseWaiters: [CheckedContinuation] = [] + + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + _ = scope + return false + } + + func trust(_ scope: MobileManualHostTrustScope) async { + _ = scope + } + + func removeAll() async { + removeCount += 1 + let waiters = removeWaiters + removeWaiters.removeAll() + for waiter in waiters { waiter.resume() } + await withCheckedContinuation { releaseWaiters.append($0) } + } + + func waitUntilRemoveCount(_ expected: Int) async { + if removeCount >= expected { return } + await withCheckedContinuation { removeWaiters.append($0) } + } + + func currentRemoveCount() -> Int { + removeCount + } + + func releaseRemovals() { + let waiters = releaseWaiters + releaseWaiters.removeAll() + for waiter in waiters { waiter.resume() } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift index 3726b29c9ac2..d23998428912 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift @@ -1,4 +1,5 @@ import CMUXMobileCore +import CmuxMobileRPC import CmuxMobileShellModel import Foundation import Testing @@ -6,6 +7,111 @@ import Testing @MainActor @Suite struct MobileShellManualHostNetworkEpochTests { + @Test func networkBoundaryRevokesSecondaryManualHostWithoutDroppingSecureForeground() async throws { + let reachability = ControllablePathChangeReachability() + let trustStore = NetworkEpochManualHostTrustStore() + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.debugLoopback, .manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: reachability, + manualHostTrustStore: trustStore + ) + store.signIn() + let foregroundRoute = try CmxAttachRoute( + id: "secure-foreground", + kind: .debugLoopback, + endpoint: .hostPort(host: "127.0.0.1", port: 56_584) + ) + let foregroundTicket = try CmxAttachTicket( + workspaceID: "foreground-workspace", + terminalID: "foreground-terminal", + macDeviceID: "foreground-mac", + macDisplayName: "Foreground Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [foregroundRoute], + expiresAt: Date().addingTimeInterval(3_600), + authToken: "foreground-ticket" + ) + #expect(await store.connectPairingURL(try attachURL(for: foregroundTicket))) + let foregroundClient = try #require(store.remoteClient) + let secondaryRoute = try CmxAttachRoute( + id: "manual-secondary", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.88", port: 58_465) + ) + let secondaryTicket = try CmxAttachTicket( + workspaceID: "secondary-workspace", + terminalID: nil, + macDeviceID: "secondary-mac", + macDisplayName: "Secondary Mac", + routes: [secondaryRoute], + expiresAt: Date().addingTimeInterval(3_600) + ) + let secondaryClient = MobileCoreRPCClient( + runtime: runtime, + route: secondaryRoute, + ticket: secondaryTicket, + allowsStackAuthFallback: true, + manualHostStackAuthTrustProvider: { true }, + authScope: MobileRPCAuthScope(), + authScopeValidator: { true } + ) + store.secondaryMacSubscriptions["secondary-mac"] = SecondaryMacSubscription( + macDeviceID: "secondary-mac", + client: secondaryClient, + route: secondaryRoute, + ticket: secondaryTicket, + supportedHostCapabilities: [], + actionCapabilities: .none + ) + store.setWorkspaceStatesForTesting([ + "foreground-mac": MacWorkspaceState( + macDeviceID: "foreground-mac", + workspaces: [], + status: .connected + ), + "secondary-mac": MacWorkspaceState( + macDeviceID: "secondary-mac", + workspaces: [], + status: .connected + ), + ], foregroundMacDeviceID: "foreground-mac") + store.startObservingNetworkPathChanges() + + reachability.emitPathChange() + await trustStore.waitUntilRemoved() + + #expect(store.remoteClient === foregroundClient) + #expect(store.connectionState == .connected) + #expect(store.secondaryMacSubscriptions["secondary-mac"] == nil) + #expect(store.workspacesByMac["secondary-mac"]?.status == .unavailable) + } + + @Test func repeatedBoundaryWhileTrustResetIsPendingDoesNotRestartReset() async { + let trustStore = BlockingNetworkEpochTrustStore() + let store = MobileShellComposite( + identityProvider: StaticIdentityProvider(userID: "phone-user"), + manualHostTrustStore: trustStore + ) + store.signIn() + + store.invalidateManualHostTrustForNetworkBoundary() + await trustStore.waitUntilRemoveCount(1) + store.invalidateManualHostTrustForNetworkBoundary() + + #expect(store.manualHostTrustResetGeneration == 1) + #expect(await trustStore.currentRemoveCount() == 1) + await trustStore.releaseRemovals() + } + @Test func foregroundResumeDisconnectsActiveManualHostWithoutAPathEvent() async throws { let reachability = ControllablePathChangeReachability() let trustStore = NetworkEpochManualHostTrustStore() diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift index 7339357c6bfe..63d631db73b9 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/PairingViewPendingApprovalTests.swift @@ -50,6 +50,30 @@ import Testing #expect(dismissCount == 1) } + @MainActor + @Test func cancelAfterCompletedFailureClearsStoreAttemptBeforeDismiss() { + var cancelPairingCount = 0 + var dismissCount = 0 + let view = PairingView( + pairingCode: .constant(""), + connectionError: "Could not connect", + connectionErrorGuidance: nil, + versionWarning: nil, + manualHostTrustWarning: nil, + connectPairingCode: {}, + acceptVersionWarning: {}, + acceptManualHostTrustWarning: {}, + connectManualHost: { _, _, _ in }, + cancelPairing: { cancelPairingCount += 1 }, + cancel: { dismissCount += 1 } + ) + + view.cancelAndDismiss() + + #expect(cancelPairingCount == 1) + #expect(dismissCount == 1) + } + private func warning() -> MobileManualHostTrustWarning { let scope = MobileManualHostTrustScope( host: "192.168.1.77", From 73b36aeffce0e6368e98bd6473ae24362c89ee7f Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 20:50:41 -0700 Subject: [PATCH 68/91] fix(ios): close final network trust lifecycle gaps --- ...MobileShellComposite+ManualHostTrust.swift | 21 ++++++++++++++++++- .../MobileShellComposite.swift | 12 +++++------ .../CmuxMobileShellUI/PairingView.swift | 1 + .../ReachabilityService.swift | 4 +++- 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index d3bb0f8e1dfb..7ece98edc21e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -200,13 +200,19 @@ extension MobileShellComposite { /// - Returns: Whether an active manual-host connection was queued for reapproval. @discardableResult func invalidateManualHostTrustForNetworkBoundary() -> Bool { + revokeSecondaryManualHostSubscriptions() + guard manualHostTrustResetTask == nil else { + // Preserve the approval queued by the first boundary while its + // durable trust reset is still in flight. + return pendingManualHostTrust != nil + } + rotateManualHostRPCAuthScope() invalidatePairingAttempt() clearSupersededManualHostTrustWarning() manualHostTrustResetGeneration &+= 1 let resetGeneration = manualHostTrustResetGeneration - manualHostTrustResetTask?.cancel() let trustStore = manualHostTrustStore manualHostTrustResetTask = Task { @MainActor [weak self] in await trustStore.removeAll() @@ -218,4 +224,17 @@ extension MobileShellComposite { guard remoteClient != nil else { return false } return queueForegroundManualHostReapproval(route: activeRoute) } + + private func revokeSecondaryManualHostSubscriptions() { + for (macDeviceID, subscription) in secondaryMacSubscriptions + where subscription.route.kind == .manualHost { + subscription.cancel() + secondaryMacSubscriptions[macDeviceID] = nil + removeSecondaryConnectionFromPool(macDeviceID: macDeviceID) + if var state = workspacesByMac[macDeviceID] { + state.status = .unavailable + workspacesByMac[macDeviceID] = state + } + } + } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 20e3d2af05a8..ae52108961e2 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1464,17 +1464,16 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } } - /// Begin observing meaningful network path changes (Wi-Fi<->cellular, - /// offline->online) so a live terminal recovers when the network moves out - /// from under it. Idempotent; only the first call arms the observation. + /// Begin observing every post-initial network path callback so a live + /// terminal recovers and plaintext trust is revoked when the network moves + /// out from under it. Idempotent; only the first call arms the observation. func startObservingNetworkPathChanges() { guard !networkPathObservationStarted else { return } networkPathObservationStarted = true let reachability = reachability networkPathObservationTask = Task { @MainActor [weak self] in - // Each yield marks a meaningful path change (offline->online or a - // primary-interface switch while online); recover the live - // connection so a moving network repaints instead of going stale. + // Every post-initial callback is a security boundary. Public NWPath + // attributes can look identical across two different Wi-Fi LANs. for await _ in reachability.pathChanges() { guard let self, !Task.isCancelled else { return } if self.invalidateManualHostTrustForNetworkBoundary() { @@ -1500,6 +1499,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func recoverMobileConnection(trigger: RecoveryTrigger) { guard remoteClient != nil || pairedMacStore != nil else { return } if connectionState == .connected, remoteClient != nil { + guard !isRecoveringConnection else { return } markMacConnectionReconnecting() resyncTerminalOutput(reason: "networkRecovery.\(trigger)", restartEventStream: true) if multiMacAggregationEnabled, trigger.reschedulesSecondaryAggregation { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift index 248d578cfdfa..351112d5951f 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift @@ -303,6 +303,7 @@ struct PairingView: View { let shouldCancelStoreAttempt = pairingTask != nil || versionWarning != nil || manualHostTrustWarning != nil + || connectionError != nil pairingTask?.cancel() pairingTaskID = nil pairingTask = nil diff --git a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift index dc27ece2c4a3..92d7e72390b8 100644 --- a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift +++ b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift @@ -94,7 +94,9 @@ public actor ReachabilityService: ReachabilityProviding { /// - Returns: An `AsyncStream` removed from the registry when its consumer /// stops iterating or the task is cancelled. public nonisolated func pathChanges() -> AsyncStream { - AsyncStream { continuation in + // Recovery only needs the newest pending security boundary; bounding + // the stream prevents callback bursts from queuing unbounded work. + AsyncStream(bufferingPolicy: .bufferingNewest(1)) { continuation in let registration = Task { await self.register(continuation) } continuation.onTermination = { _ in registration.cancel() From 0833c7fb052f54a83567b1295109db0cd89dba1a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:11:40 -0700 Subject: [PATCH 69/91] test(ios): preserve queued auth cancellation --- .../MobileCoreRPCRequestQueueTests.swift | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift index 97ae88a8541b..ef77aafe72f0 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift @@ -4,6 +4,49 @@ import Testing @testable import CmuxMobileRPC @Suite struct MobileCoreRPCRequestQueueTests { + @Test func revokedQueuedSendPreservesCancellationWithoutClosingSession() async throws { + let transport = QueuedCancellationProbeTransport() + let session = MobileCoreRPCSession(makeTransport: { transport }) + let deadline = DispatchTime.now().uptimeNanoseconds + 60_000_000_000 + let firstID = "first-blocking-send" + let revokedID = "revoked-queued-send" + let first = Task { + try await session.send( + payload: try MobileCoreRPCClient.requestData(method: "workspace.list", id: firstID), + requestID: firstID, + deadlineUptimeNanoseconds: deadline + ) + } + #expect(try await transport.waitForSentRequestCount(1).map(\.id) == [firstID]) + let revoked = Task { + try await session.send( + payload: try MobileCoreRPCClient.requestData(method: "workspace.list", id: revokedID), + requestID: revokedID, + deadlineUptimeNanoseconds: deadline, + sendAuthorizer: { throw CancellationError() } + ) + } + for _ in 0..<200 where !(await session.queuedRequestIDs.contains(revokedID)) { + await Task.yield() + } + #expect(await session.queuedRequestIDs.contains(revokedID)) + + await transport.releaseFirstSend() + do { + _ = try await revoked.value + Issue.record("Expected revoked queued send to preserve cancellation") + } catch is CancellationError { + } catch { + Issue.record("Expected CancellationError, got \(error)") + } + + #expect(try await transport.sentRequests().map(\.id) == [firstID]) + #expect(!(await transport.closed())) + first.cancel() + _ = try? await first.value + await session.tearDown(error: .connectionClosed) + } + @Test func timedOutQueuedSameIDRetryIsNotConsumedByOldTombstone() async throws { let transport = QueuedCancellationProbeTransport() let route = try hostPortRoute(kind: .debugLoopback, host: "127.0.0.1", port: 59133) From 8d313716b23a3de4e9366d0bc9b68fe56ddb7fc4 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:18:00 -0700 Subject: [PATCH 70/91] fix(ios): preserve revoked send semantics --- .../CmuxMobileRPC/MobileCoreRPCSession.swift | 25 +++++++++---------- .../MobileShellComposite.swift | 2 +- .../ReachabilityService.swift | 24 ++++-------------- .../ReachabilityServiceTests.swift | 4 +-- 4 files changed, 20 insertions(+), 35 deletions(-) diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift index 73ac085cffc2..cffde3e0b6fa 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift @@ -5,7 +5,7 @@ actor MobileCoreRPCSession { typealias ConnectedCandidateHook = @Sendable (_ candidate: any CmxByteTransport) async -> Void typealias PreEnqueueValidator = @Sendable () async throws -> Void typealias SendAuthorizer = @Sendable () async throws -> MobileRPCAuthScope.SendLease - typealias PendingContinuation = CheckedContinuation, Never> + typealias PendingContinuation = CheckedContinuation, Never> typealias ConnectingTask = (id: UUID, lease: MobileRPCConnectAttemptLease?, task: Task, waiters: Set, completed: Bool) static let defaultAbandonedConnectCleanupTimeoutNanoseconds: UInt64 = 1_000_000_000 static let defaultLateAbandonedConnectCloseTimeoutNanoseconds: UInt64 = 5_000_000_000 @@ -73,10 +73,10 @@ actor MobileCoreRPCSession { let frame = try MobileSyncFrameCodec.encodeFrame(payload) let responseTimeoutNanoseconds = try taskTimeout.remainingNanoseconds(until: deadlineUptimeNanoseconds) - let result: Result = await withTaskCancellationHandler { + let result: Result = await withTaskCancellationHandler { await withCheckedContinuation { continuation in guard pending[requestID] == nil, queuedWriteIDs[requestID] == nil else { - continuation.resume(returning: .failure(.invalidResponse)) + continuation.resume(returning: .failure(MobileShellConnectionError.invalidResponse)) return } let queuedWriteID = UUID() @@ -90,7 +90,7 @@ actor MobileCoreRPCSession { guard let queue = writeQueue else { requestTimeoutTasks.removeValue(forKey: requestID)?.cancel() pending.removeValue(forKey: requestID) - continuation.resume(returning: .failure(.connectionClosed)) + continuation.resume(returning: .failure(MobileShellConnectionError.connectionClosed)) return } queuedWriteIDs[requestID] = queuedWriteID @@ -382,8 +382,7 @@ actor MobileCoreRPCSession { if cancelledQueuedWriteIDs.remove(write.id) != nil { return } guard queuedWriteIDs[write.requestID] == write.id else { return } queuedWriteIDs[write.requestID] = nil - let connectionError = error as? MobileShellConnectionError ?? .connectionClosed - failPending(requestID: write.requestID, error: connectionError) + failPending(requestID: write.requestID, error: error) } private func readLoop(transport: any CmxByteTransport) async { @@ -443,7 +442,7 @@ actor MobileCoreRPCSession { if let data = try? JSONSerialization.data(withJSONObject: result) { cont.resume(returning: .success(data)) } else { - cont.resume(returning: .failure(.invalidResponse)) + cont.resume(returning: .failure(MobileShellConnectionError.invalidResponse)) } return } @@ -452,18 +451,18 @@ actor MobileCoreRPCSession { let code = errorPayload?["code"] as? String switch code { case "unauthorized": - cont.resume(returning: .failure(.authorizationFailed(message))) + cont.resume(returning: .failure(MobileShellConnectionError.authorizationFailed(message))) case "account_mismatch": // The Mac is signed in to a different cmux account. Surface a // distinct error so the shell drives a re-auth flow into the owner's // account rather than retrying with this account's fresh token. - cont.resume(returning: .failure(.accountMismatch(message))) + cont.resume(returning: .failure(MobileShellConnectionError.accountMismatch(message))) default: - cont.resume(returning: .failure(.rpcError(code, message))) + cont.resume(returning: .failure(MobileShellConnectionError.rpcError(code, message))) } } - private func failPending(requestID: String, error: MobileShellConnectionError) { + private func failPending(requestID: String, error: any Error) { guard let cont = pending.removeValue(forKey: requestID) else { return } requestTimeoutTasks.removeValue(forKey: requestID)?.cancel() cont.resume(returning: .failure(error)) @@ -474,7 +473,7 @@ actor MobileCoreRPCSession { if let queuedWriteID = queuedWriteIDs.removeValue(forKey: requestID) { cancelledQueuedWriteIDs.insert(queuedWriteID) } - cont.resume(returning: .failure(.requestTimedOut)) + cont.resume(returning: .failure(MobileShellConnectionError.requestTimedOut)) } private func timeoutPendingRequest(requestID: String) { @@ -483,7 +482,7 @@ actor MobileCoreRPCSession { if let queuedWriteID = queuedWriteIDs.removeValue(forKey: requestID) { cancelledQueuedWriteIDs.insert(queuedWriteID) } - cont.resume(returning: .failure(.requestTimedOut)) + cont.resume(returning: .failure(MobileShellConnectionError.requestTimedOut)) } private func shouldSendQueuedWrite(_ write: MobileCoreRPCPendingWrite) -> Bool { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index ae52108961e2..41e671e84a86 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -3470,7 +3470,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) } catch { mobileShellLog.warning( - "secondary client: ticket failed mac=\(mac.macDeviceID, privacy: .public) route=\(candidate.routeID, privacy: .public) error=\(String(describing: error), privacy: .public)" + "secondary client: ticket failed mac=\(mac.macDeviceID, privacy: .private) route=\(candidate.routeID, privacy: .private) error=\(String(describing: error), privacy: .private)" ) continue } diff --git a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift index 92d7e72390b8..e1cc56e45b24 100644 --- a/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift +++ b/Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/ReachabilityService.swift @@ -4,9 +4,8 @@ import Foundation /// A de-singletonized network-reachability monitor backed by `NWPathMonitor`. /// /// Owns the path monitor and its callback queue, tracks the current online -/// state and primary interface type as actor-isolated state, and fans -/// post-initial path updates out to any number of subscribers through -/// ``pathChanges()``. +/// state as actor-isolated state, and fans post-initial path updates out to any +/// number of subscribers through ``pathChanges()``. /// /// Construct it once at the app composition root and inject it as /// `any ReachabilityProviding`: @@ -22,7 +21,6 @@ public actor ReachabilityService: ReachabilityProviding { private let queue: DispatchQueue private var started = false private var online = true - private var lastInterfaceType: NWInterface.InterfaceType? private var nextSubscriptionID = 0 private var subscribers: [Int: AsyncStream.Continuation] = [:] /// Whether `NWPathMonitor` has delivered its first path since `start`. @@ -122,18 +120,16 @@ public actor ReachabilityService: ReachabilityProviding { guard !started else { return } started = true monitor.pathUpdateHandler = { [weak self] path in - // Compute Sendable values on the monitor queue; never capture NWPath. + // Compute Sendable state on the monitor queue; never capture NWPath. let isSatisfied = path.status == .satisfied - let primaryType = ReachabilityService.primaryInterfaceType(of: path) - Task { await self?.apply(online: isSatisfied, primaryType: primaryType) } + Task { await self?.apply(online: isSatisfied) } } monitor.start(queue: queue) } - func apply(online: Bool, primaryType: NWInterface.InterfaceType?) { + func apply(online: Bool) { let isInitialPath = !receivedFirstPath self.online = online - if online { lastInterfaceType = primaryType } if isInitialPath { receivedFirstPath = true for waiter in firstPathWaiters.values { @@ -148,16 +144,6 @@ public actor ReachabilityService: ReachabilityProviding { } } - private nonisolated static func primaryInterfaceType( - of path: NWPath - ) -> NWInterface.InterfaceType? { - for type in [NWInterface.InterfaceType.wifi, .wiredEthernet, .cellular] - where path.usesInterfaceType(type) { - return type - } - return path.availableInterfaces.first?.type - } - deinit { monitor.cancel() for continuation in subscribers.values { diff --git a/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/ReachabilityServiceTests.swift b/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/ReachabilityServiceTests.swift index be650cbfbd74..d30dc6067260 100644 --- a/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/ReachabilityServiceTests.swift +++ b/Packages/iOS/CmuxMobileTransport/Tests/CmuxMobileTransportTests/ReachabilityServiceTests.swift @@ -37,8 +37,8 @@ import Testing _ = await service.register(continuation) defer { continuation.finish() } - await service.apply(online: true, primaryType: .wifi) - await service.apply(online: true, primaryType: .wifi) + await service.apply(online: true) + await service.apply(online: true) let emitted = await withTaskGroup(of: Bool.self) { group in group.addTask { From 288842c91a412f07b956a09859e7df3d898fa593 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:18:56 -0700 Subject: [PATCH 71/91] test(ios): cover repeated network approval race --- .../BlockingNetworkEpochTrustStore.swift | 6 ++ ...bileShellManualHostNetworkEpochTests.swift | 56 +++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift index f13dcd023cb7..19646cea0fb7 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift @@ -2,6 +2,7 @@ import CmuxMobileShellModel actor BlockingNetworkEpochTrustStore: MobileManualHostTrustStoring { private var removeCount = 0 + private var trustCount = 0 private var removeWaiters: [CheckedContinuation] = [] private var releaseWaiters: [CheckedContinuation] = [] @@ -12,6 +13,7 @@ actor BlockingNetworkEpochTrustStore: MobileManualHostTrustStoring { func trust(_ scope: MobileManualHostTrustScope) async { _ = scope + trustCount += 1 } func removeAll() async { @@ -31,6 +33,10 @@ actor BlockingNetworkEpochTrustStore: MobileManualHostTrustStoring { removeCount } + func currentTrustCount() -> Int { + trustCount + } + func releaseRemovals() { let waiters = releaseWaiters releaseWaiters.removeAll() diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift index d23998428912..8e69e47e83a6 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostNetworkEpochTests.swift @@ -112,6 +112,62 @@ import Testing await trustStore.releaseRemovals() } + @Test func secondBoundarySupersedesApprovalWaitingForTrustReset() async throws { + let trustStore = BlockingNetworkEpochTrustStore() + let store = MobileShellComposite( + identityProvider: StaticIdentityProvider(userID: "phone-user"), + manualHostTrustStore: trustStore + ) + store.signIn() + store.invalidateManualHostTrustForNetworkBoundary() + await trustStore.waitUntilRemoveCount(1) + let route = try CmxAttachRoute( + id: "waiting-manual-host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 58_465) + ) + let firstAttemptID = store.beginPairingValidationAttempt() + store.queueManualHostTrustWarning( + route: route, + displayHost: "192.168.1.77", + pending: .manual( + attemptID: firstAttemptID, + name: "LAN Mac", + host: "192.168.1.77", + port: 58_465, + route: route, + pairedMacDeviceID: "manual-mac", + recordsPairingAttempt: false, + macSwitchAttemptID: nil, + ifStillCurrent: nil + ) + ) + let firstAuthScope = store.manualHostRPCAuthScope + let (approvalStarted, approvalStartedContinuation) = + AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + var approvalStartedIterator = approvalStarted.makeAsyncIterator() + let approval = Task { @MainActor in + approvalStartedContinuation.yield(()) + return await store.acceptManualHostTrustWarning() + } + _ = await approvalStartedIterator.next() + + store.invalidateManualHostTrustForNetworkBoundary() + let reissuedAttemptID = store.pendingManualHostTrust?.attemptID + + #expect(store.manualHostRPCAuthScope != firstAuthScope) + #expect(reissuedAttemptID != nil) + #expect(reissuedAttemptID != firstAttemptID) + #expect(await trustStore.currentRemoveCount() == 1) + await trustStore.releaseRemovals() + let result = await approval.value + + #expect(result == .superseded) + #expect(await trustStore.currentTrustCount() == 0) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + store.cancelPairing() + } + @Test func foregroundResumeDisconnectsActiveManualHostWithoutAPathEvent() async throws { let reachability = ControllablePathChangeReachability() let trustStore = NetworkEpochManualHostTrustStore() From 55b7efcf139efc1cf110420f555bc4c2697c18f2 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:20:23 -0700 Subject: [PATCH 72/91] fix(ios): rotate every network approval epoch --- ...MobileShellComposite+ManualHostTrust.swift | 84 +++++++++++++++---- 1 file changed, 68 insertions(+), 16 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 7ece98edc21e..c4aa00f4d9c9 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -1,6 +1,14 @@ import CMUXMobileCore public import CmuxMobileShellModel +private struct ManualHostReapproval { + let name: String + let host: String + let port: Int + let route: CmxAttachRoute + let pairedMacDeviceID: String? +} + @MainActor extension MobileShellComposite { func clearManualHostTrustWarning() { @@ -111,12 +119,19 @@ extension MobileShellComposite { /// - Returns: The resumed result, or `.superseded` when the warning is no longer current. @discardableResult public func acceptManualHostTrustWarning() async -> MobilePairingURLConnectionResult { + guard let approvalAttemptID = pendingManualHostTrust?.attemptID else { + clearManualHostTrustWarning() + return .superseded + } if let resetTask = manualHostTrustResetTask { await resetTask.value } guard let warning = manualHostTrustWarning, - let pending = pendingManualHostTrust else { - clearManualHostTrustWarning() + let pending = pendingManualHostTrust, + pending.attemptID == approvalAttemptID else { + if pendingManualHostTrust?.attemptID == approvalAttemptID { + clearManualHostTrustWarning() + } return .superseded } guard isPendingManualHostTrustCurrent(pending) else { @@ -200,31 +215,68 @@ extension MobileShellComposite { /// - Returns: Whether an active manual-host connection was queued for reapproval. @discardableResult func invalidateManualHostTrustForNetworkBoundary() -> Bool { + let reapproval = reissuableManualHostApproval() revokeSecondaryManualHostSubscriptions() - guard manualHostTrustResetTask == nil else { - // Preserve the approval queued by the first boundary while its - // durable trust reset is still in flight. - return pendingManualHostTrust != nil - } - rotateManualHostRPCAuthScope() invalidatePairingAttempt() clearSupersededManualHostTrustWarning() - manualHostTrustResetGeneration &+= 1 - let resetGeneration = manualHostTrustResetGeneration - let trustStore = manualHostTrustStore - manualHostTrustResetTask = Task { @MainActor [weak self] in - await trustStore.removeAll() - guard let self, - self.manualHostTrustResetGeneration == resetGeneration else { return } - self.manualHostTrustResetTask = nil + if manualHostTrustResetTask == nil { + manualHostTrustResetGeneration &+= 1 + let resetGeneration = manualHostTrustResetGeneration + let trustStore = manualHostTrustStore + manualHostTrustResetTask = Task { @MainActor [weak self] in + await trustStore.removeAll() + guard let self, + self.manualHostTrustResetGeneration == resetGeneration else { return } + self.manualHostTrustResetTask = nil + } + } + + if let reapproval { + let attemptID = beginPairingValidationAttempt() + queueManualHostTrustWarning( + route: reapproval.route, + displayHost: reapproval.host, + pending: .manual( + attemptID: attemptID, + name: reapproval.name, + host: reapproval.host, + port: reapproval.port, + route: reapproval.route, + pairedMacDeviceID: reapproval.pairedMacDeviceID, + recordsPairingAttempt: false, + macSwitchAttemptID: nil, + ifStillCurrent: nil + ) + ) + return true } guard remoteClient != nil else { return false } return queueForegroundManualHostReapproval(route: activeRoute) } + private func reissuableManualHostApproval() -> ManualHostReapproval? { + guard manualHostTrustWarning != nil, + case let .manual( + _, name, host, port, route, pairedMacDeviceID, + recordsPairingAttempt, macSwitchAttemptID, ifStillCurrent + )? = pendingManualHostTrust, + !recordsPairingAttempt, + macSwitchAttemptID == nil, + ifStillCurrent == nil else { + return nil + } + return ManualHostReapproval( + name: name, + host: host, + port: port, + route: route, + pairedMacDeviceID: pairedMacDeviceID + ) + } + private func revokeSecondaryManualHostSubscriptions() { for (macDeviceID, subscription) in secondaryMacSubscriptions where subscription.route.kind == .manualHost { From 1a9d25a75eb40f0bc3838f8189fbdd6d0446b00b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:38:01 -0700 Subject: [PATCH 73/91] test(ios): cover network recovery and route provenance --- .../MobileShellManualHostReconnectTests.swift | 30 ++++++++++++ .../NetworkRecoveryCoalescingTests.swift | 48 +++++++++++++++++++ .../ReconnectRouteSelectionTests.swift | 24 ++++++++-- .../MobileShellRouteAuthPolicyTests.swift | 8 ++-- 4 files changed, 101 insertions(+), 9 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/NetworkRecoveryCoalescingTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift index 3d296347e52a..c6b65b5352bb 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostReconnectTests.swift @@ -7,6 +7,36 @@ import Testing @MainActor @Suite struct MobileShellManualHostReconnectTests { + @Test(arguments: ["100.64.0.5", "copied-manual.tailnet.ts.net"]) + func tailscaleLookingManualEntryStillRequiresApproval(host: String) async { + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.manualHost, .tailscale], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + store.signIn() + + let result = await store.connectManualHost( + name: "Copied Manual Mac", + host: host, + port: CmxMobileDefaults.defaultHostPort + ) + + #expect(result == .needsUserApproval) + #expect(store.manualHostTrustWarning?.endpoint == "\(host):58465") + #expect(await router.count(of: "mobile.attach_ticket.create") == 0) + #expect(await router.count(of: "workspace.list") == 0) + } + @Test func activeManualHostReconnectWaitsForApprovalInsteadOfSwitchingMacs() async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/NetworkRecoveryCoalescingTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/NetworkRecoveryCoalescingTests.swift new file mode 100644 index 000000000000..bfa19242e126 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/NetworkRecoveryCoalescingTests.swift @@ -0,0 +1,48 @@ +import CMUXMobileCore +import Testing +@testable import CmuxMobileShell + +@MainActor +extension ReconnectRouteSelectionTests { + @Test func repeatedPathChangeDuringReconnectRunsTrailingAttempt() async throws { + let clock = TestClock() + let router = LivenessHostRouter() + let box = TransportBox() + let reachability = ControllablePathChangeReachability() + let factory = RouteRecordingTransportFactory( + router: router, + box: box, + failingPorts: [], + holdFirstFailingPort: 51002 + ) + let store = try await makeReconnectStore( + routes: [try loopbackRoute(id: "settling-network", port: 51002)], + runtime: LivenessTestRuntime( + transportFactory: factory, + now: { clock.now }, + supportedRouteKinds: [.debugLoopback] + ), + reachability: reachability + ) + store.startObservingNetworkPathChanges() + + reachability.emitPathChange() + let firstAttemptStarted = try await pollUntil { + factory.attemptedPorts() == [51002] + } + #expect(firstAttemptStarted) + let firstBoundaryScope = store.manualHostRPCAuthScope + reachability.emitPathChange() + let secondBoundaryApplied = try await pollUntil { + store.manualHostRPCAuthScope != firstBoundaryScope + } + #expect(secondBoundaryApplied) + factory.releaseHeldConnect() + let connected = try await pollUntil { + store.connectionState == .connected + } + + #expect(connected) + #expect(factory.attemptedPorts() == [51002, 51002, 51002]) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index 62ee52574684..3bed665114b0 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -2,6 +2,7 @@ import CMUXMobileCore import CmuxMobilePairedMac import CmuxMobileRPC import CmuxMobileShellModel +import CmuxMobileTransport import Foundation import Testing @testable import CmuxMobileShell @@ -99,6 +100,18 @@ import Testing #expect(route.endpoint == .hostPort(host: "192.168.1.77", port: 50906)) } + @Test func verifiedTailscaleSourcePreservesRouteKind() throws { + let source = try tailscale() + let route = try MobileShellRouteSelection().manualHostRoute( + host: "100.82.214.112", + port: 50906, + preserving: source + ) + + #expect(route == source) + #expect(route.kind == .tailscale) + } + @Test func invalidManualHostCannotConstructRoute() { do { _ = try MobileShellRouteSelection().manualHostRoute( @@ -319,7 +332,7 @@ import Testing #expect(factory.attemptedPorts() == [51000, 51001, 51001]) } - private func loopbackRoute(id: String, port: Int) throws -> CmxAttachRoute { + func loopbackRoute(id: String, port: Int) throws -> CmxAttachRoute { try CmxAttachRoute( id: id, kind: .debugLoopback, @@ -328,9 +341,10 @@ import Testing ) } - private func makeReconnectStore( + func makeReconnectStore( routes: [CmxAttachRoute], - runtime: any MobileSyncRuntime + runtime: any MobileSyncRuntime, + reachability: any ReachabilityProviding = AlwaysOnlineReachability() ) async throws -> MobileShellComposite { let (pairedStore, _) = try makePairedMacStore() try await pairedStore.upsert( @@ -347,7 +361,7 @@ import Testing isSignedIn: true, pairedMacStore: pairedStore, identityProvider: StaticIdentityProvider(userID: "user-1"), - reachability: AlwaysOnlineReachability(), + reachability: reachability, pairingHintDefaults: UserDefaults(suiteName: "reconnect-routes-\(UUID().uuidString)")! ) await store.loadPairedMacs() @@ -369,7 +383,7 @@ private enum RouteRecordingTransportError: Error { case routeFailed } -private final class RouteRecordingTransportFactory: CmxByteTransportFactory, @unchecked Sendable { +final class RouteRecordingTransportFactory: CmxByteTransportFactory, @unchecked Sendable { private let router: LivenessHostRouter private let box: TransportBox private let failingPorts: Set diff --git a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift index 225bcc678902..8ca7c5403333 100644 --- a/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift +++ b/Packages/iOS/CmuxMobileShellModel/Tests/CmuxMobileShellModelTests/MobileShellRouteAuthPolicyTests.swift @@ -84,8 +84,8 @@ import Testing for: "[::1]", allowsDebugLoopback: false ) == .manualHost) - #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "100.71.210.41") == .tailscale) - #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "work-mac.tailnet.ts.net") == .tailscale) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "100.71.210.41") == .manualHost) + #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "work-mac.tailnet.ts.net") == .manualHost) #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "127.attacker.example") == .manualHost) #expect(MobileShellRouteAuthPolicy().manualRouteKind(for: "https://bad.example") == nil) @@ -125,8 +125,8 @@ import Testing "0x7f.0.0.1", allowsDebugLoopback: false )) - #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("100.71.210.41")) - #expect(!MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("work-mac.tailnet.ts.net")) + #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("100.71.210.41")) + #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("work-mac.tailnet.ts.net")) #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("192.168.1.77")) #expect(MobileShellRouteAuthPolicy().manualHostNeedsTrustWarning("devbox.local")) } From 39b59c7b165a2c78df2a49d1de69c5823ce1833c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:42:06 -0700 Subject: [PATCH 74/91] fix(ios): preserve latest recovery and manual provenance --- ...ileShellComposite+ConnectionRecovery.swift | 94 ++++++++++++++++ .../MobileShellComposite.swift | 105 +++--------------- .../MobileShellRouteSelection.swift | 5 +- .../MobilePairingAttemptDeadlineTests.swift | 6 +- .../MobileShellRouteAuthPolicy.swift | 16 ++- 5 files changed, 128 insertions(+), 98 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift new file mode 100644 index 000000000000..1c7c457ff8c2 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -0,0 +1,94 @@ +@MainActor +extension MobileShellComposite { + enum RecoveryTrigger: CustomStringConvertible { + case networkChange + case manual + case presencePush + + var reschedulesSecondaryAggregation: Bool { self != .presencePush } + + var description: String { + switch self { + case .networkChange: return "networkChange" + case .manual: return "manual" + case .presencePush: return "presencePush" + } + } + } + + /// Begin observing every post-initial network path callback so a live + /// terminal recovers and plaintext trust is revoked when the network moves + /// out from under it. Idempotent; only the first call arms the observation. + func startObservingNetworkPathChanges() { + guard !networkPathObservationStarted else { return } + networkPathObservationStarted = true + let reachability = reachability + networkPathObservationTask = Task { @MainActor [weak self] in + // Every post-initial callback is a security boundary. Public NWPath + // attributes can look identical across two different Wi-Fi LANs. + for await _ in reachability.pathChanges() { + guard let self, !Task.isCancelled else { return } + if self.invalidateManualHostTrustForNetworkBoundary() { + continue + } + self.recoverMobileConnection(trigger: .networkChange) + } + } + } + + /// User-initiated reconnect from the Retry control. + public func retryMobileConnection() { + connectionRecoveryFailed = false + recoverMobileConnection(trigger: .manual) + } + + /// Single guarded recovery entry for every trigger (network change, manual + /// Retry). Connected sessions resync; disconnected sessions reconnect. A + /// later network boundary records one trailing attempt instead of cancelling + /// or losing the recovery whose authorization scope it just superseded. + func recoverMobileConnection(trigger: RecoveryTrigger) { + guard remoteClient != nil || pairedMacStore != nil else { return } + if recoveryInFlight || isRecoveringConnection { + if trigger == .networkChange { + networkRecoveryPending = true + } + return + } + if connectionState == .connected, remoteClient != nil { + markMacConnectionReconnecting() + resyncTerminalOutput(reason: "networkRecovery.\(trigger)", restartEventStream: true) + if multiMacAggregationEnabled, trigger.reschedulesSecondaryAggregation { + scheduleSecondaryAggregation() + } + return + } + recoveryInFlight = true + isRecoveringConnection = true + connectionRecoveryFailed = false + let stackUserID = lastReconnectStackUserID + recoveryTask?.cancel() + recoveryTask = Task { @MainActor [weak self] in + defer { self?.finishMobileConnectionRecoveryAttempt() } + guard let self, self.connectionState != .connected else { return } + let reconnected = await self.reconnectActiveMacIfAvailable(stackUserID: stackUserID) + if !reconnected, !Task.isCancelled { + self.connectionRecoveryFailed = true + } + } + } + + func finishMobileConnectionRecoveryAttempt() { + recoveryInFlight = false + isRecoveringConnection = false + recoveryTask = nil + drainPendingNetworkRecoveryIfIdle() + } + + func drainPendingNetworkRecoveryIfIdle() { + guard networkRecoveryPending, + !recoveryInFlight, + !isRecoveringConnection else { return } + networkRecoveryPending = false + recoverMobileConnection(trigger: .networkChange) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 41e671e84a86..51dbe8c7a310 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -607,7 +607,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private let presence: (any PresenceSubscribing)? let identityProvider: (any MobileIdentityProviding)? let teamIDProvider: @Sendable () async -> String? - private let reachability: any ReachabilityProviding + let reachability: any ReachabilityProviding // Internal (not private): used by the dismiss-sync extension file. let deliveredNotificationClearer: any DeliveredNotificationClearing /// Durable outbox for phone→Mac dismissals. @@ -1419,10 +1419,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// True while an automatic reconnect is in progress after a network change /// or drop. - public private(set) var isRecoveringConnection: Bool = false + public internal(set) var isRecoveringConnection: Bool = false /// True when automatic recovery could not restore the connection; the UI /// surfaces a manual Retry control in this state. - public private(set) var connectionRecoveryFailed: Bool = false { + public internal(set) var connectionRecoveryFailed: Bool = false { didSet { // Fire once on the false→true edge ("stuck disconnected, Retry is // dead"): the recovery-rate denominator. @@ -1442,89 +1442,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// the user-facing reason. public private(set) var connectionRequiresReauth: Bool = false - private var networkPathObservationStarted = false - private var networkPathObservationTask: Task? - private var recoveryInFlight = false - private var recoveryTask: Task? - private var lastReconnectStackUserID: String? - - private enum RecoveryTrigger: CustomStringConvertible { - case networkChange - case manual - case presencePush - - var reschedulesSecondaryAggregation: Bool { self != .presencePush } - - var description: String { - switch self { - case .networkChange: return "networkChange" - case .manual: return "manual" - case .presencePush: return "presencePush" - } - } - } - - /// Begin observing every post-initial network path callback so a live - /// terminal recovers and plaintext trust is revoked when the network moves - /// out from under it. Idempotent; only the first call arms the observation. - func startObservingNetworkPathChanges() { - guard !networkPathObservationStarted else { return } - networkPathObservationStarted = true - let reachability = reachability - networkPathObservationTask = Task { @MainActor [weak self] in - // Every post-initial callback is a security boundary. Public NWPath - // attributes can look identical across two different Wi-Fi LANs. - for await _ in reachability.pathChanges() { - guard let self, !Task.isCancelled else { return } - if self.invalidateManualHostTrustForNetworkBoundary() { - continue - } - self.recoverMobileConnection(trigger: .networkChange) - } - } - } - - /// User-initiated reconnect from the Retry control. - public func retryMobileConnection() { - connectionRecoveryFailed = false - recoverMobileConnection(trigger: .manual) - } - - /// Single guarded recovery entry for every trigger (network change, manual - /// Retry). When still connected, a network move usually only broke the event - /// stream while input keeps flowing over the surviving connection, so a - /// resync re-subscribes and requests a render-grid replay to repaint. - /// Otherwise the connection dropped, so reconnect once; on failure the UI - /// shows Retry and the next network change re-attempts automatically. - private func recoverMobileConnection(trigger: RecoveryTrigger) { - guard remoteClient != nil || pairedMacStore != nil else { return } - if connectionState == .connected, remoteClient != nil { - guard !isRecoveringConnection else { return } - markMacConnectionReconnecting() - resyncTerminalOutput(reason: "networkRecovery.\(trigger)", restartEventStream: true) - if multiMacAggregationEnabled, trigger.reschedulesSecondaryAggregation { - scheduleSecondaryAggregation() - } - return - } - guard !recoveryInFlight else { return } - recoveryInFlight = true - isRecoveringConnection = true - connectionRecoveryFailed = false - let stackUserID = lastReconnectStackUserID - recoveryTask?.cancel() - recoveryTask = Task { @MainActor [weak self] in - defer { - self?.recoveryInFlight = false - self?.isRecoveringConnection = false - } - guard let self, self.connectionState != .connected else { return } - let reconnected = await self.reconnectActiveMacIfAvailable(stackUserID: stackUserID) - if !reconnected, !Task.isCancelled { - self.connectionRecoveryFailed = true - } - } - } + var networkPathObservationStarted = false + var networkPathObservationTask: Task? + var recoveryInFlight = false + var recoveryTask: Task? + /// Newest-wins trailing network recovery. A later path callback must rotate + /// trust immediately, but cannot strand the reconnect it just superseded. + var networkRecoveryPending = false + var lastReconnectStackUserID: String? public func connectPreviewHost() { let trimmedCode = pairingCode.trimmingCharacters(in: .whitespacesAndNewlines) @@ -5714,15 +5639,18 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func markMacConnectionHealthy() { guard connectionState == .connected else { macConnectionStatus = .unavailable + isRecoveringConnection = false + drainPendingNetworkRecoveryIfIdle() return } macConnectionStatus = .connected isRecoveringConnection = false connectionRecoveryFailed = false connectionRequiresReauth = false + drainPendingNetworkRecoveryIfIdle() } - private func markMacConnectionReconnecting() { + func markMacConnectionReconnecting() { guard connectionState == .connected, remoteClient != nil else { macConnectionStatus = .unavailable return @@ -5735,11 +5663,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func markMacConnectionUnavailable() { guard connectionState == .connected else { macConnectionStatus = .unavailable + isRecoveringConnection = false + drainPendingNetworkRecoveryIfIdle() return } macConnectionStatus = .unavailable isRecoveringConnection = false connectionRecoveryFailed = true + drainPendingNetworkRecoveryIfIdle() } func markMacConnectionUnavailableIfNeeded(after error: any Error) { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift index ecd51ed9de48..09bd6313e6fb 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift @@ -172,7 +172,10 @@ struct MobileShellRouteSelection: Sendable { routeAuthPolicy.normalizedManualRouteHost(sourceHost) == routeAuthPolicy.normalizedManualRouteHost(host) else { return inferredRoute } - if sourceRoute.kind == .manualHost || sourceRoute.kind == inferredRoute.kind { + if sourceRoute.kind == .manualHost + || sourceRoute.kind == inferredRoute.kind + || (sourceRoute.kind == .tailscale + && routeAuthPolicy.routeAllowsStackAuth(sourceRoute)) { return sourceRoute } return inferredRoute diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 6bfbcdf5ddce..4988fd8f4f88 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -248,7 +248,11 @@ import Testing try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) let originalClient = try #require(store.remoteClient) - await store.connectManualHost(name: "Bad Route", host: "100.64.0.5", port: 58_465) + await store.connectManualHost( + name: "Bad Route", + host: "https://bad.example/path", + port: 58_465 + ) #expect(store.connectionState == .connected) #expect(store.remoteClient === originalClient) diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift index 2d23888d5855..09e7dc0fd8ba 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileShellRouteAuthPolicy.swift @@ -2,7 +2,7 @@ public import CMUXMobileCore import Foundation /// Pure routing/trust policy that decides which attach routes may carry Stack auth -/// and how a manually typed host maps to a transport kind. +/// and how a manually typed host maps to a conservative transport kind. /// /// All members are pure functions of their inputs so the trust decisions (loopback /// vs Tailscale vs LAN vs arbitrary host) can be exhaustively tested without a live @@ -46,9 +46,10 @@ public struct MobileShellRouteAuthPolicy: Sendable { /// - allowsDebugLoopback: Whether loopback aliases should become /// `.debugLoopback`. Keep this `false` for physical-device manual entry: /// loopback dials the phone itself there, not the Mac. - /// - Returns: `.debugLoopback` for allowed loopback hosts, `.tailscale` for - /// Tailscale IP/MagicDNS hosts, `.manualHost` otherwise, or `nil` for an - /// invalid host. + /// - Returns: `.debugLoopback` for allowed loopback hosts, `.manualHost` + /// otherwise, or `nil` for an invalid host. Host text alone never proves + /// that a raw TCP connection traverses Tailscale; only a structured route + /// may carry that provenance. public func manualRouteKind( for host: String, allowsDebugLoopback: Bool = true @@ -59,9 +60,6 @@ public struct MobileShellRouteAuthPolicy: Sendable { if allowsDebugLoopback, isLoopbackHost(normalizedHost) { return .debugLoopback } - if isTailscaleHost(normalizedHost) { - return .tailscale - } return .manualHost } @@ -168,12 +166,12 @@ public struct MobileShellRouteAuthPolicy: Sendable { return isLoopbackHost(host) } - /// Whether a manual host should warn the user that it is neither loopback nor Tailscale. + /// Whether a manually entered host should show the plaintext-route warning. /// - Parameters: /// - host: The manually typed host. /// - allowsDebugLoopback: Whether loopback aliases are trusted debug hosts /// for this caller. - /// - Returns: `true` when the host is valid but outside the loopback/Tailscale trust set. + /// - Returns: `true` for every valid host except an allowed debug loopback. public func manualHostNeedsTrustWarning( _ host: String, allowsDebugLoopback: Bool = true From a01b45fc3e3953b8cd0e9581a093024e82781e15 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:56:49 -0700 Subject: [PATCH 75/91] test(ios): cover scene and trust expiry lifecycle --- .../ImmediateExpiryManualHostTrustStore.swift | 25 ++++++++++++++ ...anualHostAuthorizationOwnershipTests.swift | 34 +++++++++++++++++++ .../MobileSceneRefreshActionTests.swift | 11 ++++++ 3 files changed, 70 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ImmediateExpiryManualHostTrustStore.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSceneRefreshActionTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ImmediateExpiryManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ImmediateExpiryManualHostTrustStore.swift new file mode 100644 index 000000000000..bb0fb764cc14 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ImmediateExpiryManualHostTrustStore.swift @@ -0,0 +1,25 @@ +import CmuxMobileShellModel +import Foundation + +actor ImmediateExpiryManualHostTrustStore: MobileManualHostTrustStoring { + private var expirationWasRequested = false + + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + _ = scope + return !expirationWasRequested + } + + func trust(_ scope: MobileManualHostTrustScope) async { + _ = scope + } + + func removeAll() async { + expirationWasRequested = true + } + + func expirationDate(for scope: MobileManualHostTrustScope) async -> Date? { + _ = scope + expirationWasRequested = true + return .distantPast + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift index b9645cc4b65e..6d45db088a6b 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellManualHostAuthorizationOwnershipTests.swift @@ -7,6 +7,40 @@ import Testing @MainActor @Suite struct MobileShellManualHostAuthorizationOwnershipTests { + @Test func expiredActiveManualTrustQueuesReapprovalWithoutAnotherRPC() async throws { + let trustStore = ImmediateExpiryManualHostTrustStore() + let router = LivenessHostRouter() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: trustStore + ) + store.signIn() + + let connected = await store.connectManualHost( + name: "Expiring LAN Mac", + host: "192.168.1.77", + port: 58_465 + ) + let reapprovalQueued = try await pollUntil(attempts: 50) { + store.manualHostTrustWarning != nil + } + + #expect(connected == .connected) + #expect(reapprovalQueued) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.1.77:58465") + #expect(store.connectionState == .disconnected) + #expect(store.remoteClient == nil) + } + @Test func revokedForegroundTrustQueuesHostApprovalWithoutAccountReauth() async throws { let route = try hostPortRoute(kind: .manualHost, host: "192.168.1.77", port: 58_465) let trustStore = InMemoryMobileManualHostTrustStore() diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSceneRefreshActionTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSceneRefreshActionTests.swift new file mode 100644 index 000000000000..3407c6ae977a --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSceneRefreshActionTests.swift @@ -0,0 +1,11 @@ +import SwiftUI +import Testing +@testable import CmuxMobileShellUI + +@Suite struct MobileSceneRefreshActionTests { + @Test func inactiveInterruptionDoesNotBecomeBackgroundTransition() { + #expect(MobileSceneRefreshAction.forScenePhase(.inactive) == .none) + #expect(MobileSceneRefreshAction.forScenePhase(.background) == .enterBackground) + #expect(MobileSceneRefreshAction.forScenePhase(.active) == .resumeForeground) + } +} From 44accd5e9a85d4da62f8961884b8db9e6bf9d953 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:59:57 -0700 Subject: [PATCH 76/91] fix(ios): own trust expiry and background boundaries --- ...MobileShellComposite+ManualHostTrust.swift | 57 +++++++++++++++++++ ...MobileShellComposite+ReconnectRoutes.swift | 3 +- .../MobileShellComposite+Scope.swift | 4 ++ .../MobileShellComposite.swift | 5 ++ .../MobilePairingAttemptDeadlineTests.swift | 6 +- .../MobileManualHostTrustStoring.swift | 13 ++++- ...erDefaultsMobileManualHostTrustStore.swift | 6 ++ .../CMUXMobileRootView.swift | 11 +++- .../MobileSceneRefreshAction.swift | 16 ++++++ 9 files changed, 112 insertions(+), 9 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index c4aa00f4d9c9..6e33a8383b64 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -1,5 +1,7 @@ import CMUXMobileCore +import CmuxMobileRPC public import CmuxMobileShellModel +import Foundation private struct ManualHostReapproval { let name: String @@ -211,6 +213,61 @@ extension MobileShellComposite { return await manualHostTrustStore.isTrusted(scope) } + func scheduleManualHostTrustExpirationForActiveRoute() { + manualHostTrustExpirationTask?.cancel() + manualHostTrustExpirationTask = nil + guard let route = activeRoute, + let client = remoteClient, + connectionState == .connected, + let scope = manualHostTrustScope(for: route) else { return } + let authScope = manualHostRPCAuthScope + let generation = connectionGeneration + let trustStore = manualHostTrustStore + manualHostTrustExpirationTask = Task { @MainActor [weak self] in + guard let expiration = await trustStore.expirationDate(for: scope), + let self, + self.manualHostTrustExpirationIsCurrent( + route: route, + client: client, + generation: generation, + authScope: authScope + ) else { return } + let delay = expiration.timeIntervalSince(self.runtime?.now() ?? Date()) + if delay > 0 { + try? await ContinuousClock().sleep(for: .seconds(delay)) + } + guard !Task.isCancelled, + self.manualHostTrustExpirationIsCurrent( + route: route, + client: client, + generation: generation, + authScope: authScope + ), + !(await trustStore.isTrusted(scope)), + self.manualHostTrustExpirationIsCurrent( + route: route, + client: client, + generation: generation, + authScope: authScope + ) else { return } + self.rotateManualHostRPCAuthScope() + _ = self.queueForegroundManualHostReapproval(route: route) + } + } + + private func manualHostTrustExpirationIsCurrent( + route: CmxAttachRoute, + client: MobileCoreRPCClient, + generation: UUID, + authScope: MobileRPCAuthScope + ) -> Bool { + connectionState == .connected + && remoteClient === client + && connectionGeneration == generation + && activeRoute == route + && manualHostRPCAuthScope == authScope + } + /// Revokes plaintext-route credentials at any boundary that may represent a new network. /// - Returns: Whether an active manual-host connection was queued for reapproval. @discardableResult diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift index 65f9cf4b3293..a3636fc930b2 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift @@ -47,7 +47,8 @@ extension MobileShellComposite { } } - /// Record that the app left the active scene phase. + /// Record that the app entered the background. Temporary `.inactive` + /// interruptions do not call this and therefore do not revoke trust. public func suspendForegroundRefresh() { guard lastBackgroundedAt == nil else { return } lastBackgroundedAt = runtime?.now() ?? Date() diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift index afbcb7e9d0a6..87b0643c7daf 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift @@ -18,6 +18,8 @@ extension MobileShellComposite { } func rotateRPCAuthScope() { + manualHostTrustExpirationTask?.cancel() + manualHostTrustExpirationTask = nil let invalidatedScopes = [rpcAuthScope, manualHostRPCAuthScope] for scope in invalidatedScopes { scope.revoke() } rpcAuthScope = MobileRPCAuthScope() @@ -34,6 +36,8 @@ extension MobileShellComposite { /// Invalidates only plaintext manual-host credentials after a network-path change. func rotateManualHostRPCAuthScope() { + manualHostTrustExpirationTask?.cancel() + manualHostTrustExpirationTask = nil let invalidatedScope = manualHostRPCAuthScope invalidatedScope.revoke() manualHostRPCAuthScope = MobileRPCAuthScope() diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 51dbe8c7a310..f725e0e70ac9 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -634,6 +634,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { var rpcAuthScope = MobileRPCAuthScope() var manualHostRPCAuthScope = MobileRPCAuthScope() var manualHostTrustResetTask: Task? + var manualHostTrustExpirationTask: Task? var manualHostTrustResetGeneration = 0 var rpcAuthStackUserID: String? /// Collapses connection-state edges into one-per-outage lost/recovered events. @@ -1044,6 +1045,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { presenceTask?.cancel() networkPathObservationTask?.cancel() manualHostTrustResetTask?.cancel() + manualHostTrustExpirationTask?.cancel() terminalEventListenerTask?.cancel() terminalSubscriptionStartTask?.cancel() renderGridLivenessTimer?.cancel() @@ -5182,6 +5184,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } private func clearActiveConnectionContext() { + manualHostTrustExpirationTask?.cancel() + manualHostTrustExpirationTask = nil activeTicket = nil activeRoute = nil connectedHostName = "" @@ -5647,6 +5651,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { isRecoveringConnection = false connectionRecoveryFailed = false connectionRequiresReauth = false + scheduleManualHostTrustExpirationForActiveRoute() drainPendingNetworkRecoveryIfIdle() } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift index 4988fd8f4f88..8911e1f7eb07 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingAttemptDeadlineTests.swift @@ -248,11 +248,7 @@ import Testing try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) let originalClient = try #require(store.remoteClient) - await store.connectManualHost( - name: "Bad Route", - host: "https://bad.example/path", - port: 58_465 - ) + await store.connectManualHost(name: "Bad Route", host: "https://bad.example/path", port: 58_465) #expect(store.connectionState == .connected) #expect(store.remoteClient === originalClient) diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift index a5aabe9d7dc3..761b1dcee585 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift @@ -1,4 +1,4 @@ -import Foundation +public import Foundation /// Persistence for explicit manual-host approvals. public protocol MobileManualHostTrustStoring: Sendable { @@ -10,6 +10,17 @@ public protocol MobileManualHostTrustStoring: Sendable { /// - Parameter scope: The scope to approve. func trust(_ scope: MobileManualHostTrustScope) async + /// Returns when the approval expires, or `nil` for stores without expiry. + /// - Parameter scope: The approved scope to inspect. + func expirationDate(for scope: MobileManualHostTrustScope) async -> Date? + /// Removes every stored approval. func removeAll() async } + +public extension MobileManualHostTrustStoring { + func expirationDate(for scope: MobileManualHostTrustScope) async -> Date? { + _ = scope + return nil + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift index cd4d801c8c58..a2fe554aaa9a 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -112,6 +112,12 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin defaults.set(persistedExpirations, forKey: key) } + /// Returns the recorded absolute expiry so the connection owner can queue + /// reapproval even when no further RPC happens after the deadline. + public func expirationDate(for scope: MobileManualHostTrustScope) async -> Date? { + trustedScopes[scope].map(Date.init(timeIntervalSince1970:)) + } + /// Removes every stored approval. public func removeAll() async { persistedExpirations.removeAll() diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 1486bc8117fb..7734d2e388d4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -142,8 +142,15 @@ struct CMUXMobileRootView: View { store.currentTeamDidChange() } .onChange(of: scenePhase) { _, phase in - guard phase == .active else { store.suspendForegroundRefresh(); return } - store.resumeForegroundRefresh() + switch MobileSceneRefreshAction.forScenePhase(phase) { + case .none: + return + case .enterBackground: + store.suspendForegroundRefresh() + return + case .resumeForeground: + store.resumeForegroundRefresh() + } // The user may have toggled Tailscale while we were backgrounded. tailscaleStatusMonitor?.refresh() // Re-check the Stack session on resume so one that died while diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift new file mode 100644 index 000000000000..7354d461b7c4 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift @@ -0,0 +1,16 @@ +import SwiftUI + +enum MobileSceneRefreshAction: Equatable { + case none + case enterBackground + case resumeForeground + + static func forScenePhase(_ phase: ScenePhase) -> Self { + switch phase { + case .active: .resumeForeground + case .background: .enterBackground + case .inactive: .none + @unknown default: .none + } + } +} From ce15f098e59f1b0d4eb0c7109291231ae8e8a3ba Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 22:27:36 -0700 Subject: [PATCH 77/91] test(ios): cover secondary trust and queue expiry --- .../MobileCoreRPCRequestQueueTests.swift | 61 ++++++++++++++++++ .../SendAuthorizationInvocationRecorder.swift | 14 +++++ ...ondaryManualHostTrustExpirationTests.swift | 62 +++++++++++++++++++ 3 files changed, 137 insertions(+) create mode 100644 Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/SendAuthorizationInvocationRecorder.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryManualHostTrustExpirationTests.swift diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift index ef77aafe72f0..cf5f4bbf2de8 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift @@ -4,6 +4,67 @@ import Testing @testable import CmuxMobileRPC @Suite struct MobileCoreRPCRequestQueueTests { + @Test func cancelledQueuedSendSkipsAuthorizationWork() async throws { + let transport = QueuedCancellationProbeTransport() + let session = MobileCoreRPCSession(makeTransport: { transport }) + let deadline = DispatchTime.now().uptimeNanoseconds + 60_000_000_000 + let firstID = "first-blocking-send" + let cancelledID = "cancelled-queued-send" + let liveID = "live-queued-send" + let authorizationRecorder = SendAuthorizationInvocationRecorder() + let first = Task { + try await session.send( + payload: try MobileCoreRPCClient.requestData(method: "workspace.list", id: firstID), + requestID: firstID, + deadlineUptimeNanoseconds: deadline + ) + } + #expect(try await transport.waitForSentRequestCount(1).map(\.id) == [firstID]) + + let cancelled = Task { + try await session.send( + payload: try MobileCoreRPCClient.requestData(method: "workspace.list", id: cancelledID), + requestID: cancelledID, + deadlineUptimeNanoseconds: deadline, + sendAuthorizer: { await authorizationRecorder.authorize() } + ) + } + for _ in 0..<200 where !(await session.queuedRequestIDs.contains(cancelledID)) { + await Task.yield() + } + #expect(await session.queuedRequestIDs.contains(cancelledID)) + cancelled.cancel() + do { + _ = try await cancelled.value + Issue.record("Expected queued send cancellation") + } catch is CancellationError { + } catch { + Issue.record("Expected CancellationError, got \(error)") + } + + let live = Task { + try await session.send( + payload: try MobileCoreRPCClient.requestData(method: "workspace.list", id: liveID), + requestID: liveID, + deadlineUptimeNanoseconds: deadline + ) + } + for _ in 0..<200 where !(await session.queuedRequestIDs.contains(liveID)) { + await Task.yield() + } + #expect(await session.queuedRequestIDs.contains(liveID)) + + await transport.releaseFirstSend() + #expect(try await transport.waitForSentRequestCount(2).map(\.id) == [firstID, liveID]) + #expect(await authorizationRecorder.invocationCount() == 0) + + first.cancel() + live.cancel() + _ = try? await first.value + _ = try? await live.value + await session.tearDown(error: .connectionClosed) + } + @Test func revokedQueuedSendPreservesCancellationWithoutClosingSession() async throws { let transport = QueuedCancellationProbeTransport() let session = MobileCoreRPCSession(makeTransport: { transport }) diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/SendAuthorizationInvocationRecorder.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/SendAuthorizationInvocationRecorder.swift new file mode 100644 index 000000000000..87548c2f8441 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/SendAuthorizationInvocationRecorder.swift @@ -0,0 +1,14 @@ +@testable import CmuxMobileRPC + +actor SendAuthorizationInvocationRecorder { + private var count = 0 + + func authorize() -> MobileRPCAuthScope.SendLease { + count += 1 + return MobileRPCAuthScope.SendLease() + } + + func invocationCount() -> Int { + count + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryManualHostTrustExpirationTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryManualHostTrustExpirationTests.swift new file mode 100644 index 000000000000..13793d0e2f0d --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryManualHostTrustExpirationTests.swift @@ -0,0 +1,62 @@ +import CMUXMobileCore +import CmuxMobilePairedMac +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct SecondaryManualHostTrustExpirationTests { + @Test func expiredTrustDisconnectsLiveSecondaryWithoutAnotherRPC() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let manualRoute = try CmxAttachRoute( + id: "expiring-secondary-manual-host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.88", port: 50_923) + ) + try await pairedMacStore.upsert( + macDeviceID: "secondary-mac", + displayName: "Secondary Mac", + routes: [manualRoute], + markActive: false, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let attempts = RouteAttemptRecorder() + let runtime = LivenessTestRuntime( + transportFactory: SecondaryRouteFallbackTransportFactory( + router: LivenessHostRouter(), + box: TransportBox(), + attempts: attempts + ), + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + isSignedIn: true, + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: ImmediateExpiryManualHostTrustStore() + ) + + await store.loadPairedMacs() + await store.refreshSecondaryMacWorkspaces() + let expired = try await pollUntil(attempts: 50) { + store.secondaryMacSubscriptions["secondary-mac"] == nil + } + + #expect(attempts.count(.manualHost) >= 1) + #expect(expired) + #expect(store.secondaryMacSubscriptions["secondary-mac"] == nil) + } +} From 32db47877684afe5a57ecac9e7b13187ca35b3fb Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 22:30:13 -0700 Subject: [PATCH 78/91] fix(ios): expire secondary trust and skip dead auth --- .../CmuxMobileRPC/MobileCoreRPCSession.swift | 16 +++--- ...eShellComposite+AuthorizationFailure.swift | 2 +- ...MobileShellComposite+ManualHostTrust.swift | 53 +++++++++++++++---- .../MobileShellComposite.swift | 4 ++ .../SecondaryMacSubscription.swift | 5 ++ 5 files changed, 62 insertions(+), 18 deletions(-) diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift index cffde3e0b6fa..4554f80ca695 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift @@ -360,6 +360,7 @@ actor MobileCoreRPCSession { private func writeLoop(transport: any CmxByteTransport, frames: AsyncStream) async { for await write in frames { if Task.isCancelled { return } + guard shouldSendQueuedWrite(write, claim: false) else { continue } if let authorizeSend = write.authorizeSend { do { _ = try await authorizeSend() @@ -368,7 +369,7 @@ actor MobileCoreRPCSession { continue } } - guard shouldSendQueuedWrite(write) else { continue } + guard shouldSendQueuedWrite(write, claim: true) else { continue } do { try await transport.send(write.frame) } catch { @@ -485,14 +486,13 @@ actor MobileCoreRPCSession { cont.resume(returning: .failure(MobileShellConnectionError.requestTimedOut)) } - private func shouldSendQueuedWrite(_ write: MobileCoreRPCPendingWrite) -> Bool { - if cancelledQueuedWriteIDs.remove(write.id) != nil { + private func shouldSendQueuedWrite(_ write: MobileCoreRPCPendingWrite, claim: Bool) -> Bool { + if cancelledQueuedWriteIDs.remove(write.id) != nil { return false } + guard queuedWriteIDs[write.requestID] == write.id, + pending[write.requestID] != nil else { return false } - guard queuedWriteIDs[write.requestID] == write.id else { - return false - } - queuedWriteIDs[write.requestID] = nil - return pending[write.requestID] != nil + if claim { queuedWriteIDs[write.requestID] = nil } + return true } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift index cf31ac455941..339ed2a73779 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+AuthorizationFailure.swift @@ -73,7 +73,7 @@ extension MobileShellComposite { return true } - private func invalidateSecondaryConnection( + func invalidateSecondaryConnection( macDeviceID: String, client: MobileCoreRPCClient ) { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 6e33a8383b64..9c07b28c57a8 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -268,6 +268,42 @@ extension MobileShellComposite { && manualHostRPCAuthScope == authScope } + func scheduleManualHostTrustExpirationForSecondarySubscription( + _ subscription: SecondaryMacSubscription, + stackUserID: String + ) { + subscription.trustExpirationTask?.cancel() + subscription.trustExpirationTask = nil + guard let scope = manualHostTrustScope( + for: subscription.route, + stackUserID: stackUserID + ) else { return } + let trustStore = manualHostTrustStore + subscription.trustExpirationTask = Task { @MainActor [weak self, weak subscription] in + guard let expiration = await trustStore.expirationDate(for: scope), + let self, + let subscription, + self.secondaryMacSubscriptions[subscription.macDeviceID] === subscription else { + return + } + let delay = expiration.timeIntervalSince(self.runtime?.now() ?? Date()) + if delay > 0 { + // Trust expiry is an intentional bounded deadline tied to this subscription's lifecycle. + try? await ContinuousClock().sleep(for: .seconds(delay)) + } + guard !Task.isCancelled, + self.secondaryMacSubscriptions[subscription.macDeviceID] === subscription, + !(await trustStore.isTrusted(scope)), + self.secondaryMacSubscriptions[subscription.macDeviceID] === subscription else { + return + } + self.invalidateSecondaryConnection( + macDeviceID: subscription.macDeviceID, + client: subscription.client + ) + } + } + /// Revokes plaintext-route credentials at any boundary that may represent a new network. /// - Returns: Whether an active manual-host connection was queued for reapproval. @discardableResult @@ -335,15 +371,14 @@ extension MobileShellComposite { } private func revokeSecondaryManualHostSubscriptions() { - for (macDeviceID, subscription) in secondaryMacSubscriptions - where subscription.route.kind == .manualHost { - subscription.cancel() - secondaryMacSubscriptions[macDeviceID] = nil - removeSecondaryConnectionFromPool(macDeviceID: macDeviceID) - if var state = workspacesByMac[macDeviceID] { - state.status = .unavailable - workspacesByMac[macDeviceID] = state - } + let subscriptions = secondaryMacSubscriptions.values.filter { + $0.route.kind == .manualHost + } + for subscription in subscriptions { + invalidateSecondaryConnection( + macDeviceID: subscription.macDeviceID, + client: subscription.client + ) } } } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index f725e0e70ac9..765358b591a3 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -3690,6 +3690,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { actionCapabilities: handle.actionCapabilities ) secondaryMacSubscriptions[macID] = subscription + scheduleManualHostTrustExpirationForSecondarySubscription( + subscription, + stackUserID: scope.userID + ) let displayName = mac.displayName let previews = await fetchSecondaryWorkspaces(on: client, macDeviceID: macID) // The fetch await is another sign-out window: drop the just-opened diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/SecondaryMacSubscription.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/SecondaryMacSubscription.swift index b0edd65aea38..d897494f5988 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/SecondaryMacSubscription.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/SecondaryMacSubscription.swift @@ -21,6 +21,7 @@ final class SecondaryMacSubscription { /// Coalesces hot `workspace.updated` bursts to one leading and one trailing fetch. var refreshTask: Task? var refreshPending = false + var trustExpirationTask: Task? init( macDeviceID: String, @@ -44,6 +45,8 @@ final class SecondaryMacSubscription { task = nil refreshTask?.cancel() refreshTask = nil + trustExpirationTask?.cancel() + trustExpirationTask = nil let client = self.client Task { await client.disconnect() } } @@ -54,5 +57,7 @@ final class SecondaryMacSubscription { task = nil refreshTask?.cancel() refreshTask = nil + trustExpirationTask?.cancel() + trustExpirationTask = nil } } From e4443e1af963aaba56512e81a3a86bbc3d8b61cb Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 22:59:02 -0700 Subject: [PATCH 79/91] Organize manual host authorization helpers --- .../CmuxMobileRPC/MobileCoreRPCClient.swift | 2 +- .../MobileCoreRPCPendingWrite.swift | 2 +- .../CmuxMobileRPC/MobileCoreRPCSession.swift | 2 +- .../CmuxMobileRPC/MobileRPCAuthScope.swift | 14 ++-- .../CmuxMobileRPC/MobileRPCSendLease.swift | 2 + .../CmuxMobileRPC/RPCStackTokenGate.swift | 32 +++----- .../CmuxMobileRPC/RPCStackTokenScopeKey.swift | 4 + .../RPCStackTokenTaskState.swift | 8 ++ .../SendAuthorizationInvocationRecorder.swift | 4 +- .../MobileShellReconnectRouteCandidate.swift | 8 ++ .../MobileShellRouteSelection.swift | 7 -- .../BlockingAccountSwitchTokenProvider.swift | 27 +++++++ .../BlockingNetworkEpochTrustStore.swift | 13 ++-- .../ControllablePathChangeReachability.swift | 27 ------- .../HeldAuthorizationFailureGate.swift | 24 ++++++ .../HeldAuthorizationFailureTransport.swift | 36 --------- ...AuthorizationFailureTransportFactory.swift | 12 +++ ...nualFallbackApprovalTransportFactory.swift | 15 ---- ...obileManualHostTrustPersistenceTests.swift | 13 ---- .../NetworkEpochManualHostTrustStore.swift | 28 +++++++ .../RecordedAuthLivenessTransport.swift | 49 ------------ ...RecordedAuthLivenessTransportFactory.swift | 11 +++ .../RecordedAuthTokenSink.swift | 10 +++ .../RefusingManualHostTrustStore.swift | 14 ++++ .../RouteAttemptRecorder.swift | 17 +++++ ...condaryRouteFallbackTransportFactory.swift | 7 +- .../MobileManualHostTrustScope.swift | 8 -- .../MobileManualHostTrustStoredState.swift | 55 ++++++++++++++ .../MobileManualHostTrustStoring.swift | 3 + ...erDefaultsMobileManualHostTrustStore.swift | 76 +++---------------- .../CMUXMobileRootView.swift | 2 +- .../MobileSceneRefreshAction.swift | 4 +- .../MobileSceneRefreshActionTests.swift | 6 +- 33 files changed, 271 insertions(+), 271 deletions(-) create mode 100644 Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCSendLease.swift create mode 100644 Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenScopeKey.swift create mode 100644 Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenTaskState.swift create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellReconnectRouteCandidate.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingAccountSwitchTokenProvider.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureGate.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransportFactory.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/NetworkEpochManualHostTrustStore.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransportFactory.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthTokenSink.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RefusingManualHostTrustStore.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RouteAttemptRecorder.swift create mode 100644 Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoredState.swift diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift index 0608787b8a75..a38792958e2a 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient.swift @@ -378,7 +378,7 @@ public final class MobileCoreRPCClient: MobileSyncing, Sendable { try await validateAuthScope() } - private func authorizeTokenBearingSend() async throws -> MobileRPCAuthScope.SendLease { + private func authorizeTokenBearingSend() async throws -> MobileRPCSendLease { try await validateTokenBearingRequestBeforeEnqueue() guard let lease = authScope.beginSend() else { throw CancellationError() diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCPendingWrite.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCPendingWrite.swift index bfac977b2aa0..a3d468347367 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCPendingWrite.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCPendingWrite.swift @@ -4,5 +4,5 @@ struct MobileCoreRPCPendingWrite: Sendable { let id: UUID let requestID: String let frame: Data - let authorizeSend: (@Sendable () async throws -> MobileRPCAuthScope.SendLease)? + let authorizeSend: (@Sendable () async throws -> MobileRPCSendLease)? } diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift index 4554f80ca695..17924f37f8cf 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCSession.swift @@ -4,7 +4,7 @@ actor MobileCoreRPCSession { typealias TransportFactory = @Sendable () throws -> any CmxByteTransport typealias ConnectedCandidateHook = @Sendable (_ candidate: any CmxByteTransport) async -> Void typealias PreEnqueueValidator = @Sendable () async throws -> Void - typealias SendAuthorizer = @Sendable () async throws -> MobileRPCAuthScope.SendLease + typealias SendAuthorizer = @Sendable () async throws -> MobileRPCSendLease typealias PendingContinuation = CheckedContinuation, Never> typealias ConnectingTask = (id: UUID, lease: MobileRPCConnectAttemptLease?, task: Task, waiters: Set, completed: Bool) static let defaultAbandonedConnectCleanupTimeoutNanoseconds: UInt64 = 1_000_000_000 diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCAuthScope.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCAuthScope.swift index f44490f0402d..b0e17bfa2349 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCAuthScope.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCAuthScope.swift @@ -7,12 +7,10 @@ import os /// or manual-host network trust epoch changes. Token acquisition and transport enqueue use /// it as a non-secret key so requests from different auth epochs never share an /// in-flight credential task. -// `rawValue` is immutable and the only mutable field is accessed exclusively -// through `isRevokedLock`, so cross-task references cannot race. +/// +/// `rawValue` is immutable and the only mutable field is accessed exclusively +/// through `isRevokedLock`, so the unchecked sendability has no cross-task race. public final class MobileRPCAuthScope: @unchecked Sendable, Hashable { - /// A one-send capability acquired at the writer's authorization linearization point. - struct SendLease: Sendable {} - private let rawValue: UUID // lint:allow lock - scope revocation and writer admission must be synchronous; // an actor hop would recreate the authorization TOCTOU this flag closes. @@ -29,17 +27,19 @@ public final class MobileRPCAuthScope: @unchecked Sendable, Hashable { } /// Acquires authorization for one send if revocation has not linearized first. - func beginSend() -> SendLease? { + func beginSend() -> MobileRPCSendLease? { isRevokedLock.withLock { isRevoked in guard !isRevoked else { return nil } - return SendLease() + return MobileRPCSendLease() } } + /// Returns whether two scopes represent the same authorization epoch. public static func == (lhs: MobileRPCAuthScope, rhs: MobileRPCAuthScope) -> Bool { lhs.rawValue == rhs.rawValue } + /// Hashes the authorization epoch identity into the supplied hasher. public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCSendLease.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCSendLease.swift new file mode 100644 index 000000000000..68c183f35b74 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileRPCSendLease.swift @@ -0,0 +1,2 @@ +/// A one-send capability acquired at the writer's authorization linearization point. +struct MobileRPCSendLease: Sendable {} diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenGate.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenGate.swift index b68d35254088..3c8ea5553d38 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenGate.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenGate.swift @@ -2,20 +2,8 @@ import Foundation /// Deduplicates Stack access-token acquisition across mobile RPC clients owned by the same shell. public actor RPCStackTokenGate { - private enum ScopeKey: Hashable, Sendable { - case unscoped - case scoped(MobileRPCAuthScope) - } - - private struct CurrentTokenTask { - let id: UUID - let task: Task - var waiters: Int - var timedOutUntil: UInt64? - } - - private var currentByScope: [ScopeKey: CurrentTokenTask] = [:] - private var abandonedByScope: [ScopeKey: [UUID: Task]] = [:] + private var currentByScope: [RPCStackTokenScopeKey: RPCStackTokenTaskState] = [:] + private var abandonedByScope: [RPCStackTokenScopeKey: [UUID: Task]] = [:] private let taskTimeout = RPCTaskTimeout() private let timedOutResetNanoseconds: UInt64 @@ -29,7 +17,7 @@ public actor RPCStackTokenGate { timeoutNanoseconds: UInt64, provider: @escaping @Sendable () async throws -> String ) async throws -> String { - let scopeKey = scope.map(ScopeKey.scoped) ?? .unscoped + let scopeKey = scope.map(RPCStackTokenScopeKey.scoped) ?? .unscoped let id: UUID let task: Task if let existing = currentByScope[scopeKey], let timedOutUntil = existing.timedOutUntil { @@ -50,7 +38,7 @@ public actor RPCStackTokenGate { } else { id = UUID() task = Task { try await provider() } - currentByScope[scopeKey] = CurrentTokenTask( + currentByScope[scopeKey] = RPCStackTokenTaskState( id: id, task: task, waiters: 1, @@ -82,20 +70,20 @@ public actor RPCStackTokenGate { /// disturbing requests from another signed-in scope. public func invalidate(scope: MobileRPCAuthScope) { scope.revoke() - let scopeKey = ScopeKey.scoped(scope) + let scopeKey = RPCStackTokenScopeKey.scoped(scope) currentByScope.removeValue(forKey: scopeKey)?.task.cancel() let abandoned = abandonedByScope.removeValue(forKey: scopeKey)?.values ?? [:].values for task in abandoned { task.cancel() } } - private func timeoutWaiter(scopeKey: ScopeKey, id: UUID) { + private func timeoutWaiter(scopeKey: RPCStackTokenScopeKey, id: UUID) { guard var current = currentByScope[scopeKey], current.id == id else { return } current.waiters -= 1 guard current.waiters <= 0 else { currentByScope[scopeKey] = current return } - currentByScope[scopeKey] = CurrentTokenTask( + currentByScope[scopeKey] = RPCStackTokenTaskState( id: id, task: current.task, waiters: 0, @@ -104,14 +92,14 @@ public actor RPCStackTokenGate { current.task.cancel() } - private func cancelWaiter(scopeKey: ScopeKey, id: UUID) { + private func cancelWaiter(scopeKey: RPCStackTokenScopeKey, id: UUID) { guard var current = currentByScope[scopeKey], current.id == id else { return } current.waiters -= 1 guard current.waiters <= 0 else { currentByScope[scopeKey] = current return } - currentByScope[scopeKey] = CurrentTokenTask( + currentByScope[scopeKey] = RPCStackTokenTaskState( id: id, task: current.task, waiters: 0, @@ -120,7 +108,7 @@ public actor RPCStackTokenGate { current.task.cancel() } - private func clear(scopeKey: ScopeKey, id: UUID) { + private func clear(scopeKey: RPCStackTokenScopeKey, id: UUID) { if currentByScope[scopeKey]?.id == id { currentByScope[scopeKey] = nil } diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenScopeKey.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenScopeKey.swift new file mode 100644 index 000000000000..701a5797c7d2 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenScopeKey.swift @@ -0,0 +1,4 @@ +enum RPCStackTokenScopeKey: Hashable, Sendable { + case unscoped + case scoped(MobileRPCAuthScope) +} diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenTaskState.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenTaskState.swift new file mode 100644 index 000000000000..5f345a0ef466 --- /dev/null +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/RPCStackTokenTaskState.swift @@ -0,0 +1,8 @@ +import Foundation + +struct RPCStackTokenTaskState { + let id: UUID + let task: Task + var waiters: Int + var timedOutUntil: UInt64? +} diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/SendAuthorizationInvocationRecorder.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/SendAuthorizationInvocationRecorder.swift index 87548c2f8441..803fd1b4e81f 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/SendAuthorizationInvocationRecorder.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/SendAuthorizationInvocationRecorder.swift @@ -3,9 +3,9 @@ actor SendAuthorizationInvocationRecorder { private var count = 0 - func authorize() -> MobileRPCAuthScope.SendLease { + func authorize() -> MobileRPCSendLease { count += 1 - return MobileRPCAuthScope.SendLease() + return MobileRPCSendLease() } func invocationCount() -> Int { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellReconnectRouteCandidate.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellReconnectRouteCandidate.swift new file mode 100644 index 000000000000..8374657283e7 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellReconnectRouteCandidate.swift @@ -0,0 +1,8 @@ +import CMUXMobileCore + +struct MobileShellReconnectRouteCandidate: Equatable, Sendable { + let route: CmxAttachRoute + let host: String + let port: Int + var routeID: String { route.id } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift index 09bd6313e6fb..908a7db56753 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellRouteSelection.swift @@ -3,13 +3,6 @@ import CmuxMobileShellModel import Darwin import Foundation -struct MobileShellReconnectRouteCandidate: Equatable, Sendable { - let route: CmxAttachRoute - let host: String - let port: Int - var routeID: String { route.id } -} - struct MobileShellRouteSelection: Sendable { let routeAuthPolicy: MobileShellRouteAuthPolicy diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingAccountSwitchTokenProvider.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingAccountSwitchTokenProvider.swift new file mode 100644 index 000000000000..c1d80039b4a4 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingAccountSwitchTokenProvider.swift @@ -0,0 +1,27 @@ +actor BlockingAccountSwitchTokenProvider { + private var didEnter = false + private var enteredWaiters: [CheckedContinuation] = [] + private var releaseWaiters: [CheckedContinuation] = [] + private var token = "user-a-token" + + func waitUntilRequested() async { + if didEnter { return } + await withCheckedContinuation { enteredWaiters.append($0) } + } + + func tokenIgnoringCancellation() async throws -> String { + didEnter = true + let waiters = enteredWaiters + enteredWaiters.removeAll() + for waiter in waiters { waiter.resume() } + await withCheckedContinuation { releaseWaiters.append($0) } + return token + } + + func release(with token: String) { + self.token = token + let waiters = releaseWaiters + releaseWaiters.removeAll() + for waiter in waiters { waiter.resume() } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift index 19646cea0fb7..2c7d89e42f43 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/BlockingNetworkEpochTrustStore.swift @@ -3,7 +3,10 @@ import CmuxMobileShellModel actor BlockingNetworkEpochTrustStore: MobileManualHostTrustStoring { private var removeCount = 0 private var trustCount = 0 - private var removeWaiters: [CheckedContinuation] = [] + private var removeWaiters: [( + expected: Int, + continuation: CheckedContinuation + )] = [] private var releaseWaiters: [CheckedContinuation] = [] func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { @@ -18,15 +21,15 @@ actor BlockingNetworkEpochTrustStore: MobileManualHostTrustStoring { func removeAll() async { removeCount += 1 - let waiters = removeWaiters - removeWaiters.removeAll() - for waiter in waiters { waiter.resume() } + let readyWaiters = removeWaiters.filter { $0.expected <= removeCount } + removeWaiters.removeAll { $0.expected <= removeCount } + for waiter in readyWaiters { waiter.continuation.resume() } await withCheckedContinuation { releaseWaiters.append($0) } } func waitUntilRemoveCount(_ expected: Int) async { if removeCount >= expected { return } - await withCheckedContinuation { removeWaiters.append($0) } + await withCheckedContinuation { removeWaiters.append((expected, $0)) } } func currentRemoveCount() -> Int { diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ControllablePathChangeReachability.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ControllablePathChangeReachability.swift index 5096e1131587..1b2c3828c918 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ControllablePathChangeReachability.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ControllablePathChangeReachability.swift @@ -17,30 +17,3 @@ struct ControllablePathChangeReachability: ReachabilityProviding, Sendable { func emitPathChange() { continuation.yield(()) } } - -actor NetworkEpochManualHostTrustStore: MobileManualHostTrustStoring { - private var scopes: Set = [] - private var didRemoveAll = false - private var removeWaiters: [CheckedContinuation] = [] - - func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { - scopes.contains(scope) - } - - func trust(_ scope: MobileManualHostTrustScope) async { - scopes.insert(scope) - } - - func removeAll() async { - scopes.removeAll() - didRemoveAll = true - let waiters = removeWaiters - removeWaiters.removeAll() - for waiter in waiters { waiter.resume() } - } - - func waitUntilRemoved() async { - if didRemoveAll { return } - await withCheckedContinuation { removeWaiters.append($0) } - } -} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureGate.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureGate.swift new file mode 100644 index 000000000000..cb834f44ec9f --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureGate.swift @@ -0,0 +1,24 @@ +actor HeldAuthorizationFailureGate { + private var didReachHeldRequest = false + private var reachedWaiters: [CheckedContinuation] = [] + private var releaseWaiters: [CheckedContinuation] = [] + + func waitUntilReached() async { + if didReachHeldRequest { return } + await withCheckedContinuation { reachedWaiters.append($0) } + } + + func holdUntilReleased() async { + didReachHeldRequest = true + let waiters = reachedWaiters + reachedWaiters.removeAll() + for waiter in waiters { waiter.resume() } + await withCheckedContinuation { releaseWaiters.append($0) } + } + + func release() { + let waiters = releaseWaiters + releaseWaiters.removeAll() + for waiter in waiters { waiter.resume() } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransport.swift index 666c2b94f927..c88cf31c7428 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransport.swift @@ -2,42 +2,6 @@ import CMUXMobileCore import CmuxMobileRPC import Foundation -actor HeldAuthorizationFailureGate { - private var didReachHeldRequest = false - private var reachedWaiters: [CheckedContinuation] = [] - private var releaseWaiters: [CheckedContinuation] = [] - - func waitUntilReached() async { - if didReachHeldRequest { return } - await withCheckedContinuation { reachedWaiters.append($0) } - } - - func holdUntilReleased() async { - didReachHeldRequest = true - let waiters = reachedWaiters - reachedWaiters.removeAll() - for waiter in waiters { waiter.resume() } - await withCheckedContinuation { releaseWaiters.append($0) } - } - - func release() { - let waiters = releaseWaiters - releaseWaiters.removeAll() - for waiter in waiters { waiter.resume() } - } -} - -struct HeldAuthorizationFailureTransportFactory: CmxByteTransportFactory { - let method: String - let gate: HeldAuthorizationFailureGate - let router: LivenessHostRouter - - func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { - _ = route - return HeldAuthorizationFailureTransport(method: method, gate: gate, router: router) - } -} - actor HeldAuthorizationFailureTransport: CmxByteTransport { private let method: String private let gate: HeldAuthorizationFailureGate diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransportFactory.swift new file mode 100644 index 000000000000..5f28cfeb9dba --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/HeldAuthorizationFailureTransportFactory.swift @@ -0,0 +1,12 @@ +import CMUXMobileCore + +struct HeldAuthorizationFailureTransportFactory: CmxByteTransportFactory { + let method: String + let gate: HeldAuthorizationFailureGate + let router: LivenessHostRouter + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + _ = route + return HeldAuthorizationFailureTransport(method: method, gate: gate, router: router) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift index 2b9f2060eb67..0524cb605628 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualFallbackApprovalTransportFactory.swift @@ -1,21 +1,6 @@ import CMUXMobileCore import Foundation -/// Synchronous test probe: every access to mutable state is serialized by `lock`, -/// and no locked region crosses an async suspension point. -final class RouteAttemptRecorder: @unchecked Sendable { - private let lock = NSLock() - private var counts: [CmxAttachTransportKind: Int] = [:] - - func record(_ kind: CmxAttachTransportKind) { - lock.withLock { counts[kind, default: 0] += 1 } - } - - func count(_ kind: CmxAttachTransportKind) -> Int { - lock.withLock { counts[kind, default: 0] } - } -} - struct ManualFallbackApprovalTransportFactory: CmxByteTransportFactory { let router: LivenessHostRouter let box: TransportBox diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift index 323fa85cd973..bca7816819d4 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileManualHostTrustPersistenceTests.swift @@ -40,16 +40,3 @@ import Testing #expect(await router.count(of: "workspace.list") == 0) } } - -private actor RefusingManualHostTrustStore: MobileManualHostTrustStoring { - func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { - _ = scope - return false - } - - func trust(_ scope: MobileManualHostTrustScope) async { - _ = scope - } - - func removeAll() async {} -} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/NetworkEpochManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/NetworkEpochManualHostTrustStore.swift new file mode 100644 index 000000000000..6a59b1046490 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/NetworkEpochManualHostTrustStore.swift @@ -0,0 +1,28 @@ +import CmuxMobileShellModel + +actor NetworkEpochManualHostTrustStore: MobileManualHostTrustStoring { + private var scopes: Set = [] + private var didRemoveAll = false + private var removeWaiters: [CheckedContinuation] = [] + + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + scopes.contains(scope) + } + + func trust(_ scope: MobileManualHostTrustScope) async { + scopes.insert(scope) + } + + func removeAll() async { + scopes.removeAll() + didRemoveAll = true + let waiters = removeWaiters + removeWaiters.removeAll() + for waiter in waiters { waiter.resume() } + } + + func waitUntilRemoved() async { + if didRemoveAll { return } + await withCheckedContinuation { removeWaiters.append($0) } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransport.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransport.swift index 0f6e2baaca6e..ff0bcb699f2f 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransport.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransport.swift @@ -2,27 +2,6 @@ import CMUXMobileCore import CmuxMobileRPC import Foundation -actor RecordedAuthTokenSink { - private var tokens: [String] = [] - - func record(_ token: String?) { - guard let token else { return } - tokens.append(token) - } - - func recordedTokens() -> [String] { tokens } -} - -struct RecordedAuthLivenessTransportFactory: CmxByteTransportFactory { - let router: LivenessHostRouter - let tokenSink: RecordedAuthTokenSink - - func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { - _ = route - return RecordedAuthLivenessTransport(router: router, tokenSink: tokenSink) - } -} - actor RecordedAuthLivenessTransport: CmxByteTransport { private let router: LivenessHostRouter private let tokenSink: RecordedAuthTokenSink @@ -79,31 +58,3 @@ actor RecordedAuthLivenessTransport: CmxByteTransport { } } } - -actor BlockingAccountSwitchTokenProvider { - private var didEnter = false - private var enteredWaiters: [CheckedContinuation] = [] - private var releaseWaiters: [CheckedContinuation] = [] - private var token = "user-a-token" - - func waitUntilRequested() async { - if didEnter { return } - await withCheckedContinuation { enteredWaiters.append($0) } - } - - func tokenIgnoringCancellation() async throws -> String { - didEnter = true - let waiters = enteredWaiters - enteredWaiters.removeAll() - for waiter in waiters { waiter.resume() } - await withCheckedContinuation { releaseWaiters.append($0) } - return token - } - - func release(with token: String) { - self.token = token - let waiters = releaseWaiters - releaseWaiters.removeAll() - for waiter in waiters { waiter.resume() } - } -} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransportFactory.swift new file mode 100644 index 000000000000..014f309c8dba --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthLivenessTransportFactory.swift @@ -0,0 +1,11 @@ +import CMUXMobileCore + +struct RecordedAuthLivenessTransportFactory: CmxByteTransportFactory { + let router: LivenessHostRouter + let tokenSink: RecordedAuthTokenSink + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + _ = route + return RecordedAuthLivenessTransport(router: router, tokenSink: tokenSink) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthTokenSink.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthTokenSink.swift new file mode 100644 index 000000000000..cf31e325aa68 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RecordedAuthTokenSink.swift @@ -0,0 +1,10 @@ +actor RecordedAuthTokenSink { + private var tokens: [String] = [] + + func record(_ token: String?) { + guard let token else { return } + tokens.append(token) + } + + func recordedTokens() -> [String] { tokens } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RefusingManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RefusingManualHostTrustStore.swift new file mode 100644 index 000000000000..49b3bd874485 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RefusingManualHostTrustStore.swift @@ -0,0 +1,14 @@ +import CmuxMobileShellModel + +actor RefusingManualHostTrustStore: MobileManualHostTrustStoring { + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + _ = scope + return false + } + + func trust(_ scope: MobileManualHostTrustScope) async { + _ = scope + } + + func removeAll() async {} +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RouteAttemptRecorder.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RouteAttemptRecorder.swift new file mode 100644 index 000000000000..9e1607aefd6d --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/RouteAttemptRecorder.swift @@ -0,0 +1,17 @@ +import CMUXMobileCore +import Foundation + +/// Synchronous test probe: every access to mutable state is serialized by `lock`, +/// and no locked region crosses an async suspension point. +final class RouteAttemptRecorder: @unchecked Sendable { + private let lock = NSLock() + private var counts: [CmxAttachTransportKind: Int] = [:] + + func record(_ kind: CmxAttachTransportKind) { + lock.withLock { counts[kind, default: 0] += 1 } + } + + func count(_ kind: CmxAttachTransportKind) -> Int { + lock.withLock { counts[kind, default: 0] } + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTransportFactory.swift index bc5e4fad52b3..30b17c7a6524 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTransportFactory.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/SecondaryRouteFallbackTransportFactory.swift @@ -1,10 +1,7 @@ import CMUXMobileCore +import Foundation struct SecondaryRouteFallbackTransportFactory: CmxByteTransportFactory { - enum Failure: Error { - case unreachablePreferredRoute - } - let router: LivenessHostRouter let box: TransportBox let attempts: RouteAttemptRecorder @@ -12,7 +9,7 @@ struct SecondaryRouteFallbackTransportFactory: CmxByteTransportFactory { func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { attempts.record(route.kind) guard route.kind != .tailscale else { - throw Failure.unreachablePreferredRoute + throw URLError(.cannotConnectToHost) } let transport = LivenessTransport(router: router) box.set(transport) diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift index 1ec46081980f..a6f08abd2bed 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustScope.swift @@ -51,11 +51,3 @@ public struct MobileManualHostTrustScope: Equatable, Hashable, Sendable { ].joined(separator: "|") } } - -private extension String { - var mobileManualHostTrustStorageEscaped: String { - self - .replacing("%", with: "%25") - .replacing("|", with: "%7C") - } -} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoredState.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoredState.swift new file mode 100644 index 000000000000..006a17fb497f --- /dev/null +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoredState.swift @@ -0,0 +1,55 @@ +import Foundation + +struct MobileManualHostTrustStoredState { + let persistedExpirations: [String: TimeInterval] + let trustedScopes: [MobileManualHostTrustScope: TimeInterval] + + init(defaults: UserDefaults, key: String, sessionIdentifier: String) { + let persistedExpirations: [String: TimeInterval] + if let raw = defaults.dictionary(forKey: key) { + persistedExpirations = raw.reduce(into: [:]) { result, entry in + if let expiresAt = entry.value as? TimeInterval { + result[entry.key] = expiresAt + } else if let expiresAt = entry.value as? NSNumber { + result[entry.key] = expiresAt.doubleValue + } + } + } else { + persistedExpirations = [:] + } + self.persistedExpirations = persistedExpirations + + let sessionPrefix = sessionIdentifier.mobileManualHostTrustStorageEscaped + "|" + self.trustedScopes = persistedExpirations.reduce(into: [:]) { result, entry in + guard entry.key.hasPrefix(sessionPrefix) else { return } + let components = entry.key.dropFirst(sessionPrefix.count).split( + separator: "|", + omittingEmptySubsequences: false + ) + guard components.count == 3, + let port = Int(components[2]), + let scope = MobileManualHostTrustScope( + host: String(components[1]).mobileManualHostTrustStorageUnescaped, + port: port, + stackUserID: String(components[0]).mobileManualHostTrustStorageUnescaped + ) else { + return + } + result[scope] = entry.value + } + } +} + +extension String { + var mobileManualHostTrustStorageEscaped: String { + self + .replacing("%", with: "%25") + .replacing("|", with: "%7C") + } + + var mobileManualHostTrustStorageUnescaped: String { + self + .replacing("%7C", with: "|") + .replacing("%25", with: "%") + } +} diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift index 761b1dcee585..4a4d4db3ad96 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileManualHostTrustStoring.swift @@ -18,7 +18,10 @@ public protocol MobileManualHostTrustStoring: Sendable { func removeAll() async } +/// Default behavior for trust stores that do not expire approvals themselves. public extension MobileManualHostTrustStoring { + /// Returns no expiry when the store does not own an expiration policy. + /// - Parameter scope: The approved scope to inspect. func expirationDate(for scope: MobileManualHostTrustScope) async -> Date? { _ = scope return nil diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift index a2fe554aaa9a..4f9a3c64874d 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/UserDefaultsMobileManualHostTrustStore.swift @@ -35,12 +35,13 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin self.sessionIdentifier = sessionIdentifier self.trustDuration = trustDuration self.now = now - let persistedExpirations = Self.loadTrustedExpirations(defaults: defaults, key: key) - self.persistedExpirations = persistedExpirations - self.trustedScopes = Self.loadTrustedScopes( - from: persistedExpirations, + let storedState = MobileManualHostTrustStoredState( + defaults: defaults, + key: key, sessionIdentifier: sessionIdentifier ) + self.persistedExpirations = storedState.persistedExpirations + self.trustedScopes = storedState.trustedScopes } /// Creates a same-session manual-host trust store in a named defaults suite. @@ -72,12 +73,13 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin self.sessionIdentifier = sessionIdentifier self.trustDuration = trustDuration self.now = now - let persistedExpirations = Self.loadTrustedExpirations(defaults: resolvedDefaults, key: key) - self.persistedExpirations = persistedExpirations - self.trustedScopes = Self.loadTrustedScopes( - from: persistedExpirations, + let storedState = MobileManualHostTrustStoredState( + defaults: resolvedDefaults, + key: key, sessionIdentifier: sessionIdentifier ) + self.persistedExpirations = storedState.persistedExpirations + self.trustedScopes = storedState.trustedScopes } /// Returns whether the given host/port/account scope is already trusted and unexpired. @@ -125,50 +127,6 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin defaults.removeObject(forKey: key) } - nonisolated private static func loadTrustedExpirations( - defaults: UserDefaults, - key: String - ) -> [String: TimeInterval] { - guard let raw = defaults.dictionary(forKey: key) else { - return [:] - } - var trusted: [String: TimeInterval] = [:] - for (scope, expiresAt) in raw { - if let expiresAt = expiresAt as? TimeInterval { - trusted[scope] = expiresAt - } else if let expiresAt = expiresAt as? NSNumber { - trusted[scope] = expiresAt.doubleValue - } - } - return trusted - } - - nonisolated private static func loadTrustedScopes( - from persistedExpirations: [String: TimeInterval], - sessionIdentifier: String - ) -> [MobileManualHostTrustScope: TimeInterval] { - let sessionPrefix = sessionIdentifier.mobileManualHostTrustStorageEscaped + "|" - var trustedScopes: [MobileManualHostTrustScope: TimeInterval] = [:] - for (storageKey, expiresAt) in persistedExpirations { - guard storageKey.hasPrefix(sessionPrefix) else { continue } - let components = storageKey.dropFirst(sessionPrefix.count).split( - separator: "|", - omittingEmptySubsequences: false - ) - guard components.count == 3, - let port = Int(components[2]), - let scope = MobileManualHostTrustScope( - host: String(components[1]).mobileManualHostTrustStorageUnescaped, - port: port, - stackUserID: String(components[0]).mobileManualHostTrustStorageUnescaped - ) else { - continue - } - trustedScopes[scope] = expiresAt - } - return trustedScopes - } - private func sessionStorageKey(for scope: MobileManualHostTrustScope) -> String { [ sessionIdentifier.mobileManualHostTrustStorageEscaped, @@ -176,17 +134,3 @@ public actor UserDefaultsMobileManualHostTrustStore: MobileManualHostTrustStorin ].joined(separator: "|") } } - -private extension String { - var mobileManualHostTrustStorageEscaped: String { - self - .replacing("%", with: "%25") - .replacing("|", with: "%7C") - } - - var mobileManualHostTrustStorageUnescaped: String { - self - .replacing("%7C", with: "|") - .replacing("%25", with: "%") - } -} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 7734d2e388d4..6db715585fe2 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -142,7 +142,7 @@ struct CMUXMobileRootView: View { store.currentTeamDidChange() } .onChange(of: scenePhase) { _, phase in - switch MobileSceneRefreshAction.forScenePhase(phase) { + switch MobileSceneRefreshAction(scenePhase: phase) { case .none: return case .enterBackground: diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift index 7354d461b7c4..dab447615b3a 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift @@ -5,8 +5,8 @@ enum MobileSceneRefreshAction: Equatable { case enterBackground case resumeForeground - static func forScenePhase(_ phase: ScenePhase) -> Self { - switch phase { + init(scenePhase: ScenePhase) { + self = switch scenePhase { case .active: .resumeForeground case .background: .enterBackground case .inactive: .none diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSceneRefreshActionTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSceneRefreshActionTests.swift index 3407c6ae977a..367f9b5bc242 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSceneRefreshActionTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSceneRefreshActionTests.swift @@ -4,8 +4,8 @@ import Testing @Suite struct MobileSceneRefreshActionTests { @Test func inactiveInterruptionDoesNotBecomeBackgroundTransition() { - #expect(MobileSceneRefreshAction.forScenePhase(.inactive) == .none) - #expect(MobileSceneRefreshAction.forScenePhase(.background) == .enterBackground) - #expect(MobileSceneRefreshAction.forScenePhase(.active) == .resumeForeground) + #expect(MobileSceneRefreshAction(scenePhase: .inactive) == .none) + #expect(MobileSceneRefreshAction(scenePhase: .background) == .enterBackground) + #expect(MobileSceneRefreshAction(scenePhase: .active) == .resumeForeground) } } From b6a8538015570ae4c5715270ae02cb1b90a71528 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 10 Jul 2026 00:12:05 -0700 Subject: [PATCH 80/91] Fix iOS manual host feature fixtures --- .../MobileShellPreviewFactory.swift | 1 + .../MobileShellPreviewIdentityProvider.swift | 7 ++ .../cmuxFeatureTests/cmuxFeatureTests.swift | 119 +++++++++++++----- 3 files changed, 94 insertions(+), 33 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewIdentityProvider.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift index 656f03d0cd8a..810fef2b6b3b 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewFactory.swift @@ -25,6 +25,7 @@ public struct MobileShellPreviewFactory { CMUXMobileShellStore( runtime: runtime, workspaces: PreviewMobileHost.workspaces, + identityProvider: MobileShellPreviewIdentityProvider(), deliveredNotificationClearer: NoopDeliveredNotificationClearer(), manualHostTrustStore: manualHostTrustStore ) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewIdentityProvider.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewIdentityProvider.swift new file mode 100644 index 000000000000..64300d05466c --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellPreviewIdentityProvider.swift @@ -0,0 +1,7 @@ +import CmuxMobileShellModel + +/// Supplies one stable signed-in account scope to preview and package-test shells. +@MainActor +struct MobileShellPreviewIdentityProvider: MobileIdentityProviding { + let currentUserID: String? = "cmux-mobile-shell-preview-user" +} diff --git a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift index 02c8c60e94f6..d014ff7703dd 100644 --- a/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift +++ b/ios/cmuxPackage/Tests/cmuxFeatureTests/cmuxFeatureTests.swift @@ -633,9 +633,9 @@ final class TerminalOutputCollector { } @MainActor -@Test func manualHostPairingUsesNetworkRouteForTailscaleMagicDNSHost() async throws { +@Test func manualHostPairingRequiresApprovalForTailscaleMagicDNSHost() async throws { let attachRoute = try hostPortRoute( - kind: .tailscale, + kind: .manualHost, host: "work-mac.tailnet.ts.net", port: CmxMobileDefaults.defaultHostPort ) @@ -644,23 +644,34 @@ final class TerminalOutputCollector { try rpcWorkspaceListFrame(workspaceID: "live-workspace", title: "Live Workspace"), ]) let runtime = testRuntime( - supportedRouteKinds: [.tailscale], + supportedRouteKinds: [.manualHost], transportFactory: ScriptedTransportFactory(responses: responses) ) let store = CMUXMobileShellStore.preview(runtime: runtime) store.signIn() - await store.connectManualHost(name: "Work Mac", host: "work-mac.tailnet.ts.net", port: CmxMobileDefaults.defaultHostPort) + let firstResult = await store.connectManualHost( + name: "Work Mac", + host: "work-mac.tailnet.ts.net", + port: CmxMobileDefaults.defaultHostPort + ) + + #expect(firstResult == .needsUserApproval) + #expect(store.manualHostTrustWarning?.endpoint == "work-mac.tailnet.ts.net:58465") + #expect(try await responses.sentRequests().isEmpty) + + let approvedResult = await store.acceptManualHostTrustWarning() let route = try #require(store.activeRoute) + #expect(approvedResult == .connected) #expect(store.phase == .workspaces) #expect(store.connectedHostName == "Work Mac") - #expect(route.kind == .tailscale) + #expect(route.kind == .manualHost) if case let .hostPort(host, port) = route.endpoint { #expect(host == "work-mac.tailnet.ts.net") #expect(port == CmxMobileDefaults.defaultHostPort) } else { - Issue.record("manual Tailscale route should use host/port") + Issue.record("approved manual route should use host/port") } } @@ -790,28 +801,40 @@ final class TerminalOutputCollector { } @MainActor -@Test func manualHostPairingProbesTailscaleHostForAttachTicketBeforeStackAuthFallback() async throws { - // A manually-entered Tailscale host is probed for a real attach ticket - // first; an older Mac that does not implement the probe method falls back - // to a synthetic ticket and Stack-authenticated workspace.list. +@Test func manualHostPairingRequiresApprovalBeforeAttachTicketProbe() async throws { + // Host text alone does not prove that the connection traverses Tailscale. + // After explicit approval, an older Mac that does not implement the ticket + // probe falls back to a synthetic ticket and Stack-authenticated workspace.list. let responses = ScriptedTransportResponses([ try rpcErrorFrame(code: "method_not_found", message: "unknown method"), try rpcWorkspaceListFrame(workspaceID: "manual-workspace", title: "Manual Workspace"), ]) let runtime = testRuntime( - supportedRouteKinds: [.tailscale], + supportedRouteKinds: [.manualHost], transportFactory: ScriptedTransportFactory(responses: responses), stackAccessToken: "stack-token-for-fallback" ) let store = CMUXMobileShellStore.preview(runtime: runtime) store.signIn() - await store.connectManualHost(name: "Work Mac", host: "100.71.210.41", port: 15432) + let firstResult = await store.connectManualHost( + name: "Work Mac", + host: "100.71.210.41", + port: 15432 + ) + + #expect(firstResult == .needsUserApproval) + #expect(store.manualHostTrustWarning?.endpoint == "100.71.210.41:15432") + #expect(try await responses.sentRequests().isEmpty) + let approvedResult = await store.acceptManualHostTrustWarning() + + #expect(approvedResult == .connected) #expect(store.phase == .workspaces) #expect(store.connectionState == .connected) #expect(store.connectionError == nil) #expect(store.connectedHostName == "Work Mac") + #expect(store.activeRoute?.kind == .manualHost) let requests = try await responses.sentRequests() #expect(requests.map(\.method) == ["mobile.attach_ticket.create", "workspace.list"]) #expect(requests.allSatisfy { $0.stackAccessToken == "stack-token-for-fallback" }) @@ -819,23 +842,24 @@ final class TerminalOutputCollector { } @MainActor -@Test func manualHostPairingTimesOutWrongHostWithoutStayingConnected() async throws { - let route = try CmxAttachRoute( - id: "tailscale", - kind: .tailscale, - endpoint: .hostPort(host: "work-mac.tailnet.ts.net", port: CmxMobileDefaults.defaultHostPort) - ) +@Test func approvedManualHostPairingTimesOutWrongHostWithoutStayingConnected() async throws { let runtime = testRuntime( - supportedRouteKinds: [.tailscale], + supportedRouteKinds: [.manualHost], transportFactory: HangingTransportFactory(), pairingRequestTimeoutNanoseconds: 1_000_000 ) let store = CMUXMobileShellStore.preview(runtime: runtime) store.signIn() - await store.connectManualHost(name: "Slow Mac", host: "work-mac.tailnet.ts.net", port: CmxMobileDefaults.defaultHostPort) + let firstResult = await store.connectManualHost( + name: "Slow Mac", + host: "work-mac.tailnet.ts.net", + port: CmxMobileDefaults.defaultHostPort + ) + let approvedResult = await store.acceptManualHostTrustWarning() - #expect(route.kind == .tailscale) + #expect(firstResult == .needsUserApproval) + #expect(approvedResult == .failed) #expect(store.phase == .pairing) #expect(store.connectionState == .disconnected) // A handshake timeout to a Tailscale host now points the user at the real @@ -853,17 +877,31 @@ final class TerminalOutputCollector { // the per-route timeouts into the opaque ~60s wait the reporter saw. let dials = TransportDialRecorder() let runtime = testRuntime( - supportedRouteKinds: [.tailscale], + supportedRouteKinds: [.manualHost], transportFactory: RecordingNeverConnectTransportFactory(dials: dials) ) let store = CMUXMobileShellStore( runtime: runtime, - reachability: OfflineReachability() + identityProvider: TestIdentityProvider( + currentUserIDValue: "feature-test-user", + currentUserEmailValue: nil + ), + reachability: OfflineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() ) store.signIn() - await store.connectManualHost(name: "Work Mac", host: "work-mac.tailnet.ts.net", port: CmxMobileDefaults.defaultHostPort) + let firstResult = await store.connectManualHost( + name: "Work Mac", + host: "work-mac.tailnet.ts.net", + port: CmxMobileDefaults.defaultHostPort + ) + #expect(firstResult == .needsUserApproval) + #expect(dials.count == 0) + + let approvedResult = await store.acceptManualHostTrustWarning() + #expect(approvedResult == .failed) #expect(store.phase == .pairing) #expect(store.connectionState == .disconnected) // Non-empty, offline-specific headline: the spinner can no longer revert @@ -1022,6 +1060,10 @@ final class TerminalOutputCollector { ) let store = CMUXMobileShellStore( runtime: runtime, + identityProvider: TestIdentityProvider( + currentUserIDValue: "feature-test-user", + currentUserEmailValue: nil + ), reachability: OfflineReachability() ) @@ -1965,7 +2007,7 @@ final class TerminalOutputCollector { #expect(firstResult == .needsUserApproval) #expect(secondResult == .failed) - #expect(staleApprovalResult == .failed) + #expect(staleApprovalResult == .superseded) #expect(store.manualHostTrustWarning == nil) #expect(store.connectionState == .disconnected) #expect(try await responses.sentRequests().isEmpty) @@ -1992,7 +2034,7 @@ final class TerminalOutputCollector { let staleApprovalResult = await store.acceptManualHostTrustWarning() #expect(firstResult == .needsUserApproval) - #expect(staleApprovalResult == .failed) + #expect(staleApprovalResult == .superseded) #expect(store.manualHostTrustWarning == nil) #expect(store.connectionState == .disconnected) #expect(try await responses.sentRequests().isEmpty) @@ -2019,7 +2061,7 @@ final class TerminalOutputCollector { let staleApprovalResult = await store.acceptManualHostTrustWarning() #expect(firstResult == .needsUserApproval) - #expect(staleApprovalResult == .failed) + #expect(staleApprovalResult == .superseded) #expect(store.manualHostTrustWarning == nil) #expect(try await responses.sentRequests().isEmpty) } @@ -2105,9 +2147,9 @@ final class TerminalOutputCollector { } @MainActor -@Test func manualHostPairingUsesNetworkRouteForTailscaleIP() async throws { +@Test func manualHostPairingRequiresApprovalForTailscaleIP() async throws { let attachRoute = try hostPortRoute( - kind: .tailscale, + kind: .manualHost, host: "100.71.210.41", port: CmxMobileDefaults.defaultHostPort ) @@ -2116,26 +2158,37 @@ final class TerminalOutputCollector { try rpcWorkspaceListFrame(workspaceID: "tailscale-ip-workspace", title: "Tailscale IP Workspace"), ]) let runtime = testRuntime( - supportedRouteKinds: [.tailscale], + supportedRouteKinds: [.manualHost], transportFactory: ScriptedTransportFactory(responses: responses), stackAccessToken: "stack-token-for-tailscale-ip" ) let store = CMUXMobileShellStore.preview(runtime: runtime) store.signIn() - await store.connectManualHost(name: "Work Mac", host: "100.71.210.41", port: CmxMobileDefaults.defaultHostPort) + let firstResult = await store.connectManualHost( + name: "Work Mac", + host: "100.71.210.41", + port: CmxMobileDefaults.defaultHostPort + ) + + #expect(firstResult == .needsUserApproval) + #expect(store.manualHostTrustWarning?.endpoint == "100.71.210.41:58465") + #expect(try await responses.sentRequests().isEmpty) + + let approvedResult = await store.acceptManualHostTrustWarning() let route = try #require(store.activeRoute) + #expect(approvedResult == .connected) #expect(store.phase == .workspaces) #expect(store.connectionState == .connected) #expect(store.connectionError == nil) #expect(store.connectedHostName == "Work Mac") - #expect(route.kind == .tailscale) + #expect(route.kind == .manualHost) if case let .hostPort(host, port) = route.endpoint { #expect(host == "100.71.210.41") #expect(port == CmxMobileDefaults.defaultHostPort) } else { - Issue.record("manual Tailscale IP route should use host/port") + Issue.record("approved manual IP route should use host/port") } let attachTicketRequest = try #require(try await responses.sentRequests().first { $0.method == "mobile.attach_ticket.create" }) #expect(attachTicketRequest.stackAccessToken == "stack-token-for-tailscale-ip") From d2c16ecb14f7350e428734e5ee030982e72d6d0c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 10 Jul 2026 00:30:40 -0700 Subject: [PATCH 81/91] test(ios): cover pairing cancellation commit races --- ...CancellationPreservesForegroundTests.swift | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift index 1cf0ed92d612..e2f5f64683f5 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift @@ -1,3 +1,6 @@ +import CMUXMobileCore +import CmuxMobilePairedMac +import CmuxMobileRPC import CmuxMobileShellModel import Foundation import Testing @@ -35,4 +38,109 @@ import Testing #expect(store.connectionState == .connected) #expect(store.remoteClient === originalClient) } + + @Test func cancelPairingBeforeAuthorizedResponseKeepsExistingConnection() async throws { + let clock = TestClock() + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let newRouter = LivenessHostRouter() + let newBox = TransportBox() + let tokenProvider = BlockingAccountSwitchTokenProvider() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: newRouter, box: newBox), + stackAccessTokenProvider: { try await tokenProvider.tokenIgnoringCancellation() }, + now: { clock.now }, + supportedRouteKinds: [.tailscale], + supportsServerPushEvents: false + ) + let store = makeConnectedStore(runtime: runtime) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + let originalClient = try #require(store.remoteClient) + + let pairing = Task { @MainActor in + await store.connectPairingURLResult("cmux-ios://attach?v=2&pc=1&r=100.64.0.5:58465") + } + await tokenProvider.waitUntilRequested() + store.cancelPairing() + await tokenProvider.release(with: "authorized-token") + let result = await pairing.value + + #expect(result == .superseded) + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + } + + @Test func cancelPairingDuringPairedMacLookupDoesNotActivateCandidate() async throws { + let clock = TestClock() + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let newRouter = LivenessHostRouter() + let newBox = TransportBox() + let oldRoute = try CmxAttachRoute( + id: "old-loopback", + kind: .debugLoopback, + endpoint: .hostPort(host: "127.0.0.1", port: 56_583) + ) + let pairedMacStore = DelayedTeamPairedMacStore( + recordsByTeam: [ + "team-a": [ + MobilePairedMac( + macDeviceID: "old-mac", + displayName: "Old Mac", + routes: [oldRoute], + createdAt: clock.now, + lastSeenAt: clock.now, + isActive: true, + stackUserID: "test-user", + teamID: "team-a" + ), + ], + ], + blockedTeams: ["team-a"] + ) + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: newRouter, box: newBox), + now: { clock.now }, + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + isSignedIn: true, + connectionState: .connected, + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "test-user"), + teamIDProvider: { "team-a" }, + reachability: AlwaysOnlineReachability(), + pairingHintDefaults: UserDefaults(suiteName: "pairing-cancel-persistence-\(UUID().uuidString)")! + ) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + store.setWorkspaceStatesForTesting([:], foregroundMacDeviceID: "old-mac") + let originalClient = try #require(store.remoteClient) + let ticket = try makeTicket(clock: clock) + let url = try attachURL(for: ticket) + + let pairing = Task { @MainActor in + await store.connectPairingURLResult(url) + } + await pairedMacStore.waitUntilLoadStarted(teamID: "team-a") + store.cancelPairing() + await pairedMacStore.release(teamID: "team-a") + let result = await pairing.value + + #expect(result == .superseded) + #expect(await pairedMacStore.currentUpsertCount() == 0) + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + } + + private func makeConnectedStore(runtime: any MobileSyncRuntime) -> MobileShellComposite { + MobileShellComposite( + runtime: runtime, + isSignedIn: true, + connectionState: .connected, + identityProvider: StaticIdentityProvider(userID: "test-user"), + reachability: AlwaysOnlineReachability(), + pairingHintDefaults: UserDefaults(suiteName: "pairing-cancel-\(UUID().uuidString)")! + ) + } } From c9c85019164ca201e9f5be62ed8e628dfa1a923f Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 10 Jul 2026 00:33:29 -0700 Subject: [PATCH 82/91] fix(ios): bind pairing commits to attempt ownership --- .../MobileShellComposite.swift | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 765358b591a3..662f97893aee 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -1102,7 +1102,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { invalidatePairingAttempt() clearMacSwitchAttemptState() connectionGeneration = UUID() - connectionAttemptGeneration = UUID() isSignedIn = false connectionState = .disconnected macConnectionStatus = .unavailable @@ -1619,7 +1618,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) }, pairedMacDeviceID: pairedMacDeviceID, - ifStillCurrent: ifStillCurrent + ifStillCurrent: { + self.isCurrentPairingAttempt(attemptID) + && (ifStillCurrent?() ?? true) + } ) guard isCurrentPairingAttempt(attemptID) else { return .superseded } if noThrowFailure == nil, connectionState == .connected { @@ -2877,6 +2879,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { let routesToPersist = ticket.routes.count == 1 && !storedRoutes.isEmpty ? Self.mergedReconnectRoutes(ticketRoutes: ticket.routes, storedRoutes: storedRoutes) : ticket.routes + if let scope { + guard await self.isScopeCurrent(scope) else { return } + } + guard ifStillCurrent?() != false else { return } do { try await pairedMacStore.upsert( macDeviceID: ticket.macDeviceID, @@ -2887,6 +2893,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { teamID: scope?.teamID, now: Date() ) + guard ifStillCurrent?() != false else { return } + if let scope { + guard await self.isScopeCurrent(scope) else { return } + } await self.clearForgottenMacDeviceID(ticket.macDeviceID, scope: scope) // A real, reconnectable Mac is now the active paired Mac: record // the persisted hint so the next launch shows RestoringSessionView @@ -3196,7 +3206,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { rawURL: rawURL, acceptedVersionWarning: acceptedVersionWarning, approvedRouteID: approvedManualRouteID - ) + ), + ifStillCurrent: { self.isCurrentPairingAttempt(attemptID) } ) guard isCurrentPairingAttempt(attemptID) else { return .superseded } if noThrowFailure == nil, connectionState == .connected && activeTicket != nil { @@ -3267,7 +3278,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { macSwitchAttemptID = nil macSwitchAttemptSignInGeneration = nil invalidatePairingAttempt() - connectionAttemptGeneration = UUID() if let restoreTarget { return Task { @MainActor [weak self] in guard let self else { return false } @@ -5418,7 +5428,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { macSwitchRestoreBaseline = nil } invalidatePairingAttempt() - connectionAttemptGeneration = UUID() return attemptID } @@ -5445,7 +5454,6 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { macSwitchRestoreBaseline = nil if invalidateUnderlyingConnectionAttempt { invalidatePairingAttempt() - connectionAttemptGeneration = UUID() } } @@ -5470,11 +5478,13 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// Invalidate the in-flight attempt outside ``beginPairingAttempt(method:)`` /// (cancel, sign-out, live-connection teardown), dropping its instrumentation - /// so a stale attempt can never emit `ios_pairing_*` via a later auth eviction. + /// and rotating the inner connection generation so no stale attempt can + /// commit a replacement client or emit `ios_pairing_*` later. func invalidatePairingAttempt() { pairingAttemptID = UUID() pairingAttemptStartedAt = nil pairingAttemptMethod = nil + connectionAttemptGeneration = UUID() } /// Apply a classified pairing failure to the user-visible error surface and From 83c6e69e8f345c3eff9a5a37a3d145f318186d9c Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Fri, 10 Jul 2026 00:35:23 -0700 Subject: [PATCH 83/91] Address final iOS review feedback --- .../MobileCoreRPCRequestQueueTests.swift | 30 +++++++++++-------- .../MobileSceneRefreshAction.swift | 2 +- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift index cf5f4bbf2de8..58e1d75c1d82 100644 --- a/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift +++ b/Packages/iOS/CmuxMobileRPC/Tests/CmuxMobileRPCTests/MobileCoreRPCRequestQueueTests.swift @@ -29,10 +29,7 @@ import Testing sendAuthorizer: { await authorizationRecorder.authorize() } ) } - for _ in 0..<200 where !(await session.queuedRequestIDs.contains(cancelledID)) { - await Task.yield() - } - #expect(await session.queuedRequestIDs.contains(cancelledID)) + #expect(await waitUntilQueued(cancelledID, in: session)) cancelled.cancel() do { _ = try await cancelled.value @@ -49,10 +46,7 @@ import Testing deadlineUptimeNanoseconds: deadline ) } - for _ in 0..<200 where !(await session.queuedRequestIDs.contains(liveID)) { - await Task.yield() - } - #expect(await session.queuedRequestIDs.contains(liveID)) + #expect(await waitUntilQueued(liveID, in: session)) await transport.releaseFirstSend() #expect(try await transport.waitForSentRequestCount(2).map(\.id) == [firstID, liveID]) @@ -87,10 +81,7 @@ import Testing sendAuthorizer: { throw CancellationError() } ) } - for _ in 0..<200 where !(await session.queuedRequestIDs.contains(revokedID)) { - await Task.yield() - } - #expect(await session.queuedRequestIDs.contains(revokedID)) + #expect(await waitUntilQueued(revokedID, in: session)) await transport.releaseFirstSend() do { @@ -300,4 +291,19 @@ import Testing } } + private func waitUntilQueued( + _ requestID: String, + in session: MobileCoreRPCSession + ) async -> Bool { + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: .seconds(1)) + while clock.now < deadline { + if await session.queuedRequestIDs.contains(requestID) { + return true + } + await Task.yield() + } + return await session.queuedRequestIDs.contains(requestID) + } + } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift index dab447615b3a..e34c45bbbdad 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSceneRefreshAction.swift @@ -1,6 +1,6 @@ import SwiftUI -enum MobileSceneRefreshAction: Equatable { +nonisolated enum MobileSceneRefreshAction: Equatable { case none case enterBackground case resumeForeground From fb3fd5e0813b57b9ffa026485301ceaf052e77fc Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 14 Jul 2026 15:24:22 -0700 Subject: [PATCH 84/91] test(ios): cover final trust lifecycle races --- ...alHostTrustExpirationSchedulingTests.swift | 77 ++++++++++++++++++ ...CancellationPreservesForegroundTests.swift | 67 ++++++++++++++++ ...imaryRouteAuthorizationFallbackTests.swift | 79 +++++++++++++++++++ 3 files changed, 223 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift new file mode 100644 index 000000000000..fc98bafc8a79 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift @@ -0,0 +1,77 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct ManualHostTrustExpirationSchedulingTests { + @Test func repeatedHealthSchedulingKeepsOneExpirationLookup() async throws { + let router = LivenessHostRouter() + let trustStore = CountingExpirationManualHostTrustStore() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { Date() }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: trustStore + ) + store.signIn() + + let queued = await store.connectManualHost( + name: "Studio Mac", + host: "192.168.1.77", + port: 58_465 + ) + let connected = await store.acceptManualHostTrustWarning() + let armed = try await pollUntil { + await trustStore.expirationQueryCount() >= 1 + } + + #expect(queued == .needsUserApproval) + #expect(connected == .connected) + #expect(armed) + let initialQueries = await trustStore.expirationQueryCount() + + for _ in 0..<20 { + store.scheduleManualHostTrustExpirationForActiveRoute() + } + let rearmed = try await pollUntil(attempts: 30) { + await trustStore.expirationQueryCount() > initialQueries + } + + #expect(!rearmed) + } +} + +private actor CountingExpirationManualHostTrustStore: MobileManualHostTrustStoring { + private var scopes: Set = [] + private var expirationQueries = 0 + + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + scopes.contains(scope) + } + + func trust(_ scope: MobileManualHostTrustScope) async { + scopes.insert(scope) + } + + func expirationDate(for scope: MobileManualHostTrustScope) async -> Date? { + guard scopes.contains(scope) else { return nil } + expirationQueries += 1 + return Date().addingTimeInterval(3_600) + } + + func removeAll() async { + scopes.removeAll() + } + + func expirationQueryCount() -> Int { + expirationQueries + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift index e2f5f64683f5..84acb3ab1b08 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobilePairingCancellationPreservesForegroundTests.swift @@ -133,6 +133,73 @@ import Testing #expect(store.remoteClient === originalClient) } + @Test func cancelPairingDuringPairedMacUpsertKeepsPreviousMacActive() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let innerStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let clock = TestClock() + let oldRoute = try CmxAttachRoute( + id: "old-loopback", + kind: .debugLoopback, + endpoint: .hostPort(host: "127.0.0.1", port: 56_583) + ) + try await innerStore.upsert( + macDeviceID: "old-mac", + displayName: "Old Mac", + routes: [oldRoute], + markActive: true, + stackUserID: "test-user", + teamID: nil, + now: clock.now + ) + let gatedStore = GatedUpsertStore(inner: innerStore) + let oldRouter = LivenessHostRouter() + let oldBox = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory( + router: LivenessHostRouter(), + box: TransportBox() + ), + now: { clock.now }, + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + isSignedIn: true, + connectionState: .connected, + pairedMacStore: gatedStore, + identityProvider: StaticIdentityProvider(userID: "test-user"), + reachability: AlwaysOnlineReachability(), + pairingHintDefaults: UserDefaults(suiteName: "pairing-cancel-upsert-\(UUID().uuidString)")! + ) + try installFreshLivenessRemoteClient(on: store, router: oldRouter, box: oldBox, clock: clock) + store.setWorkspaceStatesForTesting([:], foregroundMacDeviceID: "old-mac") + let originalClient = try #require(store.remoteClient) + let ticket = try makeTicket(clock: clock) + let url = try attachURL(for: ticket) + + let pairing = Task { @MainActor in + await store.connectPairingURLResult(url) + } + await gatedStore.waitUntilUpsertEntered() + store.cancelPairing() + await gatedStore.release() + let result = await pairing.value + let activeMac = try await gatedStore.activeMac( + stackUserID: "test-user", + teamID: nil + ) + + #expect(result == .superseded) + #expect(activeMac?.macDeviceID == "old-mac") + #expect(store.connectionState == .connected) + #expect(store.remoteClient === originalClient) + } + private func makeConnectedStore(runtime: any MobileSyncRuntime) -> MobileShellComposite { MobileShellComposite( runtime: runtime, diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift new file mode 100644 index 000000000000..eb4ab7586b06 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift @@ -0,0 +1,79 @@ +import CMUXMobileCore +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct PrimaryRouteAuthorizationFallbackTests { + @Test func authorizationFailureDoesNotFallBackToTrustedManualHost() async throws { + let tailscaleRoute = try CmxAttachRoute( + id: "preferred-tailscale", + kind: .tailscale, + endpoint: .hostPort(host: "100.82.214.112", port: 50_922), + priority: 0 + ) + let manualRoute = try CmxAttachRoute( + id: "approved-manual-host", + kind: .manualHost, + endpoint: .hostPort(host: "192.168.1.77", port: 50_923), + priority: 10 + ) + let ticket = try CmxAttachTicket( + workspaceID: "candidate-workspace", + terminalID: nil, + macDeviceID: "candidate-mac", + macDisplayName: "Candidate Mac", + macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, + routes: [tailscaleRoute, manualRoute], + expiresAt: Date().addingTimeInterval(3_600) + ) + let trustStore = InMemoryMobileManualHostTrustStore() + let manualScope = try #require( + MobileManualHostTrustScope(route: manualRoute, stackUserID: "phone-user") + ) + await trustStore.trust(manualScope) + let attempts = RouteAttemptRecorder() + let runtime = LivenessTestRuntime( + transportFactory: AuthorizationThenManualFallbackTransportFactory( + router: LivenessHostRouter(), + box: TransportBox(), + attempts: attempts + ), + now: { Date() }, + supportedRouteKinds: [.tailscale, .manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: trustStore + ) + store.signIn() + + let result = await store.connectPairingURLResult(try attachURL(for: ticket)) + + #expect(result == .failed) + #expect(attempts.count(.tailscale) == 2) + #expect(attempts.count(.manualHost) == 0) + #expect(store.remoteClient == nil) + #expect(store.manualHostTrustWarning == nil) + } +} + +private struct AuthorizationThenManualFallbackTransportFactory: CmxByteTransportFactory { + let router: LivenessHostRouter + let box: TransportBox + let attempts: RouteAttemptRecorder + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + attempts.record(route.kind) + if route.kind == .tailscale { + return AuthorizationFailingTransport() + } + let transport = LivenessTransport(router: router) + box.set(transport) + return transport + } +} From 84cdc180d02936cb3f9941755878ac5d36c388ea Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 14 Jul 2026 15:47:56 -0700 Subject: [PATCH 85/91] fix(ios): close final trust ownership gaps --- .../ManualHostTrustExpirationOwner.swift | 21 +++++++ ...MobileShellComposite+ManualHostTrust.swift | 60 +++++++++---------- .../MobileShellComposite+Scope.swift | 6 +- .../MobileShellComposite.swift | 43 +++++++++---- 4 files changed, 82 insertions(+), 48 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/ManualHostTrustExpirationOwner.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/ManualHostTrustExpirationOwner.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/ManualHostTrustExpirationOwner.swift new file mode 100644 index 000000000000..8d10126e6212 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/ManualHostTrustExpirationOwner.swift @@ -0,0 +1,21 @@ +import CMUXMobileCore +import CmuxMobileRPC +import CmuxMobileShellModel +import Foundation + +/// Identifies the foreground connection that owns one manual-host trust deadline. +struct ManualHostTrustExpirationOwner: Equatable { + let scope: MobileManualHostTrustScope + let route: CmxAttachRoute + let client: MobileCoreRPCClient + let generation: UUID + let authScope: MobileRPCAuthScope + + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.scope == rhs.scope + && lhs.route == rhs.route + && lhs.client === rhs.client + && lhs.generation == rhs.generation + && lhs.authScope == rhs.authScope + } +} diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift index 9c07b28c57a8..269eb08dc4c9 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ManualHostTrust.swift @@ -213,59 +213,55 @@ extension MobileShellComposite { return await manualHostTrustStore.isTrusted(scope) } - func scheduleManualHostTrustExpirationForActiveRoute() { + func cancelManualHostTrustExpiration() { manualHostTrustExpirationTask?.cancel() manualHostTrustExpirationTask = nil + manualHostTrustExpirationOwner = nil + } + + func scheduleManualHostTrustExpirationForActiveRoute() { guard let route = activeRoute, let client = remoteClient, connectionState == .connected, - let scope = manualHostTrustScope(for: route) else { return } - let authScope = manualHostRPCAuthScope - let generation = connectionGeneration + let scope = manualHostTrustScope(for: route) else { + cancelManualHostTrustExpiration() + return + } + let owner = ManualHostTrustExpirationOwner( + scope: scope, + route: route, + client: client, + generation: connectionGeneration, + authScope: manualHostRPCAuthScope + ) + guard manualHostTrustExpirationOwner != owner else { return } + cancelManualHostTrustExpiration() + manualHostTrustExpirationOwner = owner let trustStore = manualHostTrustStore manualHostTrustExpirationTask = Task { @MainActor [weak self] in guard let expiration = await trustStore.expirationDate(for: scope), let self, - self.manualHostTrustExpirationIsCurrent( - route: route, - client: client, - generation: generation, - authScope: authScope - ) else { return } + self.manualHostTrustExpirationIsCurrent(owner) else { return } let delay = expiration.timeIntervalSince(self.runtime?.now() ?? Date()) if delay > 0 { try? await ContinuousClock().sleep(for: .seconds(delay)) } guard !Task.isCancelled, - self.manualHostTrustExpirationIsCurrent( - route: route, - client: client, - generation: generation, - authScope: authScope - ), + self.manualHostTrustExpirationIsCurrent(owner), !(await trustStore.isTrusted(scope)), - self.manualHostTrustExpirationIsCurrent( - route: route, - client: client, - generation: generation, - authScope: authScope - ) else { return } + self.manualHostTrustExpirationIsCurrent(owner) else { return } self.rotateManualHostRPCAuthScope() _ = self.queueForegroundManualHostReapproval(route: route) } } - private func manualHostTrustExpirationIsCurrent( - route: CmxAttachRoute, - client: MobileCoreRPCClient, - generation: UUID, - authScope: MobileRPCAuthScope - ) -> Bool { + private func manualHostTrustExpirationIsCurrent(_ owner: ManualHostTrustExpirationOwner) -> Bool { connectionState == .connected - && remoteClient === client - && connectionGeneration == generation - && activeRoute == route - && manualHostRPCAuthScope == authScope + && manualHostTrustExpirationOwner == owner + && remoteClient === owner.client + && connectionGeneration == owner.generation + && activeRoute == owner.route + && manualHostRPCAuthScope == owner.authScope } func scheduleManualHostTrustExpirationForSecondarySubscription( diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift index 87b0643c7daf..363b3401772a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+Scope.swift @@ -18,8 +18,7 @@ extension MobileShellComposite { } func rotateRPCAuthScope() { - manualHostTrustExpirationTask?.cancel() - manualHostTrustExpirationTask = nil + cancelManualHostTrustExpiration() let invalidatedScopes = [rpcAuthScope, manualHostRPCAuthScope] for scope in invalidatedScopes { scope.revoke() } rpcAuthScope = MobileRPCAuthScope() @@ -36,8 +35,7 @@ extension MobileShellComposite { /// Invalidates only plaintext manual-host credentials after a network-path change. func rotateManualHostRPCAuthScope() { - manualHostTrustExpirationTask?.cancel() - manualHostTrustExpirationTask = nil + cancelManualHostTrustExpiration() let invalidatedScope = manualHostRPCAuthScope invalidatedScope.revoke() manualHostRPCAuthScope = MobileRPCAuthScope() diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 662f97893aee..9f2aafd4b19d 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -635,6 +635,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { var manualHostRPCAuthScope = MobileRPCAuthScope() var manualHostTrustResetTask: Task? var manualHostTrustExpirationTask: Task? + var manualHostTrustExpirationOwner: ManualHostTrustExpirationOwner? var manualHostTrustResetGeneration = 0 var rpcAuthStackUserID: String? /// Collapses connection-state edges into one-per-outage lost/recovered events. @@ -2826,21 +2827,23 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// /// The write runs on the serialized paired-Mac chain. The status-driven /// identity adoption passes `ifStillCurrent` so a stale reply cannot - /// commit `markActive: true` for an old Mac after the user has started - /// pairing a new one; the connect path leaves it `nil` (its write is for - /// the connection it just established). + /// commit for an old Mac after the user has started pairing a new one. + /// The connect path stages the record inactive while the attempt can still + /// suspend, then marks it active only after installing the foreground client. private func persistPairedMacFromTicket( _ ticket: CmxAttachTicket, + markActive: Bool = true, ifStillCurrent: (() -> Bool)? = nil - ) async { - guard let pairedMacStore else { return } - guard !ticket.macDeviceID.isEmpty else { return } + ) async -> (didPersist: Bool, scope: MobileShellScopeSnapshot?) { + guard let pairedMacStore else { return (false, nil) } + guard !ticket.macDeviceID.isEmpty else { return (false, nil) } // Strip routes that we can't reconnect to without server-side state // (manual-workspace routes have no real macDeviceID and aren't useful). guard ticket.macDeviceID != "manual-ticket-request", - !ticket.macDeviceID.hasPrefix("manual-") else { return } + !ticket.macDeviceID.hasPrefix("manual-") else { return (false, nil) } let stackUserID = identityProvider?.currentUserID let scope = await currentScopeSnapshot(userID: stackUserID) + var didPersist = false // The compact pairing QR carries no display name; the name arrives // post-handshake via `mobile.host.status`. Until it does, keep any // name we already know for this Mac instead of clobbering it with @@ -2888,7 +2891,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { macDeviceID: ticket.macDeviceID, displayName: displayName, routes: routesToPersist, - markActive: true, + markActive: markActive, stackUserID: stackUserID, teamID: scope?.teamID, now: Date() @@ -2902,10 +2905,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // the persisted hint so the next launch shows RestoringSessionView // during the reconnect window instead of the empty add-device sheet. self.hasKnownPairedMac = true + didPersist = true } catch { mobileShellLog.error("paired mac store upsert failed: \(String(describing: error), privacy: .public)") } } + return (didPersist, scope) } /// Recovers the Mac's identity for a connection whose ticket arrived @@ -3001,7 +3006,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // The connection is now attributable to a real Mac: persist it so // reconnect-on-launch and the host switcher have a record (the // empty-id ticket was skipped by the connect-time persist). - await persistPairedMacFromTicket( + _ = await persistPairedMacFromTicket( adopted, ifStillCurrent: { [weak self] in self?.remoteClient === client } ) @@ -5004,7 +5009,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) let response = try MobileSyncWorkspaceListResponse.decode(resultData) guard isConnectCurrent() else { return nil } - await persistPairedMacFromTicket(ticket, ifStillCurrent: isConnectCurrent) + let persistedPairing = await persistPairedMacFromTicket( + ticket, + markActive: false, + ifStillCurrent: isConnectCurrent + ) guard isConnectCurrent() else { return nil } if preservesActiveConnection { connectionGeneration = generation @@ -5057,6 +5066,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { generation: generation ) } + if persistedPairing.didPersist, + let activeWrite = enqueueActivePairedMacWrite( + macDeviceID: ticket.macDeviceID, + scope: persistedPairing.scope, + reloadAfterWrite: false + ) { + await activeWrite.value + } return nil } catch { lastError = error @@ -5065,6 +5082,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { mobileShellLog.error( "pairing route failed kind=\(route.kind.rawValue, privacy: .public) endpoint=\(route.endpoint.logDescription, privacy: .private) scoped=\(workspaceListRequest.isScoped ? 1 : 0, privacy: .public): \(String(describing: error), privacy: .private)" ) + if MobilePairingFailureCategory.classify(error: error, route: route).isAuthorizationFailure { + throw MobileShellRoutedConnectionError(underlying: error, route: route) + } } } } @@ -5198,8 +5218,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } private func clearActiveConnectionContext() { - manualHostTrustExpirationTask?.cancel() - manualHostTrustExpirationTask = nil + cancelManualHostTrustExpiration() activeTicket = nil activeRoute = nil connectedHostName = "" From 693b4afa35cad239f744324ff49eb805802b0d00 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Tue, 14 Jul 2026 18:08:16 -0700 Subject: [PATCH 86/91] refactor(ios): split trust lifecycle fixtures --- ...onThenManualFallbackTransportFactory.swift | 17 +++++++++++ ...untingExpirationManualHostTrustStore.swift | 29 +++++++++++++++++++ ...alHostTrustExpirationSchedulingTests.swift | 27 ----------------- ...imaryRouteAuthorizationFallbackTests.swift | 16 ---------- 4 files changed, 46 insertions(+), 43 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationThenManualFallbackTransportFactory.swift create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/CountingExpirationManualHostTrustStore.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationThenManualFallbackTransportFactory.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationThenManualFallbackTransportFactory.swift new file mode 100644 index 000000000000..252d5f93777c --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/AuthorizationThenManualFallbackTransportFactory.swift @@ -0,0 +1,17 @@ +import CMUXMobileCore + +struct AuthorizationThenManualFallbackTransportFactory: CmxByteTransportFactory { + let router: LivenessHostRouter + let box: TransportBox + let attempts: RouteAttemptRecorder + + func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { + attempts.record(route.kind) + if route.kind == .tailscale { + return AuthorizationFailingTransport() + } + let transport = LivenessTransport(router: router) + box.set(transport) + return transport + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/CountingExpirationManualHostTrustStore.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/CountingExpirationManualHostTrustStore.swift new file mode 100644 index 000000000000..ec7f0c361743 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/CountingExpirationManualHostTrustStore.swift @@ -0,0 +1,29 @@ +import CmuxMobileShellModel +import Foundation + +actor CountingExpirationManualHostTrustStore: MobileManualHostTrustStoring { + private var scopes: Set = [] + private var expirationQueries = 0 + + func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { + scopes.contains(scope) + } + + func trust(_ scope: MobileManualHostTrustScope) async { + scopes.insert(scope) + } + + func expirationDate(for scope: MobileManualHostTrustScope) async -> Date? { + guard scopes.contains(scope) else { return nil } + expirationQueries += 1 + return Date().addingTimeInterval(3_600) + } + + func removeAll() async { + scopes.removeAll() + } + + func expirationQueryCount() -> Int { + expirationQueries + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift index fc98bafc8a79..afbd91c7c95e 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift @@ -48,30 +48,3 @@ import Testing #expect(!rearmed) } } - -private actor CountingExpirationManualHostTrustStore: MobileManualHostTrustStoring { - private var scopes: Set = [] - private var expirationQueries = 0 - - func isTrusted(_ scope: MobileManualHostTrustScope) async -> Bool { - scopes.contains(scope) - } - - func trust(_ scope: MobileManualHostTrustScope) async { - scopes.insert(scope) - } - - func expirationDate(for scope: MobileManualHostTrustScope) async -> Date? { - guard scopes.contains(scope) else { return nil } - expirationQueries += 1 - return Date().addingTimeInterval(3_600) - } - - func removeAll() async { - scopes.removeAll() - } - - func expirationQueryCount() -> Int { - expirationQueries - } -} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift index eb4ab7586b06..846af02bba72 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift @@ -61,19 +61,3 @@ import Testing #expect(store.manualHostTrustWarning == nil) } } - -private struct AuthorizationThenManualFallbackTransportFactory: CmxByteTransportFactory { - let router: LivenessHostRouter - let box: TransportBox - let attempts: RouteAttemptRecorder - - func makeTransport(for route: CmxAttachRoute) throws -> any CmxByteTransport { - attempts.record(route.kind) - if route.kind == .tailscale { - return AuthorizationFailingTransport() - } - let transport = LivenessTransport(router: router) - box.set(transport) - return transport - } -} From 7483ec45b636bdf2090c45cfc7bb599f326438fb Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 16 Jul 2026 11:56:05 -0700 Subject: [PATCH 87/91] Address review policy findings: DocC, file-scope helper, TestClock in tests - Add DocC to CmxIrohTCPFirstActivation.start and MobileShellComposite.connectionError - Move stringParamSelection to a file-scope private func per package-design policy - Use injected TestClock instead of wall clock in the two new time-driven test suites Co-Authored-By: Claude Fable 5 --- .../CmxIrohTCPFirstActivation.swift | 7 ++++ ...leCoreRPCClient+RequestAuthorization.swift | 37 ++++++++++--------- .../MobileShellComposite.swift | 2 + ...alHostTrustExpirationSchedulingTests.swift | 3 +- ...imaryRouteAuthorizationFallbackTests.swift | 5 ++- 5 files changed, 33 insertions(+), 21 deletions(-) diff --git a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohTCPFirstActivation.swift b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohTCPFirstActivation.swift index d2e91e4181a2..4b46efbcd712 100644 --- a/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohTCPFirstActivation.swift +++ b/Packages/Shared/CmuxIrohTransport/Sources/CmuxIrohTransport/CmxIrohTCPFirstActivation.swift @@ -8,6 +8,13 @@ public struct CmxIrohTCPFirstActivation { /// Creates a TCP-first activation sequencer. public init() {} + /// Starts the required TCP listener synchronously, then schedules the + /// optional Iroh activation work. + /// + /// - Parameters: + /// - startTCP: Synchronously starts the required TCP listener. + /// - scheduleIroh: Enqueues asynchronous Iroh activation and returns + /// immediately without blocking on policy or credential work. public func start( startTCP: () -> Void, scheduleIroh: () -> Void diff --git a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient+RequestAuthorization.swift b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient+RequestAuthorization.swift index 122337a92f1b..99a93773bb2f 100644 --- a/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient+RequestAuthorization.swift +++ b/Packages/iOS/CmuxMobileRPC/Sources/CmuxMobileRPC/MobileCoreRPCClient+RequestAuthorization.swift @@ -63,27 +63,28 @@ extension MobileCoreRPCClient { return method != "mobile.host.status" } - private static func stringParamSelection( - _ params: [String: Any], - keys: [String] - ) -> StringParamSelection { - var selected: String? - for key in keys { - if let value = params[key] as? String { - let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmed.isEmpty { - if let selected, selected != trimmed { - return StringParamSelection(value: selected, hasConflict: true) - } - selected = selected ?? trimmed +} + +private func stringParamSelection( + _ params: [String: Any], + keys: [String] +) -> StringParamSelection { + var selected: String? + for key in keys { + if let value = params[key] as? String { + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { + if let selected, selected != trimmed { + return StringParamSelection(value: selected, hasConflict: true) } + selected = selected ?? trimmed } } - return StringParamSelection(value: selected, hasConflict: false) } + return StringParamSelection(value: selected, hasConflict: false) +} - private struct StringParamSelection { - let value: String? - let hasConflict: Bool - } +private struct StringParamSelection { + let value: String? + let hasConflict: Bool } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 2c8d7778d55b..b6653d68ca2a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -174,6 +174,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } public internal(set) var macConnectionStatus: MobileMacConnectionStatus public internal(set) var connectedHostName: String + /// User-facing description of the most recent connection failure, or `nil` + /// while no failure is being surfaced. public internal(set) var connectionError: String? /// Actionable next-step line shown beneath ``connectionError`` (for example /// "Check that both devices are on the same Tailscale"). Set and cleared diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift index afbd91c7c95e..8582ad81e0f8 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostTrustExpirationSchedulingTests.swift @@ -9,9 +9,10 @@ import Testing @Test func repeatedHealthSchedulingKeepsOneExpirationLookup() async throws { let router = LivenessHostRouter() let trustStore = CountingExpirationManualHostTrustStore() + let clock = TestClock() let runtime = LivenessTestRuntime( transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), - now: { Date() }, + now: { clock.now }, supportedRouteKinds: [.manualHost], supportsServerPushEvents: false ) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift index ddf2b1f10aba..dbdf083b3e05 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PrimaryRouteAuthorizationFallbackTests.swift @@ -7,6 +7,7 @@ import Testing @MainActor @Suite struct PrimaryRouteAuthorizationFallbackTests { @Test func authorizationFailureDoesNotFallBackToTrustedManualHost() async throws { + let clock = TestClock() let tailscaleRoute = try CmxAttachRoute( id: "preferred-tailscale", kind: .tailscale, @@ -26,7 +27,7 @@ import Testing macDisplayName: "Candidate Mac", macPairingCompatibilityVersion: CmxMobileDefaults.pairingCompatibilityVersion, routes: [tailscaleRoute, manualRoute], - expiresAt: Date().addingTimeInterval(3_600) + expiresAt: clock.now.addingTimeInterval(3_600) ) let trustStore = InMemoryMobileManualHostTrustStore() let manualScope = try #require( @@ -40,7 +41,7 @@ import Testing box: TransportBox(), attempts: attempts ), - now: { Date() }, + now: { clock.now }, supportedRouteKinds: [.tailscale, .manualHost], supportsServerPushEvents: false ) From b3f06a585e6abfd90ea4297606cb1a3a5eeb4806 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 16 Jul 2026 16:36:27 -0700 Subject: [PATCH 88/91] Add failing test: manual route priority must continue emitted sequence With a MagicDNS name plus numeric Tailscale address discovered, the resolver emits one tailscale route (priority 10) but priced the manual route off the unfiltered host count (priority 30). CmxPairingQRCode.encodableRoutes requires canonical priorities (10, 20, ...), so the mint falls back to the v1 payload and MobilePairingModel refuses to show the QR. Co-Authored-By: Claude Fable 5 --- .../MobileHostServiceSettingsTests.swift | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/cmuxTests/MobileHostServiceSettingsTests.swift b/cmuxTests/MobileHostServiceSettingsTests.swift index bb79d7cac5eb..1580feb9f934 100644 --- a/cmuxTests/MobileHostServiceSettingsTests.swift +++ b/cmuxTests/MobileHostServiceSettingsTests.swift @@ -140,6 +140,26 @@ struct MobileHostServiceSettingsTests { #expect(route.endpoint == .hostPort(host: "studio-mac.corp.example", port: 61_234)) } + @Test func routeResolverKeepsCanonicalPrioritiesWhenMagicDNSHostIsFiltered() throws { + // Production discovery prepends the MagicDNS name to the numeric + // Tailscale address; the resolver emits only the numeric host. The + // manual route's priority must continue the EMITTED sequence + // (10, 20, ...) or `CmxPairingQRCode.encodableRoutes` rejects the + // routes and the pairing QR silently degrades to the v1 payload. + let snapshot = MobileRouteResolver().routes( + port: 58_465, + tailscaleHosts: ["studio-mac.tail1234.ts.net", "100.82.214.112"], + manualHost: "studio-mac.corp.example" + ) + let minimalRoutes = snapshot.routes.filter { $0.kind != .debugLoopback } + let tailscaleRoute = try #require(minimalRoutes.first { $0.kind == .tailscale }) + let manualRoute = try #require(minimalRoutes.first { $0.kind == .manualHost }) + + #expect(minimalRoutes.count == 2) + #expect(tailscaleRoute.priority == 10) + #expect(manualRoute.priority == 20) + } + @Test func routeResolverAdvertisesConfiguredIPv6ManualHost() throws { let suiteName = "MobileHostServiceSettingsTests.ManualHost.IPv6.\(UUID().uuidString)" let defaults = try #require(UserDefaults(suiteName: suiteName)) From 836be17b018aa6c4ee2ceeb7ffed51d01f75bb46 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 16 Jul 2026 18:40:38 -0700 Subject: [PATCH 89/91] Fix manual route priority to continue the emitted tailscale sequence Discovery can prepend hosts (like the MagicDNS name) that the resolver filters out of the emitted route set. Pricing the manual route off the unfiltered count produced a 10/30 priority gap, CmxPairingQRCode's canonical-sequence check rejected the mint, and the pairing QR fell back to v1 and refused to display. Co-Authored-By: Claude Fable 5 --- Sources/Mobile/MobileRouteResolver.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/Mobile/MobileRouteResolver.swift b/Sources/Mobile/MobileRouteResolver.swift index 6665ac2b0986..85c312f9d26d 100644 --- a/Sources/Mobile/MobileRouteResolver.swift +++ b/Sources/Mobile/MobileRouteResolver.swift @@ -96,7 +96,11 @@ final class MobileRouteResolver: @unchecked Sendable { if let manualHost = manualHost.flatMap(CmxManualHost.init(routeHost:)), manualHost.isAdvertisable { - let manualPriority = 10 + (tailscaleHosts.count * 10) + // Continue the EMITTED tailscale sequence, not the discovered-host + // count: discovery can include hosts (like the MagicDNS name) that + // are filtered out above, and `CmxPairingQRCode.encodableRoutes` + // rejects any priority gap in the canonical 10, 20, ... sequence. + let manualPriority = 10 + (numericTailscaleHosts.count * 10) if let manualRoute = try? CmxAttachRoute( id: CmxAttachTransportKind.manualHost.rawValue, kind: .manualHost, From a4fba4c9c6a18bdde3c129e6b3d25d15ea235374 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 16 Jul 2026 19:05:39 -0700 Subject: [PATCH 90/91] Add failing test: second manual candidate must not clobber pending switch approval A stored Mac with two untrusted manual-host candidates queues an approval for the first candidate, then the route loop keeps dialing: the second candidate rotates the pairing attempt, supersedes the first pending trust, and finishes the switch attempt. The user's approval then resolves as .superseded and the switch is stranded. Also pins the working invariant that an approved manual-host switch leaves the connected Mac persisted as active via identity recovery. Co-Authored-By: Claude Fable 5 --- ...ualHostSwitchApprovalRegressionTests.swift | 125 ++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostSwitchApprovalRegressionTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostSwitchApprovalRegressionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostSwitchApprovalRegressionTests.swift new file mode 100644 index 000000000000..e76ccb42bf3e --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ManualHostSwitchApprovalRegressionTests.swift @@ -0,0 +1,125 @@ +import CMUXMobileCore +import CmuxMobilePairedMac +import CmuxMobileShellModel +import Foundation +import Testing +@testable import CmuxMobileShell + +/// Regressions for manual-host trust approval during a Mac switch: a queued +/// approval must survive the remaining route candidates, and the approved +/// switch must persist its target as the active Mac. +@MainActor +@Suite struct ManualHostSwitchApprovalRegressionTests { + @Test func secondManualCandidateDoesNotClobberPendingSwitchApproval() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + // Two untrusted manual-host candidates for ONE Mac. Dialing the second + // must not supersede the approval the first already queued. + try await pairedMacStore.upsert( + macDeviceID: "lan-mac", + displayName: "LAN Mac", + routes: [ + try manualRoute(host: "192.168.89.10", port: 58_465, priority: 10), + try manualRoute(host: "192.168.89.11", port: 58_466, priority: 20), + ], + markActive: false, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let store = try await makeStore(pairedMacStore: pairedMacStore) + + let switched = await store.switchToMac(macDeviceID: "lan-mac") + + #expect(!switched) + // The FIRST candidate owns the pending approval; iterating on to the + // second candidate would rotate the pairing attempt and finish the + // switch attempt, stranding the user's approval as `.superseded`. + #expect(store.manualHostTrustWarning?.endpoint == "192.168.89.10:58465") + #expect(store.isMacSwitchInFlight) + + let approved = await store.acceptManualHostTrustWarning() + + #expect(approved == .connected) + #expect(store.connectionState == .connected) + #expect(!store.isMacSwitchInFlight) + } + + @Test func approvedManualHostSwitchPersistsTheConnectedMacAsActive() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + // The router fixture identifies the host as "test-mac"; the stored row + // uses the same real device id, as a paired manual host does after its + // first identity recovery. + try await pairedMacStore.upsert( + macDeviceID: "test-mac", + displayName: "Test Mac", + routes: [try manualRoute(host: "192.168.89.21", port: 58_465, priority: 10)], + markActive: false, + stackUserID: "phone-user", + teamID: nil, + now: Date() + ) + let store = try await makeStore(pairedMacStore: pairedMacStore, deviceID: "test-mac") + + let switched = await store.switchToMac(macDeviceID: "test-mac") + #expect(!switched) + #expect(store.manualHostTrustWarning?.endpoint == "192.168.89.21:58465") + + let approved = await store.acceptManualHostTrustWarning() + + #expect(approved == .connected) + #expect(store.connectionState == .connected) + // The approved switch is a switch success: identity recovery during the + // resumed connect must leave the connected Mac persisted as active, or + // the next relaunch reconnects to the previously-active Mac instead. + let activeMac = try await pairedMacStore.activeMac( + stackUserID: "phone-user", + teamID: nil + ) + #expect(activeMac?.macDeviceID == "test-mac") + } + + private func makeStore( + pairedMacStore: MobilePairedMacStore, + deviceID: String = "lan-mac" + ) async throws -> MobileShellComposite { + let router = LivenessHostRouter() + await router.setHostIdentity(deviceID: deviceID, instanceTag: nil, displayName: "LAN Mac") + let clock = TestClock() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: TransportBox()), + now: { clock.now }, + supportedRouteKinds: [.manualHost], + supportsServerPushEvents: false + ) + let store = MobileShellComposite( + runtime: runtime, + workspaces: [], + pairedMacStore: pairedMacStore, + identityProvider: StaticIdentityProvider(userID: "phone-user"), + reachability: AlwaysOnlineReachability(), + manualHostTrustStore: InMemoryMobileManualHostTrustStore() + ) + store.signIn() + await store.loadPairedMacs() + return store + } + + private func manualRoute(host: String, port: Int, priority: Int) throws -> CmxAttachRoute { + try CmxAttachRoute( + id: "manual-\(host)-\(port)", + kind: .manualHost, + endpoint: .hostPort(host: host, port: port), + priority: priority + ) + } +} From 3f93301817eb6e69a26b2c399db7a17c9b327bcb Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 16 Jul 2026 19:06:37 -0700 Subject: [PATCH 91/91] Stop manual-host candidate iteration once an approval or supersession owns the attempt connectStoredMac's host/port loop discarded connectManualHost's result and only broke on a live connection, so a second untrusted candidate rotated the pairing attempt, superseded the first candidate's queued trust warning, and finished the switch attempt out from under the pending approval. The user's approval then resolved as .superseded and the switch was stranded. Continue to the next candidate only on a plain failure. Also drain a parked network-change recovery when the foreground-liveness recovery path finishes; it cleared the in-flight flags without running the coalesced pending recovery. Co-Authored-By: Claude Fable 5 --- .../MobileShellComposite+ConnectionRecovery.swift | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 140fc3da0713..12d7e38d0d66 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -80,6 +80,9 @@ extension MobileShellComposite { } self.recoveryInFlight = false self.isRecoveringConnection = false + // A network change that arrived during this recovery parked itself + // behind the in-flight flags; run it now or it stays pending. + self.drainPendingNetworkRecoveryIfIdle() } } @@ -236,7 +239,7 @@ extension MobileShellComposite { ) for route in candidates { guard ifStillCurrent?() ?? true else { return false } - await connectManualHost( + let result = await connectManualHost( name: name, host: route.host, port: route.port, @@ -247,11 +250,11 @@ extension MobileShellComposite { pendingMacSwitchAttemptID: pendingMacSwitchAttemptID, ifStillCurrent: ifStillCurrent ) - if connectionState == .connected, - remoteClient != nil, - foregroundMacDeviceID == pairedMacDeviceID { - break - } + // Only a plain failure moves on to the next candidate. A + // pending user approval owns this attempt's continuation: + // dialing the next candidate would rotate the pairing attempt, + // supersede the queued trust warning, and strand the approval. + guard result == .failed else { break } } }