chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
//go:embed templates/*.html
|
||||
var templateFS embed.FS
|
||||
|
||||
var (
|
||||
errorTemplate = template.Must(template.ParseFS(templateFS, "templates/error.html"))
|
||||
successTemplate = template.Must(template.ParseFS(templateFS, "templates/success.html"))
|
||||
)
|
||||
|
||||
// callbackResult is delivered by the callback server once the browser redirect
|
||||
// arrives. Exactly one of code or err is set.
|
||||
type callbackResult struct {
|
||||
code string
|
||||
err error
|
||||
}
|
||||
|
||||
// callbackServer is a short-lived local HTTP server that captures the
|
||||
// authorization code from the OAuth redirect.
|
||||
type callbackServer struct {
|
||||
server *http.Server
|
||||
listener net.Listener
|
||||
redirect string
|
||||
results chan callbackResult
|
||||
}
|
||||
|
||||
// listenCallback binds the local callback listener.
|
||||
//
|
||||
// It binds to loopback (127.0.0.1) by default so the callback server is never
|
||||
// exposed on other interfaces. bindAll is set only inside a container, where
|
||||
// Docker's published-port DNAT delivers traffic to the container's eth0 rather
|
||||
// than to loopback; host-side exposure is still constrained by the publish
|
||||
// (e.g. -p 127.0.0.1:8085:8085). A native run — even with a fixed port — stays
|
||||
// on loopback.
|
||||
func listenCallback(port int, bindAll bool) (net.Listener, error) {
|
||||
host := "127.0.0.1"
|
||||
if bindAll {
|
||||
host = "0.0.0.0"
|
||||
}
|
||||
addr := fmt.Sprintf("%s:%d", host, port)
|
||||
listener, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("starting callback listener on %s: %w", addr, err)
|
||||
}
|
||||
return listener, nil
|
||||
}
|
||||
|
||||
// newCallbackServer starts a callback server on listener that validates state
|
||||
// and reports the result on a buffered channel. The redirect URI always uses
|
||||
// localhost so it matches the value registered on the OAuth/GitHub App.
|
||||
func newCallbackServer(listener net.Listener, expectedState string) *callbackServer {
|
||||
cs := &callbackServer{
|
||||
server: &http.Server{ReadHeaderTimeout: 10 * time.Second}, // ReadHeaderTimeout guards against Slowloris.
|
||||
listener: listener,
|
||||
redirect: fmt.Sprintf("http://localhost:%d/callback", listener.Addr().(*net.TCPAddr).Port),
|
||||
results: make(chan callbackResult, 1),
|
||||
}
|
||||
cs.server.Handler = cs.handler(expectedState)
|
||||
|
||||
go func() {
|
||||
if err := cs.server.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||
cs.report(callbackResult{err: fmt.Errorf("callback server: %w", err)})
|
||||
}
|
||||
}()
|
||||
|
||||
return cs
|
||||
}
|
||||
|
||||
// handler renders the callback endpoint. It reports the outcome exactly once and
|
||||
// always shows the user a friendly page.
|
||||
func (cs *callbackServer) handler(expectedState string) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
|
||||
if errCode := q.Get("error"); errCode != "" {
|
||||
msg := errCode
|
||||
if desc := q.Get("error_description"); desc != "" {
|
||||
msg = fmt.Sprintf("%s: %s", errCode, desc)
|
||||
}
|
||||
cs.report(callbackResult{err: fmt.Errorf("authorization failed: %s", msg)})
|
||||
renderError(w, msg)
|
||||
return
|
||||
}
|
||||
|
||||
if q.Get("state") != expectedState {
|
||||
cs.report(callbackResult{err: fmt.Errorf("state mismatch (possible CSRF)")})
|
||||
renderError(w, "state mismatch")
|
||||
return
|
||||
}
|
||||
|
||||
code := q.Get("code")
|
||||
if code == "" {
|
||||
cs.report(callbackResult{err: fmt.Errorf("no authorization code in callback")})
|
||||
renderError(w, "no authorization code received")
|
||||
return
|
||||
}
|
||||
|
||||
cs.report(callbackResult{code: code})
|
||||
renderSuccess(w)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
// report delivers the first outcome and drops later ones (the channel is
|
||||
// buffered for one; subsequent redirect retries must not block the handler).
|
||||
func (cs *callbackServer) report(res callbackResult) {
|
||||
select {
|
||||
case cs.results <- res:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// wait blocks for the callback outcome or ctx cancellation, then shuts the
|
||||
// server down. It is safe to call once per server.
|
||||
func (cs *callbackServer) wait(ctx context.Context) (string, error) {
|
||||
defer cs.close()
|
||||
select {
|
||||
case res := <-cs.results:
|
||||
return res.code, res.err
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (cs *callbackServer) close() {
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
_ = cs.server.Shutdown(shutdownCtx)
|
||||
_ = cs.listener.Close()
|
||||
}
|
||||
|
||||
func renderSuccess(w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := successTemplate.Execute(w, nil); err != nil {
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// renderError shows the failure page. html/template auto-escapes msg, so a
|
||||
// hostile error_description cannot inject markup.
|
||||
func renderError(w http.ResponseWriter, msg string) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := errorTemplate.Execute(w, struct{ ErrorMessage string }{ErrorMessage: msg}); err != nil {
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// serveCallback drives the callback handler with the given query string and
|
||||
// returns the recorded response and the single reported result.
|
||||
func serveCallback(t *testing.T, expectedState, query string) (*httptest.ResponseRecorder, callbackResult) {
|
||||
t.Helper()
|
||||
cs := &callbackServer{results: make(chan callbackResult, 1)}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/callback?"+query, nil)
|
||||
|
||||
cs.handler(expectedState).ServeHTTP(rec, req)
|
||||
|
||||
select {
|
||||
case res := <-cs.results:
|
||||
return rec, res
|
||||
default:
|
||||
t.Fatal("handler did not report a result")
|
||||
return nil, callbackResult{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackHandlerSuccess(t *testing.T) {
|
||||
rec, res := serveCallback(t, "state123", "code=the-code&state=state123")
|
||||
|
||||
require.NoError(t, res.err)
|
||||
assert.Equal(t, "the-code", res.code)
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.Contains(t, rec.Body.String(), "Authorization Successful")
|
||||
}
|
||||
|
||||
func TestCallbackHandlerStateMismatch(t *testing.T) {
|
||||
rec, res := serveCallback(t, "expected", "code=the-code&state=attacker")
|
||||
|
||||
require.Error(t, res.err)
|
||||
assert.Empty(t, res.code)
|
||||
assert.Contains(t, res.err.Error(), "state mismatch")
|
||||
assert.Contains(t, rec.Body.String(), "state mismatch")
|
||||
}
|
||||
|
||||
func TestCallbackHandlerMissingCode(t *testing.T) {
|
||||
_, res := serveCallback(t, "state123", "state=state123")
|
||||
|
||||
require.Error(t, res.err)
|
||||
assert.Contains(t, res.err.Error(), "no authorization code")
|
||||
}
|
||||
|
||||
func TestCallbackHandlerOAuthError(t *testing.T) {
|
||||
_, res := serveCallback(t, "state123", "error=access_denied&error_description=user+said+no")
|
||||
|
||||
require.Error(t, res.err)
|
||||
assert.Contains(t, res.err.Error(), "access_denied")
|
||||
assert.Contains(t, res.err.Error(), "user said no")
|
||||
}
|
||||
|
||||
func TestCallbackHandlerEscapesError(t *testing.T) {
|
||||
rec, _ := serveCallback(t, "state123", "error=evil&error_description=%3Cscript%3Ealert(1)%3C%2Fscript%3E")
|
||||
|
||||
body := rec.Body.String()
|
||||
assert.NotContains(t, body, "<script>", "error message must be HTML-escaped")
|
||||
assert.Contains(t, body, "<script>")
|
||||
}
|
||||
|
||||
func TestListenCallbackRandomPortIsLoopback(t *testing.T) {
|
||||
listener, err := listenCallback(0, false)
|
||||
require.NoError(t, err)
|
||||
defer listener.Close()
|
||||
|
||||
addr, ok := listener.Addr().(*net.TCPAddr)
|
||||
require.True(t, ok)
|
||||
assert.True(t, addr.IP.IsLoopback(), "default bind must be loopback only, got %s", addr.IP)
|
||||
assert.NotZero(t, addr.Port)
|
||||
}
|
||||
|
||||
func TestListenCallbackBindAllForContainer(t *testing.T) {
|
||||
listener, err := listenCallback(0, true)
|
||||
require.NoError(t, err)
|
||||
defer listener.Close()
|
||||
|
||||
addr, ok := listener.Addr().(*net.TCPAddr)
|
||||
require.True(t, ok)
|
||||
assert.True(t, addr.IP.IsUnspecified(), "bindAll must bind all interfaces, got %s", addr.IP)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// errNoDisplay reports that the host has no display server, so no browser can be
|
||||
// launched. It is a definitive headless signal (unlike a generic launch error),
|
||||
// which lets the flow prefer device authorization — the only channel reachable
|
||||
// from a browser on another machine (e.g. a remote SSH session).
|
||||
var errNoDisplay = errors.New("no display server detected")
|
||||
|
||||
// openBrowser tries to open url in the user's default browser. It returns an
|
||||
// error when no browser can plausibly be launched so the caller can fall back
|
||||
// to elicitation. On Linux it treats a headless session (no display server) as
|
||||
// unopenable, which is the common case for SSH and containers.
|
||||
func openBrowser(url string) error {
|
||||
var cmd *exec.Cmd
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
if os.Getenv("DISPLAY") == "" && os.Getenv("WAYLAND_DISPLAY") == "" {
|
||||
return errNoDisplay
|
||||
}
|
||||
cmd = exec.Command("xdg-open", url)
|
||||
case "darwin":
|
||||
cmd = exec.Command("open", url)
|
||||
case "windows":
|
||||
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
|
||||
default:
|
||||
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
|
||||
}
|
||||
|
||||
cmd.Stdout = io.Discard
|
||||
cmd.Stderr = io.Discard
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
// The launcher (xdg-open/open/rundll32) exits as soon as it hands off to the
|
||||
// browser. Reap it asynchronously so it does not linger as a zombie for the
|
||||
// lifetime of this long-running server.
|
||||
go func() { _ = cmd.Wait() }()
|
||||
return nil
|
||||
}
|
||||
|
||||
// isRunningInDocker reports whether the process is running inside a Docker (or
|
||||
// containerd) container. Detection relies on Linux-specific paths and is always
|
||||
// false elsewhere. It is used only to skip a PKCE flow that cannot work: a
|
||||
// random callback port inside a container cannot be reached from the host
|
||||
// browser, so we go straight to device flow in that case.
|
||||
func isRunningInDocker() bool {
|
||||
if runtime.GOOS != "linux" {
|
||||
return false
|
||||
}
|
||||
if _, err := os.Stat("/.dockerenv"); err == nil {
|
||||
return true
|
||||
}
|
||||
if data, err := os.ReadFile("/proc/1/cgroup"); err == nil {
|
||||
s := string(data)
|
||||
if strings.Contains(s, "docker") || strings.Contains(s, "containerd") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// deviceAuthTimeout bounds the synchronous device-code request made while
|
||||
// preparing the device flow (before any waiting on the user).
|
||||
const deviceAuthTimeout = 30 * time.Second
|
||||
|
||||
// errCallbackBind marks a failure to bind the local OAuth callback listener, so
|
||||
// begin can treat a busy fixed port as fatal without mislabeling unrelated
|
||||
// errors (e.g. a failure to generate the state parameter) as a port conflict.
|
||||
var errCallbackBind = errors.New("OAuth callback listener could not bind")
|
||||
|
||||
// flowPlan is a prepared authorization flow ready to run in the background.
|
||||
type flowPlan struct {
|
||||
// run performs the blocking part of the flow (await callback + exchange, or
|
||||
// poll the device endpoint) and returns the token.
|
||||
run func(context.Context) (*oauth2.Token, error)
|
||||
// display, if set, presents the prompt to the user via the Prompter and
|
||||
// blocks until they act. ErrPromptDeclined (the user said no) or any other
|
||||
// error aborts the flow, except ErrPromptUnavailable, which degrades to
|
||||
// fallback when that is set.
|
||||
display func(context.Context) error
|
||||
// fallback, if set alongside display, is the manual user action to surface
|
||||
// when the display prompt cannot be delivered (ErrPromptUnavailable). It lets
|
||||
// a runtime elicitation failure degrade to the manual channel — keeping the
|
||||
// background flow alive — instead of aborting.
|
||||
fallback *UserAction
|
||||
// userAction, if set, indicates the last-resort channel: the caller must
|
||||
// surface it and the user retries after authorizing out of band.
|
||||
userAction *UserAction
|
||||
}
|
||||
|
||||
// begin selects and prepares the appropriate flow. PKCE is preferred for its
|
||||
// stronger security; device flow is the fallback. A random callback port inside
|
||||
// Docker cannot be reached from the host browser, so that combination goes
|
||||
// straight to device flow.
|
||||
func (m *Manager) begin(prompter Prompter) (*flowPlan, error) {
|
||||
canPKCE := m.config.CallbackPort != 0 || !m.inDocker()
|
||||
if canPKCE {
|
||||
plan, err := m.beginPKCE(prompter)
|
||||
if err == nil {
|
||||
return plan, nil
|
||||
}
|
||||
// A fixed callback port that won't bind is fatal, not a cue to downgrade.
|
||||
// The port was chosen deliberately (and registered with the OAuth app), so
|
||||
// a bind failure means another process holds it — possibly one positioned
|
||||
// to intercept the authorization redirect. Silently switching to device
|
||||
// flow would mask that, so stop and make the user resolve it. Only genuine
|
||||
// bind failures qualify; other errors fall through to device flow.
|
||||
if m.config.CallbackPort != 0 && errors.Is(err, errCallbackBind) {
|
||||
return nil, fmt.Errorf("OAuth callback port %d is not available; another process may be using it — free the port or set a different --oauth-callback-port: %w", m.config.CallbackPort, err)
|
||||
}
|
||||
m.logger.Info("PKCE flow unavailable, falling back to device flow", "reason", err)
|
||||
} else {
|
||||
m.logger.Info("no callback port inside container; using device flow")
|
||||
}
|
||||
return m.beginDevice(prompter)
|
||||
}
|
||||
|
||||
// beginPKCE prepares the authorization-code + PKCE flow. It binds the callback
|
||||
// server and selects the most secure available display channel: browser
|
||||
// auto-open, then URL elicitation, then a tool-response message. On a headless
|
||||
// host with a random callback port it diverts to device flow, whose redirect
|
||||
// does not depend on reaching this machine's localhost.
|
||||
func (m *Manager) beginPKCE(prompter Prompter) (*flowPlan, error) {
|
||||
state, err := randomState()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
verifier := oauth2.GenerateVerifier()
|
||||
|
||||
// Bind to all interfaces only inside a container, where the published port
|
||||
// is delivered via eth0 rather than loopback. Native runs stay on loopback.
|
||||
listener, err := listenCallback(m.config.CallbackPort, m.inDocker())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %w", errCallbackBind, err)
|
||||
}
|
||||
if m.inDocker() {
|
||||
// Inside a container the callback binds all interfaces so the published
|
||||
// port is reachable, which also exposes it to the container network.
|
||||
// Publishing to loopback only (e.g. -p 127.0.0.1:%d:%d) keeps the
|
||||
// authorization code off the network.
|
||||
m.logger.Warn(fmt.Sprintf("OAuth callback is listening on all container interfaces; publish it to loopback only (e.g. -p 127.0.0.1:%d:%d) so the authorization code is not exposed on your network", m.config.CallbackPort, m.config.CallbackPort))
|
||||
}
|
||||
cs := newCallbackServer(listener, state)
|
||||
|
||||
oc := m.oauth2Config(cs.redirect)
|
||||
authURL := oc.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier))
|
||||
|
||||
run := func(ctx context.Context) (*oauth2.Token, error) {
|
||||
code, err := cs.wait(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tok, err := oc.Exchange(ctx, code, oauth2.VerifierOption(verifier))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("exchanging authorization code: %w", err)
|
||||
}
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
browserErr := m.openURL(authURL)
|
||||
switch {
|
||||
case browserErr == nil:
|
||||
m.logger.Info("opened browser for GitHub authorization")
|
||||
return &flowPlan{run: run}, nil
|
||||
case errors.Is(browserErr, errNoDisplay) && m.config.CallbackPort == 0:
|
||||
// Headless host with a random callback port: every PKCE channel ends in a
|
||||
// redirect to this machine's localhost, which a browser on another machine
|
||||
// (e.g. a remote SSH client) cannot reach — so even URL elicitation would
|
||||
// dead-end. Device flow is the only channel reachable from elsewhere, so
|
||||
// prefer it when the app supports it; otherwise fall through to the manual
|
||||
// authorization URL below for a same-machine browser.
|
||||
plan, deviceErr := m.beginDevice(prompter)
|
||||
if deviceErr == nil {
|
||||
cs.close()
|
||||
m.logger.Info("no display server; using device flow")
|
||||
return plan, nil
|
||||
}
|
||||
m.logger.Debug("device flow unavailable on headless host; offering manual authorization URL", "reason", deviceErr)
|
||||
default:
|
||||
m.logger.Debug("browser auto-open unavailable", "reason", browserErr)
|
||||
}
|
||||
|
||||
// The manual instructions double as the fallback if a chosen display channel
|
||||
// turns out to be undeliverable at runtime, so build them once here.
|
||||
manual := &UserAction{
|
||||
URL: authURL,
|
||||
Message: fmt.Sprintf(
|
||||
"To authorize the GitHub MCP Server, open this URL in your browser:\n\n%s\n\nAfter authorizing, retry your request.\n\n%s",
|
||||
authURL, securityAdvisory,
|
||||
),
|
||||
}
|
||||
|
||||
if canPromptURL(prompter) {
|
||||
display := func(ctx context.Context) error {
|
||||
return prompter.PromptURL(ctx, Prompt{
|
||||
Message: "Authorize the GitHub MCP Server in your browser to continue.",
|
||||
URL: authURL,
|
||||
})
|
||||
}
|
||||
return &flowPlan{run: run, display: display, fallback: manual}, nil
|
||||
}
|
||||
|
||||
return &flowPlan{run: run, userAction: manual}, nil
|
||||
}
|
||||
|
||||
// beginDevice prepares the device authorization flow. It requests a device code
|
||||
// up front (so the code can be displayed) and selects a display channel:
|
||||
// URL elicitation, then form elicitation, then a tool-response message.
|
||||
func (m *Manager) beginDevice(prompter Prompter) (*flowPlan, error) {
|
||||
oc := m.oauth2Config("")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), deviceAuthTimeout)
|
||||
defer cancel()
|
||||
da, err := oc.DeviceAuth(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("requesting device code: %w", err)
|
||||
}
|
||||
|
||||
run := func(ctx context.Context) (*oauth2.Token, error) {
|
||||
tok, err := oc.DeviceAccessToken(ctx, da)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("awaiting device authorization: %w", err)
|
||||
}
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// As with PKCE, the manual instructions double as the runtime fallback, so
|
||||
// build them once and reuse for both display plans and the last resort.
|
||||
manual := &UserAction{
|
||||
URL: da.VerificationURI,
|
||||
UserCode: da.UserCode,
|
||||
Message: fmt.Sprintf(
|
||||
"%s\n\nAfter authorizing, retry your request.\n\n%s",
|
||||
deviceInstruction(da), securityAdvisory,
|
||||
),
|
||||
}
|
||||
|
||||
if canPromptURL(prompter) {
|
||||
display := func(ctx context.Context) error {
|
||||
return prompter.PromptURL(ctx, Prompt{
|
||||
Message: fmt.Sprintf("Enter code %s to authorize the GitHub MCP Server.", da.UserCode),
|
||||
URL: da.VerificationURI,
|
||||
UserCode: da.UserCode,
|
||||
})
|
||||
}
|
||||
return &flowPlan{run: run, display: display, fallback: manual}, nil
|
||||
}
|
||||
|
||||
if canPromptForm(prompter) {
|
||||
display := func(ctx context.Context) error {
|
||||
return prompter.PromptForm(ctx, Prompt{
|
||||
Message: deviceInstruction(da),
|
||||
URL: da.VerificationURI,
|
||||
UserCode: da.UserCode,
|
||||
})
|
||||
}
|
||||
return &flowPlan{run: run, display: display, fallback: manual}, nil
|
||||
}
|
||||
|
||||
return &flowPlan{run: run, userAction: manual}, nil
|
||||
}
|
||||
|
||||
// securityAdvisory nudges users on clients without URL elicitation to ask their
|
||||
// vendor for it, since it keeps the authorization URL out of the model context.
|
||||
const securityAdvisory = "Note: your MCP client does not appear to support secure URL elicitation. " +
|
||||
"For improved security, consider asking your agent, CLI, or IDE to add it (for example, by opening an issue)."
|
||||
|
||||
func deviceInstruction(da *oauth2.DeviceAuthResponse) string {
|
||||
return fmt.Sprintf("Visit %s and enter the code %s to authorize the GitHub MCP Server.", da.VerificationURI, da.UserCode)
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// DefaultAuthTimeout bounds how long a single authorization attempt waits for
|
||||
// the user to complete the browser or device flow.
|
||||
const DefaultAuthTimeout = 5 * time.Minute
|
||||
|
||||
// tokenRefreshTimeout bounds each background refresh of an expiring token so a
|
||||
// stalled GitHub token endpoint cannot block a tool call indefinitely.
|
||||
const tokenRefreshTimeout = 30 * time.Second
|
||||
|
||||
// flowStatus tracks the manager's single-flight authorization state.
|
||||
type flowStatus int
|
||||
|
||||
const (
|
||||
statusIdle flowStatus = iota // no flow running
|
||||
statusStarting // a flow is being prepared (brief)
|
||||
statusInProgress // a flow is running on a secure channel; callers may join
|
||||
statusAwaitingUser // a flow is running but the user must act out-of-band
|
||||
)
|
||||
|
||||
// Outcome reports the result of an authorization attempt that did not
|
||||
// immediately yield a token.
|
||||
type Outcome struct {
|
||||
// UserAction, when non-nil, must be surfaced to the user. The authorization
|
||||
// flow continues in the background; the user should retry once they have
|
||||
// completed it.
|
||||
UserAction *UserAction
|
||||
}
|
||||
|
||||
// UserAction is an instruction for the user to complete authorization out of
|
||||
// band (the last-resort channel, used when neither a browser nor URL
|
||||
// elicitation is available).
|
||||
type UserAction struct {
|
||||
// Message is ready to display to the user.
|
||||
Message string
|
||||
// URL is the authorization URL or device verification URI.
|
||||
URL string
|
||||
// UserCode is the device-flow code to enter, if any.
|
||||
UserCode string
|
||||
}
|
||||
|
||||
// Manager owns the OAuth login flows and the resulting (refreshing) token for a
|
||||
// single stdio session. It is safe for concurrent use; only one authorization
|
||||
// flow runs at a time.
|
||||
type Manager struct {
|
||||
config Config
|
||||
refreshConfig *oauth2.Config
|
||||
logger *slog.Logger
|
||||
|
||||
// Test seams, set by NewManager to real implementations.
|
||||
openURL func(string) error
|
||||
inDocker func() bool
|
||||
|
||||
mu sync.Mutex
|
||||
source oauth2.TokenSource // refreshing source, set once authorized
|
||||
status flowStatus
|
||||
pending *UserAction
|
||||
done chan struct{}
|
||||
lastErr error
|
||||
refreshErrLogged bool // true once a refresh failure has been logged, reset on re-auth
|
||||
}
|
||||
|
||||
// NewManager builds a Manager for the given configuration. A nil logger logs to
|
||||
// stderr.
|
||||
func NewManager(cfg Config, logger *slog.Logger) *Manager {
|
||||
if logger == nil {
|
||||
logger = slog.New(slog.NewTextHandler(os.Stderr, nil))
|
||||
}
|
||||
m := &Manager{
|
||||
config: cfg,
|
||||
logger: logger,
|
||||
openURL: openBrowser,
|
||||
inDocker: isRunningInDocker,
|
||||
}
|
||||
m.refreshConfig = m.oauth2Config("")
|
||||
return m
|
||||
}
|
||||
|
||||
// AccessToken returns a currently valid access token, refreshing it if needed,
|
||||
// or "" if the session is not authorized (or a refresh has failed and
|
||||
// re-authorization is required). It is cheap to call repeatedly: the underlying
|
||||
// token source caches and only refreshes when the token has expired.
|
||||
func (m *Manager) AccessToken() string {
|
||||
m.mu.Lock()
|
||||
src := m.source
|
||||
m.mu.Unlock()
|
||||
if src == nil {
|
||||
return ""
|
||||
}
|
||||
// Refresh (if needed) happens here, off the lock, because ReuseTokenSource may
|
||||
// make a blocking network call and holding m.mu would serialize every tool call.
|
||||
tok, err := src.Token()
|
||||
if err != nil {
|
||||
// A refresh failure (expired GitHub App refresh token, revoked grant, or a
|
||||
// network blip) leaves the session unauthorized and forces a re-login.
|
||||
// Surface it once, otherwise it only manifests as a surprise re-authorization
|
||||
// prompt. The oauth2 error carries the token endpoint's response, not the
|
||||
// access or refresh token.
|
||||
m.mu.Lock()
|
||||
if !m.refreshErrLogged {
|
||||
m.refreshErrLogged = true
|
||||
m.logger.Warn("OAuth token refresh failed; re-authorization required", "error", err)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
return ""
|
||||
}
|
||||
if !tok.Valid() {
|
||||
return ""
|
||||
}
|
||||
return tok.AccessToken
|
||||
}
|
||||
|
||||
// HasToken reports whether a valid token is currently available.
|
||||
func (m *Manager) HasToken() bool {
|
||||
return m.AccessToken() != ""
|
||||
}
|
||||
|
||||
// Authenticate ensures the session is authorized.
|
||||
//
|
||||
// It returns (nil, nil) once a token is available, so the caller may proceed.
|
||||
// It returns (&Outcome{UserAction}, nil) when the user must complete the flow
|
||||
// out of band; the flow continues in the background and the caller should show
|
||||
// the action and have the user retry. It returns (nil, err) on failure.
|
||||
//
|
||||
// Only one flow runs at a time. Concurrent callers either join a running secure
|
||||
// flow, receive the pending user action, or are told to retry shortly.
|
||||
func (m *Manager) Authenticate(ctx context.Context, prompter Prompter) (*Outcome, error) {
|
||||
if m.AccessToken() != "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
switch m.status {
|
||||
case statusAwaitingUser:
|
||||
ua := m.pending
|
||||
m.mu.Unlock()
|
||||
return &Outcome{UserAction: ua}, nil
|
||||
case statusStarting:
|
||||
m.mu.Unlock()
|
||||
return &Outcome{UserAction: &UserAction{
|
||||
Message: "GitHub authorization is already in progress. Please retry your request in a few seconds.",
|
||||
}}, nil
|
||||
case statusInProgress:
|
||||
done := m.done
|
||||
m.mu.Unlock()
|
||||
return m.joinWait(ctx, done)
|
||||
}
|
||||
|
||||
// Idle: this call owns the new flow.
|
||||
m.status = statusStarting
|
||||
m.lastErr = nil
|
||||
m.done = make(chan struct{})
|
||||
done := m.done
|
||||
m.mu.Unlock()
|
||||
|
||||
plan, err := m.begin(prompter)
|
||||
if err != nil {
|
||||
m.complete(nil, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
if plan.userAction != nil {
|
||||
m.status = statusAwaitingUser
|
||||
m.pending = plan.userAction
|
||||
} else {
|
||||
m.status = statusInProgress
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
bgCtx, cancel := context.WithTimeout(context.Background(), DefaultAuthTimeout)
|
||||
go m.runFlow(bgCtx, cancel, plan)
|
||||
|
||||
if plan.userAction != nil {
|
||||
return &Outcome{UserAction: plan.userAction}, nil
|
||||
}
|
||||
return m.joinWait(ctx, done)
|
||||
}
|
||||
|
||||
// runFlow executes a prepared flow in the background and records the result. The
|
||||
// optional display prompt runs concurrently: a decline (or other failure) aborts
|
||||
// the flow, while an undeliverable prompt degrades to the manual fallback without
|
||||
// tearing the flow down, so the user can still authorize out of band.
|
||||
func (m *Manager) runFlow(ctx context.Context, cancel context.CancelFunc, plan *flowPlan) {
|
||||
defer cancel()
|
||||
|
||||
if plan.display != nil {
|
||||
go func() {
|
||||
err := plan.display(ctx)
|
||||
switch {
|
||||
case err == nil:
|
||||
// Prompt shown; the flow completes when the token arrives.
|
||||
case ctx.Err() != nil:
|
||||
// The flow is already ending (timed out or cancelled elsewhere),
|
||||
// so there is nothing to fall back to. Checking this before the
|
||||
// fallback also prevents misreading a context-cancelled prompt as
|
||||
// a transport failure.
|
||||
case errors.Is(err, ErrPromptUnavailable) && plan.fallback != nil:
|
||||
// The client advertised the capability but could not deliver the
|
||||
// prompt. Surface the manual instructions instead of failing, and
|
||||
// keep the background flow alive so the user can still authorize.
|
||||
m.logger.Debug("authorization prompt undeliverable; falling back to manual instructions", "reason", err)
|
||||
m.fallBackToUserAction(plan.fallback)
|
||||
default:
|
||||
// A user decline (ErrPromptDeclined) or any other prompt failure
|
||||
// ends the flow.
|
||||
m.logger.Debug("authorization prompt closed", "reason", err)
|
||||
cancel()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
tok, err := plan.run(ctx)
|
||||
m.complete(tok, err)
|
||||
}
|
||||
|
||||
// fallBackToUserAction promotes a running secure flow to the manual user-action
|
||||
// channel after its prompt could not be delivered. The background flow keeps
|
||||
// running, so the user can complete authorization out of band and retry. It is a
|
||||
// no-op if the flow has already resolved.
|
||||
func (m *Manager) fallBackToUserAction(ua *UserAction) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.status != statusInProgress {
|
||||
return
|
||||
}
|
||||
m.status = statusAwaitingUser
|
||||
m.pending = ua
|
||||
// Wake any callers joined on this flow so they receive the action, and clear
|
||||
// done so complete() does not double-close it when run() later finishes.
|
||||
if m.done != nil {
|
||||
close(m.done)
|
||||
m.done = nil
|
||||
}
|
||||
}
|
||||
|
||||
// complete records the flow result, installing a refreshing token source on
|
||||
// success, and wakes any joined callers.
|
||||
func (m *Manager) complete(tok *oauth2.Token, err error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
m.status = statusIdle
|
||||
m.pending = nil
|
||||
if err != nil {
|
||||
m.lastErr = err
|
||||
m.logger.Debug("oauth flow failed", "error", err)
|
||||
} else {
|
||||
m.lastErr = nil
|
||||
// Config.TokenSource returns a ReuseTokenSource that refreshes expired
|
||||
// tokens using the refresh token — this is what makes GitHub App
|
||||
// (expiring) tokens work transparently. The refresh uses a bounded HTTP
|
||||
// client so a stalled token endpoint can't block a tool call forever.
|
||||
refreshCtx := context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{Timeout: tokenRefreshTimeout})
|
||||
m.source = m.refreshConfig.TokenSource(refreshCtx, tok)
|
||||
m.refreshErrLogged = false
|
||||
m.logger.Info("github authorization complete")
|
||||
}
|
||||
if m.done != nil {
|
||||
close(m.done)
|
||||
m.done = nil
|
||||
}
|
||||
}
|
||||
|
||||
// joinWait blocks until the running flow finishes or ctx is cancelled. If the
|
||||
// flow was promoted to the manual channel while waiting (its prompt could not be
|
||||
// delivered), it returns that user action rather than an error.
|
||||
func (m *Manager) joinWait(ctx context.Context, done chan struct{}) (*Outcome, error) {
|
||||
select {
|
||||
case <-done:
|
||||
if m.AccessToken() != "" {
|
||||
return nil, nil
|
||||
}
|
||||
m.mu.Lock()
|
||||
pending := m.pending
|
||||
err := m.lastErr
|
||||
m.mu.Unlock()
|
||||
if pending != nil {
|
||||
return &Outcome{UserAction: pending}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errors.New("authorization did not complete")
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) oauth2Config(redirectURL string) *oauth2.Config {
|
||||
return &oauth2.Config{
|
||||
ClientID: m.config.ClientID,
|
||||
ClientSecret: m.config.ClientSecret,
|
||||
RedirectURL: redirectURL,
|
||||
Scopes: m.config.Scopes,
|
||||
Endpoint: m.config.Endpoint,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// newManager wires a Manager to the fake GitHub server. By default the browser
|
||||
// auto-opens (driving the callback) and Docker detection is off.
|
||||
func newManager(t *testing.T, f *fakeGitHub) *Manager {
|
||||
t.Helper()
|
||||
cfg := Config{
|
||||
ClientID: "client-id",
|
||||
ClientSecret: "client-secret",
|
||||
Scopes: []string{"repo"},
|
||||
Endpoint: f.endpoint(),
|
||||
}
|
||||
m := NewManager(cfg, testLogger())
|
||||
m.openURL = browserGet
|
||||
m.inDocker = func() bool { return false }
|
||||
return m
|
||||
}
|
||||
|
||||
func TestAuthenticatePKCEViaBrowser(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
m := newManager(t, f)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
out, err := m.Authenticate(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, out, "browser flow completes without a user action")
|
||||
assert.Equal(t, "gho_access", m.AccessToken())
|
||||
|
||||
// PKCE must have been exercised end to end.
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
assert.Equal(t, "S256", f.codeChallengeMethod)
|
||||
assert.NotEmpty(t, f.codeChallenge, "authorize must receive a code_challenge")
|
||||
assert.NotEmpty(t, f.codeVerifier, "token exchange must send a code_verifier")
|
||||
assert.Equal(t, []string{"authorization_code"}, f.grants)
|
||||
}
|
||||
|
||||
func TestAuthenticateRefreshesExpiringGitHubAppToken(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
// GitHub App: the initial token expires immediately and carries a refresh
|
||||
// token, so the very next read must refresh transparently.
|
||||
f.authToken = "ghu_initial"
|
||||
f.authRefresh = "ghr_refresh"
|
||||
f.authExpires = 1
|
||||
f.refreshToken = "ghu_refreshed"
|
||||
f.refreshExpires = 3600
|
||||
|
||||
m := newManager(t, f)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := m.Authenticate(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "ghu_refreshed", m.AccessToken(), "expired token must be refreshed")
|
||||
assert.Equal(t, []string{"authorization_code", "refresh_token"}, f.recordedGrants())
|
||||
}
|
||||
|
||||
func TestAuthenticateURLElicitation(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
m := newManager(t, f)
|
||||
m.openURL = func(string) error { return errors.New("no browser") }
|
||||
|
||||
prompter := &fakePrompter{
|
||||
urlCapable: true,
|
||||
onURL: func(_ context.Context, p Prompt) error {
|
||||
return browserGet(p.URL) // user opens the URL and authorizes
|
||||
},
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
out, err := m.Authenticate(ctx, prompter)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, out)
|
||||
assert.Equal(t, "gho_access", m.AccessToken())
|
||||
|
||||
prompter.mu.Lock()
|
||||
defer prompter.mu.Unlock()
|
||||
require.Len(t, prompter.urlCalls, 1)
|
||||
assert.NotEmpty(t, prompter.urlCalls[0].URL)
|
||||
}
|
||||
|
||||
func TestAuthenticateDeclinedPromptFails(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
m := newManager(t, f)
|
||||
m.openURL = func(string) error { return errors.New("no browser") }
|
||||
|
||||
prompter := &fakePrompter{
|
||||
urlCapable: true,
|
||||
onURL: func(_ context.Context, _ Prompt) error {
|
||||
return ErrPromptDeclined
|
||||
},
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := m.Authenticate(ctx, prompter)
|
||||
require.Error(t, err, "declining the prompt must abort the flow")
|
||||
assert.Empty(t, m.AccessToken())
|
||||
}
|
||||
|
||||
func TestAuthenticateUndeliverablePromptFallsBack(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
m := newManager(t, f)
|
||||
m.openURL = func(string) error { return errors.New("no browser") }
|
||||
|
||||
// The client advertised URL elicitation but delivering the prompt fails (a
|
||||
// transport/protocol error, not a user decision). This must degrade to the
|
||||
// manual instructions rather than aborting like a decline does.
|
||||
prompter := &fakePrompter{
|
||||
urlCapable: true,
|
||||
onURL: func(_ context.Context, _ Prompt) error {
|
||||
return ErrPromptUnavailable
|
||||
},
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
out, err := m.Authenticate(ctx, prompter)
|
||||
require.NoError(t, err, "an undeliverable prompt must not abort the flow")
|
||||
require.NotNil(t, out)
|
||||
require.NotNil(t, out.UserAction, "an undeliverable prompt must fall back to a user action")
|
||||
assert.NotEmpty(t, out.UserAction.URL)
|
||||
assert.Contains(t, out.UserAction.Message, securityAdvisory)
|
||||
|
||||
// A concurrent retry while awaiting the user returns the same fallback action.
|
||||
out2, err := m.Authenticate(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out2.UserAction)
|
||||
assert.Equal(t, out.UserAction.URL, out2.UserAction.URL)
|
||||
|
||||
// The background flow stayed alive: opening the URL out of band completes it.
|
||||
require.NoError(t, browserGet(out.UserAction.URL))
|
||||
assert.Equal(t, "gho_access", waitForToken(t, m))
|
||||
}
|
||||
|
||||
func TestAuthenticateLastDitchUserAction(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
m := newManager(t, f)
|
||||
m.openURL = func(string) error { return errors.New("no browser") }
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// No browser and a nil prompter: the only channel left is a user action
|
||||
// returned to the caller.
|
||||
out, err := m.Authenticate(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out)
|
||||
require.NotNil(t, out.UserAction)
|
||||
assert.NotEmpty(t, out.UserAction.URL)
|
||||
assert.Contains(t, out.UserAction.Message, "open this URL")
|
||||
assert.Contains(t, out.UserAction.Message, securityAdvisory,
|
||||
"missing URL elicitation should trigger the security advisory")
|
||||
|
||||
// A concurrent retry while awaiting the user returns the same action, not a
|
||||
// second flow.
|
||||
out2, err := m.Authenticate(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out2.UserAction)
|
||||
assert.Equal(t, out.UserAction.URL, out2.UserAction.URL)
|
||||
|
||||
// The user opens the URL out of band; the background flow then completes.
|
||||
require.NoError(t, browserGet(out.UserAction.URL))
|
||||
assert.Equal(t, "gho_access", waitForToken(t, m))
|
||||
}
|
||||
|
||||
func TestAuthenticateDeviceFlow(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
f.deviceToken = "gho_device_token"
|
||||
m := newManager(t, f)
|
||||
// Inside Docker with a random port, PKCE is impossible, so the device flow
|
||||
// is selected.
|
||||
m.inDocker = func() bool { return true }
|
||||
m.openURL = func(string) error { return errors.New("no browser") }
|
||||
|
||||
prompter := &fakePrompter{urlCapable: true} // shows the code, no action needed
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
out, err := m.Authenticate(ctx, prompter)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, out)
|
||||
assert.Equal(t, "gho_device_token", m.AccessToken())
|
||||
assert.Contains(t, f.recordedGrants(), "urn:ietf:params:oauth:grant-type:device_code")
|
||||
}
|
||||
|
||||
func TestAuthenticateDevicePollingPending(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
f.deviceToken = "gho_device_token"
|
||||
f.devicePending = 1 // one authorization_pending before success
|
||||
m := newManager(t, f)
|
||||
m.inDocker = func() bool { return true }
|
||||
m.openURL = func(string) error { return errors.New("no browser") }
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := m.Authenticate(ctx, &fakePrompter{urlCapable: true})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "gho_device_token", m.AccessToken())
|
||||
}
|
||||
|
||||
func TestAuthenticateHeadlessPrefersDeviceFlow(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
f.deviceToken = "gho_device_token"
|
||||
m := newManager(t, f)
|
||||
// A headless host (no display server) with a random callback port: a PKCE
|
||||
// redirect to this machine's localhost is unreachable from a browser on
|
||||
// another machine, so device flow must be chosen even though the client can
|
||||
// elicit a URL (which would otherwise win over device flow).
|
||||
m.openURL = func(string) error { return errNoDisplay }
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
out, err := m.Authenticate(ctx, &fakePrompter{urlCapable: true})
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, out)
|
||||
assert.Equal(t, "gho_device_token", m.AccessToken())
|
||||
grants := f.recordedGrants()
|
||||
assert.Contains(t, grants, "urn:ietf:params:oauth:grant-type:device_code")
|
||||
assert.NotContains(t, grants, "authorization_code",
|
||||
"headless host must skip the unreachable PKCE authorization-code flow")
|
||||
}
|
||||
|
||||
func TestAuthenticateFixedCallbackPortUnavailableIsFatal(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
m := newManager(t, f)
|
||||
|
||||
// Occupy the fixed callback port so the OAuth listener cannot bind it. A held
|
||||
// port could belong to another user's process that would receive the redirect,
|
||||
// so the flow must fail loudly rather than quietly downgrade to device flow.
|
||||
squatter, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
defer squatter.Close()
|
||||
port := squatter.Addr().(*net.TCPAddr).Port
|
||||
m.config.CallbackPort = port
|
||||
|
||||
// A browser that would have completed PKCE, proving the abort is caused by the
|
||||
// unavailable port and not by a missing display channel.
|
||||
m.openURL = browserGet
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
out, err := m.Authenticate(ctx, &fakePrompter{urlCapable: true})
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, out)
|
||||
assert.Contains(t, err.Error(), strconv.Itoa(port))
|
||||
assert.Empty(t, m.AccessToken())
|
||||
// The decisive check: no device-code grant was attempted, so the flow did not
|
||||
// silently fall back when the deliberately chosen port was unavailable.
|
||||
assert.Empty(t, f.recordedGrants(), "fixed-port bind failure must not fall back to device flow")
|
||||
}
|
||||
|
||||
func TestAuthenticateNoTokenInitially(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
m := newManager(t, f)
|
||||
assert.False(t, m.HasToken())
|
||||
assert.Empty(t, m.AccessToken())
|
||||
}
|
||||
|
||||
func TestAuthenticateSingleFlight(t *testing.T) {
|
||||
f := newFakeGitHub(t)
|
||||
m := newManager(t, f)
|
||||
|
||||
// Hold the owner inside begin() (browser open blocks) so a concurrent caller
|
||||
// observes the in-progress flow rather than starting its own.
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
var once sync.Once
|
||||
m.openURL = func(u string) error {
|
||||
once.Do(func() { close(entered) })
|
||||
<-release
|
||||
return browserGet(u)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
ownerDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := m.Authenticate(ctx, nil)
|
||||
ownerDone <- err
|
||||
}()
|
||||
|
||||
<-entered // owner is now mid-flow with status "starting"
|
||||
|
||||
out, err := m.Authenticate(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, out.UserAction)
|
||||
assert.Contains(t, out.UserAction.Message, "already in progress")
|
||||
|
||||
close(release)
|
||||
require.NoError(t, <-ownerDone)
|
||||
|
||||
assert.Equal(t, "gho_access", waitForToken(t, m))
|
||||
// Exactly one authorization happened despite the concurrent callers.
|
||||
assert.Equal(t, []string{"authorization_code"}, f.recordedGrants())
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Package oauth implements the user-facing OAuth 2.1 login flows the stdio
|
||||
// server uses to obtain a GitHub token without a pre-provisioned Personal
|
||||
// Access Token.
|
||||
//
|
||||
// It supports both GitHub OAuth Apps and GitHub Apps (user-to-server). The
|
||||
// only practical difference is that GitHub App user tokens expire and carry a
|
||||
// refresh token; this package always returns a refreshing [golang.org/x/oauth2.TokenSource]
|
||||
// so callers never have to special-case the app type.
|
||||
//
|
||||
// The package depends only on golang.org/x/oauth2 and the standard library. MCP
|
||||
// concerns (sessions, elicitation) are abstracted behind the [Prompter]
|
||||
// interface so the flows can be tested without a live client.
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// Config describes an OAuth client and the GitHub endpoints it talks to.
|
||||
type Config struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
// Scopes requested during authorization. GitHub Apps ignore these (their
|
||||
// access is governed by installed permissions); OAuth Apps honor them.
|
||||
Scopes []string
|
||||
// Endpoint holds the authorization, token, and device endpoints. Build one
|
||||
// with [GitHubEndpoint].
|
||||
Endpoint oauth2.Endpoint
|
||||
// CallbackPort is the fixed local port for the PKCE callback server. Zero
|
||||
// requests a random port, which is the secure default for native binaries
|
||||
// but cannot be reached through Docker port mapping (see the Manager).
|
||||
CallbackPort int
|
||||
}
|
||||
|
||||
// NewGitHubConfig builds a Config for the given GitHub host. An empty host
|
||||
// targets github.com; otherwise the host may be a GHES or ghe.com hostname,
|
||||
// with or without a scheme.
|
||||
func NewGitHubConfig(clientID, clientSecret string, scopes []string, host string, callbackPort int) Config {
|
||||
return Config{
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
Scopes: scopes,
|
||||
Endpoint: GitHubEndpoint(host),
|
||||
CallbackPort: callbackPort,
|
||||
}
|
||||
}
|
||||
|
||||
// GitHubEndpoint returns the OAuth authorization, token, and device endpoints
|
||||
// for a GitHub host. An empty host targets github.com.
|
||||
func GitHubEndpoint(host string) oauth2.Endpoint {
|
||||
base := NormalizeHost(host)
|
||||
return oauth2.Endpoint{
|
||||
AuthURL: base + "/login/oauth/authorize",
|
||||
TokenURL: base + "/login/oauth/access_token",
|
||||
DeviceAuthURL: base + "/login/device/code",
|
||||
}
|
||||
}
|
||||
|
||||
// NormalizeHost turns a user-supplied host into a scheme+host base URL with no
|
||||
// trailing slash. The API subdomain is stripped because OAuth endpoints live on
|
||||
// the web host, not the API host (api.github.com -> github.com). An empty host
|
||||
// yields the github.com default, so callers can also use it to recognize the
|
||||
// default host (NormalizeHost(host) == "https://github.com").
|
||||
func NormalizeHost(host string) string {
|
||||
host = strings.TrimSpace(host)
|
||||
if host == "" {
|
||||
return "https://github.com"
|
||||
}
|
||||
|
||||
scheme := "https"
|
||||
switch {
|
||||
case strings.HasPrefix(host, "https://"):
|
||||
host = strings.TrimPrefix(host, "https://")
|
||||
case strings.HasPrefix(host, "http://"):
|
||||
scheme = "http"
|
||||
host = strings.TrimPrefix(host, "http://")
|
||||
}
|
||||
|
||||
// Drop any path, query, or fragment; we only need scheme://host.
|
||||
if i := strings.IndexAny(host, "/?#"); i >= 0 {
|
||||
host = host[:i]
|
||||
}
|
||||
|
||||
host = strings.TrimPrefix(host, "api.")
|
||||
|
||||
return fmt.Sprintf("%s://%s", scheme, host)
|
||||
}
|
||||
|
||||
// randomState returns a cryptographically random URL-safe string used as the
|
||||
// OAuth state parameter (CSRF protection) and elicitation IDs.
|
||||
func randomState() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generating random state: %w", err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNormalizeHost(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
host string
|
||||
want string
|
||||
}{
|
||||
{"empty defaults to github.com", "", "https://github.com"},
|
||||
{"bare host", "github.com", "https://github.com"},
|
||||
{"https scheme preserved", "https://github.com", "https://github.com"},
|
||||
{"http scheme preserved", "http://localhost:3000", "http://localhost:3000"},
|
||||
{"api subdomain stripped", "api.github.com", "https://github.com"},
|
||||
{"whitespace trimmed", " github.com ", "https://github.com"},
|
||||
{"path and api stripped", "https://api.github.com/api/v3", "https://github.com"},
|
||||
{"ghes host", "ghe.example.com", "https://ghe.example.com"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, NormalizeHost(tt.host))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitHubEndpoint(t *testing.T) {
|
||||
ep := GitHubEndpoint("")
|
||||
assert.Equal(t, "https://github.com/login/oauth/authorize", ep.AuthURL)
|
||||
assert.Equal(t, "https://github.com/login/oauth/access_token", ep.TokenURL)
|
||||
assert.Equal(t, "https://github.com/login/device/code", ep.DeviceAuthURL)
|
||||
|
||||
ghes := GitHubEndpoint("https://ghe.example.com")
|
||||
assert.Equal(t, "https://ghe.example.com/login/oauth/authorize", ghes.AuthURL)
|
||||
}
|
||||
|
||||
func TestNewGitHubConfig(t *testing.T) {
|
||||
cfg := NewGitHubConfig("client", "secret", []string{"repo", "read:org"}, "", 8085)
|
||||
assert.Equal(t, "client", cfg.ClientID)
|
||||
assert.Equal(t, "secret", cfg.ClientSecret)
|
||||
assert.Equal(t, []string{"repo", "read:org"}, cfg.Scopes)
|
||||
assert.Equal(t, 8085, cfg.CallbackPort)
|
||||
assert.Equal(t, GitHubEndpoint(""), cfg.Endpoint)
|
||||
}
|
||||
|
||||
func TestRandomState(t *testing.T) {
|
||||
s1, err := randomState()
|
||||
require.NoError(t, err)
|
||||
s2, err := randomState()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotEqual(t, s1, s2, "state must be unique per call")
|
||||
assert.NotContains(t, s1, "=", "state must be URL-safe without padding")
|
||||
assert.NotContains(t, s1, "+")
|
||||
assert.NotContains(t, s1, "/")
|
||||
assert.GreaterOrEqual(t, len(s1), 22, "16 random bytes encode to 22 base64url chars")
|
||||
assert.False(t, strings.ContainsAny(s1, " \t\n"))
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// ErrPromptDeclined is returned by a Prompter when the user actively cancels or
|
||||
// declines the authorization prompt. It is a deliberate "no", so the flow stops
|
||||
// rather than falling back to another channel.
|
||||
var ErrPromptDeclined = errors.New("authorization declined by user")
|
||||
|
||||
// ErrPromptUnavailable is returned by a Prompter when the prompt could not be
|
||||
// delivered at all — for example the client advertised an elicitation capability
|
||||
// but the request failed at the transport or protocol level. Unlike
|
||||
// ErrPromptDeclined it reflects no user decision, so the flow falls back to a
|
||||
// channel that needs no client capability instead of giving up.
|
||||
var ErrPromptUnavailable = errors.New("authorization prompt could not be delivered")
|
||||
|
||||
// Prompt is the content shown to the user when asking them to authorize.
|
||||
type Prompt struct {
|
||||
// Message is a human-readable instruction.
|
||||
Message string
|
||||
// URL is the authorization URL (PKCE) or device verification URI.
|
||||
URL string
|
||||
// UserCode is the device-flow code the user must enter, if any.
|
||||
UserCode string
|
||||
}
|
||||
|
||||
// Prompter presents authorization prompts to the user out of band from the LLM
|
||||
// context — for example via MCP elicitation. Keeping prompts out of the model's
|
||||
// context prevents the authorization URL (and any session-bound state) from
|
||||
// leaking into tool arguments or transcripts.
|
||||
//
|
||||
// A nil Prompter is valid and reports no capabilities, which drives the flow to
|
||||
// its last-resort channel. Implementations wrap a transport-specific client
|
||||
// (e.g. an MCP session); see the ghmcp adapter.
|
||||
type Prompter interface {
|
||||
// CanPromptURL reports whether the client can display a URL securely via
|
||||
// URL-mode elicitation.
|
||||
CanPromptURL() bool
|
||||
|
||||
// PromptURL securely presents an authorization URL to the user and blocks
|
||||
// until the user acknowledges, declines, or ctx is done. Returning nil means
|
||||
// the prompt was shown (not that authorization completed); the caller waits
|
||||
// for the OAuth flow itself to finish. It returns ErrPromptDeclined if the
|
||||
// user declines or cancels, or ErrPromptUnavailable if the prompt could not
|
||||
// be delivered.
|
||||
PromptURL(ctx context.Context, p Prompt) error
|
||||
|
||||
// CanPromptForm reports whether the client supports form elicitation, used
|
||||
// to display a device code when URL elicitation is unavailable.
|
||||
CanPromptForm() bool
|
||||
|
||||
// PromptForm presents a textual acknowledgement prompt and blocks until the
|
||||
// user responds. It returns ErrPromptDeclined if the user declines, or
|
||||
// ErrPromptUnavailable if the prompt could not be delivered.
|
||||
PromptForm(ctx context.Context, p Prompt) error
|
||||
}
|
||||
|
||||
// canPromptURL reports URL support, tolerating a nil Prompter.
|
||||
func canPromptURL(p Prompter) bool { return p != nil && p.CanPromptURL() }
|
||||
|
||||
// canPromptForm reports form support, tolerating a nil Prompter.
|
||||
func canPromptForm(p Prompter) bool { return p != nil && p.CanPromptForm() }
|
||||
@@ -0,0 +1,60 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Authorization Failed</title>
|
||||
<style>
|
||||
html, body { height: 100%; margin: 0; }
|
||||
body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif;
|
||||
background-color: #0d1117;
|
||||
color: #e6edf3;
|
||||
}
|
||||
.card {
|
||||
width: 500px;
|
||||
background-color: #161b22;
|
||||
border: 1px solid #30363d;
|
||||
border-radius: 6px;
|
||||
padding: 32px;
|
||||
text-align: center;
|
||||
}
|
||||
.octicon { margin-bottom: 16px; }
|
||||
h1 {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 12px 0;
|
||||
color: #f85149;
|
||||
}
|
||||
p { font-size: 16px; color: #8b949e; margin: 16px 0 0 0; }
|
||||
.flash-error {
|
||||
margin-top: 16px;
|
||||
padding: 12px 16px;
|
||||
background-color: rgba(248, 81, 73, 0.1);
|
||||
border: 1px solid rgba(248, 81, 73, 0.4);
|
||||
border-radius: 6px;
|
||||
}
|
||||
code {
|
||||
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
|
||||
font-size: 14px;
|
||||
color: #f85149;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="80" height="80" fill="currentColor">
|
||||
<path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path>
|
||||
</svg>
|
||||
<h1>Authorization Failed</h1>
|
||||
<div class="flash-error">
|
||||
<code>{{.ErrorMessage}}</code>
|
||||
</div>
|
||||
<p>You can close this window.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,56 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Authorization Successful</title>
|
||||
<style>
|
||||
html, body { height: 100%; margin: 0; }
|
||||
body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif;
|
||||
background-color: #0d1117;
|
||||
color: #e6edf3;
|
||||
}
|
||||
.card {
|
||||
width: 500px;
|
||||
background-color: #161b22;
|
||||
border: 1px solid #30363d;
|
||||
border-radius: 6px;
|
||||
padding: 32px;
|
||||
text-align: center;
|
||||
}
|
||||
.octicon { margin-bottom: 16px; }
|
||||
h1 {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 12px 0;
|
||||
color: #3fb950;
|
||||
}
|
||||
p { font-size: 16px; color: #8b949e; margin: 0; }
|
||||
.flash {
|
||||
margin-top: 16px;
|
||||
padding: 12px 16px;
|
||||
background-color: rgba(56, 139, 253, 0.15);
|
||||
border: 1px solid rgba(56, 139, 253, 0.4);
|
||||
border-radius: 6px;
|
||||
}
|
||||
.flash p { font-size: 14px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="80" height="80" fill="currentColor">
|
||||
<path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path>
|
||||
</svg>
|
||||
<h1>Authorization Successful</h1>
|
||||
<p>You have successfully authorized the GitHub MCP Server.</p>
|
||||
<div class="flash">
|
||||
<p>You can close this window and retry your request.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,216 @@
|
||||
package oauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// fakeGitHub is an httptest-backed stand-in for GitHub's OAuth endpoints. It
|
||||
// implements the authorize redirect, the token endpoint (authorization_code,
|
||||
// refresh_token, and device_code grants), and the device-code endpoint, while
|
||||
// recording what it received so tests can assert on real protocol behavior
|
||||
// (PKCE challenge/verifier, grant sequence) rather than re-implementing it.
|
||||
type fakeGitHub struct {
|
||||
*httptest.Server
|
||||
|
||||
mu sync.Mutex
|
||||
grants []string // grant_type of each token request, in order
|
||||
codeChallenge string
|
||||
codeChallengeMethod string
|
||||
codeVerifier string
|
||||
devicePending int // number of authorization_pending responses before success
|
||||
|
||||
// Token values returned per grant. A positive expires field is sent as
|
||||
// expires_in (and makes the token expiring/refreshable).
|
||||
authToken string
|
||||
authRefresh string
|
||||
authExpires int
|
||||
refreshToken string
|
||||
refreshExpires int
|
||||
deviceToken string
|
||||
}
|
||||
|
||||
func newFakeGitHub(t *testing.T) *fakeGitHub {
|
||||
t.Helper()
|
||||
f := &fakeGitHub{
|
||||
authToken: "gho_access",
|
||||
deviceToken: "gho_device",
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/login/oauth/authorize", f.handleAuthorize)
|
||||
mux.HandleFunc("/login/oauth/access_token", f.handleToken)
|
||||
mux.HandleFunc("/login/device/code", f.handleDeviceCode)
|
||||
|
||||
f.Server = httptest.NewServer(mux)
|
||||
t.Cleanup(f.Server.Close)
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeGitHub) endpoint() oauth2.Endpoint {
|
||||
return oauth2.Endpoint{
|
||||
AuthURL: f.URL + "/login/oauth/authorize",
|
||||
TokenURL: f.URL + "/login/oauth/access_token",
|
||||
DeviceAuthURL: f.URL + "/login/device/code",
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeGitHub) handleAuthorize(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
f.mu.Lock()
|
||||
f.codeChallenge = q.Get("code_challenge")
|
||||
f.codeChallengeMethod = q.Get("code_challenge_method")
|
||||
f.mu.Unlock()
|
||||
|
||||
redirect := q.Get("redirect_uri") + "?code=authcode&state=" + url.QueryEscape(q.Get("state"))
|
||||
http.Redirect(w, r, redirect, http.StatusFound)
|
||||
}
|
||||
|
||||
func (f *fakeGitHub) handleToken(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
grant := r.Form.Get("grant_type")
|
||||
|
||||
f.mu.Lock()
|
||||
f.grants = append(f.grants, grant)
|
||||
switch grant {
|
||||
case "authorization_code":
|
||||
f.codeVerifier = r.Form.Get("code_verifier")
|
||||
f.mu.Unlock()
|
||||
writeToken(w, f.authToken, f.authRefresh, f.authExpires)
|
||||
case "refresh_token":
|
||||
f.mu.Unlock()
|
||||
writeToken(w, f.refreshToken, "", f.refreshExpires)
|
||||
case "urn:ietf:params:oauth:grant-type:device_code":
|
||||
pending := f.devicePending
|
||||
if pending > 0 {
|
||||
f.devicePending--
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if pending > 0 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "authorization_pending"})
|
||||
return
|
||||
}
|
||||
writeToken(w, f.deviceToken, "", 0)
|
||||
default:
|
||||
f.mu.Unlock()
|
||||
http.Error(w, "unsupported grant_type", http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeGitHub) handleDeviceCode(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"device_code": "devicecode",
|
||||
"user_code": "ABCD-1234",
|
||||
"verification_uri": f.URL + "/device",
|
||||
"expires_in": 900,
|
||||
"interval": 1,
|
||||
})
|
||||
}
|
||||
|
||||
func (f *fakeGitHub) recordedGrants() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.grants...)
|
||||
}
|
||||
|
||||
func writeToken(w http.ResponseWriter, access, refresh string, expiresIn int) {
|
||||
body := map[string]any{
|
||||
"access_token": access,
|
||||
"token_type": "bearer",
|
||||
}
|
||||
if refresh != "" {
|
||||
body["refresh_token"] = refresh
|
||||
}
|
||||
if expiresIn != 0 {
|
||||
body["expires_in"] = expiresIn
|
||||
}
|
||||
writeJSON(w, http.StatusOK, body)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body map[string]any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
|
||||
// fakePrompter is a configurable Prompter. The on* hooks simulate the user
|
||||
// acting on the prompt; a nil hook means the prompt is shown and acknowledged.
|
||||
type fakePrompter struct {
|
||||
urlCapable bool
|
||||
formCapable bool
|
||||
onURL func(context.Context, Prompt) error
|
||||
onForm func(context.Context, Prompt) error
|
||||
|
||||
mu sync.Mutex
|
||||
urlCalls []Prompt
|
||||
}
|
||||
|
||||
func (p *fakePrompter) CanPromptURL() bool { return p.urlCapable }
|
||||
|
||||
func (p *fakePrompter) PromptURL(ctx context.Context, prompt Prompt) error {
|
||||
p.mu.Lock()
|
||||
p.urlCalls = append(p.urlCalls, prompt)
|
||||
p.mu.Unlock()
|
||||
if p.onURL != nil {
|
||||
return p.onURL(ctx, prompt)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *fakePrompter) CanPromptForm() bool { return p.formCapable }
|
||||
|
||||
func (p *fakePrompter) PromptForm(ctx context.Context, prompt Prompt) error {
|
||||
if p.onForm != nil {
|
||||
return p.onForm(ctx, prompt)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// browserGet simulates a user completing the authorization-code flow by opening
|
||||
// the URL: it follows the authorize redirect to the local callback, delivering
|
||||
// the code to the manager's callback server. Used both as an openURL seam and
|
||||
// inside prompter hooks.
|
||||
func browserGet(rawurl string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawurl, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
return resp.Body.Close()
|
||||
}
|
||||
|
||||
func testLogger() *slog.Logger {
|
||||
return slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
}
|
||||
|
||||
// waitForToken polls until the manager has a token or the deadline passes. The
|
||||
// authorization-code flow completes asynchronously after the callback fires, so
|
||||
// tests wait for the resulting token rather than sleeping a fixed duration.
|
||||
func waitForToken(t *testing.T, m *Manager) string {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if tok := m.AccessToken(); tok != "" {
|
||||
return tok
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("timed out waiting for access token")
|
||||
return ""
|
||||
}
|
||||
Reference in New Issue
Block a user