-
-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathlua_test.go
More file actions
760 lines (623 loc) · 18.5 KB
/
Copy pathlua_test.go
File metadata and controls
760 lines (623 loc) · 18.5 KB
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
//go:build full || e2e
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
lua "github.com/yuin/gopher-lua"
)
// Mock connection metadata for testing
type mockConnMetadata struct {
username string
remoteAddr string
uniqueID string
}
func (m *mockConnMetadata) User() string {
return m.username
}
func (m *mockConnMetadata) RemoteAddr() string {
return m.remoteAddr
}
func (m *mockConnMetadata) UniqueID() string {
return m.uniqueID
}
func (m *mockConnMetadata) GetMeta(key string) string {
return ""
}
func TestLuaPluginSimpleScript(t *testing.T) {
// Create a temporary Lua script
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
function sshpiper_on_password(conn, password)
return {
host = "localhost:2222",
username = "testuser",
}
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
// Create plugin
plugin := &luaPlugin{
ScriptPath: scriptPath,
}
// Create config
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("Failed to create config: %v", err)
}
if config.PasswordCallback == nil {
t.Fatal("PasswordCallback is nil")
}
// Test password callback
conn := &mockConnMetadata{
username: "alice",
remoteAddr: "192.168.1.100",
uniqueID: "test-123",
}
upstream, err := config.PasswordCallback(conn, []byte("password"))
if err != nil {
t.Fatalf("PasswordCallback failed: %v", err)
}
if upstream.Uri != "tcp://localhost:2222" {
t.Errorf("Expected URI 'tcp://localhost:2222', got '%s'", upstream.Uri)
}
if upstream.UserName != "testuser" {
t.Errorf("Expected username 'testuser', got '%s'", upstream.UserName)
}
}
func TestLuaPluginUsernameRouting(t *testing.T) {
// Create a temporary Lua script with username-based routing
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
function sshpiper_on_password(conn, password)
if conn.sshpiper_user == "alice" then
return {
host = "server1:22",
username = "alice_remote",
}
elseif conn.sshpiper_user == "bob" then
return {
host = "server2:22",
username = "bob_remote",
}
end
return nil
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
// Create plugin
plugin := &luaPlugin{
ScriptPath: scriptPath,
}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("Failed to create config: %v", err)
}
// Test alice
connAlice := &mockConnMetadata{
username: "alice",
remoteAddr: "192.168.1.100",
uniqueID: "test-alice",
}
upstream, err := config.PasswordCallback(connAlice, []byte("password"))
if err != nil {
t.Fatalf("PasswordCallback failed for alice: %v", err)
}
if upstream.Uri != "tcp://server1:22" {
t.Errorf("Expected URI 'tcp://server1:22' for alice, got '%s'", upstream.Uri)
}
if upstream.UserName != "alice_remote" {
t.Errorf("Expected username 'alice_remote', got '%s'", upstream.UserName)
}
// Test bob
connBob := &mockConnMetadata{
username: "bob",
remoteAddr: "192.168.1.101",
uniqueID: "test-bob",
}
upstream, err = config.PasswordCallback(connBob, []byte("password"))
if err != nil {
t.Fatalf("PasswordCallback failed for bob: %v", err)
}
if upstream.Uri != "tcp://server2:22" {
t.Errorf("Expected URI 'tcp://server2:22' for bob, got '%s'", upstream.Uri)
}
if upstream.UserName != "bob_remote" {
t.Errorf("Expected username 'bob_remote', got '%s'", upstream.UserName)
}
// Test unknown user (should fail)
connUnknown := &mockConnMetadata{
username: "charlie",
remoteAddr: "192.168.1.102",
uniqueID: "test-charlie",
}
_, err = config.PasswordCallback(connUnknown, []byte("password"))
if err == nil {
t.Error("Expected error for unknown user, got nil")
}
}
func TestLuaPluginMissingScript(t *testing.T) {
plugin := &luaPlugin{
ScriptPath: "/nonexistent/script.lua",
}
_, err := plugin.CreateConfig()
if err == nil {
t.Error("Expected error for missing script, got nil")
}
}
func TestLuaPluginInvalidReturn(t *testing.T) {
// Create a temporary Lua script with invalid return
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
function sshpiper_on_password(conn, password)
return "not a table"
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{
ScriptPath: scriptPath,
}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("Failed to create config: %v", err)
}
conn := &mockConnMetadata{
username: "alice",
remoteAddr: "192.168.1.100",
uniqueID: "test-123",
}
_, err = config.PasswordCallback(conn, []byte("password"))
if err == nil {
t.Error("Expected error for invalid return type, got nil")
}
}
func TestLuaPluginConcurrency(t *testing.T) {
// Create a temporary Lua script
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
function sshpiper_on_password(conn, password)
return {
host = "localhost:2222",
username = conn.sshpiper_user,
}
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{
ScriptPath: scriptPath,
}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("Failed to create config: %v", err)
}
// Test concurrent authentication requests
const numGoroutines = 10
errors := make(chan error, numGoroutines)
for i := 0; i < numGoroutines; i++ {
go func(id int) {
conn := &mockConnMetadata{
username: fmt.Sprintf("user%d", id),
remoteAddr: "192.168.1.100",
uniqueID: fmt.Sprintf("test-%d", id),
}
upstream, err := config.PasswordCallback(conn, []byte("password"))
if err != nil {
errors <- err
return
}
if upstream.UserName != conn.User() {
errors <- fmt.Errorf("expected username %s, got %s", conn.User(), upstream.UserName)
return
}
errors <- nil
}(i)
}
// Check all results
for i := 0; i < numGoroutines; i++ {
if err := <-errors; err != nil {
t.Errorf("Goroutine failed: %v", err)
}
}
}
func TestLuaPluginAuthAndPipeCallbacks(t *testing.T) {
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "callbacks.lua")
script := `
failure_count = 0
last_pipe_start = ""
last_pipe_error = ""
last_pipe_create_error = ""
function sshpiper_on_new_connection(conn)
if conn.sshpiper_user == "reject" then
return "blocked"
end
return true
end
function sshpiper_on_next_auth_methods(conn)
if failure_count > 0 then
return {"password"}
end
return {"publickey"}
end
function sshpiper_on_password(conn, password)
return {
host = "localhost:2222",
username = conn.sshpiper_user,
}
end
function sshpiper_on_upstream_auth_failure(conn, method, err, allowed)
failure_count = failure_count + 1
end
function sshpiper_on_banner(conn)
return "welcome " .. conn.sshpiper_user
end
function sshpiper_on_verify_hostkey(conn, hostname, netaddr, key)
if hostname == "ok" then
return true
end
return false, "bad host"
end
function sshpiper_on_pipe_create_error(remote_addr, err)
last_pipe_create_error = remote_addr .. ":" .. err
end
function sshpiper_on_pipe_start(conn)
last_pipe_start = conn.sshpiper_unique_id
end
function sshpiper_on_pipe_error(conn, err)
last_pipe_error = conn.sshpiper_unique_id .. ":" .. err
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{
ScriptPath: scriptPath,
}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("Failed to create config: %v", err)
}
conn := &mockConnMetadata{
username: "alice",
remoteAddr: "192.168.1.100",
uniqueID: "test-uid",
}
rejectConn := &mockConnMetadata{
username: "reject",
remoteAddr: "192.168.1.101",
uniqueID: "reject-uid",
}
if config.NewConnectionCallback == nil {
t.Fatalf("NewConnectionCallback not registered")
}
if config.NextAuthMethodsCallback == nil {
t.Fatalf("NextAuthMethodsCallback not registered")
}
if config.UpstreamAuthFailureCallback == nil {
t.Fatalf("UpstreamAuthFailureCallback not registered")
}
if config.BannerCallback == nil {
t.Fatalf("BannerCallback not registered")
}
if config.VerifyHostKeyCallback == nil {
t.Fatalf("VerifyHostKeyCallback not registered")
}
if config.PipeCreateErrorCallback == nil {
t.Fatalf("PipeCreateErrorCallback not registered")
}
if config.PipeStartCallback == nil {
t.Fatalf("PipeStartCallback not registered")
}
if config.PipeErrorCallback == nil {
t.Fatalf("PipeErrorCallback not registered")
}
if err := config.NewConnectionCallback(conn); err != nil {
t.Fatalf("NewConnectionCallback failed: %v", err)
}
if err := config.NewConnectionCallback(rejectConn); err == nil || !strings.Contains(err.Error(), "blocked") {
t.Fatalf("NewConnectionCallback should fail with blocked message, got: %v", err)
}
methods, err := config.NextAuthMethodsCallback(conn)
if err != nil {
t.Fatalf("NextAuthMethodsCallback failed: %v", err)
}
if len(methods) != 1 || methods[0] != "publickey" {
t.Fatalf("Unexpected methods before failure: %v", methods)
}
config.UpstreamAuthFailureCallback(conn, "password", errors.New("bad"), []string{"password"})
methods, err = config.NextAuthMethodsCallback(conn)
if err != nil {
t.Fatalf("NextAuthMethodsCallback failed after failure: %v", err)
}
if len(methods) != 1 || methods[0] != "password" {
t.Fatalf("Unexpected methods after failure: %v", methods)
}
if banner := config.BannerCallback(conn); banner != "welcome alice" {
t.Fatalf("Unexpected banner: %s", banner)
}
if err := config.VerifyHostKeyCallback(conn, "ok", "addr", []byte("key")); err != nil {
t.Fatalf("VerifyHostKeyCallback should succeed: %v", err)
}
if err := config.VerifyHostKeyCallback(conn, "bad", "addr", []byte("key")); err == nil {
t.Fatalf("VerifyHostKeyCallback should fail for bad host")
}
config.PipeStartCallback(conn)
config.PipeErrorCallback(conn, errors.New("boom"))
config.PipeCreateErrorCallback(conn.RemoteAddr(), errors.New("dial failed"))
L, err := plugin.getLuaState()
if err != nil {
t.Fatalf("failed to get lua state for verification: %v", err)
}
defer plugin.putLuaState(L)
failureCount := L.GetGlobal("failure_count")
if v, ok := failureCount.(lua.LNumber); !ok || int(v) != 1 {
t.Fatalf("failure_count not updated, got %v", failureCount)
}
if v := L.GetGlobal("last_pipe_start"); v != lua.LString(conn.UniqueID()) {
t.Fatalf("unexpected last_pipe_start: %v", v)
}
if v := L.GetGlobal("last_pipe_error"); v != lua.LString(conn.UniqueID()+":boom") {
t.Fatalf("unexpected last_pipe_error: %v", v)
}
if v := L.GetGlobal("last_pipe_create_error"); v != lua.LString(conn.RemoteAddr()+":dial failed") {
t.Fatalf("unexpected last_pipe_create_error: %v", v)
}
}
func TestLuaPluginSearchPath(t *testing.T) {
tmpDir := t.TempDir()
moduleDir := filepath.Join(tmpDir, "modules")
if err := os.MkdirAll(moduleDir, 0o755); err != nil {
t.Fatalf("Failed to create module dir: %v", err)
}
helperPath := filepath.Join(moduleDir, "helper.lua")
helper := `
local M = {}
function M.build(conn, password)
return {
host = "searchpath:2222",
username = "helper_user",
}
end
return M
`
if err := os.WriteFile(helperPath, []byte(helper), 0o644); err != nil {
t.Fatalf("Failed to write helper module: %v", err)
}
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
local helper = require("helper")
function sshpiper_on_password(conn, password)
return helper.build(conn, password)
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{
ScriptPath: scriptPath,
SearchPath: filepath.Join(moduleDir, "?.lua"),
}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("Failed to create config: %v", err)
}
conn := &mockConnMetadata{
username: "alice",
remoteAddr: "192.168.1.100",
uniqueID: "test-123",
}
upstream, err := config.PasswordCallback(conn, []byte("password"))
if err != nil {
t.Fatalf("PasswordCallback failed: %v", err)
}
if upstream.Uri != "tcp://searchpath:2222" {
t.Errorf("Expected URI 'tcp://searchpath:2222', got '%s'", upstream.Uri)
}
if upstream.UserName != "helper_user" {
t.Errorf("Expected username 'helper_user', got '%s'", upstream.UserName)
}
}
func TestLuaPluginNoCallbacks(t *testing.T) {
// Create a temporary Lua script with no callbacks defined
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
-- No callbacks defined
local x = 1 + 1
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{
ScriptPath: scriptPath,
}
_, err := plugin.CreateConfig()
if err == nil {
t.Error("Expected error when no callbacks are defined, got nil")
}
if err != nil && !strings.Contains(err.Error(), "no callbacks defined") {
t.Errorf("Expected error about no callbacks defined, got: %v", err)
}
}
// TestExampleScriptsValid tests that all example Lua scripts are valid
func TestExampleScriptsValid(t *testing.T) {
examplesDir := "examples"
// Check if examples directory exists
if _, err := os.Stat(examplesDir); os.IsNotExist(err) {
t.Skip("Examples directory not found")
}
// Read all .lua files in examples directory
files, err := filepath.Glob(filepath.Join(examplesDir, "*.lua"))
if err != nil {
t.Fatalf("Failed to read examples directory: %v", err)
}
if len(files) == 0 {
t.Error("No example Lua scripts found in examples directory")
}
// Test each example script
for _, file := range files {
t.Run(filepath.Base(file), func(t *testing.T) {
plugin := newLuaPlugin()
plugin.ScriptPath = file
// Try to create config - this validates the script
_, err := plugin.CreateConfig()
if err != nil {
t.Errorf("Example script %s failed to load: %v", filepath.Base(file), err)
}
})
}
}
func TestLuaPluginKnownHostsData(t *testing.T) {
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
function sshpiper_on_password(conn, password)
return {
host = "localhost:2222",
username = "testuser",
known_hosts_data = "host-a ssh-ed25519 AAAA...\n",
}
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{ScriptPath: scriptPath}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("Failed to create config: %v", err)
}
conn := &mockConnMetadata{username: "alice", remoteAddr: "127.0.0.1", uniqueID: "uid"}
upstream, err := config.PasswordCallback(conn, []byte("password"))
if err != nil {
t.Fatalf("PasswordCallback failed: %v", err)
}
if got, want := string(upstream.KnownHostsData), "host-a ssh-ed25519 AAAA...\n"; got != want {
t.Errorf("KnownHostsData = %q, want %q", got, want)
}
}
func TestLuaPluginKnownHostsDataMustBeString(t *testing.T) {
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
function sshpiper_on_password(conn, password)
return {
host = "localhost:2222",
known_hosts_data = 42,
}
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{ScriptPath: scriptPath}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("Failed to create config: %v", err)
}
conn := &mockConnMetadata{username: "alice", uniqueID: "uid"}
if _, err := config.PasswordCallback(conn, []byte("p")); err == nil {
t.Fatal("expected error for non-string known_hosts_data, got nil")
}
}
func TestLuaPluginUpstreamEnv(t *testing.T) {
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
function sshpiper_on_password(conn, password)
return {
host = "localhost:2222",
username = "testuser",
env = {
SSHPIPER_JOBID = "slurm-42",
SSHPIPER_RANK = "0",
},
}
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{ScriptPath: scriptPath}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("Failed to create config: %v", err)
}
conn := &mockConnMetadata{username: "alice", uniqueID: "uid"}
upstream, err := config.PasswordCallback(conn, []byte("p"))
if err != nil {
t.Fatalf("PasswordCallback failed: %v", err)
}
if got, want := upstream.Env["SSHPIPER_JOBID"], "slurm-42"; got != want {
t.Errorf("env[SSHPIPER_JOBID] = %q, want %q", got, want)
}
if got, want := upstream.Env["SSHPIPER_RANK"], "0"; got != want {
t.Errorf("env[SSHPIPER_RANK] = %q, want %q", got, want)
}
if got, want := len(upstream.Env), 2; got != want {
t.Errorf("len(env) = %d, want %d", got, want)
}
}
func TestLuaPluginUpstreamEnvMustBeTable(t *testing.T) {
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
function sshpiper_on_password(conn, password)
return {
host = "localhost:2222",
env = "FOO=bar",
}
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{ScriptPath: scriptPath}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("CreateConfig failed: %v", err)
}
conn := &mockConnMetadata{username: "alice", uniqueID: "uid"}
if _, err := config.PasswordCallback(conn, []byte("p")); err == nil {
t.Fatal("expected error for non-table env, got nil")
}
}
func TestLuaPluginUpstreamEnvValueMustBeString(t *testing.T) {
tmpDir := t.TempDir()
scriptPath := filepath.Join(tmpDir, "test.lua")
script := `
function sshpiper_on_password(conn, password)
return {
host = "localhost:2222",
env = { FOO = 123 },
}
end
`
if err := os.WriteFile(scriptPath, []byte(script), 0o644); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
plugin := &luaPlugin{ScriptPath: scriptPath}
config, err := plugin.CreateConfig()
if err != nil {
t.Fatalf("CreateConfig failed: %v", err)
}
conn := &mockConnMetadata{username: "alice", uniqueID: "uid"}
if _, err := config.PasswordCallback(conn, []byte("p")); err == nil {
t.Fatal("expected error for non-string env value, got nil")
}
}