-
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathapi_key_helper_test.go
More file actions
373 lines (331 loc) · 10.5 KB
/
api_key_helper_test.go
File metadata and controls
373 lines (331 loc) · 10.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
package util
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// overrideCredStore replaces the global credStore with an isolated file-backed
// store backed by a temp directory, then restores the original on cleanup.
// This prevents tests from touching the OS keyring or real credential files.
func overrideCredStore(t *testing.T) {
t.Helper()
original := credStore
t.Cleanup(func() { credStore = original })
credStore = newTestCredStore(t)
}
func TestGetAPIKeyFromHelper_Success(t *testing.T) {
tests := []struct {
name string
command string
expected string
}{
{
name: "simple echo command",
command: "echo 'test-api-key'",
expected: "test-api-key",
},
{
name: "command with whitespace",
command: "echo ' test-key-with-spaces '",
expected: "test-key-with-spaces",
},
{
name: "command with newlines",
command: "printf 'key-with-newline\\n'",
expected: "key-with-newline",
},
{
name: "multi-word echo",
command: "echo sk-1234567890abcdef",
expected: "sk-1234567890abcdef",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := GetAPIKeyFromHelper(context.Background(), tt.command)
if err != nil {
t.Fatalf("GetAPIKeyFromHelper() error = %v, want nil", err)
}
if result != tt.expected {
t.Errorf("GetAPIKeyFromHelper() = %q, want %q", result, tt.expected)
}
})
}
}
func TestGetAPIKeyFromHelper_EmptyCommand(t *testing.T) {
_, err := GetAPIKeyFromHelper(context.Background(), "")
if err == nil {
t.Fatal("GetAPIKeyFromHelper() with empty command should return error")
}
if !strings.Contains(err.Error(), "empty") {
t.Errorf("error message should mention empty command, got: %v", err)
}
}
func TestGetAPIKeyFromHelper_EmptyOutput(t *testing.T) {
tests := []struct {
name string
command string
}{
{
name: "true command with no output",
command: "true",
},
{
name: "command outputting only whitespace",
command: "echo ' '",
},
{
name: "command outputting only newlines",
command: "printf '\\n\\n'",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := GetAPIKeyFromHelper(context.Background(), tt.command)
if err == nil {
t.Fatal("GetAPIKeyFromHelper() with empty output should return error")
}
if !strings.Contains(err.Error(), "empty output") {
t.Errorf("error message should mention empty output, got: %v", err)
}
})
}
}
func TestGetAPIKeyFromHelper_CommandFailure(t *testing.T) {
tests := []struct {
name string
command string
wantErr string
}{
{
name: "non-existent command",
command: "nonexistentcommand12345",
wantErr: "failed",
},
{
name: "command with exit code 1",
command: "exit 1",
wantErr: "failed",
},
{
name: "command with syntax error",
command: "if then fi",
wantErr: "failed",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := GetAPIKeyFromHelper(context.Background(), tt.command)
if err == nil {
t.Fatal("GetAPIKeyFromHelper() should return error for failed command")
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error should contain %q, got: %v", tt.wantErr, err)
}
})
}
}
func TestGetAPIKeyFromHelper_Timeout(t *testing.T) {
// Command that sleeps longer than the timeout
// The process group mechanism will kill both shell and sleep subprocess
command := "sleep 15"
start := time.Now()
_, err := GetAPIKeyFromHelper(context.Background(), command)
duration := time.Since(start)
if err == nil {
t.Fatal("GetAPIKeyFromHelper() should return timeout error")
}
// Error message can be either:
// - "terminated after timeout" if SIGTERM succeeded
// - "timed out" if SIGKILL was needed
if !strings.Contains(err.Error(), "timeout") && !strings.Contains(err.Error(), "terminated") {
t.Errorf("error message should mention timeout or termination, got: %v", err)
}
// Verify it actually timed out around the expected timeout duration
// Allow up to 4 seconds margin (2s grace period + 2s buffer)
if duration < HelperTimeout || duration > HelperTimeout+4*time.Second {
t.Errorf("timeout duration = %v, want around %v", duration, HelperTimeout)
}
}
func TestGetAPIKeyFromHelper_ComplexCommands(t *testing.T) {
tests := []struct {
name string
command string
expected string
}{
{
name: "piped commands",
command: "echo 'my-api-key' | tr '[:lower:]' '[:upper:]'",
expected: "MY-API-KEY",
},
{
name: "command with variables",
command: "KEY=test-123; echo $KEY",
expected: "test-123",
},
{
name: "command with subshell",
command: "echo $(printf 'nested-key')",
expected: "nested-key",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := GetAPIKeyFromHelper(context.Background(), tt.command)
if err != nil {
t.Fatalf("GetAPIKeyFromHelper() error = %v, want nil", err)
}
if result != tt.expected {
t.Errorf("GetAPIKeyFromHelper() = %q, want %q", result, tt.expected)
}
})
}
}
func TestGetAPIKeyFromHelper_SecurityStderr(t *testing.T) {
// Command that outputs to stderr (sensitive info should not be leaked in error)
command := "echo 'secret-data' >&2; exit 1"
_, err := GetAPIKeyFromHelper(context.Background(), command)
if err == nil {
t.Fatal("GetAPIKeyFromHelper() should return error when command fails")
}
// The error message should NOT contain the stderr output (security consideration)
if strings.Contains(err.Error(), "secret-data") {
t.Error("error message should not leak stderr content (security issue)")
}
}
func TestGetAPIKeyFromHelperWithCache_NoCaching(t *testing.T) {
overrideCredStore(t)
// Test with refreshInterval = 0 (no caching)
command := "echo 'test-key-no-cache'"
key1, err := GetAPIKeyFromHelperWithCache(context.Background(), command, 0)
if err != nil {
t.Fatalf("GetAPIKeyFromHelperWithCache() error = %v", err)
}
if key1 != "test-key-no-cache" {
t.Errorf("Expected 'test-key-no-cache', got %q", key1)
}
// Second call should also execute (no caching)
key2, err := GetAPIKeyFromHelperWithCache(context.Background(), command, 0)
if err != nil {
t.Fatalf("GetAPIKeyFromHelperWithCache() error = %v", err)
}
if key2 != "test-key-no-cache" {
t.Errorf("Expected 'test-key-no-cache', got %q", key2)
}
}
func TestGetAPIKeyFromHelperWithCache_WithCaching(t *testing.T) {
overrideCredStore(t)
// Use a counter file to generate different values each time the command runs.
tmpDir := t.TempDir()
counterFile := filepath.Join(tmpDir, "counter.txt")
command := fmt.Sprintf(
"f=%s; echo $(($(cat $f 2>/dev/null || echo 0) + 1)) | tee $f",
counterFile,
)
// First call should execute and cache
key1, err := GetAPIKeyFromHelperWithCache(context.Background(), command, 5*time.Second)
if err != nil {
t.Fatalf("GetAPIKeyFromHelperWithCache() error = %v", err)
}
// Small delay to ensure time difference
time.Sleep(100 * time.Millisecond)
// Second call should return cached value (same as first)
key2, err := GetAPIKeyFromHelperWithCache(context.Background(), command, 5*time.Second)
if err != nil {
t.Fatalf("GetAPIKeyFromHelperWithCache() error = %v", err)
}
if key1 != key2 {
t.Errorf("Cache should return same value: key1=%q, key2=%q", key1, key2)
}
}
func TestGetAPIKeyFromHelperWithCache_CacheExpiration(t *testing.T) {
overrideCredStore(t)
// Create a counter file that we'll update manually.
tmpDir := t.TempDir()
counterFile := filepath.Join(tmpDir, "counter2.txt")
command := fmt.Sprintf("cat %q", counterFile)
// Write initial value
if err := os.WriteFile(counterFile, []byte("value1"), 0o600); err != nil {
t.Fatalf("Failed to write counter file: %v", err)
}
// First call with short refresh interval
key1, err := GetAPIKeyFromHelperWithCache(context.Background(), command, 500*time.Millisecond)
if err != nil {
t.Fatalf("GetAPIKeyFromHelperWithCache() error = %v", err)
}
// Update the file with a different value
if err := os.WriteFile(counterFile, []byte("value2"), 0o600); err != nil {
t.Fatalf("Failed to update counter file: %v", err)
}
// Wait for cache to expire
time.Sleep(600 * time.Millisecond)
// Second call should fetch fresh value
key2, err := GetAPIKeyFromHelperWithCache(context.Background(), command, 500*time.Millisecond)
if err != nil {
t.Fatalf("GetAPIKeyFromHelperWithCache() error = %v", err)
}
// Keys should be different (cache expired)
if key1 == key2 {
t.Errorf("Cache should have expired and returned new value: key1=%q, key2=%q", key1, key2)
}
if key1 != "value1" {
t.Errorf("First key should be 'value1', got %q", key1)
}
if key2 != "value2" {
t.Errorf("Second key should be 'value2', got %q", key2)
}
}
func TestGetAPIKeyFromHelperWithCache_DifferentCommands(t *testing.T) {
overrideCredStore(t)
cmd1 := "echo 'key-one'"
cmd2 := "echo 'key-two'"
// Get keys from different commands
key1, err := GetAPIKeyFromHelperWithCache(context.Background(), cmd1, 5*time.Second)
if err != nil {
t.Fatalf("GetAPIKeyFromHelperWithCache() error = %v", err)
}
key2, err := GetAPIKeyFromHelperWithCache(context.Background(), cmd2, 5*time.Second)
if err != nil {
t.Fatalf("GetAPIKeyFromHelperWithCache() error = %v", err)
}
// Keys should be different (different commands)
if key1 == key2 {
t.Errorf("Different commands should return different keys: key1=%q, key2=%q", key1, key2)
}
if key1 != "key-one" {
t.Errorf("Expected 'key-one', got %q", key1)
}
if key2 != "key-two" {
t.Errorf("Expected 'key-two', got %q", key2)
}
}
func TestGetAPIKeyFromHelperWithCache_StoresInCredstore(t *testing.T) {
overrideCredStore(t)
command := "echo 'test-credstore-storage'"
// Execute command to populate credstore cache
_, err := GetAPIKeyFromHelperWithCache(context.Background(), command, 5*time.Second)
if err != nil {
t.Fatalf("GetAPIKeyFromHelperWithCache() error = %v", err)
}
// Verify the value was stored in credstore under the expected key
val, err := GetCredential(helperCacheKey(command))
if err != nil {
t.Fatalf("GetCredential() error = %v", err)
}
if val == "" {
t.Fatal("Expected credstore to contain cached entry, got empty string")
}
// Verify the stored JSON contains the expected API key
var stored apiKeyCache
if err := json.Unmarshal([]byte(val), &stored); err != nil {
t.Fatalf("Failed to unmarshal stored credstore value: %v", err)
}
if stored.APIKey != "test-credstore-storage" {
t.Errorf("Stored APIKey = %q, want %q", stored.APIKey, "test-credstore-storage")
}
}