Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
fix(identity,node): canonicalize Biscuit peer IDs, bound egress response buffering, and accept single AWS Statement
Antonio Ojea75d47b717cbc
diff --git a/internal/controlplane/sts_test.go b/internal/controlplane/sts_test.goindex f102d167..72cd187b 100644--- a/internal/controlplane/sts_test.go+++ b/internal/controlplane/sts_test.go@@ -675,7 +675,7 @@ func TestOAuth21AuthorizationCodePKCEAndTokenExchange(t *testing.T) {}// Verify that a non-canonical (CIDv1 base32) peer ID in Biscuit claims is- // canonicalized before checking IsNodeBanned in authorizeBiscuitForEgress.+ // canonicalized by InspectVerifiedBiscuit and caught by IsNodeBanned in authorizeBiscuitForEgress.if err := store.SetNodeBanned(ctx, nodePeerID.String(), true); err != nil {t.Fatalf("SetNodeBanned: %v", err)}@@ -683,6 +683,14 @@ func TestOAuth21AuthorizationCodePKCEAndTokenExchange(t *testing.T) {if cidV1Str == nodePeerID.String() {t.Fatalf("expected CIDv1 string %q to differ from canonical base58 %q", cidV1Str, nodePeerID.String())}+ unbannedPriv, _, err := crypto.GenerateEd25519Key(rand.Reader)+ if err != nil {+ t.Fatalf("GenerateEd25519Key: %v", err)+ }+ unbannedPeerID, err := peer.IDFromPrivateKey(unbannedPriv)+ if err != nil {+ t.Fatalf("IDFromPrivateKey: %v", err)+ }cpPriv, _, err := store.GetCurrentKey(ctx)if err != nil {t.Fatalf("GetCurrentKey: %v", err)@@ -693,12 +701,16 @@ func TestOAuth21AuthorizationCodePKCEAndTokenExchange(t *testing.T) {IDs: []biscuit.Term{biscuit.Date(time.Now().Add(time.Hour))},}})_ = bBuilder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactActorNode,+ Name: api.FactNode,IDs: []biscuit.Term{biscuit.String(cidV1Str)},}})+ _ = bBuilder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactActorNode,+ IDs: []biscuit.Term{biscuit.String(unbannedPeerID.String())},+ }})_ = bBuilder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: api.FactClientPeerID,- IDs: []biscuit.Term{biscuit.String(cidV1Str)},+ IDs: []biscuit.Term{biscuit.String(unbannedPeerID.String())},}})_ = bBuilder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: api.FactUser,@@ -712,7 +724,14 @@ func TestOAuth21AuthorizationCodePKCEAndTokenExchange(t *testing.T) {if err != nil {t.Fatalf("nonCanonicalB.Serialize: %v", err)}- if _, status, err := srv.authorizeBiscuitForEgress(ctx, nonCanonicalBiscuit, "bigquery.googleapis.com"); err == nil || status != http.StatusForbidden {- t.Fatalf("expected authorizeBiscuitForEgress to reject banned CIDv1 peer ID with 403, got status=%d err=%v", status, err)+ inspected, err := identity.InspectVerifiedBiscuit(nonCanonicalBiscuit, []ed25519.PublicKey{cpPubKey}, time.Second)+ if err != nil {+ t.Fatalf("InspectVerifiedBiscuit: %v", err)+ }+ if inspected.NodePeerID != nodePeerID.String() {+ t.Fatalf("expected InspectVerifiedBiscuit to canonicalize NodePeerID to %q, got %q", nodePeerID.String(), inspected.NodePeerID)+ }+ if _, status, err := srv.authorizeBiscuitForEgress(ctx, nonCanonicalBiscuit, "bigquery.googleapis.com"); err == nil || status != http.StatusForbidden || !strings.Contains(err.Error(), "is banned") {+ t.Fatalf("expected authorizeBiscuitForEgress to reject banned CIDv1 peer ID with 403 'is banned', got status=%d err=%v", status, err)}}diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.goindex f6210b62..93b1504e 100644--- a/internal/identity/biscuit.go+++ b/internal/identity/biscuit.go@@ -912,15 +912,39 @@ func InspectVerifiedBiscuit(biscuitData []byte, trustedPublicKeys []ed25519.Publreturn vals[0]}+ canonicalPeer := func(factName string) (string, error) {+ raw := firstString(factName)+ if raw == "" {+ return "", nil+ }+ p, err := peer.Decode(raw)+ if err != nil {+ return "", fmt.Errorf("invalid %s peer ID in biscuit: %w", factName, err)+ }+ return p.String(), nil+ }+ nodePeerID, err := canonicalPeer(api.FactNode)+ if err != nil {+ return nil, err+ }+ actorNodePeerID, err := canonicalPeer(api.FactActorNode)+ if err != nil {+ return nil, err+ }+ clientPeerID, err := canonicalPeer(api.FactClientPeerID)+ if err != nil {+ return nil, err+ }+return &VerifiedBiscuitClaims{Biscuit: b,VerifyingKey: verifyingKey,User: firstString(api.FactUser),Email: firstString(api.FactEmail),Roles: queryStrings(api.FactRole),- NodePeerID: firstString(api.FactNode),- ActorNodePeerID: firstString(api.FactActorNode),- ClientPeerID: firstString(api.FactClientPeerID),+ NodePeerID: nodePeerID,+ ActorNodePeerID: actorNodePeerID,+ ClientPeerID: clientPeerID,Expiration: expiry,RevocationIDs: b.RevocationIds(),TaskRules: rules,diff --git a/internal/node/egress_broker.go b/internal/node/egress_broker.goindex dbec4f54..038682d3 100644--- a/internal/node/egress_broker.go+++ b/internal/node/egress_broker.go@@ -712,18 +712,34 @@ func CompileAWSSessionPolicy(templateJSON, destName string, rules []*api.TaskAutvar tmplResources []stringhasTemplate := strings.TrimSpace(templateJSON) != ""if hasTemplate {+ type awsStatement struct {+ Effect string `json:"Effect"`+ Action any `json:"Action"`+ Resource any `json:"Resource"`+ }var doc struct {- Version string `json:"Version"`- Statement []struct {- Effect string `json:"Effect"`- Action any `json:"Action"`- Resource any `json:"Resource"`- } `json:"Statement"`+ Version string `json:"Version"`+ Statement json.RawMessage `json:"Statement"`}if err := json.Unmarshal([]byte(templateJSON), &doc); err != nil {return "", fmt.Errorf("invalid aws_assume_role.session_policy JSON: %w", err)}- for _, st := range doc.Statement {+ var statements []awsStatement+ trimmedStmt := bytes.TrimSpace(doc.Statement)+ if len(trimmedStmt) > 0 {+ if trimmedStmt[0] == '[' {+ if err := json.Unmarshal(trimmedStmt, &statements); err != nil {+ return "", fmt.Errorf("invalid aws_assume_role.session_policy Statement array: %w", err)+ }+ } else {+ var st awsStatement+ if err := json.Unmarshal(trimmedStmt, &st); err != nil {+ return "", fmt.Errorf("invalid aws_assume_role.session_policy Statement object: %w", err)+ }+ statements = []awsStatement{st}+ }+ }+ for _, st := range statements {if !strings.EqualFold(st.Effect, "Allow") {continue}diff --git a/internal/node/egress_broker_test.go b/internal/node/egress_broker_test.goindex 88ac26f7..132364cc 100644--- a/internal/node/egress_broker_test.go+++ b/internal/node/egress_broker_test.go@@ -435,3 +435,36 @@ type exchangerFunc func(ctx context.Context, principal string, rules []*api.Taskfunc (f exchangerFunc) Exchange(ctx context.Context, principal string, rules []*api.TaskAuthorizationRule) (string, time.Time, error) {return f(ctx, principal, rules)}++func TestCompileAWSSessionPolicySingleStatementObject(t *testing.T) {+ singleStmtTemplate := `{+ "Version": "2012-10-17",+ "Statement": {+ "Effect": "Allow",+ "Action": ["s3:GetObject", "s3:PutObject"],+ "Resource": "arn:aws:s3:::corp-bucket/*"+ }+ }`+ tar := &api.TaskAuthorizationRule{+ Name: "read-only-s3",+ Rules: []*api.TaskRule{+ {+ AllowedServices: []string{"egress://s3.amazonaws.com"},+ AllowedResources: []string{"arn:aws:s3:::corp-bucket/reports/*"},+ Operation: &api.TaskOperation{+ AllowedPermissions: []string{"s3:GetObject"},+ },+ },+ },+ }+ compiled, err := CompileAWSSessionPolicy(singleStmtTemplate, "s3.amazonaws.com", []*api.TaskAuthorizationRule{tar})+ if err != nil {+ t.Fatalf("CompileAWSSessionPolicy with single Statement object failed: %v", err)+ }+ if !strings.Contains(compiled, "s3:GetObject") || strings.Contains(compiled, "s3:PutObject") {+ t.Fatalf("unexpected compiled policy actions: %s", compiled)+ }+ if !strings.Contains(compiled, "arn:aws:s3:::corp-bucket/reports/*") {+ t.Fatalf("unexpected compiled policy resources: %s", compiled)+ }+}diff --git a/internal/node/egress_inspect.go b/internal/node/egress_inspect.goindex 6e6dafb7..a83e9284 100644--- a/internal/node/egress_inspect.go+++ b/internal/node/egress_inspect.go@@ -22,7 +22,6 @@ import ("fmt""io""net/http"- "net/http/httptest""strconv""strings""time"@@ -40,6 +39,56 @@ const (defaultModelArmorTimeout = 5 * time.Second)+// boundedResponseRecorder buffers an upstream HTTP response up to maxBytes+1+// so response inspection cannot consume unbounded memory on large or streaming+// upstream payloads.+type boundedResponseRecorder struct {+ header http.Header+ body bytes.Buffer+ code int+ wroteHeader bool+ maxBytes int64+ overflowed bool+}++func newBoundedResponseRecorder(maxBytes int64) *boundedResponseRecorder {+ if maxBytes <= 0 {+ maxBytes = defaultExtProcMaxBufferBytes+ }+ return &boundedResponseRecorder{+ header: make(http.Header),+ code: http.StatusOK,+ maxBytes: maxBytes,+ }+}++func (r *boundedResponseRecorder) Header() http.Header {+ return r.header+}++func (r *boundedResponseRecorder) WriteHeader(statusCode int) {+ if r.wroteHeader {+ return+ }+ r.code = statusCode+ r.wroteHeader = true+}++func (r *boundedResponseRecorder) Write(p []byte) (int, error) {+ if !r.wroteHeader {+ r.WriteHeader(http.StatusOK)+ }+ remaining := (r.maxBytes + 1) - int64(r.body.Len())+ if int64(len(p)) > remaining {+ if remaining > 0 {+ _, _ = r.body.Write(p[:remaining])+ }+ r.overflowed = true+ return 0, errors.New("response body exceeds max_buffered_bytes")+ }+ return r.body.Write(p)+}+// isProtectedEgressHeader reports whether a header name is off-limits to an// ext_proc inspector. Inspectors may add/modify application headers, or block a// request, but must never select or overwrite credentials, host routing, or@@ -206,18 +255,21 @@ func (s *EgressService) serveInspectedEgress(w http.ResponseWriter, r *http.RequcallerCtx := s.extractCallerContext(r.Context())+ maxBytes := int64(defaultExtProcMaxBufferBytes)+ hasExplicitMax := false+ for _, ins := range inspectors {+ if ep := ins.GetExtProc(); ep != nil && ep.GetMaxBufferedBytes() > 0 {+ if !hasExplicitMax || int64(ep.GetMaxBufferedBytes()) > maxBytes {+ maxBytes = int64(ep.GetMaxBufferedBytes())+ hasExplicitMax = true+ }+ }+ }+// Read and buffer the request body once if present so multiple inspectors can// inspect and optionally rewrite it before forwarding upstream.var reqBody []byteif r.Body != nil && r.Body != http.NoBody {- maxBytes := int64(defaultExtProcMaxBufferBytes)- for _, ins := range inspectors {- if ep := ins.GetExtProc(); ep != nil && ep.GetMaxBufferedBytes() > 0 {- if int64(ep.GetMaxBufferedBytes()) > maxBytes {- maxBytes = int64(ep.GetMaxBufferedBytes())- }- }- }var err errorreqBody, err = io.ReadAll(io.LimitReader(r.Body, maxBytes+1))_ = r.Body.Close()@@ -374,11 +426,11 @@ func (s *EgressService) serveInspectedEgress(w http.ResponseWriter, r *http.Requreturn}- rec := httptest.NewRecorder()+ rec := newBoundedResponseRecorder(maxBytes)proxy.ServeHTTP(rec, r)- respStatus := rec.Code+ respStatus := rec.coderespHeader := rec.Header().Clone()- respBody := rec.Body.Bytes()+ respBody := rec.body.Bytes()// Run response phase across active ext_proc streams and BUFFERED ModelArmor inspectors.for _, as := range activeStreams {@@ -396,6 +448,10 @@ func (s *EgressService) serveInspectedEgress(w http.ResponseWriter, r *http.Requ}respBody = mutatedBody}+ if rec.overflowed {+ refuse(w, http.StatusBadGateway, "upstream response exceeds max_buffered_bytes", proxyStatusDenied)+ return+ }for _, ins := range inspectors {ma := ins.GetModelArmor()diff --git a/internal/node/egress_inspect_test.go b/internal/node/egress_inspect_test.goindex 221ff4e7..35dc5308 100644--- a/internal/node/egress_inspect_test.go+++ b/internal/node/egress_inspect_test.go@@ -705,3 +705,18 @@ func TestExtProcEgressClientAgainstSubprocessCallout(t *testing.T) {t.Fatalf("expected 502 on trailers-only gRPC rejection, got %d", recErr.Code)}}++func TestBoundedResponseRecorderOverflow(t *testing.T) {+ rec := newBoundedResponseRecorder(16)+ n, err := rec.Write([]byte("0123456789"))+ if err != nil || n != 10 || rec.overflowed {+ t.Fatalf("expected first write to succeed: n=%d err=%v overflowed=%v", n, err, rec.overflowed)+ }+ _, err = rec.Write([]byte("0123456789"))+ if err == nil || !rec.overflowed {+ t.Fatalf("expected second write exceeding maxBytes=16 to overflow: err=%v overflowed=%v", err, rec.overflowed)+ }+ if rec.body.Len() > 17 {+ t.Fatalf("expected bounded buffer to cap at maxBytes+1 (17), got %d", rec.body.Len())+ }+}