Skip to content
Draft
Show file tree
Hide file tree
Changes from 11 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
23 changes: 23 additions & 0 deletions integration/appaccess/appaccess_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ import (
"github.com/stretchr/testify/require"

"github.com/gravitational/teleport"
appauthconfigv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/appauthconfig/v1"
labelv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/label/v1"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/types/appauthconfig"
apievents "github.com/gravitational/teleport/api/types/events"
"github.com/gravitational/teleport/entitlements"
"github.com/gravitational/teleport/integration/helpers"
Expand Down Expand Up @@ -74,12 +77,32 @@ func TestAppAccess(t *testing.T) {
{
Name: "test-http",
URI: streamableHTTPServerURL,
StaticLabels: map[string]string{
"app_auth_config": "jwt",
},
},
}

jwks := newJwksIssuer(t)

// Reusing the pack as much as we can.
pack := SetupWithOptions(t, AppTestOptions{
ExtraRootApps: extraApps,
JWKS: jwks,
RootAppAuthConfigs: []*appauthconfigv1.AppAuthConfig{
appauthconfig.NewAppAuthConfigJWT(
"jwt",
[]*labelv1.Label{{Name: "app_auth_config", Values: []string{"jwt"}}},
&appauthconfigv1.AppAuthConfigJWTSpec{
Issuer: jwks.issuer,
Audience: "teleport",
UsernameClaim: "email",
KeysSource: &appauthconfigv1.AppAuthConfigJWTSpec_StaticJwks{
StaticJwks: jwks.encodedJwks,
},
},
),
},
})

t.Run("Forward", bind(pack, testForward))
Expand Down
55 changes: 55 additions & 0 deletions integration/appaccess/fixtures.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package appaccess

import (
"encoding/json"
"fmt"
"net"
"net/http"
Expand All @@ -28,6 +29,8 @@ import (
"testing"
"time"

"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/gravitational/trace"
Expand All @@ -36,9 +39,11 @@ import (

"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/breaker"
appauthconfigv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/appauthconfig/v1"
"github.com/gravitational/teleport/integration/helpers"
"github.com/gravitational/teleport/lib"
"github.com/gravitational/teleport/lib/auth/testauthority"
"github.com/gravitational/teleport/lib/cryptosuites"
"github.com/gravitational/teleport/lib/service/servicecfg"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/log/logtest"
Expand All @@ -51,6 +56,8 @@ type AppTestOptions struct {
LeafClusterListeners helpers.InstanceListenerSetupFunc
Clock clockwork.Clock
MonitorCloseChannel chan struct{}
RootAppAuthConfigs []*appauthconfigv1.AppAuthConfig
JWKS *jwksIssuer

RootConfig func(config *servicecfg.Config)
LeafConfig func(config *servicecfg.Config)
Expand Down Expand Up @@ -136,6 +143,8 @@ func SetupWithOptions(t *testing.T, opts AppTestOptions) *Pack {
flushAppName: "app-05",
flushAppPublicAddr: "app-05.example.com",
flushAppClusterName: "example.com",

jwks: opts.JWKS,
}

createHandler := func(handler func(conn *websocket.Conn)) http.HandlerFunc {
Expand Down Expand Up @@ -477,3 +486,49 @@ func splitHostPort(hostport string) (string, int, error) {

return host, int(port), nil
}

type jwksIssuer struct {
signer jose.Signer
signatures []jose.SignatureAlgorithm
encodedJwks string
issuer string
}

func (j *jwksIssuer) createJwt(t *testing.T, audience, email string, issuedAt time.Time, expiredAt time.Time) string {
token, err := jwt.Signed(j.signer).Claims(jwt.Claims{
Issuer: j.issuer,
Audience: jwt.Audience{audience},
IssuedAt: jwt.NewNumericDate(issuedAt),
Expiry: jwt.NewNumericDate(expiredAt),
}).Claims(
struct {
Email string `json:"email"`
}{Email: email},
).Serialize()
require.NoError(t, err)
return token
}

func newJwksIssuer(t *testing.T) *jwksIssuer {
const kid = "kid-example"
privateKey, err := cryptosuites.GenerateKeyWithAlgorithm(cryptosuites.ECDSAP256)
require.NoError(t, err)

signer, err := jose.NewSigner(
jose.SigningKey{Algorithm: jose.ES256, Key: privateKey},
(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", kid),
)
require.NoError(t, err)

encodedJwks, err := json.Marshal(&jose.JSONWebKeySet{Keys: []jose.JSONWebKey{
{Algorithm: string(jose.ES256), KeyID: kid, Key: privateKey.Public()},
}})
require.NoError(t, err)

return &jwksIssuer{
signer: signer,
signatures: []jose.SignatureAlgorithm{jose.ES256},
encodedJwks: string(encodedJwks),
issuer: "https://issuer-url/",
}
}
68 changes: 68 additions & 0 deletions integration/appaccess/mcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package appaccess

import (
"crypto/tls"
"net"
"net/http"
"testing"
Expand All @@ -31,8 +32,11 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/lib/client"
clientmcp "github.com/gravitational/teleport/lib/client/mcp"
"github.com/gravitational/teleport/lib/services"
libmcp "github.com/gravitational/teleport/lib/srv/mcp"
"github.com/gravitational/teleport/lib/utils/mcptest"
)
Expand All @@ -57,6 +61,10 @@ func testMCP(pack *Pack, t *testing.T) {
testMCPProxyStreamableHTTP(t, pack, "test-http")
})

t.Run("endpoint streamable HTTP with JWT", func(t *testing.T) {
testMCPEndpointStreamableHTTPWithJWT(t, pack, "test-http")
})

t.Run("stdio to streamable HTTP success", func(t *testing.T) {
testMCPStdioToStreamableHTTP(t, pack, "test-http")
})
Expand Down Expand Up @@ -120,6 +128,66 @@ func testMCPProxyStreamableHTTP(t *testing.T, pack *Pack, appName string) {
mcptest.MustCallServerTool(t, client)
}

func testMCPEndpointStreamableHTTPWithJWT(t *testing.T, pack *Pack, appName string) {
userNoAccess, _ := pack.CreateUser(t)
denyRole := services.RoleForUser(userNoAccess)
denyRole.SetAppLabels(types.Deny, map[string]utils.Strings{types.AppSubKindLabel: {types.SubKindMCP}})

createdDenyRole, err := pack.rootCluster.Process.GetAuthServer().UpsertRole(t.Context(), denyRole)
require.NoError(t, err)

userNoAccess.AddRole(createdDenyRole.GetName())
_, err = pack.rootCluster.Process.GetAuthServer().UpsertUser(t.Context(), userNoAccess)
require.NoError(t, err)

for name, tc := range map[string]struct {
token string
assertError require.ErrorAssertionFunc
}{
"with access": {
token: pack.jwks.createJwt(t, "teleport", pack.username, time.Now(), time.Now().Add(time.Hour)),
assertError: require.NoError,
},
"access denied": {
token: pack.jwks.createJwt(t, "teleport", userNoAccess.GetName(), time.Now(), time.Now().Add(time.Hour)),
assertError: require.Error,
},
"token issued too long ago": {
token: pack.jwks.createJwt(t, "teleport", pack.username, time.Now().Add(12*time.Hour), time.Now().Add(24*time.Hour)),
assertError: require.Error,
},
"expired token": {
token: pack.jwks.createJwt(t, "teleport", pack.username, time.Now().Add(-2*time.Hour), time.Now().Add(-1*time.Hour)),
assertError: require.Error,
},
} {
t.Run(name, func(t *testing.T) {
ctx := t.Context()
mcpClientTransport, err := mcpclienttransport.NewStreamableHTTP(
"https://"+pack.rootCluster.Web+"/mcp/apps/"+appName,
mcpclienttransport.WithHTTPHeaders(map[string]string{"Authorization": "Bearer " + tc.token}),
mcpclienttransport.WithHTTPBasicClient(&http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}),
)
require.NoError(t, err)

client := mcpclient.NewClient(mcpClientTransport)
require.NoError(t, client.Start(ctx))
defer client.Close()

_, err = mcptest.InitializeClient(t.Context(), client)
tc.assertError(t, err)
_, err = mcptest.CallServerTool(t.Context(), client)
tc.assertError(t, err)
})
}
}

func testMCPStdioToStreamableHTTP(t *testing.T, pack *Pack, appName string) {
clientConn, serverConn := net.Pipe()
t.Cleanup(func() {
Expand Down
7 changes: 7 additions & 0 deletions integration/appaccess/pack.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ type Pack struct {
flushAppPublicAddr string
flushAppClusterName string
flushAppURI string

jwks *jwksIssuer
}

func (p *Pack) RootWebAddr() string {
Expand Down Expand Up @@ -905,6 +907,11 @@ func (p *Pack) startRootAppServers(t *testing.T, count int, opts AppTestOptions)
require.NoError(t, err)
require.Len(t, configs, len(servers))

for _, config := range opts.RootAppAuthConfigs {
_, err := p.rootCluster.Process.GetAuthServer().CreateAppAuthConfig(t.Context(), config)
require.NoError(t, err, "failed to create app auth config")
}

for i, appServer := range servers {
srv := appServer
t.Cleanup(func() {
Expand Down
3 changes: 3 additions & 0 deletions lib/auth/authclient/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,9 @@ type ReadProxyAccessPoint interface {
// resources.
services.HealthCheckConfigReader

// AppAuthConfigGetter defines methods for fetching app auth configs.
services.AppAuthConfigReader

// NewWatcher returns a new event watcher.
NewWatcher(ctx context.Context, watch types.Watch) (types.Watcher, error)

Expand Down
1 change: 1 addition & 0 deletions lib/authz/permissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -949,6 +949,7 @@ func roleSpecForProxy(clusterName string) types.RoleSpecV6 {
types.NewRule(types.KindRelayServer, services.RO()),
types.NewRule(types.KindAccessList, services.RO()),
types.NewRule(types.KindHealthCheckConfig, services.RO()),
types.NewRule(types.KindAppAuthConfig, services.RO()),
// this rule allows cloud proxies to read
// plugins of `openai` type, since Assist uses the OpenAI API and runs in Proxy.
{
Expand Down
48 changes: 48 additions & 0 deletions lib/utils/mcptest/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ package mcptest
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"

Expand Down Expand Up @@ -50,6 +52,17 @@ func NewServerWithVersion(version string) *mcpserver.MCPServer {
Content: []mcp.Content{mcp.NewTextContent("hello client")},
}, nil
})
server.AddTool(mcp.Tool{
Name: "request-headers",
}, func(_ context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
data, err := json.Marshal(request.Header)
if err != nil {
return nil, trace.Wrap(err)
}
return &mcp.CallToolResult{
Content: []mcp.Content{mcp.NewTextContent(string(data))},
}, nil
})
return server
}

Expand Down Expand Up @@ -119,3 +132,38 @@ func CallServerTool(ctx context.Context, client *mcpclient.Client) (*mcp.CallToo
callToolResult, err := client.CallTool(ctx, callToolRequest)
return callToolResult, trace.Wrap(err)
}

// CallRequestHeaders calls the "request-headers" tool and returns the HTTP
// headers the server received.
func CallRequestHeaders(ctx context.Context, client *mcpclient.Client) (http.Header, error) {
Comment thread
gabrielcorado marked this conversation as resolved.
Outdated
req := mcp.CallToolRequest{}
req.Params.Name = "request-headers"
result, err := client.CallTool(ctx, req)
if err != nil {
return nil, trace.Wrap(err)
}

if len(result.Content) == 0 {
return nil, trace.BadParameter("expected content in response")
}

textContent, ok := result.Content[0].(mcp.TextContent)
if !ok {
return nil, trace.BadParameter("expected text content, got %T", result.Content[0])
}

var headers http.Header
if err := json.Unmarshal([]byte(textContent.Text), &headers); err != nil {
return nil, trace.Wrap(err)
}
return headers, nil
}

// MustCallRequestHeaders calls the "request-headers" tool and asserts it
// succeeds, returning the HTTP headers the server received.
func MustCallRequestHeaders(t *testing.T, client *mcpclient.Client) http.Header {
t.Helper()
headers, err := CallRequestHeaders(t.Context(), client)
require.NoError(t, err)
return headers
}
2 changes: 2 additions & 0 deletions lib/web/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,8 @@ func NewHandler(cfg Config, opts ...HandlerOption) (*APIHandler, error) {
if h.healthCheckAppServer == nil {
h.healthCheckAppServer = appHandler.HealthCheckAppServer
}

appHandler.BindMCPEndpoints(&h.Router, h.WithUnauthenticatedLimiter)
}

go h.startFeatureWatcher()
Expand Down
Loading
Loading