-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_test.go
More file actions
1406 lines (1169 loc) · 39.5 KB
/
proxy_test.go
File metadata and controls
1406 lines (1169 loc) · 39.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 (
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/godbus/dbus/v5"
"github.com/nikicat/secrets-dispatcher/internal/approval"
dbustypes "github.com/nikicat/secrets-dispatcher/internal/dbus"
"github.com/nikicat/secrets-dispatcher/internal/proxy"
"github.com/nikicat/secrets-dispatcher/internal/testutil"
)
// testEnv holds the test environment with two isolated D-Bus daemons.
type testEnv struct {
t *testing.T
tmpDir string
localAddr string
remoteAddr string
localCmd *exec.Cmd
remoteCmd *exec.Cmd
}
// newTestEnv creates a new test environment with isolated D-Bus daemons.
func newTestEnv(t *testing.T) *testEnv {
t.Helper()
tmpDir, err := os.MkdirTemp("", "secrets-dispatcher-test-*")
if err != nil {
t.Fatalf("create temp dir: %v", err)
}
env := &testEnv{
t: t,
tmpDir: tmpDir,
}
// Start local D-Bus daemon
localSocket := filepath.Join(tmpDir, "local.sock")
env.localCmd, env.localAddr = startDBusDaemon(t, localSocket)
// Start remote D-Bus daemon
remoteSocket := filepath.Join(tmpDir, "remote.sock")
env.remoteCmd, env.remoteAddr = startDBusDaemon(t, remoteSocket)
return env
}
// cleanup stops the D-Bus daemons and removes temp files.
func (e *testEnv) cleanup() {
if e.localCmd != nil && e.localCmd.Process != nil {
e.localCmd.Process.Kill()
e.localCmd.Wait()
}
if e.remoteCmd != nil && e.remoteCmd.Process != nil {
e.remoteCmd.Process.Kill()
e.remoteCmd.Wait()
}
if e.tmpDir != "" {
os.RemoveAll(e.tmpDir)
}
}
// localConn connects to the local D-Bus.
func (e *testEnv) localConn() *dbus.Conn {
conn, err := dbus.Connect(e.localAddr)
if err != nil {
e.t.Fatalf("connect to local dbus: %v", err)
}
return conn
}
// remoteConn connects to the remote D-Bus.
func (e *testEnv) remoteConn() *dbus.Conn {
conn, err := dbus.Connect(e.remoteAddr)
if err != nil {
e.t.Fatalf("connect to remote dbus: %v", err)
}
return conn
}
// remoteSocketPath returns the path to the remote socket file.
func (e *testEnv) remoteSocketPath() string {
return filepath.Join(e.tmpDir, "remote.sock")
}
// startDBusDaemon starts a dbus-daemon on the given socket path.
func startDBusDaemon(t *testing.T, socketPath string) (*exec.Cmd, string) {
t.Helper()
addr := "unix:path=" + socketPath
cmd := exec.Command("dbus-daemon",
"--session",
"--nofork",
"--address="+addr,
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
t.Fatalf("start dbus-daemon: %v", err)
}
// Wait for socket to be created
for range 50 {
if _, err := os.Stat(socketPath); err == nil {
return cmd, addr
}
time.Sleep(100 * time.Millisecond)
}
cmd.Process.Kill()
t.Fatalf("dbus-daemon socket not created: %s", socketPath)
return nil, ""
}
func TestProxyBasicOperations(t *testing.T) {
env := newTestEnv(t)
defer env.cleanup()
// Connect to local D-Bus and register mock service
localConn := env.localConn()
defer localConn.Close()
mock := testutil.NewMockSecretService()
if err := mock.Register(localConn); err != nil {
t.Fatalf("register mock service: %v", err)
}
// Add a test item
mock.AddItem("Test Secret", map[string]string{"test-attr": "test-value"}, []byte("test-secret"))
// Start the proxy
p := proxy.New(proxy.Config{
ClientName: "test-client",
LogLevel: slog.LevelDebug,
})
if err := connectProxyWithConns(p, env.localAddr, env.remoteSocketPath()); err != nil {
t.Fatalf("connect proxy: %v", err)
}
defer p.Close()
// Connect to remote D-Bus as a client
remoteConn := env.remoteConn()
defer remoteConn.Close()
// Test: Get Collections property
t.Run("GetCollections", func(t *testing.T) {
obj := remoteConn.Object(dbustypes.BusName, dbustypes.ServicePath)
variant, err := obj.GetProperty(dbustypes.ServiceInterface + ".Collections")
if err != nil {
t.Fatalf("get Collections: %v", err)
}
collections, ok := variant.Value().([]dbus.ObjectPath)
if !ok {
t.Fatalf("Collections is not []ObjectPath: %T", variant.Value())
}
if len(collections) == 0 {
t.Error("expected at least one collection")
}
t.Logf("Collections: %v", collections)
})
// Test: ReadAlias
t.Run("ReadAlias", func(t *testing.T) {
obj := remoteConn.Object(dbustypes.BusName, dbustypes.ServicePath)
call := obj.Call(dbustypes.ServiceInterface+".ReadAlias", 0, "default")
if call.Err != nil {
t.Fatalf("ReadAlias: %v", call.Err)
}
var collection dbus.ObjectPath
if err := call.Store(&collection); err != nil {
t.Fatalf("store result: %v", err)
}
if collection == "/" || collection == "" {
t.Error("expected non-empty collection path")
}
t.Logf("Default collection: %s", collection)
})
// Test: SearchItems
t.Run("SearchItems", func(t *testing.T) {
obj := remoteConn.Object(dbustypes.BusName, dbustypes.ServicePath)
call := obj.Call(dbustypes.ServiceInterface+".SearchItems", 0, map[string]string{"test-attr": "test-value"})
if call.Err != nil {
t.Fatalf("SearchItems: %v", call.Err)
}
var unlocked, locked []dbus.ObjectPath
if err := call.Store(&unlocked, &locked); err != nil {
t.Fatalf("store result: %v", err)
}
if len(unlocked) != 1 {
t.Errorf("expected 1 unlocked item, got %d", len(unlocked))
}
t.Logf("Found items: unlocked=%v, locked=%v", unlocked, locked)
})
// Test: OpenSession + GetSecrets
t.Run("OpenSessionAndGetSecrets", func(t *testing.T) {
obj := remoteConn.Object(dbustypes.BusName, dbustypes.ServicePath)
// Open session
call := obj.Call(dbustypes.ServiceInterface+".OpenSession", 0, "plain", dbus.MakeVariant(""))
if call.Err != nil {
t.Fatalf("OpenSession: %v", call.Err)
}
var output dbus.Variant
var sessionPath dbus.ObjectPath
if err := call.Store(&output, &sessionPath); err != nil {
t.Fatalf("store result: %v", err)
}
t.Logf("Session: %s", sessionPath)
// Search for items
call = obj.Call(dbustypes.ServiceInterface+".SearchItems", 0, map[string]string{"test-attr": "test-value"})
if call.Err != nil {
t.Fatalf("SearchItems: %v", call.Err)
}
var unlocked, locked []dbus.ObjectPath
if err := call.Store(&unlocked, &locked); err != nil {
t.Fatalf("store result: %v", err)
}
if len(unlocked) == 0 {
t.Fatal("no items found")
}
// Get secrets
call = obj.Call(dbustypes.ServiceInterface+".GetSecrets", 0, unlocked, sessionPath)
if call.Err != nil {
t.Fatalf("GetSecrets: %v", call.Err)
}
var secrets map[dbus.ObjectPath]dbustypes.Secret
if err := call.Store(&secrets); err != nil {
t.Fatalf("store result: %v", err)
}
if len(secrets) != 1 {
t.Errorf("expected 1 secret, got %d", len(secrets))
}
for path, secret := range secrets {
if string(secret.Value) != "test-secret" {
t.Errorf("wrong secret value: got %q, want %q", secret.Value, "test-secret")
}
t.Logf("Secret for %s: %q", path, secret.Value)
}
})
// Test: Unlock (should passthrough)
t.Run("Unlock", func(t *testing.T) {
obj := remoteConn.Object(dbustypes.BusName, dbustypes.ServicePath)
call := obj.Call(dbustypes.ServiceInterface+".Unlock", 0, []dbus.ObjectPath{"/org/freedesktop/secrets/collection/default"})
if call.Err != nil {
t.Fatalf("Unlock: %v", call.Err)
}
var unlocked []dbus.ObjectPath
var prompt dbus.ObjectPath
if err := call.Store(&unlocked, &prompt); err != nil {
t.Fatalf("store result: %v", err)
}
t.Logf("Unlocked: %v, prompt: %s", unlocked, prompt)
})
}
func TestProxyItemOperations(t *testing.T) {
env := newTestEnv(t)
defer env.cleanup()
localConn := env.localConn()
defer localConn.Close()
mock := testutil.NewMockSecretService()
if err := mock.Register(localConn); err != nil {
t.Fatalf("register mock service: %v", err)
}
itemPath := mock.AddItem("My Secret", map[string]string{"app": "test-app"}, []byte("secret-value"))
p := proxy.New(proxy.Config{
ClientName: "test-client",
LogLevel: slog.LevelDebug,
})
if err := connectProxyWithConns(p, env.localAddr, env.remoteSocketPath()); err != nil {
t.Fatalf("connect proxy: %v", err)
}
defer p.Close()
remoteConn := env.remoteConn()
defer remoteConn.Close()
// Test: Item.GetSecret
t.Run("ItemGetSecret", func(t *testing.T) {
// First open a session
serviceObj := remoteConn.Object(dbustypes.BusName, dbustypes.ServicePath)
call := serviceObj.Call(dbustypes.ServiceInterface+".OpenSession", 0, "plain", dbus.MakeVariant(""))
if call.Err != nil {
t.Fatalf("OpenSession: %v", call.Err)
}
var output dbus.Variant
var sessionPath dbus.ObjectPath
if err := call.Store(&output, &sessionPath); err != nil {
t.Fatalf("store result: %v", err)
}
// Get secret from item
itemObj := remoteConn.Object(dbustypes.BusName, itemPath)
call = itemObj.Call(dbustypes.ItemInterface+".GetSecret", 0, sessionPath)
if call.Err != nil {
t.Fatalf("Item.GetSecret: %v", call.Err)
}
var secret dbustypes.Secret
if err := call.Store(&secret); err != nil {
t.Fatalf("store result: %v", err)
}
if string(secret.Value) != "secret-value" {
t.Errorf("wrong secret: got %q, want %q", secret.Value, "secret-value")
}
t.Logf("Got secret: %q", secret.Value)
})
// Test: Item properties
t.Run("ItemProperties", func(t *testing.T) {
itemObj := remoteConn.Object(dbustypes.BusName, itemPath)
label, err := itemObj.GetProperty(dbustypes.ItemInterface + ".Label")
if err != nil {
t.Fatalf("get Label: %v", err)
}
if label.Value().(string) != "My Secret" {
t.Errorf("wrong label: got %q", label.Value())
}
attrs, err := itemObj.GetProperty(dbustypes.ItemInterface + ".Attributes")
if err != nil {
t.Fatalf("get Attributes: %v", err)
}
t.Logf("Item attributes: %v", attrs.Value())
})
}
func TestProxyCollectionOperations(t *testing.T) {
env := newTestEnv(t)
defer env.cleanup()
localConn := env.localConn()
defer localConn.Close()
mock := testutil.NewMockSecretService()
if err := mock.Register(localConn); err != nil {
t.Fatalf("register mock service: %v", err)
}
p := proxy.New(proxy.Config{
ClientName: "test-client",
LogLevel: slog.LevelDebug,
})
if err := connectProxyWithConns(p, env.localAddr, env.remoteSocketPath()); err != nil {
t.Fatalf("connect proxy: %v", err)
}
defer p.Close()
remoteConn := env.remoteConn()
defer remoteConn.Close()
// Test: Collection.CreateItem
t.Run("CollectionCreateItem", func(t *testing.T) {
// First open a session
serviceObj := remoteConn.Object(dbustypes.BusName, dbustypes.ServicePath)
call := serviceObj.Call(dbustypes.ServiceInterface+".OpenSession", 0, "plain", dbus.MakeVariant(""))
if call.Err != nil {
t.Fatalf("OpenSession: %v", call.Err)
}
var output dbus.Variant
var sessionPath dbus.ObjectPath
if err := call.Store(&output, &sessionPath); err != nil {
t.Fatalf("store result: %v", err)
}
// Create item
collObj := remoteConn.Object(dbustypes.BusName, "/org/freedesktop/secrets/collection/default")
properties := map[string]dbus.Variant{
"org.freedesktop.Secret.Item.Label": dbus.MakeVariant("New Item"),
"org.freedesktop.Secret.Item.Attributes": dbus.MakeVariant(map[string]string{"new-attr": "new-value"}),
}
secret := dbustypes.Secret{
Session: sessionPath,
Parameters: nil,
Value: []byte("new-secret"),
ContentType: "text/plain",
}
call = collObj.Call(dbustypes.CollectionInterface+".CreateItem", 0, properties, secret, true)
if call.Err != nil {
t.Fatalf("CreateItem: %v", call.Err)
}
var itemPath, promptPath dbus.ObjectPath
if err := call.Store(&itemPath, &promptPath); err != nil {
t.Fatalf("store result: %v", err)
}
if itemPath == "/" || itemPath == "" {
t.Error("expected valid item path")
}
t.Logf("Created item: %s", itemPath)
// Verify we can get the secret back
itemObj := remoteConn.Object(dbustypes.BusName, itemPath)
call = itemObj.Call(dbustypes.ItemInterface+".GetSecret", 0, sessionPath)
if call.Err != nil {
t.Fatalf("GetSecret: %v", call.Err)
}
var retrievedSecret dbustypes.Secret
if err := call.Store(&retrievedSecret); err != nil {
t.Fatalf("store result: %v", err)
}
if string(retrievedSecret.Value) != "new-secret" {
t.Errorf("wrong secret: got %q, want %q", retrievedSecret.Value, "new-secret")
}
})
// Test: Collection.SearchItems
t.Run("CollectionSearchItems", func(t *testing.T) {
collObj := remoteConn.Object(dbustypes.BusName, "/org/freedesktop/secrets/collection/default")
call := collObj.Call(dbustypes.CollectionInterface+".SearchItems", 0, map[string]string{"new-attr": "new-value"})
if call.Err != nil {
t.Fatalf("SearchItems: %v", call.Err)
}
var results []dbus.ObjectPath
if err := call.Store(&results); err != nil {
t.Fatalf("store result: %v", err)
}
if len(results) != 1 {
t.Errorf("expected 1 result, got %d", len(results))
}
t.Logf("Search results: %v", results)
})
}
// TestProxyAliasPathOperations tests that the proxy correctly handles
// collection operations via /org/freedesktop/secrets/aliases/default paths,
// which is how libsecret (secret-tool) accesses collections.
func TestProxyAliasPathOperations(t *testing.T) {
env := newTestEnv(t)
defer env.cleanup()
localConn := env.localConn()
defer localConn.Close()
mock := testutil.NewMockSecretService()
if err := mock.Register(localConn); err != nil {
t.Fatalf("register mock service: %v", err)
}
mock.AddItem("Existing Secret", map[string]string{"app": "test"}, []byte("existing-value"))
p := proxy.New(proxy.Config{
ClientName: "test-client",
LogLevel: slog.LevelDebug,
})
if err := connectProxyWithConns(p, env.localAddr, env.remoteSocketPath()); err != nil {
t.Fatalf("connect proxy: %v", err)
}
defer p.Close()
remoteConn := env.remoteConn()
defer remoteConn.Close()
aliasPath := dbus.ObjectPath("/org/freedesktop/secrets/aliases/default")
// Test: CreateItem via alias path (this is what secret-tool store does)
t.Run("CreateItemViaAlias", func(t *testing.T) {
// Open session first
serviceObj := remoteConn.Object(dbustypes.BusName, dbustypes.ServicePath)
call := serviceObj.Call(dbustypes.ServiceInterface+".OpenSession", 0, "plain", dbus.MakeVariant(""))
if call.Err != nil {
t.Fatalf("OpenSession: %v", call.Err)
}
var output dbus.Variant
var sessionPath dbus.ObjectPath
if err := call.Store(&output, &sessionPath); err != nil {
t.Fatalf("store result: %v", err)
}
// Create item via alias path
collObj := remoteConn.Object(dbustypes.BusName, aliasPath)
properties := map[string]dbus.Variant{
"org.freedesktop.Secret.Item.Label": dbus.MakeVariant("Alias Item"),
"org.freedesktop.Secret.Item.Attributes": dbus.MakeVariant(map[string]string{"alias-attr": "alias-value"}),
}
secret := dbustypes.Secret{
Session: sessionPath,
Parameters: nil,
Value: []byte("alias-secret"),
ContentType: "text/plain",
}
call = collObj.Call(dbustypes.CollectionInterface+".CreateItem", 0, properties, secret, true)
if call.Err != nil {
t.Fatalf("CreateItem via alias: %v", call.Err)
}
var itemPath, promptPath dbus.ObjectPath
if err := call.Store(&itemPath, &promptPath); err != nil {
t.Fatalf("store result: %v", err)
}
if itemPath == "/" || itemPath == "" {
t.Error("expected valid item path")
}
t.Logf("Created item via alias: %s", itemPath)
})
// Test: SearchItems via alias path
t.Run("SearchItemsViaAlias", func(t *testing.T) {
collObj := remoteConn.Object(dbustypes.BusName, aliasPath)
call := collObj.Call(dbustypes.CollectionInterface+".SearchItems", 0, map[string]string{"app": "test"})
if call.Err != nil {
t.Fatalf("SearchItems via alias: %v", call.Err)
}
var results []dbus.ObjectPath
if err := call.Store(&results); err != nil {
t.Fatalf("store result: %v", err)
}
if len(results) != 1 {
t.Errorf("expected 1 result, got %d", len(results))
}
t.Logf("Search results via alias: %v", results)
})
// Test: Properties via alias path
t.Run("GetPropertiesViaAlias", func(t *testing.T) {
collObj := remoteConn.Object(dbustypes.BusName, aliasPath)
label, err := collObj.GetProperty(dbustypes.CollectionInterface + ".Label")
if err != nil {
t.Fatalf("get Label via alias: %v", err)
}
if label.Value().(string) != "Default" {
t.Errorf("wrong label: got %q, want %q", label.Value(), "Default")
}
locked, err := collObj.GetProperty(dbustypes.CollectionInterface + ".Locked")
if err != nil {
t.Fatalf("get Locked via alias: %v", err)
}
if locked.Value().(bool) != false {
t.Error("expected collection to be unlocked")
}
})
}
// connectProxyWithConns connects the proxy using isolated D-Bus connections.
func connectProxyWithConns(p *proxy.Proxy, localAddr, remoteSocketPath string) error {
backendConn, err := dbus.Connect(localAddr)
if err != nil {
return fmt.Errorf("connect to backend dbus: %w", err)
}
frontConn, err := dbus.Connect("unix:path=" + remoteSocketPath)
if err != nil {
backendConn.Close()
return fmt.Errorf("connect to front socket: %w", err)
}
return p.ConnectWith(frontConn, backendConn)
}
// TestProxyClientDisconnectCancelsPendingRequest tests that when a client disconnects
// while waiting for approval, the pending request is automatically removed.
func TestProxyClientDisconnectCancelsPendingRequest(t *testing.T) {
env := newTestEnv(t)
defer env.cleanup()
localConn := env.localConn()
defer localConn.Close()
mock := testutil.NewMockSecretService()
if err := mock.Register(localConn); err != nil {
t.Fatalf("register mock service: %v", err)
}
// Add a test item and capture its path directly (avoids needing SearchItems which now requires approval)
itemPath := mock.AddItem("Test Secret", map[string]string{"test-attr": "test-value"}, []byte("test-secret"))
// Create an approval manager that requires approval (not auto-approve)
approvalMgr := approval.NewManager(approval.ManagerConfig{Timeout: 30 * time.Second, HistoryMax: 100})
p := proxy.New(proxy.Config{
ClientName: "test-client",
LogLevel: slog.LevelDebug,
Approval: approvalMgr,
})
if err := connectProxyWithConns(p, env.localAddr, env.remoteSocketPath()); err != nil {
t.Fatalf("connect proxy: %v", err)
}
defer p.Close()
// Connect a client to the remote D-Bus
clientConn := env.remoteConn()
// Open a session first
serviceObj := clientConn.Object(dbustypes.BusName, dbustypes.ServicePath)
call := serviceObj.Call(dbustypes.ServiceInterface+".OpenSession", 0, "plain", dbus.MakeVariant(""))
if call.Err != nil {
t.Fatalf("OpenSession: %v", call.Err)
}
var output dbus.Variant
var sessionPath dbus.ObjectPath
if err := call.Store(&output, &sessionPath); err != nil {
t.Fatalf("store result: %v", err)
}
// Use the item path directly (avoids SearchItems which now requires approval)
unlocked := []dbus.ObjectPath{itemPath}
// Start GetSecrets in a goroutine - it will block waiting for approval
secretsReturned := make(chan error, 1)
go func() {
call := serviceObj.Call(dbustypes.ServiceInterface+".GetSecrets", 0, unlocked, sessionPath)
secretsReturned <- call.Err
}()
// Wait for the pending request to appear
var pendingCount int
for range 50 {
pendingCount = approvalMgr.PendingCount()
if pendingCount > 0 {
break
}
time.Sleep(50 * time.Millisecond)
}
if pendingCount == 0 {
t.Fatal("pending request did not appear")
}
t.Logf("Pending request appeared (count=%d)", pendingCount)
// Now disconnect the client
clientConn.Close()
t.Log("Client disconnected")
// Wait for the pending request to be removed
var finalCount int
for range 50 {
finalCount = approvalMgr.PendingCount()
if finalCount == 0 {
break
}
time.Sleep(50 * time.Millisecond)
}
if finalCount != 0 {
t.Errorf("pending request was not removed after client disconnect: count=%d", finalCount)
} else {
t.Log("Pending request was correctly removed after client disconnect")
}
// The GetSecrets call should have returned an error (context cancelled or similar)
select {
case err := <-secretsReturned:
t.Logf("GetSecrets returned: %v", err)
case <-time.After(2 * time.Second):
// Timeout is acceptable - the goroutine might be stuck if cleanup didn't happen
t.Log("GetSecrets goroutine did not return (expected if feature not implemented)")
}
}
// TestProxyItemDeleteRequiresApproval tests that Item.Delete is gated by approval.
func TestProxyItemDeleteRequiresApproval(t *testing.T) {
env := newTestEnv(t)
defer env.cleanup()
localConn := env.localConn()
defer localConn.Close()
mock := testutil.NewMockSecretService()
if err := mock.Register(localConn); err != nil {
t.Fatalf("register mock service: %v", err)
}
itemPath := mock.AddItem("Delete Me", map[string]string{"app": "test"}, []byte("secret"))
approvalMgr := approval.NewManager(approval.ManagerConfig{Timeout: 30 * time.Second, HistoryMax: 100})
p := proxy.New(proxy.Config{
ClientName: "test-client",
LogLevel: slog.LevelDebug,
Approval: approvalMgr,
})
if err := connectProxyWithConns(p, env.localAddr, env.remoteSocketPath()); err != nil {
t.Fatalf("connect proxy: %v", err)
}
defer p.Close()
remoteConn := env.remoteConn()
defer remoteConn.Close()
// Start Item.Delete in a goroutine — it should block waiting for approval
deleteErr := make(chan error, 1)
go func() {
itemObj := remoteConn.Object(dbustypes.BusName, itemPath)
call := itemObj.Call(dbustypes.ItemInterface+".Delete", 0)
deleteErr <- call.Err
}()
// Wait for pending request
var reqID string
for range 50 {
reqs := approvalMgr.List()
if len(reqs) > 0 {
reqID = reqs[0].ID
break
}
time.Sleep(50 * time.Millisecond)
}
if reqID == "" {
t.Fatal("approval request did not appear for Item.Delete")
}
// Verify request type
req := approvalMgr.GetPending(reqID)
if req.Type != approval.RequestTypeDelete {
t.Errorf("expected request type 'delete', got %q", req.Type)
}
// Approve the request
if err := approvalMgr.Approve(reqID); err != nil {
t.Fatalf("approve failed: %v", err)
}
// Delete should succeed
select {
case err := <-deleteErr:
if err != nil {
t.Errorf("Item.Delete returned error after approval: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout waiting for Item.Delete to complete")
}
}
// TestProxyItemDeleteDenied tests that denying Item.Delete returns an access denied error.
func TestProxyItemDeleteDenied(t *testing.T) {
env := newTestEnv(t)
defer env.cleanup()
localConn := env.localConn()
defer localConn.Close()
mock := testutil.NewMockSecretService()
if err := mock.Register(localConn); err != nil {
t.Fatalf("register mock service: %v", err)
}
itemPath := mock.AddItem("Don't Delete Me", map[string]string{"app": "test"}, []byte("secret"))
approvalMgr := approval.NewManager(approval.ManagerConfig{Timeout: 30 * time.Second, HistoryMax: 100})
p := proxy.New(proxy.Config{
ClientName: "test-client",
LogLevel: slog.LevelDebug,
Approval: approvalMgr,
})
if err := connectProxyWithConns(p, env.localAddr, env.remoteSocketPath()); err != nil {
t.Fatalf("connect proxy: %v", err)
}
defer p.Close()
remoteConn := env.remoteConn()
defer remoteConn.Close()
deleteErr := make(chan error, 1)
go func() {
itemObj := remoteConn.Object(dbustypes.BusName, itemPath)
call := itemObj.Call(dbustypes.ItemInterface+".Delete", 0)
deleteErr <- call.Err
}()
// Wait for pending request
var reqID string
for range 50 {
reqs := approvalMgr.List()
if len(reqs) > 0 {
reqID = reqs[0].ID
break
}
time.Sleep(50 * time.Millisecond)
}
if reqID == "" {
t.Fatal("approval request did not appear")
}
// Deny the request
if err := approvalMgr.Deny(reqID); err != nil {
t.Fatalf("deny failed: %v", err)
}
// Delete should fail with access denied
select {
case err := <-deleteErr:
if err == nil {
t.Error("expected error after denial, got nil")
} else if !strings.Contains(err.Error(), "denied") {
t.Errorf("expected access denied error, got: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout waiting for Item.Delete to complete")
}
}
// TestProxyCollectionDeleteRequiresApproval tests that Collection.Delete is gated by approval.
func TestProxyCollectionDeleteRequiresApproval(t *testing.T) {
env := newTestEnv(t)
defer env.cleanup()
localConn := env.localConn()
defer localConn.Close()
mock := testutil.NewMockSecretService()
if err := mock.Register(localConn); err != nil {
t.Fatalf("register mock service: %v", err)
}
approvalMgr := approval.NewManager(approval.ManagerConfig{Timeout: 30 * time.Second, HistoryMax: 100})
p := proxy.New(proxy.Config{
ClientName: "test-client",
LogLevel: slog.LevelDebug,
Approval: approvalMgr,
})
if err := connectProxyWithConns(p, env.localAddr, env.remoteSocketPath()); err != nil {
t.Fatalf("connect proxy: %v", err)
}
defer p.Close()
remoteConn := env.remoteConn()
defer remoteConn.Close()
collPath := dbus.ObjectPath("/org/freedesktop/secrets/collection/default")
// Start Collection.Delete in a goroutine — it should block waiting for approval
deleteErr := make(chan error, 1)
go func() {
collObj := remoteConn.Object(dbustypes.BusName, collPath)
call := collObj.Call(dbustypes.CollectionInterface+".Delete", 0)
deleteErr <- call.Err
}()
// Wait for pending request
var reqID string
for range 50 {
reqs := approvalMgr.List()
if len(reqs) > 0 {
reqID = reqs[0].ID
break
}
time.Sleep(50 * time.Millisecond)
}
if reqID == "" {
t.Fatal("approval request did not appear for Collection.Delete")
}
// Verify request type and that it captured the collection label
req := approvalMgr.GetPending(reqID)
if req.Type != approval.RequestTypeDelete {
t.Errorf("expected request type 'delete', got %q", req.Type)
}
if len(req.Items) != 1 {
t.Fatalf("expected 1 item in request, got %d", len(req.Items))
}
if req.Items[0].Label != "Default" {
t.Errorf("expected collection label 'Default', got %q", req.Items[0].Label)
}
// Approve the request
if err := approvalMgr.Approve(reqID); err != nil {
t.Fatalf("approve failed: %v", err)
}
// Delete should succeed
select {
case err := <-deleteErr:
if err != nil {
t.Errorf("Collection.Delete returned error after approval: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout waiting for Collection.Delete to complete")
}
}
// TestProxyItemDeleteNoAutoApprove tests that approving a GetSecret does not
// auto-approve a subsequent Delete for the same item (cache bypass).
func TestProxyItemDeleteNoAutoApprove(t *testing.T) {
env := newTestEnv(t)
defer env.cleanup()
localConn := env.localConn()
defer localConn.Close()
mock := testutil.NewMockSecretService()
if err := mock.Register(localConn); err != nil {
t.Fatalf("register mock service: %v", err)
}
itemPath := mock.AddItem("Cached Secret", map[string]string{"app": "test"}, []byte("secret"))
// Use approval window so GetSecret gets cached
approvalMgr := approval.NewManager(approval.ManagerConfig{Timeout: 30 * time.Second, HistoryMax: 100, ApprovalWindow: time.Minute})
p := proxy.New(proxy.Config{
ClientName: "test-client",
LogLevel: slog.LevelDebug,
Approval: approvalMgr,
})
if err := connectProxyWithConns(p, env.localAddr, env.remoteSocketPath()); err != nil {
t.Fatalf("connect proxy: %v", err)
}
defer p.Close()
remoteConn := env.remoteConn()
defer remoteConn.Close()
// First: open session and GetSecret (approve it to populate cache)
serviceObj := remoteConn.Object(dbustypes.BusName, dbustypes.ServicePath)
call := serviceObj.Call(dbustypes.ServiceInterface+".OpenSession", 0, "plain", dbus.MakeVariant(""))
if call.Err != nil {
t.Fatalf("OpenSession: %v", call.Err)
}
var output dbus.Variant
var sessionPath dbus.ObjectPath
if err := call.Store(&output, &sessionPath); err != nil {
t.Fatalf("store result: %v", err)
}
// GetSecret blocks on approval
getSecretDone := make(chan error, 1)
go func() {
itemObj := remoteConn.Object(dbustypes.BusName, itemPath)
call := itemObj.Call(dbustypes.ItemInterface+".GetSecret", 0, sessionPath)
getSecretDone <- call.Err
}()
// Approve GetSecret
var reqID string
for range 50 {
reqs := approvalMgr.List()
if len(reqs) > 0 {
reqID = reqs[0].ID
break
}
time.Sleep(50 * time.Millisecond)
}
if reqID == "" {
t.Fatal("GetSecret approval request did not appear")
}
approvalMgr.Approve(reqID)
<-getSecretDone
// Now try Delete — it should still require approval (not use cache)
deleteErr := make(chan error, 1)