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.
 
 
 

296 lines
8.9 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 jwt
  5. import (
  6. "context"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "net/http"
  11. "net/http/httptest"
  12. "strings"
  13. "testing"
  14. "golang.org/x/oauth2"
  15. "golang.org/x/oauth2/jws"
  16. )
  17. var dummyPrivateKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
  18. MIIEpAIBAAKCAQEAx4fm7dngEmOULNmAs1IGZ9Apfzh+BkaQ1dzkmbUgpcoghucE
  19. DZRnAGd2aPyB6skGMXUytWQvNYav0WTR00wFtX1ohWTfv68HGXJ8QXCpyoSKSSFY
  20. fuP9X36wBSkSX9J5DVgiuzD5VBdzUISSmapjKm+DcbRALjz6OUIPEWi1Tjl6p5RK
  21. 1w41qdbmt7E5/kGhKLDuT7+M83g4VWhgIvaAXtnhklDAggilPPa8ZJ1IFe31lNlr
  22. k4DRk38nc6sEutdf3RL7QoH7FBusI7uXV03DC6dwN1kP4GE7bjJhcRb/7jYt7CQ9
  23. /E9Exz3c0yAp0yrTg0Fwh+qxfH9dKwN52S7SBwIDAQABAoIBAQCaCs26K07WY5Jt
  24. 3a2Cw3y2gPrIgTCqX6hJs7O5ByEhXZ8nBwsWANBUe4vrGaajQHdLj5OKfsIDrOvn
  25. 2NI1MqflqeAbu/kR32q3tq8/Rl+PPiwUsW3E6Pcf1orGMSNCXxeducF2iySySzh3
  26. nSIhCG5uwJDWI7a4+9KiieFgK1pt/Iv30q1SQS8IEntTfXYwANQrfKUVMmVF9aIK
  27. 6/WZE2yd5+q3wVVIJ6jsmTzoDCX6QQkkJICIYwCkglmVy5AeTckOVwcXL0jqw5Kf
  28. 5/soZJQwLEyBoQq7Kbpa26QHq+CJONetPP8Ssy8MJJXBT+u/bSseMb3Zsr5cr43e
  29. DJOhwsThAoGBAPY6rPKl2NT/K7XfRCGm1sbWjUQyDShscwuWJ5+kD0yudnT/ZEJ1
  30. M3+KS/iOOAoHDdEDi9crRvMl0UfNa8MAcDKHflzxg2jg/QI+fTBjPP5GOX0lkZ9g
  31. z6VePoVoQw2gpPFVNPPTxKfk27tEzbaffvOLGBEih0Kb7HTINkW8rIlzAoGBAM9y
  32. 1yr+jvfS1cGFtNU+Gotoihw2eMKtIqR03Yn3n0PK1nVCDKqwdUqCypz4+ml6cxRK
  33. J8+Pfdh7D+ZJd4LEG6Y4QRDLuv5OA700tUoSHxMSNn3q9As4+T3MUyYxWKvTeu3U
  34. f2NWP9ePU0lV8ttk7YlpVRaPQmc1qwooBA/z/8AdAoGAW9x0HWqmRICWTBnpjyxx
  35. QGlW9rQ9mHEtUotIaRSJ6K/F3cxSGUEkX1a3FRnp6kPLcckC6NlqdNgNBd6rb2rA
  36. cPl/uSkZP42Als+9YMoFPU/xrrDPbUhu72EDrj3Bllnyb168jKLa4VBOccUvggxr
  37. Dm08I1hgYgdN5huzs7y6GeUCgYEAj+AZJSOJ6o1aXS6rfV3mMRve9bQ9yt8jcKXw
  38. 5HhOCEmMtaSKfnOF1Ziih34Sxsb7O2428DiX0mV/YHtBnPsAJidL0SdLWIapBzeg
  39. KHArByIRkwE6IvJvwpGMdaex1PIGhx5i/3VZL9qiq/ElT05PhIb+UXgoWMabCp84
  40. OgxDK20CgYAeaFo8BdQ7FmVX2+EEejF+8xSge6WVLtkaon8bqcn6P0O8lLypoOhd
  41. mJAYH8WU+UAy9pecUnDZj14LAGNVmYcse8HFX71MoshnvCTFEPVo4rZxIAGwMpeJ
  42. 5jgQ3slYLpqrGlcbLgUXBUgzEO684Wk/UV9DFPlHALVqCfXQ9dpJPg==
  43. -----END RSA PRIVATE KEY-----`)
  44. func TestJWTFetch_JSONResponse(t *testing.T) {
  45. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  46. w.Header().Set("Content-Type", "application/json")
  47. w.Write([]byte(`{
  48. "access_token": "90d64460d14870c08c81352a05dedd3465940a7c",
  49. "scope": "user",
  50. "token_type": "bearer",
  51. "expires_in": 3600
  52. }`))
  53. }))
  54. defer ts.Close()
  55. conf := &Config{
  56. Email: "aaa@xxx.com",
  57. PrivateKey: dummyPrivateKey,
  58. TokenURL: ts.URL,
  59. }
  60. tok, err := conf.TokenSource(context.Background()).Token()
  61. if err != nil {
  62. t.Fatal(err)
  63. }
  64. if !tok.Valid() {
  65. t.Errorf("got invalid token: %v", tok)
  66. }
  67. if got, want := tok.AccessToken, "90d64460d14870c08c81352a05dedd3465940a7c"; got != want {
  68. t.Errorf("access token = %q; want %q", got, want)
  69. }
  70. if got, want := tok.TokenType, "bearer"; got != want {
  71. t.Errorf("token type = %q; want %q", got, want)
  72. }
  73. if got := tok.Expiry.IsZero(); got {
  74. t.Errorf("token expiry = %v, want none", got)
  75. }
  76. scope := tok.Extra("scope")
  77. if got, want := scope, "user"; got != want {
  78. t.Errorf("scope = %q; want %q", got, want)
  79. }
  80. }
  81. func TestJWTFetch_BadResponse(t *testing.T) {
  82. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  83. w.Header().Set("Content-Type", "application/json")
  84. w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`))
  85. }))
  86. defer ts.Close()
  87. conf := &Config{
  88. Email: "aaa@xxx.com",
  89. PrivateKey: dummyPrivateKey,
  90. TokenURL: ts.URL,
  91. }
  92. tok, err := conf.TokenSource(context.Background()).Token()
  93. if err != nil {
  94. t.Fatal(err)
  95. }
  96. if tok == nil {
  97. t.Fatalf("got nil token; want token")
  98. }
  99. if tok.Valid() {
  100. t.Errorf("got invalid token: %v", tok)
  101. }
  102. if got, want := tok.AccessToken, ""; got != want {
  103. t.Errorf("access token = %q; want %q", got, want)
  104. }
  105. if got, want := tok.TokenType, "bearer"; got != want {
  106. t.Errorf("token type = %q; want %q", got, want)
  107. }
  108. scope := tok.Extra("scope")
  109. if got, want := scope, "user"; got != want {
  110. t.Errorf("token scope = %q; want %q", got, want)
  111. }
  112. }
  113. func TestJWTFetch_BadResponseType(t *testing.T) {
  114. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  115. w.Header().Set("Content-Type", "application/json")
  116. w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`))
  117. }))
  118. defer ts.Close()
  119. conf := &Config{
  120. Email: "aaa@xxx.com",
  121. PrivateKey: dummyPrivateKey,
  122. TokenURL: ts.URL,
  123. }
  124. tok, err := conf.TokenSource(context.Background()).Token()
  125. if err == nil {
  126. t.Error("got a token; expected error")
  127. if got, want := tok.AccessToken, ""; got != want {
  128. t.Errorf("access token = %q; want %q", got, want)
  129. }
  130. }
  131. }
  132. func TestJWTFetch_Assertion(t *testing.T) {
  133. var assertion string
  134. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  135. r.ParseForm()
  136. assertion = r.Form.Get("assertion")
  137. w.Header().Set("Content-Type", "application/json")
  138. w.Write([]byte(`{
  139. "access_token": "90d64460d14870c08c81352a05dedd3465940a7c",
  140. "scope": "user",
  141. "token_type": "bearer",
  142. "expires_in": 3600
  143. }`))
  144. }))
  145. defer ts.Close()
  146. conf := &Config{
  147. Email: "aaa@xxx.com",
  148. PrivateKey: dummyPrivateKey,
  149. PrivateKeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  150. TokenURL: ts.URL,
  151. }
  152. _, err := conf.TokenSource(context.Background()).Token()
  153. if err != nil {
  154. t.Fatalf("Failed to fetch token: %v", err)
  155. }
  156. parts := strings.Split(assertion, ".")
  157. if len(parts) != 3 {
  158. t.Fatalf("assertion = %q; want 3 parts", assertion)
  159. }
  160. gotjson, err := base64.RawURLEncoding.DecodeString(parts[0])
  161. if err != nil {
  162. t.Fatalf("invalid token header; err = %v", err)
  163. }
  164. got := jws.Header{}
  165. if err := json.Unmarshal(gotjson, &got); err != nil {
  166. t.Errorf("failed to unmarshal json token header = %q; err = %v", gotjson, err)
  167. }
  168. want := jws.Header{
  169. Algorithm: "RS256",
  170. Typ: "JWT",
  171. KeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  172. }
  173. if got != want {
  174. t.Errorf("access token header = %q; want %q", got, want)
  175. }
  176. }
  177. func TestJWTFetch_AssertionPayload(t *testing.T) {
  178. var assertion string
  179. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  180. r.ParseForm()
  181. assertion = r.Form.Get("assertion")
  182. w.Header().Set("Content-Type", "application/json")
  183. w.Write([]byte(`{
  184. "access_token": "90d64460d14870c08c81352a05dedd3465940a7c",
  185. "scope": "user",
  186. "token_type": "bearer",
  187. "expires_in": 3600
  188. }`))
  189. }))
  190. defer ts.Close()
  191. for _, conf := range []*Config{
  192. {
  193. Email: "aaa1@xxx.com",
  194. PrivateKey: dummyPrivateKey,
  195. PrivateKeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  196. TokenURL: ts.URL,
  197. },
  198. {
  199. Email: "aaa2@xxx.com",
  200. PrivateKey: dummyPrivateKey,
  201. PrivateKeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  202. TokenURL: ts.URL,
  203. Audience: "https://example.com",
  204. },
  205. } {
  206. t.Run(conf.Email, func(t *testing.T) {
  207. _, err := conf.TokenSource(context.Background()).Token()
  208. if err != nil {
  209. t.Fatalf("Failed to fetch token: %v", err)
  210. }
  211. parts := strings.Split(assertion, ".")
  212. if len(parts) != 3 {
  213. t.Fatalf("assertion = %q; want 3 parts", assertion)
  214. }
  215. gotjson, err := base64.RawURLEncoding.DecodeString(parts[1])
  216. if err != nil {
  217. t.Fatalf("invalid token payload; err = %v", err)
  218. }
  219. claimSet := jws.ClaimSet{}
  220. if err := json.Unmarshal(gotjson, &claimSet); err != nil {
  221. t.Errorf("failed to unmarshal json token payload = %q; err = %v", gotjson, err)
  222. }
  223. if got, want := claimSet.Iss, conf.Email; got != want {
  224. t.Errorf("payload email = %q; want %q", got, want)
  225. }
  226. if got, want := claimSet.Scope, strings.Join(conf.Scopes, " "); got != want {
  227. t.Errorf("payload scope = %q; want %q", got, want)
  228. }
  229. aud := conf.TokenURL
  230. if conf.Audience != "" {
  231. aud = conf.Audience
  232. }
  233. if got, want := claimSet.Aud, aud; got != want {
  234. t.Errorf("payload audience = %q; want %q", got, want)
  235. }
  236. if got, want := claimSet.Sub, conf.Subject; got != want {
  237. t.Errorf("payload subject = %q; want %q", got, want)
  238. }
  239. if got, want := claimSet.Prn, conf.Subject; got != want {
  240. t.Errorf("payload prn = %q; want %q", got, want)
  241. }
  242. })
  243. }
  244. }
  245. func TestTokenRetrieveError(t *testing.T) {
  246. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  247. w.Header().Set("Content-type", "application/json")
  248. w.WriteHeader(http.StatusBadRequest)
  249. w.Write([]byte(`{"error": "invalid_grant"}`))
  250. }))
  251. defer ts.Close()
  252. conf := &Config{
  253. Email: "aaa@xxx.com",
  254. PrivateKey: dummyPrivateKey,
  255. TokenURL: ts.URL,
  256. }
  257. _, err := conf.TokenSource(context.Background()).Token()
  258. if err == nil {
  259. t.Fatalf("got no error, expected one")
  260. }
  261. _, ok := err.(*oauth2.RetrieveError)
  262. if !ok {
  263. t.Fatalf("got %T error, expected *RetrieveError", err)
  264. }
  265. // Test error string for backwards compatibility
  266. expected := fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", "400 Bad Request", `{"error": "invalid_grant"}`)
  267. if errStr := err.Error(); errStr != expected {
  268. t.Fatalf("got %#v, expected %#v", errStr, expected)
  269. }
  270. }