package yaiam import ( "context" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "net/url" "strings" "sync" "testing" "time" ) // op is a fake OpenID provider for a web sign-in: it hands out the code // "the-code", answers the token endpoint with an ID token made by // idClaims (unsigned: nothing here checks a signature) and UserInfo with // userBody. type op struct { t *testing.T ts *httptest.Server issuer string mu sync.Mutex forms []url.Values auths []string // Authorization headers of the token requests claims func(nonce string) map[string]any userBody string nonce string // the nonce of the last authorization request // noIDToken: the token answer has none noIDToken bool } func newOP(t *testing.T) *op { o := &op{t: t} mux := http.NewServeMux() mux.HandleFunc("GET /t/default/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(map[string]string{"issuer": o.issuer, "authorization_endpoint": o.ts.URL + "/authorize", "token_endpoint": o.ts.URL + "/token", "userinfo_endpoint": o.ts.URL + "/userinfo", "end_session_endpoint": o.ts.URL + "/logout"}) }) mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) { r.ParseForm() o.mu.Lock() o.forms = append(o.forms, r.PostForm) o.auths = append(o.auths, r.Header.Get("Authorization")) claims := o.claims(o.nonce) noID := o.noIDToken o.mu.Unlock() if r.PostForm.Get("code") != "the-code" { w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, `{"error":"invalid_grant"}`) return } out := map[string]any{"access_token": "at-1", "token_type": "Bearer", "expires_in": 300, "id_token": jwt(claims), "scope": "openid profile"} if noID { delete(out, "id_token") } json.NewEncoder(w).Encode(out) }) mux.HandleFunc("GET /userinfo", func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer at-1" { w.WriteHeader(http.StatusUnauthorized) return } fmt.Fprint(w, o.userBody) }) o.ts = httptest.NewServer(mux) t.Cleanup(o.ts.Close) o.issuer = o.ts.URL + "/t/default" o.userBody = `{"sub":"u-1","preferred_username":"alice","name":"Alice","email":"alice@example.org","email_verified":true,"groups":["staff","dev"],"roles":["editor"],"attributes":{"department":"IT"}}` o.claims = func(nonce string) map[string]any { now := time.Now() return map[string]any{"iss": o.issuer, "sub": "u-1", "aud": "web", "exp": now.Add(5 * time.Minute).Unix(), "iat": now.Unix(), "nonce": nonce, "acr": "mfa", "amr": []string{"pwd", "otp"}, "auth_time": now.Unix()} } return o } // jwt is an unsigned JWT with claims. func jwt(claims map[string]any) string { raw, _ := json.Marshal(claims) return base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256"}`)) + "." + base64.RawURLEncoding.EncodeToString(raw) + ".c2ln" } func (o *op) web() *Web { return &Web{Client: Client{Issuer: o.issuer, ClientID: "web"}, ClientSecret: "s3cret", RedirectURL: "http://localhost:8097/callback", PostLogoutRedirectURL: "http://localhost:8097/"} } // start runs SignIn and returns the authorization request's parameters // and the sign-in cookie. func (o *op) start(t *testing.T, w *Web, returnTo string) (url.Values, *http.Cookie) { t.Helper() rec := httptest.NewRecorder() if err := w.SignIn(context.Background(), rec, httptest.NewRequest(http.MethodGet, "/login", nil), returnTo); err != nil { t.Fatal(err) } if rec.Code != http.StatusFound { t.Fatalf("status %d", rec.Code) } loc, _ := url.Parse(rec.Header().Get("Location")) if loc.Scheme+"://"+loc.Host+loc.Path != o.ts.URL+"/authorize" { t.Fatalf("redirect to %s", loc) } cs := rec.Result().Cookies() if len(cs) != 1 { t.Fatalf("cookies %v", cs) } q := loc.Query() o.mu.Lock() o.nonce = q.Get("nonce") o.mu.Unlock() return q, cs[0] } // callback runs Callback for the redirect back with query and cookie. func callback(w *Web, query string, cookie *http.Cookie) (*SignedIn, *httptest.ResponseRecorder, error) { req := httptest.NewRequest(http.MethodGet, "/callback?"+query, nil) if cookie != nil { req.AddCookie(cookie) } rec := httptest.NewRecorder() s, err := w.Callback(context.Background(), rec, req) return s, rec, err } // TestWebSignIn: SignIn sends the browser to the provider with state, // nonce and an S256 challenge, remembered in a short cookie; Callback // trades the code with the verifier (client_secret_basic), checks the ID // token and takes the profile, groups and roles from UserInfo. func TestWebSignIn(t *testing.T) { o := newOP(t) w := o.web() q, cookie := o.start(t, w, "/staff?x=1") if q.Get("response_type") != "code" || q.Get("client_id") != "web" || q.Get("redirect_uri") != w.RedirectURL || q.Get("scope") != "openid profile email groups roles attributes" || q.Get("code_challenge_method") != "S256" || q.Get("state") == "" || q.Get("nonce") == "" { t.Errorf("authorization request %v", q) } if !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode || cookie.Name != "yaiam_signin" || cookie.Secure || cookie.MaxAge != 600 { t.Errorf("cookie %+v", cookie) } s, rec, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}, "iss": {o.issuer}}.Encode(), cookie) if err != nil { t.Fatal(err) } if s.Subject != "u-1" || s.Username != "alice" || s.Name != "Alice" || s.Email != "alice@example.org" || !s.EmailVerified || strings.Join(s.Groups, ",") != "staff,dev" || strings.Join(s.Roles, ",") != "editor" || s.Attributes["department"] != "IT" || len(s.Attributes) != 1 || s.ACR != "mfa" || s.AuthTime.IsZero() || s.ReturnTo != "/staff?x=1" || s.Token.AccessToken != "at-1" || s.IDToken == "" { t.Errorf("signed in %+v", s) } if c := rec.Result().Cookies(); len(c) != 1 || c[0].MaxAge >= 0 { t.Errorf("the cookie was not removed: %v", c) } form := o.forms[0] sum := sha256.Sum256([]byte(form.Get("code_verifier"))) if base64.RawURLEncoding.EncodeToString(sum[:]) != q.Get("code_challenge") || form.Get("redirect_uri") != w.RedirectURL || form.Get("grant_type") != "authorization_code" || form.Has("client_secret") || form.Has("client_id") { t.Errorf("token request %v", form) } if u, p, ok := (&http.Request{Header: http.Header{"Authorization": {o.auths[0]}}}).BasicAuth(); !ok || u != "web" || p != "s3cret" { t.Errorf("client authentication %q", o.auths[0]) } for _, leak := range []string{"at-1", s.IDToken} { if strings.Contains(fmt.Sprint(s), leak) || strings.Contains(fmt.Sprintf("%#v", s), leak) { t.Error("a token in what fmt prints") } } // A public client: the client ID in the form, no Authorization. pub := o.web() pub.ClientSecret = "" q, cookie = o.start(t, pub, "") if s, _, err := callback(pub, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), cookie); err != nil || s.ReturnTo != "/" { t.Fatalf("public: %+v, %v", s, err) } if last := o.forms[len(o.forms)-1]; last.Get("client_id") != "web" || o.auths[len(o.auths)-1] != "" { t.Errorf("public token request %v %q", last, o.auths[len(o.auths)-1]) } // https: a __Host- cookie, Secure -- a name of one's own too. sec := o.web() sec.RedirectURL = "https://app.example.org/callback" if _, c := o.start(t, sec, "/"); c.Name != "__Host-yaiam_signin" || !c.Secure { t.Errorf("https cookie %+v", c) } sec.CookieName = "mine" if _, c := o.start(t, sec, "/"); c.Name != "__Host-mine" { t.Errorf("https cookie of its own name %+v", c) } // A planted cookie's return path is checked again. q, cookie = o.start(t, w, "/") raw, _ := base64.RawURLEncoding.DecodeString(cookie.Value) var v signInCookie json.Unmarshal(raw, &v) v.ReturnTo = "//evil.example" raw, _ = json.Marshal(v) cookie.Value = base64.RawURLEncoding.EncodeToString(raw) if s, _, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), cookie); err != nil || s.ReturnTo != "/" { t.Errorf("planted return path: %+v, %v", s, err) } } // TestWebCallbackRefuses: a callback without this browser's cookie, with // another state, after the cookie's time, from another issuer, with an // error of the provider, or whose ID token or UserInfo does not fit, // signs nobody in. func TestWebCallbackRefuses(t *testing.T) { o := newOP(t) w := o.web() good := o.claims try := func(name string, mod func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie), want error, claims func(string) map[string]any) { t.Helper() o.claims = good if claims != nil { o.claims = claims } q, c := o.start(t, w, "/") cb := url.Values{"code": {"the-code"}, "state": {q.Get("state")}} if mod != nil { cb, c = mod(cb, c) } s, _, err := callback(w, cb.Encode(), c) if err == nil || s != nil || want != nil && !errors.Is(err, want) { t.Errorf("%s: %+v, %v", name, s, err) } } try("no cookie", func(q url.Values, _ *http.Cookie) (url.Values, *http.Cookie) { return q, nil }, ErrSignInState, nil) try("another state", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Set("state", "x"); return q, c }, ErrSignInState, nil) try("junk cookie", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { c.Value = "!!"; return q, c }, ErrSignInState, nil) try("expired", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { raw, _ := base64.RawURLEncoding.DecodeString(c.Value) var v signInCookie json.Unmarshal(raw, &v) v.Expires = time.Now().Add(-time.Second).Unix() raw, _ = json.Marshal(v) c.Value = base64.RawURLEncoding.EncodeToString(raw) return q, c }, ErrSignInState, nil) try("other issuer", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Set("iss", "https://evil.example") return q, c }, nil, nil) try("provider error", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Del("code") q.Set("error", "access_denied") return q, c }, ErrSignInRefused, nil) try("no code", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Del("code"); return q, c }, nil, nil) try("bad code", func(q url.Values, c *http.Cookie) (url.Values, *http.Cookie) { q.Set("code", "x"); return q, c }, nil, nil) with := func(k string, v any) func(string) map[string]any { return func(n string) map[string]any { c := good(n); c[k] = v; return c } } try("issuer", nil, nil, with("iss", "https://evil.example")) try("audience", nil, nil, with("aud", "other")) try("several audiences, other azp", nil, nil, with("aud", []string{"web", "other"})) o.userBody = `{"sub":""}` try("no subject", nil, nil, with("sub", "")) o.userBody = `{"sub":"u-1"}` o.noIDToken = true try("no ID token", nil, nil, nil) o.noIDToken = false try("expired token", nil, nil, with("exp", time.Now().Add(-2*time.Minute).Unix())) try("issued in the future", nil, nil, with("iat", time.Now().Add(2*time.Minute).Unix())) try("other nonce", nil, nil, with("nonce", "x")) o.userBody = `{"sub":"u-2","preferred_username":"mallory"}` try("UserInfo of another user", nil, nil, nil) // Several audiences with azp this client: fine. o.userBody = `{"sub":"u-1"}` o.claims = func(n string) map[string]any { c := good(n) c["aud"] = []string{"web", "api"} c["azp"] = "web" return c } q, c := o.start(t, w, "/") if _, _, err := callback(w, url.Values{"code": {"the-code"}, "state": {q.Get("state")}}.Encode(), c); err != nil { t.Errorf("azp: %v", err) } } // TestWebConfig: an http redirect URL off loopback, or no openid, is // refused; a return path elsewhere becomes "/"; the logout URL carries // the hint and the post-logout redirect. func TestWebConfig(t *testing.T) { o := newOP(t) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/login", nil) bad := o.web() bad.RedirectURL = "http://app.example.org/callback" if err := bad.SignIn(context.Background(), rec, req, "/"); err == nil { t.Error("http redirect URL taken") } noOpenID := o.web() noOpenID.Scopes = []string{"profile"} if err := noOpenID.SignIn(context.Background(), rec, req, "/"); err == nil { t.Error("no openid taken") } for in, want := range map[string]string{"/a?b=c": "/a?b=c", "//evil.example": "/", "https://evil.example": "/", "/\\evil": "/", "": "/", "a": "/", "/x\r\nSet-Cookie: y": "/", "/\t/evil.example": "/", "/\t\\evil": "/", "/a\x7f": "/", "/a\\b": "/"} { if got := localPath(in); got != want { t.Errorf("localPath(%q) = %q", in, got) } } u, err := o.web().LogoutURL(context.Background(), "the-id-token") if err != nil { t.Fatal(err) } lu, _ := url.Parse(u) if !strings.HasPrefix(u, o.ts.URL+"/logout?") || lu.Query().Get("id_token_hint") != "the-id-token" || lu.Query().Get("post_logout_redirect_uri") != "http://localhost:8097/" || lu.Query().Get("client_id") != "web" { t.Errorf("logout URL %s", u) } } // TestDeviceNeedsItsEndpoint: a provider without a device authorization // endpoint serves a web sign-in, but StartDevice says it has none. func TestDeviceNeedsItsEndpoint(t *testing.T) { o := newOP(t) c := &Client{Issuer: o.issuer, ClientID: "cli"} if _, err := c.StartDevice(context.Background()); err == nil || !strings.Contains(err.Error(), "no device sign-in") { t.Errorf("start device: %v", err) } }