Skip to content

bug(chatgptauth): gracefully shut down the OAuth callback server #1952

Closed

Description

@lizhengfeng101

Description

The ChatGPT OAuth callback server can close an active callback connection before its HTTP response has been sent. This can leave the login successful while the browser receives a transport error, and causes an intermittent failure in TestLoginCompletesWhileBrowserOpenerIsRunning:

login_recovery_test.go:77: browser opener exited before login completed
--- FAIL: TestLoginCompletesWhileBrowserOpenerIsRunning

In Client.loginAttempt, the /auth/callback handler publishes the authorization result to done before writing its response. The receiving goroutine can finish the token exchange and return, executing defer server.Close() while the handler is still active. http.Server.Close immediately closes active connections; it does not wait for the callback response to finish.

Fix direction: replace immediate closure with bounded graceful shutdown. Give active callback responses time to finish using server.Shutdown with a fresh, one-second context derived from context.Background(). If shutdown fails or reaches its deadline, call server.Close() to force cleanup:

defer func() {
    shutdownContext, shutdownCancel := context.WithTimeout(context.Background(), time.Second)
    defer shutdownCancel()
    if err := server.Shutdown(shutdownContext); err != nil {
        server.Close()
    }
}()

The cleanup context must be independent of the login context, which may already be cancelled. The timeout is required so a stalled local connection cannot keep login cleanup waiting indefinitely. Preserve the existing login result and do not wait for the browser-opening process to exit.

Moving the channel send after fmt.Fprintln alone is not sufficient: net/http may still buffer the response until the handler returns. Do not address this by adding sleeps, retrying the flaky test, or weakening its assertions.

Scope

  • Implementation: internal/chatgptauth/oauth.go, specifically callback-server cleanup in Client.loginAttempt.
  • Regression tests: internal/chatgptauth/login_recovery_test.go and narrowly scoped test helpers in the same package as needed.
  • No changes to OAuth validation, token exchange semantics, browser-launch behavior, the separate acp module, or CI configuration.

Acceptance Criteria

  • Active callback responses are allowed to finish during normal cleanup; successful login does not prematurely terminate the callback connection.
  • Cleanup uses an independent one-second shutdown context and falls back to Close on shutdown failure or timeout, without replacing the original login result.
  • Add a deterministic, channel-synchronized regression that fails with the old immediate-close implementation and passes with the fix. Exercise an active callback response rather than merely checking that a shutdown method was called.
  • Cover successful authorization, authorization denial, token exchange failure, an already-cancelled login context, and a stalled connection that requires the timeout/forced-close fallback. Preserve cancellation errors and do not leak test goroutines or connections.
  • Keep TestLoginCompletesWhileBrowserOpenerIsRunning passing without relaxing its assertions: login must complete independently of the browser opener's lifetime.
  • Run the documented checks: make test PACKAGES=./internal/chatgptauth, make test, make check, and make coverage; retain the repository's 90% coverage threshold.

Context

CI evidence

Controlled reproduction and candidate validation

Local experiments used Go overlays, real loopback HTTP connections, and the existing authentication fixture; no tracked source was changed. To reproduce the ordering deterministically:

  1. Pause the valid callback handler immediately after it publishes to done, before writing the response.
  2. Let token exchange finish and observe server cleanup while the handler is still paused.
  3. With Close, observe that cleanup finishes before the handler is released: login succeeds, the callback request fails, and the browser opener exits early.
  4. With Shutdown, use a shutdown-start notification to release the active handler, then verify that the complete callback response is received. In the timeout case, keep it paused until the forced-close fallback executes.

On macOS/arm64, Go 1.26.11, GOMAXPROCS=2, with -race enabled through make test:

Experiment Result
Original cleanup, controlled successful-login reproduction 30/30 failures; reproduces the same premature-browser-exit assertion
Candidate cleanup, five scenarios listed above 50/50 passing subtests, ten repetitions per scenario
Original browser-lifetime test, with only the cleanup fix overlaid and no probe hooks 300/300 passes
Complete internal/chatgptauth test suite, with only the cleanup fix overlaid Pass

A negative control that derived the shutdown context from the cancelled login context still lost the response in 3/3 runs on Go 1.27.2. These are local proof-of-concept results, not reruns of the Linux CI job. The original CI log does not include the underlying callback transport error; the controlled experiment establishes the shutdown race and reproduces its test signature.

Community contributions implementing this scoped fix and its regression coverage are welcome.

AI/LLM disclosure: OpenAI Codex (session-reported model: gpt-6-astra) assisted with the investigation, local reproduction and candidate validation, and drafting this issue.

Activity

  1. added
    bug
    help wanted
    verified
    good first issue
    on Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    buggood first issuehelp wantedverified

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions