|
| 1 | +// |
| 2 | +// SnowflakeAuth.swift |
| 3 | +// SnowflakeDriverPlugin |
| 4 | +// |
| 5 | +// Account identifier parsing, key-pair JWT generation, and |
| 6 | +// ~/.snowflake/connections.toml parsing. |
| 7 | +// |
| 8 | + |
| 9 | +import CryptoKit |
| 10 | +import Foundation |
| 11 | +import os |
| 12 | +import Security |
| 13 | + |
| 14 | +enum SnowflakeAccount { |
| 15 | + static func host(forAccount account: String) -> String { |
| 16 | + let trimmed = account.trimmingCharacters(in: .whitespacesAndNewlines) |
| 17 | + if trimmed.lowercased().hasSuffix(".snowflakecomputing.com") { |
| 18 | + return trimmed |
| 19 | + } |
| 20 | + if trimmed.contains("://") { |
| 21 | + return URL(string: trimmed)?.host ?? trimmed |
| 22 | + } |
| 23 | + return "\(trimmed).snowflakecomputing.com" |
| 24 | + } |
| 25 | + |
| 26 | + /// The account name used as the JWT issuer/subject prefix. Snowflake expects the |
| 27 | + /// account locator without any region/cloud segment, uppercased. |
| 28 | + static func issuerAccountName(forAccount account: String) -> String { |
| 29 | + var name = account.trimmingCharacters(in: .whitespacesAndNewlines) |
| 30 | + if name.lowercased().hasSuffix(".snowflakecomputing.com") { |
| 31 | + name = String(name.dropLast(".snowflakecomputing.com".count)) |
| 32 | + } |
| 33 | + if let dotIndex = name.firstIndex(of: ".") { |
| 34 | + name = String(name[..<dotIndex]) |
| 35 | + } |
| 36 | + return name.uppercased() |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +struct SnowflakeKeyPairAuth { |
| 41 | + private static let logger = Logger(subsystem: "com.TablePro", category: "SnowflakeKeyPairAuth") |
| 42 | + |
| 43 | + let account: String |
| 44 | + let user: String |
| 45 | + let privateKeyPEM: String |
| 46 | + let passphrase: String? |
| 47 | + |
| 48 | + func makeJWT(lifetime: TimeInterval = 3_540) throws -> String { |
| 49 | + let privateKey = try loadPrivateKey() |
| 50 | + let qualifiedUser = "\(SnowflakeAccount.issuerAccountName(forAccount: account)).\(user.uppercased())" |
| 51 | + let fingerprint = try publicKeyFingerprint(for: privateKey) |
| 52 | + let issuer = "\(qualifiedUser).\(fingerprint)" |
| 53 | + |
| 54 | + let now = Date() |
| 55 | + let iat = Int(now.timeIntervalSince1970) |
| 56 | + let exp = iat + Int(lifetime) |
| 57 | + |
| 58 | + let headerJSON = #"{"alg":"RS256","typ":"JWT"}"# |
| 59 | + let claimsJSON = #"{"iss":"\#(issuer)","sub":"\#(qualifiedUser)","iat":\#(iat),"exp":\#(exp)}"# |
| 60 | + |
| 61 | + let signingInput = "\(base64URL(Data(headerJSON.utf8))).\(base64URL(Data(claimsJSON.utf8)))" |
| 62 | + let signature = try sign(Data(signingInput.utf8), with: privateKey) |
| 63 | + return "\(signingInput).\(base64URL(signature))" |
| 64 | + } |
| 65 | + |
| 66 | + private func loadPrivateKey() throws -> SecKey { |
| 67 | + guard let pemData = privateKeyPEM.data(using: .utf8) else { |
| 68 | + throw SnowflakeError.authFailed("Private key is not valid UTF-8") |
| 69 | + } |
| 70 | + |
| 71 | + var inputFormat = SecExternalFormat.formatUnknown |
| 72 | + var itemType = SecExternalItemType.itemTypeUnknown |
| 73 | + var importedItems: CFArray? |
| 74 | + |
| 75 | + var keyParams = SecItemImportExportKeyParameters() |
| 76 | + var passphraseRef: CFTypeRef? |
| 77 | + if let passphrase, !passphrase.isEmpty { |
| 78 | + let ref = passphrase as CFString |
| 79 | + passphraseRef = ref |
| 80 | + keyParams.passphrase = Unmanaged.passUnretained(ref) |
| 81 | + } |
| 82 | + _ = passphraseRef |
| 83 | + |
| 84 | + let status = SecItemImport( |
| 85 | + pemData as CFData, |
| 86 | + "p8" as CFString, |
| 87 | + &inputFormat, |
| 88 | + &itemType, |
| 89 | + SecItemImportExportFlags(rawValue: 0), |
| 90 | + &keyParams, |
| 91 | + nil, |
| 92 | + &importedItems |
| 93 | + ) |
| 94 | + |
| 95 | + guard status == errSecSuccess, |
| 96 | + let items = importedItems as? [SecKey], |
| 97 | + let key = items.first |
| 98 | + else { |
| 99 | + throw SnowflakeError.authFailed( |
| 100 | + "Failed to load private key (OSStatus \(status)). Ensure the file is a valid RSA .p8 key and the passphrase is correct." |
| 101 | + ) |
| 102 | + } |
| 103 | + return key |
| 104 | + } |
| 105 | + |
| 106 | + private func publicKeyFingerprint(for privateKey: SecKey) throws -> String { |
| 107 | + guard let publicKey = SecKeyCopyPublicKey(privateKey) else { |
| 108 | + throw SnowflakeError.authFailed("Could not derive public key from private key") |
| 109 | + } |
| 110 | + var error: Unmanaged<CFError>? |
| 111 | + guard let pkcs1 = SecKeyCopyExternalRepresentation(publicKey, &error) as Data? else { |
| 112 | + let message = error?.takeRetainedValue().localizedDescription ?? "unknown error" |
| 113 | + throw SnowflakeError.authFailed("Could not export public key: \(message)") |
| 114 | + } |
| 115 | + let spki = Self.wrapPKCS1IntoSPKI(pkcs1) |
| 116 | + let digest = SHA256.hash(data: spki) |
| 117 | + return "SHA256:\(Data(digest).base64EncodedString())" |
| 118 | + } |
| 119 | + |
| 120 | + private func sign(_ data: Data, with key: SecKey) throws -> Data { |
| 121 | + var error: Unmanaged<CFError>? |
| 122 | + guard let signature = SecKeyCreateSignature( |
| 123 | + key, .rsaSignatureMessagePKCS1v15SHA256, data as CFData, &error |
| 124 | + ) as Data? else { |
| 125 | + let message = error?.takeRetainedValue().localizedDescription ?? "unknown error" |
| 126 | + throw SnowflakeError.authFailed("Failed to sign JWT: \(message)") |
| 127 | + } |
| 128 | + return signature |
| 129 | + } |
| 130 | + |
| 131 | + private func base64URL(_ data: Data) -> String { |
| 132 | + data.base64EncodedString() |
| 133 | + .replacingOccurrences(of: "+", with: "-") |
| 134 | + .replacingOccurrences(of: "/", with: "_") |
| 135 | + .replacingOccurrences(of: "=", with: "") |
| 136 | + } |
| 137 | + |
| 138 | + /// Wrap a PKCS#1 RSAPublicKey DER blob into a SubjectPublicKeyInfo DER blob, |
| 139 | + /// which is what Snowflake fingerprints with SHA-256. |
| 140 | + static func wrapPKCS1IntoSPKI(_ pkcs1: Data) -> Data { |
| 141 | + let rsaAlgorithmID: [UInt8] = [ |
| 142 | + 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, |
| 143 | + 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 |
| 144 | + ] |
| 145 | + var bitString: [UInt8] = [0x03] |
| 146 | + bitString += derLength(pkcs1.count + 1) |
| 147 | + bitString.append(0x00) |
| 148 | + bitString += [UInt8](pkcs1) |
| 149 | + |
| 150 | + var body = rsaAlgorithmID |
| 151 | + body += bitString |
| 152 | + |
| 153 | + var spki: [UInt8] = [0x30] |
| 154 | + spki += derLength(body.count) |
| 155 | + spki += body |
| 156 | + return Data(spki) |
| 157 | + } |
| 158 | + |
| 159 | + private static func derLength(_ length: Int) -> [UInt8] { |
| 160 | + if length < 0x80 { |
| 161 | + return [UInt8(length)] |
| 162 | + } |
| 163 | + var value = length |
| 164 | + var bytes: [UInt8] = [] |
| 165 | + while value > 0 { |
| 166 | + bytes.insert(UInt8(value & 0xFF), at: 0) |
| 167 | + value >>= 8 |
| 168 | + } |
| 169 | + return [UInt8(0x80 | bytes.count)] + bytes |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +enum SnowflakeConnectionsTOML { |
| 174 | + /// Look up the named connection in the Snowflake CLI's config files, checking |
| 175 | + /// ~/.snowflake/connections.toml first, then [connections.*] sections in |
| 176 | + /// ~/.snowflake/config.toml. Keys follow the CLI's snake_case naming |
| 177 | + /// (account, user, password, authenticator, private_key_file, role, ...). |
| 178 | + static func parameters(forConnection name: String) -> [String: String]? { |
| 179 | + for filename in ["connections.toml", "config.toml"] { |
| 180 | + let path = NSString(string: "~/.snowflake/\(filename)").expandingTildeInPath |
| 181 | + guard let contents = try? String(contentsOfFile: path, encoding: .utf8) else { continue } |
| 182 | + if let section = parse(contents)[name] { |
| 183 | + return section |
| 184 | + } |
| 185 | + } |
| 186 | + return nil |
| 187 | + } |
| 188 | + |
| 189 | + static func parse(_ contents: String) -> [String: [String: String]] { |
| 190 | + var sections: [String: [String: String]] = [:] |
| 191 | + var currentSection: String? |
| 192 | + |
| 193 | + for rawLine in contents.components(separatedBy: .newlines) { |
| 194 | + let line = stripComment(rawLine).trimmingCharacters(in: .whitespaces) |
| 195 | + if line.isEmpty { continue } |
| 196 | + |
| 197 | + if line.hasPrefix("[") && line.hasSuffix("]") { |
| 198 | + var name = String(line.dropFirst().dropLast()) |
| 199 | + if name.hasPrefix("connections.") { |
| 200 | + name = String(name.dropFirst("connections.".count)) |
| 201 | + } |
| 202 | + name = name.trimmingCharacters(in: CharacterSet(charactersIn: "\"'")) |
| 203 | + currentSection = name |
| 204 | + if sections[name] == nil { sections[name] = [:] } |
| 205 | + continue |
| 206 | + } |
| 207 | + |
| 208 | + guard let section = currentSection, |
| 209 | + let equalIndex = line.firstIndex(of: "=") else { continue } |
| 210 | + |
| 211 | + let key = line[..<equalIndex].trimmingCharacters(in: .whitespaces) |
| 212 | + let value = unquote(String(line[line.index(after: equalIndex)...]).trimmingCharacters(in: .whitespaces)) |
| 213 | + sections[section]?[key] = value |
| 214 | + } |
| 215 | + return sections |
| 216 | + } |
| 217 | + |
| 218 | + private static func stripComment(_ line: String) -> String { |
| 219 | + var inDoubleQuotes = false |
| 220 | + var inSingleQuotes = false |
| 221 | + var result = "" |
| 222 | + for char in line { |
| 223 | + if char == "\"" && !inSingleQuotes { inDoubleQuotes.toggle() } |
| 224 | + if char == "'" && !inDoubleQuotes { inSingleQuotes.toggle() } |
| 225 | + if char == "#" && !inDoubleQuotes && !inSingleQuotes { break } |
| 226 | + result.append(char) |
| 227 | + } |
| 228 | + return result |
| 229 | + } |
| 230 | + |
| 231 | + private static func unquote(_ value: String) -> String { |
| 232 | + if value.count >= 2, value.hasPrefix("\""), value.hasSuffix("\"") { |
| 233 | + return String(value.dropFirst().dropLast()) |
| 234 | + } |
| 235 | + if value.count >= 2, value.hasPrefix("'"), value.hasSuffix("'") { |
| 236 | + return String(value.dropFirst().dropLast()) |
| 237 | + } |
| 238 | + return value |
| 239 | + } |
| 240 | +} |
0 commit comments