package yaiam import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "runtime" "strings" "sync" "testing" "time" ) // provider is a fake OpenID provider: polls answers the queued token // endpoint answers to device code polls, in order; refresh the answer to // a refresh. type provider struct { t *testing.T ts *httptest.Server issuer string mu sync.Mutex polls []string // error codes, "" for the tokens refresh string // error code, "" for new tokens revoked []string forms []map[string]string userinfo string // the bearer token UserInfo accepts userBody string // what UserInfo answers, default a user verifURI string noComplete bool // no verification_uri_complete noRefresh bool // a refresh answer without a new refresh token } func newProvider(t *testing.T) *provider { p := &provider{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": p.issuer, "token_endpoint": p.ts.URL + "/token", "device_authorization_endpoint": p.ts.URL + "/device_authorization", "revocation_endpoint": p.ts.URL + "/revoke", "userinfo_endpoint": p.ts.URL + "/userinfo", }) }) mux.HandleFunc("POST /device_authorization", func(w http.ResponseWriter, r *http.Request) { p.record(r) verif := p.verifURI if verif == "" { verif = p.ts.URL + "/device" } out := map[string]any{"device_code": "the-device-code", "user_code": "BCDF-GHJK", "verification_uri": verif, "verification_uri_complete": verif + "?user_code=BCDF-GHJK", "expires_in": 600, "interval": 2} if p.noComplete { delete(out, "verification_uri_complete") } json.NewEncoder(w).Encode(out) }) mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) { form := p.record(r) p.mu.Lock() defer p.mu.Unlock() code := p.refresh if form["grant_type"] == grantDeviceCode { if len(p.polls) == 0 { t.Error("polled too often") code = "invalid_request" } else { code, p.polls = p.polls[0], p.polls[1:] } } if code != "" { w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, `{"error":%q,"error_description":"said the server"}`, code) return } n := len(p.forms) out := map[string]any{"access_token": fmt.Sprintf("access-%d", n), "token_type": "Bearer", "expires_in": 600, "refresh_token": fmt.Sprintf("refresh-%d", n), "scope": "openid offline_access"} if p.noRefresh && form["grant_type"] == "refresh_token" { delete(out, "refresh_token") } json.NewEncoder(w).Encode(out) }) mux.HandleFunc("POST /revoke", func(w http.ResponseWriter, r *http.Request) { form := p.record(r) p.mu.Lock() p.revoked = append(p.revoked, form["token_type_hint"]+":"+form["token"]) p.mu.Unlock() }) mux.HandleFunc("GET /userinfo", func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer "+p.userinfo { w.WriteHeader(http.StatusUnauthorized) return } if p.userBody != "" { fmt.Fprint(w, p.userBody) return } fmt.Fprint(w, `{"sub":"u-1","preferred_username":"alice","name":"Alice"}`) }) p.ts = httptest.NewServer(mux) t.Cleanup(p.ts.Close) p.issuer = p.ts.URL + "/t/default" return p } // record keeps a request's form. func (p *provider) record(r *http.Request) map[string]string { r.ParseForm() form := map[string]string{} for k := range r.PostForm { form[k] = r.PostForm.Get(k) } p.mu.Lock() p.forms = append(p.forms, form) p.mu.Unlock() return form } func (p *provider) client() *Client { return &Client{Issuer: p.issuer, ClientID: "cli"} } // noSleep replaces the poll wait for a test and records the waits. func noSleep(t *testing.T) *[]time.Duration { var waits []time.Duration old := sleep sleep = func(ctx context.Context, d time.Duration) error { waits = append(waits, d) return ctx.Err() } t.Cleanup(func() { sleep = old }) return &waits } func store(t *testing.T) FileStore { return FileStore{Path: filepath.Join(t.TempDir(), "state", "token.json")} } func TestLogin(t *testing.T) { p := newProvider(t) waits := noSleep(t) p.polls = []string{"authorization_pending", "slow_down", "authorization_pending", ""} s := store(t) c := p.client() var shown *DeviceAuth tok, err := c.Login(context.Background(), s, func(d *DeviceAuth) error { shown = d; return nil }) if err != nil { t.Fatal(err) } if shown.UserCode != "BCDF-GHJK" || shown.VerificationURI != p.ts.URL+"/device" || shown.VerificationURIComplete != p.ts.URL+"/device?user_code=BCDF-GHJK" || shown.Interval != 2*time.Second { t.Errorf("shown %+v", shown) } // The provider's interval, 5 s more after slow_down. if fmt.Sprint(*waits) != "[2s 2s 7s 7s]" { t.Errorf("waits = %v", *waits) } if tok.Issuer != p.issuer || tok.ClientID != "cli" || tok.AccessToken == "" || tok.RefreshToken == "" || time.Until(tok.Expiry) < 9*time.Minute { t.Errorf("token = %+v", tok) } start, poll := p.forms[0], p.forms[1] if start["client_id"] != "cli" || start["scope"] != "openid profile offline_access" { t.Errorf("device authorization form %v", start) } if poll["grant_type"] != grantDeviceCode || poll["device_code"] != "the-device-code" || poll["client_id"] != "cli" { t.Errorf("poll form %v", poll) } got, err := s.Load() if err != nil || got.AccessToken != tok.AccessToken || got.RefreshToken != tok.RefreshToken { t.Fatalf("stored %v, %v", got, err) } if runtime.GOOS != "windows" { info, _ := os.Stat(s.Path) dir, _ := os.Stat(filepath.Dir(s.Path)) if info.Mode().Perm() != 0o600 || dir.Mode().Perm() != 0o700 { t.Errorf("modes %v, %v", info.Mode(), dir.Mode()) } } // What a show error does: no polling. p.forms = nil if _, err := c.Login(context.Background(), s, func(*DeviceAuth) error { return errors.New("no terminal") }); err == nil || len(p.forms) != 1 { t.Errorf("show error: %v, %d requests", err, len(p.forms)) } } func TestWaitDeviceEnds(t *testing.T) { for _, tc := range []struct { code string want error }{ {"access_denied", ErrDenied}, {"expired_token", ErrExpired}, {"invalid_client", nil}, } { t.Run(tc.code, func(t *testing.T) { p := newProvider(t) noSleep(t) p.polls = []string{"authorization_pending", tc.code} c := p.client() d, err := c.StartDevice(context.Background()) if err != nil { t.Fatal(err) } _, err = c.WaitDevice(context.Background(), d) if tc.want != nil && !errors.Is(err, tc.want) { t.Errorf("err = %v, want %v", err, tc.want) } if tc.want == nil && !isCode(err, tc.code) { t.Errorf("err = %v, want the OAuth error %s", err, tc.code) } }) } // The code runs out here before the provider says so. p := newProvider(t) noSleep(t) c := p.client() d, _ := c.StartDevice(context.Background()) d.Expiry = time.Now().Add(time.Second) if _, err := c.WaitDevice(context.Background(), d); !errors.Is(err, ErrExpired) || len(p.forms) != 1 { t.Errorf("err = %v after %d requests", err, len(p.forms)) } // Cancelling ends the wait. ctx, cancel := context.WithCancel(context.Background()) cancel() d, _ = c.StartDevice(context.Background()) if _, err := c.WaitDevice(ctx, d); !errors.Is(err, context.Canceled) { t.Errorf("cancelled: %v", err) } } func TestToken(t *testing.T) { p := newProvider(t) c := p.client() ctx := context.Background() s := store(t) if _, err := c.Token(ctx, s); !errors.Is(err, ErrLoginRequired) { t.Errorf("no file: %v", err) } fresh := &Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now().Add(5 * time.Minute)} s.Save(fresh) if got, err := c.Token(ctx, s); err != nil || got.AccessToken != "a0" || len(p.forms) != 0 { t.Errorf("fresh token: %v, %v, %d requests", got, err, len(p.forms)) } req, _ := http.NewRequest(http.MethodGet, "https://api.example.org/", nil) if err := c.Authorize(ctx, s, req); err != nil || req.Header.Get("Authorization") != "Bearer a0" { t.Errorf("Authorize: %v, %q", err, req.Header.Get("Authorization")) } // Another issuer's or client's token is not sent here. for _, other := range []*Token{ {Issuer: "https://elsewhere.example.org", ClientID: "cli", AccessToken: "a0", Expiry: fresh.Expiry}, {Issuer: p.issuer, ClientID: "other", AccessToken: "a0", Expiry: fresh.Expiry}, } { s.Save(other) if _, err := c.Token(ctx, s); !errors.Is(err, ErrLoginRequired) { t.Errorf("token of %s/%s: %v", other.Issuer, other.ClientID, err) } } // Running out within a minute: refreshed and stored. s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now().Add(30 * time.Second)}) got, err := c.Token(ctx, s) if err != nil || got.AccessToken == "a0" || got.RefreshToken == "r0" { t.Fatalf("refresh: %v, %v", got, err) } if f := p.forms[0]; f["grant_type"] != "refresh_token" || f["refresh_token"] != "r0" || f["client_id"] != "cli" { t.Errorf("refresh form %v", f) } if stored, _ := s.Load(); stored.AccessToken != got.AccessToken || stored.RefreshToken != got.RefreshToken { t.Errorf("stored %v", stored) } // An answer without a new refresh token keeps the old one. p.noRefresh = true s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now()}) if got, err := c.Token(ctx, s); err != nil || got.RefreshToken != "r0" { t.Errorf("refresh without a new refresh token: %v, %v", got, err) } p.noRefresh = false // No refresh token: sign in again. s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", Expiry: time.Now()}) if _, err := c.Token(ctx, s); !errors.Is(err, ErrLoginRequired) { t.Errorf("without refresh token: %v", err) } // A refused refresh token: sign in again, and the file is gone. p.refresh = "invalid_grant" s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r-secret", Expiry: time.Now()}) _, err = c.Token(ctx, s) if !errors.Is(err, ErrLoginRequired) || !isCode(err, "invalid_grant") || strings.Contains(err.Error(), "r-secret") { t.Errorf("refused refresh: %v", err) } if _, err := os.Stat(s.Path); !os.IsNotExist(err) { t.Errorf("token file kept: %v", err) } // Any other failure keeps the file. p.refresh = "temporarily_unavailable" s.Save(&Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now()}) if _, err := c.Token(ctx, s); err == nil || errors.Is(err, ErrLoginRequired) { t.Errorf("server trouble: %v", err) } if t2, _ := s.Load(); t2 == nil { t.Error("token file removed on server trouble") } } func TestLogoutAndUserInfo(t *testing.T) { p := newProvider(t) c := p.client() ctx := context.Background() s := store(t) tok := &Token{Issuer: p.issuer, ClientID: "cli", AccessToken: "a0", RefreshToken: "r0", Expiry: time.Now().Add(time.Hour)} s.Save(tok) p.userinfo = "a0" u, err := c.UserInfo(ctx, tok) if err != nil || u.Subject != "u-1" || u.Username != "alice" || u.Name != "Alice" { t.Errorf("userinfo %+v, %v", u, err) } p.userBody = `{"preferred_username":"alice"}` if _, err := c.UserInfo(ctx, tok); err == nil { t.Error("userinfo without sub accepted") } p.userBody = "" p.userinfo = "other" if _, err := c.UserInfo(ctx, tok); err == nil { t.Error("userinfo with a refused token") } if err := c.Logout(ctx, s); err != nil { t.Fatal(err) } if fmt.Sprint(p.revoked) != "[refresh_token:r0 access_token:a0]" || p.forms[0]["client_id"] != "cli" { t.Errorf("revoked %v", p.revoked) } if t2, _ := s.Load(); t2 != nil { t.Error("tokens kept after logout") } if err := c.Logout(ctx, s); err != nil { t.Errorf("logout without tokens: %v", err) } // The provider cannot be reached: the tokens go anyway. s.Save(tok) p.ts.Close() gone := &Client{Issuer: p.issuer, ClientID: "cli"} if err := gone.Logout(ctx, s); err == nil { t.Error("no error without the provider") } if t2, _ := s.Load(); t2 != nil { t.Error("tokens kept when the provider is gone") } } func TestDiscoveryChecks(t *testing.T) { ctx := context.Background() p := newProvider(t) noSleep(t) // The discovery document must name exactly this issuer. wrong := &Client{Issuer: p.issuer + "/", ClientID: "cli"} if _, err := wrong.StartDevice(ctx); err == nil || !strings.Contains(err.Error(), "names the issuer") { t.Errorf("other issuer: %v", err) } for _, issuer := range []string{"http://login.example.org/t/default", "ftp://localhost/x", "/t/default", ""} { c := &Client{Issuer: issuer, ClientID: "cli"} if _, err := c.StartDevice(ctx); err == nil { t.Errorf("issuer %q accepted", issuer) } } if _, err := (&Client{Issuer: p.issuer}).StartDevice(ctx); err == nil { t.Error("no client ID accepted") } // A verification page that is not https is not shown. p.verifURI = "http://phish.example.org/device" for _, noComplete := range []bool{false, true} { p.noComplete = noComplete if _, err := p.client().StartDevice(ctx); err == nil { t.Errorf("http verification_uri accepted (without complete: %v)", noComplete) } } } // TestEndpointsNotHTTPS: endpoints of the discovery document must be https. func TestEndpointsNotHTTPS(t *testing.T) { var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(map[string]string{"issuer": ts.URL, "token_endpoint": "http://login.example.org/token", "device_authorization_endpoint": ts.URL + "/device_authorization"}) })) defer ts.Close() if _, err := (&Client{Issuer: ts.URL, ClientID: "cli"}).StartDevice(context.Background()); err == nil || !strings.Contains(err.Error(), "token_endpoint") { t.Errorf("http token endpoint: %v", err) } } // TestNoRedirects: a token request is never sent on to where an answer // points. func TestNoRedirects(t *testing.T) { var hit bool elsewhere := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hit = true })) defer elsewhere.Close() var ts *httptest.Server ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/token" { http.Redirect(w, r, elsewhere.URL+"/token", http.StatusTemporaryRedirect) return } json.NewEncoder(w).Encode(map[string]string{"issuer": ts.URL, "token_endpoint": ts.URL + "/token", "device_authorization_endpoint": ts.URL + "/device_authorization"}) })) defer ts.Close() c := &Client{Issuer: ts.URL, ClientID: "cli", HTTPClient: &http.Client{}} _, err := c.Refresh(context.Background(), &Token{RefreshToken: "r-secret"}) if err == nil || hit || strings.Contains(err.Error(), "r-secret") { t.Errorf("redirect: err %v, followed %v", err, hit) } } func TestAnswerTooLarge(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"issuer":"`)) w.Write([]byte(strings.Repeat("x", maxBody))) })) defer ts.Close() if _, err := (&Client{Issuer: ts.URL, ClientID: "cli"}).StartDevice(context.Background()); err == nil || !strings.Contains(err.Error(), "too large") { t.Errorf("large answer: %v", err) } } func TestTokenPrintsNoSecrets(t *testing.T) { tok := &Token{Issuer: "https://login.example.org", ClientID: "cli", AccessToken: "secret-access", RefreshToken: "secret-refresh"} for _, format := range []string{"%v", "%+v", "%#v", "%s"} { if out := fmt.Sprintf(format, tok); strings.Contains(out, "secret") { t.Errorf("%s prints %s", format, out) } } } func TestFileStore(t *testing.T) { s := store(t) if tok, err := s.Load(); tok != nil || err != nil { t.Errorf("no file: %v, %v", tok, err) } if err := s.Delete(); err != nil { t.Errorf("delete without file: %v", err) } s.Save(&Token{AccessToken: "a"}) if runtime.GOOS != "windows" { os.Chmod(s.Path, 0o644) if _, err := s.Load(); err == nil || !strings.Contains(err.Error(), "accessible to others") { t.Errorf("0644 file: %v", err) } os.Chmod(s.Path, 0o600) } os.WriteFile(s.Path, []byte("{"), 0o600) if _, err := s.Load(); err == nil { t.Error("broken file accepted") } // Nothing but the file is left behind. s.Save(&Token{AccessToken: "b"}) if entries, _ := os.ReadDir(filepath.Dir(s.Path)); len(entries) != 1 { t.Errorf("left behind: %v", entries) } }