import Foundation import Security /// A Google Cloud service account key (the JSON file from IAM → Service accounts → Keys). /// Signs the RS256 JWT that Google exchanges for an access token. Give the service account /// Viewer access in GA4 and it reads the same properties as a signed-in user. struct ServiceAccount { let clientEmail: String let privateKey: SecKey init(json: String) throws { guard let object = try? JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any], object["type"] as? String == "service_account", let email = object["client_email"] as? String, let pem = object["private_key"] as? String else { throw AnalyticsError.badResponse("Google service account key") } clientEmail = email privateKey = try Self.rsaKey(pem: pem) } /// JWT valid for one hour, for scope analytics.readonly. func assertion(now: Date = .now) throws -> String { let header = try JSONSerialization.data(withJSONObject: ["alg": "RS256", "typ": "JWT"]) let iat = Int(now.timeIntervalSince1970) let payload = try JSONSerialization.data(withJSONObject: [ "iss": clientEmail, "scope": GoogleAuth.serviceAccountScope, "aud": "https://oauth2.googleapis.com/token", "iat": iat, "exp": iat + 3600 ]) let signingInput = header.base64URL + "." + payload.base64URL var error: Unmanaged? guard let signature = SecKeyCreateSignature(privateKey, .rsaSignatureMessagePKCS1v15SHA256, Data(signingInput.utf8) as CFData, &error) else { throw AnalyticsError.badResponse("Service account signature: \(error?.takeRetainedValue().localizedDescription ?? "unknown")") } return signingInput + "." + (signature as Data).base64URL } /// Google ships PKCS#8 PEM; Security wants the PKCS#1 key inside it. static func rsaKey(pem: String) throws -> SecKey { let base64 = pem.components(separatedBy: .newlines).filter { !$0.hasPrefix("-----") }.joined() guard let der = Data(base64Encoded: base64) else { throw AnalyticsError.badResponse("Service account private key") } let attributes: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate] var error: Unmanaged? guard let key = SecKeyCreateWithData((pkcs1(fromPKCS8: der) ?? der) as CFData, attributes as CFDictionary, &error) else { throw AnalyticsError.badResponse("Service account private key: \(error?.takeRetainedValue().localizedDescription ?? "unknown")") } return key } /// PrivateKeyInfo ::= SEQUENCE { version INTEGER, algorithm SEQUENCE, privateKey OCTET STRING }. /// Returns the OCTET STRING contents, or nil when the input is not PKCS#8. static func pkcs1(fromPKCS8 der: Data) -> Data? { let bytes = [UInt8](der) var i = 0 func element(_ tag: UInt8) -> Range? { guard i < bytes.count, bytes[i] == tag, i + 1 < bytes.count else { return nil } i += 1 var length = Int(bytes[i]); i += 1 if length & 0x80 != 0 { let count = length & 0x7f guard count <= 4, i + count <= bytes.count else { return nil } length = bytes[i..<(i + count)].reduce(0) { $0 << 8 | Int($1) } i += count } guard i + length <= bytes.count else { return nil } defer { i += length } return i..<(i + length) } guard let outer = element(0x30) else { return nil } i = outer.lowerBound guard element(0x02) != nil, element(0x30) != nil, let key = element(0x04) else { return nil } return Data(bytes[key]) } }