Repository navigation
Expand file tree
/
Copy pathmain_test.go
More file actions
1296 lines (1241 loc) · 48.5 KB
/
Copy pathmain_test.go
File metadata and controls
1296 lines (1241 loc) · 48.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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/netip"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/maisem/tailmix/controlapi"
"github.com/maisem/tailmix/profilesocket"
tailmixversion "github.com/maisem/tailmix/version"
"github.com/maisem/tailmix/wireguardcfg"
)
type fakeManagementClient struct {
profile controlapi.Profile
profileName string
status controlapi.Status
daemonState controlapi.DaemonState
daemonUp bool
ipPatch controlapi.PatchIPRoutesRequest
exitSet controlapi.SetExitNodeRequest
exitCleared bool
exitNodes controlapi.ExitNodes
dnsPatch controlapi.PatchDNSRoutesRequest
advertised controlapi.AdvertisedRoutes
advertiseSet controlapi.PatchAdvertiseRoutesRequest
advertiseCleared string
searchReplace []string
statusProfiles []controlapi.Profile
serverVersion tailmixversion.Meta
versionErr error
updateStatus controlapi.UpdateStatus
updateAction string
wireGuardConfig wireguardcfg.Config
wireGuardSecrets wireguardcfg.Secrets
wireGuardProfile controlapi.WireGuardProfile
wireGuardName string
wireGuardShields bool
added []controlapi.AddProfileRequest
}
func (f *fakeManagementClient) Version(context.Context) (tailmixversion.Meta, error) {
return f.serverVersion, f.versionErr
}
func (f *fakeManagementClient) Status(context.Context) (controlapi.Status, error) {
return f.status, nil
}
func (f *fakeManagementClient) SetDaemonUp(_ context.Context, up bool) (controlapi.DaemonState, error) {
f.daemonUp = up
return f.daemonState, nil
}
func (f *fakeManagementClient) UpdateStatus(context.Context) (controlapi.UpdateStatus, error) {
return f.updateStatus, nil
}
func (f *fakeManagementClient) UpdateAction(_ context.Context, action string) (controlapi.UpdateStatus, error) {
f.updateAction = action
return f.updateStatus, nil
}
func (f *fakeManagementClient) Profiles(context.Context, bool) (controlapi.Profiles, error) {
if f.statusProfiles != nil {
return controlapi.Profiles{Profiles: f.statusProfiles}, nil
}
return controlapi.Profiles{Profiles: []controlapi.Profile{f.profile}}, nil
}
func (f *fakeManagementClient) Profile(_ context.Context, name string) (controlapi.Profile, error) {
f.profileName = name
return f.profile, nil
}
func (f *fakeManagementClient) AddProfile(_ context.Context, request controlapi.AddProfileRequest) (controlapi.Profile, error) {
f.added = append(f.added, request)
return f.profile, nil
}
func (f *fakeManagementClient) PatchProfile(context.Context, string, controlapi.PatchProfileRequest) (controlapi.Profile, error) {
return f.profile, nil
}
func (f *fakeManagementClient) ProfileAction(context.Context, string, string) (controlapi.Profile, error) {
return f.profile, nil
}
func (f *fakeManagementClient) RemoveProfile(context.Context, string, bool) (controlapi.Profile, error) {
return f.profile, nil
}
func (f *fakeManagementClient) IPRoutes(context.Context, bool) (controlapi.IPRoutes, error) {
return controlapi.IPRoutes{}, nil
}
func (f *fakeManagementClient) PatchIPRoutes(_ context.Context, request controlapi.PatchIPRoutesRequest) (controlapi.IPRoutes, error) {
f.ipPatch = request
return controlapi.IPRoutes{}, nil
}
func (f *fakeManagementClient) ExitNodes(context.Context) (controlapi.ExitNodes, error) {
return f.exitNodes, nil
}
func (f *fakeManagementClient) SetExitNode(_ context.Context, request controlapi.SetExitNodeRequest) (controlapi.ExitNodes, error) {
f.exitSet = request
return f.exitNodes, nil
}
func (f *fakeManagementClient) ClearExitNode(context.Context) (controlapi.ExitNodes, error) {
f.exitCleared = true
return f.exitNodes, nil
}
func (f *fakeManagementClient) AdvertiseRoutes(context.Context) (controlapi.AdvertisedRoutes, error) {
return f.advertised, nil
}
func (f *fakeManagementClient) SetAdvertiseRoutes(_ context.Context, request controlapi.PatchAdvertiseRoutesRequest) (controlapi.AdvertisedRoutes, error) {
f.advertiseSet = request
return f.advertised, nil
}
func (f *fakeManagementClient) ClearAdvertiseRoutes(_ context.Context, name string) (controlapi.AdvertisedRoutes, error) {
f.advertiseCleared = name
return f.advertised, nil
}
func (f *fakeManagementClient) DNSRoutes(context.Context, bool) (controlapi.DNSRoutes, error) {
return controlapi.DNSRoutes{}, nil
}
func (f *fakeManagementClient) PatchDNSRoutes(_ context.Context, request controlapi.PatchDNSRoutesRequest) (controlapi.DNSRoutes, error) {
f.dnsPatch = request
return controlapi.DNSRoutes{}, nil
}
func (f *fakeManagementClient) SearchDomains(context.Context) (controlapi.SearchDomains, error) {
return controlapi.SearchDomains{}, nil
}
func (f *fakeManagementClient) ReplaceSearchDomains(_ context.Context, desired []string) (controlapi.SearchDomains, error) {
f.searchReplace = slices.Clone(desired)
return controlapi.SearchDomains{Desired: desired}, nil
}
func (f *fakeManagementClient) PatchSearchDomains(context.Context, controlapi.PatchSearchDomainsRequest) (controlapi.SearchDomains, error) {
return controlapi.SearchDomains{}, nil
}
func (f *fakeManagementClient) ClearSearchDomains(context.Context) (controlapi.SearchDomains, error) {
return controlapi.SearchDomains{}, nil
}
func (f *fakeManagementClient) ApplyWireGuard(_ context.Context, config wireguardcfg.Config, secrets wireguardcfg.Secrets) (controlapi.WireGuardProfile, error) {
f.wireGuardConfig = config
f.wireGuardSecrets = secrets
return f.wireGuardProfile, nil
}
func (f *fakeManagementClient) WireGuardProfile(_ context.Context, name string) (controlapi.WireGuardProfile, error) {
f.wireGuardName = name
return f.wireGuardProfile, nil
}
func (f *fakeManagementClient) SetWireGuardShieldsUp(_ context.Context, name string, enabled bool) (controlapi.WireGuardProfile, error) {
f.wireGuardName = name
f.wireGuardShields = enabled
f.wireGuardProfile.ShieldsUp = enabled
return f.wireGuardProfile, nil
}
func testDependencies(client managementClient, stdout, stderr io.Writer, runner cliRunner) dependencies {
return dependencies{
stdin: strings.NewReader(""),
stdout: stdout,
stderr: stderr,
runCLI: runner,
newClient: func(string) managementClient {
return client
},
version: "tailmix test-version",
}
}
func TestDaemonLifecycleCommands(t *testing.T) {
for _, test := range []struct {
command string
up bool
}{
{command: "up", up: true},
{command: "down", up: false},
} {
t.Run(test.command, func(t *testing.T) {
client := &fakeManagementClient{daemonState: controlapi.DaemonState{State: test.command}}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{test.command},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 || stderr.Len() != 0 {
t.Fatalf("code = %d, stderr = %q", code, stderr.String())
}
if client.daemonUp != test.up {
t.Fatalf("daemon up = %v, want %v", client.daemonUp, test.up)
}
if got, want := stdout.String(), "tailmix is "+test.command+".\n"; got != want {
t.Fatalf("output = %q, want %q", got, want)
}
})
}
}
func TestDaemonLifecycleCommandsRejectArguments(t *testing.T) {
var stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"down", "now"},
testDependencies(&fakeManagementClient{}, io.Discard, &stderr, nil))
if code != 2 || !strings.Contains(stderr.String(), "unexpected arguments: now") {
t.Fatalf("code = %d, stderr = %q", code, stderr.String())
}
}
func TestUpdateCommands(t *testing.T) {
for _, command := range []string{"status", "enable", "disable", "check", "apply"} {
t.Run(command, func(t *testing.T) {
client := &fakeManagementClient{updateStatus: controlapi.UpdateStatus{
Enabled: true, CurrentVersion: "1.2.3", AvailableVersion: "1.2.4", State: "available",
}}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"update", command},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 || stderr.Len() != 0 {
t.Fatalf("code = %d, stderr = %q", code, stderr.String())
}
if command == "status" {
if client.updateAction != "" {
t.Fatalf("action = %q", client.updateAction)
}
} else if client.updateAction != command {
t.Fatalf("action = %q, want %q", client.updateAction, command)
}
if !strings.Contains(stdout.String(), "1.2.4") {
t.Fatalf("output = %q", stdout.String())
}
})
}
}
func TestUpdateStatusJSON(t *testing.T) {
client := &fakeManagementClient{updateStatus: controlapi.UpdateStatus{Enabled: true, State: "idle"}}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"update", "status", "--json"},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, stderr.String())
}
var got controlapi.UpdateStatus
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatal(err)
}
if !got.Enabled || got.State != "idle" {
t.Fatalf("status = %+v", got)
}
}
func TestWireGuardApplyResolvesKeyFilesRelativeToManifest(t *testing.T) {
dir := t.TempDir()
private, err := wireguardcfg.GeneratePrivateKey()
if err != nil {
t.Fatal(err)
}
peerPrivate, err := wireguardcfg.GeneratePrivateKey()
if err != nil {
t.Fatal(err)
}
peerPublic, err := peerPrivate.Public()
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "private.key"), []byte(private.String()+"\n"), 0o600); err != nil {
t.Fatal(err)
}
manifest := "version: 1\nname: lab\ndnsSuffix: wg.example\naddresses: [10.0.0.1]\nprivateKeyFile: private.key\npeers:\n - name: peer\n publicKey: " + peerPublic.String() + "\n addresses: [10.0.0.2]\n"
manifestPath := filepath.Join(dir, "profile.yaml")
if err := os.WriteFile(manifestPath, []byte(manifest), 0o600); err != nil {
t.Fatal(err)
}
client := &fakeManagementClient{wireGuardProfile: controlapi.WireGuardProfile{Name: "lab", Kind: "wireguard"}}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"wireguard", "apply", "--file", manifestPath},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 || stderr.Len() != 0 {
t.Fatalf("exit = %d, stderr = %q", code, stderr.String())
}
if client.wireGuardConfig.Name != "lab" || client.wireGuardSecrets.PrivateKey == nil || *client.wireGuardSecrets.PrivateKey != private {
t.Fatalf("apply request = config %+v, secrets %+v", client.wireGuardConfig, client.wireGuardSecrets)
}
if !strings.Contains(stdout.String(), "lab") || !strings.Contains(stdout.String(), "wireguard") {
t.Fatalf("output = %q", stdout.String())
}
}
func TestWireGuardApplyReadsManifestFromStdin(t *testing.T) {
private, err := wireguardcfg.GeneratePrivateKey()
if err != nil {
t.Fatal(err)
}
public, err := private.Public()
if err != nil {
t.Fatal(err)
}
manifest := "version: 1\nname: lab\ndnsSuffix: wg.example\naddresses: [10.0.0.1]\npeers:\n - name: peer\n publicKey: " + public.String() + "\n addresses: [10.0.0.2]\n"
client := &fakeManagementClient{wireGuardProfile: controlapi.WireGuardProfile{Name: "lab"}}
deps := testDependencies(client, io.Discard, io.Discard, nil)
deps.stdin = strings.NewReader(manifest)
if code := runWithDependencies(context.Background(), []string{"wireguard", "apply", "--file=-"}, deps); code != 0 {
t.Fatalf("exit = %d", code)
}
if client.wireGuardConfig.Name != "lab" {
t.Fatalf("config = %+v", client.wireGuardConfig)
}
}
func TestWireGuardShieldsUp(t *testing.T) {
client := &fakeManagementClient{wireGuardProfile: controlapi.WireGuardProfile{
Name: "lab", Kind: "wireguard", PacketFilter: wireguardcfg.PacketFilter{Grants: []wireguardcfg.Grant{}},
}}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"wireguard", "shields-up", "lab", "on"},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 || stderr.Len() != 0 {
t.Fatalf("exit = %d, stderr = %q", code, stderr.String())
}
if client.wireGuardName != "lab" || !client.wireGuardShields || !strings.Contains(stdout.String(), "SHIELDS UP:") || !strings.Contains(stdout.String(), "yes") {
t.Fatalf("name = %q, enabled = %v, stdout = %q", client.wireGuardName, client.wireGuardShields, stdout.String())
}
stdout.Reset()
stderr.Reset()
code = runWithDependencies(context.Background(), []string{"wireguard", "shields-up", "lab", "invalid"},
testDependencies(client, &stdout, &stderr, nil))
if code != 2 || !strings.Contains(stderr.String(), "must be on or off") {
t.Fatalf("invalid state exit = %d, stderr = %q", code, stderr.String())
}
}
func TestWireGuardShowJSON(t *testing.T) {
want := controlapi.WireGuardProfile{Name: "lab", Kind: "wireguard", PublicKey: "public", ListenPort: 51820}
client := &fakeManagementClient{wireGuardProfile: want}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"wireguard", "show", "lab", "--json"},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 || stderr.Len() != 0 {
t.Fatalf("exit = %d, stderr = %q", code, stderr.String())
}
var got controlapi.WireGuardProfile
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.Name != want.Name || got.Kind != want.Kind || got.PublicKey != want.PublicKey || got.ListenPort != want.ListenPort || client.wireGuardName != "lab" {
t.Fatalf("profile = %+v, name = %q", got, client.wireGuardName)
}
}
func TestTSSelectsOpaqueProfileLocalAPISocket(t *testing.T) {
socketDir := t.TempDir()
client := &fakeManagementClient{profile: controlapi.Profile{ID: "p_012345", Name: "work"}}
var gotArgs []string
runner := func(_ context.Context, args []string) error {
gotArgs = slices.Clone(args)
return nil
}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"--socket-dir", socketDir, "ts", "--profile", "work", "status", "--json"},
testDependencies(client, &stdout, &stderr, runner))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
wantSocket, err := profilesocket.Path(socketDir, "p_012345")
if err != nil {
t.Fatal(err)
}
want := []string{"--socket=" + wantSocket, "status", "--json"}
if !slices.Equal(gotArgs, want) {
t.Fatalf("upstream CLI args = %q, want %q", gotArgs, want)
}
if client.profileName != "work" {
t.Fatalf("profile selector = %q, want work", client.profileName)
}
}
func TestTSRejectsDelegationWhileDaemonDown(t *testing.T) {
client := &fakeManagementClient{profile: controlapi.Profile{
ID: "p_work", Name: "work", RuntimeState: "down",
}}
var stderr bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"ts", "--profile", "work", "status"},
testDependencies(client, io.Discard, &stderr, func(context.Context, []string) error {
t.Fatal("upstream CLI unexpectedly called")
return nil
}))
if code != 1 || !strings.Contains(stderr.String(), "tailmix is down; run \"tailmix up\" first") {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
}
func TestTSForwardsNativeLoginServer(t *testing.T) {
client := &fakeManagementClient{
profile: controlapi.Profile{ID: "p_work", Name: "work", LocalAPISocket: "/tmp/work.sock"},
}
var gotArgs []string
code := runWithDependencies(context.Background(),
[]string{"ts", "--profile", "work", "login", "--login-server=https://headscale.example.com"},
testDependencies(client, io.Discard, io.Discard, func(_ context.Context, args []string) error {
gotArgs = slices.Clone(args)
return nil
}))
want := []string{
"--socket=/tmp/work.sock",
"login",
"--login-server=https://headscale.example.com",
}
if code != 0 || !slices.Equal(gotArgs, want) {
t.Fatalf("exit = %d, upstream args = %q, want %q", code, gotArgs, want)
}
}
func TestTSRejectsSocketOverride(t *testing.T) {
client := &fakeManagementClient{}
var stderr bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"ts", "--profile", "work", "--socket=/tmp/other", "status"},
testDependencies(client, io.Discard, &stderr, func(context.Context, []string) error {
t.Fatal("upstream CLI unexpectedly called")
return nil
}))
if code != 2 || !bytes.Contains(stderr.Bytes(), []byte("managed by tailmix")) {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
}
func TestTSLeavesUpstreamProfileArgumentsUntouched(t *testing.T) {
client := &fakeManagementClient{profile: controlapi.Profile{ID: "p_work", Name: "work", LocalAPISocket: "/tmp/work.sock"}}
var gotArgs []string
code := runWithDependencies(context.Background(),
[]string{"ts", "-p", "work", "switch", "--profile", "upstream-profile"},
testDependencies(client, io.Discard, io.Discard, func(_ context.Context, args []string) error {
gotArgs = slices.Clone(args)
return nil
}))
want := []string{"--socket=/tmp/work.sock", "switch", "--profile", "upstream-profile"}
if code != 0 || !slices.Equal(gotArgs, want) {
t.Fatalf("exit = %d, upstream args = %q, want %q", code, gotArgs, want)
}
}
func TestShortProfileOption(t *testing.T) {
tests := []struct {
name string
args []string
gotProfile func(*fakeManagementClient) string
}{
{
name: "tailscale delegation",
args: []string{"ts", "-p", "work", "status"},
gotProfile: func(client *fakeManagementClient) string {
return client.profileName
},
},
{
name: "IP route bind",
args: []string{"routes", "bind", "-p", "work", "10.20.0.0/16"},
gotProfile: func(client *fakeManagementClient) string {
if len(client.ipPatch.Bind) == 0 {
return ""
}
return client.ipPatch.Bind[0].ProfileName
},
},
{
name: "IP route unbind",
args: []string{"routes", "unbind", "10.20.0.0/16", "-p=work"},
gotProfile: func(client *fakeManagementClient) string {
if len(client.ipPatch.Unbind) == 0 {
return ""
}
return client.ipPatch.Unbind[0].ProfileName
},
},
{
name: "IP route accept all",
args: []string{"routes", "set", "-p", "work", "--accept-all=true"},
gotProfile: func(client *fakeManagementClient) string {
if _, ok := client.ipPatch.AcceptAll["work"]; ok {
return "work"
}
return ""
},
},
{
name: "exit node",
args: []string{"exit-node", "set", "-p", "work", "gateway"},
gotProfile: func(client *fakeManagementClient) string {
return client.exitSet.ProfileName
},
},
{
name: "DNS route bind",
args: []string{"dns", "routes", "bind", "-p", "work", "corp.example"},
gotProfile: func(client *fakeManagementClient) string {
if len(client.dnsPatch.Bind) == 0 {
return ""
}
return client.dnsPatch.Bind[0].ProfileName
},
},
{
name: "DNS route unbind",
args: []string{"dns", "routes", "unbind", "corp.example", "-p=work"},
gotProfile: func(client *fakeManagementClient) string {
if len(client.dnsPatch.Unbind) == 0 {
return ""
}
return client.dnsPatch.Unbind[0].ProfileName
},
},
{
name: "DNS route accept all",
args: []string{"dns", "routes", "set", "-p", "work", "--accept-all=true"},
gotProfile: func(client *fakeManagementClient) string {
if _, ok := client.dnsPatch.AcceptAll["work"]; ok {
return "work"
}
return ""
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
client := &fakeManagementClient{profile: controlapi.Profile{
ID: "p_work", Name: "work", LocalAPISocket: "/tmp/work.sock",
}}
var stderr bytes.Buffer
code := runWithDependencies(context.Background(), test.args,
testDependencies(client, io.Discard, &stderr, func(context.Context, []string) error {
return nil
}))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
if got := test.gotProfile(client); got != "work" {
t.Fatalf("profile = %q, want work", got)
}
})
}
}
func TestProfileOptionRejectsMixedAliases(t *testing.T) {
var stderr bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"routes", "bind", "-p", "work", "--profile", "home", "10.20.0.0/16"},
testDependencies(&fakeManagementClient{}, io.Discard, &stderr, nil))
if code != 2 || !strings.Contains(stderr.String(), "--profile may be specified only once") {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
}
func TestLegacySyntaxExplainsReplacement(t *testing.T) {
var stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"work", "status"},
testDependencies(&fakeManagementClient{}, io.Discard, &stderr, nil))
if code != 2 || !strings.Contains(stderr.String(), "tailmix ts --profile work status") {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
}
func TestRootHelpShowsFullSubcommandSpace(t *testing.T) {
var stdout bytes.Buffer
code := runWithDependencies(context.Background(), []string{"help"},
testDependencies(&fakeManagementClient{}, &stdout, io.Discard, nil))
if code != 0 {
t.Fatalf("exit code = %d", code)
}
for _, command := range []string{"status", "up", "down", "profiles", "routes", "exit-node", "dns routes", "dns search", "wireguard", "tailscale", "ts", "completion", "version"} {
if !strings.Contains(stdout.String(), command) {
t.Errorf("help does not contain %q:\n%s", command, stdout.String())
}
}
}
func TestCompletionScripts(t *testing.T) {
for _, shell := range []string{"bash", "zsh", "fish", "powershell", "pwsh"} {
t.Run(shell, func(t *testing.T) {
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"completion", shell},
testDependencies(&fakeManagementClient{}, &stdout, &stderr, nil))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
if !strings.Contains(stdout.String(), "completion __complete --") {
t.Fatalf("completion script does not invoke tailmix's completion endpoint:\n%s", stdout.String())
}
})
}
}
func TestCompletionSuggestsCommandsFlagsAndValues(t *testing.T) {
client := &fakeManagementClient{statusProfiles: []controlapi.Profile{
{Name: "home", RuntimeState: "running"},
{Name: "work", RuntimeState: "disabled"},
}}
tests := []struct {
name string
words []string
want []string
}{
{name: "root commands", words: []string{""}, want: []string{"up\t", "down\t", "profiles\t", "completion\t", "--socket-dir\t"}},
{name: "subcommands", words: []string{"profiles", ""}, want: []string{"list\t", "rename\t", "help\t"}},
{name: "update subcommands", words: []string{"update", ""}, want: []string{"status\t", "check\t", "apply\t"}},
{name: "wireguard subcommands", words: []string{"wireguard", ""}, want: []string{"apply\t", "show\t", "shields-up\t"}},
{name: "wireguard shields profile", words: []string{"wireguard", "shields-up", "w"}, want: []string{"work\tdisabled"}},
{name: "wireguard shields state", words: []string{"wireguard", "shields-up", "work", ""}, want: []string{"off\t", "on\t"}},
{name: "long flag", words: []string{"routes", "bind", "--pro"}, want: []string{"--profile\t"}},
{name: "profile flag value", words: []string{"routes", "bind", "--profile", "w"}, want: []string{"work\tdisabled"}},
{name: "profile operand", words: []string{"profiles", "show", "h"}, want: []string{"home\trunning"}},
{name: "boolean flag value", words: []string{"routes", "set", "--accept-all="}, want: []string{"false\t", "true\t"}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
args := []string{"completion", "__complete", "--"}
args = append(args, test.words...)
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), args,
testDependencies(client, &stdout, &stderr, nil))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
for _, want := range test.want {
if !strings.Contains(stdout.String(), want) {
t.Errorf("completion output does not contain %q:\n%s", want, stdout.String())
}
}
if !strings.HasSuffix(stdout.String(), ":4\n") {
t.Errorf("completion output does not disable file completion:\n%s", stdout.String())
}
})
}
}
func TestCompletionDelegatesToSelectedTailscaleProfile(t *testing.T) {
client := &fakeManagementClient{profile: controlapi.Profile{
Name: "work", LocalAPISocket: "/tmp/work.sock",
}}
var gotArgs []string
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"completion", "__complete", "--", "ts", "--profile", "work", "st"},
testDependencies(client, &stdout, &stderr, func(_ context.Context, args []string) error {
gotArgs = slices.Clone(args)
return nil
}))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
want := []string{"--socket=/tmp/work.sock", "completion", "__complete", "--", "st"}
if !slices.Equal(gotArgs, want) {
t.Fatalf("upstream completion args = %q, want %q", gotArgs, want)
}
}
func TestCompletionDoesNotDelegateWhileDaemonDown(t *testing.T) {
client := &fakeManagementClient{profile: controlapi.Profile{
Name: "work", RuntimeState: "down",
}}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"completion", "__complete", "--", "ts", "--profile", "work", "st"},
testDependencies(client, &stdout, &stderr, func(context.Context, []string) error {
t.Fatal("upstream completion unexpectedly called")
return nil
}))
if code != 0 || stderr.Len() != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
if !strings.Contains(stdout.String(), "status\t") {
t.Fatalf("fallback completion = %q", stdout.String())
}
}
func TestVersion(t *testing.T) {
client := &fakeManagementClient{serverVersion: tailmixversion.Meta{
Short: "daemon-version",
Long: "daemon-long-version",
TailscaleVersion: "tailscale-version",
}}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"version"},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
want := "tailmix test-version\n\n" +
"tailmixd daemon-version\n" +
" long version: daemon-long-version\n" +
" tailscale: tailscale-version\n"
if got := stdout.String(); got != want {
t.Fatalf("version output = %q, want %q", got, want)
}
}
func TestVersionReportsUnavailableDaemon(t *testing.T) {
client := &fakeManagementClient{versionErr: errors.New("unavailable")}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"version"},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
if got, want := stdout.String(), "tailmix test-version\n\ntailmixd unavailable\n"; got != want {
t.Fatalf("version output = %q, want %q", got, want)
}
}
func TestProfilesHelpOmitsControlURL(t *testing.T) {
var stdout bytes.Buffer
code := runWithDependencies(context.Background(), []string{"profiles", "help"},
testDependencies(&fakeManagementClient{}, &stdout, io.Discard, nil))
if code != 0 {
t.Fatalf("exit code = %d", code)
}
if strings.Contains(stdout.String(), "control-url") {
t.Fatalf("profiles help still contains control-url:\n%s", stdout.String())
}
}
func TestStatusShowsActiveProfilesAndAcceptedPolicy(t *testing.T) {
prefix := netip.MustParsePrefix("10.20.0.0/16")
client := &fakeManagementClient{
status: controlapi.Status{
State: "up",
Profiles: []controlapi.Profile{{
ID: "work-id", Name: "work", Enabled: true, RuntimeState: "running",
MagicDNSSuffix: "corp.example", PeerCount: 3,
}},
IPRoutes: controlapi.IPRoutes{Bindings: []controlapi.IPRouteBinding{{
Prefix: prefix, ProfileID: "work-id", ProfileName: "work",
State: "installed", CoveringRoute: prefix,
}}},
ExitNodes: controlapi.ExitNodes{Selected: &controlapi.SelectedExitNode{
ProfileID: "work-id", ProfileName: "work", NodeID: "gateway-id",
DNSName: "gateway.corp.example", Online: true, State: "installed",
}},
DNSRoutes: controlapi.DNSRoutes{Automatic: []controlapi.DNSRouteBinding{{
Domain: "corp.example", ProfileID: "work-id", ProfileName: "work",
Source: "magicdns", State: "installed",
}}},
SearchDomains: controlapi.SearchDomains{
Desired: []string{"corp.example"},
Installed: []controlapi.InstalledSearchDomain{{
Domain: "corp.example", ProfileID: "work-id", ProfileName: "work",
}},
},
},
}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"status"},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
for _, want := range []string{
"STATE\tup", "PROFILE", "work", "running", "corp.example",
"IP ROUTES", prefix.String(),
"EXIT NODE", "gateway.corp.example",
"DNS ROUTES", "magicdns",
"DNS SEARCH", "ORDER",
} {
if !strings.Contains(stdout.String(), want) {
t.Errorf("status does not contain %q:\n%s", want, stdout.String())
}
}
}
func TestStatusJSONIncludesAcceptedPolicy(t *testing.T) {
client := &fakeManagementClient{
status: controlapi.Status{
State: "down",
Profiles: []controlapi.Profile{{ID: "work-id", Name: "work"}},
DNSRoutes: controlapi.DNSRoutes{Automatic: []controlapi.DNSRouteBinding{{
Domain: "corp.example", ProfileID: "work-id", ProfileName: "work",
State: "installed",
}}},
},
}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"status", "--json"},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
var got controlapi.Status
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.State != "down" || len(got.Profiles) != 1 || got.Profiles[0].Name != "work" {
t.Fatalf("status JSON = %+v", got)
}
if len(got.DNSRoutes.Automatic) != 1 || got.DNSRoutes.Automatic[0].Domain != "corp.example" {
t.Fatalf("status JSON DNS routes = %+v", got.DNSRoutes)
}
}
func TestStatusOmitsEmptyPolicySections(t *testing.T) {
client := &fakeManagementClient{status: controlapi.Status{
State: "down",
Profiles: []controlapi.Profile{{ID: "work-id", Name: "work"}},
}}
var stdout, stderr bytes.Buffer
code := runWithDependencies(context.Background(), []string{"status"},
testDependencies(client, &stdout, &stderr, nil))
if code != 0 {
t.Fatalf("exit code = %d, stderr = %q", code, stderr.String())
}
for _, unwanted := range []string{"IP ROUTES", "EXIT NODE", "DNS ROUTES", "DNS SEARCH", "(none)"} {
if strings.Contains(stdout.String(), unwanted) {
t.Errorf("empty status unexpectedly contains %q:\n%s", unwanted, stdout.String())
}
}
}
func TestRouteBindingAndAcceptAllRequests(t *testing.T) {
client := &fakeManagementClient{}
code := runWithDependencies(context.Background(),
[]string{"routes", "bind", "--profile", "work", "10.20.3.4/16", "2001:db8::1/64"},
testDependencies(client, io.Discard, io.Discard, nil))
if code != 0 {
t.Fatalf("bind exit code = %d", code)
}
wantPrefixes := []netip.Prefix{netip.MustParsePrefix("10.20.0.0/16"), netip.MustParsePrefix("2001:db8::/64")}
for i, want := range wantPrefixes {
if client.ipPatch.Bind[i].Prefix != want || client.ipPatch.Bind[i].ProfileName != "work" {
t.Fatalf("binding %d = %+v, want %v -> work", i, client.ipPatch.Bind[i], want)
}
}
code = runWithDependencies(context.Background(),
[]string{"routes", "set", "--profile", "work", "--accept-all=true"},
testDependencies(client, io.Discard, io.Discard, nil))
if code != 0 || !client.ipPatch.AcceptAll["work"] {
t.Fatalf("accept-all exit = %d, request = %+v", code, client.ipPatch)
}
}
func TestExitNodeSetAndClearRequests(t *testing.T) {
client := &fakeManagementClient{}
code := runWithDependencies(context.Background(),
[]string{"exit-node", "set", "--profile", "work", "gateway"},
testDependencies(client, io.Discard, io.Discard, nil))
if code != 0 {
t.Fatalf("set exit code = %d", code)
}
if client.exitSet.ProfileName != "work" || client.exitSet.Peer != "gateway" {
t.Fatalf("set request = %+v", client.exitSet)
}
code = runWithDependencies(context.Background(),
[]string{"exit-node", "clear"},
testDependencies(client, io.Discard, io.Discard, nil))
if code != 0 || !client.exitCleared {
t.Fatalf("clear exit code = %d, cleared = %v", code, client.exitCleared)
}
}
func TestAdvertiseSetAcceptsExitDefaults(t *testing.T) {
client := &fakeManagementClient{advertised: controlapi.AdvertisedRoutes{
Profiles: []controlapi.ProfileAdvertisedRoutes{{
ProfileID: "work-id", ProfileName: "work",
Routes: []netip.Prefix{netip.MustParsePrefix("0.0.0.0/0"), netip.MustParsePrefix("::/0")},
Applied: []netip.Prefix{netip.MustParsePrefix("0.0.0.0/0"), netip.MustParsePrefix("::/0")},
State: "installed",
}},
}}
code := runWithDependencies(context.Background(),
[]string{"advertise", "set", "--profile", "work", "0.0.0.0/0", "::/0"},
testDependencies(client, io.Discard, io.Discard, nil))
if code != 0 {
t.Fatalf("advertise set exit code = %d", code)
}
want := []netip.Prefix{netip.MustParsePrefix("0.0.0.0/0"), netip.MustParsePrefix("::/0")}
if client.advertiseSet.ProfileName != "work" || !client.advertiseSet.Replace ||
!slices.Equal(client.advertiseSet.Add, want) {
t.Fatalf("advertise set request = %+v", client.advertiseSet)
}
code = runWithDependencies(context.Background(),
[]string{"advertise", "clear", "--profile", "work"},
testDependencies(client, io.Discard, io.Discard, nil))
if code != 0 || client.advertiseCleared != "work" {
t.Fatalf("advertise clear code = %d, cleared = %q", code, client.advertiseCleared)
}
var stderr bytes.Buffer
code = runWithDependencies(context.Background(),
[]string{"advertise", "set", "10.0.0.0/8"},
testDependencies(client, io.Discard, &stderr, nil))
if code != 2 || !strings.Contains(stderr.String(), "advertise set requires --profile") {
t.Fatalf("code = %d, stderr = %q", code, stderr.String())
}
}
func TestAdvertiseListShowsDesiredAndApplied(t *testing.T) {
client := &fakeManagementClient{advertised: controlapi.AdvertisedRoutes{
Profiles: []controlapi.ProfileAdvertisedRoutes{{
ProfileID: "work-id", ProfileName: "work",
Routes: []netip.Prefix{netip.MustParsePrefix("0.0.0.0/0"), netip.MustParsePrefix("::/0")},
Applied: []netip.Prefix{netip.MustParsePrefix("0.0.0.0/0"), netip.MustParsePrefix("::/0")},
State: "installed",
}},
}}
var stdout bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"advertise", "list", "--profile", "work"},
testDependencies(client, &stdout, io.Discard, nil))
if code != 0 {
t.Fatalf("advertise list exit code = %d", code)
}
for _, want := range []string{"PROFILE", "work", "0.0.0.0/0", "::/0", "✓"} {
if !strings.Contains(stdout.String(), want) {
t.Fatalf("advertise list does not contain %q:\n%s", want, stdout.String())
}
}
}
func TestExitNodeListShowsSelectedAndAvailableNodes(t *testing.T) {
nodeIP := netip.MustParseAddr("100.64.0.20")
client := &fakeManagementClient{exitNodes: controlapi.ExitNodes{
Selected: &controlapi.SelectedExitNode{
ProfileID: "work-id", ProfileName: "work", NodeID: "node-id",
DNSName: "gateway.tailnet.ts.net", PeerIP: nodeIP, Online: true, State: "installed",
},
Available: []controlapi.AvailableExitNode{{
ProfileID: "work-id", ProfileName: "work", NodeID: "node-id",
DNSName: "gateway.tailnet.ts.net", IPs: []netip.Addr{nodeIP}, Online: true,
}},
}}
var stdout bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"exit-node", "list"},
testDependencies(client, &stdout, io.Discard, nil))
if code != 0 {
t.Fatalf("list exit code = %d", code)
}
for _, want := range []string{"PROFILE", "gateway.tailnet.ts.net", nodeIP.String(), "yes", "✓"} {
if !strings.Contains(stdout.String(), want) {
t.Fatalf("exit-node list does not contain %q:\n%s", want, stdout.String())
}
}
}
func TestExitNodeListUsesTailscaleLocationFiltering(t *testing.T) {
client := &fakeManagementClient{exitNodes: cliLocationExitNodes()}
var stdout bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"exit-node", "list"},
testDependencies(client, &stdout, io.Discard, nil))
if code != 0 {
t.Fatalf("list exit code = %d", code)
}
output := stdout.String()
for _, want := range []string{
"COUNTRY", "CITY", "Canada", "Any", "squamish-high", "squamish-selected",
"vancouver-high", "Germany", "legacy",
} {
if !strings.Contains(output, want) {
t.Fatalf("exit-node list does not contain %q:\n%s", want, output)
}
}
if strings.Contains(output, "vancouver-hidden") {
t.Fatalf("lower-priority city peer was not hidden:\n%s", output)
}
}
func TestExitNodeListCountryFilterShowsCompleteCountry(t *testing.T) {
client := &fakeManagementClient{exitNodes: cliLocationExitNodes()}
var stdout bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"exit-node", "list", "--filter", "cAnAdA"},
testDependencies(client, &stdout, io.Discard, nil))
if code != 0 {
t.Fatalf("filtered list exit code = %d", code)
}
output := stdout.String()
for _, want := range []string{"squamish-high", "squamish-selected", "vancouver-high", "vancouver-hidden"} {
if !strings.Contains(output, want) {
t.Fatalf("filtered list does not contain %q:\n%s", want, output)
}
}
for _, hidden := range []string{"Any", "berlin", "legacy"} {
if strings.Contains(output, hidden) {
t.Fatalf("filtered list unexpectedly contains %q:\n%s", hidden, output)
}
}
}
func TestExitNodeListCountryFilterPreservesJSONSchema(t *testing.T) {
client := &fakeManagementClient{exitNodes: cliLocationExitNodes()}
var stdout bytes.Buffer
code := runWithDependencies(context.Background(),
[]string{"exit-node", "list", "--filter=Canada", "--json"},
testDependencies(client, &stdout, io.Discard, nil))
if code != 0 {
t.Fatalf("filtered JSON exit code = %d", code)
}
var got controlapi.ExitNodes
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatal(err)
}
if len(got.Available) != 4 || got.Selected == nil || got.Selected.NodeID != "squamish-selected" {