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
10 changes: 10 additions & 0 deletions api/directory_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ const DirectoryKeyBytes = 34
// DirectoryMaxAddrs bounds the addresses one record carries.
const DirectoryMaxAddrs = 32

// DirectoryMaxAddrBytes bounds the text of one address in a record. The
// count includes the "/p2p/<provider>" suffix that the address has in an
// answer. The longest address a libp2p host announces is a circuit relay
// address through a router that has a DNS name of 253 bytes. With both peer
// IDs it is 530 bytes over WebTransport, which has two certhashes, and 660
// bytes over TLS when the address repeats the name as its SNI. 1024 is one
// and a half times the longest. DirectoryMaxAddrs addresses of this length
// are 32 KiB, half of the 64 KiB frame of the directory protocol.
const DirectoryMaxAddrBytes = 1024

// directoryKey is the sha256 multihash of a name: the two-byte multihash
// header (sha2-256, 32 bytes) and the digest. go-libp2p-kad-dht keys
// provider records by this multihash, so a record a member announces here
Expand Down
34 changes: 34 additions & 0 deletions api/directory_keys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ package api
import (
"bytes"
"encoding/hex"
"strings"
"testing"

"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
)

// The keys are the sha256 multihash of a fixed name, so a record a member
Expand Down Expand Up @@ -69,6 +71,38 @@ func TestDirectoryKeys(t *testing.T) {
}
}

// DirectoryMaxAddrBytes holds the longest addresses a libp2p host
// announces: a circuit relay address, with both peer IDs, through a router
// that has a DNS name of the maximum length.
func TestDirectoryMaxAddrBytesHoldsRealAddresses(t *testing.T) {
const (
router = "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB"
member = "12D3KooWNT6DHUiBT3881d46esEcB6RzCuN9a74pdK8Gx2jXb8ww"
certhash = "uEiDDq4_xNyDorZBH3TlGazyJdOWSwvo4PUo5YHFMrvDE8g"
)
label := strings.Repeat("a", 63)
name := strings.Join([]string{label, label, label, label[:61]}, ".")
if len(name) != 253 {
t.Fatalf("the DNS name is %d bytes, want 253", len(name))
}
relayed := "/p2p/" + router + "/p2p-circuit/p2p/" + member
for desc, addr := range map[string]string{
"TLS and WebSocket": "/dns4/" + name + "/tcp/65535/tls/ws" + relayed,
"TLS with an SNI and WebSocket": "/dns4/" + name + "/tcp/65535/tls/sni/" + name + "/ws" + relayed,
"WebTransport with two certhashes": "/dns6/" + name + "/udp/65535/quic-v1/webtransport/certhash/" + certhash + "/certhash/" + certhash + relayed,
} {
t.Run(desc, func(t *testing.T) {
ma, err := multiaddr.NewMultiaddr(addr)
if err != nil {
t.Fatalf("NewMultiaddr(%s): %v", addr, err)
}
if got := len(ma.String()); got > DirectoryMaxAddrBytes {
t.Errorf("the address is %d bytes, want at most DirectoryMaxAddrBytes = %d", got, DirectoryMaxAddrBytes)
}
})
}
}

// A record is the provider's own, under its peer key, or a service's, by
// name or by type, and the key must be that of the service it names.
func TestServiceOfRecord(t *testing.T) {
Expand Down
85 changes: 75 additions & 10 deletions api/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand All @@ -43,29 +44,34 @@ const DefaultMaxMCPBodyInspectBytes int64 = 4 << 20
// and extracts the bare tool name when present, or sets allowStreamInit for
// session handshake, capability discovery, and protocol notification methods
// that precede a tool call.
//
// The backend receives the same bytes and reads them with its own parser, so
// the method and the tool read here must be the ones every parser reads. A
// body that is not one JSON object, or that states "method", "params" or the
// tool "name" more than once (uniqueJSONMembers), names no tool and no
// handshake method: a task rule with allowed_tools denies it.
func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) {
if len(bytes.TrimSpace(body)) == 0 {
return "", false
}
var rpc struct {
Method string `json:"method"`
Params json.RawMessage `json:"params"`
members, err := uniqueJSONMembers(body, "method", "params")
if err != nil {
return "", false
}
if err := json.Unmarshal(body, &rpc); err != nil {
var method string
if err := json.Unmarshal(members["method"], &method); err != nil {
return "", false
}
switch rpc.Method {
switch method {
case "initialize", "notifications/initialized", "server/discover", "ping",
"tools/list", "resources/list", "prompts/list", "notifications/cancelled":
return "", true
case "tools/call":
var params struct {
Name string `json:"name"`
}
if err := json.Unmarshal(rpc.Params, &params); err != nil {
name, err := MCPToolCallName(members["params"])
if err != nil {
return "", false
}
rawTool := strings.TrimSpace(params.Name)
rawTool := strings.TrimSpace(name)
if rawTool == "" {
return "", false
}
Expand All @@ -78,6 +84,65 @@ func InspectJSONRPCMCPBody(body []byte) (mcpTool string, allowStreamInit bool) {
}
}

// MCPToolCallName returns the tool that the params of an MCP tools/call name.
// It fails when params is not one JSON object with one "name" member that
// holds a non-empty string (uniqueJSONMembers), so the tool an enforcement
// point checks is the tool the backend runs.
func MCPToolCallName(params []byte) (string, error) {
members, err := uniqueJSONMembers(params, "name")
if err != nil {
return "", fmt.Errorf("params: %w", err)
}
var name string
if err := json.Unmarshal(members["name"], &name); err != nil || name == "" {
return "", errors.New(`params: no "name" member with a non-empty string`)
}
return name, nil
}

// uniqueJSONMembers returns the values of the named members of the JSON
// object doc. It fails when doc does not say the same thing to every JSON
// parser: when it is not one valid JSON object and nothing else, when a named
// member occurs more than once, and when a member differs from a name only in
// letter case. A case-insensitive parser, encoding/json among them, reads
// such a member as the named one and keeps the last; most others ignore it.
func uniqueJSONMembers(doc []byte, names ...string) (map[string]json.RawMessage, error) {
// One value and nothing after it: the decoder below reads the first
// value of a stream and does not look at what follows it.
if !json.Valid(doc) {
return nil, errors.New("not one valid JSON value")
}
dec := json.NewDecoder(bytes.NewReader(doc))
if tok, err := dec.Token(); err != nil || tok != json.Delim('{') {
return nil, errors.New("not a JSON object")
}
members := make(map[string]json.RawMessage, len(names))
for dec.More() {
tok, err := dec.Token()
key, isString := tok.(string)
if err != nil || !isString {
return nil, errors.New("not a JSON object")
}
var value json.RawMessage
if err := dec.Decode(&value); err != nil {
return nil, err
}
for _, name := range names {
if !strings.EqualFold(key, name) {
continue
}
if key != name {
return nil, fmt.Errorf("member %q differs from %q only in letter case", key, name)
}
if _, seen := members[name]; seen {
return nil, fmt.Errorf("member %q occurs more than once", name)
}
members[name] = value
}
}
return members, nil
}

// InspectMCPHTTPRequestBody buffers and restores r.Body up to maxBytes
// (defaulting to DefaultMaxMCPBodyInspectBytes when maxBytes <= 0) and extracts
// the MCP tool name and stream initialization flag.
Expand Down
56 changes: 56 additions & 0 deletions api/mcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,62 @@ func TestInspectJSONRPCMCPBody(t *testing.T) {
wantTool: "",
wantAllow: false,
},
// The body goes to the backend as the same bytes. A member that two
// parsers read differently names no tool and no handshake method.
{
name: "method again in upper case",
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_file"},"METHOD":"ping"}`,
wantTool: "",
wantAllow: false,
},
{
name: "params again in upper case",
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_file"},"PARAMS":{"name":"read_file"}}`,
wantTool: "",
wantAllow: false,
},
{
name: "tool name again in upper case",
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_file","NAME":"read_file"}}`,
wantTool: "",
wantAllow: false,
},
{
name: "params again with a letter that folds to s",
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_file"},"paramſ":{"name":"read_file"}}`,
wantTool: "",
wantAllow: false,
},
{
name: "method twice",
body: `{"jsonrpc":"2.0","id":1,"method":"ping","method":"tools/call","params":{"name":"read_file"}}`,
wantTool: "",
wantAllow: false,
},
{
name: "method twice, one escaped",
body: `{"jsonrpc":"2.0","id":1,"\u006dethod":"ping","method":"tools/call","params":{"name":"read_file"}}`,
wantTool: "",
wantAllow: false,
},
{
name: "tool name twice",
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_file","name":"delete_file"}}`,
wantTool: "",
wantAllow: false,
},
{
name: "second message after the first",
body: `{"jsonrpc":"2.0","id":1,"method":"ping"} {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"delete_file"}}`,
wantTool: "",
wantAllow: false,
},
{
name: "arguments may repeat the member names",
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_file","arguments":{"name":"a","NAME":"b","method":"ping","params":{}}}}`,
wantTool: "read_file",
wantAllow: false,
},
}

for _, tc := range cases {
Expand Down
8 changes: 8 additions & 0 deletions internal/controlplane/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2074,16 +2074,24 @@ func nodeRoles(nodeRecord *storage.EnrolledNode, bindings []*api.PolicyBinding)
return roles, nil
}

// nodeRoles is the role set of the node from the stored bindings. When it
// cannot resolve the custom roles it logs the cause and returns the enrolled
// role alone. That set is never wider than the full one and each caller
// grants per role, so the fallback cannot grant more.
func (s *Server) nodeRoles(ctx context.Context, nodeRecord *storage.EnrolledNode) []string {
if nodeRecord == nil {
return nil
}
_, bindings, err := s.store.GetMeshPolicy(ctx)
if err != nil {
if !errors.Is(err, storage.ErrNotFound) {
logger.Warnw("Custom roles not resolved, using the enrolled role alone: mesh policy not read", "peer_id", nodeRecord.PeerID, "role", nodeRecord.Role, "error", err)
}
return []string{nodeRecord.Role}
}
roles, err := nodeRoles(nodeRecord, bindings)
if err != nil {
logger.Warnw("Custom roles not resolved, using the enrolled role alone: enrollment claims not parsed", "peer_id", nodeRecord.PeerID, "role", nodeRecord.Role, "error", err)
return []string{nodeRecord.Role}
}
return roles
Expand Down
Loading
Loading