diff --git a/internal/oauth/callback.go b/internal/oauth/callback.go index a022e881..d8fe2c74 100644 --- a/internal/oauth/callback.go +++ b/internal/oauth/callback.go @@ -8,6 +8,7 @@ import ( "net" "net/http" "sync" + "sync/atomic" "time" ) @@ -28,6 +29,13 @@ type callbackServer struct { redirectURI string state string once sync.Once + + // page is the server's own page for how the login went, if it has one. + page atomic.Pointer[resultPage] + // done is closed once the login has ended, after outcome is set. + done chan struct{} + outcome loginOutcome + ended sync.Once } // startCallbackServer binds the first available address in candidates (each a @@ -61,6 +69,7 @@ func startCallbackServer(candidates []redirectTarget, state string) (*callbackSe results: make(chan callbackResult, 1), redirectURI: target.uri(), state: state, + done: make(chan struct{}), } mux := http.NewServeMux() @@ -106,20 +115,63 @@ func (c *callbackServer) handle(w http.ResponseWriter, r *http.Request) { if description != "" { message = fmt.Sprintf("%s: %s", errCode, description) } - c.writePage(w, http.StatusOK, "Login failed", message) + outcome := loginOutcome{result: resultFailed, reason: reasonRefused} + if errCode == "access_denied" { + outcome = loginOutcome{result: resultDenied} + } + c.answer(w, r, outcome, http.StatusOK, "Login failed", message) c.deliver(callbackResult{err: fmt.Errorf("authorization denied (%s)", message)}) return } code := query.Get("code") if code == "" { - c.writePage(w, http.StatusBadRequest, "Login failed", "The login response contained no authorization code.") + c.answer(w, r, loginOutcome{result: resultFailed, reason: reasonRefused}, http.StatusBadRequest, "Login failed", "The login response contained no authorization code.") c.deliver(callbackResult{err: fmt.Errorf("authorization response contained no code")}) return } - c.writePage(w, http.StatusOK, "Signed in", "You can close this tab and return to your terminal.") c.deliver(callbackResult{code: code}) + + // Nobody is signed in until the code is exchanged and the session stored, + // so the browser is not told before. + select { + case <-c.done: + case <-r.Context().Done(): + return + } + if c.outcome.result == resultAuthorized { + c.answer(w, r, c.outcome, http.StatusOK, "Signed in", "You can close this tab and return to your terminal.") + } else { + c.answer(w, r, c.outcome, http.StatusOK, "Login failed", "Return to your terminal to see why.") + } +} + +// ShowResultOn has the browser sent to page, when there is one, instead of +// being shown one from here. +func (c *callbackServer) ShowResultOn(page *resultPage) { c.page.Store(page) } + +// Finish ends the login for the browser, which waits to be told how it went. +// Only the first call counts. +func (c *callbackServer) Finish(outcome loginOutcome) { + c.ended.Do(func() { + c.outcome = outcome + close(c.done) + }) +} + +// answer tells the browser how the login went: on the server's own page, or +// else with the heading and message here. +func (c *callbackServer) answer(w http.ResponseWriter, r *http.Request, outcome loginOutcome, status int, heading, message string) { + location := c.page.Load().address(outcome) + if location == "" { + c.writePage(w, status, heading, message) + return + } + // This address holds the authorization code. + w.Header().Set("Referrer-Policy", "no-referrer") + w.Header().Set("Cache-Control", "no-store") + http.Redirect(w, r, location, http.StatusFound) } // deliver sends the first result and ignores any later ones, so a reloaded @@ -140,8 +192,9 @@ func (c *callbackServer) Wait(ctx context.Context) (string, error) { } // Close shuts the server down, allowing in-flight responses a moment to reach -// the browser. +// the browser. One still waiting for the login to end is told that it failed. func (c *callbackServer) Close() { + c.Finish(loginOutcome{result: resultFailed}) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() _ = c.server.Shutdown(ctx) diff --git a/internal/oauth/login_test.go b/internal/oauth/login_test.go index 33ca160a..aceafa81 100644 --- a/internal/oauth/login_test.go +++ b/internal/oauth/login_test.go @@ -34,6 +34,8 @@ type fakeAuthServer struct { accessTokenTTL int64 rotateRefresh bool promptValues []string // advertised as prompt_values_supported + resultURI string // advertised as authorization_result_uri + refuseCodes bool } type pendingCode struct { @@ -79,6 +81,7 @@ func (f *fakeAuthServer) handleDiscovery(w http.ResponseWriter, r *http.Request) ResponseTypesSupported: []string{"code"}, CodeChallengeMethodsSupported: []string{"S256"}, PromptValuesSupported: promptValues, + AuthorizationResultURI: f.resultURI, }) } @@ -155,7 +158,7 @@ func (f *fakeAuthServer) handleToken(w http.ResponseWriter, r *http.Request) { switch r.PostForm.Get("grant_type") { case "authorization_code": pending, ok := f.codes[r.PostForm.Get("code")] - if !ok { + if !ok || f.refuseCodes { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_grant"}) return } diff --git a/internal/oauth/metadata.go b/internal/oauth/metadata.go index efcaf562..d97f1c67 100644 --- a/internal/oauth/metadata.go +++ b/internal/oauth/metadata.go @@ -25,6 +25,9 @@ type Metadata struct { // endpoint accepts (OpenID Connect Prompt Create 1.0). Signup needs // "create" here. PromptValuesSupported []string `json:"prompt_values_supported"` + // AuthorizationResultURI is the server's own page for how a login went + // (not part of RFC 8414). Empty leaves the CLI to show its own. + AuthorizationResultURI string `json:"authorization_result_uri,omitempty"` } // fallbackMetadata mirrors the published document at diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index cd846fcf..fde4c4e2 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -110,7 +110,7 @@ func parseRedirectTarget(raw string) (redirectTarget, error) { return redirectTarget{}, fmt.Errorf("redirect URI %q is not a loopback http URI", raw) } host := u.Hostname() - if host != "127.0.0.1" && host != "localhost" && host != "::1" { + if !isLoopbackHost(host) { return redirectTarget{}, fmt.Errorf("redirect URI %q is not a loopback address", raw) } port, err := strconv.Atoi(u.Port()) @@ -124,6 +124,10 @@ func parseRedirectTarget(raw string) (redirectTarget, error) { return redirectTarget{Host: host, Port: port, Path: path}, nil } +func isLoopbackHost(host string) bool { + return host == "127.0.0.1" || host == "localhost" || host == "::1" +} + // settings resolves the issuer, resource, and any pre-registered client from // the environment. type settings struct { @@ -247,6 +251,7 @@ func Login(ctx context.Context, getenv func(string) string, opts LoginOptions) ( return nil, err } defer callback.Close() + callback.ShowResultOn(newResultPage(md, client.ClientID, getenv, opts.OnAuthURL != nil)) scopes := opts.Scopes if len(scopes) == 0 { @@ -299,7 +304,15 @@ func Login(ctx context.Context, getenv func(string) string, opts LoginOptions) ( return nil, err } - tok, err := exchangeCode(ctx, httpClient, md, client.ClientID, code, verifier.verifier, callback.RedirectURI(), cfg.Resource) + session, err := completeLogin(ctx, md, cfg, client.ClientID, code, verifier.verifier, callback.RedirectURI(), scopes) + // The browser is still waiting: the page it gets says how this went. + callback.Finish(outcomeOf(err)) + return session, err +} + +// completeLogin exchanges the authorization code and stores the session. +func completeLogin(ctx context.Context, md Metadata, cfg settings, clientID, code, verifier, redirectURI string, scopes []string) (*Session, error) { + tok, err := exchangeCode(ctx, httpClient, md, clientID, code, verifier, redirectURI, cfg.Resource) if err != nil { return nil, fmt.Errorf("exchange authorization code: %w", err) } @@ -308,7 +321,7 @@ func Login(ctx context.Context, getenv func(string) string, opts LoginOptions) ( session := &Session{ Issuer: md.Issuer, TokenEndpoint: md.TokenEndpoint, - ClientID: client.ClientID, + ClientID: clientID, Resource: cfg.Resource, Scope: firstNonEmpty(tok.Scope, strings.Join(scopes, " ")), TokenType: firstNonEmpty(tok.TokenType, "Bearer"), diff --git a/internal/oauth/resultpage.go b/internal/oauth/resultpage.go new file mode 100644 index 00000000..0623e407 --- /dev/null +++ b/internal/oauth/resultpage.go @@ -0,0 +1,133 @@ +// This file is not generated by Speakeasy — it is where 'vf auth login' sends +// the browser once it knows how sign-in went. +// +// The authorization server may host a page for that, named by +// authorization_result_uri in its metadata. It is told which of a few things +// happened and never words, names or links: the client's name and icon come +// from its registration. A server without one leaves the CLI to show its own +// page. + +package oauth + +import ( + "errors" + "net/url" +) + +// The outcomes the hosted page knows. +const ( + resultAuthorized = "authorized" + resultDenied = "denied" + resultFailed = "failed" +) + +// The reasons it gives for resultFailed. +const ( + reasonRefused = "refused" + reasonUnreachable = "unreachable" + reasonNotSaved = "not_saved" +) + +// What the person does next. +const ( + nextContinue = "continue" // go back to the command, which carries on + nextClose = "close" // nothing: an agent is waiting on the command +) + +// loginOutcome is how a login went, as far as the browser is told. +type loginOutcome struct { + result string + reason string +} + +// outcomeOf is how a login that got its authorization code went. +func outcomeOf(err error) loginOutcome { + var tokErr *tokenError + switch { + case err == nil: + return loginOutcome{result: resultAuthorized} + case errors.Is(err, ErrStoreSession): + return loginOutcome{result: resultFailed, reason: reasonNotSaved} + case errors.As(err, &tokErr): + return loginOutcome{result: resultFailed, reason: reasonRefused} + default: + return loginOutcome{result: resultFailed, reason: reasonUnreachable} + } +} + +// resultPage is the hosted page for one login. +type resultPage struct { + uri *url.URL + clientID string + place string + next string + returnTo string +} + +// newResultPage returns the hosted page for a login, or nil when the server +// has none, or not one to send a browser to. +func newResultPage(md Metadata, clientID string, getenv func(string) string, agentMode bool) *resultPage { + uri, err := url.Parse(md.AuthorizationResultURI) + if err != nil || uri.Host == "" { + return nil + } + if uri.Scheme != "https" && (uri.Scheme != "http" || !isLoopbackHost(uri.Hostname())) { + return nil + } + + page := &resultPage{uri: uri, clientID: clientID, next: nextContinue, returnTo: appHere(getenv)} + if agentMode { + page.next = nextClose + } + // Over SSH the browser is on another computer than the one signed in. + if getenv("SSH_CONNECTION") == "" { + page.place = "this_computer" + } + return page +} + +// address is where the page says how the login went. A nil page has none. +func (p *resultPage) address(outcome loginOutcome) string { + if p == nil { + return "" + } + + returnTo := p.returnTo + if returnTo == "" && outcome.result == resultAuthorized { + returnTo = "voiceflow" + } + + uri := *p.uri + query := uri.Query() + for _, param := range [][2]string{ + {"client_id", p.clientID}, + {"result", outcome.result}, + {"reason", outcome.reason}, + {"place", p.place}, + {"next", p.next}, + {"return_to", returnTo}, + } { + if param[1] != "" { + query.Set(param[0], param[1]) + } + } + uri.RawQuery = query.Encode() + return uri.String() +} + +// appHere names the app the command runs in, when the hosted page has a link +// that brings it back to the front. +func appHere(getenv func(string) string) string { + switch { + case getenv("CLAUDE_CODE_ENTRYPOINT") == "claude-desktop": + return "claude" + case getenv("SSH_CONNECTION") != "": + return "" // an editor's link opens it on the browser's computer + case getenv("CURSOR_TRACE_ID") != "": + return "cursor" + case getenv("__CFBundleIdentifier") == "com.microsoft.VSCode": + return "vscode" + default: + return "" + } +} diff --git a/internal/oauth/resultpage_test.go b/internal/oauth/resultpage_test.go new file mode 100644 index 00000000..772d7fdb --- /dev/null +++ b/internal/oauth/resultpage_test.go @@ -0,0 +1,406 @@ +package oauth + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "path/filepath" + "strings" + "testing" + "time" +) + +const testResultURI = "https://creator.test/oauth2/result" + +func TestResultPageAddress(t *testing.T) { + authorized := loginOutcome{result: resultAuthorized} + denied := loginOutcome{result: resultDenied} + + tests := []struct { + name string + env map[string]string + agentMode bool + outcome loginOutcome + want string + }{ + { + name: "at a terminal", + outcome: authorized, + want: "client_id=client-1&next=continue&place=this_computer&result=authorized&return_to=voiceflow", + }, + { + name: "for an agent", + agentMode: true, + outcome: authorized, + want: "client_id=client-1&next=close&place=this_computer&result=authorized&return_to=voiceflow", + }, + { + name: "a no has nowhere else to go", + outcome: denied, + want: "client_id=client-1&next=continue&place=this_computer&result=denied", + }, + { + name: "a failure says why", + outcome: loginOutcome{result: resultFailed, reason: reasonNotSaved}, + want: "client_id=client-1&next=continue&place=this_computer&reason=not_saved&result=failed", + }, + { + name: "in Claude", + env: map[string]string{"CLAUDE_CODE_ENTRYPOINT": "claude-desktop"}, + outcome: denied, + want: "client_id=client-1&next=continue&place=this_computer&result=denied&return_to=claude", + }, + { + name: "in Claude Code at a terminal", + env: map[string]string{"CLAUDE_CODE_ENTRYPOINT": "cli"}, + outcome: denied, + want: "client_id=client-1&next=continue&place=this_computer&result=denied", + }, + { + name: "in Cursor", + env: map[string]string{"CURSOR_TRACE_ID": "trace", "__CFBundleIdentifier": "com.microsoft.VSCode"}, + outcome: authorized, + want: "client_id=client-1&next=continue&place=this_computer&result=authorized&return_to=cursor", + }, + { + name: "in VS Code", + env: map[string]string{"__CFBundleIdentifier": "com.microsoft.VSCode"}, + outcome: authorized, + want: "client_id=client-1&next=continue&place=this_computer&result=authorized&return_to=vscode", + }, + { + name: "over SSH", + env: map[string]string{"SSH_CONNECTION": "10.0.0.1 1 10.0.0.2 22", "CURSOR_TRACE_ID": "trace"}, + outcome: authorized, + want: "client_id=client-1&next=continue&result=authorized&return_to=voiceflow", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + page := newResultPage(Metadata{AuthorizationResultURI: testResultURI}, "client-1", envFunc(test.env), test.agentMode) + if got, want := page.address(test.outcome), testResultURI+"?"+test.want; got != want { + t.Errorf("address = %s, want %s", got, want) + } + }) + } +} + +func TestResultPageKeepsTheQueryOfItsAddress(t *testing.T) { + page := newResultPage(Metadata{AuthorizationResultURI: testResultURI + "?region=eu"}, "client-1", envFunc(nil), false) + + for _, outcome := range []loginOutcome{{result: resultFailed, reason: reasonRefused}, {result: resultDenied}} { + address, err := url.Parse(page.address(outcome)) + if err != nil { + t.Fatalf("parse address: %v", err) + } + got := address.Query() + if got.Get("region") != "eu" || got.Get("result") != outcome.result || got.Get("reason") != outcome.reason { + t.Errorf("query = %v, want the server's own and %v alone", got, outcome) + } + } +} + +func TestNewResultPageOnlyTakesAPageToSendABrowserTo(t *testing.T) { + for address, want := range map[string]bool{ + testResultURI: true, + "http://127.0.0.1:3000/oauth2/result": true, + "http://localhost:3000/oauth2/result": true, + "http://[::1]:3000/oauth2/result": true, + "http://creator.test/oauth2/result": false, + "javascript:alert(1)": false, + "cursor://anysphere.cursor-mcp/x": false, + "file:///etc/hosts": false, + "//creator.test/oauth2/result": false, + "/oauth2/result": false, + "https://": false, + "": false, + } { + page := newResultPage(Metadata{AuthorizationResultURI: address}, "client-1", envFunc(nil), false) + if got := page != nil; got != want { + t.Errorf("%q taken = %v, want %v", address, got, want) + } + } +} + +func TestOutcomeOf(t *testing.T) { + for want, err := range map[loginOutcome]error{ + {result: resultAuthorized}: nil, + {result: resultFailed, reason: reasonRefused}: fmt.Errorf("exchange: %w", &tokenError{Code: "invalid_grant"}), + {result: resultFailed, reason: reasonNotSaved}: fmt.Errorf("%w: %w", ErrStoreSession, errors.New("disk full")), + {result: resultFailed, reason: reasonUnreachable}: context.DeadlineExceeded, + } { + if got := outcomeOf(err); got != want { + t.Errorf("outcomeOf(%v) = %v, want %v", err, got, want) + } + } +} + +// browserAnswer is what the browser got, without being sent on. +type browserAnswer struct { + status int + location string + header http.Header + body string +} + +func visit(rawURL string) (browserAnswer, error) { + client := &http.Client{ + Timeout: 10 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + resp, err := client.Get(rawURL) + if err != nil { + return browserAnswer{}, err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + return browserAnswer{ + status: resp.StatusCode, + location: resp.Header.Get("Location"), + header: resp.Header, + body: string(body), + }, err +} + +func mustVisit(t *testing.T, rawURL string) browserAnswer { + t.Helper() + answer, err := visit(rawURL) + if err != nil { + t.Fatalf("GET %s: %v", rawURL, err) + } + return answer +} + +func startTestCallbackWithResultPage(t *testing.T, state string) *callbackServer { + t.Helper() + cb := startTestCallback(t, state) + cb.ShowResultOn(newResultPage(Metadata{AuthorizationResultURI: testResultURI}, "client-1", envFunc(nil), false)) + return cb +} + +func TestCallbackServerAnswersOnceTheLoginHasEnded(t *testing.T) { + cb := startTestCallbackWithResultPage(t, "the-state") + address := cb.RedirectURI() + "?code=the-code&state=the-state" + + // A second tab, or a reload, is told the same. + answers := make(chan browserAnswer, 2) + for range 2 { + go func() { + answer, _ := visit(address) + answers <- answer + }() + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := cb.Wait(ctx); err != nil { + t.Fatalf("Wait: %v", err) + } + select { + case answer := <-answers: + t.Fatalf("the browser was answered before the login ended: %+v", answer) + case <-time.After(100 * time.Millisecond): + } + + cb.Finish(loginOutcome{result: resultAuthorized}) + cb.Finish(loginOutcome{result: resultFailed}) + + for range 2 { + answer := <-answers + if answer.status != http.StatusFound || !strings.HasPrefix(answer.location, testResultURI+"?") || !strings.Contains(answer.location, "result=authorized") { + t.Errorf("answer = %d %s, want a redirect to the page that says authorized", answer.status, answer.location) + } + if strings.Contains(answer.location, "the-code") || strings.Contains(answer.location, "the-state") { + t.Errorf("location = %s, want neither the code nor the state in it", answer.location) + } + if answer.header.Get("Referrer-Policy") != "no-referrer" || answer.header.Get("Cache-Control") != "no-store" { + t.Errorf("headers = %v, want the address kept to this browser", answer.header) + } + } +} + +func TestCallbackServerSendsARefusalToTheResultPage(t *testing.T) { + for query, want := range map[string]string{ + "error=access_denied&error_description=user+said+no": "result=denied", + "error=server_error": "reason=refused&result=failed", + "": "reason=refused&result=failed", + } { + cb := startTestCallbackWithResultPage(t, "the-state") + answer := mustVisit(t, cb.RedirectURI()+"?state=the-state&"+query) + if answer.status != http.StatusFound || !strings.Contains(answer.location, want) { + t.Errorf("%q: answer = %d %s, want a redirect with %s", query, answer.status, answer.location, want) + } + if strings.Contains(answer.location, "said") { + t.Errorf("%q: location = %s, want none of the server's words in it", query, answer.location) + } + } +} + +func TestCallbackServerKeepsAStateMismatchOffTheResultPage(t *testing.T) { + cb := startTestCallbackWithResultPage(t, "the-state") + + answer := mustVisit(t, cb.RedirectURI()+"?code=the-code&state=forged") + if answer.status != http.StatusBadRequest || answer.location != "" { + t.Errorf("answer = %d %q, want it refused here", answer.status, answer.location) + } +} + +func TestCallbackServerCloseAnswersABrowserThatWaits(t *testing.T) { + cb := startTestCallback(t, "the-state") + + answers := make(chan browserAnswer, 1) + go func() { + answer, _ := visit(cb.RedirectURI() + "?code=the-code&state=the-state") + answers <- answer + }() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := cb.Wait(ctx); err != nil { + t.Fatalf("Wait: %v", err) + } + cb.Close() + + select { + case answer := <-answers: + if !strings.Contains(answer.body, "Login failed") { + t.Errorf("body = %s, want the login that never ended to have failed", answer.body) + } + case <-time.After(time.Second): + t.Fatal("the browser was left waiting") + } +} + +// useVisitingBrowser makes the "browser" go through the sign-in and keeps the +// answer it ends on, with what visited saw when it got there. +func useVisitingBrowser(t *testing.T, onAnswer func()) <-chan browserAnswer { + t.Helper() + answers := make(chan browserAnswer, 1) + orig := browserOpener + browserOpener = func(rawURL string) error { + go func() { + consent, err := visit(rawURL) + if err != nil { + return + } + answer, err := visit(consent.location) + if err != nil { + return + } + onAnswer() + answers <- answer + }() + return nil + } + t.Cleanup(func() { browserOpener = orig }) + return answers +} + +func TestLoginSendsTheBrowserOnOnceTheSessionIsStored(t *testing.T) { + _, ring := useTestStore(t, true) + useTestHTTPClient(t) + server := newFakeAuthServer(t) + server.resultURI = testResultURI + + var stored string + answers := useVisitingBrowser(t, func() { stored = ring.get(keyringAccessToken) }) + + session, err := Login(context.Background(), testEnv(server), LoginOptions{Timeout: 15 * time.Second}) + if err != nil { + t.Fatalf("Login: %v", err) + } + + answer := <-answers + want := fmt.Sprintf("%s?client_id=%s&next=continue&place=this_computer&result=authorized&return_to=voiceflow", testResultURI, session.ClientID) + if answer.location != want { + t.Errorf("location = %s, want %s", answer.location, want) + } + if stored != session.AccessToken { + t.Errorf("stored token when the browser was told = %q, want %q", stored, session.AccessToken) + } +} + +func TestLoginTellsTheResultPageAnAgentWaits(t *testing.T) { + useTestStore(t, true) + useTestHTTPClient(t) + server := newFakeAuthServer(t) + server.resultURI = testResultURI + answers := useVisitingBrowser(t, func() {}) + + if _, err := Login(context.Background(), testEnv(server), LoginOptions{Timeout: 15 * time.Second, OnAuthURL: func(string) {}}); err != nil { + t.Fatalf("Login: %v", err) + } + if answer := <-answers; !strings.Contains(answer.location, "next=close") { + t.Errorf("location = %s, want nothing left to do", answer.location) + } +} + +func TestLoginTellsTheBrowserItFailed(t *testing.T) { + tests := []struct { + name string + resultURI string + fail func(t *testing.T, server *fakeAuthServer, dir string) + want string + }{ + { + name: "the code is refused", + resultURI: testResultURI, + fail: func(_ *testing.T, server *fakeAuthServer, _ string) { server.refuseCodes = true }, + want: "reason=refused&result=failed", + }, + { + name: "the session can't be stored", + resultURI: testResultURI, + fail: func(_ *testing.T, _ *fakeAuthServer, dir string) { + storeDir = func() (string, error) { return filepath.Join(dir, "missing", "\x00"), nil } + }, + want: "reason=not_saved&result=failed", + }, + { + name: "the server has no page", + fail: func(_ *testing.T, server *fakeAuthServer, _ string) { server.refuseCodes = true }, + want: "Login failed", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + dir, _ := useTestStore(t, true) + useTestHTTPClient(t) + server := newFakeAuthServer(t) + server.resultURI = test.resultURI + answers := useVisitingBrowser(t, func() {}) + + _, err := Login(context.Background(), testEnv(server), LoginOptions{ + Timeout: 15 * time.Second, + observeAuthURL: func(string) { test.fail(t, server, dir) }, + }) + if err == nil { + t.Fatal("Login succeeded") + } + + answer := <-answers + if got := answer.location + answer.body; !strings.Contains(got, test.want) || strings.Contains(got, "Signed in") { + t.Errorf("answer = %s, want %s", got, test.want) + } + }) + } +} + +func TestLoginShowsItsOwnPageWithoutAResultPage(t *testing.T) { + useTestStore(t, true) + useTestHTTPClient(t) + server := newFakeAuthServer(t) + answers := useVisitingBrowser(t, func() {}) + + if _, err := Login(context.Background(), testEnv(server), LoginOptions{Timeout: 15 * time.Second}); err != nil { + t.Fatalf("Login: %v", err) + } + if answer := <-answers; answer.status != http.StatusOK || !strings.Contains(answer.body, "Signed in") { + t.Errorf("answer = %d %s, want the page here", answer.status, answer.body) + } +}