Repository Public
1import Foundation2import Testing3@testable import SSHKit45@Suite struct SSHConfigParserTests {6 let parser = SSHConfigParser(fileSystem: .inMemory([:]), homeDirectory: "/home/u")78 @Test func aliasesExcludeWildcardsNegationsAndDuplicates() {9 let config = parser.parse("""10 Host web-1 db *.example.com !bastion staging?11 User a12 Host *13 Port 2214 Host db other15 User b16 """)17 #expect(config.aliases == ["web-1", "db", "other"])18 #expect(config.hosts.map(\.alias) == ["web-1", "db", "other"])19 }2021 @Test func firstObtainedValueWinsAcrossMatchingBlocks() {22 let config = parser.parse("""23 Host web-*24 User deploy25 Host web-1 db26 HostName 10.0.0.127 User admin28 Port 222229 Host * !db30 User fallback31 ForwardAgent yes32 ProxyJump bastion33 Host *34 Port 2235 IdentityFile ~/.ssh/id_default36 """)37 let web = config.resolve("web-1")38 #expect(web.user == "deploy")39 #expect(web.hostName == "10.0.0.1")40 #expect(web.port == 2222)41 #expect(web.forwardAgent == true)42 #expect(web.proxyJump == "bastion")43 #expect(web.identityFiles == ["~/.ssh/id_default"])4445 let db = config.resolve("db")46 #expect(db.user == "admin")47 #expect(db.port == 2222)48 #expect(db.forwardAgent == nil)49 #expect(db.proxyJump == nil)5051 let other = config.resolve("unlisted")52 #expect(other.user == "fallback")53 #expect(other.port == 22)54 #expect(other.hostName == nil)55 }5657 @Test func globalOptionsBeforeAnyHostApplyToEveryone() {58 let config = parser.parse("User root\nHost a\n User alice\n")59 #expect(config.resolve("a").user == "root")60 #expect(config.resolve("zzz").user == "root")61 }6263 @Test func wildcardsAndNegation() {64 let config = parser.parse("""65 Host *.corp !secret.corp66 User corp67 Host node?68 Port 220069 Host !node1 node170 User never71 """)72 #expect(config.resolve("a.corp").user == "corp")73 #expect(config.resolve("secret.corp").user == nil)74 #expect(config.resolve("node7").port == 2200)75 #expect(config.resolve("node77").port == nil)76 // A negated match excludes the block even when another pattern matches.77 #expect(config.resolve("node1").user == nil)78 // A block with only negated patterns never matches.79 #expect(parser.parse("Host !x\n User u\n").resolve("y").user == nil)80 #expect(SSHWildcard.matches(pattern: "a*b*c", text: "a--b--b--c"))81 #expect(!SSHWildcard.matches(pattern: "a*b", text: "a--c"))82 #expect(SSHWildcard.matches(pattern: "*", text: ""))83 #expect(!SSHWildcard.matches(pattern: "Web", text: "web"))84 }8586 @Test func syntaxVariantsQuotesCommentsAndCase() {87 let config = parser.parse("""88 # a comment89 # an indented comment9091 HOST "my host" plain # trailing comment92 \thostname=example.org93 USER = "john doe"94 port\t202295 IdentityFile "~/keys/my key"96 identityfile '~/keys/second'97 IdentityFile ~/keys/esc\\ aped98 IdentityFile "~/keys/my key"99 ProxyJump=jump1,jump2100 ForwardAgent No101 UnknownKeyword whatever102 Port103 """)104 #expect(config.aliases == ["my host", "plain"])105 let host = config.resolve("my host")106 #expect(host.hostName == "example.org")107 #expect(host.user == "john doe")108 #expect(host.port == 2022)109 #expect(host.identityFiles == ["~/keys/my key", "~/keys/second", "~/keys/esc aped"])110 #expect(host.proxyJump == "jump1,jump2")111 #expect(host.forwardAgent == false)112 #expect(config.resolve("plain") == SSHConfigHost(113 alias: "plain", hostName: "example.org", user: "john doe", port: 2022, proxyJump: "jump1,jump2",114 identityFiles: ["~/keys/my key", "~/keys/second", "~/keys/esc aped"], forwardAgent: false115 ))116 }117118 @Test func invalidPortIsIgnoredAndLaterValueUsed() {119 let config = parser.parse("Host a\n Port 70000\n Port abc\n Port 2200\n ForwardAgent $SSH_AUTH_SOCK\n")120 #expect(config.resolve("a").port == 2200)121 #expect(config.resolve("a").forwardAgent == true)122 }123124 @Test func matchBlocksAreSkippedExceptMatchAll() {125 let config = parser.parse("""126 Host a127 User alice128 Match host a exec "true"129 User evil130 Port 9131 HostName evil.example132 Host b133 User bob134 Match all135 Port 2222136 """)137 let a = config.resolve("a")138 #expect(a.user == "alice")139 #expect(a.hostName == nil)140 #expect(a.port == 2222)141 #expect(config.resolve("b").user == "bob")142 #expect(config.aliases == ["a", "b"])143144 let leading = parser.parse("Match user root\n User evil\nHost a\n Port 1\n").resolve("a")145 #expect(leading.user == nil)146 #expect(leading.port == 1)147 }148149 @Test func includeResolvesRelativeTildeAbsoluteAndGlobs() {150 let files = [151 "/home/u/.ssh/conf.d/10-a.conf": "Host inc-a\n User ua\n",152 "/home/u/.ssh/conf.d/20-b.conf": "Host inc-b\n User ub\n",153 "/home/u/.ssh/conf.d/sub/ignored.conf": "Host nested\n",154 "/home/u/.ssh/conf.d/readme.txt": "Host txt\n",155 "/home/u/extra": "Host tilde\n Port 2201\n",156 "/etc/abs.conf": "Host abs\n Port 2202\n",157 ]158 let parser = SSHConfigParser(fileSystem: .inMemory(files), homeDirectory: "/home/u")159 let config = parser.parse("""160 Include conf.d/*.conf ~/extra /etc/abs.conf missing.conf161 Host last162 User l163 """)164 #expect(config.aliases == ["inc-a", "inc-b", "tilde", "abs", "last"])165 #expect(config.resolve("inc-b").user == "ub")166 #expect(config.resolve("tilde").port == 2201)167 #expect(config.resolve("abs").port == 2202)168 }169170 @Test func includeDoesNotLeakItsHostBlockAndHonoursEnclosingBlock() {171 let files = [172 "/cfg/inner": "User inherited\nHost inner\n Port 2222\n",173 ]174 let parser = SSHConfigParser(fileSystem: .inMemory(files), homeDirectory: "/home/u")175 let config = parser.parse("""176 Host outer177 Include inner178 HostName outer.example179 """, configDirectory: "/cfg")180 // `User inherited` sits in the included file before any Host: it belongs to `Host outer`.181 #expect(config.resolve("outer").user == "inherited")182 #expect(config.resolve("inner").user == nil)183 // After the Include, the `Host outer` block continues (the included `Host inner` did not leak).184 #expect(config.resolve("outer").hostName == "outer.example")185 #expect(config.resolve("inner").hostName == nil)186 #expect(config.resolve("inner").port == 2222)187 #expect(config.resolve("outer").port == nil)188 }189190 @Test func includeDepthIsLimitedAndCyclesTerminate() {191 let files = [192 "/cfg/loop": "Host looped\nInclude loop\n",193 "/cfg/d1": "Host one\nInclude d2\n",194 "/cfg/d2": "Host two\nInclude d3\n",195 "/cfg/d3": "Host three\n",196 ]197 let cyclic = SSHConfigParser(fileSystem: .inMemory(files), homeDirectory: "/h").parse("Include loop\n", configDirectory: "/cfg")198 #expect(cyclic.aliases == ["looped"])199 let shallow = SSHConfigParser(fileSystem: .inMemory(files), homeDirectory: "/h", maxIncludeDepth: 2)200 #expect(shallow.parse("Include d1\n", configDirectory: "/cfg").aliases == ["one", "two"])201 let none = SSHConfigParser(fileSystem: .inMemory(files), homeDirectory: "/h", maxIncludeDepth: 0)202 #expect(none.parse("Include d1\nHost x\n", configDirectory: "/cfg").aliases == ["x"])203 }204205 @Test func parseFileUsesItsDirectoryAndToleratesMissingFile() {206 let files = [207 "/home/u/.ssh/config": "Include extra\nHost main\n",208 "/home/u/.ssh/extra": "Host extra\n",209 ]210 let parser = SSHConfigParser(fileSystem: .inMemory(files), homeDirectory: "/home/u")211 #expect(parser.parseFile().aliases == ["extra", "main"])212 #expect(parser.parseFile(at: "/nowhere/config").aliases.isEmpty)213 }214215 @Test func liveFileSystemReadsAndGlobsRealFiles() throws {216 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("SSHKitTests-\(UUID().uuidString)")217 try FileManager.default.createDirectory(at: directory.appendingPathComponent("conf.d"), withIntermediateDirectories: true)218 defer { try? FileManager.default.removeItem(at: directory) }219 try "Include conf.d/*\nHost top\n".write(to: directory.appendingPathComponent("config"), atomically: true, encoding: .utf8)220 try "Host b\n".write(to: directory.appendingPathComponent("conf.d/b"), atomically: true, encoding: .utf8)221 try "Host a\n".write(to: directory.appendingPathComponent("conf.d/a"), atomically: true, encoding: .utf8)222 let config = SSHConfigParser().parseFile(at: directory.appendingPathComponent("config").path)223 #expect(config.aliases == ["a", "b", "top"])224 }225}226227@Suite struct SSHHostProfileTests {228 @Test func codableRoundTrip() throws {229 let profile = SSHHostProfile(label: "Prod", host: "prod.example.com", user: "ops", port: 2222, proxyJump: "bastion", group: "Work", isFavorite: true, source: .manual)230 let data = try JSONEncoder().encode(profile)231 #expect(try JSONDecoder().decode(SSHHostProfile.self, from: data) == profile)232 #expect(String(decoding: data, as: UTF8.self).contains("\"source\":\"manual\""))233 }234235 @Test func mergeKeepsUserMetadataRefreshesConfigFieldsAndDropsStaleAliases() {236 let keptID = UUID()237 let saved = [238 SSHHostProfile(id: keptID, label: "My web", host: "web", user: "old", port: 1, group: "G", isFavorite: true, source: .sshConfig),239 SSHHostProfile(label: "gone", host: "gone", source: .sshConfig),240 SSHHostProfile(label: "Manual", host: "web", user: "me", source: .manual),241 ]242 let config = [243 SSHConfigHost(alias: "web", hostName: "10.0.0.1", user: "deploy", port: 2222, proxyJump: "jump"),244 SSHConfigHost(alias: "new"),245 SSHConfigHost(alias: "web"),246 ]247 let merged = SSHHostProfile.merge(configHosts: config, saved: saved)248 #expect(merged.map(\.host) == ["web", "new", "web"])249 #expect(merged[0] == SSHHostProfile(id: keptID, label: "My web", host: "web", user: "deploy", port: 2222, proxyJump: "jump", group: "G", isFavorite: true, source: .sshConfig))250 #expect(merged[1].source == .sshConfig)251 #expect(merged[1].label == "new")252 #expect(merged[1].id == SSHHostProfile.stableID(forAlias: "new"))253 #expect(merged[2] == saved[2])254 // Merging again is stable.255 #expect(SSHHostProfile.merge(configHosts: config, saved: merged) == merged)256 #expect(SSHHostProfile.stableID(forAlias: "a") != SSHHostProfile.stableID(forAlias: "b"))257 }258}259