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

Universal auth v1 and v2 NetworkProtection #1207

Merged
merged 23 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
337a9c0
re-adding v1 classes and renaming new classes with v2
federicocappelli Jan 27, 2025
9c48278
porting other changes
federicocappelli Jan 27, 2025
ace2294
v1 suffix removed and v2 suffix added
federicocappelli Jan 27, 2025
36b2690
V1 Testing utilities re-added
federicocappelli Jan 27, 2025
ac64aa3
func documentation, renaming
federicocappelli Jan 27, 2025
91d64d0
commented out code removed
federicocappelli Jan 27, 2025
2dfe234
lint
federicocappelli Jan 27, 2025
b5f5759
unit tests renamed v2
federicocappelli Jan 27, 2025
e17b52c
v1 tests restored
federicocappelli Jan 27, 2025
fc31514
lint
federicocappelli Jan 27, 2025
f77e067
tests fixed
federicocappelli Jan 27, 2025
fecc9d9
Merge branch 'main' into fcappelli/authv2/adding_v2_classes
federicocappelli Jan 27, 2025
d2d6852
tests timeouts increased
federicocappelli Jan 27, 2025
c81c5f8
fix MaliciousSiteProtectionUpdateManagerTests
mallexxx Jan 28, 2025
38dd027
Merge branch 'main' into fcappelli/authv2/adding_v2_classes
federicocappelli Jan 30, 2025
7188555
Universal auth v1 and v2 NetworkProtection
federicocappelli Jan 30, 2025
a0759e6
cleanup
federicocappelli Jan 30, 2025
aea4b55
lint
federicocappelli Jan 30, 2025
2051596
NetworkProtectionKeychainTokenStore implementation of SubscriptionTok…
federicocappelli Jan 30, 2025
8a8de2d
Merge branch 'main' into fcappelli/authv2/network_protection_2tokens
federicocappelli Feb 3, 2025
288b580
clenup
federicocappelli Feb 3, 2025
a00f1d5
v1 and v2 compatibility fix
federicocappelli Feb 3, 2025
c86f1c5
lint
federicocappelli Feb 4, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ public actor NetworkProtectionServerStatusMonitor {
}

private let networkClient: NetworkProtectionClient
private let tokenStore: NetworkProtectionTokenStore
private let tokenHandler: any SubscriptionTokenHandling

// MARK: - Init & deinit

init(networkClient: NetworkProtectionClient, tokenStore: NetworkProtectionTokenStore) {
init(networkClient: NetworkProtectionClient, tokenHandler: any SubscriptionTokenHandling) {
self.networkClient = networkClient
self.tokenStore = tokenStore
self.tokenHandler = tokenHandler

Logger.networkProtectionMemory.debug("[+] \(String(describing: self), privacy: .public)")
}
Expand Down Expand Up @@ -99,11 +99,11 @@ public actor NetworkProtectionServerStatusMonitor {
// MARK: - Server Status Check

private func checkServerStatus(for serverName: String) async -> Result<NetworkProtectionServerStatus, NetworkProtectionClientError> {
guard let accessToken = try? tokenStore.fetchToken() else {
guard let accessToken = try? await VPNAuthTokenBuilder.getVPNAuthToken(from: tokenHandler) else {
Logger.networkProtection.fault("Failed to check server status due to lack of access token")
assertionFailure("Failed to check server status due to lack of access token")
return .failure(.invalidAuthToken)
}

return await networkClient.getServerStatus(authToken: accessToken, serverName: serverName)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,8 @@ public final class NetworkProtectionKeychainKeyStore: NetworkProtectionKeyStore
// MARK: - EventMapping

private func handle(_ error: Error) {
Logger.networkProtectionKeyManagement.error("Failed to perform operation: \(error, privacy: .public)")

guard let error = error as? NetworkProtectionKeychainStoreError else {
assertionFailure("Failed to cast Network Protection Keychain store error")
errorEvents?.fire(NetworkProtectionError.unhandledError(function: #function, line: #line, error: error))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ enum NetworkProtectionKeychainStoreError: Error, NetworkProtectionErrorConvertib
}

/// General Keychain access helper class for the NetworkProtection module. Should be used for specific KeychainStore types.
final class NetworkProtectionKeychainStore {
public final class NetworkProtectionKeychainStore {
private let label: String
private let serviceName: String
private let keychainType: KeychainType

init(label: String,
serviceName: String,
keychainType: KeychainType) {
public init(label: String,
serviceName: String,
keychainType: KeychainType) {

self.label = label
self.serviceName = serviceName
Expand All @@ -55,7 +55,8 @@ final class NetworkProtectionKeychainStore {

// MARK: - Keychain Interaction

func readData(named name: String) throws -> Data? {
public func readData(named name: String) throws -> Data? {
Logger.networkProtectionKeyManagement.debug("Reading key \(name, privacy: .public) from keychain")
Copy link
Contributor

Choose a reason for hiding this comment

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

Nice, the new log entries are handy 🙌

Copy link
Member Author

Choose a reason for hiding this comment

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

Just to clarify, I added logs that I found useful during my VPN debug sessions

var query = defaultAttributes()
query[kSecAttrAccount] = name
query[kSecReturnData] = true
Expand All @@ -78,7 +79,8 @@ final class NetworkProtectionKeychainStore {
}
}

func writeData(_ data: Data, named name: String) throws {
public func writeData(_ data: Data, named name: String) throws {
Logger.networkProtectionKeyManagement.debug("Writing key \(name, privacy: .public) to keychain")
var query = defaultAttributes()
query[kSecAttrAccount] = name
query[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlock
Expand All @@ -101,18 +103,20 @@ final class NetworkProtectionKeychainStore {
}

private func updateData(_ data: Data, named name: String) -> OSStatus {
Logger.networkProtectionKeyManagement.debug("Updating key \(name, privacy: .public) in keychain")
var query = defaultAttributes()
query[kSecAttrAccount] = name

let newAttributes = [
kSecValueData: data,
kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock
kSecValueData: data,
kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock
] as [CFString: Any]

return SecItemUpdate(query as CFDictionary, newAttributes as CFDictionary)
}

func deleteAll() throws {
public func deleteAll() throws {
Logger.networkProtectionKeyManagement.debug("Deleting all keys from keychain")
var query = defaultAttributes()
#if os(macOS)
// This line causes the delete to error with status -50 on iOS. Needs investigation but, for now, just delete the first item
Expand All @@ -125,6 +129,7 @@ final class NetworkProtectionKeychainStore {
case errSecItemNotFound, errSecSuccess:
break
default:
Logger.networkProtectionKeyManagement.error("🔴 Failed to delete all keys, SecItemDelete status \(String(describing: status), privacy: .public)")
throw NetworkProtectionKeychainStoreError.keychainDeleteError(status: status)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
//
// NetworkProtectionKeychainTokenStore+LegacyAuthTokenStoring.swift
//
// Copyright © 2025 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation
import Networking

extension NetworkProtectionKeychainTokenStore: LegacyAuthTokenStoring {

public var token: String? {
get {
do {
return try fetchToken()
} catch {
assertionFailure("Failed to retrieve auth token: \(error)")
}
return nil
}
set(newValue) {
do {
guard let newValue else {
try deleteToken()
return
}
try store(newValue)
} catch {
assertionFailure("Failed set token: \(error)")
}
}
}
}
1 change: 1 addition & 0 deletions Sources/NetworkProtection/Logger+NetworkProtection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@ public extension Logger {
static var networkProtectionStatusReporter = { Logger(subsystem: Logger.subsystem, category: "Status Reporter") }()
static var networkProtectionSleep = { Logger(subsystem: Logger.subsystem, category: "Sleep and Wake") }()
static var networkProtectionEntitlement = { Logger(subsystem: Logger.subsystem, category: "Entitlement Monitor") }()
static var networkProtectionWireGuard = { Logger(subsystem: Logger.subsystem, category: "WireGuardAdapter") }()
}
30 changes: 16 additions & 14 deletions Sources/NetworkProtection/NetworkProtectionDeviceManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,27 +73,27 @@ public protocol NetworkProtectionDeviceManagement {

public actor NetworkProtectionDeviceManager: NetworkProtectionDeviceManagement {
private let networkClient: NetworkProtectionClient
private let tokenStore: NetworkProtectionTokenStore
private let tokenHandler: any SubscriptionTokenHandling
private let keyStore: NetworkProtectionKeyStore

private let errorEvents: EventMapping<NetworkProtectionError>?

public init(environment: VPNSettings.SelectedEnvironment,
tokenStore: NetworkProtectionTokenStore,
tokenHandler: any SubscriptionTokenHandling,
keyStore: NetworkProtectionKeyStore,
errorEvents: EventMapping<NetworkProtectionError>?) {
self.init(networkClient: NetworkProtectionBackendClient(environment: environment),
tokenStore: tokenStore,
tokenHandler: tokenHandler,
keyStore: keyStore,
errorEvents: errorEvents)
}

init(networkClient: NetworkProtectionClient,
tokenStore: NetworkProtectionTokenStore,
tokenHandler: any SubscriptionTokenHandling,
keyStore: NetworkProtectionKeyStore,
errorEvents: EventMapping<NetworkProtectionError>?) {
self.networkClient = networkClient
self.tokenStore = tokenStore
self.tokenHandler = tokenHandler
self.keyStore = keyStore
self.errorEvents = errorEvents
}
Expand All @@ -102,17 +102,18 @@ public actor NetworkProtectionDeviceManager: NetworkProtectionDeviceManagement {
/// This method will return the remote server list if available, or the local server list if there was a problem with the service call.
///
public func refreshServerList() async throws -> [NetworkProtectionServer] {
guard let token = try? tokenStore.fetchToken() else {
guard let token = try? await VPNAuthTokenBuilder.getVPNAuthToken(from: tokenHandler) else {
throw NetworkProtectionError.noAuthTokenFound
}

let result = await networkClient.getServers(authToken: token)
let completeServerList: [NetworkProtectionServer]

switch result {
case .success(let serverList):
completeServerList = serverList
case .failure(let failure):
handle(clientError: failure)
await handle(clientError: failure)
throw failure
}

Expand Down Expand Up @@ -188,8 +189,9 @@ public actor NetworkProtectionDeviceManager: NetworkProtectionDeviceManagement {
private func register(keyPair: KeyPair,
selectionMethod: NetworkProtectionServerSelectionMethod) async throws -> (server: NetworkProtectionServer,
newExpiration: Date?) {

guard let token = try? tokenStore.fetchToken() else { throw NetworkProtectionError.noAuthTokenFound }
guard let token = try? await VPNAuthTokenBuilder.getVPNAuthToken(from: tokenHandler) else {
throw NetworkProtectionError.noAuthTokenFound
}

let serverSelection: RegisterServerSelection
let excludedServerName: String?
Expand Down Expand Up @@ -231,7 +233,7 @@ public actor NetworkProtectionDeviceManager: NetworkProtectionDeviceManagement {
selectedServer = registeredServer
return (selectedServer, selectedServer.expirationDate)
case .failure(let error):
handle(clientError: error)
await handle(clientError: error)
try handleAccessRevoked(error)
throw error
}
Expand Down Expand Up @@ -312,12 +314,12 @@ public actor NetworkProtectionDeviceManager: NetworkProtectionDeviceManagement {
return peerConfiguration
}

private func handle(clientError: NetworkProtectionClientError) {
#if os(macOS)
private func handle(clientError: NetworkProtectionClientError) async {
#if os(macOS)
if case .invalidAuthToken = clientError {
try? tokenStore.deleteToken()
try? await tokenHandler.removeToken()
}
#endif
#endif
errorEvents?.fire(clientError.networkProtectionError)
}

Expand Down
1 change: 1 addition & 0 deletions Sources/NetworkProtection/NetworkProtectionOptionKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public enum NetworkProtectionOptionKey {
public static let dnsSettings = "dnsSettings"
public static let excludeLocalNetworks = "excludeLocalNetworks"
public static let authToken = "authToken"
public static let tokenContainer = "tokenContainer"
public static let isOnDemand = "is-on-demand"
public static let activationAttemptId = "activationAttemptId"
public static let tunnelFailureSimulation = "tunnelFailureSimulation"
Expand Down
20 changes: 20 additions & 0 deletions Sources/NetworkProtection/Networking/NetworkProtectionClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,26 @@ public enum NetworkProtectionClientError: CustomNSError, NetworkProtectionErrorC
return [:]
}
}

public var errorDescription: String? {
switch self {
case .failedToFetchLocationList: return "Failed to fetch location list"
case .failedToParseLocationListResponse: return "Failed to parse location list response"
case .failedToFetchServerList: return "Failed to fetch server list"
case .failedToParseServerListResponse: return "Failed to parse server list response"
case .failedToEncodeRegisterKeyRequest: return "Failed to encode register key request"
case .failedToFetchServerStatus(let error):
return "Failed to fetch server status: \(error)"
case .failedToParseServerStatusResponse(let error):
return "Failed to parse server status response: \(error)"
case .failedToFetchRegisteredServers(let error):
return "Failed to fetch registered servers: \(error)"
case .failedToParseRegisteredServersResponse(let error):
return "Failed to parse registered servers response: \(error)"
case .invalidAuthToken: return "Invalid auth token"
case .accessDenied: return "Access denied"
}
}
}

struct RegisterKeyRequestBody: Encodable {
Expand Down
Loading
Loading