-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathauth_test.go
More file actions
735 lines (617 loc) · 23.5 KB
/
auth_test.go
File metadata and controls
735 lines (617 loc) · 23.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
package cmd
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
"github.com/timescale/tiger-cli/internal/tiger/config"
)
func setupAuthTest(t *testing.T) string {
t.Helper()
// Mock the API key validation for testing
originalValidator := validateAPIKeyForLogin
validateAPIKeyForLogin = func(apiKey, projectID string) error {
// Always return success for testing
return nil
}
// Aggressively clean up any existing keyring entries before starting
// Uses a test-specific keyring entry.
config.RemoveAPIKeyFromKeyring()
// Create temporary directory for test config
tmpDir, err := os.MkdirTemp("", "tiger-auth-test-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
// Set temporary config directory
os.Setenv("TIGER_CONFIG_DIR", tmpDir)
// Reset global config and viper to ensure test isolation
if _, err := config.UseTestConfig(tmpDir, map[string]any{}); err != nil {
t.Fatalf("Failed to use test config: %v", err)
}
// Also ensure config file doesn't exist
configFile := config.GetConfigFile(tmpDir)
os.Remove(configFile)
t.Cleanup(func() {
// Clean up test keyring
config.RemoveAPIKeyFromKeyring()
// Reset global config and viper first
config.ResetGlobalConfig()
validateAPIKeyForLogin = originalValidator // Restore original validator
// Remove config file explicitly
configFile := config.GetConfigFile(tmpDir)
os.Remove(configFile)
// Clean up environment variable BEFORE cleaning up file system
os.Unsetenv("TIGER_CONFIG_DIR")
// Then clean up file system
os.RemoveAll(tmpDir)
})
return tmpDir
}
func executeAuthCommand(args ...string) (string, error) {
// Use buildRootCmd() to get a complete root command with all flags and subcommands
testRoot := buildRootCmd()
buf := new(bytes.Buffer)
testRoot.SetOut(buf)
testRoot.SetErr(buf)
testRoot.SetArgs(args)
err := testRoot.Execute()
return buf.String(), err
}
func TestAuthLogin_KeyAndProjectIDFlags(t *testing.T) {
tmpDir := setupAuthTest(t)
// Execute login command with public and secret key flags and project ID
output, err := executeAuthCommand("auth", "login", "--public-key", "test-public-key", "--secret-key", "test-secret-key", "--project-id", "test-project-123")
if err != nil {
t.Fatalf("Login failed: %v", err)
}
expectedOutput := "Validating API key...\nSuccessfully logged in and stored API key\nSet default project ID to: test-project-123\n" + nextStepsMessage
if output != expectedOutput {
t.Errorf("Unexpected output: '%s'", output)
}
// Verify API key was stored (try keyring first, then file fallback)
// The combined key should be in format "public:secret"
expectedAPIKey := "test-public-key:test-secret-key"
apiKey, err := config.GetAPIKeyFromKeyring()
if err != nil {
// Keyring failed, check file fallback
apiKeyFile := filepath.Join(tmpDir, "api-key")
data, err := os.ReadFile(apiKeyFile)
if err != nil {
t.Fatalf("API key not stored in keyring or file: %v", err)
}
if string(data) != expectedAPIKey {
t.Errorf("Expected API key '%s', got '%s'", expectedAPIKey, string(data))
}
} else {
if apiKey != expectedAPIKey {
t.Errorf("Expected API key '%s', got '%s'", expectedAPIKey, apiKey)
}
}
// Verify project ID was stored in config
cfg, err := config.Load()
if err != nil {
t.Fatalf("Failed to load config: %v", err)
}
if cfg.ProjectID != "test-project-123" {
t.Errorf("Expected project ID 'test-project-123', got '%s'", cfg.ProjectID)
}
}
func TestAuthLogin_KeyFlags_NoProjectID(t *testing.T) {
setupAuthTest(t)
// Execute login command with only public and secret key flags (no project ID)
// This should fail since project ID is now required
_, err := executeAuthCommand("auth", "login", "--public-key", "test-public-key", "--secret-key", "test-secret-key")
if err == nil {
t.Fatal("Expected login to fail without project ID, but it succeeded")
}
// Verify the error message mentions TTY not detected
expectedErrorMsg := "TTY not detected - credentials required"
if !strings.Contains(err.Error(), expectedErrorMsg) {
t.Errorf("Expected error to contain %q, got: %v", expectedErrorMsg, err)
}
// Verify no API key was stored since login failed
if _, err = config.GetAPIKey(); err == nil {
t.Error("API key should not be stored when login fails")
}
}
func TestAuthLogin_KeyAndProjectIDEnvironmentVariables(t *testing.T) {
setupAuthTest(t)
// Set environment variables for public and secret keys
os.Setenv("TIGER_PUBLIC_KEY", "env-public-key")
os.Setenv("TIGER_SECRET_KEY", "env-secret-key")
os.Setenv("TIGER_PROJECT_ID", "env-project-id")
defer os.Unsetenv("TIGER_PUBLIC_KEY")
defer os.Unsetenv("TIGER_SECRET_KEY")
defer os.Unsetenv("TIGER_PROJECT_ID")
// Execute login command with project ID flag but using env vars for keys
output, err := executeAuthCommand("auth", "login")
if err != nil {
t.Fatalf("Login failed: %v", err)
}
expectedOutput := "Validating API key...\nSuccessfully logged in and stored API key\nSet default project ID to: env-project-id\n" + nextStepsMessage
if output != expectedOutput {
t.Errorf("Unexpected output: '%s'", output)
}
// Verify API key was stored (should be combined format)
expectedAPIKey := "env-public-key:env-secret-key"
storedKey, err := config.GetAPIKey()
if err != nil {
t.Fatalf("Failed to get stored API key: %v", err)
}
if storedKey != expectedAPIKey {
t.Errorf("Expected API key '%s', got '%s'", expectedAPIKey, storedKey)
}
}
func TestAuthLogin_KeyEnvironmentVariables_ProjectIDFlag(t *testing.T) {
setupAuthTest(t)
// Set environment variables for public and secret keys
os.Setenv("TIGER_PUBLIC_KEY", "env-public-key")
os.Setenv("TIGER_SECRET_KEY", "env-secret-key")
defer os.Unsetenv("TIGER_PUBLIC_KEY")
defer os.Unsetenv("TIGER_SECRET_KEY")
// Execute login command with project ID flag but using env vars for keys
output, err := executeAuthCommand("auth", "login", "--project-id", "test-project-456")
if err != nil {
t.Fatalf("Login failed: %v", err)
}
expectedOutput := "Validating API key...\nSuccessfully logged in and stored API key\nSet default project ID to: test-project-456\n" + nextStepsMessage
if output != expectedOutput {
t.Errorf("Unexpected output: '%s'", output)
}
// Verify API key was stored (should be combined format)
expectedAPIKey := "env-public-key:env-secret-key"
storedKey, err := config.GetAPIKey()
if err != nil {
t.Fatalf("Failed to get stored API key: %v", err)
}
if storedKey != expectedAPIKey {
t.Errorf("Expected API key '%s', got '%s'", expectedAPIKey, storedKey)
}
}
// setupOAuthTest creates a complete OAuth test environment with mock server and browser
func setupOAuthTest(t *testing.T, projects []Project, expectedProjectID string) string {
t.Helper()
tmpDir := setupAuthTest(t)
// Ensure no keys in environment
os.Unsetenv("TIGER_PUBLIC_KEY")
os.Unsetenv("TIGER_SECRET_KEY")
os.Unsetenv("TIGER_PROJECT_ID")
// Start mock server for OAuth endpoints
mockServer := startMockOAuthServer(t, projects)
// Set up mock browser function
originalOpenBrowser := openBrowser
openBrowser = mockOpenBrowser(t)
// Set config URLs to point to mock server
configFile := config.GetConfigFile(tmpDir)
configContent := fmt.Sprintf(`
console_url: "%s"
gateway_url: "%s"
`, mockServer.URL, mockServer.URL)
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to write config file: %v", err)
}
// Return cleanup function
t.Cleanup(func() {
mockServer.Close()
openBrowser = originalOpenBrowser
})
return mockServer.URL
}
// startMockOAuthServer starts a mock server that handles all OAuth endpoints
func startMockOAuthServer(t *testing.T, projects []Project) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
// Token exchange endpoint
mux.HandleFunc("POST /idp/external/cli/token", func(w http.ResponseWriter, r *http.Request) {
t.Logf("Mock server received token exchange request")
if err := r.ParseForm(); err != nil {
http.Error(w, "Failed to parse form", http.StatusBadRequest)
return
}
clientID := r.FormValue("client_id")
code := r.FormValue("code")
codeVerifier := r.FormValue("code_verifier")
if clientID == "" || code == "" || codeVerifier == "" {
http.Error(w, "Missing required parameters", http.StatusBadRequest)
return
}
tokenResponse := map[string]interface{}{
"access_token": "mock-access-token-12345",
"refresh_token": "mock-refresh-token-67890",
"expires_at": 1234567890,
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(tokenResponse); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
})
// GraphQL endpoint for getUserProjects and other queries
mux.HandleFunc("POST /query", func(w http.ResponseWriter, r *http.Request) {
t.Logf("Mock server received GraphQL request")
var requestBody map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
http.Error(w, "Failed to decode request body", http.StatusBadRequest)
return
}
query, ok := requestBody["query"].(string)
if !ok {
http.Error(w, "Missing query in request", http.StatusBadRequest)
return
}
// Handle different GraphQL queries
if strings.Contains(query, "getAllProjects") {
response := GraphQLResponse[GetAllProjectsData]{
Data: &GetAllProjectsData{
GetAllProjects: projects,
},
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
} else if strings.Contains(query, "getUser") {
response := GraphQLResponse[GetUserData]{
Data: &GetUserData{
GetUser: User{
ID: "user-456",
Name: "Test User",
Email: "test@example.com",
},
},
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
} else if strings.Contains(query, "createPATRecord") {
response := GraphQLResponse[CreatePATRecordData]{
Data: &CreatePATRecordData{
CreatePATRecord: PATRecordResponse{
ClientCredentials: struct {
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
}{
AccessKey: "test-access-key",
SecretKey: "test-secret-key",
},
},
},
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
} else {
http.Error(w, "Unknown GraphQL query", http.StatusBadRequest)
}
})
// OAuth success endpoint (just returns 200 OK)
mux.HandleFunc("GET /oauth/code/success", func(w http.ResponseWriter, r *http.Request) {
t.Logf("Mock server received OAuth success request")
w.WriteHeader(http.StatusOK)
})
// Create test server
return httptest.NewServer(mux)
}
// mockOpenBrowser returns a mock openBrowser function that simulates OAuth callback
func mockOpenBrowser(t *testing.T) func(string) error {
return func(authURL string) error {
t.Logf("Mock browser opening URL: %s", authURL)
// Extract redirect_uri and state from the URL parameters
parsedURL, err := url.Parse(authURL)
if err != nil {
return err
}
clientID := parsedURL.Query().Get("client_id")
responseType := parsedURL.Query().Get("response_type")
codeChallengeMethod := parsedURL.Query().Get("code_challenge_method")
codeChallenge := parsedURL.Query().Get("code_challenge")
redirectURI := parsedURL.Query().Get("redirect_uri")
state := parsedURL.Query().Get("state")
if clientID == "" {
t.Fatal("no client_id found in OAuth URL")
return errors.New("no client_id found in OAuth URL")
}
if responseType != "code" {
t.Fatal("invalid response_type found in OAuth URL")
return errors.New("no response_type found in OAuth URL")
}
if codeChallengeMethod != "S256" {
t.Fatal("invalid code_challenge_method found in OAuth URL")
return errors.New("no code_challenge_method found in OAuth URL")
}
if codeChallenge == "" {
t.Fatal("no code_challenge found in OAuth URL")
return errors.New("no code_challenge found in OAuth URL")
}
if redirectURI == "" {
t.Fatal("no redirect_uri found in OAuth URL")
return errors.New("no redirect_uri found in OAuth URL")
}
if state == "" {
t.Fatal("no state found in OAuth URL")
return errors.New("no state found in OAuth URL")
}
// Give the OAuth server a moment to start
go func() {
// Sleep to ensure the OAuth callback server is listening
// This prevents "EOF" errors in CI when the server hasn't started yet
time.Sleep(100 * time.Millisecond)
// Make the OAuth callback request directly
callbackURL := fmt.Sprintf("%s?code=test-auth-code&state=%s", redirectURI, state)
t.Logf("Mock browser making callback request to: %s", callbackURL)
resp, err := http.Get(callbackURL)
if err != nil {
t.Errorf("Mock callback request failed: %v", err)
return
}
if err := resp.Body.Close(); err != nil {
t.Errorf("Error closing callback request body: %v", err)
}
}()
return nil
}
}
func TestAuthLogin_OAuth_SingleProject(t *testing.T) {
mockServerURL := setupOAuthTest(t, []Project{
{ID: "project-123", Name: "Test Project"},
}, "project-123")
// Execute login command - the mocked openBrowser will handle the callback automatically
output, err := executeAuthCommand("auth", "login")
if err != nil {
t.Fatalf("Login failed: %v", err)
}
// Build regex pattern to match the complete output
// Auth URL format: http://mockserver/oauth/authorize?client_id=45e1b16d-e435-4049-97b2-8daad150818c&code_challenge=base64&code_challenge_method=S256&redirect_uri=http%3A%2F%2Flocalhost%3APORT%2Fcallback&response_type=code&state=randomstring
expectedPattern := fmt.Sprintf(`^Auth URL is: %s/oauth/authorize\?client_id=45e1b16d-e435-4049-97b2-8daad150818c&code_challenge=[A-Za-z0-9_-]+&code_challenge_method=S256&redirect_uri=http%%3A%%2F%%2Flocalhost%%3A\d+%%2Fcallback&response_type=code&state=[A-Za-z0-9_-]+\n`+
`Opening browser for authentication\.\.\.\n`+
`Validating API key\.\.\.\n`+
`Successfully logged in and stored API key\n`+
`Set default project ID to: project-123\n`+regexp.QuoteMeta(nextStepsMessage)+`$`, regexp.QuoteMeta(mockServerURL))
matched, err := regexp.MatchString(expectedPattern, output)
if err != nil {
t.Fatalf("Regex compilation failed: %v", err)
}
if !matched {
t.Errorf("Output doesn't match expected pattern.\nPattern: %s\nActual output: '%s'", expectedPattern, output)
}
// Verify API key was stored
storedKey, err := config.GetAPIKey()
if err != nil {
t.Fatalf("Failed to get stored API key: %v", err)
}
// Expected API key is "test-access-key:test-secret-key"
expectedAPIKey := "test-access-key:test-secret-key"
if storedKey != expectedAPIKey {
t.Errorf("Expected API key '%s', got '%s'", expectedAPIKey, storedKey)
}
// Verify project ID was stored in config
cfg, err := config.Load()
if err != nil {
t.Fatalf("Failed to load config: %v", err)
}
if cfg.ProjectID != "project-123" {
t.Errorf("Expected project ID 'project-123', got '%s'", cfg.ProjectID)
}
}
func TestAuthLogin_OAuth_MultipleProjects(t *testing.T) {
mockServerURL := setupOAuthTest(t, []Project{
{ID: "project-123", Name: "Test Project 1"},
{ID: "project-456", Name: "Test Project 2"},
{ID: "project-789", Name: "Test Project 3"},
}, "project-789")
// Mock the project selection to simulate user selecting the third project (index 2)
originalSelectProjectInteractively := selectProjectInteractively
defer func() {
selectProjectInteractively = originalSelectProjectInteractively
}()
selectProjectInteractively = func(projects []Project, out io.Writer) (string, error) {
t.Logf("Mock project selection - user selects project at index 2: %s", projects[2].ID)
// Simulate user pressing down arrow twice and then enter (selects third project)
return projects[2].ID, nil
}
// Execute login command - both mocked functions will handle OAuth flow and project selection
output, err := executeAuthCommand("auth", "login")
if err != nil {
t.Fatalf("Login failed: %v", err)
}
// Build regex pattern to match the complete output
expectedPattern := fmt.Sprintf(`^Auth URL is: %s/oauth/authorize\?client_id=45e1b16d-e435-4049-97b2-8daad150818c&code_challenge=[A-Za-z0-9_-]+&code_challenge_method=S256&redirect_uri=http%%3A%%2F%%2Flocalhost%%3A\d+%%2Fcallback&response_type=code&state=[A-Za-z0-9_-]+\n`+
`Opening browser for authentication\.\.\.\n`+
`Validating API key\.\.\.\n`+
`Successfully logged in and stored API key\n`+
`Set default project ID to: project-789\n`+regexp.QuoteMeta(nextStepsMessage)+`$`, regexp.QuoteMeta(mockServerURL))
matched, err := regexp.MatchString(expectedPattern, output)
if err != nil {
t.Fatalf("Regex compilation failed: %v", err)
}
if !matched {
t.Errorf("Output doesn't match expected pattern.\nPattern: %s\nActual output: '%s'", expectedPattern, output)
}
// Verify API key was stored
storedKey, err := config.GetAPIKey()
if err != nil {
t.Fatalf("Failed to get stored API key: %v", err)
}
// Expected API key is "test-access-key:test-secret-key"
expectedAPIKey := "test-access-key:test-secret-key"
if storedKey != expectedAPIKey {
t.Errorf("Expected API key '%s', got '%s'", expectedAPIKey, storedKey)
}
// Verify project ID was stored in config (should be the third project - project-789)
cfg, err := config.Load()
if err != nil {
t.Fatalf("Failed to load config: %v", err)
}
if cfg.ProjectID != "project-789" {
t.Errorf("Expected project ID 'project-789', got '%s'", cfg.ProjectID)
}
}
// TestAuthLogin_KeyringFallback tests the scenario where keyring fails and system falls back to file storage
func TestAuthLogin_KeyringFallback(t *testing.T) {
tmpDir := setupAuthTest(t)
// We can't easily mock keyring failure, but we can test file storage directly
// by ensuring the API key gets stored to file when keyring might not be available
// Execute login command with public and secret key flags and project ID
output, err := executeAuthCommand("auth", "login", "--public-key", "fallback-public", "--secret-key", "fallback-secret", "--project-id", "test-project-fallback")
if err != nil {
t.Fatalf("Login failed: %v", err)
}
expectedOutput := "Validating API key...\nSuccessfully logged in and stored API key\nSet default project ID to: test-project-fallback\n" + nextStepsMessage
if output != expectedOutput {
t.Errorf("Unexpected output: '%s'", output)
}
// Force test file storage scenario by directly checking file
apiKeyFile := filepath.Join(tmpDir, "api-key")
// If keyring worked, manually create file scenario by removing keyring and adding file
config.RemoveAPIKeyFromKeyring()
// Store to file manually to simulate fallback (combined format)
expectedAPIKey := "fallback-public:fallback-secret"
err = config.StoreAPIKeyToFile(expectedAPIKey)
if err != nil {
t.Fatalf("Failed to store API key to file: %v", err)
}
// Verify file storage works
storedKey, err := config.GetAPIKey()
if err != nil {
t.Fatalf("Failed to get API key from file fallback: %v", err)
}
if storedKey != expectedAPIKey {
t.Errorf("Expected API key '%s', got '%s'", expectedAPIKey, storedKey)
}
// Test whoami with file-only storage
output, err = executeAuthCommand("auth", "whoami")
if err != nil {
t.Fatalf("Whoami failed with file storage: %v", err)
}
if output != "Logged in (API key stored)\n" {
t.Errorf("Unexpected whoami output: '%s'", output)
}
// Test logout with file-only storage
output, err = executeAuthCommand("auth", "logout")
if err != nil {
t.Fatalf("Logout failed with file storage: %v", err)
}
if output != "Successfully logged out and removed stored credentials\n" {
t.Errorf("Unexpected logout output: '%s'", output)
}
// Verify file was removed
if _, err := os.Stat(apiKeyFile); !os.IsNotExist(err) {
t.Error("API key file should be removed after logout")
}
}
// TestAuthLogin_EnvironmentVariable_FileOnly tests env var login when only file storage is available
func TestAuthLogin_EnvironmentVariable_FileOnly(t *testing.T) {
tmpDir := setupAuthTest(t)
// Clear any keyring entries to force file-only storage
config.RemoveAPIKeyFromKeyring()
// Set environment variables for public key, secret key, and project ID
os.Setenv("TIGER_PUBLIC_KEY", "env-file-public")
os.Setenv("TIGER_SECRET_KEY", "env-file-secret")
os.Setenv("TIGER_PROJECT_ID", "test-project-env-file")
defer os.Unsetenv("TIGER_PUBLIC_KEY")
defer os.Unsetenv("TIGER_SECRET_KEY")
defer os.Unsetenv("TIGER_PROJECT_ID")
// Execute login command without any flags (all from env vars)
output, err := executeAuthCommand("auth", "login")
if err != nil {
t.Fatalf("Login failed: %v", err)
}
expectedOutput := "Validating API key...\nSuccessfully logged in and stored API key\nSet default project ID to: test-project-env-file\n" + nextStepsMessage
if output != expectedOutput {
t.Errorf("Unexpected output: '%s'", output)
}
// Clear keyring again to ensure we're testing file-only retrieval
config.RemoveAPIKeyFromKeyring()
// Verify API key was stored in file (since keyring is cleared)
expectedAPIKey := "env-file-public:env-file-secret"
apiKeyFile := filepath.Join(tmpDir, "api-key")
data, err := os.ReadFile(apiKeyFile)
if err != nil {
// If file doesn't exist, the keyring might have worked, so manually ensure file storage
err = config.StoreAPIKeyToFile(expectedAPIKey)
if err != nil {
t.Fatalf("Failed to store API key to file: %v", err)
}
data, err = os.ReadFile(apiKeyFile)
if err != nil {
t.Fatalf("API key file should exist: %v", err)
}
}
if string(data) != expectedAPIKey {
t.Errorf("Expected API key '%s' in file, got '%s'", expectedAPIKey, string(data))
}
// Verify getAPIKey works with file-only storage
storedKey, err := config.GetAPIKey()
if err != nil {
t.Fatalf("Failed to get API key from file: %v", err)
}
if storedKey != expectedAPIKey {
t.Errorf("Expected API key '%s', got '%s'", expectedAPIKey, storedKey)
}
}
func TestAuthWhoami_LoggedIn(t *testing.T) {
setupAuthTest(t)
// Store API key first
err := config.StoreAPIKey("test-api-key-789")
if err != nil {
t.Fatalf("Failed to store API key: %v", err)
}
// Execute whoami command
output, err := executeAuthCommand("auth", "whoami")
if err != nil {
t.Fatalf("Whoami failed: %v", err)
}
if output != "Logged in (API key stored)\n" {
t.Errorf("Unexpected output: '%s' (len=%d)", output, len(output))
}
}
func TestAuthWhoami_NotLoggedIn(t *testing.T) {
setupAuthTest(t)
// Execute whoami command without being logged in
_, err := executeAuthCommand("auth", "whoami")
if err == nil {
t.Fatal("Expected whoami to fail when not logged in")
}
// Error should indicate not logged in
if err.Error() != config.ErrNotLoggedIn.Error() {
t.Errorf("Expected 'not logged in' error, got: %v", err)
}
}
func TestAuthLogout_Success(t *testing.T) {
setupAuthTest(t)
// Store API key first
err := config.StoreAPIKey("test-api-key-logout")
if err != nil {
t.Fatalf("Failed to store API key: %v", err)
}
// Verify API key is stored
_, err = config.GetAPIKey()
if err != nil {
t.Fatalf("API key should be stored: %v", err)
}
// Execute logout command
output, err := executeAuthCommand("auth", "logout")
if err != nil {
t.Fatalf("Logout failed: %v", err)
}
if output != "Successfully logged out and removed stored credentials\n" {
t.Errorf("Unexpected output: '%s' (len=%d)", output, len(output))
}
// Verify API key is removed
_, err = config.GetAPIKey()
if err == nil {
t.Fatal("API key should be removed after logout")
}
}