Skip to content

Agent Mesh

fix: enforce connect-time Model Armor DialContext, guard empty replacement, and use BytesBuilder

Antonio Ojea12dea1138cc4
diff --git a/internal/node/egress_inspect.go b/internal/node/egress_inspect.go
index ae2ed629..d9b93a00 100644
--- a/internal/node/egress_inspect.go
+++ b/internal/node/egress_inspect.go
@@ -577,7 +577,10 @@ func (s *EgressService) callModelArmorAPI(ctx context.Context, cfg *api.ModelArm
client := s.modelArmorClient
if client == nil {
- client = &http.Client{Timeout: timeout}
+ client = &http.Client{
+ Timeout: timeout,
+ Transport: s.newSafeModelArmorTransport(),
+ }
}
resp, err := client.Do(req)
if err != nil {
@@ -634,6 +637,18 @@ func (s *EgressService) callModelArmorAPI(ctx context.Context, cfg *api.ModelArm
return false, replacement, nil
}
+func (s *EgressService) newSafeModelArmorTransport() http.RoundTripper {
+ dial := func(ctx context.Context, _, addr string) (net.Conn, error) {
+ return dialSafeEgressTCP(ctx, addr, s.allowsLocalTarget() || s.modelArmorBaseURL != "")
+ }
+ if dt, ok := http.DefaultTransport.(*http.Transport); ok {
+ cloned := dt.Clone()
+ cloned.DialContext = dial
+ return cloned
+ }
+ return &http.Transport{DialContext: dial}
+}
+
func (s *EgressService) resolveModelArmorEndpoint(ctx context.Context, template string) (string, string, error) {
tmpl := strings.TrimSpace(template)
if tmpl == "" {
@@ -647,19 +662,15 @@ func (s *EgressService) resolveModelArmorEndpoint(ctx context.Context, template
if err != nil || u.Hostname() == "" {
return "", "", fmt.Errorf("invalid model_armor.template URL %q", tmpl)
}
- if ip, pErr := netip.ParseAddr(u.Hostname()); pErr == nil {
+ host := strings.TrimSpace(u.Hostname())
+ if !s.allowsLocalTarget() && (strings.EqualFold(host, "localhost") || strings.HasSuffix(strings.ToLower(host), ".localhost")) {
+ return "", "", fmt.Errorf("model_armor.template URL host %q is in a forbidden local domain", host)
+ }
+ // Connect-time DNS resolution and IP validation against DNS rebinding
+ // are enforced by dialSafeEgressTCP in newSafeModelArmorTransport().
+ if ip, pErr := netip.ParseAddr(host); pErr == nil {
if isForbiddenEgressAddr(ip, s.allowsLocalTarget()) {
- return "", "", fmt.Errorf("model_armor.template URL host %q is in a forbidden IP range", u.Hostname())
- }
- } else {
- ips, lErr := net.DefaultResolver.LookupNetIP(ctx, "ip", u.Hostname())
- if lErr != nil {
- return "", "", fmt.Errorf("failed to resolve model_armor.template URL host %q: %w", u.Hostname(), lErr)
- }
- for _, resolvedIP := range ips {
- if isForbiddenEgressAddr(resolvedIP, s.allowsLocalTarget()) {
- return "", "", fmt.Errorf("model_armor.template URL host %q resolves to forbidden IP %s", u.Hostname(), resolvedIP)
- }
+ return "", "", fmt.Errorf("model_armor.template URL host %q is in a forbidden IP range", host)
}
}
return tmpl, "", nil
@@ -758,6 +769,9 @@ func replaceInspectableText(body []byte, original, replacement string) ([]byte,
if original == replacement {
return body, nil
}
+ if original == "" {
+ return nil, errors.New("cannot replace empty original inspectable text")
+ }
var doc map[string]any
if err := json.Unmarshal(body, &doc); err != nil {
return bytes.ReplaceAll(body, []byte(original), []byte(replacement)), nil
@@ -802,7 +816,7 @@ func replaceInspectableText(body []byte, original, replacement string) ([]byte,
if modified {
return json.Marshal(updated)
}
- if bytes.Contains(body, []byte(original)) {
+ if original != "" && bytes.Contains(body, []byte(original)) {
return bytes.ReplaceAll(body, []byte(original), []byte(replacement)), nil
}
return nil, errors.New("failed to map inspection replacement back into structured JSON payload")
@@ -814,7 +828,7 @@ func replaceStringInJSONValue(v any, original, replacement string) (any, bool) {
if val == original {
return replacement, true
}
- if strings.Contains(val, original) {
+ if original != "" && strings.Contains(val, original) {
return strings.ReplaceAll(val, original, replacement), true
}
return val, false
diff --git a/internal/node/egress_inspect_test.go b/internal/node/egress_inspect_test.go
index 9d819d42..238eef5e 100644
--- a/internal/node/egress_inspect_test.go
+++ b/internal/node/egress_inspect_test.go
@@ -701,6 +701,11 @@ func TestReplaceInspectableTextMultiMessageNewlineAndFailClosed(t *testing.T) {
if _, err := replaceInspectableText(body, extracted, "single-line-summary [REDACTED]"); err == nil {
t.Fatal("expected error when replacement cannot be mapped back into multi-message JSON")
}
+
+ // Empty original search pattern with non-empty replacement must fail-closed rather than corrupting JSON.
+ if _, err := replaceInspectableText([]byte(`{"other":"value"}`), "", "[REDACTED]"); err == nil {
+ t.Fatal("expected error when original inspectable text is empty and replacement is non-empty")
+ }
}
func TestResolveModelArmorEndpointSSRF(t *testing.T) {
@@ -723,6 +728,17 @@ func TestResolveModelArmorEndpointSSRF(t *testing.T) {
}
}
+ // Connect-time DialContext via newSafeModelArmorTransport must also block
+ // connections to loopback/forbidden IPs even if hostname resolution happens at dial time.
+ tr, ok := remoteSvc.newSafeModelArmorTransport().(*http.Transport)
+ if !ok || tr.DialContext == nil {
+ t.Fatal("expected newSafeModelArmorTransport to return *http.Transport with custom DialContext")
+ }
+ if conn, err := tr.DialContext(ctx, "tcp", "localhost:8080"); err == nil {
+ _ = conn.Close()
+ t.Fatal("expected connect-time DialContext to reject localhost:8080 when local target is not allowed")
+ }
+
localSvc, err := newEgressService(&api.EgressDestination{
Name: "api.openai.com",
TargetUrl: "http://127.0.0.1:8080",
@@ -738,3 +754,4 @@ func TestResolveModelArmorEndpointSSRF(t *testing.T) {
t.Fatal("expected link-local metadata IP to be rejected even when local target is allowed")
}
}
+
diff --git a/mobile/sam-node-app/lib/mcp_server.dart b/mobile/sam-node-app/lib/mcp_server.dart
index dacaecf1..383102fd 100644
--- a/mobile/sam-node-app/lib/mcp_server.dart
+++ b/mobile/sam-node-app/lib/mcp_server.dart
@@ -1,6 +1,7 @@
import 'dart:io';
import 'dart:convert';
import 'dart:math';
+import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
@@ -119,16 +120,16 @@ class SamDartMcpServer {
return;
}
- final chunks = <int>[];
+ final builder = BytesBuilder(copy: false);
await for (final chunk in request) {
- if (chunks.length + chunk.length > _maxRequestBodyBytes) {
+ if (builder.length + chunk.length > _maxRequestBodyBytes) {
request.response.statusCode = HttpStatus.requestEntityTooLarge;
await request.response.close();
return;
}
- chunks.addAll(chunk);
+ builder.add(chunk);
}
- final body = utf8.decode(chunks, allowMalformed: true);
+ final body = utf8.decode(builder.takeBytes(), allowMalformed: true);
try {
final jsonRpc = jsonDecode(body);