Created
March 10, 2021 23:46
-
-
Save hfhbd/5084cb6e0c67e49f37886075cc57d83e to your computer and use it in GitHub Desktop.
Apple CloudKit ServerSide API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Copyright 2021 Philip Wedemann | |
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 CryptoKit | |
import Foundation | |
import Combine | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
/** | |
New generated EC Keys for mail/demonstration purpose only | |
To generate the private key using the supported | |
PKCS8 format, use the following commands: | |
``` | |
openssl ecparam -name prime256v1 -out gen.pem -genkey -noout | |
openssl pkcs8 -topk8 -in gen.pem -nocrypt -out privateKey.pem | |
``` | |
To retrieve the private key use `cat privateKey.pem`, for the public key use `openssl ec -in privateKey.pem -pubout`. | |
*/ | |
let privateKey = """ | |
-----BEGIN PRIVATE KEY----- | |
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgkqBrp/uLPWNECNJn | |
IA1ay7rWLRdbpF43VZzoZB8j2BihRANCAARHCbhVIBYtMbfyu11OklgmvldThRbw | |
6Bwaj9TqU6C+K5hQOA6WHEYV4k3qKXSVhhBzA+69k952UjCuO9G+q4XS | |
-----END PRIVATE KEY----- | |
""" | |
let publicKey = """ | |
-----BEGIN PUBLIC KEY----- | |
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAERwm4VSAWLTG38rtdTpJYJr5XU4UW | |
8OgcGo/U6lOgviuYUDgOlhxGFeJN6il0lYYQcwPuvZPedlIwrjvRvquF0g== | |
-----END PUBLIC KEY----- | |
""" | |
struct Request { | |
let keyID: String | |
let date: String | |
let signature: String | |
let body: String | |
let subPath: String | |
} | |
func createCKRequest(keyID: String, body: String, subPath: String) -> Request { | |
let isoDateFormatter = ISO8601DateFormatter() | |
let date = isoDateFormatter.string(from: Date()) | |
body | |
let hashedBody = Data(SHA256.hash(data: body.data(using: .utf8)!)).base64EncodedString() | |
let dataToSign = "\(date):\(hashedBody):\(subPath)".data(using: .utf8)! | |
let signer = try! P256.Signing.PrivateKey(pemRepresentation: privateKey) | |
let signatureData = try! signer.signature(for: dataToSign) | |
let signature = signatureData.derRepresentation.base64EncodedString() | |
guard try! P256.Signing.PublicKey(pemRepresentation: publicKey).isValidSignature(signatureData, for: dataToSign) else { | |
fatalError("invalid signature") | |
} | |
return Request(keyID: keyID, date: date, signature: signature, body: body, subPath: subPath) | |
} | |
struct Lookup: Codable { | |
let users: [Value] | |
struct Value: Codable { | |
let emailAddress: String | |
} | |
} | |
func createBody(lookupEmail: String) -> String { | |
let body = Lookup(users: [Lookup.Value(emailAddress: "[\(lookupEmail)]")]) | |
let jsonData = try! JSONEncoder().encode(body) | |
return String(data: jsonData, encoding: .utf8)! | |
} | |
enum Err: Error { | |
case badData(Data) | |
case network(URLError) | |
} | |
func curl(header: [String: String], body: String, path: String) -> AnyPublisher<String, Error> { | |
// sent POST request using curl | |
var request = URLRequest(url: URL(string: path)!) | |
request.httpMethod = "POST" | |
request.httpBody = body.data(using: .utf8) | |
for (header, value) in header { | |
request.setValue(value, forHTTPHeaderField: header) | |
} | |
return URLSession.shared.dataTaskPublisher(for: request) | |
.mapError { | |
Err.network($0) | |
} | |
.tryMap { | |
guard let string = String(data: $0.data, encoding: .utf8) else { throw | |
Err.badData($0.data) | |
} | |
return string | |
} | |
.eraseToAnyPublisher() | |
} | |
let request = createCKRequest(keyID: "7188dd48...", body: createBody(lookupEmail: "[email protected]"), subPath: "/database/1/iCloud.wedemann.test/development/public/users/lookup/email") | |
let cancel = curl(header: [ | |
"X-Apple-CloudKit-Request-KeyID": request.keyID, | |
"X-Apple-CloudKit-Request-ISO8601Date": request.date, | |
"X-Apple-CloudKit-Request-SignatureV1": request.signature | |
], body: request.body, | |
path: "https://api.apple-cloudkit.com" + request.subPath | |
).sink { completion in | |
switch(completion) { | |
case .finished: | |
break | |
case .failure(let error): | |
print(error) | |
} | |
PlaygroundPage.current.finishExecution() | |
} receiveValue: { result in | |
print(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment