(ctx context.Context, expectedState, authURL, callbackAddr string, opts LoginOptions)
| 267 | } |
| 268 | |
| 269 | func (m *Manager) waitForCallback(ctx context.Context, expectedState, authURL, callbackAddr string, opts LoginOptions) (string, error) { |
| 270 | lc := net.ListenConfig{} |
| 271 | listener, err := lc.Listen(ctx, "tcp", callbackAddr) |
| 272 | if err != nil { |
| 273 | return "", fmt.Errorf("failed to start callback server: %w", err) |
| 274 | } |
| 275 | defer func() { _ = listener.Close() }() |
| 276 | |
| 277 | codeCh := make(chan string, 1) |
| 278 | errCh := make(chan error, 1) |
| 279 | var shutdownOnce sync.Once |
| 280 | |
| 281 | server := &http.Server{ |
| 282 | ReadHeaderTimeout: 10 * time.Second, |
| 283 | ReadTimeout: 15 * time.Second, |
| 284 | WriteTimeout: 10 * time.Second, |
| 285 | IdleTimeout: 30 * time.Second, |
| 286 | } |
| 287 | |
| 288 | shutdownServer := func() { |
| 289 | shutdownOnce.Do(func() { |
| 290 | shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) //nolint:gosec // G118: cancel deferred in goroutine; async shutdown required to avoid handler self-deadlock |
| 291 | go func() { |
| 292 | defer cancel() |
| 293 | if shutdownErr := server.Shutdown(shutdownCtx); shutdownErr != nil && !errors.Is(shutdownErr, http.ErrServerClosed) { |
| 294 | fmt.Fprintf(os.Stderr, "warning: callback server shutdown failed: %v\n", shutdownErr) |
| 295 | } |
| 296 | }() |
| 297 | }) |
| 298 | } |
| 299 | |
| 300 | server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 301 | state := r.URL.Query().Get("state") |
| 302 | code := r.URL.Query().Get("code") |
| 303 | errParam := r.URL.Query().Get("error") |
| 304 | |
| 305 | if errParam != "" { |
| 306 | errCh <- fmt.Errorf("OAuth error: %s", errParam) |
| 307 | fmt.Fprint(w, "<html><body><h1>Authentication failed</h1><p>You can close this window.</p></body></html>") |
| 308 | shutdownServer() |
| 309 | return |
| 310 | } |
| 311 | |
| 312 | if state != expectedState { |
| 313 | errCh <- fmt.Errorf("state mismatch: CSRF protection failed") |
| 314 | fmt.Fprint(w, "<html><body><h1>Authentication failed</h1><p>State mismatch.</p></body></html>") |
| 315 | shutdownServer() |
| 316 | return |
| 317 | } |
| 318 | |
| 319 | codeCh <- code |
| 320 | fmt.Fprint(w, "<html><body><h1>Authentication successful!</h1><p>You can close this window.</p></body></html>") |
| 321 | shutdownServer() |
| 322 | }) |
| 323 | |
| 324 | go server.Serve(listener) //nolint:errcheck |
| 325 | |
| 326 | if !opts.NoBrowser { |
no test coverage detected