|
| 1 | +package oauth |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "embed" |
| 6 | + "fmt" |
| 7 | + "html/template" |
| 8 | + "net" |
| 9 | + "net/http" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +//go:embed templates/*.html |
| 14 | +var templateFS embed.FS |
| 15 | + |
| 16 | +var ( |
| 17 | + errorTemplate = template.Must(template.ParseFS(templateFS, "templates/error.html")) |
| 18 | + successTemplate = template.Must(template.ParseFS(templateFS, "templates/success.html")) |
| 19 | +) |
| 20 | + |
| 21 | +// callbackResult is delivered by the callback server once the browser redirect |
| 22 | +// arrives. Exactly one of code or err is set. |
| 23 | +type callbackResult struct { |
| 24 | + code string |
| 25 | + err error |
| 26 | +} |
| 27 | + |
| 28 | +// callbackServer is a short-lived local HTTP server that captures the |
| 29 | +// authorization code from the OAuth redirect. |
| 30 | +type callbackServer struct { |
| 31 | + server *http.Server |
| 32 | + listener net.Listener |
| 33 | + redirect string |
| 34 | + results chan callbackResult |
| 35 | +} |
| 36 | + |
| 37 | +// listenCallback binds the local callback listener. |
| 38 | +// |
| 39 | +// A random port (port == 0) binds to 127.0.0.1 only: the redirect target is |
| 40 | +// loopback and never reachable off-host. A fixed port binds to all interfaces |
| 41 | +// because Docker's published-port DNAT delivers traffic to the container's eth0 |
| 42 | +// rather than to loopback; exposure is still constrained by the host-side |
| 43 | +// publish (e.g. -p 127.0.0.1:8085:8085). |
| 44 | +func listenCallback(port int) (net.Listener, error) { |
| 45 | + host := "127.0.0.1" |
| 46 | + if port > 0 { |
| 47 | + host = "0.0.0.0" |
| 48 | + } |
| 49 | + addr := fmt.Sprintf("%s:%d", host, port) |
| 50 | + listener, err := net.Listen("tcp", addr) |
| 51 | + if err != nil { |
| 52 | + return nil, fmt.Errorf("starting callback listener on %s: %w", addr, err) |
| 53 | + } |
| 54 | + return listener, nil |
| 55 | +} |
| 56 | + |
| 57 | +// newCallbackServer starts a callback server on listener that validates state |
| 58 | +// and reports the result on a buffered channel. The redirect URI always uses |
| 59 | +// localhost so it matches the value registered on the OAuth/GitHub App. |
| 60 | +func newCallbackServer(listener net.Listener, expectedState string) *callbackServer { |
| 61 | + cs := &callbackServer{ |
| 62 | + server: &http.Server{ReadHeaderTimeout: 10 * time.Second}, // ReadHeaderTimeout guards against Slowloris. |
| 63 | + listener: listener, |
| 64 | + redirect: fmt.Sprintf("http://localhost:%d/callback", listener.Addr().(*net.TCPAddr).Port), |
| 65 | + results: make(chan callbackResult, 1), |
| 66 | + } |
| 67 | + cs.server.Handler = cs.handler(expectedState) |
| 68 | + |
| 69 | + go func() { |
| 70 | + if err := cs.server.Serve(listener); err != nil && err != http.ErrServerClosed { |
| 71 | + cs.report(callbackResult{err: fmt.Errorf("callback server: %w", err)}) |
| 72 | + } |
| 73 | + }() |
| 74 | + |
| 75 | + return cs |
| 76 | +} |
| 77 | + |
| 78 | +// handler renders the callback endpoint. It reports the outcome exactly once and |
| 79 | +// always shows the user a friendly page. |
| 80 | +func (cs *callbackServer) handler(expectedState string) http.Handler { |
| 81 | + mux := http.NewServeMux() |
| 82 | + mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { |
| 83 | + q := r.URL.Query() |
| 84 | + |
| 85 | + if errCode := q.Get("error"); errCode != "" { |
| 86 | + msg := errCode |
| 87 | + if desc := q.Get("error_description"); desc != "" { |
| 88 | + msg = fmt.Sprintf("%s: %s", errCode, desc) |
| 89 | + } |
| 90 | + cs.report(callbackResult{err: fmt.Errorf("authorization failed: %s", msg)}) |
| 91 | + renderError(w, msg) |
| 92 | + return |
| 93 | + } |
| 94 | + |
| 95 | + if q.Get("state") != expectedState { |
| 96 | + cs.report(callbackResult{err: fmt.Errorf("state mismatch (possible CSRF)")}) |
| 97 | + renderError(w, "state mismatch") |
| 98 | + return |
| 99 | + } |
| 100 | + |
| 101 | + code := q.Get("code") |
| 102 | + if code == "" { |
| 103 | + cs.report(callbackResult{err: fmt.Errorf("no authorization code in callback")}) |
| 104 | + renderError(w, "no authorization code received") |
| 105 | + return |
| 106 | + } |
| 107 | + |
| 108 | + cs.report(callbackResult{code: code}) |
| 109 | + renderSuccess(w) |
| 110 | + }) |
| 111 | + return mux |
| 112 | +} |
| 113 | + |
| 114 | +// report delivers the first outcome and drops later ones (the channel is |
| 115 | +// buffered for one; subsequent redirect retries must not block the handler). |
| 116 | +func (cs *callbackServer) report(res callbackResult) { |
| 117 | + select { |
| 118 | + case cs.results <- res: |
| 119 | + default: |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +// wait blocks for the callback outcome or ctx cancellation, then shuts the |
| 124 | +// server down. It is safe to call once per server. |
| 125 | +func (cs *callbackServer) wait(ctx context.Context) (string, error) { |
| 126 | + defer cs.close() |
| 127 | + select { |
| 128 | + case res := <-cs.results: |
| 129 | + return res.code, res.err |
| 130 | + case <-ctx.Done(): |
| 131 | + return "", ctx.Err() |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +func (cs *callbackServer) close() { |
| 136 | + shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 137 | + defer cancel() |
| 138 | + _ = cs.server.Shutdown(shutdownCtx) |
| 139 | + _ = cs.listener.Close() |
| 140 | +} |
| 141 | + |
| 142 | +func renderSuccess(w http.ResponseWriter) { |
| 143 | + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 144 | + if err := successTemplate.Execute(w, nil); err != nil { |
| 145 | + http.Error(w, "internal error", http.StatusInternalServerError) |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +// renderError shows the failure page. html/template auto-escapes msg, so a |
| 150 | +// hostile error_description cannot inject markup. |
| 151 | +func renderError(w http.ResponseWriter, msg string) { |
| 152 | + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 153 | + if err := errorTemplate.Execute(w, struct{ ErrorMessage string }{ErrorMessage: msg}); err != nil { |
| 154 | + http.Error(w, "internal error", http.StatusInternalServerError) |
| 155 | + } |
| 156 | +} |
0 commit comments