forked from codeGROOVE-dev/slacker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoauth_handlers_test.go
More file actions
612 lines (495 loc) · 17.1 KB
/
oauth_handlers_test.go
File metadata and controls
612 lines (495 loc) · 17.1 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
package slack
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/slack-go/slack"
)
// mockWorkspaceStore is a programmable mock for WorkspaceStorer.
type mockWorkspaceStore struct {
storeFunc func(ctx context.Context, metadata *WorkspaceMetadata, token string) error
}
func (m *mockWorkspaceStore) StoreWorkspace(ctx context.Context, metadata *WorkspaceMetadata, token string) error {
if m.storeFunc != nil {
return m.storeFunc(ctx, metadata, token)
}
return nil // Default: success
}
// mockOAuthExchanger is a programmable mock for OAuthExchanger.
type mockOAuthExchanger struct {
exchangeFunc func(ctx context.Context, clientID, clientSecret, code string) (*slack.OAuthV2Response, error)
}
func (m *mockOAuthExchanger) ExchangeCode(ctx context.Context, clientID, clientSecret, code string) (*slack.OAuthV2Response, error) {
if m.exchangeFunc != nil {
return m.exchangeFunc(ctx, clientID, clientSecret, code)
}
// Default: return error (OAuth exchange requires real Slack API)
return nil, errors.New("mock: OAuth exchange not configured")
}
// TestHandleCallback_MissingCode tests when code parameter is missing.
func TestHandleCallback_MissingCode(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: &mockOAuthExchanger{},
store: &mockWorkspaceStore{},
}
req := httptest.NewRequest(http.MethodGet, "/oauth/callback", http.NoBody)
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status 400, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "Missing code parameter") {
t.Errorf("Expected error message about missing code, got: %s", body)
}
}
// TestHandleCallback_ShortCode tests OAuth code logging with short value.
func TestHandleCallback_ShortCode(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: &mockOAuthExchanger{},
store: &mockWorkspaceStore{},
}
// Use very short code (< 10 chars) to test min() edge case in logging
// Use context with short timeout to avoid waiting for retries
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=abc", http.NoBody).WithContext(ctx)
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
// Will fail at OAuth exchange but we're testing the code path before that
// The important part is that the short code doesn't cause a panic
if w.Code != http.StatusInternalServerError && w.Code != http.StatusBadRequest {
t.Logf("Got status %d (expected some error status)", w.Code)
}
}
// TestHandleCallback_OAuthError tests when OAuth returns an error.
func TestHandleCallback_OAuthError(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: &mockOAuthExchanger{},
store: &mockWorkspaceStore{},
}
// Error parameter takes priority over code
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=test&error=access_denied", http.NoBody)
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status 400, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "OAuth error") {
t.Errorf("Expected OAuth error message, got: %s", body)
}
}
// TestHandleCallback_StateMismatch tests CSRF protection.
func TestHandleCallback_StateMismatch(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: &mockOAuthExchanger{},
store: &mockWorkspaceStore{},
}
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=test-code&state=wrong-state", http.NoBody)
req.AddCookie(&http.Cookie{
Name: "oauth_state",
Value: "correct-state",
})
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status 400, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "Invalid state parameter") {
t.Errorf("Expected invalid state error, got: %s", body)
}
}
// TestHandleCallback_StateMismatchShortValue tests state mismatch with short strings.
func TestHandleCallback_StateMismatchShortValue(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: &mockOAuthExchanger{},
store: &mockWorkspaceStore{},
}
// Use very short state values (< 10 chars) to test min() edge case in logging
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=test-code&state=abc", http.NoBody)
req.AddCookie(&http.Cookie{
Name: "oauth_state",
Value: "xyz",
})
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status 400, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "Invalid state parameter") {
t.Errorf("Expected invalid state error, got: %s", body)
}
}
// TestHandleCallback_MissingStateCookie tests when state param exists but cookie doesn't.
func TestHandleCallback_MissingStateCookie(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: &mockOAuthExchanger{},
store: &mockWorkspaceStore{},
}
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=test-code&state=some-state", http.NoBody)
// Don't add cookie
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status 400, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "Invalid state parameter") {
t.Errorf("Expected invalid state error, got: %s", body)
}
}
// TestHandleCallback_StateMatchSuccess tests successful state verification.
func TestHandleCallback_StateMatchSuccess(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: &mockOAuthExchanger{},
store: &mockWorkspaceStore{},
}
// Use context with short timeout to avoid waiting for retries
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=test-code&state=matching-state", http.NoBody).WithContext(ctx)
req.AddCookie(&http.Cookie{
Name: "oauth_state",
Value: "matching-state",
})
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
// This will fail at token exchange (since we're not mocking Slack OAuth API)
// but we can verify state checking passed by checking we got past that point
// The error should be about token exchange, not state
if w.Code == http.StatusBadRequest {
body := w.Body.String()
if strings.Contains(body, "Invalid state parameter") {
t.Error("State verification should have passed")
}
}
}
// TestHandleCallback_CookieDeletion tests that state cookie is cleared after verification.
func TestHandleCallback_CookieDeletion(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: &mockOAuthExchanger{},
store: &mockWorkspaceStore{},
}
// Use context with short timeout to avoid waiting for retries
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=test-code&state=matching-state", http.NoBody).WithContext(ctx)
req.AddCookie(&http.Cookie{
Name: "oauth_state",
Value: "matching-state",
})
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
// Verify the state cookie was cleared (MaxAge: -1)
cookies := w.Result().Cookies()
var stateCookie *http.Cookie
for _, cookie := range cookies {
if cookie.Name == "oauth_state" {
stateCookie = cookie
break
}
}
if stateCookie == nil {
t.Error("Expected oauth_state cookie to be set for deletion")
return
}
if stateCookie.MaxAge != -1 {
t.Errorf("Expected oauth_state cookie MaxAge to be -1 (deleted), got %d", stateCookie.MaxAge)
}
if stateCookie.Value != "" {
t.Errorf("Expected oauth_state cookie value to be empty, got %q", stateCookie.Value)
}
if !stateCookie.HttpOnly {
t.Error("Expected oauth_state cookie to be HttpOnly")
}
if !stateCookie.Secure {
t.Error("Expected oauth_state cookie to be Secure")
}
}
// TestHandleCallback_NoStateParam tests direct installation without state.
func TestHandleCallback_NoStateParam(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: &mockOAuthExchanger{},
store: &mockWorkspaceStore{},
}
// Use context with short timeout to avoid waiting for retries
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=test-code", http.NoBody).WithContext(ctx)
// No state parameter, no cookie
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
// Should proceed without state checking (Slack App Directory flow)
// Will fail at token exchange but that's expected
if w.Code == http.StatusBadRequest {
body := w.Body.String()
if strings.Contains(body, "Invalid state parameter") {
t.Error("Should allow installation without state parameter")
}
}
}
// TestHandleCallback_StoreWorkspaceError tests workspace storage failure.
func TestHandleCallback_StoreWorkspaceError(t *testing.T) {
t.Parallel()
// Create mocks - OAuth succeeds but storage fails
mockExchanger := &mockOAuthExchanger{
exchangeFunc: func(ctx context.Context, clientID, clientSecret, code string) (*slack.OAuthV2Response, error) {
return &slack.OAuthV2Response{
SlackResponse: slack.SlackResponse{
Ok: true,
},
Team: slack.OAuthV2ResponseTeam{
ID: "T12345",
Name: "Test Workspace",
},
AccessToken: "xoxb-test-token",
BotUserID: "U123BOT",
}, nil
},
}
mockStore := &mockWorkspaceStore{
storeFunc: func(ctx context.Context, metadata *WorkspaceMetadata, token string) error {
return errors.New("storage failure")
},
}
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: mockExchanger,
store: mockStore,
}
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=valid-code", http.NoBody)
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
// Should return 500 due to storage failure
if w.Code != http.StatusInternalServerError {
t.Errorf("Expected status 500, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "Failed to store credentials") {
t.Errorf("Expected storage error message, got: %s", body)
}
}
// TestHandleCallback_OAuthNotOk tests OAuth response with Ok: false.
func TestHandleCallback_OAuthNotOk(t *testing.T) {
t.Parallel()
mockExchanger := &mockOAuthExchanger{
exchangeFunc: func(ctx context.Context, clientID, clientSecret, code string) (*slack.OAuthV2Response, error) {
return &slack.OAuthV2Response{
SlackResponse: slack.SlackResponse{
Ok: false,
Error: "invalid_code",
},
}, nil
},
}
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: mockExchanger,
store: &mockWorkspaceStore{},
}
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=invalid-code", http.NoBody)
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
if w.Code != http.StatusInternalServerError {
t.Errorf("Expected status 500, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "OAuth error") {
t.Errorf("Expected OAuth error message, got: %s", body)
}
}
// TestHandleCallback_SuccessfulFlow tests complete OAuth success flow.
func TestHandleCallback_SuccessfulFlow(t *testing.T) {
t.Parallel()
var storedMetadata *WorkspaceMetadata
var storedToken string
mockExchanger := &mockOAuthExchanger{
exchangeFunc: func(ctx context.Context, clientID, clientSecret, code string) (*slack.OAuthV2Response, error) {
return &slack.OAuthV2Response{
SlackResponse: slack.SlackResponse{
Ok: true,
},
Team: slack.OAuthV2ResponseTeam{
ID: "T12345",
Name: "Test Workspace",
},
AccessToken: "xoxb-test-token",
BotUserID: "U123BOT",
Scope: "channels:read,chat:write",
}, nil
},
}
mockStore := &mockWorkspaceStore{
storeFunc: func(ctx context.Context, metadata *WorkspaceMetadata, token string) error {
storedMetadata = metadata
storedToken = token
return nil
},
}
handler := &OAuthHandler{
clientID: "test-client-id",
clientSecret: "test-secret",
exchanger: mockExchanger,
store: mockStore,
}
req := httptest.NewRequest(http.MethodGet, "/oauth/callback?code=valid-code", http.NoBody)
w := httptest.NewRecorder()
handler.HandleCallback(w, req)
// Should return 200 with success page
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
// Verify metadata was stored
if storedMetadata == nil {
t.Fatal("Expected metadata to be stored")
}
if storedMetadata.TeamID != "T12345" {
t.Errorf("Expected TeamID T12345, got %s", storedMetadata.TeamID)
}
if storedMetadata.TeamName != "Test Workspace" {
t.Errorf("Expected TeamName 'Test Workspace', got %s", storedMetadata.TeamName)
}
if storedMetadata.BotUserID != "U123BOT" {
t.Errorf("Expected BotUserID U123BOT, got %s", storedMetadata.BotUserID)
}
if storedToken != "xoxb-test-token" {
t.Errorf("Expected token 'xoxb-test-token', got %s", storedToken)
}
// Verify success page HTML
body := w.Body.String()
if !strings.Contains(body, "<!DOCTYPE html>") {
t.Error("Expected HTML success page")
}
if !strings.Contains(body, "Test Workspace") {
t.Error("Expected workspace name in success page")
}
}
// TestWriteSuccessPage tests HTML success page rendering.
func TestWriteSuccessPage(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{}
w := httptest.NewRecorder()
handler.writeSuccessPage(w, "Test Workspace")
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
contentType := w.Header().Get("Content-Type")
if !strings.Contains(contentType, "text/html") {
t.Errorf("Expected text/html content type, got %s", contentType)
}
body := w.Body.String()
if !strings.Contains(body, "<!DOCTYPE html>") {
t.Error("Expected HTML doctype")
}
if !strings.Contains(body, "Test Workspace") {
t.Error("Expected workspace name in output")
}
if !strings.Contains(body, "Installation Complete") || !strings.Contains(body, "Success") {
t.Error("Expected success message in output")
}
}
// TestWriteSuccessPage_EmptyWorkspaceName tests with empty workspace name.
func TestWriteSuccessPage_EmptyWorkspaceName(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{}
w := httptest.NewRecorder()
handler.writeSuccessPage(w, "")
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "<!DOCTYPE html>") {
t.Error("Expected HTML doctype even with empty workspace name")
}
}
// TestWriteInstallPage tests HTML install page rendering.
func TestWriteInstallPage(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{}
authURL := "https://slack.com/oauth/v2/authorize?client_id=test&scope=test"
w := httptest.NewRecorder()
handler.writeInstallPage(w, authURL)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
contentType := w.Header().Get("Content-Type")
if !strings.Contains(contentType, "text/html") {
t.Errorf("Expected text/html content type, got %s", contentType)
}
body := w.Body.String()
if !strings.Contains(body, "<!DOCTYPE html>") {
t.Error("Expected HTML doctype")
}
if !strings.Contains(body, authURL) {
t.Error("Expected auth URL in output")
}
if !strings.Contains(body, "Install reviewGOOSE") || !strings.Contains(body, "Add to Slack") {
t.Error("Expected install button/text in output")
}
}
// TestWriteInstallPage_EmptyAuthURL tests with empty auth URL.
func TestWriteInstallPage_EmptyAuthURL(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{}
w := httptest.NewRecorder()
handler.writeInstallPage(w, "")
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "<!DOCTYPE html>") {
t.Error("Expected HTML doctype even with empty auth URL")
}
}
// TestWriteInstallPage_SpecialCharactersInURL tests URL with special characters.
func TestWriteInstallPage_SpecialCharactersInURL(t *testing.T) {
t.Parallel()
handler := &OAuthHandler{}
authURL := "https://slack.com/oauth?param1=value1¶m2=value2&redirect_uri=https://example.com/callback"
w := httptest.NewRecorder()
handler.writeInstallPage(w, authURL)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
body := w.Body.String()
// URL should be in the output (possibly HTML-escaped)
if !strings.Contains(body, "slack.com/oauth") {
t.Error("Expected auth URL domain in output")
}
}