oauth2_test.go 15 KB

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