Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
node,docs: accept RFC 7523 client assertion and jwt-bearer grants on /oauth/token
Antonio Ojea37b7c74e832b
diff --git a/api/network.go b/api/network.goindex 53757546..c80536c5 100644--- a/api/network.go+++ b/api/network.go@@ -178,6 +178,19 @@ const (// GrantTypeAuthorizationCode is the standard OAuth 2.1 authorization_code grant type.GrantTypeAuthorizationCode = "authorization_code"+ // GrantTypeClientCredentials is the RFC 6749 client_credentials grant type.+ GrantTypeClientCredentials = "client_credentials"++ // GrantTypeJWTBearer is the RFC 7523 section 2.1 JWT authorization grant type URI.+ GrantTypeJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer"++ // ClientAssertionTypeJWTBearer is the RFC 7523 section 2.2 client assertion type URI.+ ClientAssertionTypeJWTBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"++ // ClientAssertionTypeJWTSPIFFE is the client assertion type URI for a SPIFFE+ // JWT-SVID (draft-ietf-oauth-spiffe-client-auth).+ ClientAssertionTypeJWTSPIFFE = "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe"+// TokenTypeBiscuit is the token type URI identifying a Agent Mesh Biscuit token in RFC 8693 exchanges.TokenTypeBiscuit = "urn:agentmesh:params:oauth:token-type:biscuit"diff --git a/internal/node/sidecar.go b/internal/node/sidecar.goindex e99e7c98..5ba57f41 100644--- a/internal/node/sidecar.go+++ b/internal/node/sidecar.go@@ -50,6 +50,9 @@ func StartSidecarServer(node *AgentMeshNode, addr, socketPath, token, certFile,mux.HandleFunc("/.well-known/oauth-protected-resource", func(w http.ResponseWriter, r *http.Request) {handleOAuthProtectedResource(node, w, r)})+ mux.HandleFunc("/.well-known/oauth-authorization-server", func(w http.ResponseWriter, r *http.Request) {+ handleOAuthAuthorizationServer(node, w, r)+ })mux.HandleFunc("/oauth/token", func(w http.ResponseWriter, r *http.Request) {handleNodeOAuthToken(node, token, w, r)})diff --git a/internal/node/sts.go b/internal/node/sts.goindex ecb42745..2075ea61 100644--- a/internal/node/sts.go+++ b/internal/node/sts.go@@ -24,6 +24,7 @@ import ("errors""fmt""net/http"+ "net/url""strings""time"@@ -464,8 +465,21 @@ func withCallerOrTokenAuth(node *AgentMeshNode, token string, allowAuthorization})}-// handleNodeOAuthToken implements RFC 8693 Token Exchange & Attenuation-// (POST /oauth/token) on agentmesh-node.+// handleNodeOAuthToken implements the token endpoint (POST /oauth/token) on+// agentmesh-node. It accepts three grant shapes, all of which end in a Biscuit:+//+// - RFC 8693 token exchange: subject_token is a Biscuit to attenuate or an+// external JWT to exchange at the control plane.+// - RFC 6749 client_credentials with RFC 7523 section 2.2 client+// authentication: client_assertion is a JWT (for example a SPIFFE JWT-SVID,+// draft-ietf-oauth-spiffe-client-auth) that is exchanged at the control+// plane. This is the shape OAuth clients such as NVIDIA OpenShell token+// grants and Keycloak-style workload clients send.+// - RFC 7523 section 2.1 jwt-bearer authorization grant: assertion is a JWT+// authorization grant, as produced by draft-ietf-oauth-identity-chaining.+//+// A client_assertion on any grant also authenticates the caller, so a token+// exchange without a subject_token narrows the assertion's own identity.func handleNodeOAuthToken(node *AgentMeshNode, sidecarToken string, w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {writeNodeOAuthError(w, http.StatusMethodNotAllowed, "invalid_request", "Method not allowed")@@ -481,14 +495,44 @@ func handleNodeOAuthToken(node *AgentMeshNode, sidecarToken string, w http.Resporeturn}- grantType := r.FormValue("grant_type")- if grantType != api.GrantTypeTokenExchange {- writeNodeOAuthError(w, http.StatusBadRequest, "unsupported_grant_type", "Only urn:ietf:params:oauth:grant-type:token-exchange is supported on agentmesh-node")+ clientAssertion, hasClientAssertion, caErr := clientAssertionFromForm(r.Form)+ if caErr != nil {+ writeNodeOAuthError(w, http.StatusUnauthorized, "invalid_client", caErr.Error())return}subjectToken := strings.TrimSpace(r.FormValue("subject_token"))subjectTokenType := strings.TrimSpace(r.FormValue("subject_token_type"))+ // A rejected subject is invalid_grant, unless the subject is the client+ // assertion itself, which makes it a client authentication failure.+ subjectRejected := func(err error) {+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_grant", err.Error())+ }+ switch grantType := r.FormValue("grant_type"); grantType {+ case api.GrantTypeTokenExchange:+ case api.GrantTypeClientCredentials:+ if !hasClientAssertion {+ writeNodeOAuthError(w, http.StatusUnauthorized, "invalid_client", "client_credentials requires a JWT client_assertion (RFC 7523 section 2.2)")+ return+ }+ subjectToken = clientAssertion+ subjectTokenType = api.TokenTypeJWT+ subjectRejected = func(err error) {+ writeNodeOAuthError(w, http.StatusUnauthorized, "invalid_client", err.Error())+ }+ case api.GrantTypeJWTBearer:+ assertion := strings.TrimSpace(r.FormValue("assertion"))+ if !isLikelyJWT(assertion) {+ writeNodeOAuthError(w, http.StatusBadRequest, "invalid_grant", "assertion must be a JWT (RFC 7523 section 2.1)")+ return+ }+ subjectToken = assertion+ subjectTokenType = api.TokenTypeJWT+ default:+ writeNodeOAuthError(w, http.StatusBadRequest, "unsupported_grant_type", "Supported grant types: "+strings.Join(nodeOAuthGrantTypes, ", "))+ return+ }+requestedTokenType := strings.TrimSpace(r.FormValue("requested_token_type"))resources := r.Form["resource"]scope := strings.TrimSpace(r.FormValue("scope"))@@ -523,7 +567,7 @@ func handleNodeOAuthToken(node *AgentMeshNode, sidecarToken string, w http.Respoif requestedTokenType != api.TokenTypeJWT {resp, exErr := node.ExchangeSubjectJWT(r.Context(), subjectToken, subjectTokenType, tar, seal)if exErr != nil {- writeNodeOAuthError(w, http.StatusBadRequest, "invalid_grant", exErr.Error())+ subjectRejected(exErr)return}expIn := int64(300)@@ -538,7 +582,7 @@ func handleNodeOAuthToken(node *AgentMeshNode, sidecarToken string, w http.Respo}resp, exErr := node.ExchangeSubjectJWT(r.Context(), subjectToken, subjectTokenType, tar, false)if exErr != nil {- writeNodeOAuthError(w, http.StatusBadRequest, "invalid_grant", exErr.Error())+ subjectRejected(exErr)return}baseBiscuit = resp.GetBiscuitToken()@@ -547,12 +591,24 @@ func handleNodeOAuthToken(node *AgentMeshNode, sidecarToken string, w http.Respo}}} else {- // No subject_token (or "self"): authenticate caller via sidecar gate and- // use the caller's Biscuit if provided, or the node's own Biscuit.- callerBiscuit, ok := authenticateSidecarCaller(node, sidecarToken, r)- if !ok {- writeNodeOAuthError(w, http.StatusUnauthorized, "invalid_client", "Sidecar authentication or subject_token required")- return+ // No subject_token (or "self"): authenticate caller via a client+ // assertion or the sidecar gate, and use the caller's Biscuit if+ // provided, or the node's own Biscuit.+ var callerBiscuit []byte+ if hasClientAssertion {+ resp, exErr := node.ExchangeSubjectJWT(r.Context(), clientAssertion, api.TokenTypeJWT, nil, false)+ if exErr != nil {+ writeNodeOAuthError(w, http.StatusUnauthorized, "invalid_client", exErr.Error())+ return+ }+ callerBiscuit = resp.GetBiscuitToken()+ } else {+ var ok bool+ callerBiscuit, ok = authenticateSidecarCaller(node, sidecarToken, r)+ if !ok {+ writeNodeOAuthError(w, http.StatusUnauthorized, "invalid_client", "Sidecar authentication, client_assertion, or subject_token required")+ return+ }}if len(callerBiscuit) > 0 {baseBiscuit = callerBiscuit@@ -708,13 +764,44 @@ func handleNodeOAuthRevoke(node *AgentMeshNode, sidecarToken string, w http.Respw.WriteHeader(http.StatusOK)}-// handleOAuthProtectedResource serves RFC 9728 OAuth 2.0 Protected Resource Metadata-// (GET /.well-known/oauth-protected-resource).-func handleOAuthProtectedResource(node *AgentMeshNode, w http.ResponseWriter, r *http.Request) {- if r.Method != http.MethodGet {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- return+// nodeOAuthGrantTypes and nodeOAuthClientAuthMethods are what the node's token+// endpoint accepts and advertises (RFC 8414 and draft-ietf-oauth-spiffe-client-auth+// section 4).+var (+ nodeOAuthGrantTypes = []string{+ api.GrantTypeTokenExchange,+ api.GrantTypeClientCredentials,+ api.GrantTypeJWTBearer,}+ nodeOAuthClientAuthMethods = []string{"none", "private_key_jwt", "spiffe_jwt"}+)++// clientAssertionFromForm reads an RFC 7523 section 2.2 client assertion from+// the token request. It returns (assertion, true, nil) for a well-formed JWT+// assertion, (_, false, nil) when the request carries none, and an error when+// the assertion or its type is unusable.+func clientAssertionFromForm(form url.Values) (string, bool, error) {+ assertion := strings.TrimSpace(form.Get("client_assertion"))+ assertionType := strings.TrimSpace(form.Get("client_assertion_type"))+ if assertion == "" && assertionType == "" {+ return "", false, nil+ }+ switch assertionType {+ case api.ClientAssertionTypeJWTBearer, api.ClientAssertionTypeJWTSPIFFE:+ case "":+ return "", false, errors.New("client_assertion_type is required with client_assertion")+ default:+ return "", false, fmt.Errorf("unsupported client_assertion_type %q; use %s or %s", assertionType, api.ClientAssertionTypeJWTBearer, api.ClientAssertionTypeJWTSPIFFE)+ }+ if !isLikelyJWT(assertion) {+ return "", false, errors.New("client_assertion must be a JWT")+ }+ return assertion, true, nil+}++// nodeBaseURL is the origin a caller reached this node on, for self-referencing+// metadata documents.+func nodeBaseURL(node *AgentMeshNode, r *http.Request) string {scheme := "http"if r.TLS != nil {scheme = "https"@@ -726,6 +813,16 @@ func handleOAuthProtectedResource(node *AgentMeshNode, w http.ResponseWriter, rif host == "" {host = "localhost"}+ return scheme + "://" + host+}++// handleOAuthProtectedResource serves RFC 9728 OAuth 2.0 Protected Resource Metadata+// (GET /.well-known/oauth-protected-resource).+func handleOAuthProtectedResource(node *AgentMeshNode, w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }var authServers []stringif node != nil {if cpURL, err := node.controlPlaneURL(); err == nil && cpURL != "" {@@ -733,7 +830,7 @@ func handleOAuthProtectedResource(node *AgentMeshNode, w http.ResponseWriter, r}}meta := map[string]any{- "resource": fmt.Sprintf("%s://%s/mcp", scheme, host),+ "resource": nodeBaseURL(node, r) + "/mcp","authorization_servers": authServers,"bearer_methods_supported": []string{"header"},"scopes_supported": []string{"mcp", "inference", "egress", "a2a"},@@ -742,6 +839,29 @@ func handleOAuthProtectedResource(node *AgentMeshNode, w http.ResponseWriter, r_ = json.NewEncoder(w).Encode(meta)}+// handleOAuthAuthorizationServer serves RFC 8414 Authorization Server Metadata+// (GET /.well-known/oauth-authorization-server) for the node's own token+// endpoint. The node issues Biscuits only; interactive authorization lives on+// the control plane, which the protected resource metadata points at.+func handleOAuthAuthorizationServer(node *AgentMeshNode, w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }+ issuer := nodeBaseURL(node, r)+ meta := map[string]any{+ "issuer": issuer,+ "token_endpoint": issuer + "/oauth/token",+ "revocation_endpoint": issuer + "/oauth/revoke",+ "response_types_supported": []string{},+ "grant_types_supported": nodeOAuthGrantTypes,+ "token_endpoint_auth_methods_supported": nodeOAuthClientAuthMethods,+ "revocation_endpoint_auth_methods_supported": nodeOAuthClientAuthMethods,+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(meta)+}+func writeNodeOAuthTokenResponse(w http.ResponseWriter, accessToken, issuedTokenType string, expiresIn int64, scope string) {resp := map[string]any{"access_token": accessToken,diff --git a/internal/node/sts_test.go b/internal/node/sts_test.goindex 1c2a1372..46018ecf 100644--- a/internal/node/sts_test.go+++ b/internal/node/sts_test.go@@ -26,6 +26,7 @@ import ("net/http""net/http/httptest""net/url"+ "slices""strings""sync/atomic""testing"@@ -423,6 +424,298 @@ func TestWithCallerOrTokenAuthAndJWTExchange(t *testing.T) {}}+// startFakeExchangeControlPlane serves POST /token/exchange for h.node,+// answering every subject JWT with delegated, attenuated and sealed as the+// request asks, the way the real control plane does.+func startFakeExchangeControlPlane(t *testing.T, h *stsNodeHarness, delegated []byte) *atomic.Int32 {+ t.Helper()+ var calls atomic.Int32+ cpServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/token/exchange" {+ http.NotFound(w, r)+ return+ }+ calls.Add(1)+ body, _ := io.ReadAll(r.Body)+ var req api.TokenExchangeRequest+ if err := proto.Unmarshal(body, &req); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }+ out := delegated+ if req.GetTaskRule() != nil {+ var err error+ if out, err = identity.AttenuateBiscuit(out, req.GetTaskRule()); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }+ }+ if req.GetSeal() {+ var err error+ if out, err = identity.SealBiscuit(out); err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ return+ }+ }+ payload, _ := proto.Marshal(&api.TokenExchangeResponse{+ BiscuitToken: out,+ ExpireTime: timestamppb.New(time.Now().Add(5 * time.Minute)),+ Roles: []string{"developer"},+ Subject: "spiffe://openshell.example/sandbox/sbx-1",+ })+ w.Header().Set("Content-Type", "application/x-protobuf")+ _, _ = w.Write(payload)+ }))+ t.Cleanup(cpServer.Close)+ origTransport := http.DefaultTransport+ http.DefaultTransport = cpServer.Client().Transport+ t.Cleanup(func() { http.DefaultTransport = origTransport })+ if err := h.node.Store.SaveControlPlaneURL(cpServer.URL); err != nil {+ t.Fatalf("SaveControlPlaneURL: %v", err)+ }+ return &calls+}++// postNodeOAuthToken posts form to the node token endpoint over TCP (no local+// socket, no sidecar header) and returns the status and decoded JSON body.+func postNodeOAuthToken(t *testing.T, h *stsNodeHarness, sidecarToken string, form url.Values) (int, map[string]any) {+ t.Helper()+ req := httptest.NewRequest(http.MethodPost, "/oauth/token", strings.NewReader(form.Encode()))+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ rec := httptest.NewRecorder()+ handleNodeOAuthToken(h.node, sidecarToken, rec, req)+ var body map[string]any+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatalf("response is not JSON (%d): %s", rec.Code, rec.Body.String())+ }+ return rec.Code, body+}++func decodeIssuedBiscuit(t *testing.T, body map[string]any) []byte {+ t.Helper()+ if body["issued_token_type"] != api.TokenTypeBiscuit {+ t.Fatalf("issued_token_type = %v, want biscuit", body["issued_token_type"])+ }+ raw, err := base64.StdEncoding.DecodeString(body["access_token"].(string))+ if err != nil {+ t.Fatalf("access_token is not base64: %v", err)+ }+ return raw+}++// TestNodeOAuthTokenClientAssertionGrants covers the RFC 7523 shapes an OAuth+// client such as an OpenShell token grant or an identity-chaining caller sends+// to /oauth/token, alongside the RFC 8693 exchange the node already served.+func TestNodeOAuthTokenClientAssertionGrants(t *testing.T) {+ h := newSTSNodeHarness(t)+ sidecarToken := "secret-sidecar-token"++ delegated, err := identity.MintDelegatedBiscuitToken(+ h.cpPriv,+ jwt.MapClaims{"sub": "spiffe://openshell.example/sandbox/sbx-1"},+ h.peerID,+ time.Now().Add(5*time.Minute),+ []string{"developer"},+ h.policyRoles,+ nil,+ false,+ )+ if err != nil {+ t.Fatalf("MintDelegatedBiscuitToken: %v", err)+ }+ exchangeCalls := startFakeExchangeControlPlane(t, h, delegated)++ // A SPIFFE JWT-SVID as the Workload API would hand it out: the fake control+ // plane does not check the signature, the real one does.+ svid := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"ES256","typ":"JWT","kid":"k1"}`)) ++ "." + base64.RawURLEncoding.EncodeToString([]byte(`{"sub":"spiffe://openshell.example/sandbox/sbx-1","aud":["agentmesh-audience"]}`)) ++ "." + base64.RawURLEncoding.EncodeToString([]byte("sig"))++ getPR := RequestContext{PeerID: h.peerID, Protocol: string(api.MCPProtocolID), Target: "mcp://github", MCPTool: "get_pr", Local: true}+ mergePR := getPR+ mergePR.MCPTool = "merge_pr"+ gemini := RequestContext{PeerID: h.peerID, Target: "inference://gemini-pro", Local: true}++ t.Run("client_credentials with jwt-spiffe assertion issues the delegated biscuit", func(t *testing.T) {+ exchangeCalls.Store(0)+ form := url.Values{}+ form.Set("grant_type", api.GrantTypeClientCredentials)+ form.Set("client_assertion_type", api.ClientAssertionTypeJWTSPIFFE)+ form.Set("client_assertion", svid)+ for i := range 2 {+ code, body := postNodeOAuthToken(t, h, sidecarToken, form)+ if code != http.StatusOK {+ t.Fatalf("attempt %d: status %d: %v", i+1, code, body)+ }+ if !bytes.Equal(decodeIssuedBiscuit(t, body), delegated) {+ t.Fatalf("attempt %d: access_token is not the delegated biscuit", i+1)+ }+ if body["token_type"] != "Bearer" {+ t.Fatalf("token_type = %v", body["token_type"])+ }+ }+ if got := exchangeCalls.Load(); got != 1 {+ t.Fatalf("unattenuated assertion grants should share the exchange cache, got %d control plane calls", got)+ }+ })++ t.Run("client_credentials with jwt-bearer assertion honours scope, resource and seal", func(t *testing.T) {+ form := url.Values{}+ form.Set("grant_type", api.GrantTypeClientCredentials)+ form.Set("client_assertion_type", api.ClientAssertionTypeJWTBearer)+ form.Set("client_assertion", svid)+ form.Add("resource", "mcp://github")+ form.Set("scope", "tool:get_pr")+ form.Set("seal", "true")+ code, body := postNodeOAuthToken(t, h, sidecarToken, form)+ if code != http.StatusOK {+ t.Fatalf("status %d: %v", code, body)+ }+ issued := decodeIssuedBiscuit(t, body)+ if err := h.node.VerifyBiscuitToken(issued, getPR); err != nil {+ t.Fatalf("get_pr on mcp://github should be allowed: %v", err)+ }+ if err := h.node.VerifyBiscuitToken(issued, mergePR); err == nil {+ t.Fatalf("merge_pr should be denied by the scope")+ }+ if err := h.node.VerifyBiscuitToken(issued, gemini); err == nil {+ t.Fatalf("inference://gemini-pro should be denied by the resource")+ }+ if _, err := identity.AttenuateBiscuit(issued, &api.TaskAuthorizationRule{Name: "x"}); err == nil {+ t.Fatalf("sealed biscuit must not accept further blocks")+ }+ })++ t.Run("jwt-bearer authorization grant issues the delegated biscuit", func(t *testing.T) {+ form := url.Values{}+ form.Set("grant_type", api.GrantTypeJWTBearer)+ form.Set("assertion", svid)+ code, body := postNodeOAuthToken(t, h, sidecarToken, form)+ if code != http.StatusOK {+ t.Fatalf("status %d: %v", code, body)+ }+ if !bytes.Equal(decodeIssuedBiscuit(t, body), delegated) {+ t.Fatalf("access_token is not the delegated biscuit")+ }+ })++ t.Run("token exchange without subject_token narrows the client assertion's own identity", func(t *testing.T) {+ form := url.Values{}+ form.Set("grant_type", api.GrantTypeTokenExchange)+ form.Set("client_assertion_type", api.ClientAssertionTypeJWTSPIFFE)+ form.Set("client_assertion", svid)+ form.Add("resource", "inference://gemini-pro")+ code, body := postNodeOAuthToken(t, h, sidecarToken, form)+ if code != http.StatusOK {+ t.Fatalf("status %d: %v", code, body)+ }+ issued := decodeIssuedBiscuit(t, body)+ if err := h.node.VerifyBiscuitToken(issued, gemini); err != nil {+ t.Fatalf("inference://gemini-pro should be allowed: %v", err)+ }+ if err := h.node.VerifyBiscuitToken(issued, getPR); err == nil {+ t.Fatalf("mcp://github should be denied by the resource")+ }+ })++ rejected := []struct {+ name string+ form url.Values+ status int+ code string+ }{+ {+ name: "client_credentials without assertion",+ form: url.Values{"grant_type": {api.GrantTypeClientCredentials}},+ status: http.StatusUnauthorized,+ code: "invalid_client",+ },+ {+ name: "client_credentials with unsupported assertion type",+ form: url.Values{+ "grant_type": {api.GrantTypeClientCredentials},+ "client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:saml2-bearer"},+ "client_assertion": {svid},+ },+ status: http.StatusUnauthorized,+ code: "invalid_client",+ },+ {+ name: "client_credentials with assertion that is not a JWT",+ form: url.Values{+ "grant_type": {api.GrantTypeClientCredentials},+ "client_assertion_type": {api.ClientAssertionTypeJWTSPIFFE},+ "client_assertion": {sidecarToken},+ },+ status: http.StatusUnauthorized,+ code: "invalid_client",+ },+ {+ name: "client_assertion without client_assertion_type",+ form: url.Values{+ "grant_type": {api.GrantTypeClientCredentials},+ "client_assertion": {svid},+ },+ status: http.StatusUnauthorized,+ code: "invalid_client",+ },+ {+ name: "jwt-bearer without assertion",+ form: url.Values{"grant_type": {api.GrantTypeJWTBearer}},+ status: http.StatusBadRequest,+ code: "invalid_grant",+ },+ {+ name: "unknown grant type",+ form: url.Values{"grant_type": {"password"}},+ status: http.StatusBadRequest,+ code: "unsupported_grant_type",+ },+ }+ for _, tc := range rejected {+ t.Run("rejects "+tc.name, func(t *testing.T) {+ before := exchangeCalls.Load()+ code, body := postNodeOAuthToken(t, h, sidecarToken, tc.form)+ if code != tc.status || body["error"] != tc.code {+ t.Fatalf("status %d error %v, want %d %s (%v)", code, body["error"], tc.status, tc.code, body["error_description"])+ }+ if exchangeCalls.Load() != before {+ t.Fatalf("a rejected request must not reach the control plane")+ }+ })+ }++ t.Run("authorization server metadata advertises the grants and spiffe_jwt", func(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/.well-known/oauth-authorization-server", nil)+ req.Host = "node.example:8080"+ rec := httptest.NewRecorder()+ handleOAuthAuthorizationServer(h.node, rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status %d", rec.Code)+ }+ var meta struct {+ Issuer string `json:"issuer"`+ TokenEndpoint string `json:"token_endpoint"`+ GrantTypes []string `json:"grant_types_supported"`+ AuthMethods []string `json:"token_endpoint_auth_methods_supported"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &meta); err != nil {+ t.Fatalf("json: %v", err)+ }+ if meta.Issuer != "http://node.example:8080" || meta.TokenEndpoint != "http://node.example:8080/oauth/token" {+ t.Fatalf("issuer/token_endpoint = %q / %q", meta.Issuer, meta.TokenEndpoint)+ }+ for _, want := range []string{api.GrantTypeTokenExchange, api.GrantTypeClientCredentials, api.GrantTypeJWTBearer} {+ if !slices.Contains(meta.GrantTypes, want) {+ t.Fatalf("grant_types_supported %v lacks %s", meta.GrantTypes, want)+ }+ }+ if !slices.Contains(meta.AuthMethods, "spiffe_jwt") || !slices.Contains(meta.AuthMethods, "private_key_jwt") {+ t.Fatalf("token_endpoint_auth_methods_supported = %v", meta.AuthMethods)+ }+ })+}+func TestExtAuthzHTTPAndGRPC(t *testing.T) {h := newSTSNodeHarness(t)diff --git a/site/content/docs/preview/sandboxed-agents.md b/site/content/docs/preview/sandboxed-agents.mdindex a0dc4e06..ac56cb15 100644--- a/site/content/docs/preview/sandboxed-agents.md+++ b/site/content/docs/preview/sandboxed-agents.md@@ -64,6 +64,27 @@ flowchart LRThe sandboxed process has no credential in its environment variables orfilesystem.+### Per-sandbox identity without a pre-minted token++A sandbox proxy that holds a workload identity for each sandbox can skip the+minting step and let the mesh bind the credential to that identity. OpenShell's+`token_grant` sends the sandbox's SPIFFE JWT-SVID to the node token endpoint as+an RFC 7523 client assertion (`grant_type=client_credentials`,+`client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-spiffe`),+caches the Biscuit it gets back, and injects it as above. Agent Substrate's+egress policy puts a Substrate-issued actor JWT directly on+`X-Mesh-Authentication` (`replace_headers` with `actor_jwt`), and the node+exchanges it on each request. In both cases the control plane trusts the+issuer with `--workload-issuer` and binds roles to the subject:++```json+{ "role": "pr-reviewer", "members": ["user:spiffe://openshell.example/openshell/sandbox/*", "user:actor/reviews/*"] }+```++The sandbox still holds nothing. What changes is that the mesh, not the+orchestrator, decides what each sandbox identity may call, and revoking the+sandbox's role takes effect without touching the proxy.+## Blueprint 2: Docker Sandbox (`docker sbx`) & Kubernetes `agent-sandbox`In `docker sbx` (local microVM) and Kubernetes `agent-sandbox`diff --git a/site/content/docs/reference/node-api.md b/site/content/docs/reference/node-api.mdindex 1c66bddc..6d4ed5d3 100644--- a/site/content/docs/reference/node-api.md+++ b/site/content/docs/reference/node-api.md@@ -47,7 +47,8 @@ Authorization Server.|---|---|---|| `GET /healthz`, `GET /readyz` | none | `200` while the process is up. Every other route except `/debug/*` and `/.well-known/*` answers `503` until the node is connected to the mesh. || `GET /.well-known/oauth-protected-resource` | none | RFC 9728 OAuth 2.1 Protected Resource Metadata naming the Agent Mesh control plane in `authorization_servers`. |-| `POST /oauth/token` | token | RFC 8693 Token Exchange: exchanges a platform JWT or Biscuit into a Delegated or Task-Attenuated Biscuit. See [Token exchange (`/oauth/token`)](#token-exchange-oauthtoken). |+| `GET /.well-known/oauth-authorization-server` | none | RFC 8414 metadata for this node's token endpoint: the grant types and client authentication methods it accepts. |+| `POST /oauth/token` | token or client assertion | Token endpoint: RFC 8693 token exchange, RFC 7523 client assertion and JWT authorization grants. Every grant returns a Delegated or Task-Attenuated Biscuit. See [Token endpoint (`/oauth/token`)](#token-endpoint-oauthtoken). || `POST /oauth/revoke` | token | RFC 7009 Token Revocation: revokes a task Biscuit in this node's local revocation cache. || `GET /metrics` | token | Prometheus metrics (`agentmesh_node_*`). || `POST /mcp` | token | The MCP server (Streamable HTTP, sessionless: no `Mcp-Session-Id`, `GET` answers `405`). `/` is an alias. |@@ -64,15 +65,24 @@ Authorization Server.`--metrics-addr` serves `/metrics`, `/healthz` and `/readyz` on a secondlistener without authentication, for scrapers that hold no token.-## Token exchange (`/oauth/token`) and revocation (`/oauth/revoke`)+## Token endpoint (`/oauth/token`) and revocation (`/oauth/revoke`)-`POST /oauth/token` implements RFC 8693 (`application/x-www-form-urlencoded`):+`POST /oauth/token` takes `application/x-www-form-urlencoded` and accepts+three grant types. Each one ends in a Biscuit: a platform JWT is exchanged at+the control plane's `POST /token/exchange`, a Biscuit is attenuated locally.++| `grant_type` | Subject | Standard |+|---|---|---|+| `urn:ietf:params:oauth:grant-type:token-exchange` | `subject_token` with `subject_token_type` | RFC 8693 token exchange. |+| `client_credentials` | `client_assertion` with `client_assertion_type` | RFC 7523 section 2.2 client authentication. The assertion both authenticates the client and names the subject. |+| `urn:ietf:params:oauth:grant-type:jwt-bearer` | `assertion` | RFC 7523 section 2.1 JWT authorization grant, as produced by OAuth identity chaining. || Parameter | Meaning ||---|---|-| `grant_type` | Required: `urn:ietf:params:oauth:grant-type:token-exchange`. |-| `subject_token` | The input JWT or base64 Biscuit. If omitted when authenticated with the node's API token, defaults to the node's own Biscuit. |+| `subject_token` | Token exchange: the input JWT or base64 Biscuit. If omitted when the caller is authenticated (API token, local socket, or `client_assertion`), defaults to that caller's Biscuit, or to the node's own Biscuit. || `subject_token_type` | `urn:ietf:params:oauth:token-type:jwt`, `id_token`, `access_token`, or `urn:agentmesh:params:oauth:token-type:biscuit`. |+| `client_assertion`, `client_assertion_type` | A JWT with type `urn:ietf:params:oauth:client-assertion-type:jwt-bearer` or `urn:ietf:params:oauth:client-assertion-type:jwt-spiffe` (a SPIFFE JWT-SVID). Required for `client_credentials`; on any other grant it authenticates the caller. The control plane verifies the JWT against its `--issuer`, `--workload-issuer` and `--allowed-audiences`, so a JWT-SVID must carry one of those audiences. A rejected assertion answers `401 invalid_client`. |+| `assertion` | The JWT authorization grant for `jwt-bearer`. || `options` (or `scope` / `resource`) | Optional `TaskAuthorizationRule` as protojson (or space-separated service patterns in `scope`) to append as a `tar_block`. || `seal` | Optional (`true` / `1`): seal the returned Biscuit so downstream holders cannot append further blocks. |@@ -80,6 +90,23 @@ Returns standard RFC 8693 JSON (`access_token`,`issued_token_type: "urn:agentmesh:params:oauth:token-type:biscuit"`,`token_type: "Bearer"`, `expires_in`).+`GET /.well-known/oauth-authorization-server` lists these grant types in+`grant_types_supported` and `none`, `private_key_jwt` and `spiffe_jwt` in+`token_endpoint_auth_methods_supported`, so an OAuth client that discovers its+token endpoint can pick the client assertion type it holds.++An OpenShell provider profile that acquires its credential with a+`client_credentials` token grant posts exactly this shape:++```yaml+token_grant:+ grant_type: client_credentials+ token_endpoint: https://agentmesh-node.internal:8080/oauth/token+ client_assertion_type: urn:ietf:params:oauth:client-assertion-type:jwt-spiffe+ jwt_svid_audience: agentmesh-audience+ scopes: ["mcp://github", "inference://*"]+```+`POST /oauth/revoke` accepts `token=<base64-biscuit>` and records its leafrevocation ID in the node's local revocation cache until the token expires.diff --git a/tests/integration/sts_cuj_test.go b/tests/integration/sts_cuj_test.goindex 9bf09b03..fdae8970 100644--- a/tests/integration/sts_cuj_test.go+++ b/tests/integration/sts_cuj_test.go@@ -27,6 +27,7 @@ import ("net/url""os""path/filepath"+ "slices""strings""sync/atomic""testing"@@ -432,6 +433,118 @@ egress:}})+ t.Run("RFC 7523 client assertion grant from a header-injecting sandbox proxy", func(t *testing.T) {+ // What an OpenShell token grant does: the supervisor holds the+ // sandbox's workload JWT, trades it at the node token endpoint with+ // grant_type=client_credentials, then puts the result on+ // X-Mesh-Authentication for every request that leaves the sandbox. The+ // workload JWT is the mock issuer's; a SPIFFE JWT-SVID or Substrate+ // actor JWT differs only in the issuer the control plane trusts.+ workloadJWT := mintToken(map[string]any{"sub": "contractor-user"})++ meta, err := client.Get("http://" + callerAPI + "/.well-known/oauth-authorization-server")+ if err != nil {+ t.Fatalf("GET authorization server metadata: %v", err)+ }+ var asMeta struct {+ TokenEndpoint string `json:"token_endpoint"`+ GrantTypes []string `json:"grant_types_supported"`+ AuthMethods []string `json:"token_endpoint_auth_methods_supported"`+ }+ if err := json.NewDecoder(meta.Body).Decode(&asMeta); err != nil {+ t.Fatalf("decode authorization server metadata: %v", err)+ }+ _ = meta.Body.Close()+ if !slices.Contains(asMeta.GrantTypes, api.GrantTypeClientCredentials) || !slices.Contains(asMeta.AuthMethods, "spiffe_jwt") {+ t.Fatalf("metadata does not advertise client_credentials/spiffe_jwt: %+v", asMeta)+ }++ grant := func(t *testing.T, form url.Values) (int, map[string]any) {+ t.Helper()+ resp, err := client.PostForm(asMeta.TokenEndpoint, form)+ if err != nil {+ t.Fatalf("POST %s: %v", asMeta.TokenEndpoint, err)+ }+ defer func() { _ = resp.Body.Close() }()+ var body map[string]any+ if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {+ t.Fatalf("decode token response: %v", err)+ }+ return resp.StatusCode, body+ }++ // 1. client_credentials + jwt-spiffe assertion, narrowed by scope the+ // way an OpenShell profile's token_grant.scopes would.+ status, body := grant(t, url.Values{+ "grant_type": {api.GrantTypeClientCredentials},+ "client_assertion_type": {api.ClientAssertionTypeJWTSPIFFE},+ "client_assertion": {workloadJWT},+ "resource": {"egress://api.github.com"},+ "scope": {"method:GET path:/repos/acme/public/*"},+ })+ if status != http.StatusOK {+ t.Fatalf("client_credentials grant status = %d: %v", status, body)+ }+ if body["issued_token_type"] != api.TokenTypeBiscuit || body["token_type"] != "Bearer" {+ t.Fatalf("unexpected token response: %v", body)+ }+ sandboxToken, _ := body["access_token"].(string)++ // 2. The proxy injects it; the mesh enforces the contractor role and the+ // scope, and the upstream still sees the brokered credential only.+ meshURL := fmt.Sprintf("http://%s/mesh/%s/egress/api.github.com", callerAPI, pepPeer)+ reqAllow, _ := http.NewRequest(http.MethodGet, meshURL+"/repos/acme/public/readme", nil)+ reqAllow.Header.Set(api.HeaderMeshAuthentication, "Bearer "+sandboxToken)+ respAllow, err := client.Do(reqAllow)+ if err != nil {+ t.Fatalf("mesh egress with granted biscuit: %v", err)+ }+ allowBody, _ := io.ReadAll(respAllow.Body)+ _ = respAllow.Body.Close()+ if respAllow.StatusCode != http.StatusOK {+ t.Fatalf("granted biscuit allow status = %d, want 200: %s", respAllow.StatusCode, allowBody)+ }+ if !strings.Contains(string(allowBody), `"auth":"Bearer ghp_upstream_secret"`) {+ t.Fatalf("upstream did not receive the brokered credential: %s", allowBody)+ }+ reqDeny, _ := http.NewRequest(http.MethodGet, meshURL+"/repos/acme/private/secret", nil)+ reqDeny.Header.Set(api.HeaderMeshAuthentication, "Bearer "+sandboxToken)+ respDeny, err := client.Do(reqDeny)+ if err != nil {+ t.Fatalf("mesh egress deny: %v", err)+ }+ _ = respDeny.Body.Close()+ if respDeny.StatusCode != http.StatusForbidden {+ t.Fatalf("granted biscuit deny status = %d, want 403", respDeny.StatusCode)+ }++ // 3. The RFC 7523 section 2.1 authorization grant, as an identity-chaining+ // caller sends it, yields the same identity.+ status, body = grant(t, url.Values{+ "grant_type": {api.GrantTypeJWTBearer},+ "assertion": {workloadJWT},+ })+ if status != http.StatusOK || body["issued_token_type"] != api.TokenTypeBiscuit {+ t.Fatalf("jwt-bearer grant status = %d: %v", status, body)+ }++ // 4. An assertion the control plane does not trust is refused as a+ // client authentication failure and never becomes a credential.+ forged := strings.Join(append(strings.Split(workloadJWT, ".")[:2], base64.RawURLEncoding.EncodeToString([]byte("forged"))), ".")+ status, body = grant(t, url.Values{+ "grant_type": {api.GrantTypeClientCredentials},+ "client_assertion_type": {api.ClientAssertionTypeJWTSPIFFE},+ "client_assertion": {forged},+ })+ if status != http.StatusUnauthorized || body["error"] != "invalid_client" {+ t.Fatalf("forged assertion: status %d body %v, want 401 invalid_client", status, body)+ }+ status, body = grant(t, url.Values{"grant_type": {api.GrantTypeClientCredentials}})+ if status != http.StatusUnauthorized || body["error"] != "invalid_client" {+ t.Fatalf("missing assertion: status %d body %v, want 401 invalid_client", status, body)+ }+ })+t.Run("Task biscuit attenuation, mesh enforcement, egress ext_proc callout, outbound STS JWT minting, and task revocation", func(t *testing.T) {// 1. Exchange caller node's standing Biscuit into a narrowed Task Biscuit// only allowing GET /repos/acme/public/* on egress://api.github.com.