Skip to content

Commit dffd0b8

Browse files
committed
feat(oauth): inject agent exchange audience for apiserver-valid backend tokens
TEMPORARY WORKAROUND (#965) until kagent-dev/kagent#2106 (Go) + #2107 (Python) add KAGENT_STS_AUDIENCE. kagent's STS exchange presents subject+actor but passes a nil audience, so muster self-issues aud=<resourceIdentifier>, which the Dex-only kube-apiserver cannot validate, forcing mcp-kubernetes to impersonate. Inject TokenExchangeBroker.DefaultAgentAudience into on-behalf-of token-exchange requests (actor_token present) that carry no audience of their own, routing the exchange to the matching broker target so muster mints a Dex-signed dex-k8s-authenticator token. mcp-kubernetes then passes it through natively (--downstream-oauth), removing MC impersonation. When #2106/#2107 merge, set KAGENT_STS_AUDIENCE and delete this middleware plus the DefaultAgentAudience field.
1 parent 9cc2dd0 commit dffd0b8

3 files changed

Lines changed: 142 additions & 1 deletion

File tree

‎internal/config/types.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,17 @@ type TokenExchangeBrokerConfig struct {
373373
// secret refs that do not set an explicit namespace. Populated from the
374374
// muster namespace by the serve command; not user-facing config.
375375
DefaultSecretNamespace string `yaml:"-"`
376+
377+
// DefaultAgentAudience is a TEMPORARY WORKAROUND (giantswarm/muster#965).
378+
// When an agent on-behalf-of exchange (grant_type=token-exchange with an
379+
// actor_token) arrives with no `audience`, muster injects this audience so
380+
// the exchange routes to the matching Targets entry and mints a Dex-signed
381+
// token (e.g. aud=dex-k8s-authenticator) the kube-apiserver accepts, letting
382+
// mcp-kubernetes pass it through without impersonation. kagent passes a nil
383+
// audience today; once kagent-dev/kagent#2106 (Go) + #2107 (Python) add
384+
// KAGENT_STS_AUDIENCE, kagent scopes the token itself and this field plus its
385+
// injection middleware must be deleted. Empty disables the injection.
386+
DefaultAgentAudience string `yaml:"defaultAgentAudience,omitempty"`
376387
}
377388

378389
// Enabled reports whether brokered token exchange is configured.

‎internal/server/oauth_http.go‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
package server
22

33
import (
4+
"bytes"
45
"context"
56
"crypto/tls"
67
"crypto/x509"
78
"encoding/base64"
89
"encoding/json"
910
"errors"
1011
"fmt"
12+
"io"
1113
"log/slog"
1214
"net/http"
1315
"net/url"
16+
"strconv"
1417
"strings"
1518
"time"
1619

@@ -217,7 +220,63 @@ func (s *OAuthHTTPServer) CreateMux() http.Handler {
217220
// Setup MCP endpoint with OAuth protection
218221
s.setupMCPRoutes(mux)
219222

220-
return mux
223+
return s.withAgentExchangeAudience(mux)
224+
}
225+
226+
// grantTypeTokenExchange is the RFC 8693 token-exchange grant.
227+
const grantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"
228+
229+
// maxTokenExchangeBody bounds the request body the audience-injection middleware
230+
// reads. Token-exchange requests are a handful of form fields; this only guards
231+
// against an unbounded read.
232+
const maxTokenExchangeBody = 1 << 20
233+
234+
// withAgentExchangeAudience is a TEMPORARY WORKAROUND (giantswarm/muster#965).
235+
//
236+
// The glean apiserver trusts Dex only (aud=dex-k8s-authenticator). kagent's STS
237+
// exchange presents subject+actor but passes a nil audience, so muster self-issues
238+
// aud=<resourceIdentifier>, which the apiserver cannot validate — forcing
239+
// mcp-kubernetes to impersonate. Injecting the configured broker audience here
240+
// routes the exchange to the matching Targets entry, so muster mints a Dex-signed
241+
// dex-k8s-authenticator token that mcp-kubernetes passes through natively (no
242+
// impersonation). Once kagent-dev/kagent#2106 (Go) + #2107 (Python) add
243+
// KAGENT_STS_AUDIENCE, kagent scopes the token itself and this middleware plus
244+
// TokenExchangeBrokerConfig.DefaultAgentAudience must be deleted.
245+
//
246+
// The injection is scoped to on-behalf-of exchanges (an actor_token is present)
247+
// that carry no audience of their own, so a caller that requests an explicit
248+
// audience is never overridden.
249+
func (s *OAuthHTTPServer) withAgentExchangeAudience(next http.Handler) http.Handler {
250+
audience := s.config.TokenExchangeBroker.DefaultAgentAudience
251+
if audience == "" {
252+
return next
253+
}
254+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
255+
if isTokenExchangePost(r) {
256+
raw, err := io.ReadAll(io.LimitReader(r.Body, maxTokenExchangeBody))
257+
_ = r.Body.Close()
258+
if err == nil {
259+
body := raw
260+
if values, parseErr := url.ParseQuery(string(raw)); parseErr == nil &&
261+
values.Get("grant_type") == grantTypeTokenExchange &&
262+
values.Get("actor_token") != "" &&
263+
values.Get("audience") == "" {
264+
values.Set("audience", audience)
265+
body = []byte(values.Encode())
266+
}
267+
r.Body = io.NopCloser(bytes.NewReader(body))
268+
r.ContentLength = int64(len(body))
269+
r.Header.Set("Content-Length", strconv.Itoa(len(body)))
270+
}
271+
}
272+
next.ServeHTTP(w, r)
273+
})
274+
}
275+
276+
// isTokenExchangePost reports whether r is a form-encoded POST to the token endpoint.
277+
func isTokenExchangePost(r *http.Request) bool {
278+
return r.Method == http.MethodPost && r.URL.Path == "/oauth/token" &&
279+
strings.HasPrefix(r.Header.Get("Content-Type"), "application/x-www-form-urlencoded")
221280
}
222281

223282
// setupOAuthRoutes registers OAuth 2.1 endpoints on the mux.
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package server
2+
3+
import (
4+
"net/http"
5+
"net/http/httptest"
6+
"net/url"
7+
"strings"
8+
"testing"
9+
10+
"github.com/stretchr/testify/require"
11+
12+
"github.com/giantswarm/muster/internal/config"
13+
)
14+
15+
// serveExchange runs a form-encoded POST through withAgentExchangeAudience and
16+
// returns the audience the downstream handler observed after re-parsing the body.
17+
func serveExchange(t *testing.T, defaultAudience string, form url.Values) (seenAudience string, downstreamHit bool) {
18+
t.Helper()
19+
s := &OAuthHTTPServer{config: config.OAuthServerConfig{
20+
TokenExchangeBroker: config.TokenExchangeBrokerConfig{DefaultAgentAudience: defaultAudience},
21+
}}
22+
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23+
downstreamHit = true
24+
require.NoError(t, r.ParseForm())
25+
seenAudience = r.PostForm.Get("audience")
26+
})
27+
req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(form.Encode()))
28+
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
29+
s.withAgentExchangeAudience(next).ServeHTTP(httptest.NewRecorder(), req)
30+
return seenAudience, downstreamHit
31+
}
32+
33+
func TestWithAgentExchangeAudience(t *testing.T) {
34+
obo := url.Values{
35+
"grant_type": {grantTypeTokenExchange},
36+
"subject_token": {"user.jwt"},
37+
"actor_token": {"agent.jwt"},
38+
}
39+
40+
t.Run("injects audience for an on-behalf-of exchange with none", func(t *testing.T) {
41+
seen, hit := serveExchange(t, "glean", obo)
42+
require.True(t, hit)
43+
require.Equal(t, "glean", seen)
44+
})
45+
46+
t.Run("does not override an explicit audience", func(t *testing.T) {
47+
form := url.Values{
48+
"grant_type": {grantTypeTokenExchange},
49+
"subject_token": {"user.jwt"},
50+
"actor_token": {"agent.jwt"},
51+
"audience": {"explicit"},
52+
}
53+
seen, _ := serveExchange(t, "glean", form)
54+
require.Equal(t, "explicit", seen)
55+
})
56+
57+
t.Run("does not inject without an actor token", func(t *testing.T) {
58+
form := url.Values{
59+
"grant_type": {grantTypeTokenExchange},
60+
"subject_token": {"user.jwt"},
61+
}
62+
seen, _ := serveExchange(t, "glean", form)
63+
require.Empty(t, seen)
64+
})
65+
66+
t.Run("no-op when DefaultAgentAudience is empty", func(t *testing.T) {
67+
seen, hit := serveExchange(t, "", obo)
68+
require.True(t, hit)
69+
require.Empty(t, seen)
70+
})
71+
}

0 commit comments

Comments
 (0)