Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ type OBOConfig struct {
// TokenExchangeConfig holds configuration for RFC-8693 OAuth 2.0 Token Exchange.
// This configuration is used to exchange incoming authentication tokens for tokens
// that can be used with external services.
// The structure matches the tokenexchange.Config from pkg/oauthproto/tokenexchange/middleware.go
// The structure matches the tokenexchange.Config from pkg/auth/tokenexchange/middleware.go
type TokenExchangeConfig struct {
// TokenURL is the OAuth 2.0 token endpoint URL for token exchange
// +kubebuilder:validation:Required
Expand Down
5 changes: 3 additions & 2 deletions cmd/thv-operator/pkg/controllerutil/tokenexchange.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import (
"github.com/stacklok/toolhive/pkg/auth/awssts"
"github.com/stacklok/toolhive/pkg/auth/obo"
"github.com/stacklok/toolhive/pkg/auth/remote"
"github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/auth/tokenexchange"
exchange "github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/runner"
)

Expand Down Expand Up @@ -358,7 +359,7 @@ func addTokenExchangeConfig(
}

// Normalize SubjectTokenType to full URN (accepts both short forms and full URNs)
normalizedTokenType, err := tokenexchange.NormalizeTokenType(tokenExchangeSpec.SubjectTokenType)
normalizedTokenType, err := exchange.NormalizeTokenType(tokenExchangeSpec.SubjectTokenType)
if err != nil {
return fmt.Errorf("invalid subject token type: %w", err)
}
Expand Down
5 changes: 3 additions & 2 deletions cmd/thv/app/auth_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import (

"github.com/spf13/cobra"

"github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/auth/tokenexchange"
exchange "github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/runner"
)

Expand Down Expand Up @@ -129,7 +130,7 @@ func (f *RemoteAuthFlags) BuildTokenExchangeConfig() (*tokenexchange.Config, err
normalizedTokenType := f.TokenExchangeSubjectTokenType
if normalizedTokenType != "" {
var err error
normalizedTokenType, err = tokenexchange.NormalizeTokenType(normalizedTokenType)
normalizedTokenType, err = exchange.NormalizeTokenType(normalizedTokenType)
if err != nil {
return nil, fmt.Errorf("invalid subject token type: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/thv/app/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ import (
"github.com/stacklok/toolhive/pkg/auth/discovery"
"github.com/stacklok/toolhive/pkg/auth/oauth"
"github.com/stacklok/toolhive/pkg/auth/remote"
"github.com/stacklok/toolhive/pkg/auth/tokenexchange"
"github.com/stacklok/toolhive/pkg/bodylimit"
"github.com/stacklok/toolhive/pkg/networking"
"github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/transport"
"github.com/stacklok/toolhive/pkg/transport/middleware"
"github.com/stacklok/toolhive/pkg/transport/middleware/origin"
Expand Down
9 changes: 9 additions & 0 deletions docs/arch/03-transport-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,15 @@ Ownership* in [Virtual MCP](10-virtual-mcp-architecture.md).

### Middleware Integration

Token exchange's host adapter and host tests live in `pkg/auth/tokenexchange`;
`factory.go` handles runner setup and lifecycle, while `middleware.go` holds
runtime behavior and configuration. Reusable RFC 8693 exchange and normalization
remain in `pkg/oauthproto/tokenexchange`.
The host depends on the reusable package, never the reverse. Runner startup uses
`GetSupportedMiddlewareFactories` to select the host factory by `tokenexchange`;
there is no token-exchange `init()` registration. See the
[Go API migration](../middleware.md#8-token-exchange-middleware) for moved symbols.

All proxy types integrate with the middleware chain:

```mermaid
Expand Down
24 changes: 23 additions & 1 deletion docs/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,29 @@ thv config usage-metrics enable

**Purpose**: Exchanges incoming JWT tokens for external service tokens using OAuth 2.0 Token Exchange (RFC 8693).

**Location**: `pkg/oauthproto/tokenexchange/middleware.go`
**Location**: `pkg/auth/tokenexchange/middleware.go` (runtime and configuration)
and `pkg/auth/tokenexchange/factory.go` (runner factory and lifecycle).

**Go API migration (OWN-05)**: Host middleware moved from
`github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange` to
`github.com/stacklok/toolhive/pkg/auth/tokenexchange`. Update imports for these symbols:

- `Config`, `MiddlewareParams`, `Middleware` (including `Handler` and `Close`)
- `MiddlewareType`, `HeaderStrategyReplace`, `HeaderStrategyCustom`, `EnvClientSecret`
- `SubjectTokenProvider`
- `CreateMiddleware`, `CreateMiddlewareFromHeader`, `CreateMiddlewareFromTokenSource`

`ExchangeConfig` (including `Validate` and `TokenSource`) and `NormalizeTokenType`
remain in `pkg/oauthproto/tokenexchange`. Code using both layers should import
that package with an alias such as `exchange`, and the host package as
`tokenexchange`. There is no compatibility wrapper from the reusable package
back to the host. This is an import/ownership migration, not a runtime feature
change: configuration keys, defaults, environment variables, authentication,
headers, errors, and token-source lifetime remain unchanged.

The runner explicitly maps `tokenexchange.MiddlewareType` to the host
`CreateMiddleware` in `GetSupportedMiddlewareFactories`; neither package relies
on `init()` registration. Direct proxy callers use the two host constructors.

**Responsibilities**:
- Extract claims from authenticated JWT tokens
Expand Down
2 changes: 1 addition & 1 deletion docs/operator/crd-api.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pkg/auth/obo/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func DefaultFactory(config *types.MiddlewareConfig, runner types.MiddlewareRunne
// produces a 503 stub.
//
// Declared as a function (matching sibling middleware packages such as
// awssts, upstreamswap, and oauthproto/tokenexchange) so RegisterFactory is
// awssts, upstreamswap, and tokenexchange) so RegisterFactory is
// the only mutation path — there is no second escape hatch via direct
// assignment to CreateMiddleware.
func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error {
Expand Down
75 changes: 75 additions & 0 deletions pkg/auth/tokenexchange/factory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

package tokenexchange

import (
"encoding/json"
"fmt"

"github.com/stacklok/toolhive/pkg/transport/types"
)

// Middleware wraps token exchange middleware functionality
type Middleware struct {
middleware types.MiddlewareFunction
}

// Handler returns the middleware function used by the proxy.
func (m *Middleware) Handler() types.MiddlewareFunction {
return m.middleware
}

// Close cleans up any resources used by the middleware.
func (*Middleware) Close() error {
// Token exchange middleware doesn't need cleanup
return nil
}

// CreateMiddleware factory function for token exchange middleware
func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error {
var params MiddlewareParams
if err := json.Unmarshal(config.Parameters, &params); err != nil {
return fmt.Errorf("failed to unmarshal token exchange middleware parameters: %w", err)
}

// Token exchange config is required when this middleware type is specified
if params.TokenExchangeConfig == nil {
return fmt.Errorf("token exchange configuration is required but not provided")
}

// Validate configuration
if err := validateTokenExchangeConfig(params.TokenExchangeConfig); err != nil {
return fmt.Errorf("invalid token exchange configuration: %w", err)
}

middleware, err := createTokenExchangeMiddleware(*params.TokenExchangeConfig, nil, defaultEnvGetter)
if err != nil {
return fmt.Errorf("invalid token exchange middleware config: %w", err)
}

tokenExchangeMw := &Middleware{
middleware: middleware,
}

// Add middleware to runner
runner.AddMiddleware(config.Type, tokenExchangeMw)

return nil
}

// validateTokenExchangeConfig validates the token exchange configuration
func validateTokenExchangeConfig(config *Config) error {
if config.HeaderStrategy == HeaderStrategyCustom && config.ExternalTokenHeaderName == "" {
return fmt.Errorf("external_token_header_name must be specified when header_strategy is '%s'", HeaderStrategyCustom)
}

if config.HeaderStrategy != "" &&
config.HeaderStrategy != HeaderStrategyReplace &&
config.HeaderStrategy != HeaderStrategyCustom {
return fmt.Errorf("invalid header_strategy: %s (valid values: '%s', '%s')",
config.HeaderStrategy, HeaderStrategyReplace, HeaderStrategyCustom)
}

return nil
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

// Package tokenexchange adapts reusable OAuth token exchange to ToolHive middleware.
package tokenexchange

import (
"encoding/json"
"errors"
"fmt"
"log/slog"
Expand All @@ -16,6 +16,7 @@ import (

"github.com/stacklok/toolhive/pkg/auth"
"github.com/stacklok/toolhive/pkg/oauthproto"
exchange "github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/transport/types"
)

Expand Down Expand Up @@ -84,70 +85,6 @@ type Config struct {
ExternalTokenHeaderName string `json:"external_token_header_name,omitempty"`
}

// Middleware wraps token exchange middleware functionality
type Middleware struct {
middleware types.MiddlewareFunction
}

// Handler returns the middleware function used by the proxy.
func (m *Middleware) Handler() types.MiddlewareFunction {
return m.middleware
}

// Close cleans up any resources used by the middleware.
func (*Middleware) Close() error {
// Token exchange middleware doesn't need cleanup
return nil
}

// CreateMiddleware factory function for token exchange middleware
func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error {
var params MiddlewareParams
if err := json.Unmarshal(config.Parameters, &params); err != nil {
return fmt.Errorf("failed to unmarshal token exchange middleware parameters: %w", err)
}

// Token exchange config is required when this middleware type is specified
if params.TokenExchangeConfig == nil {
return fmt.Errorf("token exchange configuration is required but not provided")
}

// Validate configuration
if err := validateTokenExchangeConfig(params.TokenExchangeConfig); err != nil {
return fmt.Errorf("invalid token exchange configuration: %w", err)
}

middleware, err := createTokenExchangeMiddleware(*params.TokenExchangeConfig, nil, defaultEnvGetter)
if err != nil {
return fmt.Errorf("invalid token exchange middleware config: %w", err)
}

tokenExchangeMw := &Middleware{
middleware: middleware,
}

// Add middleware to runner
runner.AddMiddleware(config.Type, tokenExchangeMw)

return nil
}

// validateTokenExchangeConfig validates the token exchange configuration
func validateTokenExchangeConfig(config *Config) error {
if config.HeaderStrategy == HeaderStrategyCustom && config.ExternalTokenHeaderName == "" {
return fmt.Errorf("external_token_header_name must be specified when header_strategy is '%s'", HeaderStrategyCustom)
}

if config.HeaderStrategy != "" &&
config.HeaderStrategy != HeaderStrategyReplace &&
config.HeaderStrategy != HeaderStrategyCustom {
return fmt.Errorf("invalid header_strategy: %s (valid values: '%s', '%s')",
config.HeaderStrategy, HeaderStrategyReplace, HeaderStrategyCustom)
}

return nil
}

// injectionFunc is a function that injects a token into an HTTP request
type injectionFunc func(*http.Request, string) error

Expand Down Expand Up @@ -287,7 +224,7 @@ func createTokenExchangeMiddleware(
}

// Create base exchange config at startup time with all static fields
baseExchangeConfig := ExchangeConfig{
baseExchangeConfig := exchange.ExchangeConfig{
TokenURL: config.TokenURL,
ClientID: config.ClientID,
ClientSecret: clientSecret,
Expand Down
2 changes: 1 addition & 1 deletion pkg/runner/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/stacklok/toolhive/pkg/auth/awssts"
"github.com/stacklok/toolhive/pkg/auth/remote"
authsecrets "github.com/stacklok/toolhive/pkg/auth/secrets"
"github.com/stacklok/toolhive/pkg/auth/tokenexchange"
"github.com/stacklok/toolhive/pkg/auth/upstreamswap"
"github.com/stacklok/toolhive/pkg/authserver"
"github.com/stacklok/toolhive/pkg/authz"
Expand All @@ -28,7 +29,6 @@ import (
"github.com/stacklok/toolhive/pkg/ignore"
"github.com/stacklok/toolhive/pkg/labels"
"github.com/stacklok/toolhive/pkg/networking"
"github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/redisconfig"
"github.com/stacklok/toolhive/pkg/secrets"
"github.com/stacklok/toolhive/pkg/state"
Expand Down
2 changes: 1 addition & 1 deletion pkg/runner/config_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/stacklok/toolhive/pkg/auth"
"github.com/stacklok/toolhive/pkg/auth/awssts"
"github.com/stacklok/toolhive/pkg/auth/remote"
"github.com/stacklok/toolhive/pkg/auth/tokenexchange"
"github.com/stacklok/toolhive/pkg/authserver"
"github.com/stacklok/toolhive/pkg/authserver/server/registration"
"github.com/stacklok/toolhive/pkg/authz"
Expand All @@ -33,7 +34,6 @@ import (
"github.com/stacklok/toolhive/pkg/labels"
"github.com/stacklok/toolhive/pkg/mcp"
"github.com/stacklok/toolhive/pkg/networking"
"github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/recovery"
"github.com/stacklok/toolhive/pkg/telemetry"
"github.com/stacklok/toolhive/pkg/transport"
Expand Down
2 changes: 1 addition & 1 deletion pkg/runner/config_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ import (
regtypes "github.com/stacklok/toolhive-core/registry/types"
"github.com/stacklok/toolhive/pkg/audit"
"github.com/stacklok/toolhive/pkg/auth"
"github.com/stacklok/toolhive/pkg/auth/tokenexchange"
"github.com/stacklok/toolhive/pkg/authserver"
"github.com/stacklok/toolhive/pkg/authserver/server/registration"
"github.com/stacklok/toolhive/pkg/authz"
appconfig "github.com/stacklok/toolhive/pkg/config"
"github.com/stacklok/toolhive/pkg/mcp"
"github.com/stacklok/toolhive/pkg/networking"
"github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/transport/types"
"github.com/stacklok/toolhive/pkg/webhook"
)
Expand Down
2 changes: 1 addition & 1 deletion pkg/runner/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ import (
"github.com/stacklok/toolhive/pkg/auth"
"github.com/stacklok/toolhive/pkg/auth/awssts"
"github.com/stacklok/toolhive/pkg/auth/obo"
"github.com/stacklok/toolhive/pkg/auth/tokenexchange"
"github.com/stacklok/toolhive/pkg/auth/upstreamswap"
"github.com/stacklok/toolhive/pkg/authserver"
"github.com/stacklok/toolhive/pkg/authz"
"github.com/stacklok/toolhive/pkg/authz/authorizers/cedar"
"github.com/stacklok/toolhive/pkg/bodylimit"
cfg "github.com/stacklok/toolhive/pkg/config"
"github.com/stacklok/toolhive/pkg/mcp"
"github.com/stacklok/toolhive/pkg/oauthproto/tokenexchange"
"github.com/stacklok/toolhive/pkg/ratelimit"
"github.com/stacklok/toolhive/pkg/recovery"
"github.com/stacklok/toolhive/pkg/telemetry"
Expand Down
Loading
Loading