Repository Public
1import Foundation2import Testing3@testable import SSHKit45@Suite struct SSHCommandBuilderTests {6 func manual(_ host: String = "example.com", user: String? = nil, port: Int? = nil, jump: String? = nil) -> SSHHostProfile {7 SSHHostProfile(label: "x", host: host, user: user, port: port, proxyJump: jump, source: .manual)8 }910 @Test func buildsSSHArgv() throws {11 let command = try SSHCommandBuilder.sshCommand(12 for: manual(user: "ops", port: 2222, jump: "me@bastion:2200,[fe80::1]:22"),13 extraOptions: [SSHOption("connecttimeout", "10"), SSHOption("ForwardAgent", "YES")]14 )15 #expect(command.executable == "/usr/bin/ssh")16 #expect(command.arguments == [17 "-o", "ConnectTimeout=10", "-o", "ForwardAgent=yes",18 "-p", "2222", "-l", "ops", "-J", "me@bastion:2200,[fe80::1]:22", "--", "example.com",19 ])20 }2122 @Test func buildsSFTPArgv() throws {23 let command = try SSHCommandBuilder.sftpCommand(for: manual(user: "ops", port: 2222, jump: "bastion"))24 #expect(command.executable == "/usr/bin/sftp")25 #expect(command.arguments == ["-P", "2222", "-o", "User=ops", "-J", "bastion", "--", "example.com"])26 }2728 @Test func minimalAndConfigProfilesEmitOnlyTheHost() throws {29 #expect(try SSHCommandBuilder.sshCommand(for: manual("10.0.0.1")).arguments == ["--", "10.0.0.1"])30 #expect(try SSHCommandBuilder.sshCommand(for: manual("::1")).arguments == ["--", "::1"])31 let alias = SSHHostProfile(label: "a", host: "M3U96a", user: "shown", port: 2222, proxyJump: "%h weird", source: .sshConfig)32 #expect(try SSHCommandBuilder.sshCommand(for: alias).arguments == ["--", "M3U96a"])33 #expect(try SSHCommandBuilder.sftpCommand(for: alias).arguments == ["--", "M3U96a"])34 }3536 @Test(arguments: [37 ("", SSHCommandError.emptyValue(.host)),38 ("-oProxyCommand=evil", .leadingDash(.host)),39 ("-", .leadingDash(.host)),40 ("host name", .invalidCharacters(.host)),41 ("host\tname", .invalidCharacters(.host)),42 ("host\nname", .invalidCharacters(.host)),43 ("host\u{0}", .invalidCharacters(.host)),44 ("host\u{7f}", .invalidCharacters(.host)),45 ("host;id", .invalidCharacters(.host)),46 ("host|id", .invalidCharacters(.host)),47 ("host&id", .invalidCharacters(.host)),48 ("$(id)", .invalidCharacters(.host)),49 ("`id`", .invalidCharacters(.host)),50 ("host>out", .invalidCharacters(.host)),51 ("a'b", .invalidCharacters(.host)),52 ("a\"b", .invalidCharacters(.host)),53 ("a\\b", .invalidCharacters(.host)),54 ("a*b", .invalidCharacters(.host)),55 ("user@host", .invalidCharacters(.host)),56 ("h\u{00e9}te", .invalidCharacters(.host)),57 (String(repeating: "a", count: 256), .invalidCharacters(.host)),58 ])59 func rejectsBadHost(host: String, expected: SSHCommandError) {60 #expect(throws: expected) { try SSHCommandBuilder.sshCommand(for: manual(host)) }61 #expect(throws: expected) { try SSHCommandBuilder.sftpCommand(for: manual(host)) }62 // The host of a config-sourced profile is validated just the same.63 #expect(throws: expected) { try SSHCommandBuilder.sshCommand(for: SSHHostProfile(label: "x", host: host, source: .sshConfig)) }64 }6566 @Test(arguments: [67 ("", SSHCommandError.emptyValue(.user)),68 ("-root", .leadingDash(.user)),69 ("ro ot", .invalidCharacters(.user)),70 ("root;reboot", .invalidCharacters(.user)),71 ("root\n", .invalidCharacters(.user)),72 ("$USER", .invalidCharacters(.user)),73 ("a=b", .invalidCharacters(.user)),74 ])75 func rejectsBadUser(user: String, expected: SSHCommandError) {76 #expect(throws: expected) { try SSHCommandBuilder.sshCommand(for: manual(user: user)) }77 #expect(throws: expected) { try SSHCommandBuilder.sftpCommand(for: manual(user: user)) }78 }7980 @Test(arguments: [0, -1, 65536, 1_000_000])81 func rejectsPortOutOfRange(port: Int) {82 #expect(throws: SSHCommandError.portOutOfRange(port)) { try SSHCommandBuilder.sshCommand(for: manual(port: port)) }83 #expect(throws: SSHCommandError.portOutOfRange(port)) { try SSHCommandBuilder.sftpCommand(for: manual(port: port)) }84 }8586 @Test func acceptsPortBounds() throws {87 #expect(try SSHCommandBuilder.sshCommand(for: manual(port: 1)).arguments.prefix(2) == ["-p", "1"])88 #expect(try SSHCommandBuilder.sshCommand(for: manual(port: 65535)).arguments.prefix(2) == ["-p", "65535"])89 }9091 @Test(arguments: [92 ("", SSHCommandError.emptyValue(.proxyJump)),93 ("-oProxyCommand=x", .leadingDash(.proxyJump)),94 ("a b", .invalidCharacters(.proxyJump)),95 ("a;b", .invalidCharacters(.proxyJump)),96 ("a,,b", .emptyValue(.proxyJump)),97 ("a,", .emptyValue(.proxyJump)),98 ("a,-b", .leadingDash(.proxyJump)),99 ("u@-b", .leadingDash(.proxyJump)),100 ("a:b", .invalidCharacters(.proxyJump)),101 ("a:22:33", .invalidCharacters(.proxyJump)),102 ("a:0", .portOutOfRange(0)),103 ("a:70000", .portOutOfRange(70000)),104 ("[::1", .invalidCharacters(.proxyJump)),105 ("[::1]x", .invalidCharacters(.proxyJump)),106 ("ssh://a", .invalidCharacters(.proxyJump)),107 ("%h", .invalidCharacters(.proxyJump)),108 ])109 func rejectsBadProxyJump(jump: String, expected: SSHCommandError) {110 #expect(throws: expected) { try SSHCommandBuilder.sshCommand(for: manual(jump: jump)) }111 }112113 @Test func acceptsProxyJumpForms() throws {114 for jump in ["none", "bastion", "u@b", "b:2222", "u@b:22,c", "[2001:db8::1]:2222", "u@[::1]"] {115 #expect(try SSHCommandBuilder.sshCommand(for: manual(jump: jump)).arguments.contains(jump))116 }117 }118119 static let weakeningOptions: [SSHOption] = [120 SSHOption("StrictHostKeyChecking", "no"),121 SSHOption("StrictHostKeyChecking", "off"),122 SSHOption("StrictHostKeyChecking", "accept-new"),123 SSHOption("stricthostkeychecking", "yes"),124 SSHOption("UserKnownHostsFile", "/dev/null"),125 SSHOption("GlobalKnownHostsFile", "/dev/null"),126 SSHOption("KnownHostsCommand", "/bin/echo"),127 SSHOption("CheckHostIP", "no"),128 SSHOption("VerifyHostKeyDNS", "yes"),129 SSHOption("HostKeyAlias", "other"),130 SSHOption("NoHostAuthenticationForLocalhost", "yes"),131 SSHOption("UpdateHostKeys", "yes"),132 SSHOption("BatchMode", "yes"),133 SSHOption("BATCHMODE", "no"),134 SSHOption("PasswordAuthentication", "yes"),135 SSHOption("KbdInteractiveAuthentication", "yes"),136 SSHOption("NumberOfPasswordPrompts", "1"),137 SSHOption("ProxyCommand", "nc %h %p"),138 SSHOption("LocalCommand", "id"),139 SSHOption("PermitLocalCommand", "yes"),140 ]141142 @Test(arguments: weakeningOptions)143 func forbiddenOptionsThrow(option: SSHOption) {144 #expect(throws: SSHCommandError.forbiddenOption(option.key)) {145 try SSHCommandBuilder.sshCommand(for: manual(), extraOptions: [option])146 }147 #expect(throws: SSHCommandError.forbiddenOption(option.key)) {148 try SSHCommandBuilder.sftpCommand(for: manual(), extraOptions: [option])149 }150 }151152 @Test(arguments: [153 SSHOption("ControlPath", "/tmp/x"), SSHOption("LogLevel", "QUIET"), SSHOption("Ciphers", "aes128-ctr"),154 SSHOption("", "x"), SSHOption("ConnectTimeout=5 -o StrictHostKeyChecking", "no"),155 SSHOption("-oStrictHostKeyChecking", "no"), SSHOption("Connect Timeout", "5"),156 ])157 func optionsOutsideAllowlistThrow(option: SSHOption) {158 #expect(throws: SSHCommandError.optionNotAllowed(option.key)) {159 try SSHCommandBuilder.sshCommand(for: manual(), extraOptions: [option])160 }161 }162163 @Test(arguments: [164 SSHOption("ConnectTimeout", "0"), SSHOption("ConnectTimeout", "-1"), SSHOption("ConnectTimeout", "5 -o StrictHostKeyChecking=no"),165 SSHOption("ConnectTimeout", ""), SSHOption("ConnectTimeout", "+5"), SSHOption("ConnectTimeout", "99999999999999999999"),166 SSHOption("ServerAliveInterval", "abc"), SSHOption("ServerAliveCountMax", "0"),167 SSHOption("ForwardAgent", "/tmp/agent.sock"), SSHOption("ForwardAgent", "yes\nStrictHostKeyChecking=no"),168 SSHOption("RequestTTY", "maybe"),169 ])170 func invalidOptionValuesThrow(option: SSHOption) {171 #expect(throws: SSHCommandError.self) {172 try SSHCommandBuilder.sshCommand(for: manual(), extraOptions: [option])173 }174 }175176 @Test func everyAllowlistedOptionIsAcceptedInCanonicalForm() throws {177 let options = [178 SSHOption("addressfamily", "inet"), SSHOption("compression", "yes"), SSHOption("connecttimeout", "15"),179 SSHOption("connectionattempts", "2"), SSHOption("forwardagent", "no"), SSHOption("requesttty", "force"),180 SSHOption("serveralivecountmax", "3"), SSHOption("serveraliveinterval", "30"), SSHOption("tcpkeepalive", "yes"),181 ]182 let command = try SSHCommandBuilder.sshCommand(for: manual(), extraOptions: options)183 let emitted = stride(from: 1, to: options.count * 2, by: 2).map { command.arguments[$0] }184 #expect(emitted.map { String($0.prefix { $0 != "=" }) } == SSHCommandBuilder.allowedOptionKeys)185 #expect(Set(SSHCommandBuilder.allowedOptionKeys.map { $0.lowercased() }).isDisjoint(with: SSHCommandBuilder.forbiddenOptionKeys))186 }187188 /// Whatever valid input is given, the argv never carries an option touching host key verification189 /// or password handling, and every `-o` key is on the allowlist.190 @Test func neverEmitsHostKeyWeakeningOrPasswordOptions() throws {191 let banned = ["stricthostkeychecking", "userknownhostsfile", "globalknownhostsfile", "batchmode", "/dev/null",192 "accept-new", "password", "checkhostip", "hostkeyalias", "proxycommand", "verifyhostkeydns"]193 let allowedKeys = Set(SSHCommandBuilder.allowedOptionKeys + ["User"])194 let profiles = [195 manual(), manual(user: "u", port: 22, jump: "j"), manual("alias", user: "a.b-c_d", port: 65535, jump: "none"),196 SSHHostProfile(label: "StrictHostKeyChecking=no", host: "cfg", group: "UserKnownHostsFile=/dev/null", source: .sshConfig),197 ]198 let optionSets: [[SSHOption]] = [199 [], [SSHOption("ConnectTimeout", "5")],200 [SSHOption("ServerAliveInterval", "15"), SSHOption("ServerAliveCountMax", "3"), SSHOption("ForwardAgent", "yes"), SSHOption("RequestTTY", "yes")],201 ]202 for profile in profiles {203 for options in optionSets {204 for command in [try SSHCommandBuilder.sshCommand(for: profile, extraOptions: options),205 try SSHCommandBuilder.sftpCommand(for: profile, extraOptions: options)] {206 for (index, argument) in command.arguments.enumerated() {207 let lowered = argument.lowercased()208 #expect(!banned.contains(where: lowered.contains), "\(argument)")209 if argument == "-o" {210 let key = String(command.arguments[index + 1].prefix { $0 != "=" })211 #expect(allowedKeys.contains(key), "\(key)")212 }213 }214 #expect(command.arguments.suffix(2) == ["--", profile.host])215 #expect(command.displayString.lowercased().contains("stricthostkeychecking") == false)216 }217 }218 }219 }220221 @Test func shellQuoting() {222 #expect(SSHCommandBuilder.shellQuote("plain-Word_1.2:/x@y") == "plain-Word_1.2:/x@y")223 #expect(SSHCommandBuilder.shellQuote("") == "''")224 #expect(SSHCommandBuilder.shellQuote("two words") == "'two words'")225 #expect(SSHCommandBuilder.shellQuote("it's") == "'it'\\''s'")226 #expect(SSHCommandBuilder.shellQuote("$(id);`x`|&") == "'$(id);`x`|&'")227 #expect(SSHCommandBuilder.shellQuote("[::1]:22") == "'[::1]:22'")228 #expect(SSHCommandBuilder.shellQuote("a\nb") == "'a\nb'")229 }230231 @Test func displayStringIsQuotedAndRoundTripsThroughShell() throws {232 let command = try SSHCommandBuilder.sshCommand(for: manual(user: "ops", port: 2222, jump: "u@[::1]:22"), extraOptions: [SSHOption("ConnectTimeout", "10")])233 #expect(command.displayString == "/usr/bin/ssh -o ConnectTimeout=10 -p 2222 -l ops -J 'u@[::1]:22' -- example.com")234235 // Round trip of awkward arguments through a real /bin/sh (local, no network).236 let awkward = SSHCommand(executable: "/usr/bin/printf", arguments: ["%s\\n", "it's", "a b", "$HOME", "*", "", "é;|"])237 let process = Process()238 process.executableURL = URL(fileURLWithPath: "/bin/sh")239 process.arguments = ["-c", awkward.displayString]240 let pipe = Pipe()241 process.standardOutput = pipe242 try process.run()243 let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)244 process.waitUntilExit()245 #expect(output == "it's\na b\n$HOME\n*\n\né;|\n")246 }247}248