|
| 1 | +// |
| 2 | +// PasswordSourceResolver.swift |
| 3 | +// TablePro |
| 4 | +// |
| 5 | + |
| 6 | +import Foundation |
| 7 | +import os |
| 8 | + |
| 9 | +/// Resolves a connection password from an external source declared in connections.json. |
| 10 | +/// File and command sources require a non-sandboxed build; TablePro ships with the hardened |
| 11 | +/// runtime and no App Sandbox, so spawning a process and reading arbitrary files is allowed. |
| 12 | +enum PasswordSourceResolver { |
| 13 | + private static let logger = Logger(subsystem: "com.TablePro", category: "PasswordSourceResolver") |
| 14 | + |
| 15 | + private static let commandTimeoutSeconds: UInt64 = 30 |
| 16 | + private static let maxOutputBytes = 1_048_576 |
| 17 | + |
| 18 | + enum ResolutionError: LocalizedError { |
| 19 | + case fileNotFound(path: String) |
| 20 | + case fileUnreadable(path: String) |
| 21 | + case environmentVariableNotSet(name: String) |
| 22 | + case commandFailed(exitCode: Int32, stderr: String) |
| 23 | + case commandTimedOut |
| 24 | + case outputTooLarge |
| 25 | + case emptyPassword |
| 26 | + |
| 27 | + var errorDescription: String? { |
| 28 | + switch self { |
| 29 | + case let .fileNotFound(path): |
| 30 | + return String(format: String(localized: "Password file not found: %@"), path) |
| 31 | + case let .fileUnreadable(path): |
| 32 | + return String(format: String(localized: "Could not read password file: %@"), path) |
| 33 | + case let .environmentVariableNotSet(name): |
| 34 | + return String( |
| 35 | + format: String(localized: """ |
| 36 | + Environment variable %@ is not set in TablePro's environment. \ |
| 37 | + Apps launched from the Dock do not inherit shell exports. Launch TablePro \ |
| 38 | + from a terminal, or set the variable with launchctl setenv. |
| 39 | + """), |
| 40 | + name |
| 41 | + ) |
| 42 | + case let .commandFailed(exitCode, stderr): |
| 43 | + let message = stderr.trimmingCharacters(in: .whitespacesAndNewlines) |
| 44 | + if message.isEmpty { |
| 45 | + return String(format: String(localized: "Password command failed with exit code %d"), exitCode) |
| 46 | + } |
| 47 | + return String(format: String(localized: "Password command failed (exit %d): %@"), exitCode, message) |
| 48 | + case .commandTimedOut: |
| 49 | + return String(localized: "Password command timed out after 30 seconds") |
| 50 | + case .outputTooLarge: |
| 51 | + return String(localized: "Password command produced too much output") |
| 52 | + case .emptyPassword: |
| 53 | + return String(localized: "The password source produced an empty password") |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + static func resolve(_ source: PasswordSource) async throws -> String { |
| 59 | + switch source { |
| 60 | + case let .file(path): |
| 61 | + return try resolveFile(path: path) |
| 62 | + case let .env(variable): |
| 63 | + return try resolveEnvironment(variable: variable) |
| 64 | + case let .command(shell): |
| 65 | + return try await resolveCommand(shell: shell, timeoutSeconds: commandTimeoutSeconds) |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + private static func resolveFile(path: String) throws -> String { |
| 70 | + let expandedPath = (path as NSString).expandingTildeInPath |
| 71 | + guard FileManager.default.fileExists(atPath: expandedPath) else { |
| 72 | + throw ResolutionError.fileNotFound(path: expandedPath) |
| 73 | + } |
| 74 | + warnIfPermissionsInsecure(path: expandedPath) |
| 75 | + guard let contents = try? String(contentsOfFile: expandedPath, encoding: .utf8) else { |
| 76 | + throw ResolutionError.fileUnreadable(path: expandedPath) |
| 77 | + } |
| 78 | + return try nonEmpty(contents.trimmingCharacters(in: .whitespacesAndNewlines)) |
| 79 | + } |
| 80 | + |
| 81 | + private static func resolveEnvironment(variable: String) throws -> String { |
| 82 | + guard let value = ProcessInfo.processInfo.environment[variable] else { |
| 83 | + throw ResolutionError.environmentVariableNotSet(name: variable) |
| 84 | + } |
| 85 | + return try nonEmpty(value.trimmingCharacters(in: .whitespacesAndNewlines)) |
| 86 | + } |
| 87 | + |
| 88 | + static func resolveCommand(shell: String, timeoutSeconds: UInt64) async throws -> String { |
| 89 | + let output = try await Task.detached(priority: .userInitiated) { () throws -> String in |
| 90 | + let process = Process() |
| 91 | + process.executableURL = URL(fileURLWithPath: "/bin/bash") |
| 92 | + process.arguments = ["-c", shell] |
| 93 | + process.environment = augmentedEnvironment() |
| 94 | + process.standardInput = FileHandle.nullDevice |
| 95 | + |
| 96 | + let stdoutPipe = Pipe() |
| 97 | + let stderrPipe = Pipe() |
| 98 | + process.standardOutput = stdoutPipe |
| 99 | + process.standardError = stderrPipe |
| 100 | + |
| 101 | + let stdoutCollector = PipeDataCollector(maxBytes: maxOutputBytes) |
| 102 | + let stderrCollector = PipeDataCollector(maxBytes: maxOutputBytes) |
| 103 | + stdoutPipe.fileHandleForReading.readabilityHandler = { handle in |
| 104 | + let chunk = handle.availableData |
| 105 | + guard !chunk.isEmpty else { return } |
| 106 | + stdoutCollector.append(chunk) |
| 107 | + if stdoutCollector.overflowed, process.isRunning { |
| 108 | + process.terminate() |
| 109 | + } |
| 110 | + } |
| 111 | + stderrPipe.fileHandleForReading.readabilityHandler = { handle in |
| 112 | + let chunk = handle.availableData |
| 113 | + if !chunk.isEmpty { stderrCollector.append(chunk) } |
| 114 | + } |
| 115 | + |
| 116 | + try process.run() |
| 117 | + |
| 118 | + let didTimeout = AtomicFlag() |
| 119 | + let timeoutTask = Task.detached { |
| 120 | + try await Task.sleep(nanoseconds: timeoutSeconds * 1_000_000_000) |
| 121 | + if process.isRunning { |
| 122 | + didTimeout.set() |
| 123 | + process.terminate() |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + process.waitUntilExit() |
| 128 | + timeoutTask.cancel() |
| 129 | + |
| 130 | + stdoutPipe.fileHandleForReading.readabilityHandler = nil |
| 131 | + stderrPipe.fileHandleForReading.readabilityHandler = nil |
| 132 | + |
| 133 | + if stdoutCollector.overflowed { |
| 134 | + throw ResolutionError.outputTooLarge |
| 135 | + } |
| 136 | + if didTimeout.isSet { |
| 137 | + throw ResolutionError.commandTimedOut |
| 138 | + } |
| 139 | + if process.terminationStatus != 0 { |
| 140 | + throw ResolutionError.commandFailed( |
| 141 | + exitCode: process.terminationStatus, |
| 142 | + stderr: stderrCollector.string |
| 143 | + ) |
| 144 | + } |
| 145 | + return stdoutCollector.string |
| 146 | + }.value |
| 147 | + |
| 148 | + guard !output.contains("\0") else { |
| 149 | + throw ResolutionError.emptyPassword |
| 150 | + } |
| 151 | + return try nonEmpty(output.trimmingCharacters(in: .whitespacesAndNewlines)) |
| 152 | + } |
| 153 | + |
| 154 | + private static func augmentedEnvironment() -> [String: String] { |
| 155 | + var environment = ProcessInfo.processInfo.environment |
| 156 | + let toolPaths = ["/usr/local/bin", "/opt/homebrew/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"] |
| 157 | + var pathComponents = (environment["PATH"] ?? "").split(separator: ":").map(String.init) |
| 158 | + for toolPath in toolPaths where !pathComponents.contains(toolPath) { |
| 159 | + pathComponents.append(toolPath) |
| 160 | + } |
| 161 | + environment["PATH"] = pathComponents.joined(separator: ":") |
| 162 | + return environment |
| 163 | + } |
| 164 | + |
| 165 | + private static func warnIfPermissionsInsecure(path: String) { |
| 166 | + guard let attributes = try? FileManager.default.attributesOfItem(atPath: path), |
| 167 | + let permissions = attributes[.posixPermissions] as? Int else { |
| 168 | + return |
| 169 | + } |
| 170 | + if permissions & 0o077 != 0 { |
| 171 | + logger.warning("Password file is group or world accessible; restrict it with chmod 600") |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + private static func nonEmpty(_ password: String) throws -> String { |
| 176 | + guard !password.isEmpty else { |
| 177 | + throw ResolutionError.emptyPassword |
| 178 | + } |
| 179 | + return password |
| 180 | + } |
| 181 | +} |
| 182 | + |
| 183 | +private final class PipeDataCollector: @unchecked Sendable { |
| 184 | + private let lock = NSLock() |
| 185 | + private let maxBytes: Int |
| 186 | + private var data = Data() |
| 187 | + private var didOverflow = false |
| 188 | + |
| 189 | + init(maxBytes: Int) { |
| 190 | + self.maxBytes = maxBytes |
| 191 | + } |
| 192 | + |
| 193 | + func append(_ chunk: Data) { |
| 194 | + lock.lock() |
| 195 | + defer { lock.unlock() } |
| 196 | + let remaining = maxBytes - data.count |
| 197 | + guard remaining > 0 else { |
| 198 | + didOverflow = true |
| 199 | + return |
| 200 | + } |
| 201 | + if chunk.count > remaining { |
| 202 | + data.append(chunk.prefix(remaining)) |
| 203 | + didOverflow = true |
| 204 | + } else { |
| 205 | + data.append(chunk) |
| 206 | + } |
| 207 | + } |
| 208 | + |
| 209 | + var overflowed: Bool { |
| 210 | + lock.lock() |
| 211 | + defer { lock.unlock() } |
| 212 | + return didOverflow |
| 213 | + } |
| 214 | + |
| 215 | + var string: String { |
| 216 | + lock.lock() |
| 217 | + defer { lock.unlock() } |
| 218 | + return String(data: data, encoding: .utf8) ?? "" |
| 219 | + } |
| 220 | +} |
| 221 | + |
| 222 | +private final class AtomicFlag: @unchecked Sendable { |
| 223 | + private let lock = NSLock() |
| 224 | + private var value = false |
| 225 | + |
| 226 | + func set() { |
| 227 | + lock.lock() |
| 228 | + value = true |
| 229 | + lock.unlock() |
| 230 | + } |
| 231 | + |
| 232 | + var isSet: Bool { |
| 233 | + lock.lock() |
| 234 | + defer { lock.unlock() } |
| 235 | + return value |
| 236 | + } |
| 237 | +} |
0 commit comments