You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

506 lines
17 KiB

  1. // Copyright 2014 The Go 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. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "net/http/httptest"
  11. "net/url"
  12. "testing"
  13. "time"
  14. "golang.org/x/net/context"
  15. )
  16. type mockTransport struct {
  17. rt func(req *http.Request) (resp *http.Response, err error)
  18. }
  19. func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  20. return t.rt(req)
  21. }
  22. func newConf(url string) *Config {
  23. return &Config{
  24. ClientID: "CLIENT_ID",
  25. ClientSecret: "CLIENT_SECRET",
  26. RedirectURL: "REDIRECT_URL",
  27. Scopes: []string{"scope1", "scope2"},
  28. Endpoint: Endpoint{
  29. AuthURL: url + "/auth",
  30. TokenURL: url + "/token",
  31. },
  32. }
  33. }
  34. func TestAuthCodeURL(t *testing.T) {
  35. conf := newConf("server")
  36. url := conf.AuthCodeURL("foo", AccessTypeOffline, ApprovalForce)
  37. const want = "server/auth?access_type=offline&approval_prompt=force&client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=foo"
  38. if got := url; got != want {
  39. t.Errorf("got auth code URL = %q; want %q", got, want)
  40. }
  41. }
  42. func TestAuthCodeURL_CustomParam(t *testing.T) {
  43. conf := newConf("server")
  44. param := SetAuthURLParam("foo", "bar")
  45. url := conf.AuthCodeURL("baz", param)
  46. const want = "server/auth?client_id=CLIENT_ID&foo=bar&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=baz"
  47. if got := url; got != want {
  48. t.Errorf("got auth code = %q; want %q", got, want)
  49. }
  50. }
  51. func TestAuthCodeURL_Optional(t *testing.T) {
  52. conf := &Config{
  53. ClientID: "CLIENT_ID",
  54. Endpoint: Endpoint{
  55. AuthURL: "/auth-url",
  56. TokenURL: "/token-url",
  57. },
  58. }
  59. url := conf.AuthCodeURL("")
  60. const want = "/auth-url?client_id=CLIENT_ID&response_type=code"
  61. if got := url; got != want {
  62. t.Fatalf("got auth code = %q; want %q", got, want)
  63. }
  64. }
  65. func TestURLUnsafeClientConfig(t *testing.T) {
  66. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  67. if got, want := r.Header.Get("Authorization"), "Basic Q0xJRU5UX0lEJTNGJTNGOkNMSUVOVF9TRUNSRVQlM0YlM0Y="; got != want {
  68. t.Errorf("Authorization header = %q; want %q", got, want)
  69. }
  70. w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
  71. w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer"))
  72. }))
  73. defer ts.Close()
  74. conf := newConf(ts.URL)
  75. conf.ClientID = "CLIENT_ID??"
  76. conf.ClientSecret = "CLIENT_SECRET??"
  77. _, err := conf.Exchange(context.Background(), "exchange-code")
  78. if err != nil {
  79. t.Error(err)
  80. }
  81. }
  82. func TestExchangeRequest(t *testing.T) {
  83. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  84. if r.URL.String() != "/token" {
  85. t.Errorf("Unexpected exchange request URL, %v is found.", r.URL)
  86. }
  87. headerAuth := r.Header.Get("Authorization")
  88. if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" {
  89. t.Errorf("Unexpected authorization header, %v is found.", headerAuth)
  90. }
  91. headerContentType := r.Header.Get("Content-Type")
  92. if headerContentType != "application/x-www-form-urlencoded" {
  93. t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType)
  94. }
  95. body, err := ioutil.ReadAll(r.Body)
  96. if err != nil {
  97. t.Errorf("Failed reading request body: %s.", err)
  98. }
  99. if string(body) != "code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL" {
  100. t.Errorf("Unexpected exchange payload, %v is found.", string(body))
  101. }
  102. w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
  103. w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer"))
  104. }))
  105. defer ts.Close()
  106. conf := newConf(ts.URL)
  107. tok, err := conf.Exchange(context.Background(), "exchange-code")
  108. if err != nil {
  109. t.Error(err)
  110. }
  111. if !tok.Valid() {
  112. t.Fatalf("Token invalid. Got: %#v", tok)
  113. }
  114. if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" {
  115. t.Errorf("Unexpected access token, %#v.", tok.AccessToken)
  116. }
  117. if tok.TokenType != "bearer" {
  118. t.Errorf("Unexpected token type, %#v.", tok.TokenType)
  119. }
  120. scope := tok.Extra("scope")
  121. if scope != "user" {
  122. t.Errorf("Unexpected value for scope: %v", scope)
  123. }
  124. }
  125. func TestExchangeRequest_JSONResponse(t *testing.T) {
  126. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  127. if r.URL.String() != "/token" {
  128. t.Errorf("Unexpected exchange request URL, %v is found.", r.URL)
  129. }
  130. headerAuth := r.Header.Get("Authorization")
  131. if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" {
  132. t.Errorf("Unexpected authorization header, %v is found.", headerAuth)
  133. }
  134. headerContentType := r.Header.Get("Content-Type")
  135. if headerContentType != "application/x-www-form-urlencoded" {
  136. t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType)
  137. }
  138. body, err := ioutil.ReadAll(r.Body)
  139. if err != nil {
  140. t.Errorf("Failed reading request body: %s.", err)
  141. }
  142. if string(body) != "code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL" {
  143. t.Errorf("Unexpected exchange payload, %v is found.", string(body))
  144. }
  145. w.Header().Set("Content-Type", "application/json")
  146. w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 86400}`))
  147. }))
  148. defer ts.Close()
  149. conf := newConf(ts.URL)
  150. tok, err := conf.Exchange(context.Background(), "exchange-code")
  151. if err != nil {
  152. t.Error(err)
  153. }
  154. if !tok.Valid() {
  155. t.Fatalf("Token invalid. Got: %#v", tok)
  156. }
  157. if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" {
  158. t.Errorf("Unexpected access token, %#v.", tok.AccessToken)
  159. }
  160. if tok.TokenType != "bearer" {
  161. t.Errorf("Unexpected token type, %#v.", tok.TokenType)
  162. }
  163. scope := tok.Extra("scope")
  164. if scope != "user" {
  165. t.Errorf("Unexpected value for scope: %v", scope)
  166. }
  167. expiresIn := tok.Extra("expires_in")
  168. if expiresIn != float64(86400) {
  169. t.Errorf("Unexpected non-numeric value for expires_in: %v", expiresIn)
  170. }
  171. }
  172. func TestExtraValueRetrieval(t *testing.T) {
  173. values := url.Values{}
  174. kvmap := map[string]string{
  175. "scope": "user", "token_type": "bearer", "expires_in": "86400.92",
  176. "server_time": "1443571905.5606415", "referer_ip": "10.0.0.1",
  177. "etag": "\"afZYj912P4alikMz_P11982\"", "request_id": "86400",
  178. "untrimmed": " untrimmed ",
  179. }
  180. for key, value := range kvmap {
  181. values.Set(key, value)
  182. }
  183. tok := Token{raw: values}
  184. scope := tok.Extra("scope")
  185. if got, want := scope, "user"; got != want {
  186. t.Errorf("got scope = %q; want %q", got, want)
  187. }
  188. serverTime := tok.Extra("server_time")
  189. if got, want := serverTime, 1443571905.5606415; got != want {
  190. t.Errorf("got server_time value = %v; want %v", got, want)
  191. }
  192. refererIP := tok.Extra("referer_ip")
  193. if got, want := refererIP, "10.0.0.1"; got != want {
  194. t.Errorf("got referer_ip value = %v, want %v", got, want)
  195. }
  196. expiresIn := tok.Extra("expires_in")
  197. if got, want := expiresIn, 86400.92; got != want {
  198. t.Errorf("got expires_in value = %v, want %v", got, want)
  199. }
  200. requestID := tok.Extra("request_id")
  201. if got, want := requestID, int64(86400); got != want {
  202. t.Errorf("got request_id value = %v, want %v", got, want)
  203. }
  204. untrimmed := tok.Extra("untrimmed")
  205. if got, want := untrimmed, " untrimmed "; got != want {
  206. t.Errorf("got untrimmed = %q; want %q", got, want)
  207. }
  208. }
  209. const day = 24 * time.Hour
  210. func TestExchangeRequest_JSONResponse_Expiry(t *testing.T) {
  211. seconds := int32(day.Seconds())
  212. for _, c := range []struct {
  213. expires string
  214. want bool
  215. }{
  216. {fmt.Sprintf(`"expires_in": %d`, seconds), true},
  217. {fmt.Sprintf(`"expires_in": "%d"`, seconds), true}, // PayPal case
  218. {fmt.Sprintf(`"expires": %d`, seconds), true}, // Facebook case
  219. {`"expires": false`, false}, // wrong type
  220. {`"expires": {}`, false}, // wrong type
  221. {`"expires": "zzz"`, false}, // wrong value
  222. } {
  223. testExchangeRequest_JSONResponse_expiry(t, c.expires, c.want)
  224. }
  225. }
  226. func testExchangeRequest_JSONResponse_expiry(t *testing.T, exp string, want bool) {
  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(fmt.Sprintf(`{"access_token": "90d", "scope": "user", "token_type": "bearer", %s}`, exp)))
  230. }))
  231. defer ts.Close()
  232. conf := newConf(ts.URL)
  233. t1 := time.Now().Add(day)
  234. tok, err := conf.Exchange(context.Background(), "exchange-code")
  235. t2 := time.Now().Add(day)
  236. if got := (err == nil); got != want {
  237. if want {
  238. t.Errorf("unexpected error: got %v", err)
  239. } else {
  240. t.Errorf("unexpected success")
  241. }
  242. }
  243. if !want {
  244. return
  245. }
  246. if !tok.Valid() {
  247. t.Fatalf("Token invalid. Got: %#v", tok)
  248. }
  249. expiry := tok.Expiry
  250. if expiry.Before(t1) || expiry.After(t2) {
  251. t.Errorf("Unexpected value for Expiry: %v (shold be between %v and %v)", expiry, t1, t2)
  252. }
  253. }
  254. func TestExchangeRequest_BadResponse(t *testing.T) {
  255. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  256. w.Header().Set("Content-Type", "application/json")
  257. w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`))
  258. }))
  259. defer ts.Close()
  260. conf := newConf(ts.URL)
  261. _, err := conf.Exchange(context.Background(), "code")
  262. if err == nil {
  263. t.Error("expected error from missing access_token")
  264. }
  265. }
  266. func TestExchangeRequest_BadResponseType(t *testing.T) {
  267. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  268. w.Header().Set("Content-Type", "application/json")
  269. w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`))
  270. }))
  271. defer ts.Close()
  272. conf := newConf(ts.URL)
  273. _, err := conf.Exchange(context.Background(), "exchange-code")
  274. if err == nil {
  275. t.Error("expected error from non-string access_token")
  276. }
  277. }
  278. func TestExchangeRequest_NonBasicAuth(t *testing.T) {
  279. tr := &mockTransport{
  280. rt: func(r *http.Request) (w *http.Response, err error) {
  281. headerAuth := r.Header.Get("Authorization")
  282. if headerAuth != "" {
  283. t.Errorf("Unexpected authorization header, %v is found.", headerAuth)
  284. }
  285. return nil, errors.New("no response")
  286. },
  287. }
  288. c := &http.Client{Transport: tr}
  289. conf := &Config{
  290. ClientID: "CLIENT_ID",
  291. Endpoint: Endpoint{
  292. AuthURL: "https://accounts.google.com/auth",
  293. TokenURL: "https://accounts.google.com/token",
  294. },
  295. }
  296. ctx := context.WithValue(context.Background(), HTTPClient, c)
  297. conf.Exchange(ctx, "code")
  298. }
  299. func TestPasswordCredentialsTokenRequest(t *testing.T) {
  300. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  301. defer r.Body.Close()
  302. expected := "/token"
  303. if r.URL.String() != expected {
  304. t.Errorf("URL = %q; want %q", r.URL, expected)
  305. }
  306. headerAuth := r.Header.Get("Authorization")
  307. expected = "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ="
  308. if headerAuth != expected {
  309. t.Errorf("Authorization header = %q; want %q", headerAuth, expected)
  310. }
  311. headerContentType := r.Header.Get("Content-Type")
  312. expected = "application/x-www-form-urlencoded"
  313. if headerContentType != expected {
  314. t.Errorf("Content-Type header = %q; want %q", headerContentType, expected)
  315. }
  316. body, err := ioutil.ReadAll(r.Body)
  317. if err != nil {
  318. t.Errorf("Failed reading request body: %s.", err)
  319. }
  320. expected = "grant_type=password&password=password1&scope=scope1+scope2&username=user1"
  321. if string(body) != expected {
  322. t.Errorf("res.Body = %q; want %q", string(body), expected)
  323. }
  324. w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
  325. w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer"))
  326. }))
  327. defer ts.Close()
  328. conf := newConf(ts.URL)
  329. tok, err := conf.PasswordCredentialsToken(context.Background(), "user1", "password1")
  330. if err != nil {
  331. t.Error(err)
  332. }
  333. if !tok.Valid() {
  334. t.Fatalf("Token invalid. Got: %#v", tok)
  335. }
  336. expected := "90d64460d14870c08c81352a05dedd3465940a7c"
  337. if tok.AccessToken != expected {
  338. t.Errorf("AccessToken = %q; want %q", tok.AccessToken, expected)
  339. }
  340. expected = "bearer"
  341. if tok.TokenType != expected {
  342. t.Errorf("TokenType = %q; want %q", tok.TokenType, expected)
  343. }
  344. }
  345. func TestTokenRefreshRequest(t *testing.T) {
  346. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  347. if r.URL.String() == "/somethingelse" {
  348. return
  349. }
  350. if r.URL.String() != "/token" {
  351. t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL)
  352. }
  353. headerContentType := r.Header.Get("Content-Type")
  354. if headerContentType != "application/x-www-form-urlencoded" {
  355. t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType)
  356. }
  357. body, _ := ioutil.ReadAll(r.Body)
  358. if string(body) != "grant_type=refresh_token&refresh_token=REFRESH_TOKEN" {
  359. t.Errorf("Unexpected refresh token payload, %v is found.", string(body))
  360. }
  361. }))
  362. defer ts.Close()
  363. conf := newConf(ts.URL)
  364. c := conf.Client(context.Background(), &Token{RefreshToken: "REFRESH_TOKEN"})
  365. c.Get(ts.URL + "/somethingelse")
  366. }
  367. func TestFetchWithNoRefreshToken(t *testing.T) {
  368. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  369. if r.URL.String() == "/somethingelse" {
  370. return
  371. }
  372. if r.URL.String() != "/token" {
  373. t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL)
  374. }
  375. headerContentType := r.Header.Get("Content-Type")
  376. if headerContentType != "application/x-www-form-urlencoded" {
  377. t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType)
  378. }
  379. body, _ := ioutil.ReadAll(r.Body)
  380. if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" {
  381. t.Errorf("Unexpected refresh token payload, %v is found.", string(body))
  382. }
  383. }))
  384. defer ts.Close()
  385. conf := newConf(ts.URL)
  386. c := conf.Client(context.Background(), nil)
  387. _, err := c.Get(ts.URL + "/somethingelse")
  388. if err == nil {
  389. t.Errorf("Fetch should return an error if no refresh token is set")
  390. }
  391. }
  392. func TestTokenRetrieveError(t *testing.T) {
  393. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  394. if r.URL.String() != "/token" {
  395. t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL)
  396. }
  397. w.Header().Set("Content-type", "application/json")
  398. w.WriteHeader(http.StatusBadRequest)
  399. w.Write([]byte(`{"error": "invalid_grant"}`))
  400. }))
  401. defer ts.Close()
  402. conf := newConf(ts.URL)
  403. _, err := conf.Exchange(context.Background(), "exchange-code")
  404. if err == nil {
  405. t.Fatalf("got no error, expected one")
  406. }
  407. _, ok := err.(*RetrieveError)
  408. if !ok {
  409. t.Fatalf("got %T error, expected *RetrieveError", err)
  410. }
  411. // Test error string for backwards compatibility
  412. expected := fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", "400 Bad Request", `{"error": "invalid_grant"}`)
  413. if errStr := err.Error(); errStr != expected {
  414. t.Fatalf("got %#v, expected %#v", errStr, expected)
  415. }
  416. }
  417. func TestRefreshToken_RefreshTokenReplacement(t *testing.T) {
  418. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  419. w.Header().Set("Content-Type", "application/json")
  420. w.Write([]byte(`{"access_token":"ACCESS_TOKEN", "scope": "user", "token_type": "bearer", "refresh_token": "NEW_REFRESH_TOKEN"}`))
  421. return
  422. }))
  423. defer ts.Close()
  424. conf := newConf(ts.URL)
  425. tkr := conf.TokenSource(context.Background(), &Token{RefreshToken: "OLD_REFRESH_TOKEN"})
  426. tk, err := tkr.Token()
  427. if err != nil {
  428. t.Errorf("got err = %v; want none", err)
  429. return
  430. }
  431. if want := "NEW_REFRESH_TOKEN"; tk.RefreshToken != want {
  432. t.Errorf("RefreshToken = %q; want %q", tk.RefreshToken, want)
  433. }
  434. }
  435. func TestRefreshToken_RefreshTokenPreservation(t *testing.T) {
  436. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  437. w.Header().Set("Content-Type", "application/json")
  438. w.Write([]byte(`{"access_token":"ACCESS_TOKEN", "scope": "user", "token_type": "bearer"}`))
  439. return
  440. }))
  441. defer ts.Close()
  442. conf := newConf(ts.URL)
  443. const oldRefreshToken = "OLD_REFRESH_TOKEN"
  444. tkr := conf.TokenSource(context.Background(), &Token{RefreshToken: oldRefreshToken})
  445. tk, err := tkr.Token()
  446. if err != nil {
  447. t.Fatalf("got err = %v; want none", err)
  448. }
  449. if tk.RefreshToken != oldRefreshToken {
  450. t.Errorf("RefreshToken = %q; want %q", tk.RefreshToken, oldRefreshToken)
  451. }
  452. }
  453. func TestConfigClientWithToken(t *testing.T) {
  454. tok := &Token{
  455. AccessToken: "abc123",
  456. }
  457. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  458. if got, want := r.Header.Get("Authorization"), fmt.Sprintf("Bearer %s", tok.AccessToken); got != want {
  459. t.Errorf("Authorization header = %q; want %q", got, want)
  460. }
  461. return
  462. }))
  463. defer ts.Close()
  464. conf := newConf(ts.URL)
  465. c := conf.Client(context.Background(), tok)
  466. req, err := http.NewRequest("GET", ts.URL, nil)
  467. if err != nil {
  468. t.Error(err)
  469. }
  470. _, err = c.Do(req)
  471. if err != nil {
  472. t.Error(err)
  473. }
  474. }