Skip to content

Agent Mesh

mobile, node: per-device API token, authenticated sensor server, coarse location (audit PR 8)

Antonio Ojea3b6dc32f2591
diff --git a/api/policy.go b/api/policy.go
index f9918d49..61799679 100644
--- a/api/policy.go
+++ b/api/policy.go
@@ -20,12 +20,18 @@ const (
)
type ServiceConfig struct {
- Type string `yaml:"type"` // e.g., "mcp", "inference"
- Name string `yaml:"name"`
- Description string `yaml:"description"`
- TargetURL string `yaml:"target_url,omitempty"`
- Command []string `yaml:"command,omitempty"`
- Env map[string]string `yaml:"env,omitempty"`
+ Type string `yaml:"type"` // e.g., "mcp", "inference"
+ Name string `yaml:"name"`
+ Description string `yaml:"description"`
+ TargetURL string `yaml:"target_url,omitempty"`
+ // TargetAuthPath names a file holding the credential the backend at
+ // TargetURL requires: "TOKEN" is sent as "Authorization: Bearer TOKEN",
+ // "user:pass" as HTTP Basic. A file, not a value, for the same reason
+ // the CLI takes --api-token-path: config files are copied, committed and
+ // rendered into ConfigMaps; a credential in one is a credential in all.
+ TargetAuthPath string `yaml:"target_auth_path,omitempty"`
+ Command []string `yaml:"command,omitempty"`
+ Env map[string]string `yaml:"env,omitempty"`
}
// NodeConfig defines the optional attenuation rules and static services for a specific SAM Node.
diff --git a/internal/node/a2a_service.go b/internal/node/a2a_service.go
index 5990098c..3498901c 100644
--- a/internal/node/a2a_service.go
+++ b/internal/node/a2a_service.go
@@ -66,12 +66,16 @@ func (s *A2AService) Probe(ctx context.Context) error {
if !ok {
return fmt.Errorf("a2a service %q has no URL backend to probe", s.info.GetName())
}
- cardURL := strings.TrimSuffix(target.TargetUrl, "/") + "/.well-known/agent-card.json"
+ backend, err := parseBackendTarget(target.TargetUrl)
+ if err != nil {
+ return err
+ }
+ cardURL := strings.TrimSuffix(backend.url.String(), "/") + "/.well-known/agent-card.json"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, cardURL, nil)
if err != nil {
return err
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := backend.client().Do(req)
if err != nil {
return fmt.Errorf("fetch agent card of %q: %w", s.info.GetName(), err)
}
diff --git a/internal/node/backend_target.go b/internal/node/backend_target.go
new file mode 100644
index 00000000..d99d8737
--- /dev/null
+++ b/internal/node/backend_target.go
@@ -0,0 +1,131 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package node
+
+import (
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+)
+
+// backendTarget is a service's target_url split into the address the node
+// dials and the credential it presents there. A target_url may carry that
+// credential as URL userinfo: "http://:token@host" sends "Bearer token",
+// "http://user:pass@host" sends HTTP Basic. Nothing else in the node sees
+// the userinfo: it is not advertised, logged or forwarded to callers.
+type backendTarget struct {
+ url *url.URL // userinfo stripped
+ auth string // Authorization header value, or ""
+}
+
+func parseBackendTarget(raw string) (backendTarget, error) {
+ u, err := url.Parse(raw)
+ if err != nil {
+ // Not %w: url.Error prints the raw URL, userinfo included.
+ return backendTarget{}, errors.New("invalid target URL")
+ }
+ t := backendTarget{url: u}
+ if u.User == nil {
+ return t, nil
+ }
+ pass, _ := u.User.Password()
+ t.auth = authorizationFor(u.User.Username(), pass)
+ clean := *u
+ clean.User = nil
+ t.url = &clean
+ return t, nil
+}
+
+// authorizationFor turns decoded userinfo into an Authorization header value:
+// a password with no user is a bearer token, user and password are Basic.
+func authorizationFor(user, pass string) string {
+ if user == "" {
+ return "Bearer " + pass
+ }
+ return "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))
+}
+
+// rejectInlineBackendCredential refuses a credential written into a config
+// file's target_url; target_auth_path is the channel for that. Userinfo is
+// still honoured on the wire (parseBackendTarget) so an in-process caller,
+// e.g. the mobile app, can pass a per-launch token without ever writing it.
+func rejectInlineBackendCredential(raw string) error {
+ u, err := url.Parse(raw)
+ if err != nil {
+ return errors.New("invalid target_url")
+ }
+ if u.User != nil {
+ return errors.New("target_url must not carry a credential; put it in a file and set target_auth_path")
+ }
+ return nil
+}
+
+// withBackendAuthFile composes the in-memory target URL for a service whose
+// credential lives in a file: the file's content becomes the URL userinfo,
+// which parseBackendTarget turns into the Authorization header and strips
+// before dialling. The credential never returns to disk or to any log.
+func withBackendAuthFile(targetURL, authPath string) (string, error) {
+ data, err := os.ReadFile(authPath)
+ if err != nil {
+ return "", fmt.Errorf("read target_auth_path: %w", err)
+ }
+ cred := strings.TrimSpace(string(data))
+ if cred == "" {
+ return "", fmt.Errorf("target_auth_path %s is empty", authPath)
+ }
+ u, err := url.Parse(targetURL)
+ if err != nil {
+ return "", errors.New("invalid target_url")
+ }
+ if user, pass, ok := strings.Cut(cred, ":"); ok {
+ u.User = url.UserPassword(user, pass)
+ } else {
+ u.User = url.UserPassword("", cred)
+ }
+ return u.String(), nil
+}
+
+// apply sets the backend credential on an outbound request. The operator's
+// configured credential wins over anything a caller sent: the caller's
+// Authorization was for the node, this one is the node's for the backend.
+func (t backendTarget) apply(h http.Header) {
+ if t.auth != "" {
+ h.Set("Authorization", t.auth)
+ }
+}
+
+// client returns an HTTP client that presents the backend credential on
+// every request, for backends dialled through an SDK rather than a proxy.
+func (t backendTarget) client() *http.Client {
+ if t.auth == "" {
+ return http.DefaultClient
+ }
+ return &http.Client{Transport: backendAuthTransport{target: t, base: http.DefaultTransport}}
+}
+
+type backendAuthTransport struct {
+ target backendTarget
+ base http.RoundTripper
+}
+
+func (b backendAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ req = req.Clone(req.Context())
+ b.target.apply(req.Header)
+ return b.base.RoundTrip(req)
+}
diff --git a/internal/node/backend_target_test.go b/internal/node/backend_target_test.go
new file mode 100644
index 00000000..f3786709
--- /dev/null
+++ b/internal/node/backend_target_test.go
@@ -0,0 +1,163 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package node
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/google/sam/api"
+)
+
+func TestParseBackendTarget(t *testing.T) {
+ tests := []struct {
+ raw string
+ wantURL string
+ wantAuth string
+ }{
+ {"http://127.0.0.1:9090", "http://127.0.0.1:9090", ""},
+ {"http://:[email protected]:9090/mcp", "http://127.0.0.1:9090/mcp", "Bearer s3cret"},
+ {"http://alice:[email protected]/v1", "http://backend.example/v1", "Basic YWxpY2U6cHc="},
+ // Percent-encoded userinfo is decoded before it becomes a header.
+ {"http://alice:p%[email protected]", "http://backend.example", "Basic YWxpY2U6cEBzcw=="},
+ }
+ for _, tt := range tests {
+ t.Run(tt.raw, func(t *testing.T) {
+ got, err := parseBackendTarget(tt.raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.url.String() != tt.wantURL {
+ t.Errorf("url = %q, want %q", got.url.String(), tt.wantURL)
+ }
+ if got.auth != tt.wantAuth {
+ t.Errorf("auth = %q, want %q", got.auth, tt.wantAuth)
+ }
+ if strings.Contains(got.url.String(), "@") {
+ t.Errorf("userinfo leaked into the dialled URL %q", got.url)
+ }
+ })
+ }
+ // A malformed URL must not be echoed: url.Error prints it, credential
+ // included.
+ _, err := parseBackendTarget("http://:leaked-secret@[::1")
+ if err == nil {
+ t.Fatal("an unparsable URL must be an error")
+ }
+ if strings.Contains(err.Error(), "leaked-secret") {
+ t.Errorf("parse error echoes the credential: %v", err)
+ }
+}
+
+// Config files are copied, committed and rendered into ConfigMaps, so a
+// credential written into target_url is refused there; target_auth_path
+// reads it from a file and composes the in-memory URL instead.
+func TestBackendCredentialComesFromAFileNotTheConfig(t *testing.T) {
+ if err := rejectInlineBackendCredential("http://:[email protected]:9090"); err == nil {
+ t.Error("a credential inside target_url must be refused in a config file")
+ }
+ if err := rejectInlineBackendCredential("http://127.0.0.1:9090"); err != nil {
+ t.Errorf("a plain target_url must be accepted: %v", err)
+ }
+
+ dir := t.TempDir()
+ tokenFile := filepath.Join(dir, "token")
+ if err := os.WriteFile(tokenFile, []byte("phone-token\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ basicFile := filepath.Join(dir, "basic")
+ if err := os.WriteFile(basicFile, []byte("alice:p@ss"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ for _, tt := range []struct {
+ name, path, wantAuth string
+ }{
+ {"bearer", tokenFile, "Bearer phone-token"},
+ {"basic", basicFile, "Basic YWxpY2U6cEBzcw=="},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ req, err := buildRegisterRequest(api.ServiceConfig{
+ Type: "mcp", Name: "sensors", TargetURL: "http://127.0.0.1:9090/mcp", TargetAuthPath: tt.path,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ target, err := parseBackendTarget(req.GetTargetUrl())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if target.auth != tt.wantAuth {
+ t.Errorf("auth = %q, want %q", target.auth, tt.wantAuth)
+ }
+ if target.url.String() != "http://127.0.0.1:9090/mcp" {
+ t.Errorf("dialled URL = %q", target.url)
+ }
+ })
+ }
+
+ if _, err := buildRegisterRequest(api.ServiceConfig{Type: "mcp", Name: "s", TargetURL: "http://127.0.0.1:1", TargetAuthPath: filepath.Join(dir, "missing")}); err == nil {
+ t.Error("a missing credential file must fail the service, not silently run unauthenticated")
+ }
+ empty := filepath.Join(dir, "empty")
+ if err := os.WriteFile(empty, []byte(" \n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := buildRegisterRequest(api.ServiceConfig{Type: "mcp", Name: "s", TargetURL: "http://127.0.0.1:1", TargetAuthPath: empty}); err == nil {
+ t.Error("an empty credential file must be an error")
+ }
+}
+
+// The credential in target_url is the node's for the backend: it is sent on
+// every proxied request and overrides whatever Authorization the caller
+// sent, which was for the node.
+func TestReverseProxySendsBackendCredential(t *testing.T) {
+ var gotAuth string
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotAuth = r.Header.Get("Authorization")
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer backend.Close()
+
+ h, err := newReverseProxyHandler(strings.Replace(backend.URL, "http://", "http://:phone-token@", 1))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/mcp", nil)
+ req.Header.Set("Authorization", "Bearer caller-token")
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusNoContent {
+ t.Fatalf("status = %d", rec.Code)
+ }
+ if gotAuth != "Bearer phone-token" {
+ t.Errorf("backend saw Authorization %q, want the configured backend credential", gotAuth)
+ }
+
+ // Without a configured credential the caller's header passes through.
+ plain, err := newReverseProxyHandler(backend.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plain.ServeHTTP(httptest.NewRecorder(), req)
+ if gotAuth != "Bearer caller-token" {
+ t.Errorf("without a backend credential the caller's Authorization must pass through, got %q", gotAuth)
+ }
+}
diff --git a/internal/node/config.go b/internal/node/config.go
index ee60b0e5..85f79d7c 100644
--- a/internal/node/config.go
+++ b/internal/node/config.go
@@ -62,6 +62,17 @@ func LoadNodeConfig(path string) (*NodeConfigComplete, error) {
path, config.Version, api.NodeConfigVersionV1Alpha1)
}
+ // A credential written into a file on disk is refused here, not in
+ // CompleteNodeConfig: the mobile FFI builds its config in memory with a
+ // per-launch token that is never written anywhere.
+ for _, svc := range config.Services {
+ if svc.TargetURL != "" {
+ if err := rejectInlineBackendCredential(svc.TargetURL); err != nil {
+ return nil, fmt.Errorf("node config %s, service %q: %w", path, svc.Name, err)
+ }
+ }
+ }
+
return CompleteNodeConfig(config)
}
@@ -97,6 +108,9 @@ func CompleteNodeConfig(config api.NodeConfig) (*NodeConfigComplete, error) {
if err := api.ValidateServiceFormat(svc.Type + "://" + svc.Name); err != nil {
return nil, fmt.Errorf("invalid service config at index %d: %w", i, err)
}
+ if svc.TargetAuthPath != "" && svc.TargetURL == "" {
+ return nil, fmt.Errorf("service %q: target_auth_path needs a target_url", svc.Name)
+ }
}
for _, pStr := range config.Attenuation.Policies {
diff --git a/internal/node/config_test.go b/internal/node/config_test.go
index 3b9190fb..7ecb1db7 100644
--- a/internal/node/config_test.go
+++ b/internal/node/config_test.go
@@ -17,6 +17,7 @@ package node
import (
"os"
"path/filepath"
+ "strings"
"testing"
"github.com/google/sam/api"
@@ -337,6 +338,55 @@ func TestCompleteNodeConfig(t *testing.T) {
}
}
+// A backend credential may not be written into sam-node.yaml: the file is
+// copied, committed and rendered into ConfigMaps. It comes from
+// target_auth_path instead. An in-memory config (the mobile FFI, which
+// passes a per-launch token that is never written) is not held to this.
+func TestBackendCredentialRefusedInConfigFileOnly(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "sam-node.yaml")
+ inline := `version: v1alpha1
+services:
+ - type: mcp
+ name: sensors
+ target_url: "http://:[email protected]:9090"
+`
+ if err := os.WriteFile(path, []byte(inline), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ _, err := LoadNodeConfig(path)
+ if err == nil {
+ t.Fatal("a credential inside target_url in a config file must be refused")
+ }
+ if strings.Contains(err.Error(), "s3cret") {
+ t.Errorf("the refusal must not echo the credential: %v", err)
+ }
+
+ viaFile := `version: v1alpha1
+services:
+ - type: mcp
+ name: sensors
+ target_url: "http://127.0.0.1:9090"
+ target_auth_path: ` + filepath.Join(dir, "token") + `
+`
+ if err := os.WriteFile(path, []byte(viaFile), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ cfg, err := LoadNodeConfig(path)
+ if err != nil {
+ t.Fatalf("target_auth_path form must load: %v", err)
+ }
+ if cfg.Services[0].TargetAuthPath == "" {
+ t.Error("target_auth_path was not carried through")
+ }
+
+ if _, err := CompleteNodeConfig(api.NodeConfig{
+ Services: []api.ServiceConfig{{Type: "mcp", Name: "sensors", TargetURL: "http://:[email protected]:41225"}},
+ }); err != nil {
+ t.Errorf("an in-memory config with a per-launch credential must be accepted: %v", err)
+ }
+}
+
func TestLoadNodeConfigEgressFloor(t *testing.T) {
write := func(t *testing.T, body string) string {
t.Helper()
diff --git a/internal/node/inference_service.go b/internal/node/inference_service.go
index 6c94682b..08659f36 100644
--- a/internal/node/inference_service.go
+++ b/internal/node/inference_service.go
@@ -42,9 +42,10 @@ const backendProbeTTL = 30 * time.Second
// and token usage tracking for OpenAI-compatible endpoints.
type InferenceService struct {
baseService
- backendURL *url.URL
- engine InferenceEngine
- active atomic.Int64
+ backendURL *url.URL
+ backendAuth backendTarget
+ engine InferenceEngine
+ active atomic.Int64
modelsMu sync.Mutex
cachedModels []string
@@ -54,12 +55,13 @@ type InferenceService struct {
func (s *InferenceService) Init(ctx context.Context) error {
switch x := s.backend.(type) {
case *api.RegisterServiceRequest_TargetUrl:
- u, err := url.Parse(x.TargetUrl)
+ target, err := parseBackendTarget(x.TargetUrl)
if err != nil {
- return fmt.Errorf("invalid inference backend URL %q: %w", x.TargetUrl, err)
+ return fmt.Errorf("invalid inference backend URL: %w", err)
}
- s.backendURL = u
- s.engine = newOpenAIEngine(u, nil)
+ s.backendURL = target.url
+ s.backendAuth = target
+ s.engine = newOpenAIEngine(target.url, target.client())
s.handler = s.trackActive(s.newInferenceProxy())
case *api.RegisterServiceRequest_Command:
return fmt.Errorf("command-based backends are not supported for InferenceService")
@@ -115,6 +117,7 @@ func (s *InferenceService) newInferenceProxy() http.Handler {
},
Transport: &inferenceTransport{
backend: s.backendURL,
+ auth: s.backendAuth,
base: http.DefaultTransport,
},
}
@@ -122,6 +125,7 @@ func (s *InferenceService) newInferenceProxy() http.Handler {
type inferenceTransport struct {
backend *url.URL
+ auth backendTarget
base http.RoundTripper
}
@@ -133,6 +137,7 @@ func (t *inferenceTransport) RoundTrip(req *http.Request) (*http.Response, error
attemptReq.Header.Del("X-Forwarded-For")
attemptReq.Header.Del("X-Forwarded-Host")
attemptReq.Header.Del("X-Forwarded-Proto")
+ t.auth.apply(attemptReq.Header)
attemptReq.URL.Scheme = t.backend.Scheme
attemptReq.URL.Host = t.backend.Host
diff --git a/internal/node/mcp_service.go b/internal/node/mcp_service.go
index 0fb80068..a7873c10 100644
--- a/internal/node/mcp_service.go
+++ b/internal/node/mcp_service.go
@@ -140,7 +140,11 @@ func (m *MCPService) Teardown() error {
func (m *MCPService) backendTransport() (mcp.Transport, error) {
switch x := m.backend.(type) {
case *api.RegisterServiceRequest_TargetUrl:
- return &mcp.StreamableClientTransport{Endpoint: x.TargetUrl}, nil
+ target, err := parseBackendTarget(x.TargetUrl)
+ if err != nil {
+ return nil, err
+ }
+ return &mcp.StreamableClientTransport{Endpoint: target.url.String(), HTTPClient: target.client()}, nil
case *api.RegisterServiceRequest_Command:
if x.Command == nil || len(x.Command.Command) == 0 {
return nil, fmt.Errorf("missing command for command-backed MCP service %q", m.info.GetName())
diff --git a/internal/node/service.go b/internal/node/service.go
index 28487857..5969d510 100644
--- a/internal/node/service.go
+++ b/internal/node/service.go
@@ -19,7 +19,6 @@ import (
"fmt"
"net/http"
"net/http/httputil"
- "net/url"
"os/exec"
"strings"
@@ -51,10 +50,11 @@ type baseService struct {
// newReverseProxyHandler builds a single-host reverse-proxy handler for a
// URL backend. Same code path as today's URL branch in RegisterService.
func newReverseProxyHandler(targetURL string) (http.Handler, error) {
- u, err := url.Parse(targetURL)
+ target, err := parseBackendTarget(targetURL)
if err != nil {
- return nil, fmt.Errorf("invalid target URL: %w", err)
+ return nil, err
}
+ u := target.url
return &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) {
noTrailingSlash := pr.In.Header.Get(api.HeaderSamNoTrailingSlash) == "true"
@@ -63,6 +63,7 @@ func newReverseProxyHandler(targetURL string) (http.Handler, error) {
// is addressed by its configured URL.
pr.Out.Host = u.Host
pr.Out.Header.Del(api.HeaderSamNoTrailingSlash)
+ target.apply(pr.Out.Header)
if noTrailingSlash && !strings.HasSuffix(u.Path, "/") && strings.HasSuffix(pr.Out.URL.Path, "/") {
pr.Out.URL.Path = strings.TrimSuffix(pr.Out.URL.Path, "/")
}
@@ -143,7 +144,14 @@ func buildRegisterRequest(sCfg api.ServiceConfig) (*api.RegisterServiceRequest,
}
switch {
case sCfg.TargetURL != "":
- req.Backend = &api.RegisterServiceRequest_TargetUrl{TargetUrl: sCfg.TargetURL}
+ target := sCfg.TargetURL
+ if sCfg.TargetAuthPath != "" {
+ var err error
+ if target, err = withBackendAuthFile(target, sCfg.TargetAuthPath); err != nil {
+ return nil, fmt.Errorf("service %s: %w", sCfg.Name, err)
+ }
+ }
+ req.Backend = &api.RegisterServiceRequest_TargetUrl{TargetUrl: target}
case len(sCfg.Command) > 0:
req.Backend = &api.RegisterServiceRequest_Command{
Command: &api.CommandBackend{
diff --git a/mobile/sam-node-app/README.md b/mobile/sam-node-app/README.md
index b3298444..c27656fb 100644
--- a/mobile/sam-node-app/README.md
+++ b/mobile/sam-node-app/README.md
@@ -64,7 +64,7 @@ Once launched, the app displays a control interface:
1. **Control plane URL**: The address of the SAM control plane (e.g., `https://bananas.sam-mesh.dev`).
2. **Enrollment JWT**: A valid JWT token retrieved from your OIDC provider to authenticate the node registration.
-3. **Local API Token**: The secret bearer token used to secure the local sidecar REST APIs (defaults to `secret-token`).
+3. **Local API Token**: The bearer token that secures the local sidecar REST API. It is generated on first launch and kept in the app's private storage; view, copy or regenerate it on the **Config** tab. There is no default: Android loopback is shared by every installed app, so a fixed value would let any of them act as this node.
4. **Enroll Node**: Click this button first to generate the local Peer Identity and register the node with the control plane.
5. **Start Node**: Launches the Go node runtime in the background. It will bind its local MCP sidecar to `127.0.0.1:5005`.
6. **Stop Node**: Gracefully shuts down the background Go mesh client.
@@ -111,23 +111,24 @@ You can query the phone's telemetry from a remote machine (or another node) usin
1. **Discover tools on the remote phone service**:
```bash
# Query the local SAM node proxy for tools hosted by the phone-sensors peer
+ # (-token is your own node's API token, not the phone's)
go run cmd/mcp-client/main.go \
-url "http://localhost:8080/sam/<PHONE_PEER_ID>/mcp/phone-sensors" \
- -token "secret-token" \
+ -token "$(cat ~/.config/sam-mesh/api-token)" \
-list
```
*Output:*
* `get_battery_status`: Returns the current battery level and charging status of the device.
- * `get_location`: Returns the current coarse location of the device.
+ * `get_location`: Returns the approximate location of the device, rounded to about a kilometre.
2. **Query the location**:
```bash
go run cmd/mcp-client/main.go \
-url "http://localhost:8080/sam/<PHONE_PEER_ID>/mcp/phone-sensors" \
- -token "secret-token" \
+ -token "$(cat ~/.config/sam-mesh/api-token)" \
-tool "get_location"
```
- *Output:* `{"latitude": 42.2805588, "longitude": -8.6124088}`
+ *Output:* `{"latitude": 42.28, "longitude": -8.61, "precision_km": 1}`
---
diff --git a/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml b/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
index b38c0f47..1488396d 100644
--- a/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
+++ b/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
@@ -1,6 +1,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
@@ -13,7 +12,12 @@
<application
android:label="sam_agent"
android:name=".SamApplication"
- android:icon="@mipmap/ic_launcher">
+ android:icon="@mipmap/ic_launcher"
+ android:allowBackup="false">
+ <!-- allowBackup=false: app data holds the node's private key, its
+ biscuit and the local API token; none of it belongs in a cloud or
+ adb backup, and a restore onto another device would clone the
+ identity. -->
<activity
android:name=".MainActivity"
android:exported="true"
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
index ff98cfe7..eab8f192 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
@@ -46,8 +46,10 @@ class MainActivity : FlutterActivity() {
val enabled = call.argument<Boolean>("enabled") ?: false
Log.d("SAM_NODE", "setExposeLocation: $enabled")
if (enabled) {
+ // Coarse only: the tool promises an approximate position, so
+ // the app must not hold a permission that could give more.
if (androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
- androidx.core.app.ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION), 1001)
+ androidx.core.app.ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION), 1001)
}
}
result.success(true)
@@ -72,18 +74,18 @@ class MainActivity : FlutterActivity() {
result.success("{\"error\": \"Location permission not granted\"}")
return@setMethodCallHandler
}
-
- val hasFineLocation = androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED
+
+ // Network provider only, and rounded to two decimals (about
+ // a kilometre): a mesh peer gets the neighbourhood, not the
+ // building, whatever the platform would hand this app.
val locationManager = getSystemService(Context.LOCATION_SERVICE) as android.location.LocationManager
- val location: android.location.Location? = if (hasFineLocation) {
- locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER)
- ?: locationManager.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER)
- } else {
+ val location: android.location.Location? =
locationManager.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER)
- }
-
+
if (location != null) {
- result.success("{\"latitude\": ${location.latitude}, \"longitude\": ${location.longitude}}")
+ val lat = coarsen(location.latitude)
+ val lon = coarsen(location.longitude)
+ result.success("{\"latitude\": $lat, \"longitude\": $lon, \"precision_km\": 1}")
} else {
result.success("{\"error\": \"No location available\"}")
}
@@ -97,4 +99,7 @@ class MainActivity : FlutterActivity() {
}
}
}
+
+ // Two decimal places of a degree is roughly 1.1 km at the equator.
+ private fun coarsen(degrees: Double): Double = Math.round(degrees * 100.0) / 100.0
}
diff --git a/mobile/sam-node-app/lib/main.dart b/mobile/sam-node-app/lib/main.dart
index 46049fe9..19204d54 100644
--- a/mobile/sam-node-app/lib/main.dart
+++ b/mobile/sam-node-app/lib/main.dart
@@ -83,7 +83,13 @@ class _NodeControlPageState extends State<NodeControlPage> {
final _jwtController = TextEditingController();
// Saved by the FFI at enrollment so Re-enroll can skip the browser.
String _refreshToken = '';
- final _tokenController = TextEditingController(text: 'secret-token');
+ // Bearer token for the sidecar API on 127.0.0.1:5005. Android loopback is
+ // shared by every installed app, so a fixed value would let any of them
+ // act as this node. Generated once and kept in the app-private data dir
+ // next to the identity it protects; shown on the Config tab.
+ static const _apiTokenFile = 'api-token';
+ String _apiToken = '';
+ bool _apiTokenVisible = false;
// Labels are attested at enrollment; changing them requires re-enrolling.
// The field is saved here after a successful enrollment and read back at
// launch, like attenuation.json.
@@ -141,7 +147,6 @@ class _NodeControlPageState extends State<NodeControlPage> {
_pollingTimer?.cancel();
_controlPlaneController.dispose();
_jwtController.dispose();
- _tokenController.dispose();
_labelsController.dispose();
_externalMcpUrlController.dispose();
_externalMcpNameController.dispose();
@@ -157,6 +162,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
final dataDir = '${appDir.path}/sam_data';
final enrolled = _samLib.isEnrolled(dataDir);
await _loadAttenuation(dataDir);
+ await _loadOrCreateApiToken(dataDir);
final labelsFile = File('$dataDir/$_labelsFile');
if (await labelsFile.exists()) {
_labelsController.text = await labelsFile.readAsString();
@@ -193,6 +199,31 @@ class _NodeControlPageState extends State<NodeControlPage> {
}
}
+ Future<void> _loadOrCreateApiToken(String dataDir) async {
+ final file = File('$dataDir/$_apiTokenFile');
+ if (await file.exists()) {
+ final saved = (await file.readAsString()).trim();
+ if (saved.isNotEmpty) {
+ _apiToken = saved;
+ return;
+ }
+ }
+ await _writeApiToken(file, SamDartMcpServer.newToken());
+ }
+
+ Future<void> _writeApiToken(File file, String token) async {
+ await file.parent.create(recursive: true);
+ await file.writeAsString(token, flush: true);
+ _apiToken = token;
+ }
+
+ Future<void> _regenerateApiToken() async {
+ final appDir = await getApplicationDocumentsDirectory();
+ await _writeApiToken(
+ File('${appDir.path}/sam_data/$_apiTokenFile'), SamDartMcpServer.newToken());
+ if (mounted) setState(() {});
+ }
+
// The field keeps the CLI's old --labels wire format. Only the split lives
// here; the FFI validates keys and values with the CLI's rules.
Map<String, String> _parseLabels(String text) {
@@ -792,7 +823,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
// services are declared in the start configuration and probed at startup,
// there is no runtime registration.
try {
- await _embeddedMcpServer.start(port: 9090);
+ await _embeddedMcpServer.start();
} catch (e) {
setState(() {
_status = 'Start failed: embedded MCP server: $e';
@@ -806,7 +837,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
'name': 'phone-sensors',
'description':
'Exposes phone sensors like battery and location to the SAM mesh',
- 'targetUrl': 'http://127.0.0.1:9090',
+ 'targetUrl': _embeddedMcpServer.targetUrl,
},
if (_externalMcpUrlController.text.isNotEmpty &&
_externalMcpNameController.text.isNotEmpty)
@@ -830,7 +861,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
'controlPlaneURL': _controlPlaneController.text,
'meshID': 'public-mesh',
'bindAddr': '127.0.0.1:5005', // sidecar port inside phone
- 'apiToken': _tokenController.text,
+ 'apiToken': _apiToken,
'allowLoopback': true,
'enableRelay': false,
'labels': labels,
@@ -1015,7 +1046,7 @@ class _NodeControlPageState extends State<NodeControlPage> {
),
SwitchListTile(
title: const Text('Location'),
- subtitle: const Text('Share coarse location with mesh peers'),
+ subtitle: const Text('Share approximate location (about 1 km) with mesh peers'),
value: _exposeLocation,
onChanged: (bool value) async {
setState(() {
@@ -1103,6 +1134,68 @@ class _NodeControlPageState extends State<NodeControlPage> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
+ Card(
+ child: Padding(
+ padding: const EdgeInsets.all(16.0),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const Text('Local API Token',
+ style:
+ TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
+ const SizedBox(height: 6),
+ const Text(
+ 'Bearer token for the sidecar API on 127.0.0.1:5005. Any '
+ 'app on this phone that holds it can act as this node, '
+ 'so it is generated here and never a fixed value. '
+ 'Regenerating takes effect on the next Start.',
+ style: TextStyle(fontSize: 12, color: Colors.grey),
+ ),
+ const SizedBox(height: 10),
+ Row(
+ children: [
+ Expanded(
+ child: SelectableText(
+ _apiTokenVisible
+ ? _apiToken
+ : '\u2022' * 24,
+ style: const TextStyle(
+ fontFamily: 'monospace', fontSize: 13),
+ ),
+ ),
+ IconButton(
+ tooltip: _apiTokenVisible ? 'Hide' : 'Show',
+ icon: Icon(_apiTokenVisible
+ ? Icons.visibility_off
+ : Icons.visibility),
+ onPressed: () => setState(
+ () => _apiTokenVisible = !_apiTokenVisible),
+ ),
+ IconButton(
+ tooltip: 'Copy',
+ icon: const Icon(Icons.copy),
+ onPressed: () async {
+ await Clipboard.setData(
+ ClipboardData(text: _apiToken));
+ if (mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(
+ content: Text('Token copied')));
+ }
+ },
+ ),
+ IconButton(
+ tooltip: 'Regenerate',
+ icon: const Icon(Icons.refresh),
+ onPressed: isRunning ? null : _regenerateApiToken,
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 20),
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
diff --git a/mobile/sam-node-app/lib/mcp_server.dart b/mobile/sam-node-app/lib/mcp_server.dart
index a111e8d0..afe6f98c 100644
--- a/mobile/sam-node-app/lib/mcp_server.dart
+++ b/mobile/sam-node-app/lib/mcp_server.dart
@@ -1,5 +1,6 @@
import 'dart:io';
import 'dart:convert';
+import 'dart:math';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
@@ -7,6 +8,9 @@ class SamDartMcpServer {
static const MethodChannel _channel = MethodChannel('com.example.sam_agent/mesh_expose');
HttpServer? _server;
final List<HttpResponse> _sseClients = [];
+ // Android loopback is shared by every installed app, so the port alone is
+ // no boundary: each start mints a token only the node is told about.
+ String? _token;
// Callbacks to check current feature status from UI
final bool Function() isBatteryEnabled;
@@ -17,19 +21,37 @@ class SamDartMcpServer {
required this.isLocationEnabled,
});
- /// Starts the Dart HTTP Server acting as an MCP backend. The service it
- /// backs is declared in the node's start configuration; there is no
- /// runtime registration, so this server must be listening before the node
- /// starts and probes it.
+ /// The URL the node dials, with this launch's credential as userinfo; the
+ /// node turns that into an Authorization header and never advertises it.
+ String get targetUrl {
+ final s = _server;
+ if (s == null || _token == null) throw StateError('not started');
+ return 'http://:[email protected]:${s.port}';
+ }
+
+ static String newToken() {
+ final rng = Random.secure();
+ return base64Url.encode(List<int>.generate(32, (_) => rng.nextInt(256))).replaceAll('=', '');
+ }
+
+ /// Starts the Dart HTTP Server acting as an MCP backend on a random
+ /// loopback port. The service it backs is declared in the node's start
+ /// configuration; there is no runtime registration, so this server must be
+ /// listening before the node starts and probes it.
///
- /// Throws if the port cannot be bound.
- Future<void> start({int port = 9090}) async {
+ /// Throws if no port can be bound.
+ Future<void> start({int port = 0}) async {
if (_server != null) throw StateError('already started');
+ _token = newToken();
_server = await HttpServer.bind(InternetAddress.loopbackIPv4, port);
- debugPrint('SAM Dart MCP Server listening on port $port');
+ debugPrint('SAM Dart MCP Server listening on port ${_server!.port}');
_server!.listen((HttpRequest request) async {
- // Handle CORS if needed, but since it's loopback and called by Go, maybe not strict
+ if (!_authorized(request)) {
+ request.response.statusCode = HttpStatus.unauthorized;
+ await request.response.close();
+ return;
+ }
if (request.method == 'GET') {
_handleSse(request);
} else if (request.method == 'POST') {
@@ -41,10 +63,28 @@ class SamDartMcpServer {
});
}
+ bool _authorized(HttpRequest request) {
+ final token = _token;
+ if (token == null) return false;
+ return constantTimeEquals(request.headers.value(HttpHeaders.authorizationHeader), 'Bearer $token');
+ }
+
+ /// Compares a presented credential without leaking where it diverges.
+ @visibleForTesting
+ static bool constantTimeEquals(String? a, String b) {
+ if (a == null || a.length != b.length) return false;
+ var diff = 0;
+ for (var i = 0; i < a.length; i++) {
+ diff |= a.codeUnitAt(i) ^ b.codeUnitAt(i);
+ }
+ return diff == 0;
+ }
+
/// Stops the server
Future<void> stop() async {
await _server?.close(force: true);
_server = null;
+ _token = null;
_sseClients.clear();
debugPrint('SAM Dart MCP Server stopped');
}
@@ -127,7 +167,7 @@ class SamDartMcpServer {
if (isLocationEnabled()) {
tools.add({
'name': 'get_location',
- 'description': 'Returns the current coarse location of the device.',
+ 'description': 'Returns the approximate location of the device, rounded to about a kilometre.',
'inputSchema': {'type': 'object', 'properties': {}}
});
}
diff --git a/mobile/sam-node-app/test/mcp_server_test.dart b/mobile/sam-node-app/test/mcp_server_test.dart
index 74b94719..0b9e953e 100644
--- a/mobile/sam-node-app/test/mcp_server_test.dart
+++ b/mobile/sam-node-app/test/mcp_server_test.dart
@@ -1,3 +1,6 @@
+import 'dart:convert';
+import 'dart:io';
+
import 'package:flutter_test/flutter_test.dart';
import 'package:sam_agent/mcp_server.dart';
@@ -104,4 +107,77 @@ void main() {
expect(response['error']['code'], -32601); // Method not implemented
});
});
+
+ // Android loopback is shared by every installed app, so the sensor server
+ // must refuse anyone who does not hold this launch's token; only the node,
+ // told the token through target_url userinfo, may reach the sensors.
+ group('SamDartMcpServer loopback authentication', () {
+ late SamDartMcpServer server;
+
+ setUp(() async {
+ server = SamDartMcpServer(
+ isBatteryEnabled: () => true,
+ isLocationEnabled: () => false,
+ );
+ await server.start();
+ });
+
+ tearDown(() => server.stop());
+
+ Future<HttpClientResponse> post(String? authorization) async {
+ final target = Uri.parse(server.targetUrl);
+ final client = HttpClient();
+ try {
+ final req = await client.postUrl(Uri(scheme: 'http', host: target.host, port: target.port, path: '/'));
+ if (authorization != null) {
+ req.headers.set(HttpHeaders.authorizationHeader, authorization);
+ }
+ req.headers.contentType = ContentType.json;
+ req.write(jsonEncode({'jsonrpc': '2.0', 'id': 1, 'method': 'tools/list', 'params': {}}));
+ return await req.close();
+ } finally {
+ client.close();
+ }
+ }
+
+ test('binds a random loopback port and carries the token as userinfo', () {
+ final target = Uri.parse(server.targetUrl);
+ expect(target.host, '127.0.0.1');
+ expect(target.port, isNot(0));
+ expect(target.userInfo, startsWith(':'));
+ expect(target.userInfo.length, greaterThan(32));
+ });
+
+ test('refuses a request without the token', () async {
+ final resp = await post(null);
+ expect(resp.statusCode, HttpStatus.unauthorized);
+ });
+
+ test('refuses a request with a wrong token', () async {
+ final resp = await post('Bearer not-the-token');
+ expect(resp.statusCode, HttpStatus.unauthorized);
+ });
+
+ test('serves a request with this launch token', () async {
+ final token = Uri.parse(server.targetUrl).userInfo.substring(1);
+ final resp = await post('Bearer $token');
+ expect(resp.statusCode, HttpStatus.ok);
+ final body = jsonDecode(await utf8.decoder.bind(resp).join());
+ expect((body['result']['tools'] as List).single['name'], 'get_battery_status');
+ });
+
+ test('each start mints a new token', () async {
+ final first = server.targetUrl;
+ await server.stop();
+ await server.start();
+ expect(server.targetUrl, isNot(first));
+ });
+
+ test('constant-time comparison rejects length and content mismatches', () {
+ expect(SamDartMcpServer.constantTimeEquals('Bearer abc', 'Bearer abc'), isTrue);
+ expect(SamDartMcpServer.constantTimeEquals('Bearer abd', 'Bearer abc'), isFalse);
+ expect(SamDartMcpServer.constantTimeEquals('Bearer ab', 'Bearer abc'), isFalse);
+ expect(SamDartMcpServer.constantTimeEquals(null, 'Bearer abc'), isFalse);
+ });
+ });
}
diff --git a/site/content/docs/user/node-configuration.md b/site/content/docs/user/node-configuration.md
index 07af2184..c38d2bd0 100644
--- a/site/content/docs/user/node-configuration.md
+++ b/site/content/docs/user/node-configuration.md
@@ -71,7 +71,8 @@ The `services` array allows you to register endpoints that remote peers in the S
| `description` | A human-readable description published to the mesh discovery catalogue. |
| `command` | *(For MCP)* The executable command array to spawn as a local subprocess, speaking MCP over stdio (e.g. `["node", "index.js"]`). Mutually exclusive with `target_url`. |
| `env` | *(For MCP)* Key-value environment variables passed to the subprocess. |
-| `target_url` | *(For MCP/Inference/A2A)* The upstream URL to proxy traffic to. For `type: mcp`, this points to an already-running Streamable HTTP MCP server; SAM does not spawn or manage its lifecycle, but only proxies to it. Mutually exclusive with `command`. |
+| `target_url` | *(For MCP/Inference/A2A)* The upstream URL to proxy traffic to. For `type: mcp`, this points to an already-running Streamable HTTP MCP server; SAM does not spawn or manage its lifecycle, but only proxies to it. Mutually exclusive with `command`. Must not carry a credential (`http://user:pass@...` is refused); use `target_auth_path`. |
+| `target_auth_path` | *(Optional, with `target_url`)* Path to a file holding the credential the backend requires: a bare `TOKEN` is sent as `Authorization: Bearer TOKEN`, `user:pass` as HTTP Basic. The node reads the file once at start, presents the credential on every request to the backend (overriding any `Authorization` a caller sent) and never advertises or logs it. A file, not a value, because `sam-node.yaml` is copied, committed and rendered into ConfigMaps; mount a Secret and point here, as with `--api-token-path`. |
### Inference Service Path Standards & Proxy Routing