Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
fail closed on missing wiring, warn on insecure TLS, pin the tar_block grammar
Antonio Ojea9c33ad45b3a7
diff --git a/cmd/sam-control-plane/main.go b/cmd/sam-control-plane/main.goindex c84c038b..0d7779ef 100644--- a/cmd/sam-control-plane/main.go+++ b/cmd/sam-control-plane/main.go@@ -91,6 +91,9 @@ func main() {if oidcIssuer == "" && workloadIssuer == "" {logger.Fatalf("OIDC issuer is required (use --issuer or --workload-issuer flag)")}+ if insecureSkipTLSVerify {+ logger.Warnf("--insecure-skip-tls-verify is set: identity provider TLS certificates are not verified, so anyone on the path to the provider can forge the identities this control plane admits. For development only.")+ }adminToken, err := secrets.FromPathOrEnv("admin-token", adminTokenPath, "SAM_ADMIN_TOKEN")if err != nil {diff --git a/internal/node/openai_facade.go b/internal/node/openai_facade.goindex d6ff9875..07c6b6a8 100644--- a/internal/node/openai_facade.go+++ b/internal/node/openai_facade.go@@ -467,11 +467,14 @@ func (f *openAIFacade) handleCompletions(w http.ResponseWriter, r *http.Request)}func (f *openAIFacade) serveLocal(w http.ResponseWriter, r *http.Request, serviceName string) {- if f.authorizeLocal != nil {- if err := f.authorizeLocal(r.Context(), serviceName, r.Method, r.URL.Path); err != nil {- writeOpenAIError(w, http.StatusForbidden, "permission_denied", fmt.Sprintf("authorization failed: %v", err))- return- }+ if f.authorizeLocal == nil {+ writeOpenAIError(w, http.StatusServiceUnavailable, "authorization_unavailable",+ "local authorization is unavailable on this node")+ return+ }+ if err := f.authorizeLocal(r.Context(), serviceName, r.Method, r.URL.Path); err != nil {+ writeOpenAIError(w, http.StatusForbidden, "permission_denied", fmt.Sprintf("authorization failed: %v", err))+ return}for _, svc := range f.localServices() {if svc.Info().GetName() != serviceName || svc.Handler() == nil {diff --git a/internal/node/openai_facade_test.go b/internal/node/openai_facade_test.goindex 9818ca6e..93678150 100644--- a/internal/node/openai_facade_test.go+++ b/internal/node/openai_facade_test.go@@ -50,8 +50,9 @@ func newFakeModelService(name string, handler http.Handler, models ...string) *f}// newTestFacade builds a facade with inert seams; tests override as needed.-// The provider verifier accepts everyone: tests that care about the gate-// replace it, and tests of the fail-closed path set it to nil explicitly.+// The provider verifier and the local authorizer accept everyone: tests that+// care about a gate replace it, and tests of the fail-closed path set it to+// nil explicitly.func newTestFacade() *openAIFacade {return &openAIFacade{ttl: time.Minute,@@ -64,6 +65,7 @@ func newTestFacade() *openAIFacade {return nil, nil},verifyPeerLabels: func(context.Context, string, map[string]string) error { return nil },+ authorizeLocal: func(context.Context, string, string, string) error { return nil },}}@@ -237,6 +239,29 @@ func TestFacade_Completions_PrefersLocal(t *testing.T) {}}+// A facade without a local authorizer must not serve local models: the+// seam is wiring, and missing wiring is a refusal, not an allow.+func TestFacade_Completions_LocalWithoutAuthorizerFailsClosed(t *testing.T) {+ f := newTestFacade()+ f.authorizeLocal = nil+ localHit := false+ local := newFakeModelService("local-llm", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ localHit = true+ }), "m1")+ f.localServices = func() []Service { return []Service{local} }++ req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"m1"}`))+ rec := httptest.NewRecorder()+ f.handleCompletions(rec, req)++ if localHit {+ t.Fatal("local service was invoked without authorization")+ }+ if rec.Code != http.StatusServiceUnavailable {+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusServiceUnavailable, rec.Body.String())+ }+}+func TestFacade_Completions_UnknownModel(t *testing.T) {f := newTestFacade()req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"nope"}`))diff --git a/sdk/js/src/authorizer.test.ts b/sdk/js/src/authorizer.test.tsindex 87308dac..b77b4251 100644--- a/sdk/js/src/authorizer.test.ts+++ b/sdk/js/src/authorizer.test.ts@@ -23,6 +23,7 @@ import { before, test } from "node:test";import { AuthorizationError, authorizeCaller, type AuthorizeRequest } from "./authorizer.ts";import { BiscuitVerificationError, attenuateBiscuit, loadBiscuit, sealBiscuit } from "./biscuit.ts";import { BASELINE_DATALOG } from "./gen/datalog.ts";+import { encodeTARBlockFact } from "./tar.ts";type Wasm = Awaited<ReturnType<typeof loadBiscuit>>;@@ -284,3 +285,42 @@ test("attenuateBiscuit and sealBiscuit narrow authority across hops", async () =);});+// An appended block may carry exactly one tar_block fact. Anything else a+// holder writes there (a rule, a check, a second fact) is refused before the+// Datalog runs, whatever the authority block grants.+test("appended blocks carrying anything but one tar_block fact are refused", async () => {+ const root = nodeToken(CALLER, [`granted_service_all_types(true)`, `target_unrestricted(true)`]);+ const tarFact = encodeTARBlockFact({ name: "hop", rules: [{ allowedServices: ["mcp://calc"] }] });+ const append = (build: (block: ReturnType<Wasm["Biscuit"]["block_builder"]>) => void): Uint8Array => {+ const token = wasm.Biscuit.fromBytes(root, cpKeyPair.getPublicKey());+ const block = wasm.Biscuit.block_builder();+ build(block);+ return token.appendBlock(block).toBytes();+ };++ const malformed: Record<string, Uint8Array> = {+ rule: append((b) => b.addRule(wasm.Rule.fromString(`role("sam:role:router") <- role("sam:role:node")`))),+ check: append((b) => b.addCheck(wasm.Check.fromString(`check if true`))),+ "extra fact": append((b) => {+ b.addFact(wasm.Fact.fromString(tarFact));+ b.addFact(wasm.Fact.fromString(`node(${JSON.stringify(CALLER)})`));+ }),+ "rule beside tar_block": append((b) => {+ b.addFact(wasm.Fact.fromString(tarFact));+ b.addRule(wasm.Rule.fromString(`granted_service_all_types(true) <- role("sam:role:node")`));+ }),+ };+ for (const [name, token] of Object.entries(malformed)) {+ await assert.rejects(+ authorizeCaller(request(token, "mcp://calc"), options([])),+ (err: unknown) => err instanceof AuthorizationError && /tar_block/.test(err.message),+ name,+ );+ }++ // The well-formed block is the control.+ const ok = append((b) => b.addFact(wasm.Fact.fromString(tarFact)));+ const verified = await authorizeCaller(request(ok, "mcp://calc"), options([]));+ assert.equal(verified.taskRules.length, 1);+});+diff --git a/sdk/python/tests/test_authorizer.py b/sdk/python/tests/test_authorizer.pyindex 8341e3b8..b436181e 100644--- a/sdk/python/tests/test_authorizer.py+++ b/sdk/python/tests/test_authorizer.py@@ -266,3 +266,41 @@ def test_attenuate_biscuit_narrows_authority_across_hops():[CP_KEY],)++def test_appended_blocks_carrying_anything_but_one_tar_block_fact_are_refused():+ """An appended block may carry exactly one tar_block fact. Anything else a+ holder writes there (a rule, a check, a second fact) is refused before the+ Datalog runs, whatever the authority block grants."""+ from agent_mesh.tar import encode_tar_block_fact++ root = node_token(CALLER, ["granted_service_all_types(true)", "target_unrestricted(true)"])+ tar_fact = encode_tar_block_fact(sam_pb2.TaskAuthorizationRule(name="hop", rules=[sam_pb2.TaskRule(allowed_services=["mcp://calc"])]))++ def append(build) -> bytes:+ token = ba.Biscuit.from_bytes(root, CP.public_key)+ bb = ba.BlockBuilder()+ build(bb)+ return token.append(bb).to_bytes()++ def rule_only(bb):+ bb.add_rule(ba.Rule('role("sam:role:router") <- role("sam:role:node")'))++ def check_only(bb):+ bb.add_check(ba.Check("check if true"))++ def extra_fact(bb):+ bb.add_fact(ba.Fact(tar_fact))+ bb.add_fact(ba.Fact(f'node("{CALLER}")'))++ def rule_beside_tar_block(bb):+ bb.add_fact(ba.Fact(tar_fact))+ bb.add_rule(ba.Rule('granted_service_all_types(true) <- role("sam:role:node")'))++ for build in (rule_only, check_only, extra_fact, rule_beside_tar_block):+ with pytest.raises(AuthorizationError, match="tar_block"):+ authorize_caller(request(append(build)), options([]))++ # The well-formed block is the control.+ verified = authorize_caller(request(append(lambda bb: bb.add_fact(ba.Fact(tar_fact)))), options([]))+ assert len(verified.task_rules) == 1+