SPB Git

Repository Public

KnownHostsInspector.swift 4.0 KB 100 lines swift

1import Foundation2internal import SPProcess34/// Captured result of a helper process.5public struct SSHProcessResult: Sendable, Hashable {6    public var exitStatus: Int327    public var standardOutput: String8    public var standardError: String910    public init(exitStatus: Int32, standardOutput: String = "", standardError: String = "") {11        self.exitStatus = exitStatus12        self.standardOutput = standardOutput13        self.standardError = standardError14    }15}1617/// Runs a helper executable with an explicit argv; injectable for tests.18public protocol SSHProcessRunning: Sendable {19    func run(executable: String, arguments: [String]) async throws -> SSHProcessResult20}2122/// Default ``SSHProcessRunning``: `Process` without a shell, 10 s timeout, 1 MiB of captured output.23public struct SystemProcessRunner: SSHProcessRunning {24    public init() {}2526    public func run(executable: String, arguments: [String]) async throws -> SSHProcessResult {27        let output = try await runProcess(28            executable: URL(fileURLWithPath: executable),29            arguments: arguments,30            timeout: .seconds(10),31            maxOutputBytes: 1 << 2032        )33        return SSHProcessResult(34            exitStatus: output.timedOut ? -1 : output.exitStatus,35            standardOutput: String(decoding: output.standardOutput, as: UTF8.self),36            standardError: String(decoding: output.standardError, as: UTF8.self)37        )38    }39}4041/// Whether a host key is already recorded in `known_hosts`.42public enum KnownHostStatus: String, Sendable, Codable, Hashable {43    /// At least one key is recorded for the host.44    case known45    /// The file was searched (or does not exist) and holds no key for the host.46    case unknown47    /// The lookup could not be performed (invalid host, tool failure, timeout).48    case indeterminate49}5051/// Read-only lookup in `known_hosts` through `/usr/bin/ssh-keygen -F`. Never modifies the file.52public struct KnownHostsInspector: Sendable {53    public static let sshKeygenPath = "/usr/bin/ssh-keygen"5455    private let runner: any SSHProcessRunning56    private let knownHostsFile: String?5758    /// - Parameter knownHostsFile: file to search; `nil` uses ssh-keygen's default (`~/.ssh/known_hosts`).59    public init(runner: any SSHProcessRunning = SystemProcessRunner(), knownHostsFile: String? = nil) {60        self.runner = runner61        self.knownHostsFile = knownHostsFile62    }6364    /// The exact ssh-keygen arguments used for a lookup, or `nil` when host or port is invalid.65    public func arguments(host: String, port: Int? = nil) -> [String]? {66        guard (try? SSHCommandBuilder.validateHost(host)) != nil else { return nil }67        var target = host68        if let port, port != 22 {69            guard (1...65535).contains(port) else { return nil }70            target = "[\(host)]:\(port)"71        }72        var arguments = ["-F", target]73        if let knownHostsFile {74            guard !knownHostsFile.isEmpty, !knownHostsFile.hasPrefix("-") else { return nil }75            arguments += ["-f", knownHostsFile]76        }77        return arguments78    }7980    /// Looks up `host` (the real host name, not a config alias) and optional non-default `port`.81    public func status(host: String, port: Int? = nil) async -> KnownHostStatus {82        guard let arguments = arguments(host: host, port: port) else { return .indeterminate }83        guard let result = try? await runner.run(executable: Self.sshKeygenPath, arguments: arguments) else {84            return .indeterminate85        }86        switch result.exitStatus {87        case 0:88            let hasEntry = result.standardOutput.split(whereSeparator: \.isNewline).contains {89                !$0.hasPrefix("#") && !$0.allSatisfy(\.isWhitespace)90            }91            return hasEntry ? .known : .indeterminate92        case 1:93            return .unknown94        default:95            // No known_hosts file at all: nothing is known yet.96            return result.standardError.contains("No such file or directory") ? .unknown : .indeterminate97        }98    }99}100
Files main
Menu

Theme