summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/MullvadAPI.swift
blob: 9e6add133acbbe4c87e81378a1074b053156db8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
//
//  MullvadAPI.swift
//  MullvadVPN
//
//  Created by pronebird on 02/05/2019.
//  Copyright © 2019 Mullvad VPN AB. All rights reserved.
//

import Foundation
import Network
import Combine

/// API server URL
private let kMullvadAPIURL = URL(string: "https://api.mullvad.net/rpc/")!

/// Network request timeout in seconds
private let kNetworkTimeout: TimeInterval = 10

/// A type that describes the account verification result
enum AccountVerification {
    /// The app should attempt to verify the account token at some point later because the network
    /// may not be available at this time.
    case deferred(DeferReasonError)

    /// The app successfully verified the account token with the server
    case verified(Date)

    // Invalid token
    case invalid
}

/// An error type that describes why the account verification was deferred
enum DeferReasonError: Error {
    /// Mullvad API communication error
    case communication(MullvadAPI.Error)

    /// Mullvad API responded with an error
    case server(MullvadAPI.ResponseError)
}

class MullvadAPI {
    private let session: URLSession

    /// A enum mapping the integer codes returned by Mullvad API with the corresponding enum
    /// variants
    private enum RawResponseCode: Int {
        case accountDoesNotExist = -200
        case tooManyWireguardKeys = -703
    }

    /// A enum describing the Mullvad API response code
    enum ResponseCode: RawRepresentable, Codable {
        var rawValue: Int {
            switch self {
            case .accountDoesNotExist:
                return RawResponseCode.accountDoesNotExist.rawValue

            case .tooManyWireguardKeys:
                return RawResponseCode.tooManyWireguardKeys.rawValue

            case .other(let value):
                return value
            }
        }

        init?(rawValue: Int) {
            switch RawResponseCode(rawValue: rawValue) {
            case .accountDoesNotExist:
                self = .accountDoesNotExist
            case .tooManyWireguardKeys:
                self = .tooManyWireguardKeys
            case .none:
                self = ResponseCode.other(rawValue)
            }
        }

        case accountDoesNotExist
        case tooManyWireguardKeys
        case other(Int)
    }

    /// An error type emitted by `MullvadAPI`
    enum Error: Swift.Error {
        /// A network communication error
        case network(URLError)

        /// An error occured when decoding the JSON response
        case decoding(Swift.Error)

        /// An error occured when encoding the JSON request
        case encoding(Swift.Error)
    }

    typealias ResponseError = JsonRpcResponseError<ResponseCode>
    typealias Response<T: Decodable> = JsonRpcResponse<T, ResponseCode>

    init(session: URLSession = URLSession.shared) {
        self.session = session
    }

    func getRelayList() -> AnyPublisher<Response<RelayList>, MullvadAPI.Error> {
        let request = JsonRpcRequest(method: "relay_list_v3", params: [])

        return MullvadAPI.makeDataTaskPublisher(request: request)
    }

    func getAccountExpiry(accountToken: String) -> AnyPublisher<Response<Date>, MullvadAPI.Error> {
        let request = JsonRpcRequest(method: "get_expiry", params: [AnyEncodable(accountToken)])

        return MullvadAPI.makeDataTaskPublisher(request: request)
    }

    func verifyAccount(accountToken: String) -> AnyPublisher<AccountVerification, Never> {
        return getAccountExpiry(accountToken: accountToken)
            .map({ (response) -> AccountVerification in
                switch response.result {
                case .success(let expiry):
                    // Report .verified when expiry is successfully received
                    return .verified(expiry)

                case .failure(let serverError):
                    if case .accountDoesNotExist = serverError.code {
                        // Report .invalid account if the server responds with the special code
                        return .invalid
                    } else {
                        // Otherwise report .deferred and pass the server error along
                        return .deferred(.server(serverError))
                    }
                }
            })
            .catch({ (networkError) in
                // Treat all communication errors as .deferred verification
                return Just(.deferred(.communication(networkError)))
            })
            .eraseToAnyPublisher()
    }

    func pushWireguardKey(accountToken: String, publicKey: Data) -> AnyPublisher<Response<WireguardAssociatedAddresses>, MullvadAPI.Error> {
        let request = JsonRpcRequest(method: "push_wg_key", params: [
            AnyEncodable(accountToken),
            AnyEncodable(publicKey)
        ])

        return MullvadAPI.makeDataTaskPublisher(request: request)
    }

    func replaceWireguardKey(accountToken: String, oldPublicKey: Data, newPublicKey: Data) -> AnyPublisher<Response<WireguardAssociatedAddresses>, MullvadAPI.Error> {
        let request = JsonRpcRequest(method: "replace_wg_key", params: [
            AnyEncodable(accountToken),
            AnyEncodable(oldPublicKey),
            AnyEncodable(newPublicKey)
        ])

        return MullvadAPI.makeDataTaskPublisher(request: request)
    }

    func checkWireguardKey(accountToken: String, publicKey: Data) -> AnyPublisher<Response<Bool>, MullvadAPI.Error> {
        let request = JsonRpcRequest(method: "check_wg_key", params: [
            AnyEncodable(accountToken),
            AnyEncodable(publicKey)
        ])

        return MullvadAPI.makeDataTaskPublisher(request: request)
    }

    func removeWireguardKey(accountToken: String, publicKey: Data) -> AnyPublisher<Response<Bool>, MullvadAPI.Error> {
        let request = JsonRpcRequest(method: "remove_wg_key", params: [
            AnyEncodable(accountToken),
            AnyEncodable(publicKey)
        ])

        return MullvadAPI.makeDataTaskPublisher(request: request)
    }

    private static func makeDataTaskPublisher<T: Decodable>(request: JsonRpcRequest) -> AnyPublisher<Response<T>, MullvadAPI.Error> {
        return Just(request)
            .encode(encoder: makeJSONEncoder())
            .mapError { MullvadAPI.Error.encoding($0) }
            .map { self.makeURLRequest(httpBody: $0) }
            .flatMap {
                URLSession.shared.dataTaskPublisher(for: $0)
                    .mapError { MullvadAPI.Error.network($0) }
                    .flatMap { (data, response) in
                        Just(data)
                            .decode(type: Response<T>.self, decoder: makeJSONDecoder())
                            .mapError { MullvadAPI.Error.decoding($0) }
                }
        }.eraseToAnyPublisher()
    }

    private static func makeURLRequest(httpBody: Data) -> URLRequest {
        var request = URLRequest(url: kMullvadAPIURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: kNetworkTimeout)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        request.httpBody = httpBody

        return request
    }

    private static func makeJSONEncoder() -> JSONEncoder {
        let encoder = JSONEncoder()
        encoder.keyEncodingStrategy = .convertToSnakeCase
        encoder.dateEncodingStrategy = .iso8601
        encoder.dataEncodingStrategy = .base64
        return encoder
    }

    private static func makeJSONDecoder() -> JSONDecoder {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        decoder.dateDecodingStrategy = .iso8601
        decoder.dataDecodingStrategy = .base64
        return decoder
    }
}


extension JsonRpcResponseError: LocalizedError
    where
    ResponseCode == MullvadAPI.ResponseCode
{
    var errorDescription: String? {
        switch code {
        case .accountDoesNotExist:
            return NSLocalizedString("Invalid account", comment: "")

        case .tooManyWireguardKeys:
            return NSLocalizedString("Too many public WireGuard keys", comment: "")

        case .other:
            return nil
        }
    }

    var recoverySuggestion: String? {
        switch code {
        case .tooManyWireguardKeys:
            return NSLocalizedString("Remove unused WireGuard keys", comment: "")

        default:
            return nil
        }
    }
}