session-ios/SignalServiceKit/src/Loki/API/LokiDotNetAPI.swift

215 lines
12 KiB
Swift
Raw Normal View History

2019-09-26 03:32:47 +02:00
import PromiseKit
import SignalMetadataKit
2019-09-26 03:32:47 +02:00
/// Base class for `LokiFileServerAPI` and `LokiPublicChatAPI`.
2019-09-26 03:32:47 +02:00
public class LokiDotNetAPI : NSObject {
2020-02-17 05:14:00 +01:00
2019-09-26 03:32:47 +02:00
// MARK: Convenience
internal static let storage = OWSPrimaryStorage.shared()
2019-10-02 05:34:34 +02:00
internal static let userKeyPair = OWSIdentityManager.shared().identityKeyPair()!
2019-09-26 03:32:47 +02:00
internal static let userHexEncodedPublicKey = userKeyPair.hexEncodedPublicKey
// MARK: Settings
private static let attachmentType = "network.loki"
2019-09-26 03:32:47 +02:00
// MARK: Error
@objc public class LokiDotNetAPIError : NSError { // Not called `Error` for Obj-C interoperablity
2020-02-10 05:47:15 +01:00
@objc public static let generic = LokiDotNetAPIError(domain: "LokiDotNetAPIErrorDomain", code: 1, userInfo: [ NSLocalizedDescriptionKey : "An error occurred." ])
@objc public static let parsingFailed = LokiDotNetAPIError(domain: "LokiDotNetAPIErrorDomain", code: 2, userInfo: [ NSLocalizedDescriptionKey : "Invalid file server response." ])
@objc public static let signingFailed = LokiDotNetAPIError(domain: "LokiDotNetAPIErrorDomain", code: 3, userInfo: [ NSLocalizedDescriptionKey : "Couldn't sign message." ])
@objc public static let encryptionFailed = LokiDotNetAPIError(domain: "LokiDotNetAPIErrorDomain", code: 4, userInfo: [ NSLocalizedDescriptionKey : "Couldn't encrypt file." ])
@objc public static let decryptionFailed = LokiDotNetAPIError(domain: "LokiDotNetAPIErrorDomain", code: 5, userInfo: [ NSLocalizedDescriptionKey : "Couldn't decrypt file." ])
@objc public static let maxFileSizeExceeded = LokiDotNetAPIError(domain: "LokiDotNetAPIErrorDomain", code: 6, userInfo: [ NSLocalizedDescriptionKey : "Maximum file size exceeded." ])
2019-09-26 03:32:47 +02:00
}
// MARK: Database
/// To be overridden by subclasses.
internal class var authTokenCollection: String { preconditionFailure("authTokenCollection is abstract and must be overridden.") }
private static func getAuthTokenFromDatabase(for server: String, in transaction: YapDatabaseReadTransaction? = nil) -> String? {
func getAuthTokenInternal(in transaction: YapDatabaseReadTransaction) -> String? {
return transaction.object(forKey: server, inCollection: authTokenCollection) as! String?
}
if let transaction = transaction {
return getAuthTokenInternal(in: transaction)
} else {
var result: String? = nil
storage.dbReadConnection.read { transaction in
result = getAuthTokenInternal(in: transaction)
}
return result
2019-09-26 03:32:47 +02:00
}
}
2020-02-17 05:14:00 +01:00
internal static func getAuthToken(for server: String, in transaction: YapDatabaseReadWriteTransaction? = nil) -> Promise<String> {
if let token = getAuthTokenFromDatabase(for: server, in: transaction) {
return Promise.value(token)
} else {
2020-04-07 03:18:55 +02:00
return requestNewAuthToken(for: server).then(on: LokiAPI.workQueue) { submitAuthToken($0, for: server) }.map { token -> String in
2020-02-17 05:14:00 +01:00
setAuthToken(for: server, to: token, in: transaction)
return token
}
}
}
2019-09-26 03:32:47 +02:00
private static func setAuthToken(for server: String, to newValue: String, in transaction: YapDatabaseReadWriteTransaction? = nil) {
func setAuthTokenInternal(in transaction: YapDatabaseReadWriteTransaction) {
2019-09-26 03:32:47 +02:00
transaction.setObject(newValue, forKey: server, inCollection: authTokenCollection)
}
2020-02-26 03:58:36 +01:00
if let transaction = transaction, transaction.connection.pendingTransactionCount != 0 {
setAuthTokenInternal(in: transaction)
} else {
storage.dbReadWriteConnection.readWrite { transaction in
setAuthTokenInternal(in: transaction)
}
}
2019-09-26 03:32:47 +02:00
}
// MARK: Lifecycle
override private init() { }
// MARK: Attachments (Public API)
public static func uploadAttachment(_ attachment: TSAttachmentStream, with attachmentID: String, to server: String) -> Promise<Void> {
let isEncryptionRequired = (server == LokiFileServerAPI.server)
return Promise<Void>() { seal in
func proceed(with token: String) {
// Get the attachment
let data: Data
guard let unencryptedAttachmentData = try? attachment.readDataFromFile() else {
print("[Loki] Couldn't read attachment from disk.")
return seal.reject(LokiDotNetAPIError.generic)
}
// Encrypt the attachment if needed
if isEncryptionRequired {
var encryptionKey = NSData()
var digest = NSData()
guard let encryptedAttachmentData = Cryptography.encryptAttachmentData(unencryptedAttachmentData, outKey: &encryptionKey, outDigest: &digest) else {
print("[Loki] Couldn't encrypt attachment.")
return seal.reject(LokiDotNetAPIError.encryptionFailed)
}
attachment.encryptionKey = encryptionKey as Data
attachment.digest = digest as Data
data = encryptedAttachmentData
} else {
data = unencryptedAttachmentData
}
2020-02-10 05:47:15 +01:00
// Check the file size if needed
let isLokiFileServer = (server == LokiFileServerAPI.server)
if isLokiFileServer && data.count > LokiFileServerAPI.maxFileSize {
return seal.reject(LokiDotNetAPIError.maxFileSizeExceeded)
2020-02-10 05:47:15 +01:00
}
// Create the request
let url = "\(server)/files"
let parameters: JSON = [ "type" : attachmentType, "Content-Type" : "application/binary" ]
var error: NSError?
var request = AFHTTPRequestSerializer().multipartFormRequest(withMethod: "POST", urlString: url, parameters: parameters, constructingBodyWith: { formData in
formData.appendPart(withFileData: data, name: "content", fileName: UUID().uuidString, mimeType: "application/binary")
}, error: &error)
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
if let error = error {
print("[Loki] Couldn't upload attachment due to error: \(error).")
return seal.reject(error)
}
// Send the request
2020-02-17 00:29:43 +01:00
func parseResponse(_ responseObject: Any) {
2020-02-03 10:55:42 +01:00
// Parse the server ID & download URL
2020-02-17 00:29:43 +01:00
guard let json = responseObject as? JSON, let data = json["data"] as? JSON, let serverID = data["id"] as? UInt64, let downloadURL = data["url"] as? String else {
print("[Loki] Couldn't parse attachment from: \(responseObject).")
return seal.reject(LokiDotNetAPIError.parsingFailed)
2020-02-03 10:55:42 +01:00
}
// Update the attachment
attachment.serverId = serverID
attachment.isUploaded = true
attachment.downloadURL = downloadURL
attachment.save()
seal.fulfill(())
}
let isProxyingRequired = (server == LokiFileServerAPI.server) // Don't proxy open group requests for now
2020-02-03 10:27:13 +01:00
if isProxyingRequired {
attachment.isUploaded = false
attachment.save()
2020-02-03 10:27:13 +01:00
let _ = LokiFileServerProxy(for: server).performLokiFileServerNSURLRequest(request as NSURLRequest).done { responseObject in
2020-02-03 10:55:42 +01:00
parseResponse(responseObject)
2020-02-03 06:50:14 +01:00
}.catch { error in
seal.reject(error)
}
2020-02-03 06:50:14 +01:00
} else {
let task = AFURLSessionManager(sessionConfiguration: .default).uploadTask(withStreamedRequest: request as URLRequest, progress: { rawProgress in
// Broadcast progress updates
let progress = max(0.1, rawProgress.fractionCompleted)
let userInfo: [String:Any] = [ kAttachmentUploadProgressKey : progress, kAttachmentUploadAttachmentIDKey : attachmentID ]
DispatchQueue.main.async {
NotificationCenter.default.post(name: .attachmentUploadProgress, object: nil, userInfo: userInfo)
}
}, completionHandler: { response, responseObject, error in
if let error = error {
print("[Loki] Couldn't upload attachment due to error: \(error).")
return seal.reject(error)
}
let statusCode = (response as! HTTPURLResponse).statusCode
let isSuccessful = (200...299) ~= statusCode
guard isSuccessful else {
print("[Loki] Couldn't upload attachment.")
return seal.reject(LokiDotNetAPIError.generic)
2020-02-03 06:50:14 +01:00
}
2020-02-03 10:55:42 +01:00
parseResponse(responseObject)
2020-02-03 06:50:14 +01:00
})
task.resume()
}
}
if server == LokiFileServerAPI.server {
2020-04-07 03:18:55 +02:00
LokiAPI.workQueue.async {
proceed(with: "loki") // Uploads to the Loki File Server shouldn't include any personally identifiable information so use a dummy auth token
}
} else {
2020-04-07 03:18:55 +02:00
getAuthToken(for: server).done(on: LokiAPI.workQueue) { token in
proceed(with: token)
}.catch { error in
print("[Loki] Couldn't upload attachment due to error: \(error).")
seal.reject(error)
}
}
}
}
2019-09-26 03:32:47 +02:00
// MARK: Private API
private static func requestNewAuthToken(for server: String) -> Promise<String> {
print("[Loki] Requesting auth token for server: \(server).")
let queryParameters = "pubKey=\(userHexEncodedPublicKey)"
let url = URL(string: "\(server)/loki/v1/get_challenge?\(queryParameters)")!
let request = TSRequest(url: url)
2020-04-07 03:18:55 +02:00
return LokiFileServerProxy(for: server).perform(request, withCompletionQueue: LokiAPI.workQueue).map(on: LokiAPI.workQueue) { rawResponse in
2019-09-26 03:32:47 +02:00
guard let json = rawResponse as? JSON, let base64EncodedChallenge = json["cipherText64"] as? String, let base64EncodedServerPublicKey = json["serverPubKey64"] as? String,
let challenge = Data(base64Encoded: base64EncodedChallenge), var serverPublicKey = Data(base64Encoded: base64EncodedServerPublicKey) else {
throw LokiDotNetAPIError.parsingFailed
2019-09-26 03:32:47 +02:00
}
// Discard the "05" prefix if needed
if serverPublicKey.count == 33 {
2019-10-02 05:34:34 +02:00
let hexEncodedServerPublicKey = serverPublicKey.toHexString()
2019-09-26 03:32:47 +02:00
serverPublicKey = Data.data(fromHex: hexEncodedServerPublicKey.substring(from: 2))!
}
// The challenge is prefixed by the 16 bit IV
guard let tokenAsData = try? DiffieHellman.decrypt(challenge, publicKey: serverPublicKey, privateKey: userKeyPair.privateKey),
let token = String(bytes: tokenAsData, encoding: .utf8) else {
throw LokiDotNetAPIError.decryptionFailed
2019-09-26 03:32:47 +02:00
}
return token
}
}
private static func submitAuthToken(_ token: String, for server: String) -> Promise<String> {
print("[Loki] Submitting auth token for server: \(server).")
let url = URL(string: "\(server)/loki/v1/submit_challenge")!
let parameters = [ "pubKey" : userHexEncodedPublicKey, "token" : token ]
let request = TSRequest(url: url, method: "POST", parameters: parameters)
2020-04-07 03:18:55 +02:00
return LokiFileServerProxy(for: server).perform(request, withCompletionQueue: LokiAPI.workQueue).map { _ in token }
2019-09-26 03:32:47 +02:00
}
// MARK: Attachments (Public Obj-C API)
@objc(uploadAttachment:withID:toServer:)
public static func objc_uploadAttachment(_ attachment: TSAttachmentStream, with attachmentID: String, to server: String) -> AnyPromise {
return AnyPromise.from(uploadAttachment(attachment, with: attachmentID, to: server))
}
2019-09-26 03:32:47 +02:00
}