-
Notifications
You must be signed in to change notification settings - Fork 44
/
client_test.go
2590 lines (2235 loc) · 107 KB
/
client_test.go
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"
"fmt"
"os"
"os/exec"
"path"
"regexp"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"gorm.io/gorm"
"github.com/ddworken/hishtory/client/cmd"
"github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib"
"github.com/ddworken/hishtory/shared"
"github.com/ddworken/hishtory/shared/testutils"
"github.com/stretchr/testify/require"
)
func skipSlowTests() bool {
return os.Getenv("FAST") != ""
}
func TestMain(m *testing.M) {
// Configure key environment variables
defer testutils.BackupAndRestoreEnv("HISHTORY_TEST")()
os.Setenv("HISHTORY_TEST", "1")
defer testutils.BackupAndRestoreEnv("HISHTORY_SKIP_INIT_IMPORT")()
os.Setenv("HISHTORY_SKIP_INIT_IMPORT", "1")
// Start the test server
defer testutils.RunTestServer()()
// Build the client so it is available in /tmp/client
cmd := exec.Command("go", "build", "-o", "/tmp/client")
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "CGO_ENABLED=0")
err := cmd.Run()
if err != nil {
panic(fmt.Sprintf("failed to build client: %v", err))
}
// Start the tests
m.Run()
}
var shellTesters []shellTester = []shellTester{bashTester{}, zshTester{}}
func TestParam(t *testing.T) {
if skipSlowTests() {
shellTesters = shellTesters[:1]
}
for _, tester := range shellTesters {
t.Run("testRepeatedCommandThenQuery/"+tester.ShellName(), func(t *testing.T) { testRepeatedCommandThenQuery(t, tester) })
t.Run("testRepeatedCommandAndQuery/"+tester.ShellName(), func(t *testing.T) { testRepeatedCommandAndQuery(t, tester) })
t.Run("testRepeatedEnableDisable/"+tester.ShellName(), func(t *testing.T) { testRepeatedEnableDisable(t, tester) })
t.Run("testExcludeHiddenCommand/"+tester.ShellName(), func(t *testing.T) { testExcludeHiddenCommand(t, tester) })
t.Run("testUpdate/head->release/"+tester.ShellName(), func(t *testing.T) { testUpdateFromHeadToRelease(t, tester) })
t.Run("testUpdate/prev->release/"+tester.ShellName(), func(t *testing.T) { testUpdateFromPrevToRelease(t, tester) })
t.Run("testUpdate/prev->release/prod/"+tester.ShellName(), func(t *testing.T) { testUpdateFromPrevToReleaseViaProd(t, tester) })
t.Run("testUpdate/prev->current/"+tester.ShellName(), func(t *testing.T) { testUpdateFromPrevToCurrent(t, tester) })
t.Run("testAdvancedQuery/"+tester.ShellName(), func(t *testing.T) { testAdvancedQuery(t, tester) })
t.Run("testIntegration/"+tester.ShellName(), func(t *testing.T) { testIntegration(t, tester, Online) })
t.Run("testIntegration/offline/"+tester.ShellName(), func(t *testing.T) { testIntegration(t, tester, Offline) })
t.Run("testIntegrationWithNewDevice/"+tester.ShellName(), func(t *testing.T) { testIntegrationWithNewDevice(t, tester) })
t.Run("testHishtoryBackgroundSaving/"+tester.ShellName(), func(t *testing.T) { testHishtoryBackgroundSaving(t, tester) })
t.Run("testDisplayTable/"+tester.ShellName(), func(t *testing.T) { testDisplayTable(t, tester) })
t.Run("testTableDisplayCwd/"+tester.ShellName(), func(t *testing.T) { testTableDisplayCwd(t, tester) })
t.Run("testTimestampsAreReasonablyCorrect/"+tester.ShellName(), func(t *testing.T) { testTimestampsAreReasonablyCorrect(t, tester) })
t.Run("testRequestAndReceiveDbDump/"+tester.ShellName(), func(t *testing.T) { testRequestAndReceiveDbDump(t, tester) })
t.Run("testInstallViaPythonScript/"+tester.ShellName(), func(t *testing.T) { testInstallViaPythonScript(t, tester) })
t.Run("testExportWithQuery/"+tester.ShellName(), func(t *testing.T) { testExportWithQuery(t, tester) })
t.Run("testHelpCommand/"+tester.ShellName(), func(t *testing.T) { testHelpCommand(t, tester) })
t.Run("testReuploadHistoryEntries/"+tester.ShellName(), func(t *testing.T) { testReuploadHistoryEntries(t, tester) })
t.Run("testHishtoryOffline/"+tester.ShellName(), func(t *testing.T) { testHishtoryOffline(t, tester) })
t.Run("testInitialHistoryImport/"+tester.ShellName(), func(t *testing.T) { testInitialHistoryImport(t, tester) })
t.Run("testLocalRedaction/"+tester.ShellName(), func(t *testing.T) { testLocalRedaction(t, tester, Online) })
t.Run("testLocalRedaction/offline/"+tester.ShellName(), func(t *testing.T) { testLocalRedaction(t, tester, Offline) })
t.Run("testRemoteRedaction/"+tester.ShellName(), func(t *testing.T) { testRemoteRedaction(t, tester) })
t.Run("testMultipleUsers/"+tester.ShellName(), func(t *testing.T) { testMultipleUsers(t, tester) })
t.Run("testConfigGetSet/"+tester.ShellName(), func(t *testing.T) { testConfigGetSet(t, tester) })
t.Run("testHandleUpgradedFeatures/"+tester.ShellName(), func(t *testing.T) { testHandleUpgradedFeatures(t, tester) })
t.Run("testCustomColumns/"+tester.ShellName(), func(t *testing.T) { testCustomColumns(t, tester) })
t.Run("testUninstall/"+tester.ShellName(), func(t *testing.T) { testUninstall(t, tester) })
t.Run("testPresaving/"+tester.ShellName(), func(t *testing.T) { testPresaving(t, tester) })
t.Run("testControlR/"+tester.ShellName(), func(t *testing.T) { testControlR(t, tester, tester.ShellName(), Online) })
}
t.Run("testControlR/offline/bash", func(t *testing.T) { testControlR(t, bashTester{}, "bash", Offline) })
t.Run("testControlR/fish", func(t *testing.T) { testControlR(t, bashTester{}, "fish", Online) })
t.Run("testTui/search", testTui_search)
t.Run("testTui/general", testTui_general)
t.Run("testTui/scroll", testTui_scroll)
t.Run("testTui/resize", testTui_resize)
t.Run("testTui/delete", testTui_delete)
t.Run("testTui/color", testTui_color)
// Assert there are no leaked connections
assertNoLeakedConnections(t)
}
func testIntegration(t *testing.T, tester shellTester, onlineStatus OnlineStatus) {
// Set up
defer testutils.BackupAndRestore(t)()
// Run the test
testBasicUserFlow(t, tester, onlineStatus)
}
func testIntegrationWithNewDevice(t *testing.T, tester shellTester) {
// Set up
defer testutils.BackupAndRestore(t)()
// Run the test
userSecret := testBasicUserFlow(t, tester, Online)
// Clear all local state
testutils.ResetLocalState(t)
// Install it again
installHishtory(t, tester, userSecret)
// Querying should show the history from the previous run
out := tester.RunInteractiveShell(t, `hishtory query`)
expected := []string{"echo thisisrecorded", "hishtory enable", "echo bar", "echo foo", "ls /foo", "ls /bar", "ls /a"}
for _, item := range expected {
require.Contains(t, out, item)
if strings.Count(out, item) != 1 {
t.Fatalf("output has %#v in it multiple times! out=%#v", item, out)
}
}
tester.RunInteractiveShell(t, "echo mynewcommand")
out = hishtoryQuery(t, tester, "")
require.Contains(t, out, "echo mynewcommand")
if strings.Count(out, "echo mynewcommand") != 1 {
t.Fatalf("output has `echo mynewcommand` the wrong number of times")
}
// Clear local state again
testutils.ResetLocalState(t)
// Install it a 3rd time
installHishtory(t, tester, "adifferentsecret")
// Run a command that shouldn't be in the hishtory later on
tester.RunInteractiveShell(t, `echo notinthehistory`)
out = hishtoryQuery(t, tester, "")
require.Contains(t, out, "echo notinthehistory")
// Set the secret key to the previous secret key
out, err := tester.RunInteractiveShellRelaxed(t, ` export HISHTORY_SKIP_INIT_IMPORT=1
yes | hishtory init `+userSecret)
require.NoError(t, err)
require.Contains(t, out, "Setting secret hishtory key to "+userSecret, "Failed to re-init with the user secret")
// Querying shouldn't show the entry from the previous account
out = hishtoryQuery(t, tester, "")
require.NotContains(t, out, "notinthehistory", "output contains the unexpected item: notinthehistory")
// And it should show the history from the previous run on this account
expected = []string{"echo thisisrecorded", "echo mynewcommand", "hishtory enable", "echo bar", "echo foo", "ls /foo", "ls /bar", "ls /a"}
for _, item := range expected {
require.Contains(t, out, item, "output is missing expected item")
if strings.Count(out, item) != 1 {
t.Fatalf("output has %#v in it multiple times! out=%#v", item, out)
}
}
tester.RunInteractiveShell(t, "echo mynewercommand")
out = hishtoryQuery(t, tester, "")
require.Contains(t, out, "echo mynewercommand")
if strings.Count(out, "echo mynewercommand") != 1 {
t.Fatalf("output has `echo mynewercommand` the wrong number of times")
}
// Manually submit an event that isn't in the local DB, and then we'll
// check if we see it when we do a query without ever having done an init
newEntry := testutils.MakeFakeHistoryEntry("othercomputer")
newEntry.StartTime = time.Now()
newEntry.EndTime = time.Now()
manuallySubmitHistoryEntry(t, userSecret, newEntry)
// Now check if that is in there when we do hishtory query
out = hishtoryQuery(t, tester, "")
require.Contains(t, out, "othercomputer", "hishtory query doesn't contain cmd run on another machine")
// Run a reupload just to test that flow
tester.RunInteractiveShell(t, "hishtory reupload")
// Finally, test the export command
out = tester.RunInteractiveShell(t, `hishtory export | grep -v pipefail | grep -v '/tmp/client install'`)
require.NotContains(t, out, "thisisnotrecorded", "hishtory export contains a command that should not have been recorded")
expectedOutputWithoutKey := "hishtory status\nhishtory query\nls /a\nls /bar\nls /foo\necho foo\necho bar\nhishtory enable\necho thisisrecorded\nhishtory query\nhishtory query foo\necho hello | grep complex | sed s/h/i/g; echo baz && echo \"fo 'o\" # mycommand\nhishtory query complex\nhishtory query\necho mynewcommand\nhishtory query\nyes | hishtory init %s\nhishtory query\necho mynewercommand\nhishtory query\nothercomputer\nhishtory query\nhishtory reupload\n"
expectedOutput := fmt.Sprintf(expectedOutputWithoutKey, userSecret)
if diff := cmp.Diff(expectedOutput, out); diff != "" {
t.Fatalf("hishtory export mismatch (-expected +got):\n%s\nout=%#v", diff, out)
}
// And test the export for each shell without anything filtered out
out = tester.RunInteractiveShell(t, `hishtory export -pipefail | grep -v 'hishtory init '`)
testutils.CompareGoldens(t, out, "testIntegrationWithNewDevice-"+tester.ShellName())
// And test the table but with a subset of columns that is static
tester.RunInteractiveShell(t, `hishtory config-set displayed-columns Hostname 'Exit Code' Command`)
out = tester.RunInteractiveShell(t, `hishtory query -pipefail | grep -v 'hishtory init ' | grep -v 'ls /'`)
testutils.CompareGoldens(t, out, "testIntegrationWithNewDevice-table"+tester.ShellName())
// Assert there are no leaked connections
assertNoLeakedConnections(t)
}
func installWithOnlineStatus(t testing.TB, tester shellTester, onlineStatus OnlineStatus) string {
if onlineStatus == Online {
return installHishtory(t, tester, "")
} else {
return installHishtory(t, tester, "--offline")
}
}
func testBasicUserFlow(t *testing.T, tester shellTester, onlineStatus OnlineStatus) string {
// Test install
userSecret := installWithOnlineStatus(t, tester, onlineStatus)
assertOnlineStatus(t, onlineStatus)
// Test the status subcommand
out := tester.RunInteractiveShell(t, `hishtory status`)
if out != fmt.Sprintf("hiSHtory: v0.Unknown\nEnabled: true\nSecret Key: %s\nCommit Hash: Unknown\n", userSecret) {
t.Fatalf("status command has unexpected output: %#v", out)
}
// Assert that hishtory is correctly using the dev config.sh
homedir, err := os.UserHomeDir()
require.NoError(t, err)
dat, err := os.ReadFile(path.Join(homedir, data.GetHishtoryPath(), "config.sh"))
require.NoError(t, err, "failed to read config.sh")
require.NotContains(t, string(dat), "# Background Run", "config.sh is the prod version when it shouldn't be")
// Test the banner
if onlineStatus == Online {
os.Setenv("FORCED_BANNER", "HELLO_FROM_SERVER")
defer os.Setenv("FORCED_BANNER", "")
out = hishtoryQuery(t, tester, "")
require.Contains(t, out, "HELLO_FROM_SERVER\nHostname", "hishtory query didn't show the banner message")
os.Setenv("FORCED_BANNER", "")
}
// Test recording commands
out, err = tester.RunInteractiveShellRelaxed(t, `ls /a
ls /bar
ls /foo
echo foo
echo bar
hishtory disable
echo thisisnotrecorded
sleep 0.5
hishtory enable
echo thisisrecorded`)
require.NoError(t, err)
if out != "foo\nbar\nthisisnotrecorded\nthisisrecorded\n" {
t.Fatalf("unexpected output from running commands: %#v", out)
}
// Test querying for all commands
out = hishtoryQuery(t, tester, "")
expected := []string{"echo thisisrecorded", "hishtory enable", "echo bar", "echo foo", "ls /foo", "ls /bar", "ls /a"}
for _, item := range expected {
require.Contains(t, out, item, "output is missing expected item")
}
// Test the actual table output
hostnameMatcher := `\S+`
tableDividerMatcher := `\s+`
pathMatcher := `~?/[a-zA-Z_0-9/-]+`
datetimeMatcher := `[a-zA-Z]{3}\s\d{1,2}\s\d{4}\s[0-9:]+\s([A-Z]{3}|[+-]\d{4})`
runtimeMatcher := `[0-9.ms]+`
exitCodeMatcher := `0`
pipefailMatcher := `set -em?o pipefail`
line1Matcher := `Hostname` + tableDividerMatcher + `CWD` + tableDividerMatcher + `Timestamp` + tableDividerMatcher + `Runtime` + tableDividerMatcher + `Exit Code` + tableDividerMatcher + `Command\s*\n`
line2Matcher := hostnameMatcher + tableDividerMatcher + pathMatcher + tableDividerMatcher + datetimeMatcher + tableDividerMatcher + runtimeMatcher + tableDividerMatcher + exitCodeMatcher + tableDividerMatcher + pipefailMatcher + tableDividerMatcher + `\n`
line3Matcher := hostnameMatcher + tableDividerMatcher + pathMatcher + tableDividerMatcher + datetimeMatcher + tableDividerMatcher + runtimeMatcher + tableDividerMatcher + exitCodeMatcher + tableDividerMatcher + `echo thisisrecorded` + tableDividerMatcher + `\n`
match, err := regexp.MatchString(line3Matcher, out)
require.NoError(t, err)
if !match {
t.Fatalf("output is missing the row for `echo thisisrecorded`: %v", out)
}
match, err = regexp.MatchString(line1Matcher, out)
require.NoError(t, err)
if !match {
t.Fatalf("output is missing the headings: %v", out)
}
match, err = regexp.MatchString(line2Matcher, out)
require.NoError(t, err)
if !match {
t.Fatalf("output is missing the pipefail: %v", out)
}
match, err = regexp.MatchString(line1Matcher+line2Matcher+line3Matcher, out)
require.NoError(t, err)
if !match {
t.Fatalf("output doesn't match the expected table: %v", out)
}
// Test querying for a specific command
out = hishtoryQuery(t, tester, "foo")
expected = []string{"echo foo", "ls /foo"}
unexpected := []string{"echo thisisrecorded", "hishtory enable", "echo bar", "ls /bar", "ls /a"}
for _, item := range expected {
require.Contains(t, out, item, "output is missing expected item")
if strings.Count(out, item) != 1 {
t.Fatalf("output has %#v in it multiple times! out=%#v", item, out)
}
}
for _, item := range unexpected {
require.NotContains(t, out, item, "output is containing unexpected item")
}
// Add a complex command
complexCommand := "echo hello | grep complex | sed s/h/i/g; echo baz && echo \"fo 'o\" # mycommand"
_, _ = tester.RunInteractiveShellRelaxed(t, complexCommand)
// Query for it
out = hishtoryQuery(t, tester, "complex")
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
require.Contains(t, out, complexCommand, "hishtory query doesn't contain the expected complex command")
// Assert there are no leaked connections
assertNoLeakedConnections(t)
return userSecret
}
func testAdvancedQuery(t *testing.T, tester shellTester) {
// Set up
defer testutils.BackupAndRestore(t)()
// Install hishtory
userSecret := installHishtory(t, tester, "")
// Run some commands we can query for
_, err := tester.RunInteractiveShellRelaxed(t, `echo nevershouldappear
notacommand
cd /tmp/
echo querybydir
hishtory disable`)
require.NoError(t, err)
// A super basic query just to ensure the basics are working
out := hishtoryQuery(t, tester, `echo`)
require.Contains(t, out, "echo querybydir", "hishtory query doesn't contain result matching echo querybydir")
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on cwd
out = hishtoryQuery(t, tester, `cwd:/tmp`)
require.Contains(t, out, "echo querybydir", "hishtory query doesn't contain result matching cwd:/tmp")
require.NotContains(t, out, "nevershouldappear")
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// And again, but with a strailing slash
out = hishtoryQuery(t, tester, `cwd:/tmp/`)
require.Contains(t, out, "echo querybydir", "hishtory query doesn't contain result matching cwd:/tmp/")
require.NotContains(t, out, "nevershouldappear")
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on cwd without the slash
out = hishtoryQuery(t, tester, `cwd:tmp`)
require.Contains(t, out, "echo querybydir")
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on cwd and another term
out = hishtoryQuery(t, tester, `cwd:/tmp querybydir`)
require.Contains(t, out, "echo querybydir")
require.NotContains(t, out, "nevershouldappear")
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on exit_code
out = hishtoryQuery(t, tester, `exit_code:127`)
require.Contains(t, out, "notacommand")
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on exit_code and something else that matches nothing
out = hishtoryQuery(t, tester, `exit_code:127 foo`)
if strings.Count(out, "\n") != 1 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on before: and cwd:
out = hishtoryQuery(t, tester, `before:2125-07-02 cwd:/tmp`)
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
out = hishtoryQuery(t, tester, `before:2125-07-02 cwd:tmp`)
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
out = hishtoryQuery(t, tester, `before:2125-07-02 cwd:mp`)
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on after: and cwd:
out = hishtoryQuery(t, tester, `after:1980-07-02 cwd:/tmp`)
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on after: that returns no results
out = hishtoryQuery(t, tester, `after:2120-07-02 cwd:/tmp`)
if strings.Count(out, "\n") != 1 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Manually submit an entry with a different hostname and username so we can test those atoms
entry := testutils.MakeFakeHistoryEntry("cmd_with_diff_hostname_and_username")
entry.LocalUsername = "otheruser"
entry.Hostname = "otherhostname"
manuallySubmitHistoryEntry(t, userSecret, entry)
// Query based on the username that exists
out = hishtoryQuery(t, tester, `user:otheruser`)
require.Contains(t, out, "cmd_with_diff_hostname_and_username")
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on the username that doesn't exist
out = hishtoryQuery(t, tester, `user:noexist`)
if strings.Count(out, "\n") != 1 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Query based on the hostname
out = hishtoryQuery(t, tester, `hostname:otherhostname`)
require.Contains(t, out, "cmd_with_diff_hostname_and_username")
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Test filtering out a search item
out = hishtoryQuery(t, tester, "")
require.Contains(t, out, "cmd_with_diff_hostname_and_username")
out = hishtoryQuery(t, tester, `-cmd_with_diff_hostname_and_username`)
require.NotContains(t, out, "cmd_with_diff_hostname_and_username")
out = hishtoryQuery(t, tester, `-echo -pipefail`)
require.NotContains(t, out, "echo")
if strings.Count(out, "\n") != 4 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Test filtering out with an atom
out = hishtoryQuery(t, tester, `-hostname:otherhostname`)
require.NotContains(t, out, "cmd_with_diff_hostname_and_username")
out = hishtoryQuery(t, tester, `-user:otheruser`)
require.NotContains(t, out, "cmd_with_diff_hostname_and_username")
out = hishtoryQuery(t, tester, `-exit_code:0`)
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Test filtering out a search item that also looks like it could be a search for a flag
entry = testutils.MakeFakeHistoryEntry("foo -echo")
manuallySubmitHistoryEntry(t, userSecret, entry)
out = hishtoryQuery(t, tester, `-echo -install -pipefail`)
require.NotContains(t, out, "echo")
if strings.Count(out, "\n") != 4 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
// Search for a cwd based on the home directory
entry = testutils.MakeFakeHistoryEntry("foobar")
entry.HomeDirectory = "/home/david/"
entry.CurrentWorkingDirectory = "~/dir/"
manuallySubmitHistoryEntry(t, userSecret, entry)
out = tester.RunInteractiveShell(t, `hishtory export cwd:~/dir`)
expectedOutput := "foobar\n"
if diff := cmp.Diff(expectedOutput, out); diff != "" {
t.Fatalf("hishtory export mismatch (-expected +got):\n%s\nout=%#v", diff, out)
}
// And search with the fully expanded path
out = tester.RunInteractiveShell(t, `hishtory export cwd:/home/david/dir`)
expectedOutput = "foobar\n"
if diff := cmp.Diff(expectedOutput, out); diff != "" {
t.Fatalf("hishtory export mismatch (-expected +got):\n%s\nout=%#v", diff, out)
}
// Search using an escaped dash
out = tester.RunInteractiveShell(t, `hishtory export \\-echo`)
expectedOutput = "foo -echo\n"
if diff := cmp.Diff(expectedOutput, out); diff != "" {
t.Fatalf("hishtory export mismatch (-expected +got):\n%s\nout=%#v", diff, out)
}
// Search using a colon that doesn't match a column name
manuallySubmitHistoryEntry(t, userSecret, testutils.MakeFakeHistoryEntry("foo:bar"))
out = tester.RunInteractiveShell(t, `hishtory export foo\\:bar`)
expectedOutput = "foo:bar\n"
if diff := cmp.Diff(expectedOutput, out); diff != "" {
t.Fatalf("hishtory export mismatch (-expected +got):\n%s\nout=%#v", diff, out)
}
}
func installFromHead(t *testing.T, tester shellTester) (string, string) {
return installHishtory(t, tester, ""), "v0.Unknown"
}
func installFromPrev(t *testing.T, tester shellTester) (string, string) {
defer testutils.BackupAndRestoreEnv("HISHTORY_FORCE_CLIENT_VERSION")()
dd, err := cmd.GetDownloadData(makeTestOnlyContextWithFakeConfig())
require.NoError(t, err)
pv, err := shared.ParseVersionString(dd.Version)
require.NoError(t, err)
previousVersion := pv.Decrement()
os.Setenv("HISHTORY_FORCE_CLIENT_VERSION", previousVersion.String())
userSecret := installHishtory(t, tester, "")
out := tester.RunInteractiveShell(t, ` hishtory update`)
require.Regexp(t, regexp.MustCompile(`^Successfully updated hishtory from v0[.]Unknown to `+previousVersion.String()+`\n$`), out)
return userSecret, previousVersion.String()
}
func updateToRelease(t *testing.T, tester shellTester) string {
dd, err := cmd.GetDownloadData(makeTestOnlyContextWithFakeConfig())
require.NoError(t, err)
// Update
out := tester.RunInteractiveShell(t, " hishtory update\necho postupdate")
require.Regexp(t, regexp.MustCompile(`^Successfully updated hishtory from v0[.][a-zA-Z0-9]+ to `+dd.Version+`\npostupdate\n$`), out)
require.NotContains(t, out, "skipping SLSA validation")
// Update again and assert that it skipped the update
out = tester.RunInteractiveShell(t, " hishtory update")
require.Equal(t, fmt.Sprintf("Latest version (%s) is already installed\n", dd.Version), out)
return dd.Version
}
func updateToHead(t *testing.T, tester shellTester) string {
out := tester.RunInteractiveShell(t, " /tmp/client install\necho postupdate")
require.Equal(t, "postupdate\n", out)
return "v0.Unknown"
}
func testUpdateFromHeadToRelease(t *testing.T, tester shellTester) {
testGenericUpdate(t, tester, installFromHead, updateToRelease)
}
func testUpdateFromPrevToRelease(t *testing.T, tester shellTester) {
testGenericUpdate(t, tester, installFromPrev, updateToRelease)
}
func testUpdateFromPrevToCurrent(t *testing.T, tester shellTester) {
testGenericUpdate(t, tester, installFromPrev, updateToHead)
}
func testUpdateFromPrevToReleaseViaProd(t *testing.T, tester shellTester) {
defer testutils.BackupAndRestoreEnv("HISHTORY_SERVER")()
os.Setenv("HISHTORY_SERVER", "https://api.hishtory.dev")
testGenericUpdate(t, tester, installFromPrev, updateToRelease)
}
func testGenericUpdate(t *testing.T, tester shellTester, installInitialVersion func(*testing.T, shellTester) (string, string), installUpdatedVersion func(*testing.T, shellTester) string) {
defer testutils.BackupAndRestoreEnv("HISHTORY_FORCE_CLIENT_VERSION")()
if !testutils.IsOnline() {
t.Skip("skipping because we're currently offline")
}
if runtime.GOOS == "linux" && runtime.GOARCH == "arm64" {
t.Skip("skipping on linux/arm64 which is unsupported")
}
// Set up
defer testutils.BackupAndRestore(t)()
userSecret, initialVersion := installInitialVersion(t, tester)
// Record a command before the update
tester.RunInteractiveShell(t, "echo hello")
// Check the status command
out := tester.RunInteractiveShell(t, `hishtory status`)
require.Contains(t, out, fmt.Sprintf("hiSHtory: %s\nEnabled: true\nSecret Key: %s\nCommit Hash: ", initialVersion, userSecret))
if initialVersion == "v0.Unknown" {
require.Contains(t, out, "Commit Hash: Unknown")
} else {
require.NotContains(t, out, "Commit Hash: Unknown")
}
// Update
updatedVersion := installUpdatedVersion(t, tester)
// Then check the status command again to confirm the update worked
out = tester.RunInteractiveShell(t, `hishtory status`)
require.Contains(t, out, fmt.Sprintf("\nEnabled: true\nSecret Key: %s\nCommit Hash: ", userSecret))
if updatedVersion != "v0.Unknown" {
require.NotContains(t, out, "\nCommit Hash: Unknown\n")
}
// Check that the history was preserved after the update
out = tester.RunInteractiveShell(t, "hishtory export -pipefail | grep -v '/tmp/client install'")
expectedOutput := "echo hello\nhishtory status\necho postupdate\nhishtory status\n"
if diff := cmp.Diff(expectedOutput, out); diff != "" {
t.Fatalf("hishtory export mismatch (-expected +got):\n%s\nout=%#v", diff, out)
}
}
func testRepeatedCommandThenQuery(t *testing.T, tester shellTester) {
// Set up
defer testutils.BackupAndRestore(t)()
userSecret := installHishtory(t, tester, "")
// Check the status command
out := tester.RunInteractiveShell(t, `hishtory status`)
if out != fmt.Sprintf("hiSHtory: v0.Unknown\nEnabled: true\nSecret Key: %s\nCommit Hash: Unknown\n", userSecret) {
t.Fatalf("status command has unexpected output: %#v", out)
}
// Run a command many times
for i := 0; i < 25; i++ {
tester.RunInteractiveShell(t, fmt.Sprintf("echo mycommand-%d", i))
}
// Check that it shows up correctly
out = hishtoryQuery(t, tester, `mycommand`)
if strings.Count(out, "\n") != 26 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v", strings.Count(out, "\n"), out)
}
if strings.Count(out, "echo mycommand") != 25 {
t.Fatalf("hishtory query has the wrong number of commands=%d, out=%#v", strings.Count(out, "echo mycommand"), out)
}
// Run a few more commands including some empty lines that don't get recorded
tester.RunInteractiveShell(t, `echo mycommand-30
echo mycommand-31
echo mycommand-3`)
out = tester.RunInteractiveShell(t, "hishtory export | grep -v pipefail | grep -v '/tmp/client install'")
expectedOutput := "hishtory status\necho mycommand-0\necho mycommand-1\necho mycommand-2\necho mycommand-3\necho mycommand-4\necho mycommand-5\necho mycommand-6\necho mycommand-7\necho mycommand-8\necho mycommand-9\necho mycommand-10\necho mycommand-11\necho mycommand-12\necho mycommand-13\necho mycommand-14\necho mycommand-15\necho mycommand-16\necho mycommand-17\necho mycommand-18\necho mycommand-19\necho mycommand-20\necho mycommand-21\necho mycommand-22\necho mycommand-23\necho mycommand-24\nhishtory query mycommand\necho mycommand-30\necho mycommand-31\necho mycommand-3\n"
if diff := cmp.Diff(expectedOutput, out); diff != "" {
t.Fatalf("hishtory export mismatch (-expected +got):\n%s\nout=%#v", diff, out)
}
}
func testRepeatedCommandAndQuery(t *testing.T, tester shellTester) {
// Set up
defer testutils.BackupAndRestore(t)()
userSecret := installHishtory(t, tester, "")
// Check the status command
out := tester.RunInteractiveShell(t, `hishtory status`)
if out != fmt.Sprintf("hiSHtory: v0.Unknown\nEnabled: true\nSecret Key: %s\nCommit Hash: Unknown\n", userSecret) {
t.Fatalf("status command has unexpected output: %#v", out)
}
// Run a command many times
for i := 0; i < 25; i++ {
tester.RunInteractiveShell(t, fmt.Sprintf("echo mycommand-%d", i))
out = hishtoryQuery(t, tester, fmt.Sprintf("mycommand-%d", i))
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query #%d has the wrong number of lines=%d, out=%#v", i, strings.Count(out, "\n"), out)
}
if strings.Count(out, "echo mycommand") != 1 {
t.Fatalf("hishtory query #%d has the wrong number of commands=%d, out=%#v", i, strings.Count(out, "echo mycommand"), out)
}
}
}
func testRepeatedEnableDisable(t *testing.T, tester shellTester) {
// Set up
defer testutils.BackupAndRestore(t)()
installHishtory(t, tester, "")
// Run a command many times
for i := 0; i < 25; i++ {
tester.RunInteractiveShell(t, fmt.Sprintf(`echo mycommand-%d
hishtory disable
echo shouldnotshowup
sleep 0.5
hishtory enable`, i))
out := hishtoryQuery(t, tester, fmt.Sprintf("mycommand-%d", i))
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query #%d has the wrong number of lines=%d, out=%#v", i, strings.Count(out, "\n"), out)
}
if strings.Count(out, "echo mycommand") != 1 {
t.Fatalf("hishtory query #%d has the wrong number of commands=%d, out=%#v", i, strings.Count(out, "echo mycommand"), out)
}
out = hishtoryQuery(t, tester, "")
require.NotContains(t, out, "shouldnotshowup")
}
out := tester.RunInteractiveShell(t, "hishtory export | grep -v pipefail | grep -v '/tmp/client install'")
expectedOutput := "echo mycommand-0\nhishtory enable\nhishtory query mycommand-0\nhishtory query\necho mycommand-1\nhishtory enable\nhishtory query mycommand-1\nhishtory query\necho mycommand-2\nhishtory enable\nhishtory query mycommand-2\nhishtory query\necho mycommand-3\nhishtory enable\nhishtory query mycommand-3\nhishtory query\necho mycommand-4\nhishtory enable\nhishtory query mycommand-4\nhishtory query\necho mycommand-5\nhishtory enable\nhishtory query mycommand-5\nhishtory query\necho mycommand-6\nhishtory enable\nhishtory query mycommand-6\nhishtory query\necho mycommand-7\nhishtory enable\nhishtory query mycommand-7\nhishtory query\necho mycommand-8\nhishtory enable\nhishtory query mycommand-8\nhishtory query\necho mycommand-9\nhishtory enable\nhishtory query mycommand-9\nhishtory query\necho mycommand-10\nhishtory enable\nhishtory query mycommand-10\nhishtory query\necho mycommand-11\nhishtory enable\nhishtory query mycommand-11\nhishtory query\necho mycommand-12\nhishtory enable\nhishtory query mycommand-12\nhishtory query\necho mycommand-13\nhishtory enable\nhishtory query mycommand-13\nhishtory query\necho mycommand-14\nhishtory enable\nhishtory query mycommand-14\nhishtory query\necho mycommand-15\nhishtory enable\nhishtory query mycommand-15\nhishtory query\necho mycommand-16\nhishtory enable\nhishtory query mycommand-16\nhishtory query\necho mycommand-17\nhishtory enable\nhishtory query mycommand-17\nhishtory query\necho mycommand-18\nhishtory enable\nhishtory query mycommand-18\nhishtory query\necho mycommand-19\nhishtory enable\nhishtory query mycommand-19\nhishtory query\necho mycommand-20\nhishtory enable\nhishtory query mycommand-20\nhishtory query\necho mycommand-21\nhishtory enable\nhishtory query mycommand-21\nhishtory query\necho mycommand-22\nhishtory enable\nhishtory query mycommand-22\nhishtory query\necho mycommand-23\nhishtory enable\nhishtory query mycommand-23\nhishtory query\necho mycommand-24\nhishtory enable\nhishtory query mycommand-24\nhishtory query\n"
if diff := cmp.Diff(expectedOutput, out); diff != "" {
t.Fatalf("hishtory export mismatch (-expected +got):\n%s\nout=%#v", diff, out)
}
}
func testExcludeHiddenCommand(t *testing.T, tester shellTester) {
// Set up
defer testutils.BackupAndRestore(t)()
installHishtory(t, tester, "")
tester.RunInteractiveShell(t, `echo hello1
echo hidden
echo hello2
echo hidden`)
tester.RunInteractiveShell(t, " echo hidden")
out := hishtoryQuery(t, tester, "-pipefail")
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has the wrong number of lines=%d, out=%#v, bash hishtory file=%#v", strings.Count(out, "\n"), out, tester.RunInteractiveShell(t, "cat ~/.bash_history"))
}
if strings.Count(out, "echo hello") != 2 {
t.Fatalf("hishtory query has the wrong number of commands=%d, out=%#v", strings.Count(out, "echo mycommand"), out)
}
if strings.Count(out, "echo hello1") != 1 {
t.Fatalf("hishtory query has the wrong number of commands=%d, out=%#v", strings.Count(out, "echo mycommand"), out)
}
if strings.Count(out, "echo hello2") != 1 {
t.Fatalf("hishtory query has the wrong number of commands=%d, out=%#v", strings.Count(out, "echo mycommand"), out)
}
require.NotContains(t, out, "hidden")
out = tester.RunInteractiveShell(t, "hishtory export | grep -v pipefail | grep -v '/tmp/client install'")
expectedOutput := "echo hello1\necho hello2\n"
if out != expectedOutput {
t.Fatalf("hishtory export has unexpected output=%#v", out)
}
}
func waitForBackgroundSavesToComplete(t testing.TB) {
lastOut := ""
lastErr := ""
for i := 0; i < 20; i++ {
cmd := exec.Command(getPidofCommand(), "hishtory")
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil && err.Error() != "exit status 1" {
t.Fatalf("failed to check if hishtory was running: %v, stdout=%#v, stderr=%#v", err, stdout.String(), stderr.String())
}
if !strings.Contains(stdout.String(), "\n") {
// pidof had no output, so hishtory isn't running and we're done waiting
time.Sleep(1000 * time.Millisecond)
return
}
lastOut = stdout.String()
lastErr = stderr.String()
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("failed to wait until hishtory wasn't running (lastOut=%#v, lastErr=%#v)", lastOut, lastErr)
}
func testTimestampsAreReasonablyCorrect(t *testing.T, tester shellTester) {
// Setup
defer testutils.BackupAndRestore(t)()
installHishtory(t, tester, "")
// Record a command
out := tester.RunInteractiveShell(t, "echo hello")
if out != "hello\n" {
t.Fatalf("running echo hello had unexpected out=%#v", out)
}
// Query for it and check that the timestamp that gets recorded looks reasonable
out = hishtoryQuery(t, tester, "echo hello")
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query has unexpected number of lines: out=%#v", out)
}
expectedDate := time.Now().Format("Jan 2 2006")
require.Contains(t, out, expectedDate)
}
func testTableDisplayCwd(t *testing.T, tester shellTester) {
// Setup
defer testutils.BackupAndRestore(t)()
installHishtory(t, tester, "")
// Record a command
out := tester.RunInteractiveShell(t, `cd ~/.hishtory/
echo hello
cd /tmp/
echo other`)
if out != "hello\nother\n" {
t.Fatalf("running echo hello had unexpected out=%#v", out)
}
// Query for it and check that the directory gets recorded correctly
out = hishtoryQuery(t, tester, "echo hello")
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query has unexpected number of lines: out=%#v", out)
}
require.Contains(t, out, "~/"+data.GetHishtoryPath())
out = hishtoryQuery(t, tester, "echo other")
if strings.Count(out, "\n") != 2 {
t.Fatalf("hishtory query has unexpected number of lines: out=%#v", out)
}
require.Contains(t, out, "/tmp")
}
func testHishtoryBackgroundSaving(t *testing.T, tester shellTester) {
if runtime.GOOS == "darwin" {
t.Skip("skip testing background saving since it is flakey on MacOs")
}
// Setup
defer testutils.BackupAndRestore(t)()
// Check that we can find the go binary
_, err := exec.LookPath("go")
require.NoError(t, err)
// Test install with an unset HISHTORY_TEST var so that we save in the background (this is likely to be flakey!)
out := tester.RunInteractiveShell(t, `unset HISHTORY_TEST
CGO_ENABLED=0 go build -o /tmp/client
/tmp/client install`)
r := regexp.MustCompile(`Setting secret hishtory key to (.*)`)
matches := r.FindStringSubmatch(out)
if len(matches) != 2 {
t.Fatalf("Failed to extract userSecret from output=%#v: matches=%#v", out, matches)
}
userSecret := matches[1]
// Assert that config.sh isn't the dev version
homedir, err := os.UserHomeDir()
require.NoError(t, err)
dat, err := os.ReadFile(path.Join(homedir, data.GetHishtoryPath(), "config.sh"))
require.NoError(t, err, "failed to read config.sh")
require.NotContains(t, string(dat), "except it doesn't run the save process in the background", "config.sh is the testing version when it shouldn't be")
// Test the status subcommand
out = tester.RunInteractiveShell(t, `hishtory status`)
if out != fmt.Sprintf("hiSHtory: v0.Unknown\nEnabled: true\nSecret Key: %s\nCommit Hash: Unknown\n", userSecret) {
t.Fatalf("status command has unexpected output: %#v", out)
}
// Test recording commands
out, err = tester.RunInteractiveShellRelaxed(t, `ls /a
echo foo`)
require.NoError(t, err)
if out != "foo\n" {
t.Fatalf("unexpected output from running commands: %#v", out)
}
// Test querying for all commands
waitForBackgroundSavesToComplete(t)
time.Sleep(time.Second)
out = hishtoryQuery(t, tester, "")
expected := []string{"echo foo", "ls /a"}
for _, item := range expected {
require.Contains(t, out, item, "output is missing expected item")
}
// Test querying for a specific command
waitForBackgroundSavesToComplete(t)
out = hishtoryQuery(t, tester, "foo")
require.Contains(t, out, "echo foo")
require.NotContains(t, out, "ls /a")
}
func testDisplayTable(t *testing.T, tester shellTester) {
// Setup
defer testutils.BackupAndRestore(t)()
userSecret := installHishtory(t, tester, "")
// Submit two fake entries
tmz, err := time.LoadLocation("America/Los_Angeles")
require.NoError(t, err)
entry1 := testutils.MakeFakeHistoryEntry("table_cmd1")
entry1.StartTime = time.Unix(1650096186, 0).In(tmz)
entry1.EndTime = time.Unix(1650096190, 0).In(tmz)
manuallySubmitHistoryEntry(t, userSecret, entry1)
entry2 := testutils.MakeFakeHistoryEntry("table_cmd2")
entry2.StartTime = time.Unix(1650096196, 0).In(tmz)
entry2.EndTime = time.Unix(1650096220, 0).In(tmz)
entry2.CurrentWorkingDirectory = "~/foo/"
entry2.ExitCode = 3
manuallySubmitHistoryEntry(t, userSecret, entry2)
// Query and check the table
tester.RunInteractiveShell(t, ` hishtory disable`)
out := hishtoryQuery(t, tester, "table")
testutils.CompareGoldens(t, out, "testDisplayTable-defaultColumns")
// Adjust the columns that should be displayed
tester.RunInteractiveShell(t, `hishtory config-set displayed-columns Hostname Command`)
// And check the table again
out = hishtoryQuery(t, tester, "table")
testutils.CompareGoldens(t, out, "testDisplayTable-customColumns")
// And again
tester.RunInteractiveShell(t, `hishtory config-set displayed-columns Hostname 'Exit Code' Command`)
out = hishtoryQuery(t, tester, "table")
testutils.CompareGoldens(t, out, "testDisplayTable-customColumns-2")
// And again
tester.RunInteractiveShell(t, `hishtory config-add displayed-columns CWD`)
out = hishtoryQuery(t, tester, "table")
testutils.CompareGoldens(t, out, "testDisplayTable-customColumns-3")
// Test displaying a command with multiple lines
entry3 := testutils.MakeFakeHistoryEntry("while :\ndo\nls /table/\ndone")
manuallySubmitHistoryEntry(t, userSecret, entry3)
out = hishtoryQuery(t, tester, "table")
testutils.CompareGoldens(t, out, "testDisplayTable-customColumns-multiLineCommand")
// Add a custom column
tester.RunInteractiveShell(t, `hishtory config-add custom-columns foo "echo aaaaaaaaaaaaa"`)
require.NoError(t, os.Chdir("/"))
tester.RunInteractiveShell(t, ` hishtory enable`)
tester.RunInteractiveShell(t, `echo table-1`)
tester.RunInteractiveShell(t, `echo table-2`)
tester.RunInteractiveShell(t, `echo bar`)
tester.RunInteractiveShell(t, ` hishtory disable`)
tester.RunInteractiveShell(t, `hishtory config-add displayed-columns foo`)
// And run a query and confirm it is displayed
out = hishtoryQuery(t, tester, "table")
testutils.CompareGoldens(t, out, "testDisplayTable-customColumns-trulyCustom")
}
func testRequestAndReceiveDbDump(t *testing.T, tester shellTester) {
// Set up
defer testutils.BackupAndRestore(t)()
secretKey := installHishtory(t, tester, "")
// Confirm there are no pending dump requests
ctx := hctx.MakeContext()
config := hctx.GetConf(ctx)
deviceId1 := config.DeviceId
respBytes, err := lib.ApiGet(ctx, "/api/v1/get-dump-requests?user_id="+data.UserId(secretKey)+"&device_id="+deviceId1)
resp := strings.TrimSpace(string(respBytes))
require.NoError(t, err, "failed to get pending dump requests")
require.Equalf(t, "[]", resp, "there are pending dump requests! user_id=%#v, resp=%#v", data.UserId(secretKey), resp)
// Record two commands and then query for them
out := tester.RunInteractiveShell(t, `echo hello
echo other`)
if out != "hello\nother\n" {
t.Fatalf("running echo had unexpected out=%#v", out)
}
// Query for it and check that the directory gets recorded correctly
out = hishtoryQuery(t, tester, "echo")
if strings.Count(out, "\n") != 3 {
t.Fatalf("hishtory query has unexpected number of lines: out=%#v", out)
}
require.Contains(t, out, "echo hello")
require.Contains(t, out, "echo other")
// Back up this copy
restoreFirstInstallation := testutils.BackupAndRestoreWithId(t, "-install1")
// Wipe the DB to simulate entries getting deleted because they've already been read and expired
_, err = lib.ApiGet(ctx, "/api/v1/wipe-db-entries")
require.NoError(t, err, "failed to wipe the remote DB")
// Install a new one (with the same secret key but a diff device id)
installHishtory(t, tester, secretKey)
// Confirm there is now a pending dump requests that the first device should respond to
respBytes, err = lib.ApiGet(ctx, "/api/v1/get-dump-requests?user_id="+data.UserId(secretKey)+"&device_id="+deviceId1)
resp = strings.TrimSpace(string(respBytes))
require.NoError(t, err, "failed to get pending dump requests")
require.NotEqualf(t, "[]", resp, "There are no pending dump requests! user_id=%#v, resp=%#v", data.UserId(secretKey), string(resp))
// Check that the new one doesn't have the commands yet
out = hishtoryQuery(t, tester, "echo")
if strings.Count(out, "\n") != 1 {
t.Fatalf("hishtory query has unexpected number of lines, should contain no entries: out=%#v", out)
}
require.NotContains(t, out, "echo hello", "hishtory query contains unexpected command")
require.NotContains(t, out, "echo other", "hishtory query contains unexpected command")
out = tester.RunInteractiveShell(t, `hishtory export | grep -v pipefail`)
if out != "hishtory query echo\n" {
t.Fatalf("hishtory export has unexpected out=%#v", out)
}
// Restore the first copy