|
| 1 | +//go:build cgo || windows |
| 2 | + |
| 3 | +package credstore |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "errors" |
| 8 | + "reflect" |
| 9 | + "testing" |
| 10 | +) |
| 11 | + |
| 12 | +type keychainExitCode int |
| 13 | + |
| 14 | +func (e keychainExitCode) Error() string { return "security failed" } |
| 15 | +func (e keychainExitCode) ExitCode() int { return int(e) } |
| 16 | + |
| 17 | +func TestStableKeychainReadUsesServiceAndAccount(t *testing.T) { |
| 18 | + var args []string |
| 19 | + want := []byte("secret\nwith trailing newline\n") |
| 20 | + got, err := readKeychainPasswordWith(context.Background(), "example-cli", "default/bundle", func(_ context.Context, command ...string) ([]byte, error) { |
| 21 | + args = command |
| 22 | + return append(append([]byte(nil), want...), '\n'), nil |
| 23 | + }) |
| 24 | + if err != nil { |
| 25 | + t.Fatal(err) |
| 26 | + } |
| 27 | + if !reflect.DeepEqual(args, []string{"find-generic-password", "-s", "example-cli", "-a", "default/bundle", "-w"}) { |
| 28 | + t.Fatalf("security args = %q", args) |
| 29 | + } |
| 30 | + if !reflect.DeepEqual(got, want) { |
| 31 | + t.Fatal("credential changed during read") |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func TestStableKeychainReadErrorMapping(t *testing.T) { |
| 36 | + for _, tc := range []struct { |
| 37 | + name string |
| 38 | + err error |
| 39 | + want error |
| 40 | + }{ |
| 41 | + {"missing", keychainExitCode(44), errKeyringItemNotFound}, |
| 42 | + {"denied", keychainExitCode(36), keychainExitCode(36)}, |
| 43 | + } { |
| 44 | + t.Run(tc.name, func(t *testing.T) { |
| 45 | + _, err := readKeychainPasswordWith(context.Background(), "svc", "acct", func(context.Context, ...string) ([]byte, error) { |
| 46 | + return nil, tc.err |
| 47 | + }) |
| 48 | + if !errors.Is(err, tc.want) { |
| 49 | + t.Fatalf("read error = %v, want %v", err, tc.want) |
| 50 | + } |
| 51 | + }) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +func TestStableKeychainReadLeavesOtherOperationsNative(t *testing.T) { |
| 56 | + kr := &captureBytenessKeyring{} |
| 57 | + b := keychainStableReadBackend{ |
| 58 | + keyringBackend: bytenessBackend{kr: kr}, |
| 59 | + service: "svc", |
| 60 | + read: func(service, account string) ([]byte, error) { |
| 61 | + if service != "svc" || account != "default/token" { |
| 62 | + t.Fatalf("read %q/%q", service, account) |
| 63 | + } |
| 64 | + return []byte("secret"), nil |
| 65 | + }, |
| 66 | + } |
| 67 | + item, err := b.get("default/token") |
| 68 | + if err != nil || string(item.data) != "secret" || kr.getCalls != 0 { |
| 69 | + t.Fatalf("get = %q, %v; native get calls = %d", item.data, err, kr.getCalls) |
| 70 | + } |
| 71 | + if err := b.set(keyringItem{key: "default/token", data: []byte("new")}); err != nil || kr.setCalls != 1 { |
| 72 | + t.Fatalf("native set error = %v, calls = %d", err, kr.setCalls) |
| 73 | + } |
| 74 | +} |
0 commit comments