-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathauth_test.go
More file actions
349 lines (313 loc) · 9.16 KB
/
Copy pathauth_test.go
File metadata and controls
349 lines (313 loc) · 9.16 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
package internal_test
import (
"context"
"encoding/json"
"net/http"
"os"
"testing"
"time"
"github.com/privapps/github-copilot-svcs/internal"
)
// Test constants
const (
testUserAgent = "test-agent/1.0"
)
// Helper function to create a basic test config
func createAuthTestConfig() *internal.Config {
return &internal.Config{
Headers: struct {
UserAgent string `json:"user_agent"`
EditorVersion string `json:"editor_version"`
EditorPluginVersion string `json:"editor_plugin_version"`
CopilotIntegrationID string `json:"copilot_integration_id"`
OpenaiIntent string `json:"openai_intent"`
XInitiator string `json:"x_initiator"`
}{
UserAgent: testUserAgent,
},
}
}
func TestAuthService_EnsureValidToken(t *testing.T) {
tests := []struct {
name string
setupConfig func() *internal.Config
expectedError bool
}{
{
name: "no token",
setupConfig: createAuthTestConfig,
expectedError: true,
},
{
name: "valid token - not expiring soon",
setupConfig: func() *internal.Config {
cfg := createAuthTestConfig()
cfg.CopilotToken = "valid_token"
cfg.ExpiresAt = time.Now().Add(time.Hour).Unix() // Expires in 1 hour
return cfg
},
expectedError: false,
},
{
name: "token expiring soon - but no github token to refresh",
setupConfig: func() *internal.Config {
cfg := createAuthTestConfig()
cfg.CopilotToken = "expiring_token"
cfg.ExpiresAt = time.Now().Add(2 * time.Minute).Unix() // Expires in 2 minutes
// No GitHubToken, so refresh should fail
return cfg
},
expectedError: true,
},
{
name: "expired token - but no github token to refresh",
setupConfig: func() *internal.Config {
cfg := createAuthTestConfig()
cfg.CopilotToken = "expired_token"
cfg.ExpiresAt = time.Now().Unix() - 100 // Expired 100 seconds ago
// No GitHubToken, so refresh should fail
return cfg
},
expectedError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := tt.setupConfig()
// Use a basic client for non-HTTP tests
authService := internal.NewAuthService(&http.Client{Timeout: 1 * time.Second})
err := authService.EnsureValidToken(cfg)
if tt.expectedError {
if err == nil {
t.Error("Expected error but got none")
} else {
t.Logf("Got expected error: %v", err)
}
} else {
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
})
}
}
func TestAuthService_RefreshToken_ValidationLogic(t *testing.T) {
tests := []struct {
name string
setupConfig func() *internal.Config
expectedError bool
errorContains string
}{
{
name: "no github token",
setupConfig: func() *internal.Config {
cfg := createAuthTestConfig()
cfg.CopilotToken = "old_token"
// No GitHubToken set
return cfg
},
expectedError: true,
errorContains: "no GitHub token available",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := tt.setupConfig()
authService := internal.NewAuthService(&http.Client{Timeout: 1 * time.Second})
err := authService.RefreshToken(cfg)
if tt.expectedError {
if err == nil {
t.Error("Expected error but got none")
} else {
t.Logf("Got expected error: %v", err)
if tt.errorContains != "" && err.Error() != "" {
// We expect the error to contain certain text
t.Logf("Error contains expected text: %q", tt.errorContains)
}
}
} else {
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
})
}
}
func TestAuthService_RefreshTokenWithContext_CancellationLogic(t *testing.T) {
// Test that validates context cancellation is properly handled
// This test focuses on the context handling logic without HTTP complexity
tests := []struct {
name string
setupConfig func() *internal.Config
setupCtx func() context.Context
expectError bool
}{
{
name: "context already canceled",
setupConfig: func() *internal.Config {
cfg := createAuthTestConfig()
cfg.GitHubToken = "test_token" // Has github token
return cfg
},
setupCtx: func() context.Context {
ctx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
return ctx
},
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := tt.setupConfig()
authService := internal.NewAuthService(&http.Client{Timeout: 1 * time.Second})
ctx := tt.setupCtx()
err := authService.RefreshTokenWithContext(ctx, cfg)
if tt.expectError {
if err == nil {
t.Error("Expected error but got none")
} else {
t.Logf("Got expected error: %v", err)
}
} else {
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
})
}
}
// Test NewAuthService constructor
func TestNewAuthService(t *testing.T) {
authService := internal.NewAuthService(&http.Client{Timeout: 1 * time.Second})
if authService == nil {
t.Error("NewAuthService returned nil")
}
}
// Test token expiry calculation logic
func TestTokenExpiryLogic(t *testing.T) {
tests := []struct {
name string
expiresAt int64
currentTime int64
shouldBeValid bool
description string
}{
{
name: "token valid for 1 hour",
expiresAt: time.Now().Add(time.Hour).Unix(),
shouldBeValid: true,
description: "Token expires in 1 hour, should be valid",
},
{
name: "token expiring in 2 minutes",
expiresAt: time.Now().Add(2 * time.Minute).Unix(),
shouldBeValid: false,
description: "Token expires in 2 minutes, should trigger refresh",
},
{
name: "token expired 1 hour ago",
expiresAt: time.Now().Add(-time.Hour).Unix(),
shouldBeValid: false,
description: "Token expired 1 hour ago, should trigger refresh",
},
{
name: "token expiring in exactly 5 minutes",
expiresAt: time.Now().Add(5 * time.Minute).Unix(),
shouldBeValid: false,
description: "Token expires in exactly 5 minutes, should trigger refresh",
},
{
name: "token expiring in 6 minutes",
expiresAt: time.Now().Add(6 * time.Minute).Unix(),
shouldBeValid: true,
description: "Token expires in 6 minutes, should still be valid",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := createAuthTestConfig()
cfg.CopilotToken = "test_token"
cfg.ExpiresAt = tt.expiresAt
authService := internal.NewAuthService(&http.Client{Timeout: 1 * time.Second})
err := authService.EnsureValidToken(cfg)
if tt.shouldBeValid {
if err != nil {
t.Errorf("Expected token to be valid, but got error: %v", err)
}
} else {
if err == nil {
t.Error("Expected token to need refresh, but no error was returned")
}
}
t.Logf("%s: %v", tt.description, err)
})
}
}
// Benchmark tests for performance verification
func BenchmarkAuthService_EnsureValidToken_ValidToken(b *testing.B) {
cfg := createAuthTestConfig()
cfg.CopilotToken = "valid_token"
cfg.ExpiresAt = time.Now().Add(time.Hour).Unix()
authService := internal.NewAuthService(&http.Client{Timeout: 1 * time.Second})
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = authService.EnsureValidToken(cfg)
}
}
func BenchmarkAuthService_EnsureValidToken_ExpiredToken(b *testing.B) {
cfg := createAuthTestConfig()
cfg.CopilotToken = "expired_token"
cfg.ExpiresAt = time.Now().Add(-time.Hour).Unix() // Expired
authService := internal.NewAuthService(&http.Client{Timeout: 1 * time.Second})
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = authService.EnsureValidToken(cfg) // Will return error quickly
}
}
// Test that RefreshToken saves to config file without hitting network
/* Obsolete TestRefreshTokenSavesConfig removed; use TestAuthService_RefreshToken_SavesConfig instead */
// Test that RefreshToken saves to the injected config path
func TestAuthService_RefreshToken_SavesConfig(t *testing.T) {
// Create temp config file
tmpfile, err := os.CreateTemp("", "copilot-config-*.json")
if err != nil {
t.Fatalf("failed to create temp file: %v", err)
}
defer os.Remove(tmpfile.Name())
cfg := createAuthTestConfig()
cfg.GitHubToken = "dummy-github-token"
// Dummy refresh func (no network)
refreshFunc := func(c *internal.Config) error {
c.CopilotToken = "dummy-copilot-token"
c.ExpiresAt = time.Now().Unix() + 3600
c.RefreshIn = 1800
return nil
}
authSvc := internal.NewAuthService(&http.Client{},
internal.WithConfigPath(tmpfile.Name()),
internal.WithRefreshFunc(refreshFunc),
)
if refreshErr := authSvc.RefreshToken(cfg); refreshErr != nil {
t.Fatalf("RefreshToken failed: %v", refreshErr)
}
// Read back the config file
loaded := &internal.Config{}
f, openErr := os.Open(tmpfile.Name())
if openErr != nil {
t.Fatalf("failed to open temp config file: %v", openErr)
}
defer f.Close()
if decodeErr := json.NewDecoder(f).Decode(loaded); decodeErr != nil {
t.Fatalf("failed to decode config: %v", decodeErr)
}
if loaded.CopilotToken != "dummy-copilot-token" {
t.Errorf("CopilotToken not saved correctly, got: %v", loaded.CopilotToken)
}
if loaded.ExpiresAt == 0 {
t.Errorf("ExpiresAt not saved")
}
if loaded.RefreshIn == 0 {
t.Errorf("RefreshIn not saved")
}
}