Skip to content

Commit 8eac70f

Browse files
Fix parse token expiration (#2650)
Fixes: #2649 .
1 parent da244a4 commit 8eac70f

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

github/github.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -571,7 +571,8 @@ type Response struct {
571571
// propagate to Response.
572572
Rate Rate
573573

574-
// token's expiration date
574+
// token's expiration date. Timestamp is 0001-01-01 when token doesn't expire.
575+
// So it is valid for TokenExpiration.Equal(Timestamp{}) or TokenExpiration.Time.After(time.Now())
575576
TokenExpiration Timestamp
576577
}
577578

@@ -672,14 +673,19 @@ func parseRate(r *http.Response) Rate {
672673
}
673674

674675
// parseTokenExpiration parses the TokenExpiration related headers.
676+
// Returns 0001-01-01 if the header is not defined or could not be parsed.
675677
func parseTokenExpiration(r *http.Response) Timestamp {
676-
var exp Timestamp
677678
if v := r.Header.Get(headerTokenExpiration); v != "" {
678-
if t, err := time.Parse("2006-01-02 03:04:05 MST", v); err == nil {
679-
exp = Timestamp{t.Local()}
679+
if t, err := time.Parse("2006-01-02 15:04:05 MST", v); err == nil {
680+
return Timestamp{t.Local()}
681+
}
682+
// Some tokens include the timezone offset instead of the timezone.
683+
// https://github.com/google/go-github/issues/2649
684+
if t, err := time.Parse("2006-01-02 15:04:05 -0700", v); err == nil {
685+
return Timestamp{t.Local()}
680686
}
681687
}
682-
return exp
688+
return Timestamp{} // 0001-01-01 00:00:00
683689
}
684690

685691
type requestContext uint8

github/github_test.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2860,6 +2860,16 @@ func TestParseTokenExpiration(t *testing.T) {
28602860
header: "2021-09-03 02:34:04 UTC",
28612861
want: Timestamp{time.Date(2021, time.September, 3, 2, 34, 4, 0, time.UTC)},
28622862
},
2863+
{
2864+
header: "2021-09-03 14:34:04 UTC",
2865+
want: Timestamp{time.Date(2021, time.September, 3, 14, 34, 4, 0, time.UTC)},
2866+
},
2867+
// Some tokens include the timezone offset instead of the timezone.
2868+
// https://github.com/google/go-github/issues/2649
2869+
{
2870+
header: "2023-04-26 20:23:26 +0200",
2871+
want: Timestamp{time.Date(2023, time.April, 26, 18, 23, 26, 0, time.UTC)},
2872+
},
28632873
}
28642874

28652875
for _, tt := range tests {
@@ -2871,7 +2881,7 @@ func TestParseTokenExpiration(t *testing.T) {
28712881
res.Header.Set(headerTokenExpiration, tt.header)
28722882
exp := parseTokenExpiration(res)
28732883
if !exp.Equal(tt.want) {
2874-
t.Errorf("parseTokenExpiration returned %#v, want %#v", exp, tt.want)
2884+
t.Errorf("parseTokenExpiration of %q\nreturned %#v\n want %#v", tt.header, exp, tt.want)
28752885
}
28762886
}
28772887
}

0 commit comments

Comments
 (0)