Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(apple): Handle network changes reliably on macOS and iOS #4133

Merged
merged 14 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 4 additions & 13 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 12 additions & 17 deletions rust/connlib/clients/apple/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ mod ffi {
callback_handler: CallbackHandler,
) -> Result<WrappedSession, String>;

fn reconnect(&mut self);
#[swift_bridge(swift_name = "setDns")]
fn set_dns(&mut self, dns_servers: String);
Comment on lines +47 to +49
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll leave some redundant questions just to make sure I understand how the Apple Client fits together.

So this part is exposing the Rust functions to Swift, we're declaring these two new functions. This is still on the Rust side, so I assume it would error if the signature is wrong.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah! The macros in here are used to generate the bindings.

fn disconnect(self);
}

Expand All @@ -58,9 +61,6 @@ mod ffi {
dnsAddresses: String,
);

#[swift_bridge(swift_name = "onTunnelReady")]
fn on_tunnel_ready(&self);

#[swift_bridge(swift_name = "onUpdateRoutes")]
fn on_update_routes(&self, routeList4: String, routeList6: String);

Expand All @@ -69,10 +69,6 @@ mod ffi {

#[swift_bridge(swift_name = "onDisconnect")]
fn on_disconnect(&self, error: String);

// TODO: remove in favor of set_dns
#[swift_bridge(swift_name = "getSystemDefaultResolvers")]
fn get_system_default_resolvers(&self) -> String;
}
}

Expand Down Expand Up @@ -115,10 +111,6 @@ impl Callbacks for CallbackHandler {
None
}

fn on_tunnel_ready(&self) {
self.inner.on_tunnel_ready();
}

fn on_update_routes(
&self,
route_list_4: Vec<Cidrv4>,
Expand Down Expand Up @@ -182,10 +174,6 @@ impl WrappedSession {
let handle = init_logging(log_dir.into(), log_filter).map_err(|e| e.to_string())?;
let secret = SecretString::from(token);

let resolvers_json = callback_handler.get_system_default_resolvers();
let resolvers: Vec<IpAddr> = serde_json::from_str(&resolvers_json)
.expect("developer error: failed to deserialize resolvers");

let (private_key, public_key) = keypair();
let login = LoginUrl::client(
api_url.as_str(),
Expand Down Expand Up @@ -217,14 +205,21 @@ impl WrappedSession {
)
.map_err(|err| err.to_string())?;

session.set_dns(resolvers);

Ok(Self {
inner: session,
runtime,
})
}

fn reconnect(&mut self) {
self.inner.reconnect()
}

fn set_dns(&mut self, dns_servers: String) {
self.inner
.set_dns(serde_json::from_str(&dns_servers).unwrap())
}

fn disconnect(self) {
self.inner.disconnect()
}
Expand Down
26 changes: 14 additions & 12 deletions swift/apple/Firezone.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
05CF1D16290B1FE700CF4755 /* PacketTunnelProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05833DFA28F73B070008FAB0 /* PacketTunnelProvider.swift */; };
05CF1D17290B1FE700CF4755 /* PacketTunnelProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05833DFA28F73B070008FAB0 /* PacketTunnelProvider.swift */; };
05D3BB2128FDE9C000BC3727 /* NetworkExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 05D3BB1628FDBD8A00BC3727 /* NetworkExtension.framework */; };
6FA39A042A6A7248000F0157 /* NetworkResource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FA39A032A6A7248000F0157 /* NetworkResource.swift */; };
6FA39A052A6A7248000F0157 /* NetworkResource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FA39A032A6A7248000F0157 /* NetworkResource.swift */; };
6FE454F62A5BFB93006549B1 /* Adapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FE454EA2A5BFABA006549B1 /* Adapter.swift */; };
6FE454F72A5BFB93006549B1 /* Adapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FE454EA2A5BFABA006549B1 /* Adapter.swift */; };
6FE455092A5D110D006549B1 /* CallbackHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FE455082A5D110D006549B1 /* CallbackHandler.swift */; };
Expand All @@ -30,8 +28,10 @@
794C38152970A2660029F38F /* FirezoneKit in Frameworks */ = {isa = PBXBuildFile; productRef = 794C38142970A2660029F38F /* FirezoneKit */; };
794C38172970A26A0029F38F /* FirezoneKit in Frameworks */ = {isa = PBXBuildFile; productRef = 794C38162970A26A0029F38F /* FirezoneKit */; };
79756C6629704A7A0018E2D5 /* FirezoneKit in Frameworks */ = {isa = PBXBuildFile; productRef = 79756C6529704A7A0018E2D5 /* FirezoneKit */; };
8D28EB992B35FBD70083621C /* Resolv.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D28EB982B35FBD70083621C /* Resolv.swift */; };
8D28EB9A2B35FBD70083621C /* Resolv.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D28EB982B35FBD70083621C /* Resolv.swift */; };
8D69392C2BA24FE600AF4396 /* BindResolvers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D69392B2BA24FE600AF4396 /* BindResolvers.swift */; };
8D69392F2BA2502000AF4396 /* DeviceMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D69392E2BA2502000AF4396 /* DeviceMetadata.swift */; };
8D6939302BA2502000AF4396 /* DeviceMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D69392E2BA2502000AF4396 /* DeviceMetadata.swift */; };
8D6939322BA2521A00AF4396 /* SystemConfigurationResolvers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D6939312BA2521A00AF4396 /* SystemConfigurationResolvers.swift */; };
8DC08BCB2B296C4500675F46 /* libresolv.9.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 8DC08BCA2B296C4500675F46 /* libresolv.9.tbd */; };
8DC08BCD2B296C5900675F46 /* libresolv.9.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 8DC08BCC2B296C5900675F46 /* libresolv.9.tbd */; };
8DC08BD22B297B7B00675F46 /* libresolv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 8DC08BD12B297B7B00675F46 /* libresolv.tbd */; };
Expand Down Expand Up @@ -108,15 +108,16 @@
05CF1CF6290B1CEE00CF4755 /* FirezoneNetworkExtension_iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = FirezoneNetworkExtension_iOS.entitlements; sourceTree = "<group>"; };
05CF1D03290B1DCD00CF4755 /* FirezoneNetworkExtensionmacOS.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = FirezoneNetworkExtensionmacOS.appex; sourceTree = BUILT_PRODUCTS_DIR; };
05D3BB1628FDBD8A00BC3727 /* NetworkExtension.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = NetworkExtension.framework; path = System/Library/Frameworks/NetworkExtension.framework; sourceTree = SDKROOT; };
6FA39A032A6A7248000F0157 /* NetworkResource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkResource.swift; sourceTree = "<group>"; };
6FE454EA2A5BFABA006549B1 /* Adapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Adapter.swift; sourceTree = "<group>"; };
6FE455082A5D110D006549B1 /* CallbackHandler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CallbackHandler.swift; sourceTree = "<group>"; };
6FE4550B2A5D111D006549B1 /* SwiftBridgeCore.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SwiftBridgeCore.swift; path = Connlib/Generated/SwiftBridgeCore.swift; sourceTree = "<group>"; };
6FE4550E2A5D112C006549B1 /* connlib-client-apple.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "connlib-client-apple.swift"; path = "Connlib/Generated/connlib-client-apple/connlib-client-apple.swift"; sourceTree = "<group>"; };
6FE455112A5D13A2006549B1 /* FirezoneNetworkExtension-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "FirezoneNetworkExtension-Bridging-Header.h"; sourceTree = "<group>"; };
6FE93AFA2A738D7E002D278A /* NetworkSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkSettings.swift; sourceTree = "<group>"; };
6FFECD5B2AD6998400E00273 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; };
8D28EB982B35FBD70083621C /* Resolv.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Resolv.swift; sourceTree = "<group>"; };
8D69392B2BA24FE600AF4396 /* BindResolvers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BindResolvers.swift; sourceTree = "<group>"; };
8D69392E2BA2502000AF4396 /* DeviceMetadata.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeviceMetadata.swift; sourceTree = "<group>"; };
8D6939312BA2521A00AF4396 /* SystemConfigurationResolvers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SystemConfigurationResolvers.swift; sourceTree = "<group>"; };
8DC08BCA2B296C4500675F46 /* libresolv.9.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libresolv.9.tbd; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS17.2.sdk/usr/lib/libresolv.9.tbd; sourceTree = DEVELOPER_DIR; };
8DC08BCC2B296C5900675F46 /* libresolv.9.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libresolv.9.tbd; path = usr/lib/libresolv.9.tbd; sourceTree = SDKROOT; };
8DC08BD12B297B7B00675F46 /* libresolv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libresolv.tbd; path = usr/lib/libresolv.tbd; sourceTree = SDKROOT; };
Expand Down Expand Up @@ -177,17 +178,18 @@
05833DF928F73B070008FAB0 /* FirezoneNetworkExtension */ = {
isa = PBXGroup;
children = (
8D6939312BA2521A00AF4396 /* SystemConfigurationResolvers.swift */,
8D69392E2BA2502000AF4396 /* DeviceMetadata.swift */,
8D69392B2BA24FE600AF4396 /* BindResolvers.swift */,
05CF1CF6290B1CEE00CF4755 /* FirezoneNetworkExtension_iOS.entitlements */,
05CF1CDE290B1A9000CF4755 /* FirezoneNetworkExtension_macOS.entitlements */,
05833DFA28F73B070008FAB0 /* PacketTunnelProvider.swift */,
6FE454EA2A5BFABA006549B1 /* Adapter.swift */,
6FE93AFA2A738D7E002D278A /* NetworkSettings.swift */,
6FA39A032A6A7248000F0157 /* NetworkResource.swift */,
6FE455082A5D110D006549B1 /* CallbackHandler.swift */,
6FE4550B2A5D111D006549B1 /* SwiftBridgeCore.swift */,
6FE4550E2A5D112C006549B1 /* connlib-client-apple.swift */,
6FE455112A5D13A2006549B1 /* FirezoneNetworkExtension-Bridging-Header.h */,
8D28EB982B35FBD70083621C /* Resolv.swift */,
);
path = FirezoneNetworkExtension;
sourceTree = "<group>";
Expand Down Expand Up @@ -498,12 +500,12 @@
files = (
8DC08BD72B297DB400675F46 /* FirezoneNetworkExtension-Bridging-Header.h in Sources */,
6FE455092A5D110D006549B1 /* CallbackHandler.swift in Sources */,
8D28EB992B35FBD70083621C /* Resolv.swift in Sources */,
6FE4550F2A5D112C006549B1 /* connlib-client-apple.swift in Sources */,
05CF1D17290B1FE700CF4755 /* PacketTunnelProvider.swift in Sources */,
6FE454F62A5BFB93006549B1 /* Adapter.swift in Sources */,
6FA39A042A6A7248000F0157 /* NetworkResource.swift in Sources */,
6FE4550C2A5D111E006549B1 /* SwiftBridgeCore.swift in Sources */,
8D69392C2BA24FE600AF4396 /* BindResolvers.swift in Sources */,
8D69392F2BA2502000AF4396 /* DeviceMetadata.swift in Sources */,
6FE93AFB2A738D7E002D278A /* NetworkSettings.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand All @@ -514,13 +516,13 @@
files = (
8DC08BD62B297DA400675F46 /* FirezoneNetworkExtension-Bridging-Header.h in Sources */,
6FE4550A2A5D110D006549B1 /* CallbackHandler.swift in Sources */,
8D28EB9A2B35FBD70083621C /* Resolv.swift in Sources */,
6FE455102A5D112C006549B1 /* connlib-client-apple.swift in Sources */,
05CF1D16290B1FE700CF4755 /* PacketTunnelProvider.swift in Sources */,
8D6939302BA2502000AF4396 /* DeviceMetadata.swift in Sources */,
6FE454F72A5BFB93006549B1 /* Adapter.swift in Sources */,
6FA39A052A6A7248000F0157 /* NetworkResource.swift in Sources */,
6FE4550D2A5D111E006549B1 /* SwiftBridgeCore.swift in Sources */,
6FE93AFC2A738D7E002D278A /* NetworkSettings.swift in Sources */,
8D6939322BA2521A00AF4396 /* SystemConfigurationResolvers.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
26 changes: 10 additions & 16 deletions swift/apple/Firezone/Application/FirezoneApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ struct FirezoneApp: App {
StateObject(
wrappedValue: AskPermissionViewModel(
tunnelStore: appStore.tunnelStore,
sessionNotificationHelper: SessionNotificationHelper(logger: appStore.logger, authStore: appStore.authStore)
sessionNotificationHelper: SessionNotificationHelper(
logger: appStore.logger, tunnelStore: appStore.tunnelStore)
)
)
appDelegate.appStore = appStore
Expand All @@ -47,7 +48,7 @@ struct FirezoneApp: App {
}
#else
WindowGroup(
"Firezone (VPN Permission)",
"Welcome to Firezone",
id: AppStore.WindowDefinition.askPermission.identifier
) {
AskPermissionView(model: askPermissionViewModel)
Expand All @@ -74,31 +75,24 @@ struct FirezoneApp: App {
private var isAppLaunched = false
private var menuBar: MenuBar?

public var appStore: AppStore? {
didSet {
if self.isAppLaunched {
// This is not expected to happen because appStore
// should be set before the app finishes launching.
// This code is only a contingency.
if let appStore = self.appStore {
self.menuBar = MenuBar(appStore: appStore)
}
}
}
}
public var appStore: AppStore?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"store" here means some persistent variable storage, it's not related to the Apple App Store package manager, right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was confused by that too at first. That's correct.

It could probably use a rename.


func applicationDidFinishLaunching(_: Notification) {
self.isAppLaunched = true
if let appStore = self.appStore {
self.menuBar = MenuBar(appStore: appStore)
self.menuBar = MenuBar(
tunnelStore: appStore.tunnelStore,
settingsViewModel: appStore.settingsViewModel,
logger: appStore.logger
)
}

// SwiftUI will show the first window group, so close it on launch
_ = AppStore.WindowDefinition.allCases.map { $0.window()?.close() }
}

func applicationWillTerminate(_: Notification) {
self.appStore?.authStore.cancelSignIn()
self.appStore?.tunnelStore.cancelSignIn()
}
}
#endif
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,13 @@ public final class AskPermissionViewModel: ObservableObject {
self.tunnelStore = tunnelStore
self.sessionNotificationHelper = sessionNotificationHelper

tunnelStore.$tunnelAuthStatus
.filter { $0.isInitialized }
.sink { [weak self] tunnelAuthStatus in
tunnelStore.$status
.sink { [weak self] status in
guard let self = self else { return }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is equivalent to the let-else we use in Rust? The else is required to diverge, and it doesn't do anything special, it's just a more idiomatic way to do an early return?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's correct. Guards are pretty heavily used in Swift and they turn Optional(obj) into just obj so you don't need the optional modifier in the remainder of the block body.


Task {
await MainActor.run {
if case .noTunnelFound = tunnelAuthStatus {
if case .invalid = status {
self.needsTunnelPermission = true
} else {
self.needsTunnelPermission = false
Expand All @@ -66,19 +65,12 @@ public final class AskPermissionViewModel: ObservableObject {
}
}
.store(in: &cancellables)

}

func grantPermissionButtonTapped() {
Task {
do {
try await self.tunnelStore.createTunnel()
} catch {
#if os(macOS)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
AppStore.WindowDefinition.askPermission.bringAlreadyOpenWindowFront()
}
#endif
try await self.tunnelStore.createManager()
}
}
}
Expand All @@ -90,7 +82,7 @@ public final class AskPermissionViewModel: ObservableObject {
#endif

#if os(macOS)
func closeAskPermissionWindow() {
public func closeAskPermissionWindow() {
AppStore.WindowDefinition.askPermission.window()?.close()
}
#endif
Expand All @@ -111,11 +103,10 @@ public struct AskPermissionView: View {
Image("LogoText")
.resizable()
.scaledToFit()
.frame(maxWidth: 600)
.frame(maxWidth: 320)
.padding(.horizontal, 10)
Spacer()
if $model.needsTunnelPermission.wrappedValue {

#if os(macOS)
Text(
"Firezone requires your permission to create VPN tunnels.\nUntil it has that permission, all functionality will be disabled."
Expand Down Expand Up @@ -180,7 +171,6 @@ public struct AskPermissionView: View {
.multilineTextAlignment(.center)
#endif
} else {

#if os(macOS)
Text(
"You can sign in to Firezone by clicking on the Firezone icon in the macOS menu bar.\nYou may now close this window."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,19 @@ import XCTestDynamicOverlay
@MainActor
final class AuthViewModel: ObservableObject {

let authStore: AuthStore
let tunnelStore: TunnelStore

var settingsUndefined: () -> Void = unimplemented("\(AuthViewModel.self).settingsUndefined")

private var cancellables = Set<AnyCancellable>()

init(authStore: AuthStore) {
self.authStore = authStore
init(tunnelStore: TunnelStore) {
self.tunnelStore = tunnelStore
}

func signInButtonTapped() async {
do {
try await authStore.signIn()
try await tunnelStore.signIn()
} catch {
dump(error)
}
Expand Down
Loading
Loading