oauth2_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright 2014 The oauth2 Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package oauth2
  5. import (
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "net/http/httptest"
  12. "reflect"
  13. "strconv"
  14. "testing"
  15. "time"
  16. "golang.org/x/net/context"
  17. )
  18. type mockTransport struct {
  19. rt func(req *http.Request) (resp *http.Response, err error)
  20. }
  21. func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  22. return t.rt(req)
  23. }
  24. type mockCache struct {
  25. token *Token
  26. readErr error
  27. }
  28. func (c *mockCache) ReadToken() (*Token, error) {
  29. return c.token, c.readErr
  30. }
  31. func (c *mockCache) WriteToken(*Token) {
  32. // do nothing
  33. }
  34. func newConf(url string) *Config {
  35. return &Config{
  36. ClientID: "CLIENT_ID",
  37. ClientSecret: "CLIENT_SECRET",
  38. RedirectURL: "REDIRECT_URL",
  39. Scopes: []string{"scope1", "scope2"},
  40. Endpoint: Endpoint{
  41. AuthURL: url + "/auth",
  42. TokenURL: url + "/token",
  43. },
  44. }
  45. }
  46. func TestAuthCodeURL(t *testing.T) {
  47. conf := newConf("server")
  48. url := conf.AuthCodeURL("foo", AccessTypeOffline, ApprovalForce)
  49. if url != "server/auth?access_type=offline&approval_prompt=force&client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=foo" {
  50. t.Errorf("Auth code URL doesn't match the expected, found: %v", url)
  51. }
  52. }
  53. func TestAuthCodeURL_CustomParam(t *testing.T) {
  54. conf := newConf("server")
  55. param := SetParam("foo", "bar")
  56. url := conf.AuthCodeURL("baz", param)
  57. if url != "server/auth?client_id=CLIENT_ID&foo=bar&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=baz" {
  58. t.Errorf("Auth code URL doesn't match the expected, found: %v", url)
  59. }
  60. }
  61. func TestAuthCodeURL_Optional(t *testing.T) {
  62. conf := &Config{
  63. ClientID: "CLIENT_ID",
  64. Endpoint: Endpoint{
  65. AuthURL: "/auth-url",
  66. TokenURL: "/token-url",
  67. },
  68. }
  69. url := conf.AuthCodeURL("")
  70. if url != "/auth-url?client_id=CLIENT_ID&response_type=code" {
  71. t.Fatalf("Auth code URL doesn't match the expected, found: %v", url)
  72. }
  73. }
  74. func TestExchangeRequest(t *testing.T) {
  75. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  76. if r.URL.String() != "/token" {
  77. t.Errorf("Unexpected exchange request URL, %v is found.", r.URL)
  78. }
  79. headerAuth := r.Header.Get("Authorization")
  80. if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" {
  81. t.Errorf("Unexpected authorization header, %v is found.", headerAuth)
  82. }
  83. headerContentType := r.Header.Get("Content-Type")
  84. if headerContentType != "application/x-www-form-urlencoded" {
  85. t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType)
  86. }
  87. body, err := ioutil.ReadAll(r.Body)
  88. if err != nil {
  89. t.Errorf("Failed reading request body: %s.", err)
  90. }
  91. if string(body) != "client_id=CLIENT_ID&code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL&scope=scope1+scope2" {
  92. t.Errorf("Unexpected exchange payload, %v is found.", string(body))
  93. }
  94. w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
  95. w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer"))
  96. }))
  97. defer ts.Close()
  98. conf := newConf(ts.URL)
  99. tok, err := conf.Exchange(NoContext, "exchange-code")
  100. if err != nil {
  101. t.Error(err)
  102. }
  103. if !tok.Valid() {
  104. t.Fatalf("Token invalid. Got: %#v", tok)
  105. }
  106. if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" {
  107. t.Errorf("Unexpected access token, %#v.", tok.AccessToken)
  108. }
  109. if tok.TokenType != "bearer" {
  110. t.Errorf("Unexpected token type, %#v.", tok.TokenType)
  111. }
  112. scope := tok.Extra("scope")
  113. if scope != "user" {
  114. t.Errorf("Unexpected value for scope: %v", scope)
  115. }
  116. }
  117. func TestExchangeRequest_JSONResponse(t *testing.T) {
  118. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  119. if r.URL.String() != "/token" {
  120. t.Errorf("Unexpected exchange request URL, %v is found.", r.URL)
  121. }
  122. headerAuth := r.Header.Get("Authorization")
  123. if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" {
  124. t.Errorf("Unexpected authorization header, %v is found.", headerAuth)
  125. }
  126. headerContentType := r.Header.Get("Content-Type")
  127. if headerContentType != "application/x-www-form-urlencoded" {
  128. t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType)
  129. }
  130. body, err := ioutil.ReadAll(r.Body)
  131. if err != nil {
  132. t.Errorf("Failed reading request body: %s.", err)
  133. }
  134. if string(body) != "client_id=CLIENT_ID&code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL&scope=scope1+scope2" {
  135. t.Errorf("Unexpected exchange payload, %v is found.", string(body))
  136. }
  137. w.Header().Set("Content-Type", "application/json")
  138. w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 86400}`))
  139. }))
  140. defer ts.Close()
  141. conf := newConf(ts.URL)
  142. tok, err := conf.Exchange(NoContext, "exchange-code")
  143. if err != nil {
  144. t.Error(err)
  145. }
  146. if !tok.Valid() {
  147. t.Fatalf("Token invalid. Got: %#v", tok)
  148. }
  149. if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" {
  150. t.Errorf("Unexpected access token, %#v.", tok.AccessToken)
  151. }
  152. if tok.TokenType != "bearer" {
  153. t.Errorf("Unexpected token type, %#v.", tok.TokenType)
  154. }
  155. scope := tok.Extra("scope")
  156. if scope != "user" {
  157. t.Errorf("Unexpected value for scope: %v", scope)
  158. }
  159. }
  160. const day = 24 * time.Hour
  161. func TestExchangeRequest_JSONResponse_Expiry(t *testing.T) {
  162. seconds := int32(day.Seconds())
  163. jsonNumberType := reflect.TypeOf(json.Number("0"))
  164. for _, c := range []struct {
  165. expires string
  166. expect error
  167. }{
  168. {fmt.Sprintf(`"expires_in": %d`, seconds), nil},
  169. {fmt.Sprintf(`"expires_in": "%d"`, seconds), nil}, // PayPal case
  170. {fmt.Sprintf(`"expires": %d`, seconds), nil}, // Facebook case
  171. {`"expires": false`, &json.UnmarshalTypeError{Value: "bool", Type: jsonNumberType}}, // wrong type
  172. {`"expires": {}`, &json.UnmarshalTypeError{Value: "object", Type: jsonNumberType}}, // wrong type
  173. {`"expires": "zzz"`, &strconv.NumError{Func: "ParseInt", Num: "zzz", Err: strconv.ErrSyntax}}, // wrong value
  174. } {
  175. testExchangeRequest_JSONResponse_expiry(t, c.expires, c.expect)
  176. }
  177. }
  178. func testExchangeRequest_JSONResponse_expiry(t *testing.T, exp string, expect error) {
  179. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  180. w.Header().Set("Content-Type", "application/json")
  181. w.Write([]byte(fmt.Sprintf(`{"access_token": "90d", "scope": "user", "token_type": "bearer", %s}`, exp)))
  182. }))
  183. defer ts.Close()
  184. conf := newConf(ts.URL)
  185. t1 := time.Now().Add(day)
  186. tok, err := conf.Exchange(NoContext, "exchange-code")
  187. t2 := time.Now().Add(day)
  188. // Do a fmt.Sprint comparison so either side can be
  189. // nil. fmt.Sprint just stringifies them to "<nil>", and no
  190. // non-nil expected error ever stringifies as "<nil>", so this
  191. // isn't terribly disgusting. We do this because Go 1.4 and
  192. // Go 1.5 return a different deep value for
  193. // json.UnmarshalTypeError. In Go 1.5, the
  194. // json.UnmarshalTypeError contains a new field with a new
  195. // non-zero value. Rather than ignore it here with reflect or
  196. // add new files and +build tags, just look at the strings.
  197. if fmt.Sprint(err) != fmt.Sprint(expect) {
  198. t.Errorf("Error = %v; want %v", err, expect)
  199. }
  200. if err != nil {
  201. return
  202. }
  203. if !tok.Valid() {
  204. t.Fatalf("Token invalid. Got: %#v", tok)
  205. }
  206. expiry := tok.Expiry
  207. if expiry.Before(t1) || expiry.After(t2) {
  208. t.Errorf("Unexpected value for Expiry: %v (shold be between %v and %v)", expiry, t1, t2)
  209. }
  210. }
  211. func TestExchangeRequest_BadResponse(t *testing.T) {
  212. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  213. w.Header().Set("Content-Type", "application/json")
  214. w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`))
  215. }))
  216. defer ts.Close()
  217. conf := newConf(ts.URL)
  218. tok, err := conf.Exchange(NoContext, "code")
  219. if err != nil {
  220. t.Fatal(err)
  221. }
  222. if tok.AccessToken != "" {
  223. t.Errorf("Unexpected access token, %#v.", tok.AccessToken)
  224. }
  225. }
  226. func TestExchangeRequest_BadResponseType(t *testing.T) {
  227. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  228. w.Header().Set("Content-Type", "application/json")
  229. w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`))
  230. }))
  231. defer ts.Close()
  232. conf := newConf(ts.URL)
  233. _, err := conf.Exchange(NoContext, "exchange-code")
  234. if err == nil {
  235. t.Error("expected error from invalid access_token type")
  236. }
  237. }
  238. func TestExchangeRequest_NonBasicAuth(t *testing.T) {
  239. tr := &mockTransport{
  240. rt: func(r *http.Request) (w *http.Response, err error) {
  241. headerAuth := r.Header.Get("Authorization")
  242. if headerAuth != "" {
  243. t.Errorf("Unexpected authorization header, %v is found.", headerAuth)
  244. }
  245. return nil, errors.New("no response")
  246. },
  247. }
  248. c := &http.Client{Transport: tr}
  249. conf := &Config{
  250. ClientID: "CLIENT_ID",
  251. Endpoint: Endpoint{
  252. AuthURL: "https://accounts.google.com/auth",
  253. TokenURL: "https://accounts.google.com/token",
  254. },
  255. }
  256. ctx := context.WithValue(context.Background(), HTTPClient, c)
  257. conf.Exchange(ctx, "code")
  258. }
  259. func TestPasswordCredentialsTokenRequest(t *testing.T) {
  260. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  261. defer r.Body.Close()
  262. expected := "/token"
  263. if r.URL.String() != expected {
  264. t.Errorf("URL = %q; want %q", r.URL, expected)
  265. }
  266. headerAuth := r.Header.Get("Authorization")
  267. expected = "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ="
  268. if headerAuth != expected {
  269. t.Errorf("Authorization header = %q; want %q", headerAuth, expected)
  270. }
  271. headerContentType := r.Header.Get("Content-Type")
  272. expected = "application/x-www-form-urlencoded"
  273. if headerContentType != expected {
  274. t.Errorf("Content-Type header = %q; want %q", headerContentType, expected)
  275. }
  276. body, err := ioutil.ReadAll(r.Body)
  277. if err != nil {
  278. t.Errorf("Failed reading request body: %s.", err)
  279. }
  280. expected = "client_id=CLIENT_ID&grant_type=password&password=password1&scope=scope1+scope2&username=user1"
  281. if string(body) != expected {
  282. t.Errorf("res.Body = %q; want %q", string(body), expected)
  283. }
  284. w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
  285. w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer"))
  286. }))
  287. defer ts.Close()
  288. conf := newConf(ts.URL)
  289. tok, err := conf.PasswordCredentialsToken(NoContext, "user1", "password1")
  290. if err != nil {
  291. t.Error(err)
  292. }
  293. if !tok.Valid() {
  294. t.Fatalf("Token invalid. Got: %#v", tok)
  295. }
  296. expected := "90d64460d14870c08c81352a05dedd3465940a7c"
  297. if tok.AccessToken != expected {
  298. t.Errorf("AccessToken = %q; want %q", tok.AccessToken, expected)
  299. }
  300. expected = "bearer"
  301. if tok.TokenType != expected {
  302. t.Errorf("TokenType = %q; want %q", tok.TokenType, expected)
  303. }
  304. }
  305. func TestTokenRefreshRequest(t *testing.T) {
  306. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  307. if r.URL.String() == "/somethingelse" {
  308. return
  309. }
  310. if r.URL.String() != "/token" {
  311. t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL)
  312. }
  313. headerContentType := r.Header.Get("Content-Type")
  314. if headerContentType != "application/x-www-form-urlencoded" {
  315. t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType)
  316. }
  317. body, _ := ioutil.ReadAll(r.Body)
  318. if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" {
  319. t.Errorf("Unexpected refresh token payload, %v is found.", string(body))
  320. }
  321. }))
  322. defer ts.Close()
  323. conf := newConf(ts.URL)
  324. c := conf.Client(NoContext, &Token{RefreshToken: "REFRESH_TOKEN"})
  325. c.Get(ts.URL + "/somethingelse")
  326. }
  327. func TestFetchWithNoRefreshToken(t *testing.T) {
  328. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  329. if r.URL.String() == "/somethingelse" {
  330. return
  331. }
  332. if r.URL.String() != "/token" {
  333. t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL)
  334. }
  335. headerContentType := r.Header.Get("Content-Type")
  336. if headerContentType != "application/x-www-form-urlencoded" {
  337. t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType)
  338. }
  339. body, _ := ioutil.ReadAll(r.Body)
  340. if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" {
  341. t.Errorf("Unexpected refresh token payload, %v is found.", string(body))
  342. }
  343. }))
  344. defer ts.Close()
  345. conf := newConf(ts.URL)
  346. c := conf.Client(NoContext, nil)
  347. _, err := c.Get(ts.URL + "/somethingelse")
  348. if err == nil {
  349. t.Errorf("Fetch should return an error if no refresh token is set")
  350. }
  351. }
  352. func TestRefreshToken_RefreshTokenReplacement(t *testing.T) {
  353. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  354. w.Header().Set("Content-Type", "application/json")
  355. w.Write([]byte(`{"access_token":"ACCESS TOKEN", "scope": "user", "token_type": "bearer", "refresh_token": "NEW REFRESH TOKEN"}`))
  356. return
  357. }))
  358. defer ts.Close()
  359. conf := newConf(ts.URL)
  360. tkr := tokenRefresher{
  361. conf: conf,
  362. ctx: NoContext,
  363. refreshToken: "OLD REFRESH TOKEN",
  364. }
  365. tk, err := tkr.Token()
  366. if err != nil {
  367. t.Errorf("Unexpected refreshToken error returned: %v", err)
  368. return
  369. }
  370. if tk.RefreshToken != tkr.refreshToken {
  371. t.Errorf("tokenRefresher.refresh_token = %s; want %s", tkr.refreshToken, tk.RefreshToken)
  372. }
  373. }
  374. func TestConfigClientWithToken(t *testing.T) {
  375. tok := &Token{
  376. AccessToken: "abc123",
  377. }
  378. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  379. if got, want := r.Header.Get("Authorization"), fmt.Sprintf("Bearer %s", tok.AccessToken); got != want {
  380. t.Errorf("Authorization header = %q; want %q", got, want)
  381. }
  382. return
  383. }))
  384. defer ts.Close()
  385. conf := newConf(ts.URL)
  386. c := conf.Client(NoContext, tok)
  387. req, err := http.NewRequest("GET", ts.URL, nil)
  388. if err != nil {
  389. t.Error(err)
  390. }
  391. _, err = c.Do(req)
  392. if err != nil {
  393. t.Error(err)
  394. }
  395. }
  396. func Test_providerAuthHeaderWorks(t *testing.T) {
  397. for _, p := range brokenAuthHeaderProviders {
  398. if providerAuthHeaderWorks(p) {
  399. t.Errorf("URL: %s not found in list", p)
  400. }
  401. p := fmt.Sprintf("%ssomesuffix", p)
  402. if providerAuthHeaderWorks(p) {
  403. t.Errorf("URL: %s not found in list", p)
  404. }
  405. }
  406. p := "https://api.not-in-the-list-example.com/"
  407. if !providerAuthHeaderWorks(p) {
  408. t.Errorf("URL: %s found in list", p)
  409. }
  410. }