-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallback.go
More file actions
186 lines (161 loc) · 5.49 KB
/
callback.go
File metadata and controls
186 lines (161 loc) · 5.49 KB
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
176
177
178
179
180
181
182
183
184
185
186
package main
import (
"context"
"crypto/subtle"
"fmt"
"html"
"net"
"net/http"
"sync"
"time"
"github.com/go-authgate/oauth-cli/tui"
)
const (
// callbackTimeout is how long we wait for the browser to deliver the code.
callbackTimeout = 5 * time.Minute
// callbackWriteTimeout is the HTTP write deadline for the callback handler.
// It must exceed tokenExchangeTimeout to ensure the exchange result can be
// written back to the browser before the connection times out.
callbackWriteTimeout = 30 * time.Second
)
// callbackResult holds the outcome of the local callback round-trip.
type callbackResult struct {
Storage *tui.TokenStorage
Error string
Desc string
}
// startCallbackServer starts a local HTTP server on the given port and waits
// for the OAuth callback. It validates the returned state against expectedState,
// then calls exchangeFn with the received authorization code. The HTTP response
// is held open until exchangeFn returns so the browser reflects the true outcome.
//
// The server shuts itself down after the first request or when ctx is cancelled.
func startCallbackServer(
ctx context.Context,
port int,
expectedState string,
exchangeFn func(ctx context.Context, code string) (*tui.TokenStorage, error),
) (*tui.TokenStorage, error) {
resultCh := make(chan callbackResult, 1)
// sendResult delivers the result exactly once. Any concurrent or subsequent
// invocations (e.g. a browser retry or automated agent) are silently
// discarded, preventing a goroutine from blocking forever on the send.
var once sync.Once
sendResult := func(r callbackResult) {
once.Do(func() { resultCh <- r })
}
// exchangeOnce ensures the token exchange runs at most once even when the
// browser retries the callback request.
var (
exchangeOnce sync.Once
exchangeStorage *tui.TokenStorage
exchangeErr error
)
mux := http.NewServeMux()
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
// Check for OAuth error response first.
if oauthErr := q.Get("error"); oauthErr != "" {
desc := q.Get("error_description")
writeCallbackPage(w, false, oauthErr, desc)
sendResult(callbackResult{Error: oauthErr, Desc: desc})
return
}
// Validate state (CSRF protection) using constant-time comparison.
state := q.Get("state")
if len(state) != len(expectedState) ||
subtle.ConstantTimeCompare([]byte(state), []byte(expectedState)) != 1 {
writeCallbackPage(w, false, "state_mismatch",
"State parameter does not match. Possible CSRF attack.")
sendResult(callbackResult{
Error: "state_mismatch",
Desc: "state parameter mismatch",
})
return
}
code := q.Get("code")
if code == "" {
writeCallbackPage(w, false, "missing_code", "No authorization code in callback.")
sendResult(callbackResult{Error: "missing_code", Desc: "code parameter missing"})
return
}
// Hold the HTTP response open while exchanging the code for tokens so
// the browser reflects the true outcome (success or failure).
exchangeOnce.Do(func() {
exchangeStorage, exchangeErr = exchangeFn(r.Context(), code)
})
if exchangeErr != nil {
writeCallbackPage(w, false, "token_exchange_failed", exchangeErr.Error())
sendResult(callbackResult{Error: "token_exchange_failed", Desc: exchangeErr.Error()})
return
}
writeCallbackPage(w, true, "", "")
sendResult(callbackResult{Storage: exchangeStorage})
})
srv := &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", port),
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: callbackWriteTimeout,
}
// Use a listener so we can report the actual bound port.
ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", srv.Addr)
if err != nil {
return nil, fmt.Errorf("failed to start callback server on port %d: %w", port, err)
}
// Serve in background; shut down after receiving the result.
go func() {
_ = srv.Serve(ln)
}()
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
}()
// Wait for callback, timeout, or context cancellation.
timer := time.NewTimer(callbackTimeout)
defer timer.Stop()
select {
case result := <-resultCh:
if result.Error != "" {
if result.Desc != "" {
return nil, fmt.Errorf("%s: %s", result.Error, result.Desc)
}
return nil, fmt.Errorf("%s", result.Error)
}
return result.Storage, nil
case <-ctx.Done():
return nil, ctx.Err()
case <-timer.C:
return nil, fmt.Errorf("timed out waiting for browser authorization (%s)", callbackTimeout)
}
}
// writeCallbackPage writes a minimal HTML response to the browser tab.
func writeCallbackPage(w http.ResponseWriter, success bool, errCode, errDesc string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if success {
fmt.Fprint(w, `<!DOCTYPE html>
<html>
<head><title>Authorization Successful</title></head>
<body style="font-family:sans-serif;text-align:center;padding:4rem">
<h1 style="color:#2ea44f">✓ Authorization Successful</h1>
<p>You have been successfully authorized.</p>
<p>You can close this tab and return to your terminal.</p>
</body>
</html>`)
return
}
msg := errCode
if errDesc != "" {
msg = errDesc
}
fmt.Fprintf(w, `<!DOCTYPE html>
<html>
<head><title>Authorization Failed</title></head>
<body style="font-family:sans-serif;text-align:center;padding:4rem">
<h1 style="color:#cb2431">✗ Authorization Failed</h1>
<p>%s</p>
<p>You can close this tab and check your terminal for details.</p>
</body>
</html>`, html.EscapeString(msg))
}