Skip to content

Commit

Permalink
Fix parse token expiration
Browse files Browse the repository at this point in the history
  • Loading branch information
christoph-jerolimov committed Jan 31, 2023
1 parent da244a4 commit 9bac7a5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
16 changes: 11 additions & 5 deletions github/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,8 @@ type Response struct {
// propagate to Response.
Rate Rate

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

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

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

type requestContext uint8
Expand Down
12 changes: 11 additions & 1 deletion github/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2860,6 +2860,16 @@ func TestParseTokenExpiration(t *testing.T) {
header: "2021-09-03 02:34:04 UTC",
want: Timestamp{time.Date(2021, time.September, 3, 2, 34, 4, 0, time.UTC)},
},
{
header: "2021-09-03 14:34:04 UTC",
want: Timestamp{time.Date(2021, time.September, 3, 14, 34, 4, 0, time.UTC)},
},
// Some tokens include the timezone offset instead of the timezone.
// https://github.com/google/go-github/issues/2649
{
header: "2023-04-26 20:23:26 +0200",
want: Timestamp{time.Date(2023, time.April, 26, 18, 23, 26, 0, time.UTC)},
},
}

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

0 comments on commit 9bac7a5

Please sign in to comment.