internal: tolerate malformed expires_in values more

Fixes golang/oauth2#239

Change-Id: Id3fdfbfb64bc1a12ab0e952e83ae444b50de1bb5
Reviewed-on: https://go-review.googlesource.com/c/161964
Reviewed-by: Ross Light <light@google.com>
Run-TryBot: Ross Light <light@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Brad Fitzpatrick 2019-02-12 00:33:33 +00:00
parent 5f6b76b7c9
commit 3e8b2be136
2 changed files with 16 additions and 8 deletions

View File

@ -78,6 +78,9 @@ func (e *tokenJSON) expiry() (t time.Time) {
type expirationTime int32 type expirationTime int32
func (e *expirationTime) UnmarshalJSON(b []byte) error { func (e *expirationTime) UnmarshalJSON(b []byte) error {
if len(b) == 0 || string(b) == "null" {
return nil
}
var n json.Number var n json.Number
err := json.Unmarshal(b, &n) err := json.Unmarshal(b, &n)
if err != nil { if err != nil {
@ -257,7 +260,7 @@ func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) {
Raw: vals, Raw: vals,
} }
e := vals.Get("expires_in") e := vals.Get("expires_in")
if e == "" { if e == "" || e == "null" {
// TODO(jbd): Facebook's OAuth2 implementation is broken and // TODO(jbd): Facebook's OAuth2 implementation is broken and
// returns expires_in field in expires. Remove the fallback to expires, // returns expires_in field in expires. Remove the fallback to expires,
// when Facebook fixes their implementation. // when Facebook fixes their implementation.

View File

@ -275,17 +275,22 @@ const day = 24 * time.Hour
func TestExchangeRequest_JSONResponse_Expiry(t *testing.T) { func TestExchangeRequest_JSONResponse_Expiry(t *testing.T) {
seconds := int32(day.Seconds()) seconds := int32(day.Seconds())
for _, c := range []struct { for _, c := range []struct {
name string
expires string expires string
want bool want bool
}{ }{
{fmt.Sprintf(`"expires_in": %d`, seconds), true}, {"normal", fmt.Sprintf(`"expires_in": %d`, seconds), true},
{fmt.Sprintf(`"expires_in": "%d"`, seconds), true}, // PayPal case {"paypal", fmt.Sprintf(`"expires_in": "%d"`, seconds), true},
{fmt.Sprintf(`"expires": %d`, seconds), true}, // Facebook case {"facebook", fmt.Sprintf(`"expires": %d`, seconds), true},
{`"expires": false`, false}, // wrong type {"issue_239", fmt.Sprintf(`"expires_in": null, "expires": %d`, seconds), true},
{`"expires": {}`, false}, // wrong type
{`"expires": "zzz"`, false}, // wrong value {"wrong_type", `"expires": false`, false},
{"wrong_type2", `"expires": {}`, false},
{"wrong_value", `"expires": "zzz"`, false},
} { } {
testExchangeRequest_JSONResponse_expiry(t, c.expires, c.want) t.Run(c.name, func(t *testing.T) {
testExchangeRequest_JSONResponse_expiry(t, c.expires, c.want)
})
} }
} }