Graphley / app · graphley.ai / Sources / AnalyticsKit / ServiceAccount.swift
| 1 | import Foundation |
| 2 | import Security |
| 3 | |
| 4 | /// A Google Cloud service account key (the JSON file from IAM → Service accounts → Keys). |
| 5 | /// Signs the RS256 JWT that Google exchanges for an access token. Give the service account |
| 6 | /// Viewer access in GA4 and it reads the same properties as a signed-in user. |
| 7 | struct ServiceAccount { |
| 8 | let clientEmail: String |
| 9 | let privateKey: SecKey |
| 10 | |
| 11 | init(json: String) throws { |
| 12 | guard let object = try? JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any], |
| 13 | object["type"] as? String == "service_account", |
| 14 | let email = object["client_email"] as? String, let pem = object["private_key"] as? String |
| 15 | else { throw AnalyticsError.badResponse("Google service account key") } |
| 16 | clientEmail = email |
| 17 | privateKey = try Self.rsaKey(pem: pem) |
| 18 | } |
| 19 | |
| 20 | /// JWT valid for one hour, for scope analytics.readonly. |
| 21 | func assertion(now: Date = .now) throws -> String { |
| 22 | let header = try JSONSerialization.data(withJSONObject: ["alg": "RS256", "typ": "JWT"]) |
| 23 | let iat = Int(now.timeIntervalSince1970) |
| 24 | let payload = try JSONSerialization.data(withJSONObject: [ |
| 25 | "iss": clientEmail, "scope": GoogleAuth.serviceAccountScope, "aud": "https://oauth2.googleapis.com/token", "iat": iat, "exp": iat + 3600 |
| 26 | ]) |
| 27 | let signingInput = header.base64URL + "." + payload.base64URL |
| 28 | var error: Unmanaged<CFError>? |
| 29 | guard let signature = SecKeyCreateSignature(privateKey, .rsaSignatureMessagePKCS1v15SHA256, Data(signingInput.utf8) as CFData, &error) else { |
| 30 | throw AnalyticsError.badResponse("Service account signature: \(error?.takeRetainedValue().localizedDescription ?? "unknown")") |
| 31 | } |
| 32 | return signingInput + "." + (signature as Data).base64URL |
| 33 | } |
| 34 | |
| 35 | /// Google ships PKCS#8 PEM; Security wants the PKCS#1 key inside it. |
| 36 | static func rsaKey(pem: String) throws -> SecKey { |
| 37 | let base64 = pem.components(separatedBy: .newlines).filter { !$0.hasPrefix("-----") }.joined() |
| 38 | guard let der = Data(base64Encoded: base64) else { throw AnalyticsError.badResponse("Service account private key") } |
| 39 | let attributes: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate] |
| 40 | var error: Unmanaged<CFError>? |
| 41 | guard let key = SecKeyCreateWithData((pkcs1(fromPKCS8: der) ?? der) as CFData, attributes as CFDictionary, &error) else { |
| 42 | throw AnalyticsError.badResponse("Service account private key: \(error?.takeRetainedValue().localizedDescription ?? "unknown")") |
| 43 | } |
| 44 | return key |
| 45 | } |
| 46 | |
| 47 | /// PrivateKeyInfo ::= SEQUENCE { version INTEGER, algorithm SEQUENCE, privateKey OCTET STRING }. |
| 48 | /// Returns the OCTET STRING contents, or nil when the input is not PKCS#8. |
| 49 | static func pkcs1(fromPKCS8 der: Data) -> Data? { |
| 50 | let bytes = [UInt8](der) |
| 51 | var i = 0 |
| 52 | func element(_ tag: UInt8) -> Range<Int>? { |
| 53 | guard i < bytes.count, bytes[i] == tag, i + 1 < bytes.count else { return nil } |
| 54 | i += 1 |
| 55 | var length = Int(bytes[i]); i += 1 |
| 56 | if length & 0x80 != 0 { |
| 57 | let count = length & 0x7f |
| 58 | guard count <= 4, i + count <= bytes.count else { return nil } |
| 59 | length = bytes[i..<(i + count)].reduce(0) { $0 << 8 | Int($1) } |
| 60 | i += count |
| 61 | } |
| 62 | guard i + length <= bytes.count else { return nil } |
| 63 | defer { i += length } |
| 64 | return i..<(i + length) |
| 65 | } |
| 66 | guard let outer = element(0x30) else { return nil } |
| 67 | i = outer.lowerBound |
| 68 | guard element(0x02) != nil, element(0x30) != nil, let key = element(0x04) else { return nil } |
| 69 | return Data(bytes[key]) |
| 70 | } |
| 71 | } |