oauth2_discovery_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. package oauth2
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. "testing"
  9. "time"
  10. )
  11. // ── BuildWellKnownURL ─────────────────────────────────────────────────────────
  12. func TestBuildWellKnownURL_PlainIssuer(t *testing.T) {
  13. got := BuildWellKnownURL("https://accounts.google.com")
  14. want := "https://accounts.google.com/.well-known/openid-configuration"
  15. if got != want {
  16. t.Errorf("got %q, want %q", got, want)
  17. }
  18. }
  19. func TestBuildWellKnownURL_TrailingSlash(t *testing.T) {
  20. got := BuildWellKnownURL("https://accounts.google.com/")
  21. want := "https://accounts.google.com/.well-known/openid-configuration"
  22. if got != want {
  23. t.Errorf("got %q, want %q", got, want)
  24. }
  25. }
  26. func TestBuildWellKnownURL_AlreadyHasPath(t *testing.T) {
  27. full := "https://accounts.google.com/.well-known/openid-configuration"
  28. got := BuildWellKnownURL(full)
  29. if got != full {
  30. t.Errorf("got %q, want %q (should not double-append)", got, full)
  31. }
  32. }
  33. func TestBuildWellKnownURL_PathPrefix(t *testing.T) {
  34. // Some providers have a path prefix (e.g. Keycloak, Azure)
  35. got := BuildWellKnownURL("https://login.microsoftonline.com/tenant123/v2.0")
  36. want := "https://login.microsoftonline.com/tenant123/v2.0/.well-known/openid-configuration"
  37. if got != want {
  38. t.Errorf("got %q, want %q", got, want)
  39. }
  40. }
  41. // ── FetchOIDCDiscovery ────────────────────────────────────────────────────────
  42. // minimalDiscoveryDoc returns a valid OIDC discovery JSON body for a given base URL.
  43. func minimalDiscoveryDoc(base string) []byte {
  44. doc := map[string]interface{}{
  45. "issuer": base,
  46. "authorization_endpoint": base + "/oauth2/authorize",
  47. "token_endpoint": base + "/oauth2/token",
  48. "userinfo_endpoint": base + "/oauth2/userinfo",
  49. "jwks_uri": base + "/oauth2/jwks",
  50. "scopes_supported": []string{"openid", "email", "profile"},
  51. "claims_supported": []string{"sub", "email", "name", "preferred_username"},
  52. "response_types_supported": []string{"code"},
  53. "grant_types_supported": []string{"authorization_code"},
  54. }
  55. b, _ := json.Marshal(doc)
  56. return b
  57. }
  58. func newDiscoveryServer(t *testing.T, handler http.HandlerFunc) (*httptest.Server, func()) {
  59. t.Helper()
  60. srv := httptest.NewServer(handler)
  61. return srv, srv.Close
  62. }
  63. // withMockClient temporarily replaces the package-level httpClient with one
  64. // that talks to the given server. Restored by the returned cleanup func.
  65. func withMockClient(srv *httptest.Server) func() {
  66. orig := httpClient
  67. httpClient = srv.Client()
  68. return func() { httpClient = orig }
  69. }
  70. func TestFetchOIDCDiscovery_Success(t *testing.T) {
  71. // Declare srv before the closure so the handler can reference it by the
  72. // time it is actually invoked (Go closures capture by reference).
  73. var srv *httptest.Server
  74. srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  75. if !strings.HasSuffix(r.URL.Path, "/.well-known/openid-configuration") {
  76. t.Errorf("unexpected path: %s", r.URL.Path)
  77. }
  78. w.Header().Set("Content-Type", "application/json")
  79. w.Write(minimalDiscoveryDoc(srv.URL))
  80. }))
  81. defer srv.Close()
  82. defer withMockClient(srv)()
  83. doc, err := FetchOIDCDiscovery(srv.URL)
  84. if err != nil {
  85. t.Fatalf("FetchOIDCDiscovery returned error: %v", err)
  86. }
  87. if doc.AuthorizationEndpoint == "" {
  88. t.Error("AuthorizationEndpoint is empty")
  89. }
  90. if doc.TokenEndpoint == "" {
  91. t.Error("TokenEndpoint is empty")
  92. }
  93. if doc.UserinfoEndpoint == "" {
  94. t.Error("UserinfoEndpoint is empty")
  95. }
  96. if len(doc.ScopesSupported) == 0 {
  97. t.Error("ScopesSupported is empty")
  98. }
  99. }
  100. func TestFetchOIDCDiscovery_AcceptsTrailingSlash(t *testing.T) {
  101. var srv *httptest.Server
  102. srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  103. w.Header().Set("Content-Type", "application/json")
  104. w.Write(minimalDiscoveryDoc(srv.URL))
  105. }))
  106. defer srv.Close()
  107. defer withMockClient(srv)()
  108. _, err := FetchOIDCDiscovery(srv.URL + "/")
  109. if err != nil {
  110. t.Errorf("FetchOIDCDiscovery with trailing slash returned error: %v", err)
  111. }
  112. }
  113. func TestFetchOIDCDiscovery_AcceptsFullWellKnownPath(t *testing.T) {
  114. var srv *httptest.Server
  115. srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  116. w.Header().Set("Content-Type", "application/json")
  117. w.Write(minimalDiscoveryDoc(srv.URL))
  118. }))
  119. defer srv.Close()
  120. defer withMockClient(srv)()
  121. _, err := FetchOIDCDiscovery(srv.URL + "/.well-known/openid-configuration")
  122. if err != nil {
  123. t.Errorf("FetchOIDCDiscovery with full path returned error: %v", err)
  124. }
  125. }
  126. func TestFetchOIDCDiscovery_HTTPError_404(t *testing.T) {
  127. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  128. http.NotFound(w, r)
  129. }))
  130. defer srv.Close()
  131. defer withMockClient(srv)()
  132. _, err := FetchOIDCDiscovery(srv.URL)
  133. if err == nil {
  134. t.Fatal("expected error for 404 response, got nil")
  135. }
  136. if !strings.Contains(err.Error(), "404") {
  137. t.Errorf("error should mention HTTP 404; got: %v", err)
  138. }
  139. }
  140. func TestFetchOIDCDiscovery_HTTPError_500(t *testing.T) {
  141. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  142. w.WriteHeader(http.StatusInternalServerError)
  143. }))
  144. defer srv.Close()
  145. defer withMockClient(srv)()
  146. _, err := FetchOIDCDiscovery(srv.URL)
  147. if err == nil {
  148. t.Fatal("expected error for 500 response, got nil")
  149. }
  150. }
  151. func TestFetchOIDCDiscovery_InvalidJSON(t *testing.T) {
  152. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  153. w.Header().Set("Content-Type", "application/json")
  154. w.Write([]byte("this is not json {{{"))
  155. }))
  156. defer srv.Close()
  157. defer withMockClient(srv)()
  158. _, err := FetchOIDCDiscovery(srv.URL)
  159. if err == nil {
  160. t.Fatal("expected error for invalid JSON, got nil")
  161. }
  162. if !strings.Contains(err.Error(), "parse") {
  163. t.Errorf("error should mention parse failure; got: %v", err)
  164. }
  165. }
  166. func TestFetchOIDCDiscovery_MissingAuthorizationEndpoint(t *testing.T) {
  167. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  168. doc := map[string]string{
  169. // authorization_endpoint deliberately omitted
  170. "token_endpoint": "https://example.com/token",
  171. "userinfo_endpoint": "https://example.com/userinfo",
  172. }
  173. json.NewEncoder(w).Encode(doc)
  174. }))
  175. defer srv.Close()
  176. defer withMockClient(srv)()
  177. _, err := FetchOIDCDiscovery(srv.URL)
  178. if err == nil {
  179. t.Fatal("expected error for missing authorization_endpoint, got nil")
  180. }
  181. if !strings.Contains(err.Error(), "authorization_endpoint") {
  182. t.Errorf("error should mention missing field; got: %v", err)
  183. }
  184. }
  185. func TestFetchOIDCDiscovery_MissingTokenEndpoint(t *testing.T) {
  186. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  187. doc := map[string]string{
  188. "authorization_endpoint": "https://example.com/auth",
  189. // token_endpoint deliberately omitted
  190. }
  191. json.NewEncoder(w).Encode(doc)
  192. }))
  193. defer srv.Close()
  194. defer withMockClient(srv)()
  195. _, err := FetchOIDCDiscovery(srv.URL)
  196. if err == nil {
  197. t.Fatal("expected error for missing token_endpoint, got nil")
  198. }
  199. if !strings.Contains(err.Error(), "token_endpoint") {
  200. t.Errorf("error should mention missing field; got: %v", err)
  201. }
  202. }
  203. func TestFetchOIDCDiscovery_EmptyIssuerURL(t *testing.T) {
  204. _, err := FetchOIDCDiscovery("")
  205. if err == nil {
  206. t.Fatal("expected error for empty issuer URL, got nil")
  207. }
  208. }
  209. func TestFetchOIDCDiscovery_NetworkUnreachable(t *testing.T) {
  210. // Use a client with a very short timeout so the test completes quickly.
  211. orig := httpClient
  212. httpClient = &http.Client{Timeout: 100 * time.Millisecond}
  213. defer func() { httpClient = orig }()
  214. // 192.0.2.1 is TEST-NET-1 (RFC 5737) — guaranteed to be unreachable.
  215. _, err := FetchOIDCDiscovery("http://192.0.2.1")
  216. if err == nil {
  217. t.Fatal("expected error for unreachable host, got nil")
  218. }
  219. }
  220. func TestFetchOIDCDiscovery_SetsAcceptHeader(t *testing.T) {
  221. var gotAccept string
  222. var srv *httptest.Server
  223. srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  224. gotAccept = r.Header.Get("Accept")
  225. w.Header().Set("Content-Type", "application/json")
  226. w.Write(minimalDiscoveryDoc(srv.URL))
  227. }))
  228. defer srv.Close()
  229. defer withMockClient(srv)()
  230. FetchOIDCDiscovery(srv.URL) //nolint:errcheck
  231. if !strings.Contains(gotAccept, "application/json") {
  232. t.Errorf("expected Accept: application/json, got %q", gotAccept)
  233. }
  234. }
  235. // ── getUserInfoFromEndpoint ───────────────────────────────────────────────────
  236. func newUserInfoServer(t *testing.T, accessToken string, claims map[string]interface{}) (*httptest.Server, func()) {
  237. t.Helper()
  238. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  239. auth := r.Header.Get("Authorization")
  240. if auth != "Bearer "+accessToken {
  241. w.WriteHeader(http.StatusUnauthorized)
  242. fmt.Fprintf(w, `{"error":"invalid_token","got":%q}`, auth)
  243. return
  244. }
  245. w.Header().Set("Content-Type", "application/json")
  246. json.NewEncoder(w).Encode(claims)
  247. }))
  248. return srv, srv.Close
  249. }
  250. func TestGetUserInfoFromEndpoint_Success_EmailField(t *testing.T) {
  251. srv, close := newUserInfoServer(t, "tok-abc", map[string]interface{}{
  252. "sub": "user-001",
  253. "email": "alice@example.com",
  254. "name": "Alice",
  255. })
  256. defer close()
  257. defer withMockClient(srv)()
  258. username, err := getUserInfoFromEndpoint("tok-abc", srv.URL, "email")
  259. if err != nil {
  260. t.Fatalf("unexpected error: %v", err)
  261. }
  262. if username != "alice@example.com" {
  263. t.Errorf("got %q, want %q", username, "alice@example.com")
  264. }
  265. }
  266. func TestGetUserInfoFromEndpoint_Success_PreferredUsername(t *testing.T) {
  267. srv, close := newUserInfoServer(t, "tok-xyz", map[string]interface{}{
  268. "sub": "usr123",
  269. "preferred_username": "bob",
  270. "email": "bob@corp.com",
  271. })
  272. defer close()
  273. defer withMockClient(srv)()
  274. username, err := getUserInfoFromEndpoint("tok-xyz", srv.URL, "preferred_username")
  275. if err != nil {
  276. t.Fatalf("unexpected error: %v", err)
  277. }
  278. if username != "bob" {
  279. t.Errorf("got %q, want %q", username, "bob")
  280. }
  281. }
  282. func TestGetUserInfoFromEndpoint_DefaultsToEmailField(t *testing.T) {
  283. srv, close := newUserInfoServer(t, "tok-def", map[string]interface{}{
  284. "email": "charlie@example.org",
  285. })
  286. defer close()
  287. defer withMockClient(srv)()
  288. // Pass empty usernameField --> should default to "email"
  289. username, err := getUserInfoFromEndpoint("tok-def", srv.URL, "")
  290. if err != nil {
  291. t.Fatalf("unexpected error: %v", err)
  292. }
  293. if username != "charlie@example.org" {
  294. t.Errorf("got %q, want %q", username, "charlie@example.org")
  295. }
  296. }
  297. func TestGetUserInfoFromEndpoint_BearerTokenSent(t *testing.T) {
  298. var capturedAuth string
  299. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  300. capturedAuth = r.Header.Get("Authorization")
  301. w.Header().Set("Content-Type", "application/json")
  302. json.NewEncoder(w).Encode(map[string]string{"email": "d@e.com"})
  303. }))
  304. defer srv.Close()
  305. defer withMockClient(srv)()
  306. getUserInfoFromEndpoint("my-access-token", srv.URL, "email") //nolint:errcheck
  307. if capturedAuth != "Bearer my-access-token" {
  308. t.Errorf("Authorization header: got %q, want %q", capturedAuth, "Bearer my-access-token")
  309. }
  310. }
  311. func TestGetUserInfoFromEndpoint_InvalidToken(t *testing.T) {
  312. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  313. w.WriteHeader(http.StatusUnauthorized)
  314. w.Write([]byte(`{"error":"invalid_token"}`))
  315. }))
  316. defer srv.Close()
  317. defer withMockClient(srv)()
  318. _, err := getUserInfoFromEndpoint("bad-token", srv.URL, "email")
  319. if err == nil {
  320. t.Fatal("expected error for 401 response, got nil")
  321. }
  322. if !strings.Contains(err.Error(), "401") {
  323. t.Errorf("error should mention 401; got: %v", err)
  324. }
  325. }
  326. func TestGetUserInfoFromEndpoint_ServerError(t *testing.T) {
  327. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  328. w.WriteHeader(http.StatusInternalServerError)
  329. }))
  330. defer srv.Close()
  331. defer withMockClient(srv)()
  332. _, err := getUserInfoFromEndpoint("tok", srv.URL, "email")
  333. if err == nil {
  334. t.Fatal("expected error for 500, got nil")
  335. }
  336. }
  337. func TestGetUserInfoFromEndpoint_FieldNotFound(t *testing.T) {
  338. srv, close := newUserInfoServer(t, "tok", map[string]interface{}{
  339. "sub": "123",
  340. // "email" is absent
  341. })
  342. defer close()
  343. defer withMockClient(srv)()
  344. _, err := getUserInfoFromEndpoint("tok", srv.URL, "email")
  345. if err == nil {
  346. t.Fatal("expected error for missing field, got nil")
  347. }
  348. if !strings.Contains(err.Error(), "email") {
  349. t.Errorf("error should mention missing field name; got: %v", err)
  350. }
  351. }
  352. func TestGetUserInfoFromEndpoint_FieldNotString(t *testing.T) {
  353. srv, close := newUserInfoServer(t, "tok", map[string]interface{}{
  354. "email": 12345, // not a string
  355. })
  356. defer close()
  357. defer withMockClient(srv)()
  358. _, err := getUserInfoFromEndpoint("tok", srv.URL, "email")
  359. if err == nil {
  360. t.Fatal("expected error for non-string field, got nil")
  361. }
  362. if !strings.Contains(err.Error(), "not a string") {
  363. t.Errorf("error should mention 'not a string'; got: %v", err)
  364. }
  365. }
  366. func TestGetUserInfoFromEndpoint_EmptyFieldValue(t *testing.T) {
  367. srv, close := newUserInfoServer(t, "tok", map[string]interface{}{
  368. "email": "", // empty string
  369. })
  370. defer close()
  371. defer withMockClient(srv)()
  372. _, err := getUserInfoFromEndpoint("tok", srv.URL, "email")
  373. if err == nil {
  374. t.Fatal("expected error for empty field value, got nil")
  375. }
  376. }
  377. func TestGetUserInfoFromEndpoint_EmptyURL(t *testing.T) {
  378. _, err := getUserInfoFromEndpoint("tok", "", "email")
  379. if err == nil {
  380. t.Fatal("expected error for empty URL, got nil")
  381. }
  382. }
  383. func TestGetUserInfoFromEndpoint_InvalidJSON(t *testing.T) {
  384. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  385. w.Header().Set("Content-Type", "application/json")
  386. w.Write([]byte("not-json"))
  387. }))
  388. defer srv.Close()
  389. defer withMockClient(srv)()
  390. _, err := getUserInfoFromEndpoint("tok", srv.URL, "email")
  391. if err == nil {
  392. t.Fatal("expected error for invalid JSON userinfo, got nil")
  393. }
  394. }
  395. func TestGetUserInfoFromEndpoint_NetworkFailure(t *testing.T) {
  396. orig := httpClient
  397. httpClient = &http.Client{Timeout: 50 * time.Millisecond}
  398. defer func() { httpClient = orig }()
  399. _, err := getUserInfoFromEndpoint("tok", "http://192.0.2.1/userinfo", "email")
  400. if err == nil {
  401. t.Fatal("expected error for unreachable host, got nil")
  402. }
  403. }