-
Notifications
You must be signed in to change notification settings - Fork 1
/
UsageExample.swift
599 lines (509 loc) · 15.3 KB
/
UsageExample.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//===----------------------------------------------------------------------===//
//
// This source file is part of the SshConfig open source project
//
// Copyright (c) 2021 Artem Labazin
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SshConfig project contributors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import SshConfig
final class UsageExample: XCTestCase {
func testExample () throws {
let config = ssh.Config(
ssh.Host("github.com gitlab.com",
{ $0.user = "" },
{ $0.identityFile = ["~/.ssh/id_ed25519"] }
),
ssh.Host("myserv",
{ $0.port = 56 },
{ $0.user = "xxlabaza" },
{ $0.hostKeyAlias = " " },
{ $0.proxyJump = ["A", "B", "C", "D", "E"] }
),
ssh.Host("*",
{ $0.port = 2020 },
{ $0.user = "popa" },
{ $0.addKeysToAgent = .no },
{ $0.forwardX11Timeout = ssh.TimeFormat(days: 1, seconds: 15) }
)
)
let properties = config.resolve(for: "myserv")
XCTAssertEqual(properties.port, 56)
XCTAssertEqual(properties.user, "xxlabaza")
XCTAssertEqual(properties.hostKeyAlias, " ")
XCTAssertEqual(properties.proxyJump, ["A", "B", "C", "D", "E"])
XCTAssertEqual(properties.addKeysToAgent, .no)
XCTAssertEqual(properties.forwardX11Timeout, ssh.TimeFormat(days: 1, seconds: 15))
XCTAssertEqual(properties.identityFile, [
"~/.ssh/id_dsa",
"~/.ssh/id_ecdsa",
"~/.ssh/id_ecdsa_sk",
"~/.ssh/id_ed25519",
"~/.ssh/id_ed25519_sk",
"~/.ssh/id_rsa"
])
let json = try! config.toJsonString()
XCTAssertFalse(json.isEmpty)
let decoded = try! ssh.Config.from(json: json)
XCTAssertEqual(config, decoded)
XCTAssertEqual(properties, decoded.resolve(for: "myserv"))
XCTAssertEqual(try! config.toString(), """
Host github.com gitlab.com
IdentityFile ~/.ssh/id_ed25519
User ""
Host myserv
HostKeyAlias " "
Port 56
ProxyJump A,B,C,D,E
User xxlabaza
Host *
AddKeysToAgent no
ForwardX11Timeout 1d15s
Port 2020
User popa
""")
XCTAssertEqual(config.hosts.count, 3)
XCTAssertEqual(config.hosts[0], ssh.Host(" github.com gitlab.com ",
{ $0.user = "" },
{ $0.identityFile = ["~/.ssh/id_ed25519"] }
))
XCTAssertNotNil(config.hosts[0].properties.user)
XCTAssertEqual(config.hosts[0].properties.user, "")
XCTAssertNotNil(config.hosts[0].properties.identityFile)
XCTAssertEqual(config.hosts[0].properties.identityFile, ["~/.ssh/id_ed25519"])
XCTAssertNil(config.hosts[0].properties.port)
}
func testReadme1 () throws {
let filePath = NSTemporaryDirectory() + "ssh_config"
defer {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
try! fileManager.removeItem(atPath: filePath)
}
}
try """
Host gitlab.com github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
User xxlabaza
Host my*
User admin
Port 2021
Host *
SetEnv POPA=3000
""".write(
toFile: filePath,
atomically: true,
encoding: String.Encoding.utf8
)
let config = try! ssh.Config.load(path: filePath)
let github = config.resolve(for: "github.com")
assert(github.preferredAuthentications == [.publickey])
assert(github.identityFile == ["~/.ssh/id_rsa"])
assert(github.user == "xxlabaza")
assert(github.setEnv == ["POPA": "3000"]) // from 'Host *'
assert(github.port == 22) // the default one
// github.com and gitlab.com resolve the same
assert(github == config.resolve(for: "gitlab.com"))
let myserver = config.resolve(for: "myserver")
assert(myserver.user == "admin")
assert(myserver.port == 2021)
assert(myserver.setEnv == ["POPA": "3000"]) // from 'Host *'
let backend = config.resolve(for: "backend")
assert(backend.user == nil) // the default one
assert(backend.port == 22) // the default one
assert(backend.setEnv == ["POPA": "3000"]) // from 'Host *'
}
func testReadme2 () throws {
let config = ssh.Config(
ssh.Host("gitlab.com github.com",
{ $0.preferredAuthentications = [.publickey] },
{ $0.identityFile = ["~/.ssh/id_rsa"] },
{ $0.user = "xxlabaza" }
),
ssh.Host("my*",
{ $0.user = "admin" },
{ $0.port = 2021 }
),
ssh.Host("*",
{ $0.setEnv = ["POPA": "3000"] }
)
)
let github = config.resolve(for: "github.com")
assert(github.preferredAuthentications == [.publickey])
assert(github.identityFile == ["~/.ssh/id_rsa"])
assert(github.user == "xxlabaza")
assert(github.setEnv == ["POPA": "3000"]) // from 'Host *'
assert(github.port == 22) // the default one
// github.com and gitlab.com resolve the same
assert(github == config.resolve(for: "gitlab.com"))
let myserver = config.resolve(for: "myserver")
assert(myserver.user == "admin")
assert(myserver.port == 2021)
assert(myserver.setEnv == ["POPA": "3000"]) // from 'Host *'
let backend = config.resolve(for: "backend")
assert(backend.user == nil) // the default one
assert(backend.port == 22) // the default one
assert(backend.setEnv == ["POPA": "3000"]) // from 'Host *'
}
func testConfigParser () throws {
let content = """
Host myserv
User alice
Port 2021
"""
let parser = ssh.ConfigParser()
let parsedConfig = try! parser.parse(content)
assert(parsedConfig.count == 1)
let (host, properties) = parsedConfig[0]
assert(host == "myserv")
assert(properties["user"] == ["alice"])
assert(properties["port"] == ["2021"])
}
func testEncoder () throws {
let config = ssh.Config(
ssh.Host("myserv",
{ $0.user = "alice" },
{ $0.port = 2021 }
)
)
let encoder = ssh.ConfigEncoder()
let string = try! encoder.encode(config)
assert(string == """
Host myserv
Port 2021
User alice
""")
}
func testDecoder () throws {
let content = """
Host myserv
User alice
Port 2021
"""
let decoder = ssh.ConfigDecoder()
let config = try! decoder.decode(from: content)
assert(config.hosts.count == 1)
assert(config.hosts[0].alias == "myserv")
assert(config.hosts[0].properties.user == "alice")
assert(config.hosts[0].properties.port == 2021)
}
func testEmptyKeyToken () {
let content = """
Host myserv
=user
"" 2021
"""
var errorCatched = false
do {
_ = try ssh.ConfigParser().parse(content)
} catch ssh.ConfigParserError.emptyKeyToken {
errorCatched = true
} catch {}
assert(errorCatched)
}
func testEmptyValueToken () {
let content = """
Host myserv
user
"""
var errorCatched = false
do {
_ = try ssh.ConfigParser().parse(content)
} catch ssh.ConfigParserError.emptyValueToken {
errorCatched = true
} catch {}
assert(errorCatched)
}
func testIllegalTokensDelimiter () {
let content = """
Host myserv
user?xxlabaza
"""
var errorCatched = false
do {
_ = try ssh.ConfigParser().parse(content)
} catch let ssh.ConfigParserError.illegalTokensDelimiter(after, delimiter) {
assert(after == "user")
assert(delimiter == "?")
errorCatched = true
} catch {}
assert(errorCatched)
}
func testUnexpectedToken () {
let content = """
host
"""
var errorCatched = false
do {
_ = try ssh.ConfigParser().parse(content)
} catch let ssh.ConfigParserError.unexpectedToken(token) {
assert(token == "key(\"host\")")
errorCatched = true
} catch {}
assert(errorCatched)
}
func testNoAliasForHost () {
let content = """
Host " "
"""
var errorCatched = false
do {
_ = try ssh.ConfigParser().parse(content)
} catch ssh.ConfigParserError.noAliasForHost {
errorCatched = true
} catch {}
assert(errorCatched)
}
func testNoPropertiesForHost () {
let content = """
Host myserv
"""
var errorCatched = false
do {
_ = try ssh.ConfigParser().parse(content)
} catch ssh.ConfigParserError.noPropertiesForHost {
errorCatched = true
} catch {}
assert(errorCatched)
}
func testUnableToDecode () {
let content = """
Host *
port abc
"""
var errorCatched = false
do {
_ = try ssh.ConfigDecoder().decode(from: content)
} catch let ssh.ConfigDecoderError.unableToDecode(path, value, type) {
assert(path == "port")
assert(value == "abc")
assert(type == UInt16.self)
errorCatched = true
} catch {}
assert(errorCatched)
}
func testUnableToLoad () {
var errorCatched = false
do {
_ = try ssh.Config.load(path: "/nonexistent/path")
} catch let ssh.ConfigError.unableToLoad(path, cause) {
assert(path == "/nonexistent/path")
assert(type(of: cause) == NSError.self)
// Different messages depend on OS and Swift version,
// but they say the same - 'No such file'.
assert(cause.localizedDescription.contains("o such file"))
errorCatched = true
} catch {}
assert(errorCatched)
}
func testUnableToDump () {
let config = ssh.Config()
var errorCatched = false
do {
try config.dump(to: "/nonexistent/path")
} catch let ssh.ConfigError.unableToDump(path, cause) {
assert(path == "/nonexistent/path")
assert(type(of: cause) == NSError.self)
// Different messages depend on OS and Swift version,
// but they say the same - 'file doesn’t exist'.
assert(cause.localizedDescription.contains(" doesn’t exist."))
errorCatched = true
} catch {}
assert(errorCatched)
}
func testConfigFromJsonString () throws {
let string = """
{
"hosts": [
{
"alias": "myserv",
"properties": {
"port": 2021
}
}
]
}
"""
let config = try! ssh.Config.from(json: string)
assert(config.hosts.count == 1)
assert(config.hosts[0].alias == "myserv")
assert(config.hosts[0].properties.port == 2021)
}
func testConfigFromJsonData () throws {
let string = """
{
"hosts": [
{
"alias": "myserv",
"properties": {
"port": 2021
}
}
]
}
"""
let data = string.data(using: .utf8)!
let config = try! ssh.Config.from(json: data)
assert(config.hosts.count == 1)
assert(config.hosts[0].alias == "myserv")
assert(config.hosts[0].properties.port == 2021)
}
func testConfigLoad () throws {
let content = """
Host myserv
port 2021
"""
try content.write(
toFile: NSString(string: "~/my-ssh-config").expandingTildeInPath,
atomically: true,
encoding: String.Encoding.utf8
)
let config = try! ssh.Config.load(path: "~/my-ssh-config")
assert(config.hosts.count == 1)
assert(config.hosts[0].alias == "myserv")
assert(config.hosts[0].properties.port == 2021)
}
func testConfigParse () throws {
let content = """
Host myserv
port 2021
"""
let config = try! ssh.Config.parse(content)
assert(config.hosts.count == 1)
assert(config.hosts[0].alias == "myserv")
assert(config.hosts[0].properties.port == 2021)
}
func testConfigInit () throws {
let config = ssh.Config(
ssh.Host("github.com gitlab.com",
{ $0.user = "xxlabaza" },
{ $0.identityFile = ["~/.ssh/id_ed25519"] }
),
ssh.Host("myserv",
{ $0.port = 56 },
{ $0.user = "admin" }
),
ssh.Host("*",
{ $0.port = 2020 },
{ $0.user = "artem" },
{ $0.addKeysToAgent = .yes },
{ $0.forwardX11Timeout = ssh.TimeFormat(minutes: 1, seconds: 15) }
)
)
assert(config.hosts.count == 3)
assert(config.hosts[0].alias == "github.com gitlab.com")
assert(config.hosts[0].properties.user == "xxlabaza")
assert(config.hosts[1].alias == "myserv")
assert(config.hosts[1].properties.port == 56)
assert(config.hosts[2].alias == "*")
assert(config.hosts[2].properties.addKeysToAgent == .yes)
}
func testConfigToJsonData () throws {
let config = ssh.Config(
ssh.Host("myserv", { $0.port = 15 })
)
let data = try! config.toJsonData()
assert(jsonEquals(
actual: data,
expected: #"{"hosts":[{"alias":"myserv","properties":{"port":15}}]}"#
))
}
func testConfigToJsonString () throws {
let config = ssh.Config(
ssh.Host("myserv", { $0.port = 15 })
)
let json = try! config.toJsonString()
assert(jsonEquals(
actual: json,
expected: #"{"hosts":[{"alias":"myserv","properties":{"port":15}}]}"#
))
}
func testConfigToString () throws {
let config = ssh.Config(
ssh.Host("myserv", { $0.port = 15 })
)
let string = try! config.toString()
assert(string == """
Host myserv
Port 15
""")
}
func testConfigDump () throws {
let config = ssh.Config(
ssh.Host("myserv", { $0.port = 15 })
)
try! config.dump(to: "~/my-ssh-config")
let filePath = NSString(string: "~/my-ssh-config").expandingTildeInPath
assert(FileManager.default.fileExists(atPath: filePath))
assert(try! String(contentsOfFile: filePath) == """
Host myserv
Port 15
""")
}
func testConfigResolve () throws {
let config = ssh.Config(
ssh.Host("github.com gitlab.com",
{ $0.user = "xxlabaza" }
),
ssh.Host("my*",
{ $0.user = "admin" },
{ $0.port = 56 }
),
ssh.Host("*",
{ $0.user = "artem" },
{ $0.port = 2020 }
)
)
let github = config.resolve(for: "github.com")
assert(github.user == "xxlabaza")
assert(github.port == 2020)
let gitlab = config.resolve(for: "gitlab.com")
assert(gitlab.user == "xxlabaza")
assert(gitlab.port == 2020)
let myserv = config.resolve(for: "myserv")
assert(myserv.user == "admin")
assert(myserv.port == 56)
let example = config.resolve(for: "example.com")
assert(example.user == "artem")
assert(example.port == 2020)
}
func testHostInit () throws {
let host = ssh.Host("myserv",
{ $0.user = "admin" },
{ $0.port = 2021 }
)
assert(host.alias == "myserv")
assert(host.properties.user == "admin")
}
func testHostInit2 () throws {
var properties = ssh.Properties.create()
properties.user = "admin"
properties.port = 2021
let host = ssh.Host("myserv", properties)
assert(host.alias == "myserv")
assert(host.properties.user == "admin")
}
func testPropertiesDefaults () throws {
var properties = ssh.Properties.defaults;
properties.addKeysToAgent = .yes
assert(properties.addKeysToAgent == .yes)
assert(ssh.Properties.defaults.addKeysToAgent == .no)
}
private func jsonEquals (actual: String, expected: String) -> Bool {
let data = actual.data(using: .utf8)!
return jsonEquals(actual: data, expected: expected)
}
private func jsonEquals (actual: Data, expected: String) -> Bool {
let left = try! ssh.Config.from(json: actual)
let right = try! ssh.Config.from(json: expected)
XCTAssertEqual(left, right, "JSON string:\n\(actual)\ndoesn't equal to:\n\(expected)")
return true
}
}