-
Notifications
You must be signed in to change notification settings - Fork 18
/
server.go
175 lines (159 loc) · 5.04 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package oauth2cli
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"sync"
"time"
"github.com/int128/listener"
"golang.org/x/sync/errgroup"
)
func receiveCodeViaLocalServer(ctx context.Context, c *Config) (string, error) {
l, err := listener.New(c.LocalServerBindAddress)
if err != nil {
return "", fmt.Errorf("could not start a local server: %w", err)
}
defer l.Close()
c.OAuth2Config.RedirectURL = computeRedirectURL(l, c)
respCh := make(chan *authorizationResponse)
server := http.Server{
Handler: c.LocalServerMiddleware(&localServerHandler{
config: c,
respCh: respCh,
}),
}
shutdownCh := make(chan struct{})
var resp *authorizationResponse
var eg errgroup.Group
eg.Go(func() error {
defer close(respCh)
c.Logf("oauth2cli: starting a server at %s", l.Addr())
defer c.Logf("oauth2cli: stopped the server")
if c.isLocalServerHTTPS() {
if err := server.ServeTLS(l, c.LocalServerCertFile, c.LocalServerKeyFile); err != nil && err != http.ErrServerClosed {
return fmt.Errorf("could not start HTTPS server: %w", err)
}
return nil
}
if err := server.Serve(l); err != nil && err != http.ErrServerClosed {
return fmt.Errorf("could not start HTTP server: %w", err)
}
return nil
})
eg.Go(func() error {
defer close(shutdownCh)
select {
case gotResp, ok := <-respCh:
if ok {
resp = gotResp
}
return nil
case <-ctx.Done():
return ctx.Err()
}
})
eg.Go(func() error {
<-shutdownCh
// Gracefully shutdown the server in the timeout.
// If the server has not started, Shutdown returns nil and this returns immediately.
// If Shutdown has failed, force-close the server.
c.Logf("oauth2cli: shutting down the server")
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
c.Logf("oauth2cli: force-closing the server: shutdown failed: %s", err)
_ = server.Close()
return nil
}
return nil
})
eg.Go(func() error {
if c.LocalServerReadyChan == nil {
return nil
}
select {
case c.LocalServerReadyChan <- c.OAuth2Config.RedirectURL:
return nil
case <-ctx.Done():
return ctx.Err()
}
})
if err := eg.Wait(); err != nil {
return "", fmt.Errorf("authorization error: %w", err)
}
if resp == nil {
return "", errors.New("no authorization response")
}
return resp.code, resp.err
}
func computeRedirectURL(l net.Listener, c *Config) string {
hostPort := fmt.Sprintf("%s:%d", c.RedirectURLHostname, l.Addr().(*net.TCPAddr).Port)
if c.LocalServerCertFile != "" {
return "https://" + hostPort
}
return "http://" + hostPort
}
type authorizationResponse struct {
code string // non-empty if a valid code is received
err error // non-nil if an error is received or any error occurs
}
type localServerHandler struct {
config *Config
respCh chan<- *authorizationResponse // channel to send a response to
onceRespCh sync.Once // ensure send once
}
func (h *localServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
switch {
case r.Method == "GET" && r.URL.Path == "/" && q.Get("error") != "":
h.onceRespCh.Do(func() {
h.respCh <- h.handleErrorResponse(w, r)
})
case r.Method == "GET" && r.URL.Path == "/" && q.Get("code") != "":
h.onceRespCh.Do(func() {
h.respCh <- h.handleCodeResponse(w, r)
})
case r.Method == "GET" && r.URL.Path == "/":
h.handleIndex(w, r)
default:
http.NotFound(w, r)
}
}
func (h *localServerHandler) handleIndex(w http.ResponseWriter, r *http.Request) {
authCodeURL := h.config.OAuth2Config.AuthCodeURL(h.config.State, h.config.AuthCodeOptions...)
h.config.Logf("oauth2cli: sending redirect to %s", authCodeURL)
http.Redirect(w, r, authCodeURL, 302)
}
func (h *localServerHandler) handleCodeResponse(w http.ResponseWriter, r *http.Request) *authorizationResponse {
q := r.URL.Query()
code, state := q.Get("code"), q.Get("state")
if state != h.config.State {
h.authorizationError(w, r)
return &authorizationResponse{err: fmt.Errorf("state does not match (wants %s but got %s)", h.config.State, state)}
}
if h.config.SuccessRedirectURL != "" {
http.Redirect(w, r, h.config.SuccessRedirectURL, http.StatusFound)
} else {
w.Header().Add("Content-Type", "text/html")
if _, err := fmt.Fprint(w, h.config.LocalServerSuccessHTML); err != nil {
http.Error(w, "server error", 500)
return &authorizationResponse{err: fmt.Errorf("write error: %w", err)}
}
}
return &authorizationResponse{code: code}
}
func (h *localServerHandler) handleErrorResponse(w http.ResponseWriter, r *http.Request) *authorizationResponse {
q := r.URL.Query()
errorCode, errorDescription := q.Get("error"), q.Get("error_description")
h.authorizationError(w, r)
return &authorizationResponse{err: fmt.Errorf("authorization error from server: %s %s", errorCode, errorDescription)}
}
func (h *localServerHandler) authorizationError(w http.ResponseWriter, r *http.Request) {
if h.config.FailureRedirectURL != "" {
http.Redirect(w, r, h.config.FailureRedirectURL, http.StatusFound)
} else {
http.Error(w, "authorization error", 500)
}
}