SPB Git

Repository Public

KnownHostsAndClassifierTests.swift 8.6 KB 165 lines swift

1import Foundation2import Testing3@testable import SSHKit45final class FakeRunner: SSHProcessRunning, @unchecked Sendable {6    struct Failure: Error {}7    private let lock = NSLock()8    private var recorded: [(String, [String])] = []9    private let result: SSHProcessResult?1011    init(_ result: SSHProcessResult?) { self.result = result }1213    var calls: [(String, [String])] {14        lock.lock()15        defer { lock.unlock() }16        return recorded17    }1819    private func record(_ executable: String, _ arguments: [String]) {20        lock.lock()21        recorded.append((executable, arguments))22        lock.unlock()23    }2425    func run(executable: String, arguments: [String]) async throws -> SSHProcessResult {26        record(executable, arguments)27        guard let result else { throw Failure() }28        return result29    }30}3132@Suite struct KnownHostsInspectorTests {33    static let found = "# Host example.com found: line 3\nexample.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFake\n"3435    @Test func knownWhenSshKeygenPrintsAnEntry() async {36        let runner = FakeRunner(SSHProcessResult(exitStatus: 0, standardOutput: Self.found))37        #expect(await KnownHostsInspector(runner: runner).status(host: "example.com") == .known)38        #expect(runner.calls.count == 1)39        #expect(runner.calls[0].0 == "/usr/bin/ssh-keygen")40        #expect(runner.calls[0].1 == ["-F", "example.com"])41    }4243    @Test func unknownWhenNotFoundOrNoFile() async {44        let notFound = FakeRunner(SSHProcessResult(exitStatus: 1))45        #expect(await KnownHostsInspector(runner: notFound).status(host: "example.com") == .unknown)46        let noFile = FakeRunner(SSHProcessResult(exitStatus: 255, standardError: "Cannot stat /Users/x/.ssh/known_hosts: No such file or directory\n"))47        #expect(await KnownHostsInspector(runner: noFile).status(host: "example.com") == .unknown)48    }4950    @Test func indeterminateOnFailures() async {51        let cases: [SSHProcessResult?] = [52            nil,53            SSHProcessResult(exitStatus: 255, standardError: "ssh-keygen: something broke"),54            SSHProcessResult(exitStatus: -1),55            SSHProcessResult(exitStatus: 0, standardOutput: ""),56            SSHProcessResult(exitStatus: 0, standardOutput: "# only a comment\n"),57        ]58        for result in cases {59            #expect(await KnownHostsInspector(runner: FakeRunner(result)).status(host: "example.com") == .indeterminate)60        }61    }6263    @Test func portAndFileArguments() async {64        let runner = FakeRunner(SSHProcessResult(exitStatus: 1))65        let inspector = KnownHostsInspector(runner: runner, knownHostsFile: "/tmp/kh")66        _ = await inspector.status(host: "example.com", port: 2222)67        _ = await inspector.status(host: "example.com", port: 22)68        _ = await inspector.status(host: "::1", port: nil)69        #expect(runner.calls.map(\.1) == [70            ["-F", "[example.com]:2222", "-f", "/tmp/kh"],71            ["-F", "example.com", "-f", "/tmp/kh"],72            ["-F", "::1", "-f", "/tmp/kh"],73        ])74    }7576    @Test func invalidInputNeverReachesTheRunnerAndNoMutatingFlagIsUsed() async {77        let runner = FakeRunner(SSHProcessResult(exitStatus: 0, standardOutput: Self.found))78        let inspector = KnownHostsInspector(runner: runner)79        for host in ["", "-R", "-Rexample.com", "a b", "a;b", "$(id)"] {80            #expect(await inspector.status(host: host) == .indeterminate)81        }82        #expect(await inspector.status(host: "example.com", port: 0) == .indeterminate)83        #expect(await inspector.status(host: "example.com", port: 70000) == .indeterminate)84        #expect(await KnownHostsInspector(runner: runner, knownHostsFile: "-x").status(host: "example.com") == .indeterminate)85        #expect(runner.calls.isEmpty)8687        _ = await inspector.status(host: "example.com", port: 2200)88        let flags = runner.calls.flatMap(\.1).filter { $0.hasPrefix("-") }89        #expect(flags == ["-F"])90    }9192    /// Runs the real ssh-keygen against a throwaway file: local, read-only, no network.93    @Test func realSshKeygenAgainstTemporaryFile() async throws {94        let directory = FileManager.default.temporaryDirectory.appendingPathComponent("SSHKitTests-\(UUID().uuidString)")95        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)96        defer { try? FileManager.default.removeItem(at: directory) }97        let file = directory.appendingPathComponent("known_hosts")98        let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl"99        let contents = "known.example \(key)\n[ported.example]:2222 \(key)\n"100        try contents.write(to: file, atomically: true, encoding: .utf8)101102        let inspector = KnownHostsInspector(knownHostsFile: file.path)103        #expect(await inspector.status(host: "known.example") == .known)104        #expect(await inspector.status(host: "other.example") == .unknown)105        #expect(await inspector.status(host: "ported.example", port: 2222) == .known)106        #expect(await inspector.status(host: "ported.example") == .unknown)107        #expect(try String(contentsOf: file, encoding: .utf8) == contents)108109        let missing = KnownHostsInspector(knownHostsFile: directory.appendingPathComponent("absent").path)110        #expect(await missing.status(host: "known.example") == .unknown)111        #expect(!FileManager.default.fileExists(atPath: directory.appendingPathComponent("absent").path))112    }113}114115@Suite struct SSHErrorClassifierTests {116    @Test(arguments: [117        ("""118        @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@119        @    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @120        @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@121        IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!122        Offending ED25519 key in /Users/u/.ssh/known_hosts:12123        Host key for example.com has changed and you have requested strict checking.124        Host key verification failed.125        """, SSHErrorKind.hostKeyChanged),126        ("Host key verification failed.\r\n", .hostKeyUnknown),127        ("The authenticity of host 'example.com (93.184.216.34)' can't be established.\nED25519 key fingerprint is SHA256:abc.\nHost key verification failed.", .hostKeyUnknown),128        ("No ED25519 host key is known for example.com and you have requested strict checking.\nHost key verification failed.", .hostKeyUnknown),129        ("user@example.com: Permission denied (publickey,password).", .authenticationFailed),130        ("Received disconnect from 10.0.0.1 port 22:2: Too many authentication failures\nDisconnected from 10.0.0.1 port 22", .authenticationFailed),131        ("ssh: connect to host example.com port 22: Connection refused", .connectionRefused),132        ("ssh: connect to host 10.0.0.9 port 22: Operation timed out", .timedOut),133        ("ssh: connect to host 10.0.0.9 port 22: Connection timed out", .timedOut),134        ("Timeout, server example.com not responding.", .timedOut),135        ("ssh: Could not resolve hostname nope.invalid: nodename nor servname provided, or not known", .nameResolutionFailed),136        ("ssh: Could not resolve hostname nope: Name or service not known", .nameResolutionFailed),137        ("ssh: connect to host 10.9.9.9 port 22: Network is unreachable", .networkUnreachable),138        ("ssh: connect to host 10.9.9.9 port 22: No route to host", .networkUnreachable),139        ("Connection closed by 10.0.0.1 port 22", .connectionClosed),140        ("kex_exchange_identification: read: Connection reset by peer\nConnection reset by 10.0.0.1 port 22", .connectionClosed),141        ("Connection to example.com closed by remote host.", .connectionClosed),142        ("client_loop: send disconnect: Broken pipe", .connectionClosed),143        ("something entirely new", .unknown),144        ("", .unknown),145    ])146    func classifiesSample(stderr: String, expected: SSHErrorKind) {147        #expect(SSHErrorClassifier.classify(stderr: stderr, exitStatus: 255) == expected)148    }149150    @Test func successAndRemoteCommandStatusesAreNotErrors() {151        #expect(SSHErrorClassifier.classify(stderr: "Connection refused", exitStatus: 0) == nil)152        #expect(SSHErrorClassifier.classify(stderr: "grep: no match", exitStatus: 1) == nil)153        #expect(SSHErrorClassifier.classify(stderr: "", exitStatus: 127) == nil)154        #expect(SSHErrorClassifier.classify(stderr: "ssh: connect to host x port 22: Connection refused", exitStatus: 1) == .connectionRefused)155    }156157    @Test func everyKindHasAnExplanation() {158        for kind in SSHErrorKind.allCases {159            #expect(kind.explanation.count > 20)160            #expect(kind.explanation.hasSuffix("."))161        }162        #expect(Set(SSHErrorKind.allCases.map(\.explanation)).count == SSHErrorKind.allCases.count)163    }164}165
Files main
Menu

Theme