Skip to content

Commit acbbdd6

Browse files
authored
Respect context when writing to LocalServerReadyChan (#50)
1 parent 5205b86 commit acbbdd6

File tree

2 files changed

+51
-5
lines changed

2 files changed

+51
-5
lines changed

e2e_test/context_test.go

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313
"golang.org/x/oauth2"
1414
)
1515

16-
func TestContextCancel(t *testing.T) {
16+
func TestContextCancelOnWaitingForBrowser(t *testing.T) {
1717
ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
1818
defer cancel()
1919
s := httptest.NewServer(&authserver.Handler{
@@ -47,3 +47,41 @@ func TestContextCancel(t *testing.T) {
4747
t.Errorf("err wants DeadlineExceeded but %+v", err)
4848
}
4949
}
50+
51+
func TestContextCancelOnLocalServerReadyChan(t *testing.T) {
52+
ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
53+
defer cancel()
54+
openBrowserCh := make(chan string)
55+
defer close(openBrowserCh)
56+
s := httptest.NewServer(&authserver.Handler{
57+
T: t,
58+
NewAuthorizationResponse: func(r authserver.AuthorizationRequest) string {
59+
return fmt.Sprintf("%s?error=server_error", r.RedirectURI)
60+
},
61+
NewTokenResponse: func(r authserver.TokenRequest) (int, string) {
62+
return 500, "should not reach here"
63+
},
64+
})
65+
defer s.Close()
66+
cfg := oauth2cli.Config{
67+
OAuth2Config: oauth2.Config{
68+
ClientID: "YOUR_CLIENT_ID",
69+
ClientSecret: "YOUR_CLIENT_SECRET",
70+
Scopes: []string{"email", "profile"},
71+
Endpoint: oauth2.Endpoint{
72+
AuthURL: s.URL + "/auth",
73+
TokenURL: s.URL + "/token",
74+
},
75+
},
76+
LocalServerReadyChan: openBrowserCh,
77+
Logf: t.Logf,
78+
}
79+
_, err := oauth2cli.GetToken(ctx, cfg)
80+
if err == nil {
81+
t.Errorf("GetToken wants error but was nil")
82+
return
83+
}
84+
if !errors.Is(err, context.DeadlineExceeded) {
85+
t.Errorf("err wants DeadlineExceeded but %+v", err)
86+
}
87+
}

server.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,18 @@ func receiveCodeViaLocalServer(ctx context.Context, c *Config) (string, error) {
6666
}
6767
return nil
6868
})
69-
if c.LocalServerReadyChan != nil {
70-
c.LocalServerReadyChan <- c.OAuth2Config.RedirectURL
71-
}
72-
69+
eg.Go(func() error {
70+
if c.LocalServerReadyChan == nil {
71+
return nil
72+
}
73+
select {
74+
case c.LocalServerReadyChan <- c.OAuth2Config.RedirectURL:
75+
c.Logf("oauth2cli: wrote a URL to LocalServerReadyChan: %s", c.OAuth2Config.RedirectURL)
76+
return nil
77+
case <-ctx.Done():
78+
return ctx.Err()
79+
}
80+
})
7381
if err := eg.Wait(); err != nil {
7482
return "", fmt.Errorf("authorization error: %w", err)
7583
}

0 commit comments

Comments
 (0)