Repository navigation
Description
Description
Phase 1 of the DCR story (#4976). Rename the existing pkg/oauth leaf package to pkg/oauthproto, move the RFC 7591 Dynamic Client Registration primitives out of pkg/auth/oauth/dynamic_registration.go into pkg/oauthproto/dcr.go, and relocate the handful of helpers (IsLocalhost, UserAgent) they depend on so that pkg/oauthproto/ stays a true leaf package (no pkg/networking import). This unblocks Phase 2: once the rename lands, pkg/authserver/ can import the DCR client without creating an import cycle.
Context
Today, DCR primitives live in pkg/auth/oauth/dynamic_registration.go, which transitively imports pkg/networking. The authserver cannot import pkg/auth/oauth without creating a cycle, so there is no path for pkg/authserver/ to reuse the DCR client. This task solves that by preserving the pkg/oauth leaf-package invariant under a new name (pkg/oauthproto) and moving only the pure protocol primitives into it. FetchAuthorizationServerMetadata, DCRUpstreamConfig, and the authserver wiring are deliberately deferred to Phase 2 (#4978).
Key design points carried into this task:
pkg/oauthproto/must remain a leaf package.IsLocalhostis therefore relocated intopkg/oauthproto/(as a privateisLoopbackHost), andpkg/networkingimports it back out rather than the other way around. This keeps thepkg/oauthprotodep graph pointing atnet/url/errors/fositeonly.RegisterClientDynamicallytakes*http.Clientdirectly (nil means "build a default one"). The privateregisterClientDynamicallyWithClienthelper and thenetworking.HTTPClientinterface indirection are dropped in this move.- The CLI-specific error string in
handleHTTPResponse(referencing--remote-auth-client-id/--remote-auth-client-secret) is generalized before the move, because the protocol package must not leak CLI assumptions. - The CLI-side
NewDynamicClientRegistrationRequest(scopes, callbackPort)helper — which hardcodeshttp://localhost:<port>/callback— stays out of the protocol package and is hosted inpkg/auth/discovery/, its sole caller. UserAgent = "ToolHive/1.0"constant moves out ofpkg/auth/oauth/oidc.go:24intopkg/oauthproto/constants.goso the moved DCR code and any future leaf-package HTTP builders can share it.
The existing pkg/oauth/doc.go documents the leaf-package invariant that the rename preserves.
Dependencies: #4976 (parent story only — no technical task dependency)
Blocks: #4978 (authserver DCR integration cannot import pkg/oauthproto until this rename lands)
Acceptance Criteria
-
pkg/oauth/directory is renamed topkg/oauthproto/; all 17 call sites that importgithub.com/stacklok/toolhive/pkg/oauthare updated to importgithub.com/stacklok/toolhive/pkg/oauthproto(the 8 that already alias asoauthprotocan drop the alias). -
pkg/auth/oauth/dynamic_registration.gois deleted; its content (types, constructors,RegisterClientDynamically, validation helpers,handleHTTPResponse,ToolHiveMCPClientName, andScopeListJSON codec) lives inpkg/oauthproto/dcr.go. -
pkg/auth/oauth/dynamic_registration_test.gois deleted; tests that cover the moved functions live inpkg/oauthproto/dcr_test.goand pass from the new location. -
grep -r "pkg/auth/oauth/dynamic_registration"returns no hits across the repository (including Go files, docs, and planning artifacts). -
RegisterClientDynamicallysignature isfunc(ctx context.Context, registrationEndpoint string, request *DynamicClientRegistrationRequest, client *http.Client) (*DynamicClientRegistrationResponse, error)— takes*http.Clientdirectly (nil for default); the privateregisterClientDynamicallyWithClienthelper is removed; thenetworking.HTTPClientinterface is no longer referenced from DCR code. -
IsLocalhostis relocated out ofpkg/networking/utilities.go:99-106and hosted privately insidepkg/oauthproto/(e.g.,isLoopbackHost).pkg/networkingimports it back through the exported wrapper so existing callers outside this task's scope are unaffected.pkg/oauthproto/has nogithub.com/stacklok/toolhive/pkg/networkingimport. -
UserAgentconstant is moved frompkg/auth/oauth/oidc.go:24intopkg/oauthproto/constants.goand all references to it resolve to the new location. - The CLI-specific hint string in
handleHTTPResponse(currently suggesting--remote-auth-client-id/--remote-auth-client-secretflags) is rewritten to a protocol-neutral message before the function moves intopkg/oauthproto/dcr.go. -
pkg/auth/discovery/hostsNewDynamicClientRegistrationRequest(scopes []string, callbackPort int) *oauthproto.DynamicClientRegistrationRequest(the sole caller isregisterDynamicClientatpkg/auth/discovery/discovery.go:~720); the factory no longer lives inpkg/auth/oauth/. -
pkg/oauthproto/doc.gois updated to reflect the expanded (still leaf-package) surface area. -
go build ./...succeeds with no import cycles. -
task testpasses; all moved tests run frompkg/oauthproto/and exercise the same behavior they covered inpkg/auth/oauth/. -
task lint-fixreports no findings. -
task license-checkis clean. Any new files written inpkg/oauthproto/use the 2-line SPDX header style documented in.claude/rules/go-style.md; existing 13-line Apache header blocks on moved files are preserved unless the file is being rewritten in full. - Code reviewed and approved.
Technical Approach
Recommended Implementation
Do the rename and the move in a single PR where possible (the plan treats Phase 1 as one unit, and the diff should stay comfortably under the 400-LOC / 10-file cap). Order matters — do it in roughly this sequence so intermediate go build failures are contained:
- Rename the directory
pkg/oauth/->pkg/oauthproto/and update thepackage oauthline at the top of every file topackage oauthproto. Fix the package doc indoc.go. - Update call-site imports across the 17 files that import
pkg/oauth. The 8 sites already using theoauthproto "github.com/stacklok/toolhive/pkg/oauth"alias can drop the alias. Use one commit per logical area (upstream, auth/oauth, auth/discovery, server/handlers, etc.) if that makes review easier, but keep the PR singular. - Move
UserAgentfrompkg/auth/oauth/oidc.go:24intopkg/oauthproto/constants.go. Update the three referencing call sites (grep forUserAgentinsidepkg/auth/oauth/first). - Relocate
IsLocalhostintopkg/oauthproto/as privateisLoopbackHost. Changepkg/networking/utilities.goso the package-levelIsLocalhostwraps the new private helper via an exported pass-through (func IsLocalhost(host string) bool { return oauthproto.IsLoopbackHost(host) }— or export it frompkg/oauthprotoif the call surface warrants it). Verifypkg/oauthprotostill has nopkg/networkingimport. - Generalize
handleHTTPResponseerror string inpkg/auth/oauth/dynamic_registration.gobefore moving the file — replace the CLI-flag-specific hint ("Please configure OAuth client credentials using --remote-auth-client-id…") with a protocol-neutral message (e.g., "the provider does not support RFC 7591 Dynamic Client Registration; configure client credentials out of band"). Land this as part of the same PR; keeping it as a separate prep commit inside the PR is fine. - Move the DCR content from
pkg/auth/oauth/dynamic_registration.gotopkg/oauthproto/dcr.go. KeepToolHiveMCPClientName,DynamicClientRegistrationRequest,DynamicClientRegistrationResponse,ScopeList(with itsMarshalJSON/UnmarshalJSON— preserve verbatim),validateRegistrationEndpoint,validateAndSetDefaults,createHTTPRequest,handleHTTPResponse, andRegisterClientDynamically. DropgetHTTPClient(networking.HTTPClient)andregisterClientDynamicallyWithClient. Delete the original file. - Collapse the client-injection seam on
RegisterClientDynamically— its new signature takes*http.Client(nil means build the default 30s/10s/10s client inline). Tests that previously used a mocknetworking.HTTPClientswap tohttptest.NewServer(already the idiom in the existingdynamic_registration_test.go) plus a realhttp.Clientpointed at the test server. - Host the CLI factory — create
NewDynamicClientRegistrationRequest(scopes, callbackPort)insidepkg/auth/discovery/(the sole caller). UpdateregisterDynamicClientatpkg/auth/discovery/discovery.go:~720to call the local factory andoauthproto.RegisterClientDynamicallydirectly. The CLI factory retains thehttp://localhost:<port>/callbackredirect URI assumption that does not belong in the protocol package. - Move the tests.
pkg/auth/oauth/dynamic_registration_test.go→pkg/oauthproto/dcr_test.gowith packageoauthproto_test(external test package to mirror the public API shape). Keep the existinghttptest.NewServerstructure. Drop any test that exercised the removedregisterClientDynamicallyWithCliententry point; rewrite the equivalent case to usehttptest.NewServerand the real*http.Clientparameter. - Update
pkg/oauthproto/doc.goso the package comment mentions both the pre-existing protocol surface (RFC 8414 types, redirect policy, well-known paths) and the new DCR surface (RFC 7591 request/response types,RegisterClientDynamically,ScopeList,UserAgent,ToolHiveMCPClientName). Reassert the leaf-package invariant in the doc comment. - Verify. Run
task build,task test,task lint-fix, andtask license-check. Run the explicit grep checks listed in Acceptance Criteria. Confirmpkg/oauthprotohas nopkg/networkingimport (a quickgrep -r "pkg/networking" pkg/oauthprotosanity check).
Patterns & Frameworks
- Plain
testing+github.com/stretchr/testifyfor unit tests. The existing unit tests inpkg/oauth/,pkg/auth/*, andpkg/authserver/*do not use Ginkgo — match that convention. Userequire.NoErrorovert.Fatal; table-driven tests where input permutations matter. httptest.NewServerfor HTTP mocking — already the idiom inpkg/auth/oauth/dynamic_registration_test.go:1-80. Register teardown witht.Cleanup(server.Close), notdefer, when the test usest.Parallel().- Standard-library only for URL handling in
pkg/oauthproto/(net/url,errors).fositeis already pulled in viapkg/oauthproto/redirect.go's redirect-URI helpers and stays. - SPDX headers per
.claude/rules/go-style.md: 2-line style on new files written inpkg/oauthproto/; leave existing 13-line Apache headers on moved files alone unless the diff rewrites the whole file. Runtask license-fixiftask license-checkcomplains. - Always drive builds/tests/lint through
task(task build,task test,task lint-fix,task license-check) perCLAUDE.md. Nevergo test ./...orgolangci-lint rundirectly. - Commit-message style: imperative mood, capitalized subject, no trailing period, 50-char limit, no conventional-commit prefixes (
CLAUDE.md).
Code Pointers
pkg/oauth/— current leaf package. Rename in place topkg/oauthproto/; update thepackageline in every.gofile. Preserve the existing 13-line Apache headers on these files.pkg/oauth/doc.go— rewrite the package comment to describe the expanded scope (types + constants + DCR client). Reassert the "leaf package, nopkg/networkingdep" invariant.pkg/auth/oauth/dynamic_registration.go(352 LOC) — canonical content to move.ToolHiveMCPClientName(L23),DynamicClientRegistrationRequest(L26-36),NewDynamicClientRegistrationRequest(L39-53 — stays inpkg/auth/discovery/, does not move topkg/oauthproto/),ScopeList+ codec (L70-132 — preserve verbatim),DynamicClientRegistrationResponse(L135-153),RegisterClientDynamically(L156-162 — new signature takes*http.Client), validators (L165-211),createHTTPRequest(L214-237),getHTTPClient(L240-252 — delete, fold the default-client creation intoRegisterClientDynamically),handleHTTPResponse(L255-307 — generalize the error string at L275-278 before moving),registerClientDynamicallyWithClient(L310-351 — delete; inline its body intoRegisterClientDynamically).pkg/auth/oauth/dynamic_registration_test.go— tests moved topkg/oauthproto/dcr_test.go. Change package fromoauth_testtooauthproto_test. Convert any mock-networking.HTTPClienttests tohttptest.NewServer+ real*http.Client.pkg/auth/oauth/oidc.go:24—UserAgent = "ToolHive/1.0"moves topkg/oauthproto/constants.go. Update three in-tree references (grep first).pkg/auth/discovery/discovery.go:720—registerDynamicClientupdated to call a locally-hostedNewDynamicClientRegistrationRequestandoauthproto.RegisterClientDynamically. Add the factory in this package (same file or a newdcr_request.go).pkg/networking/utilities.go:99-106—IsLocalhostrelocated intopkg/oauthproto/asisLoopbackHost(or an exportedIsLoopbackHostif callers outsidepkg/networkingneed it). Thepkg/networking.IsLocalhostsymbol remains as a thin wrapper to avoid touching the existing external callers (6+ sites across the repo).pkg/auth/discovery/discovery.go:745-812— template (FetchResourceMetadata) for the futureFetchAuthorizationServerMetadatain Authserver DCR integration (Phase 2, Steps 2a-2g) #4978; reference only, not changed here.
Component Interfaces
// pkg/oauthproto/dcr.go
// ToolHiveMCPClientName is advertised in dynamic client registration requests.
const ToolHiveMCPClientName = "ToolHive MCP Client"
// DynamicClientRegistrationRequest (RFC 7591). Shape unchanged from pkg/auth/oauth.
type DynamicClientRegistrationRequest struct {
RedirectURIs []string `json:"redirect_uris"`
ClientName string `json:"client_name,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
Scopes ScopeList `json:"scope,omitempty"`
}
// DynamicClientRegistrationResponse (RFC 7591 + RFC 7592 fields). Shape unchanged.
type DynamicClientRegistrationResponse struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret,omitempty"` //nolint:gosec
ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"`
ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
RegistrationAccessToken string `json:"registration_access_token,omitempty"`
RegistrationClientURI string `json:"registration_client_uri,omitempty"`
ClientName string `json:"client_name,omitempty"`
RedirectURIs []string `json:"redirect_uris,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
Scopes ScopeList `json:"scope,omitempty"`
}
// RegisterClientDynamically performs RFC 7591 Dynamic Client Registration.
// If client is nil, a default http.Client with 30s timeout / 10s TLS handshake
// / 10s response header timeout is used.
func RegisterClientDynamically(
ctx context.Context,
registrationEndpoint string,
request *DynamicClientRegistrationRequest,
client *http.Client,
) (*DynamicClientRegistrationResponse, error)
// ScopeList handles the RFC 7591 scope-field ambiguity (string vs. array on the
// wire, []string in Go). Marshal/Unmarshal preserved verbatim from the previous
// location in pkg/auth/oauth.
type ScopeList []string// pkg/oauthproto/constants.go
// (additions to the existing file)
// UserAgent is sent on all HTTP requests originating from this package.
const UserAgent = "ToolHive/1.0"// pkg/oauthproto/locality.go (or folded into an existing file)
// isLoopbackHost reports whether host is a loopback hostname.
// Kept private to preserve the leaf-package invariant — pkg/networking exposes
// the public IsLocalhost wrapper for legacy callers.
func isLoopbackHost(host string) bool// pkg/auth/discovery/dcr_request.go (or adjacent to the sole caller)
// NewDynamicClientRegistrationRequest constructs a DCR request for the CLI flow,
// which always uses an http://localhost:<port>/callback redirect URI (loopback
// public client per RFC 8252).
func NewDynamicClientRegistrationRequest(
scopes []string,
callbackPort int,
) *oauthproto.DynamicClientRegistrationRequestTesting Strategy
Unit Tests (in pkg/oauthproto/dcr_test.go, package oauthproto_test):
-
RegisterClientDynamicallyhappy path against anhttptest.NewServerreturning a 201 JSON body withclient_id,client_secret, and echoed request fields. -
RegisterClientDynamicallywithclient == nilbuilds the default*http.Client(no panic; request lands on the test server — bind to a loopback host sovalidateRegistrationEndpointaccepts the HTTP URL). -
RegisterClientDynamicallywith a caller-supplied*http.Client(pointed athttptest.NewServer) demonstrates the non-default client path. -
validateRegistrationEndpointrejects non-HTTPS non-loopback URLs, accepts localhost HTTP URLs, and rejects malformed URLs. -
validateAndSetDefaultsrejects nil request, emptyRedirectURIs, and scope values containing spaces; fills in defaults forClientName,GrantTypes,ResponseTypes,TokenEndpointAuthMethodwhen omitted. -
handleHTTPResponsemaps 404/405/501 to the new protocol-neutral "provider does not support DCR" error (verify the CLI-flag hint is absent from the error string — this is the regression guard for the generalization step). -
handleHTTPResponserejects non-JSON content types, caps body size viaio.LimitReader, and requiresclient_idon success. -
ScopeList.UnmarshalJSONcovers the four shapes documented in the type's doc comment: space-delimited string, JSON array, null, empty/whitespace.MarshalJSONround-trips. -
isLoopbackHostcoverslocalhost,localhost:8080,127.0.0.1,127.0.0.1:1,[::1],[::1]:80, plus negative cases (e.g.,example.com,127.0.0.1.example.com).
Integration Tests
- No new integration tests in this task — Authserver DCR integration (Phase 2, Steps 2a-2g) #4978 extends
pkg/authserver/integration_test.goto cover the DCR path end-to-end once the authserver wiring exists.
Edge Cases
-
pkg/oauthprotobuilds standalone withgo build ./pkg/oauthproto/...(nopkg/networkingtransitive dep — verify viago list -deps ./pkg/oauthproto/...that the networking path is absent). -
pkg/auth/discovery/still compiles after the factory move; the CLI flow atpkg/auth/discovery/discovery.go:720produces an identical request body as before (diff the on-wire JSON to confirm no behavioral drift in the move). - The 8 call sites that already alias
pkg/oauthasoauthprotodrop the alias cleanly — no dangling aliases left behind.
Out of Scope
FetchAuthorizationServerMetadataand the three-path RFC 8414 discovery fallback (deferred to Authserver DCR integration (Phase 2, Steps 2a-2g) #4978 Phase 2).DCRUpstreamConfig,resolveDCRCredentials,DCRResolution,DCRCredentialStoreinterface / in-memory stub, and authserver wiring (all Phase 2 — Authserver DCR integration (Phase 2, Steps 2a-2g) #4978).- Persistent
DCRCredentialStorebackends (memory + Redis) — Phase 3, Persistent DCRCredentialStore backends (memory + Redis) #4979. - Log-level upgrade at
pkg/authserver/server/handlers/dcr.go:98, stale-cache warn log, andinvalid_clientremediation log atpkg/auth/monitored_token_source.go:361— Phase 2 (Authserver DCR integration (Phase 2, Steps 2a-2g) #4978). - Removing
networking.HTTPClientfrom the rest of the codebase (still used by e.g.pkg/auth/oauth/oidc.go:42). This task only drops it from DCR code; a wider cleanup is out of scope. - CLI persistence of
registration_client_uriinpkg/auth/remote/config.go(deferred follow-up). - Any change to the authserver
/registerhandler semantics atpkg/authserver/server/handlers/dcr.gobeyond what is unavoidable for the rename.
References
- Parent story: Authserver-driven DCR for upstream OAuth 2.1 MCP servers #4976 — "Authserver-driven DCR for upstream OAuth 2.1 MCP servers".
- Downstream: Authserver DCR integration (Phase 2, Steps 2a-2g) #4978 (blocked until this lands), Persistent DCRCredentialStore backends (memory + Redis) #4979.
.claude/rules/go-style.md— SPDX headers, constructor validation, drain-response-body conventions..claude/rules/testing.md— testify overt.Fatal,t.Cleanupoverdefer, no Ginkgo in this area.CLAUDE.md— always usetask(nevergo test/golangci-lintdirectly); 400 LOC / 10 files PR cap.- RFC 7591 (Dynamic Client Registration); RFC 8252 (loopback redirect URIs for public clients).
Activity
Rename pkg/oauth to pkg/oauthproto and move DCR primitives
tgrunnagle commentedon Apr 27, 2026
Before closing and after #5036 : the authserver still defines its own DCRRequest/DCRResponse in pkg/authserver/server/registration/dcr.go alongside the new types in pkg/oauthproto. Reconciling Scope string vs ScopeList is the blocking work, so it doesn't belong in #5036.
See #5371
Rename pkg/oauth to pkg/oauthproto and move DCR primitives
Rename pkg/oauth to pkg/oauthproto and move DCR primitives
Rename pkg/oauth to pkg/oauthproto and move DCR primitives (#5036)