-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallback.go
More file actions
153 lines (133 loc) · 4.31 KB
/
callback.go
File metadata and controls
153 lines (133 loc) · 4.31 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
package main
import (
"context"
"errors"
"fmt"
"html"
"net"
"net/http"
"sync"
"time"
)
const (
// callbackTimeout is how long we wait for the browser to deliver the code.
callbackTimeout = 2 * time.Minute
)
// ErrCallbackTimeout is returned when no browser callback is received within callbackTimeout.
// Callers can use errors.Is to distinguish a timeout from other authorization errors
// and decide whether to fall back to Device Code Flow.
var ErrCallbackTimeout = errors.New("browser authorization timed out")
// callbackResult holds the outcome of the local callback round-trip.
type callbackResult struct {
Storage *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,
// calls exchangeFn to exchange the code for tokens, and returns the resulting
// TokenStorage (or an error).
//
// The server shuts itself down after the first request.
func startCallbackServer(ctx context.Context, port int, expectedState string,
exchangeFn func(context.Context, string) (*TokenStorage, error),
) (*TokenStorage, error) {
resultCh := make(chan callbackResult, 1)
var once sync.Once
sendResult := func(r callbackResult) {
once.Do(func() { resultCh <- r })
}
mux := http.NewServeMux()
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if oauthErr := q.Get("error"); oauthErr != "" {
desc := q.Get("error_description")
writeCallbackPage(w, false, oauthErr, desc)
sendResult(callbackResult{Error: oauthErr, Desc: desc})
return
}
state := q.Get("state")
if state != expectedState {
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
}
storage, 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: storage})
})
srv := &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", port),
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
}
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)
}
go func() {
_ = srv.Serve(ln)
}()
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = srv.Shutdown(shutdownCtx)
}()
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 <-time.After(callbackTimeout):
return nil, fmt.Errorf("%w after %s", ErrCallbackTimeout, 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))
}