-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgithub_test.go
More file actions
1362 lines (1252 loc) · 42.1 KB
/
Copy pathgithub_test.go
File metadata and controls
1362 lines (1252 loc) · 42.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
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package githubauth
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"golang.org/x/oauth2"
)
func Test_githubClient_withEnterpriseURL(t *testing.T) {
tests := []struct {
name string
baseURL string
wantErr bool
expectedBaseURL string
}{
{
name: "valid URL with first subdomain",
baseURL: "https://api.github.example.com",
wantErr: false,
expectedBaseURL: "https://api.github.example.com/",
},
{
name: "valid URL with first subdomain and trailing slash",
baseURL: "https://api.github.example.com/",
wantErr: false,
expectedBaseURL: "https://api.github.example.com/",
},
{
name: "valid URL with second subdomain",
baseURL: "https://ghes.api.example.com",
wantErr: false,
expectedBaseURL: "https://ghes.api.example.com/",
},
{
name: "valid URL with second subdomain and trailing slash",
baseURL: "https://ghes.api.example.com/",
wantErr: false,
expectedBaseURL: "https://ghes.api.example.com/",
},
{
name: "valid URL with path",
baseURL: "https://github.example.com/api/v3",
wantErr: false,
expectedBaseURL: "https://github.example.com/api/v3/",
},
{
name: "valid URL with path and trailing slash",
baseURL: "https://github.example.com/api/v3/",
wantErr: false,
expectedBaseURL: "https://github.example.com/api/v3/",
},
{
name: "valid URL without path",
baseURL: "https://github.example.com",
wantErr: false,
expectedBaseURL: "https://github.example.com/api/v3/",
},
{
name: "valid URL without path but with trailing slash",
baseURL: "https://github.example.com/",
wantErr: false,
expectedBaseURL: "https://github.example.com/api/v3/",
},
{
name: "invalid URL with control characters",
baseURL: "ht\ntp://invalid",
wantErr: true,
expectedBaseURL: "",
},
{
name: "URL with spaces",
baseURL: "http://invalid url with spaces",
wantErr: true,
expectedBaseURL: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := newGitHubClient(&http.Client{})
githubClient, err := client.withEnterpriseURL(tt.baseURL)
if (err != nil) != tt.wantErr {
t.Errorf("withEnterpriseURL(%v) error = %v", tt.baseURL, err)
}
if err == nil && githubClient.baseURL.String() != tt.expectedBaseURL {
t.Errorf("withEnterpriseURL(%v) expected = %v, received = %v", tt.baseURL, tt.expectedBaseURL, githubClient.baseURL)
}
})
}
}
func Test_githubClient_withBaseURL(t *testing.T) {
tests := []struct {
name string
baseURL string
wantErr bool
expectedBaseURL string
}{
{
name: "GHEC data residency URL is used verbatim",
baseURL: "https://api.octocorp.ghe.com",
wantErr: false,
expectedBaseURL: "https://api.octocorp.ghe.com/",
},
{
name: "GHEC data residency URL with trailing slash",
baseURL: "https://api.octocorp.ghe.com/",
wantErr: false,
expectedBaseURL: "https://api.octocorp.ghe.com/",
},
{
name: "plain host without /api/v3 suffix appended",
baseURL: "https://github.example.com",
wantErr: false,
expectedBaseURL: "https://github.example.com/",
},
{
name: "existing path is preserved without /api/v3 munging",
baseURL: "https://github.example.com/api/v3",
wantErr: false,
expectedBaseURL: "https://github.example.com/api/v3/",
},
{
name: "httptest-style host and port used verbatim",
baseURL: "http://127.0.0.1:8080",
wantErr: false,
expectedBaseURL: "http://127.0.0.1:8080/",
},
{
name: "invalid URL with control characters",
baseURL: "ht\ntp://invalid",
wantErr: true,
expectedBaseURL: "",
},
{
name: "URL with spaces",
baseURL: "http://invalid url with spaces",
wantErr: true,
expectedBaseURL: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := newGitHubClient(&http.Client{})
githubClient, err := client.withBaseURL(tt.baseURL)
if (err != nil) != tt.wantErr {
t.Errorf("withBaseURL(%v) error = %v", tt.baseURL, err)
}
if err == nil && githubClient.baseURL.String() != tt.expectedBaseURL {
t.Errorf("withBaseURL(%v) expected = %v, received = %v", tt.baseURL, tt.expectedBaseURL, githubClient.baseURL)
}
})
}
}
func Test_githubClient_createInstallationToken_ErrorCases(t *testing.T) {
tests := []struct {
name string
setupServer func() *httptest.Server
opts *InstallationTokenOptions
wantErr bool
errorSubstring string
}{
{
name: "invalid JSON in options",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(InstallationToken{
Token: "test-token",
ExpiresAt: time.Now().Add(1 * time.Hour),
})
}))
},
opts: &InstallationTokenOptions{
Repositories: []string{"repo1"},
},
wantErr: false,
},
{
name: "bad request - 400",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"message":"Bad Request"}`))
}))
},
opts: nil,
wantErr: true,
errorSubstring: "400",
},
{
name: "unauthorized - 401",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"message":"Unauthorized"}`))
}))
},
opts: nil,
wantErr: true,
errorSubstring: "401",
},
{
name: "forbidden - 403",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message":"Forbidden"}`))
}))
},
opts: nil,
wantErr: true,
errorSubstring: "403",
},
{
name: "not found - 404",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message":"Not Found"}`))
}))
},
opts: nil,
wantErr: true,
errorSubstring: "404",
},
{
name: "invalid JSON response",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{invalid json`))
}))
},
opts: nil,
wantErr: true,
errorSubstring: "failed to decode response",
},
{
name: "success with nil options",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(InstallationToken{
Token: "test-token",
ExpiresAt: time.Now().Add(1 * time.Hour),
})
}))
},
opts: nil,
wantErr: false,
},
{
name: "success with HTTP 200",
setupServer: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(InstallationToken{
Token: "test-token",
ExpiresAt: time.Now().Add(1 * time.Hour),
})
}))
},
opts: nil,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := tt.setupServer()
defer server.Close()
client := newGitHubClient(&http.Client{})
client.baseURL, _ = client.baseURL.Parse(server.URL)
_, err := client.createInstallationToken(context.Background(), 12345, tt.opts)
if (err != nil) != tt.wantErr {
t.Errorf("createInstallationToken() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.wantErr && tt.errorSubstring != "" {
if err == nil {
t.Errorf("expected error containing %q, got nil", tt.errorSubstring)
} else if !strings.Contains(err.Error(), tt.errorSubstring) {
t.Errorf("expected error containing %q, got %q", tt.errorSubstring, err.Error())
}
}
})
}
}
func Test_Ptr(t *testing.T) {
t.Run("string pointer", func(t *testing.T) {
s := "test"
p := Ptr(s)
if p == nil {
t.Fatal("Ptr() returned nil")
}
if *p != s {
t.Errorf("Ptr() = %v, want %v", *p, s)
}
})
t.Run("int pointer", func(t *testing.T) {
i := 42
p := Ptr(i)
if p == nil {
t.Fatal("Ptr() returned nil")
}
if *p != i {
t.Errorf("Ptr() = %v, want %v", *p, i)
}
})
t.Run("int64 pointer", func(t *testing.T) {
i := int64(123456)
p := Ptr(i)
if p == nil {
t.Fatal("Ptr() returned nil")
}
if *p != i {
t.Errorf("Ptr() = %v, want %v", *p, i)
}
})
}
// roundTripperFunc adapts a function to http.RoundTripper so a transport can
// fail without standing up a server.
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
// Test_doCreateInstallationToken_RequestErrors covers the two failures of a
// single POST attempt that never produce a response: a URL net/url refuses, and
// a transport that fails the round trip. They are driven through
// doCreateInstallationToken directly because createInstallationToken builds its
// URL with url.URL.JoinPath and therefore cannot produce an unusable one.
func Test_doCreateInstallationToken_RequestErrors(t *testing.T) {
t.Parallel()
tests := []struct {
name string
transport http.RoundTripper
reqURL string
want string
}{
{
// DEL is a control character net/url rejects, so http.NewRequest
// fails and no connection is ever attempted.
name: "URL carrying a control character",
reqURL: "http://example.invalid/app/installations/1/access_tokens\x7f",
want: "failed to create request",
},
{
name: "transport fails the round trip",
transport: roundTripperFunc(func(*http.Request) (*http.Response, error) {
return nil, errors.New("connection refused")
}),
reqURL: "http://example.invalid/app/installations/1/access_tokens",
want: "failed to execute request",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := newGitHubClient(&http.Client{Transport: tt.transport})
tok, err := c.doCreateInstallationToken(context.Background(), tt.reqURL, nil)
if err == nil {
t.Fatalf("doCreateInstallationToken() err = nil, want an error containing %q", tt.want)
}
if tok != nil {
t.Errorf("token = %+v, want nil", tok)
}
if !strings.Contains(err.Error(), tt.want) {
t.Errorf("err = %q, want it to contain %q", err, tt.want)
}
})
}
}
// Test_createInstallationToken_EndpointURL pins the path the client POSTs to.
// The endpoint is joined onto the base with url.URL.JoinPath, so an Enterprise
// base path such as /api/v3/ has to survive rather than be resolved away the
// way a relative reference would resolve it.
func Test_createInstallationToken_EndpointURL(t *testing.T) {
t.Parallel()
tests := []struct {
name string
basePath string // appended to the httptest server URL
wantPath string
}{
{
name: "root base path",
basePath: "/",
wantPath: "/app/installations/12345/access_tokens",
},
{
name: "enterprise base path",
basePath: "/api/v3/",
wantPath: "/api/v3/app/installations/12345/access_tokens",
},
{
name: "nested base path",
basePath: "/gh/api/v3/",
wantPath: "/gh/api/v3/app/installations/12345/access_tokens",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
gotPath := make(chan string, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath <- r.URL.Path
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(InstallationToken{
Token: "test-token",
ExpiresAt: time.Now().Add(time.Hour),
})
}))
defer server.Close()
c := newGitHubClient(&http.Client{})
if _, err := c.withBaseURL(server.URL + tt.basePath); err != nil {
t.Fatalf("withBaseURL(%q): %v", tt.basePath, err)
}
if _, err := c.createInstallationToken(context.Background(), 12345, nil); err != nil {
t.Fatalf("createInstallationToken() err = %v", err)
}
select {
case got := <-gotPath:
if got != tt.wantPath {
t.Errorf("request path = %q, want %q", got, tt.wantPath)
}
default:
t.Fatal("server received no request")
}
})
}
}
// Test_createInstallationToken_SendsOptionsBody proves InstallationTokenOptions
// reach GitHub as the JSON request body, and that a nil options value sends no
// body at all rather than a JSON "null".
func Test_createInstallationToken_SendsOptionsBody(t *testing.T) {
t.Parallel()
tests := []struct {
name string
opts *InstallationTokenOptions
wantBody string
}{
{
name: "nil options send no body",
opts: nil,
wantBody: "",
},
{
name: "options are marshaled into the body",
opts: &InstallationTokenOptions{
Repositories: []string{"repo1", "repo2"},
Permissions: &InstallationPermissions{
Contents: Ptr("read"),
Issues: Ptr("write"),
},
},
wantBody: `{"repositories":["repo1","repo2"],"permissions":{"contents":"read","issues":"write"}}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
gotBody := make(chan string, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("read request body: %v", err)
}
gotBody <- string(b)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(InstallationToken{
Token: "test-token",
ExpiresAt: time.Now().Add(time.Hour),
})
}))
defer server.Close()
client := newClientForServer(t, server)
tok, err := client.createInstallationToken(context.Background(), 12345, tt.opts)
if err != nil {
t.Fatalf("createInstallationToken() err = %v", err)
}
if tok.Token != "test-token" {
t.Errorf("token = %q, want %q", tok.Token, "test-token")
}
select {
case got := <-gotBody:
if got != tt.wantBody {
t.Errorf("request body = %q, want %q", got, tt.wantBody)
}
default:
t.Fatal("server received no request")
}
})
}
}
// throttleResponse programs one hit on throttleHandler. A response is emitted
// per call, indexed by attempt count; exceeding the list replays the last entry.
type throttleResponse struct {
status int
headers map[string]string
body string
writeToken bool // serialize an InstallationToken JSON body instead of body
}
func throttleHandler(t *testing.T, responses []throttleResponse, attempts *atomic.Int32) http.HandlerFunc {
t.Helper()
return func(w http.ResponseWriter, _ *http.Request) {
n := attempts.Add(1)
idx := int(n-1) % len(responses)
r := responses[idx]
for k, v := range r.headers {
w.Header().Set(k, v)
}
if r.writeToken {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(r.status)
_ = json.NewEncoder(w).Encode(InstallationToken{
Token: "test-token",
ExpiresAt: time.Now().Add(time.Hour),
})
return
}
w.WriteHeader(r.status)
if r.body != "" {
_, _ = w.Write([]byte(r.body))
}
}
}
func newClientForServer(t *testing.T, server *httptest.Server) *githubClient {
t.Helper()
c := newGitHubClient(&http.Client{Timeout: 10 * time.Second})
baseURL, err := c.baseURL.Parse(server.URL + "/")
if err != nil {
t.Fatalf("parse server URL: %v", err)
}
c.baseURL = baseURL
return c
}
func Test_createInstallationToken_RetryOnThrottle(t *testing.T) {
tests := []struct {
name string
responses []throttleResponse
retryEnabled bool
wantAttempts int32
wantErr bool
wantRateLimit bool
minElapsed time.Duration
maxElapsed time.Duration
}{
{
name: "429 with Retry-After=1 retries and succeeds",
responses: []throttleResponse{
{status: http.StatusTooManyRequests, headers: map[string]string{"Retry-After": "1"}, body: `{"message":"rate limited"}`},
{status: http.StatusCreated, writeToken: true},
},
retryEnabled: true,
wantAttempts: 2,
wantErr: false,
minElapsed: 900 * time.Millisecond,
maxElapsed: 3 * time.Second,
},
{
name: "429 without Retry-After uses default 1s backoff",
responses: []throttleResponse{
{status: http.StatusTooManyRequests, body: `{"message":"rate limited"}`},
{status: http.StatusCreated, writeToken: true},
},
retryEnabled: true,
wantAttempts: 2,
wantErr: false,
minElapsed: 900 * time.Millisecond,
maxElapsed: 3 * time.Second,
},
{
name: "two consecutive 429s retry once then fail",
responses: []throttleResponse{
{status: http.StatusTooManyRequests, headers: map[string]string{"Retry-After": "0"}, body: `{"message":"first"}`},
{status: http.StatusTooManyRequests, headers: map[string]string{"Retry-After": "0"}, body: `{"message":"second"}`},
},
retryEnabled: true,
wantAttempts: 2,
wantErr: true,
wantRateLimit: true,
},
{
name: "WithRetryOnThrottle(false) disables retry",
responses: []throttleResponse{
{status: http.StatusTooManyRequests, headers: map[string]string{"Retry-After": "0"}, body: `{"message":"no retry"}`},
{status: http.StatusCreated, writeToken: true},
},
retryEnabled: false,
wantAttempts: 1,
wantErr: true,
wantRateLimit: true,
},
{
name: "403 without retry headers is not retried",
responses: []throttleResponse{
{status: http.StatusForbidden, body: `{"message":"forbidden"}`},
},
retryEnabled: true,
wantAttempts: 1,
wantErr: true,
},
{
name: "403 with unparseable Retry-After is not retried",
responses: []throttleResponse{
{status: http.StatusForbidden, headers: map[string]string{"Retry-After": "not-a-date"}, body: `{"message":"forbidden"}`},
},
retryEnabled: true,
wantAttempts: 1,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var attempts atomic.Int32
server := httptest.NewServer(throttleHandler(t, tt.responses, &attempts))
defer server.Close()
client := newClientForServer(t, server)
client.retryOnThrottle = tt.retryEnabled
start := time.Now()
_, err := client.createInstallationToken(context.Background(), 12345, nil)
elapsed := time.Since(start)
if got := attempts.Load(); got != tt.wantAttempts {
t.Errorf("attempts = %d, want %d", got, tt.wantAttempts)
}
if (err != nil) != tt.wantErr {
t.Errorf("err = %v, wantErr = %v", err, tt.wantErr)
}
if tt.wantRateLimit && !errors.Is(err, ErrRateLimited) {
t.Errorf("err = %v, want errors.Is(err, ErrRateLimited)", err)
}
if tt.minElapsed > 0 && elapsed < tt.minElapsed {
t.Errorf("elapsed = %v, want >= %v", elapsed, tt.minElapsed)
}
if tt.maxElapsed > 0 && elapsed > tt.maxElapsed {
t.Errorf("elapsed = %v, want <= %v", elapsed, tt.maxElapsed)
}
})
}
}
func Test_createInstallationToken_XRateLimitReset(t *testing.T) {
// x-ratelimit-reset is a Unix-second epoch, so the header value must be
// computed at request-time to avoid sub-second truncation that makes the
// elapsed-time assertion flaky. x-ratelimit-remaining is 0 because that is
// what marks a 403 as throttled rather than terminal; see
// Test_createInstallationToken_403PermissionNotThrottled.
var attempts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
n := attempts.Add(1)
if n == 1 {
w.Header().Set("X-RateLimit-Remaining", "0")
w.Header().Set("X-RateLimit-Reset", strconv.FormatInt(time.Now().Add(3*time.Second).Unix(), 10))
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message":"rate limited"}`))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(InstallationToken{
Token: "test-token",
ExpiresAt: time.Now().Add(time.Hour),
})
}))
defer server.Close()
client := newClientForServer(t, server)
start := time.Now()
tok, err := client.createInstallationToken(context.Background(), 12345, nil)
elapsed := time.Since(start)
if err != nil {
t.Fatalf("createInstallationToken err = %v", err)
}
if tok == nil || tok.Token != "test-token" {
t.Errorf("token = %+v, want Token=\"test-token\"", tok)
}
if got := attempts.Load(); got != 2 {
t.Errorf("attempts = %d, want 2", got)
}
// Reset is now+3, Unix() can truncate up to 1s, so the floor is ~2s.
if elapsed < 1500*time.Millisecond {
t.Errorf("elapsed = %v, want >= 1.5s (reset hint was now+3s)", elapsed)
}
if elapsed > 5*time.Second {
t.Errorf("elapsed = %v, want <= 5s (bounded by reset hint)", elapsed)
}
}
func Test_throttleDelay_CapsAtMaxRetrySleep(t *testing.T) {
// Verify directly at the throttleDelay boundary so the assertion is
// deterministic and fast (no real sleep).
c := newGitHubClient(&http.Client{})
resp := &http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"Retry-After": []string{"600"}},
}
d, ok := c.throttleDelay(resp, nil)
if !ok {
t.Fatalf("throttleDelay ok = false, want true")
}
if d != maxRetrySleep {
t.Errorf("delay = %v, want %v", d, maxRetrySleep)
}
resp = &http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"Retry-After": []string{time.Now().Add(1 * time.Hour).UTC().Format(http.TimeFormat)}},
}
d, ok = c.throttleDelay(resp, nil)
if !ok {
t.Fatalf("throttleDelay ok = false, want true")
}
if d != maxRetrySleep {
t.Errorf("HTTP-date delay = %v, want %v", d, maxRetrySleep)
}
}
func Test_createInstallationToken_ContextCancelledDuringSleep(t *testing.T) {
var attempts atomic.Int32
server := httptest.NewServer(throttleHandler(t, []throttleResponse{
{status: http.StatusTooManyRequests, headers: map[string]string{"Retry-After": "30"}, body: `{"message":"rate limited"}`},
}, &attempts))
defer server.Close()
client := newClientForServer(t, server)
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(150 * time.Millisecond)
cancel()
}()
start := time.Now()
_, err := client.createInstallationToken(ctx, 12345, nil)
elapsed := time.Since(start)
if !errors.Is(err, context.Canceled) {
t.Errorf("err = %v, want context.Canceled", err)
}
if elapsed > 5*time.Second {
t.Errorf("elapsed = %v, expected ctx cancellation to abort sleep quickly", elapsed)
}
if got := attempts.Load(); got != 1 {
t.Errorf("attempts = %d, want 1 (no retry after cancellation)", got)
}
}
func Test_parseRetryAfter(t *testing.T) {
now := time.Date(2026, 4, 20, 12, 0, 0, 0, time.UTC)
tests := []struct {
name string
value string
want time.Duration
wantOK bool
}{
{name: "integer seconds", value: "5", want: 5 * time.Second, wantOK: true},
{name: "integer seconds with whitespace", value: " 7 ", want: 7 * time.Second, wantOK: true},
{name: "zero seconds", value: "0", want: 0, wantOK: true},
{name: "negative seconds", value: "-3", want: -3 * time.Second, wantOK: true},
{name: "HTTP-date future", value: now.Add(10 * time.Second).Format(http.TimeFormat), want: 10 * time.Second, wantOK: true},
{name: "HTTP-date past", value: now.Add(-10 * time.Second).Format(http.TimeFormat), want: -10 * time.Second, wantOK: true},
{name: "unparseable reports not-ok", value: "not-a-date", want: 0, wantOK: false},
{name: "empty reports not-ok", value: "", want: 0, wantOK: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, ok := parseRetryAfter(tt.value, now)
if got != tt.want || ok != tt.wantOK {
t.Errorf("parseRetryAfter(%q) = (%v, %v), want (%v, %v)", tt.value, got, ok, tt.want, tt.wantOK)
}
})
}
}
func Test_throttleDelay_NonThrottledStatus(t *testing.T) {
c := newGitHubClient(&http.Client{})
for _, status := range []int{http.StatusOK, http.StatusCreated, http.StatusBadRequest, http.StatusInternalServerError} {
resp := &http.Response{StatusCode: status, Header: http.Header{"Retry-After": []string{"5"}}}
if d, ok := c.throttleDelay(resp, nil); ok || d != 0 {
t.Errorf("status %d: got (%v, %v), want (0, false)", status, d, ok)
}
}
}
func Test_WithRetryOnThrottle_AffectsSource(t *testing.T) {
// Drive a full installationTokenSource.Token() through a throttled server
// to verify the option propagates from the source down to the client.
var attempts atomic.Int32
server := httptest.NewServer(throttleHandler(t, []throttleResponse{
{status: http.StatusTooManyRequests, headers: map[string]string{"Retry-After": "0"}, body: `{"message":"first"}`},
{status: http.StatusCreated, writeToken: true},
}, &attempts))
defer server.Close()
src := oauth2StaticSource{accessToken: "jwt"}
ts := NewInstallationTokenSource(42, src,
WithEnterpriseURL(server.URL),
WithRetryOnThrottle(true),
)
tok, err := ts.Token()
if err != nil {
t.Fatalf("Token() err = %v", err)
}
if tok.AccessToken != "test-token" {
t.Errorf("AccessToken = %q, want %q", tok.AccessToken, "test-token")
}
if got := attempts.Load(); got != 2 {
t.Errorf("attempts = %d, want 2", got)
}
var attempts2 atomic.Int32
server2 := httptest.NewServer(throttleHandler(t, []throttleResponse{
{status: http.StatusTooManyRequests, headers: map[string]string{"Retry-After": "0"}, body: `{"message":"first"}`},
{status: http.StatusCreated, writeToken: true},
}, &attempts2))
defer server2.Close()
ts2 := NewInstallationTokenSource(42, src,
WithEnterpriseURL(server2.URL),
WithRetryOnThrottle(false),
)
_, err = ts2.Token()
if err == nil {
t.Fatalf("Token() err = nil, want ErrRateLimited")
}
if !errors.Is(err, ErrRateLimited) {
t.Errorf("err = %v, want errors.Is(err, ErrRateLimited)", err)
}
if got := attempts2.Load(); got != 1 {
t.Errorf("attempts = %d, want 1", got)
}
}
// oauth2StaticSource is a minimal oauth2.TokenSource emitting a fixed JWT so
// the installation-token POST can authenticate against the mock server.
type oauth2StaticSource struct {
accessToken string
}
func (s oauth2StaticSource) Token() (*oauth2.Token, error) {
return &oauth2.Token{
AccessToken: s.accessToken,
TokenType: "Bearer",
Expiry: time.Now().Add(time.Hour),
}, nil
}
// Test_createInstallationToken_TokenFormats pins the contract that the
// installation token is carried through verbatim as an opaque string. GitHub is
// migrating installation tokens to a stateless "ghs_"-prefixed JWT that is much
// longer (~520 characters) and contains two dots, alongside the classic short
// opaque form. Neither is parsed, validated, or length-checked by this package,
// and this test exists to keep it that way.
//
// See https://github.blog/changelog/2026-05-15-github-app-installation-tokens-per-request-override-header/
func Test_createInstallationToken_TokenFormats(t *testing.T) {
// A stateless token: "ghs_" + three JWT segments, 520 characters total.
statelessToken := "ghs_" + strings.Repeat("a", 171) + "." + strings.Repeat("b", 171) + "." + strings.Repeat("c", 172)
tests := []struct {
name string
token string
wantLen int
wantDots int
}{
{
name: "stateless JWT format",
token: statelessToken,
wantLen: 520,
wantDots: 2,
},
{
name: "stateful opaque format",
token: "ghs_16C7e42F292c6912E7710c838347Ae178B4a",
wantLen: 40,
wantDots: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Guard the fixtures themselves so a typo cannot weaken the test.
if len(tt.token) != tt.wantLen {
t.Fatalf("fixture length = %d, want %d", len(tt.token), tt.wantLen)
}
if got := strings.Count(tt.token, "."); got != tt.wantDots {
t.Fatalf("fixture dots = %d, want %d", got, tt.wantDots)
}
expiresAt := time.Now().Add(time.Hour).UTC().Truncate(time.Second)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]any{
"token": tt.token,
"expires_at": expiresAt.Format(time.RFC3339),
})
}))
defer server.Close()
ts := NewInstallationTokenSource(42, oauth2StaticSource{accessToken: "jwt"},
WithBaseURL(server.URL),
)
tok, err := ts.Token()
if err != nil {
t.Fatalf("Token() err = %v", err)
}
if tok.AccessToken != tt.token {
t.Errorf("AccessToken = %q (len %d), want %q (len %d)",
tok.AccessToken, len(tok.AccessToken), tt.token, len(tt.token))
}
// Expiry must come from the expires_at field, never from the token
// body — a stateless token is a JWT with its own exp claim, which
// this package deliberately does not read.
if !tok.Expiry.Equal(expiresAt) {
t.Errorf("Expiry = %v, want %v", tok.Expiry, expiresAt)
}
})
}
}
// Test_createInstallationToken_403PermissionNotThrottled pins the distinction
// between a throttled 403 and a terminal permission 403.
//
// GitHub attaches X-RateLimit-Limit / X-RateLimit-Remaining / X-RateLimit-Reset
// to essentially every authenticated REST response, including terminal failures
// such as 403 {"message":"Resource not accessible by integration"}. Those carry
// a healthy X-RateLimit-Remaining and a reset epoch up to an hour out, so the
// reset header alone must never make a 403 retryable: doing so stalls the caller
// for up to maxRetrySleep and then reports ErrRateLimited for what is really a
// permissions problem.
//
// A 403 is throttled only when Retry-After is present or X-RateLimit-Remaining
// is exactly "0". 429 keeps its existing behaviour.
func Test_createInstallationToken_403PermissionNotThrottled(t *testing.T) {
// Computed once here; the server replays it milliseconds later.
futureReset := strconv.FormatInt(time.Now().Add(5*time.Second).Unix(), 10)
pastReset := strconv.FormatInt(time.Now().Add(-time.Minute).Unix(), 10)