Skip to content

Go implementation of DeepSeek Harness and self-hosted personal agent.

Go
6.4 KB
Raw Blame
package mcpclient

import (
	"context"
	"net/http"
	"net/url"
	"slices"
	"strings"
	"testing"
	"time"

	mcpconfig "go-bot/mcp"
)

type oauthChallengeTransport struct {
	resource, scope string
}

func (t oauthChallengeTransport) RoundTrip(request *http.Request) (*http.Response, error) {
	response, err := http.DefaultTransport.RoundTrip(request)
	if err == nil && request.URL.String() == t.resource && response.StatusCode == http.StatusUnauthorized && t.scope != "" {
		response.Header.Set("WWW-Authenticate", response.Header.Get("WWW-Authenticate")+`, scope="`+t.scope+`"`)
	}
	return response, err
}

func TestOAuthUsesConfiguredOrChallengeScopeWithoutInferringAdditionalAccess(t *testing.T) {
	empty, configured := "", "configured-only"
	for _, scenario := range []struct {
		name, challenge, expected string
		configured                *string
	}{
		{"no-scope", "", "", nil},
		{"challenge", "challenge-only", "challenge-only", nil},
		{"explicit-empty", "challenge-only", "", &empty},
		{"configured", "challenge-only", "configured-only", &configured},
	} {
		t.Run(scenario.name, func(t *testing.T) {
			f := oauthServiceFixture(t)
			manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir(), Connection: ConnectionOptions{HTTPClient: &http.Client{
				Transport: oauthChallengeTransport{resource: f.resource.URL + "/mcp", scope: scenario.challenge},
			}}})
			defer manager.Close()
			settings := f.settings("fixture")
			settings.Servers["oauth"].OAuth.Scope = scenario.configured
			if _, err := manager.Apply(t.Context(), settings); err != nil {
				t.Fatal(err)
			}
			ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
			defer cancel()
			view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")
			if err != nil {
				t.Fatal(err)
			}
			parsed, err := url.Parse(view.URL)
			if err != nil || parsed.Query().Get("scope") != scenario.expected {
				t.Fatal("scope inference differs from upstream", parsed.Query().Get("scope"), err)
			}
		})
	}
}

func TestOAuthClientKeyMatchesUpstreamJSONIdentity(t *testing.T) {
	manager := &Manager{}
	entry := &serverEntry{name: "original", owner: "plugin:handle", config: mcpconfig.Server{
		URL: "https://resource.example/mcp?x=1&y=2", OAuth: &mcpconfig.OAuth{CredentialKey: "mcp-client/mail"},
	}}
	// Generated by the upstream JSON.stringify tuple + SHA256 expression;
	// omission produces null, and URL '&' must not become an HTML escape.
	key := manager.oauthClientKey(entry, "https://issuer.example/", "http://127.0.0.1:9090/callback")
	if key != "mcp-client/mail-client-eff213c4fed6766933aeaad656408665f95f020b0f93543167e44a3f4eaa9275" {
		t.Fatal("client registration key differs from upstream", key)
	}
	entry.name, entry.owner = "renamed", "another-plugin:another-handle"
	entry.config.OAuth.ClientSecret = "rotated-secret"
	if got := manager.oauthClientKey(entry, "https://issuer.example/", "http://127.0.0.1:9090/callback"); got != key {
		t.Fatal("runtime ownership or secret rotation changed client identity")
	}
	empty := ""
	entry.config.OAuth.ClientID, entry.config.OAuth.Scope = "public", &empty
	if got := manager.oauthClientKey(entry, "https://issuer.example/", "http://127.0.0.1:9090/callback"); got != "mcp-client/mail-client-0ff30b886fa63a547940d1c6a5331308c5e78540a4ace5dbf9f906ed2422cc84" {
		t.Fatal("configured empty scope was treated as omitted", got)
	}
}

func TestOAuthGrantBindingUsesOnlyUpstreamConfigurationIdentity(t *testing.T) {
	manager := &Manager{}
	server := mcpconfig.Server{URL: "https://resource.example/mcp", OAuth: &mcpconfig.OAuth{CredentialKey: "mcp-client/mail"}}
	bound := manager.oauthConfigBinding("mail", "first:handle", server)
	budget := int64(500)
	server.OAuth.RequestTimeoutMS = &budget
	server.OAuth.ClientSecret = "new-client-secret"
	if got := manager.oauthConfigBinding("renamed", "other:handle", server); got != bound {
		t.Fatal("operational options invalidated a compatible grant")
	}
	for _, change := range []func(*mcpconfig.Server){
		func(s *mcpconfig.Server) { s.URL += "/other" },
		func(s *mcpconfig.Server) { s.OAuth.ClientID = "different" },
		func(s *mcpconfig.Server) { empty := ""; s.OAuth.Scope = &empty },
	} {
		copy := server
		oauth := *server.OAuth
		copy.OAuth = &oauth
		change(&copy)
		if got := manager.oauthConfigBinding("mail", "first:handle", copy); got == bound {
			t.Fatal("different endpoint, client or scope reused the grant")
		}
	}
}

func TestOAuthOriginalScopeAndBudgetsReachActualAuthorization(t *testing.T) {
	f := oauthServiceFixture(t)
	manager := NewManager(t.Context(), ManagerOptions{CWD: t.TempDir()})
	defer manager.Close()
	settings := f.settings("test-client")
	server := settings.Servers["oauth"]
	scope, requestMS, authorizationMS := "read custom", int64(700), int64(800)
	server.OAuth.Scope = &scope
	server.OAuth.RequestTimeoutMS = &requestMS
	server.OAuth.AuthorizationTimeoutMS = &authorizationMS
	settings.Servers["oauth"] = server
	if _, err := manager.Apply(t.Context(), settings); err != nil {
		t.Fatal(err)
	}
	if client := manager.oauthHTTPClient(server.OAuth); client.Timeout != 700*time.Millisecond {
		t.Fatal("configured request budget ignored", client.Timeout)
	}
	if manager.oauthHTTPClient(nil).Timeout != 10*time.Second || oauthAuthorizationTimeout(nil) != 10*time.Minute {
		t.Fatal("OAuth defaults differ from upstream")
	}
	ctx, cancel := context.WithTimeout(t.Context(), 4*time.Second)
	defer cancel()
	view, err := manager.Authorize(ctx, "oauth", "http://127.0.0.1:9090"+mcpconfig.OAuthCallbackPath+"alice")
	if err != nil {
		t.Fatal(err)
	}
	authorizationURL, err := url.Parse(view.URL)
	if err != nil {
		t.Fatal(err)
	}
	actualScopes, expectedScopes := strings.Fields(authorizationURL.Query().Get("scope")), strings.Fields(scope)
	// OAuth scopes form a set. The Go SDK's union uses map iteration order,
	// so wire ordering is not a permission difference.
	slices.Sort(actualScopes)
	slices.Sort(expectedScopes)
	if !slices.Equal(actualScopes, expectedScopes) {
		t.Fatal("original singular scope was not sent to the authorization server", err)
	}
	for ctx.Err() == nil {
		manager.mu.RLock()
		attempt := manager.authorizations["oauth"]
		manager.mu.RUnlock()
		select {
		case <-attempt.done:
			manager.mu.RLock()
			state := attempt.view.State
			manager.mu.RUnlock()
			if state != "expired" {
				t.Fatal("browser deadline did not expire the actual flow", state)
			}
			return
		case <-ctx.Done():
			t.Fatal("configured browser deadline was ignored", ctx.Err())
		}
	}
}