From 7267f35d74f9712992d6ad9fb070c7bb7d87f5a1 Mon Sep 17 00:00:00 2001 From: Peter Boers Date: Wed, 25 Nov 2026 08:39:22 +0100 Subject: [PATCH 1/2] feat: Dedicated subagents via subAgent.agentRef over the A2A gateway (restores the kagent#2952 API deferred in #3007; SURF carry on planeo/v1.0.1) - api: restore SubAgentToolBinding.agentRef (exactly one of templateRef/agentRef, same namespace), CRDs regenerated. - translator: Dedicated bindings compile to ADK remote_agents pointing at the controller gateway (/agents///.well-known/agent-card.json, 30m timeout, sessions not isolated); self-reference and agentRef inside a Shared child are rejected. - translator: kagent.surf.net/remote-agents annotation for external A2A servers (url entries only, egress origins added; controller origin and IP literals rejected). - runtimeauth: PeerDelegator also accepts an agentRef binding on the caller's own template as the peer declaration; planeo's kagent.planeo.dev/agent-refs keeps working. Upstream: https://github.com/kagent-dev/kagent/issues/3642 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Peter Boers --- go/api/v1alpha3/agenttemplate_types.go | 14 +- go/api/v1alpha3/configuration_crd_cel_test.go | 7 +- go/api/v1alpha3/zz_generated.deepcopy.go | 5 + go/core/internal/runtimeauth/delegation.go | 20 ++- .../internal/runtimeauth/delegation_test.go | 42 ++++++ .../internal/translator/adkconfig/builder.go | 43 +++++- .../translator/adkconfig/dedicated.go | 38 +++++ .../translator/adkconfig/dedicated_test.go | 34 +++++ .../internal/translator/adkconfig/external.go | 92 ++++++++++++ .../translator/adkconfig/external_test.go | 83 +++++++++++ go/core/internal/translator/byo/compiler.go | 2 +- go/core/internal/translator/compiler.go | 59 +++++++- go/core/internal/translator/compiler_test.go | 131 +++++++++++++++++- .../internal/translator/kagent/compiler.go | 2 +- .../templates/api.kagent.dev_agents.yaml | 26 +++- .../api.kagent.dev_agenttemplates.yaml | 24 +++- 16 files changed, 596 insertions(+), 26 deletions(-) create mode 100644 go/core/internal/translator/adkconfig/dedicated.go create mode 100644 go/core/internal/translator/adkconfig/dedicated_test.go create mode 100644 go/core/internal/translator/adkconfig/external.go create mode 100644 go/core/internal/translator/adkconfig/external_test.go diff --git a/go/api/v1alpha3/agenttemplate_types.go b/go/api/v1alpha3/agenttemplate_types.go index 9b4bbcc83e..16a5846742 100644 --- a/go/api/v1alpha3/agenttemplate_types.go +++ b/go/api/v1alpha3/agenttemplate_types.go @@ -71,7 +71,8 @@ type MCPToolBinding struct { RequireApproval bool `json:"requireApproval,omitempty"` } -// SubAgentToolBinding exposes a same-namespace AgentTemplate as a logical tool. +// SubAgentToolBinding exposes a same-namespace AgentTemplate or Agent as a logical tool. +// +kubebuilder:validation:XValidation:rule="has(self.templateRef) != has(self.agentRef)",message="exactly one of templateRef or agentRef must be specified" type SubAgentToolBinding struct { // +kubebuilder:validation:MinLength=1 // +required @@ -82,11 +83,12 @@ type SubAgentToolBinding struct { Description string `json:"description"` // TemplateRef selects a Shared subagent compiled into the parent's runtime using its Harness. // +kubebuilder:validation:XValidation:rule="has(self.name) && self.name != ''",message="templateRef.name must not be empty" - // +required - TemplateRef *corev1.LocalObjectReference `json:"templateRef"` - - // Deferred until Dedicated subagents can create and invoke their own Session. - // AgentRef *corev1.LocalObjectReference `json:"agentRef,omitempty"` + // +optional + TemplateRef *corev1.LocalObjectReference `json:"templateRef,omitempty"` + // AgentRef selects a Dedicated subagent with its own Harness and Session, invoked over A2A. + // +kubebuilder:validation:XValidation:rule="has(self.name) && self.name != ''",message="agentRef.name must not be empty" + // +optional + AgentRef *corev1.LocalObjectReference `json:"agentRef,omitempty"` } // ToolBinding selects exactly one MCP or subagent tool source. diff --git a/go/api/v1alpha3/configuration_crd_cel_test.go b/go/api/v1alpha3/configuration_crd_cel_test.go index 069155f140..1f29cfffa1 100644 --- a/go/api/v1alpha3/configuration_crd_cel_test.go +++ b/go/api/v1alpha3/configuration_crd_cel_test.go @@ -441,8 +441,13 @@ func TestConfigurationCRDValidation(t *testing.T) { wantReject string }{ {name: "template-ref", binding: SubAgentToolBinding{TemplateRef: &corev1.LocalObjectReference{Name: "context"}}}, - {name: "missing-template-ref", wantReject: "templateRef: Required value"}, + {name: "agent-ref", binding: SubAgentToolBinding{AgentRef: &corev1.LocalObjectReference{Name: "peer"}}}, + {name: "both-refs", binding: SubAgentToolBinding{ + TemplateRef: &corev1.LocalObjectReference{Name: "context"}, AgentRef: &corev1.LocalObjectReference{Name: "peer"}, + }, wantReject: "exactly one of templateRef or agentRef must be specified"}, + {name: "neither-ref", wantReject: "exactly one of templateRef or agentRef must be specified"}, {name: "empty-template-ref", binding: SubAgentToolBinding{TemplateRef: &corev1.LocalObjectReference{}}, wantReject: "templateRef.name must not be empty"}, + {name: "empty-agent-ref", binding: SubAgentToolBinding{AgentRef: &corev1.LocalObjectReference{}}, wantReject: "agentRef.name must not be empty"}, } { for _, inline := range []bool{false, true} { name := fmt.Sprintf("subagent-%s-inline-%t", tc.name, inline) diff --git a/go/api/v1alpha3/zz_generated.deepcopy.go b/go/api/v1alpha3/zz_generated.deepcopy.go index 3d2f977e92..9a55bed132 100644 --- a/go/api/v1alpha3/zz_generated.deepcopy.go +++ b/go/api/v1alpha3/zz_generated.deepcopy.go @@ -1950,6 +1950,11 @@ func (in *SubAgentToolBinding) DeepCopyInto(out *SubAgentToolBinding) { *out = new(v1.LocalObjectReference) **out = **in } + if in.AgentRef != nil { + in, out := &in.AgentRef, &out.AgentRef + *out = new(v1.LocalObjectReference) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubAgentToolBinding. diff --git a/go/core/internal/runtimeauth/delegation.go b/go/core/internal/runtimeauth/delegation.go index 84faf7f349..1dbc764bc7 100644 --- a/go/core/internal/runtimeauth/delegation.go +++ b/go/core/internal/runtimeauth/delegation.go @@ -83,13 +83,14 @@ func (d *PeerDelegator) DelegatePeer(ctx context.Context, target types.Namespace return auth.AuthSessionTo(ctx, delegatedSession{owner: actor.owner, agent: callerNamespace + "/" + callerName, sessionID: actor.sessionID}), nil } -// declares reports whether the caller Agent, or the AgentTemplate it references, lists peer in AgentRefsAnnotation. +// declares reports whether the caller Agent, or the AgentTemplate it references, declares peer: either in +// AgentRefsAnnotation or as a Dedicated subAgent.agentRef tool binding of its effective template. func (d *PeerDelegator) declares(ctx context.Context, caller types.NamespacedName, peer string) (bool, error) { var agent v1alpha3.Agent if err := d.kube.Get(ctx, caller, &agent); err != nil { return false, client.IgnoreNotFound(err) } - if listed(agent.GetAnnotations()[AgentRefsAnnotation], peer) { + if listed(agent.GetAnnotations()[AgentRefsAnnotation], peer) || bindsAgentRef(agent.Spec.Template.Inline, peer) { return true, nil } ref := agent.Spec.Template.Ref @@ -103,7 +104,20 @@ func (d *PeerDelegator) declares(ctx context.Context, caller types.NamespacedNam } return false, fmt.Errorf("read AgentTemplate %s/%s: %w", caller.Namespace, ref.Name, err) } - return listed(template.GetAnnotations()[AgentRefsAnnotation], peer), nil + return listed(template.GetAnnotations()[AgentRefsAnnotation], peer) || bindsAgentRef(&template.Spec, peer), nil +} + +// bindsAgentRef reports whether the template has a Dedicated subagent tool that references peer. +func bindsAgentRef(template *v1alpha3.AgentTemplateSpec, peer string) bool { + if template == nil { + return false + } + for _, tool := range template.Tools { + if tool.SubAgent != nil && tool.SubAgent.AgentRef != nil && tool.SubAgent.AgentRef.Name == peer { + return true + } + } + return false } func listed(value, name string) bool { diff --git a/go/core/internal/runtimeauth/delegation_test.go b/go/core/internal/runtimeauth/delegation_test.go index 66293d9f65..03050f9479 100644 --- a/go/core/internal/runtimeauth/delegation_test.go +++ b/go/core/internal/runtimeauth/delegation_test.go @@ -92,6 +92,48 @@ func TestDeclaredPeerIsDelegatedToTheSessionOwner(t *testing.T) { } } +func agentRefTool(peer string) v1alpha3.ToolBinding { + return v1alpha3.ToolBinding{SubAgent: &v1alpha3.SubAgentToolBinding{ + Name: "peer_tool", Description: "peer", AgentRef: &corev1.LocalObjectReference{Name: peer}, + }} +} + +// A Dedicated subAgent.agentRef binding is a declaration, next to the annotation. +func TestAgentRefBindingIsADeclaration(t *testing.T) { + f := newDelegationFixture(t) + inline := func(tools ...v1alpha3.ToolBinding) *v1alpha3.Agent { + agent := callerAgent(nil, "") + agent.Spec.Template.Inline = &v1alpha3.AgentTemplateSpec{Tools: tools} + return agent + } + referenced := func(tools ...v1alpha3.ToolBinding) *v1alpha3.AgentTemplate { + tpl := template("coordinator", nil) + tpl.Spec.Tools = tools + return tpl + } + peer := types.NamespacedName{Namespace: "team-a", Name: "peer"} + for name, test := range map[string]struct { + reader client.Reader + wantDelegated bool + }{ + "inline agentRef": {kube(t, inline(agentRefTool("peer"))), true}, + "referenced-template agentRef": {kube(t, callerAgent(nil, "coordinator"), referenced(agentRefTool("peer"))), true}, + "agentRef to another name": {kube(t, inline(agentRefTool("peer-2"))), false}, + "shared templateRef is no peer": {kube(t, inline(v1alpha3.ToolBinding{SubAgent: &v1alpha3.SubAgentToolBinding{Name: "peer", Description: "d", TemplateRef: &corev1.LocalObjectReference{Name: "peer"}}})), false}, + "planeo annotation still declares": {kube(t, callerAgent(map[string]string{runtimeauth.AgentRefsAnnotation: "peer"}, "")), true}, + } { + t.Run(name, func(t *testing.T) { + principal := delegate(t, f, test.reader, peer) + if test.wantDelegated { + require.Nil(t, principal.RuntimeBinding, "a delegated call is not an actor any more") + require.Equal(t, "owner", principal.ID) + return + } + require.NotNil(t, principal.RuntimeBinding, "stays an actor, so upstream's actor policy decides") + }) + } +} + func TestUndeclaredCrossNamespaceAndSelfStayActors(t *testing.T) { f := newDelegationFixture(t) declared := map[string]string{runtimeauth.AgentRefsAnnotation: "peer"} diff --git a/go/core/internal/translator/adkconfig/builder.go b/go/core/internal/translator/adkconfig/builder.go index 54ce256187..24051c63ff 100644 --- a/go/core/internal/translator/adkconfig/builder.go +++ b/go/core/internal/translator/adkconfig/builder.go @@ -36,8 +36,9 @@ type provenanceEntry struct { // Builder assembles resolved inputs into an ADK agent configuration. type Builder struct { - ctx krt.HandlerContext - collections translator.Collections + ctx krt.HandlerContext + collections translator.Collections + controlPlaneURL string } // NewBuilder constructs an ADK configuration builder. @@ -45,6 +46,13 @@ func NewBuilder(ctx krt.HandlerContext, collections translator.Collections) *Bui return &Builder{ctx: ctx, collections: collections} } +// WithControlPlaneURL sets the controller origin that Dedicated subagents call +// through the A2A gateway. +func (c *Builder) WithControlPlaneURL(url string) *Builder { + c.controlPlaneURL = url + return c +} + type Result struct { Config *configv1.ADKAgentConfig Models []*translator.ResolvedModelConfig @@ -88,12 +96,43 @@ func (c *Builder) Build(ctx context.Context, input *translator.HarnessInput) (*R return nil, err } } + if err := c.applyRemoteAgents(result, input); err != nil { + return nil, err + } // The Python runtime needs an async SQLite driver; the Go runtime accepts // this URL and strips the driver before opening the same durable database. result.Config.SessionDbUrl = "sqlite+aiosqlite:////data/sessions.db" return result, nil } +// applyRemoteAgents adds the root agent's Dedicated subagents and the external +// A2A agents declared by annotation. Binding names are unique across all three +// kinds of subagent because each becomes a tool of the same name. +func (c *Builder) applyRemoteAgents(result *Result, input *translator.HarnessInput) error { + if len(input.Root.Dedicated) > 0 && c.controlPlaneURL == "" { + return fmt.Errorf("control plane URL is required for Dedicated subagents") + } + remote := DedicatedRemoteAgents(c.controlPlaneURL, input.Root.Template.Namespace, input.Root.Dedicated) + external, origins, err := ExternalRemoteAgents(c.controlPlaneURL, input.Annotations) + if err != nil { + return translator.NewValidationError("%w", err) + } + remote = append(remote, external...) + taken := map[string]struct{}{} + for _, child := range result.Config.SubAgents { + taken[child.Name] = struct{}{} + } + for _, agent := range remote { + if _, ok := taken[agent.Name]; ok { + return translator.NewValidationError("duplicate subagent binding name %q", agent.Name) + } + taken[agent.Name] = struct{}{} + } + result.Config.RemoteAgents = remote + result.Egress = append(result.Egress, origins...) + return nil +} + func (c *Builder) compileAgent(ctx context.Context, input *translator.AgentInput) (*Result, error) { modelRuntime := &modelRuntime{} var modelConfig *v1alpha3.ModelConfig diff --git a/go/core/internal/translator/adkconfig/dedicated.go b/go/core/internal/translator/adkconfig/dedicated.go new file mode 100644 index 0000000000..9a78ece007 --- /dev/null +++ b/go/core/internal/translator/adkconfig/dedicated.go @@ -0,0 +1,38 @@ +package adkconfig + +import ( + "strings" + "time" + + "google.golang.org/protobuf/types/known/durationpb" + + configv1 "github.com/kagent-dev/kagent/go/api/gen/kagent/config/v1" + "github.com/kagent-dev/kagent/go/core/internal/translator" +) + +// remoteAgentTimeout bounds one call to a peer Agent. A peer runs a full agent +// loop, so the bound is generous; it matches the kagent 0.10 default. +const remoteAgentTimeout = 30 * time.Minute + +// DedicatedRemoteAgents turns subAgent.agentRef bindings into ADK remote A2A +// agents that call the peer through the controller's A2A gateway. +// +// The card URL carries the gateway path, which a2a-go fetches verbatim +// (kagent#3275). The compiled output depends only on the parent's own spec: a +// missing peer surfaces at call time as a gateway 404. +func DedicatedRemoteAgents(controlPlaneURL, namespace string, bindings []translator.DedicatedBinding) []*configv1.ADKRemoteAgentConfig { + if len(bindings) == 0 { + return nil + } + base := strings.TrimRight(controlPlaneURL, "/") + agents := make([]*configv1.ADKRemoteAgentConfig, 0, len(bindings)) + for _, binding := range bindings { + agents = append(agents, &configv1.ADKRemoteAgentConfig{ + Name: binding.Name, + Description: binding.Description, + Url: base + "/agents/" + namespace + "/" + binding.AgentRef.Name + "/.well-known/agent-card.json", + Timeout: durationpb.New(remoteAgentTimeout), + }) + } + return agents +} diff --git a/go/core/internal/translator/adkconfig/dedicated_test.go b/go/core/internal/translator/adkconfig/dedicated_test.go new file mode 100644 index 0000000000..14323b3ada --- /dev/null +++ b/go/core/internal/translator/adkconfig/dedicated_test.go @@ -0,0 +1,34 @@ +package adkconfig + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + + "github.com/kagent-dev/kagent/go/core/internal/translator" +) + +func TestDedicatedRemoteAgents(t *testing.T) { + const controlPlane = "http://kagent-v1-controller.kagent-v1.svc.cluster.local:8083" + + require.Nil(t, DedicatedRemoteAgents(controlPlane, "troubleshooting", nil)) + + agents := DedicatedRemoteAgents(controlPlane, "troubleshooting", []translator.DedicatedBinding{{ + Name: "telemetry_agent", Description: "T", AgentRef: corev1.LocalObjectReference{Name: "telemetry-agent"}, + }}) + require.Len(t, agents, 1) + require.Equal(t, "telemetry_agent", agents[0].Name) + require.Equal(t, "T", agents[0].Description) + require.Equal(t, controlPlane+"/agents/troubleshooting/telemetry-agent/.well-known/agent-card.json", agents[0].Url) + require.Equal(t, 30*time.Minute, agents[0].Timeout.AsDuration()) + require.False(t, agents[0].IsolateSessions) +} + +func TestDedicatedRemoteAgentsToleratesTrailingSlash(t *testing.T) { + agents := DedicatedRemoteAgents("http://controller:8083/", "ns", []translator.DedicatedBinding{{ + Name: "peer", Description: "d", AgentRef: corev1.LocalObjectReference{Name: "peer-agent"}, + }}) + require.Equal(t, "http://controller:8083/agents/ns/peer-agent/.well-known/agent-card.json", agents[0].Url) +} diff --git a/go/core/internal/translator/adkconfig/external.go b/go/core/internal/translator/adkconfig/external.go new file mode 100644 index 0000000000..a5bf7bf7e2 --- /dev/null +++ b/go/core/internal/translator/adkconfig/external.go @@ -0,0 +1,92 @@ +package adkconfig + +import ( + "encoding/json" + "fmt" + "net/netip" + "net/url" + "slices" + "strings" + "time" + + "google.golang.org/protobuf/types/known/durationpb" + + configv1 "github.com/kagent-dev/kagent/go/api/gen/kagent/config/v1" + "github.com/kagent-dev/kagent/go/core/internal/egress" +) + +// ExternalA2AAnnotation lists A2A agents outside kagent that an Agent (or its +// AgentTemplate) may call directly, bypassing the controller gateway. The value +// is a JSON list of {name, description, url, timeoutSeconds?}; url is the peer's +// agent card URL. SURF extension, not part of the upstream API. +const ExternalA2AAnnotation = "kagent.surf.net/remote-agents" + +type externalRemoteAgent struct { + Name string `json:"name"` + Description string `json:"description"` + URL string `json:"url"` + TimeoutSeconds *int64 `json:"timeoutSeconds,omitempty"` +} + +// ExternalRemoteAgents reads ExternalA2AAnnotation and returns the ADK remote +// agents plus the egress origins they need. controlPlaneURL is the controller: +// kagent Agents must be declared with subAgent.agentRef so the gateway +// authorizes the call. +func ExternalRemoteAgents(controlPlaneURL string, annotations map[string]string) ([]*configv1.ADKRemoteAgentConfig, []string, error) { + raw := strings.TrimSpace(annotations[ExternalA2AAnnotation]) + if raw == "" { + return nil, nil, nil + } + var entries []externalRemoteAgent + if err := json.Unmarshal([]byte(raw), &entries); err != nil { + return nil, nil, fmt.Errorf("annotation %s must be a JSON list of {name, description, url, timeoutSeconds}: %w", ExternalA2AAnnotation, err) + } + controller, err := url.Parse(controlPlaneURL) + if err != nil { + return nil, nil, fmt.Errorf("parse control plane URL: %w", err) + } + controllerOrigin := egress.Origin(controller) + + var agents []*configv1.ADKRemoteAgentConfig + var origins []string + names := map[string]struct{}{} + for i, entry := range entries { + fail := func(format string, args ...any) ([]*configv1.ADKRemoteAgentConfig, []string, error) { + return nil, nil, fmt.Errorf("annotation %s entry %d: %s", ExternalA2AAnnotation, i, fmt.Sprintf(format, args...)) + } + switch { + case entry.Name == "": + return fail("name is required") + case entry.Description == "": + return fail("description is required for %q", entry.Name) + } + if _, ok := names[entry.Name]; ok { + return fail("duplicate name %q", entry.Name) + } + names[entry.Name] = struct{}{} + target, err := url.Parse(entry.URL) + if err != nil || (target.Scheme != "http" && target.Scheme != "https") || target.Hostname() == "" { + return fail("url %q for %q must be an absolute http(s) URL", entry.URL, entry.Name) + } + if _, err := netip.ParseAddr(target.Hostname()); err == nil { + return fail("url %q for %q uses an IP-literal host; Substrate egress requires a DNS name", entry.URL, entry.Name) + } + origin := egress.Origin(target) + if origin == controllerOrigin { + return fail("url %q for %q points at the controller: use subAgent.agentRef for kagent Agents", entry.URL, entry.Name) + } + timeout := remoteAgentTimeout + if entry.TimeoutSeconds != nil { + if *entry.TimeoutSeconds <= 0 || *entry.TimeoutSeconds > int64(24*time.Hour/time.Second) { + return fail("timeoutSeconds for %q must be between 1 and 86400", entry.Name) + } + timeout = time.Duration(*entry.TimeoutSeconds) * time.Second + } + agents = append(agents, &configv1.ADKRemoteAgentConfig{ + Name: entry.Name, Description: entry.Description, Url: entry.URL, Timeout: durationpb.New(timeout), + }) + origins = append(origins, origin) + } + slices.Sort(origins) + return agents, slices.Compact(origins), nil +} diff --git a/go/core/internal/translator/adkconfig/external_test.go b/go/core/internal/translator/adkconfig/external_test.go new file mode 100644 index 0000000000..8ad175f494 --- /dev/null +++ b/go/core/internal/translator/adkconfig/external_test.go @@ -0,0 +1,83 @@ +package adkconfig + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestExternalRemoteAgents(t *testing.T) { + const wfo = `{"name":"wfo_search","description":"W","url":"http://wfo-search.troubleshooting.svc.cluster.local:8080/.well-known/agent-card.json","timeoutSeconds":1800}` + for _, tc := range []struct { + name string + annotations map[string]string + wantAgents int + wantOrigins []string + wantError string + check func(*testing.T, []string) + }{ + {name: "none"}, + {name: "empty annotation", annotations: map[string]string{ExternalA2AAnnotation: ""}}, + { + name: "wfo-search", annotations: map[string]string{ExternalA2AAnnotation: "[" + wfo + "]"}, + wantAgents: 1, wantOrigins: []string{"http://wfo-search.troubleshooting.svc.cluster.local:8080"}, + }, + { + name: "missing timeoutSeconds", wantAgents: 1, wantOrigins: []string{"http://wfo.example.com:80"}, + annotations: map[string]string{ExternalA2AAnnotation: `[{"name":"wfo","description":"W","url":"http://wfo.example.com/card.json"}]`}, + }, + { + name: "missing description", wantError: "description", + annotations: map[string]string{ExternalA2AAnnotation: `[{"name":"wfo","url":"http://wfo.example.com/card.json"}]`}, + }, + { + name: "missing name", wantError: "name", + annotations: map[string]string{ExternalA2AAnnotation: `[{"description":"W","url":"http://wfo.example.com/card.json"}]`}, + }, + { + name: "duplicate name", wantError: "duplicate", + annotations: map[string]string{ExternalA2AAnnotation: `[` + wfo + `,` + wfo + `]`}, + }, + { + name: "invalid JSON", wantError: ExternalA2AAnnotation, + annotations: map[string]string{ExternalA2AAnnotation: `{not json`}, + }, + { + name: "IP-literal URL", wantError: "IP", + annotations: map[string]string{ExternalA2AAnnotation: `[{"name":"wfo","description":"W","url":"http://10.1.2.3:8080/card.json"}]`}, + }, + { + name: "non-HTTP URL", wantError: "url", + annotations: map[string]string{ExternalA2AAnnotation: `[{"name":"wfo","description":"W","url":"ftp://wfo.example.com/card.json"}]`}, + }, + { + name: "negative timeout", wantError: "timeoutSeconds", + annotations: map[string]string{ExternalA2AAnnotation: `[{"name":"wfo","description":"W","url":"http://wfo.example.com/card.json","timeoutSeconds":-1}]`}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + agents, origins, err := ExternalRemoteAgents("http://kagent-controller.kagent:8083", tc.annotations) + if tc.wantError != "" { + require.ErrorContains(t, err, tc.wantError) + return + } + require.NoError(t, err) + require.Len(t, agents, tc.wantAgents) + require.Equal(t, tc.wantOrigins, origins) + if tc.wantAgents == 0 { + require.Nil(t, agents) + return + } + require.Equal(t, 30*time.Minute, agents[0].Timeout.AsDuration()) + require.False(t, agents[0].IsolateSessions) + }) + } +} + +func TestExternalRemoteAgentsRejectsTheControllerOrigin(t *testing.T) { + _, _, err := ExternalRemoteAgents("http://kagent-controller.kagent:8083", map[string]string{ + ExternalA2AAnnotation: `[{"name":"peer","description":"P","url":"http://kagent-controller.kagent:8083/agents/ns/peer/.well-known/agent-card.json"}]`, + }) + require.ErrorContains(t, err, "use subAgent.agentRef for kagent Agents") +} diff --git a/go/core/internal/translator/byo/compiler.go b/go/core/internal/translator/byo/compiler.go index 9c1f6e69d7..94d260e8b4 100644 --- a/go/core/internal/translator/byo/compiler.go +++ b/go/core/internal/translator/byo/compiler.go @@ -29,7 +29,7 @@ type Compiler struct { var _ translator.HarnessCompiler = (*Compiler)(nil) func NewCompiler(ctx krt.HandlerContext, collections translator.Collections, settings *configv1.RuntimeDefaultsConfig) *Compiler { - return &Compiler{settings: settings, config: adkconfig.NewBuilder(ctx, collections)} + return &Compiler{settings: settings, config: adkconfig.NewBuilder(ctx, collections).WithControlPlaneURL(settings.GetControlPlaneUrl())} } func (c *Compiler) Compile(ctx context.Context, input *translator.HarnessInput) (*translator.CompileResult, error) { diff --git a/go/core/internal/translator/compiler.go b/go/core/internal/translator/compiler.go index a58bd270fe..944f83d2f5 100644 --- a/go/core/internal/translator/compiler.go +++ b/go/core/internal/translator/compiler.go @@ -8,6 +8,7 @@ import ( "slices" "istio.io/istio/pkg/kube/krt" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" @@ -50,8 +51,9 @@ type resolvedTemplateTree struct { // resolvedTemplate is one template and its validated Shared children. type resolvedTemplate struct { - Template *TemplateConfiguration - Shared []resolvedTemplateBinding + Template *TemplateConfiguration + Shared []resolvedTemplateBinding + Dedicated []DedicatedBinding } // resolvedTemplateBinding preserves the parent-specific identity of a Shared child. @@ -68,6 +70,10 @@ type HarnessInput struct { Harness *HarnessConfiguration Root *AgentInput OutputSchema *ResolvedOutputSchema + // Annotations are the runnable Agent's annotations laid over those of its + // referenced AgentTemplate. Inline TemplateConfiguration has no Source, so the + // Agent's own metadata cannot be read from the template. + Annotations map[string]string } // AgentInput contains resolved Kubernetes inputs for one agent. @@ -77,6 +83,16 @@ type AgentInput struct { Instruction string MCPTools []ResolvedMCPTool Shared []AgentInputBinding + // Dedicated are same-namespace Agents invoked over A2A, each with its own Session. + Dedicated []DedicatedBinding +} + +// DedicatedBinding is a subAgent.agentRef tool: the parent calls the referenced +// same-namespace Agent through the controller's A2A gateway. +type DedicatedBinding struct { + Name string + Description string + AgentRef corev1.LocalObjectReference } // ResolvedMCPTool pairs an exact tool allowlist with its resolved server. @@ -150,7 +166,7 @@ func (c *Compiler) compileConfiguration(ctx context.Context, agent *v1alpha3.Age if harnessCompiler == nil { return nil, NewValidationError("Harness runtime is not supported by any compiler") } - tree, err := c.resolveTree(ctx, harness, template) + tree, err := c.resolveTree(ctx, harness, template, agent.Name) if err != nil { return nil, err } @@ -159,6 +175,7 @@ func (c *Compiler) compileConfiguration(ctx context.Context, agent *v1alpha3.Age return nil, err } input.AgentName = agent.Name + input.Annotations = effectiveAnnotations(agent, template) image, err := harnessImage(harness, c.images) if err != nil { return nil, err @@ -184,6 +201,16 @@ func (c *Compiler) compileConfiguration(ctx context.Context, agent *v1alpha3.Age return result, nil } +// effectiveAnnotations lays the Agent's annotations over its referenced AgentTemplate's. +func effectiveAnnotations(agent *v1alpha3.Agent, template *TemplateConfiguration) map[string]string { + merged := map[string]string{} + if template.Source != nil { + maps.Copy(merged, template.Source.Annotations) + } + maps.Copy(merged, agent.Annotations) + return merged +} + func harnessType(harness *HarnessConfiguration) HarnessType { switch { case harness.Spec.Kagent != nil: @@ -199,7 +226,7 @@ func harnessType(harness *HarnessConfiguration) HarnessType { } } -func (c *Compiler) resolveTree(ctx context.Context, harness *HarnessConfiguration, root *TemplateConfiguration) (*resolvedTemplateTree, error) { +func (c *Compiler) resolveTree(ctx context.Context, harness *HarnessConfiguration, root *TemplateConfiguration, agentName string) (*resolvedTemplateTree, error) { seen, path, names := map[string]struct{}{}, map[string]struct{}{}, map[string]struct{}{} var resolve func(*TemplateConfiguration, bool) (*resolvedTemplate, error) resolve = func(template *TemplateConfiguration, child bool) (*resolvedTemplate, error) { @@ -224,13 +251,30 @@ func (c *Compiler) resolveTree(ctx context.Context, harness *HarnessConfiguratio continue } binding := tool.SubAgent - if binding.TemplateRef == nil || binding.TemplateRef.Name == "" { - return nil, NewValidationError("subagent %q requires templateRef.name", binding.Name) + if (binding.TemplateRef == nil) == (binding.AgentRef == nil) { + return nil, NewValidationError("subagent %q requires exactly one of templateRef or agentRef", binding.Name) } if _, ok := names[binding.Name]; ok { - return nil, NewValidationError("duplicate Shared AgentTemplate binding name %q", binding.Name) + return nil, NewValidationError("duplicate subagent binding name %q", binding.Name) } names[binding.Name] = struct{}{} + if binding.AgentRef != nil { + if binding.AgentRef.Name == "" { + return nil, NewValidationError("subagent %q requires agentRef.name", binding.Name) + } + if binding.AgentRef.Name == agentName { + return nil, NewValidationError("Dedicated subagent %q cannot reference its own Agent", binding.Name) + } + // The gateway authorizes a peer call against the calling Agent's own template only. + if child { + return nil, NewValidationError("Dedicated subagent %q must be declared on the Agent's own template, not a Shared one", binding.Name) + } + resolved.Dedicated = append(resolved.Dedicated, DedicatedBinding{Name: binding.Name, Description: binding.Description, AgentRef: *binding.AgentRef}) + continue + } + if binding.TemplateRef.Name == "" { + return nil, NewValidationError("subagent %q requires templateRef.name", binding.Name) + } key := types.NamespacedName{Namespace: template.Namespace, Name: binding.TemplateRef.Name} childTemplate := krt.FetchOne(c.ctx, c.collections.AgentTemplates, krt.FilterObjectName(key)) if childTemplate == nil { @@ -314,6 +358,7 @@ func (c *Compiler) buildInputs(ctx context.Context, tree *resolvedTemplateTree) return nil, err } } + input.Dedicated = slices.Clone(agent.Dedicated) for _, binding := range agent.Shared { child, err := build(binding.Agent) if err != nil { diff --git a/go/core/internal/translator/compiler_test.go b/go/core/internal/translator/compiler_test.go index 6c0393341f..bce7c5a422 100644 --- a/go/core/internal/translator/compiler_test.go +++ b/go/core/internal/translator/compiler_test.go @@ -22,6 +22,7 @@ import ( "github.com/kagent-dev/kagent/go/api/v1alpha3" "github.com/kagent-dev/kagent/go/core/internal/substrate" "github.com/kagent-dev/kagent/go/core/internal/translator" + "github.com/kagent-dev/kagent/go/core/internal/translator/adkconfig" byotranslator "github.com/kagent-dev/kagent/go/core/internal/translator/byo" claudetranslator "github.com/kagent-dev/kagent/go/core/internal/translator/claude" codextranslator "github.com/kagent-dev/kagent/go/core/internal/translator/codex" @@ -890,7 +891,7 @@ func TestCompileAgentRejectsInvalidSubagentReferences(t *testing.T) { }{ { name: "missing reference", - wantError: "requires templateRef.name", + wantError: "exactly one of templateRef or agentRef", }, { name: "empty reference", @@ -911,6 +912,134 @@ func TestCompileAgentRejectsInvalidSubagentReferences(t *testing.T) { } } +func TestCompileAgentDedicatedSubAgent(t *testing.T) { + harness := &v1alpha3.Harness{ + ObjectMeta: metav1.ObjectMeta{Name: "kagent", Namespace: "test"}, + Spec: v1alpha3.HarnessSpec{ + Kagent: &v1alpha3.KagentHarness{}, + Workload: v1alpha3.HarnessWorkload{Image: new("example.com/kagent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")}, + Substrate: v1alpha3.RuntimeSubstratePolicy{WorkerPoolRef: corev1.LocalObjectReference{Name: "default"}, SnapshotPolicy: v1alpha3.RuntimeSnapshotPolicy{Location: "snapshots"}}, + }, + } + dedicated := func(name, peer string) v1alpha3.ToolBinding { + return v1alpha3.ToolBinding{SubAgent: &v1alpha3.SubAgentToolBinding{Name: name, Description: "T", AgentRef: &corev1.LocalObjectReference{Name: peer}}} + } + shared := func(name, target string) v1alpha3.ToolBinding { + return v1alpha3.ToolBinding{SubAgent: &v1alpha3.SubAgentToolBinding{Name: name, Description: name, TemplateRef: &corev1.LocalObjectReference{Name: target}}} + } + template := func(tools ...v1alpha3.ToolBinding) *v1alpha3.AgentTemplate { + return &v1alpha3.AgentTemplate{ObjectMeta: metav1.ObjectMeta{Name: "planner", Namespace: "test"}, Spec: v1alpha3.AgentTemplateSpec{ + ModelConfig: &v1alpha3.ObjectReference{Name: "default-model"}, SystemPrompt: "plan", Tools: tools, + }} + } + mcp := v1alpha3.ToolBinding{MCP: &v1alpha3.MCPToolBinding{Server: corev1.TypedObjectReference{Kind: "RemoteMCPServer", Name: "search"}}} + + t.Run("compiles to a remote A2A agent through the controller", func(t *testing.T) { + revision, err := compiler(t, modelConfig(), harness, remoteMCPServer("search", "https://search.example.com/mcp")). + CompileAgent(t.Context(), inlineAgent(harness, template(dedicated("telemetry_agent", "telemetry-agent"), mcp))) + require.NoError(t, err) + var config configv1.ADKConfig + require.NoError(t, runtimeconfig.Unmarshal(revision.ConfigJSON, &config)) + require.Len(t, config.Agent.RemoteAgents, 1) + remote := config.Agent.RemoteAgents[0] + require.Equal(t, "telemetry_agent", remote.Name) + require.Equal(t, "http://kagent-controller.kagent:8083/agents/test/telemetry-agent/.well-known/agent-card.json", remote.Url) + require.Empty(t, config.Agent.SubAgents) + require.Len(t, config.Agent.HttpTools, 1) + require.Contains(t, revision.EgressDestinations, "http://kagent-controller.kagent:8083") + }) + t.Run("rejects a reference to its own Agent", func(t *testing.T) { + _, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), inlineAgent(harness, template(dedicated("me", "runnable-agent")))) + require.ErrorContains(t, err, "cannot reference its own Agent") + var validationError *translator.ValidationError + require.ErrorAs(t, err, &validationError) + }) + t.Run("rejects a binding name used by a Shared and a Dedicated binding", func(t *testing.T) { + child := &v1alpha3.AgentTemplate{ObjectMeta: metav1.ObjectMeta{Name: "child", Namespace: "test"}, Spec: v1alpha3.AgentTemplateSpec{ModelConfig: &v1alpha3.ObjectReference{Name: "default-model"}}} + _, err := compiler(t, modelConfig(), harness, child).CompileAgent(t.Context(), inlineAgent(harness, template(shared("helper", "child"), dedicated("helper", "peer")))) + require.ErrorContains(t, err, "duplicate") + }) + t.Run("rejects two Dedicated bindings with one name", func(t *testing.T) { + _, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), inlineAgent(harness, template(dedicated("helper", "a"), dedicated("helper", "b")))) + require.ErrorContains(t, err, "duplicate") + }) + t.Run("rejects both refs", func(t *testing.T) { + both := v1alpha3.ToolBinding{SubAgent: &v1alpha3.SubAgentToolBinding{Name: "x", Description: "x", + TemplateRef: &corev1.LocalObjectReference{Name: "child"}, AgentRef: &corev1.LocalObjectReference{Name: "peer"}}} + _, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), inlineAgent(harness, template(both))) + require.ErrorContains(t, err, "exactly one of templateRef or agentRef") + }) + t.Run("rejects an empty agentRef name", func(t *testing.T) { + _, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), inlineAgent(harness, template(dedicated("helper", "")))) + require.ErrorContains(t, err, "requires agentRef.name") + }) + t.Run("rejects a Dedicated binding inside a Shared template", func(t *testing.T) { + child := &v1alpha3.AgentTemplate{ObjectMeta: metav1.ObjectMeta{Name: "child", Namespace: "test"}, Spec: v1alpha3.AgentTemplateSpec{ + ModelConfig: &v1alpha3.ObjectReference{Name: "default-model"}, Tools: []v1alpha3.ToolBinding{dedicated("peer_tool", "peer")}, + }} + _, err := compiler(t, modelConfig(), harness, child).CompileAgent(t.Context(), inlineAgent(harness, template(shared("helper", "child")))) + require.ErrorContains(t, err, "must be declared on the Agent's own template") + }) +} + +func TestCompileAgentExternalRemoteAgentsAnnotation(t *testing.T) { + harness := &v1alpha3.Harness{ + ObjectMeta: metav1.ObjectMeta{Name: "kagent", Namespace: "test"}, + Spec: v1alpha3.HarnessSpec{ + Kagent: &v1alpha3.KagentHarness{}, + Workload: v1alpha3.HarnessWorkload{Image: new("example.com/kagent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")}, + Substrate: v1alpha3.RuntimeSubstratePolicy{WorkerPoolRef: corev1.LocalObjectReference{Name: "default"}, SnapshotPolicy: v1alpha3.RuntimeSnapshotPolicy{Location: "snapshots"}}, + }, + } + value := `[{"name":"wfo_search","description":"W","url":"http://wfo-search.troubleshooting.svc.cluster.local:8080/.well-known/agent-card.json","timeoutSeconds":1800}]` + behavior := &v1alpha3.AgentTemplate{ObjectMeta: metav1.ObjectMeta{Name: "planner", Namespace: "test"}, Spec: v1alpha3.AgentTemplateSpec{ + ModelConfig: &v1alpha3.ObjectReference{Name: "default-model"}, SystemPrompt: "plan", + Tools: []v1alpha3.ToolBinding{{SubAgent: &v1alpha3.SubAgentToolBinding{Name: "wfo_search", Description: "d", AgentRef: &corev1.LocalObjectReference{Name: "peer"}}}}, + }} + plain := &v1alpha3.AgentTemplate{ObjectMeta: metav1.ObjectMeta{Name: "plain", Namespace: "test"}, Spec: v1alpha3.AgentTemplateSpec{ + ModelConfig: &v1alpha3.ObjectReference{Name: "default-model"}, SystemPrompt: "plan", + }} + + t.Run("Agent annotation on an inline template", func(t *testing.T) { + agent := inlineAgent(harness, plain) + agent.Annotations = map[string]string{adkconfig.ExternalA2AAnnotation: value} + revision, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), agent) + require.NoError(t, err) + var config configv1.ADKConfig + require.NoError(t, runtimeconfig.Unmarshal(revision.ConfigJSON, &config)) + require.Len(t, config.Agent.RemoteAgents, 1) + require.Equal(t, "wfo_search", config.Agent.RemoteAgents[0].Name) + require.Contains(t, revision.EgressDestinations, "http://wfo-search.troubleshooting.svc.cluster.local:8080") + }) + t.Run("AgentTemplate annotation on a referenced template", func(t *testing.T) { + annotated := plain.DeepCopy() + annotated.Annotations = map[string]string{adkconfig.ExternalA2AAnnotation: value} + agent := &v1alpha3.Agent{ObjectMeta: metav1.ObjectMeta{Name: "runnable-agent", Namespace: "test"}, Spec: v1alpha3.AgentSpec{ + Template: v1alpha3.AgentTemplateSource{Ref: &corev1.LocalObjectReference{Name: annotated.Name}}, + HarnessRef: corev1.LocalObjectReference{Name: harness.Name}, + }} + revision, err := compiler(t, modelConfig(), harness, annotated).CompileAgent(t.Context(), agent) + require.NoError(t, err) + var config configv1.ADKConfig + require.NoError(t, runtimeconfig.Unmarshal(revision.ConfigJSON, &config)) + require.Len(t, config.Agent.RemoteAgents, 1) + }) + t.Run("names are unique across Dedicated and external agents", func(t *testing.T) { + agent := inlineAgent(harness, behavior) + agent.Annotations = map[string]string{adkconfig.ExternalA2AAnnotation: value} + _, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), agent) + require.ErrorContains(t, err, "duplicate") + }) + t.Run("an invalid annotation is a validation error", func(t *testing.T) { + agent := inlineAgent(harness, plain) + agent.Annotations = map[string]string{adkconfig.ExternalA2AAnnotation: "nope"} + _, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), agent) + var validationError *translator.ValidationError + require.ErrorAs(t, err, &validationError) + require.ErrorContains(t, err, adkconfig.ExternalA2AAnnotation) + }) +} + func TestCompileAgentRejectsInvalidSources(t *testing.T) { template := &v1alpha3.AgentTemplateSpec{} ref := &corev1.LocalObjectReference{Name: "shared"} diff --git a/go/core/internal/translator/kagent/compiler.go b/go/core/internal/translator/kagent/compiler.go index 866802404c..435947b524 100644 --- a/go/core/internal/translator/kagent/compiler.go +++ b/go/core/internal/translator/kagent/compiler.go @@ -27,7 +27,7 @@ type Compiler struct { var _ translator.HarnessCompiler = (*Compiler)(nil) func NewCompiler(ctx krt.HandlerContext, collections translator.Collections, settings *configv1.RuntimeDefaultsConfig) *Compiler { - return &Compiler{settings: settings, config: adkconfig.NewBuilder(ctx, collections)} + return &Compiler{settings: settings, config: adkconfig.NewBuilder(ctx, collections).WithControlPlaneURL(settings.GetControlPlaneUrl())} } func (c *Compiler) Compile(ctx context.Context, input *translator.HarnessInput) (*translator.CompileResult, error) { diff --git a/helm/kagent-crds/templates/api.kagent.dev_agents.yaml b/helm/kagent-crds/templates/api.kagent.dev_agents.yaml index 3e958a4737..238b1518e2 100644 --- a/helm/kagent-crds/templates/api.kagent.dev_agents.yaml +++ b/helm/kagent-crds/templates/api.kagent.dev_agents.yaml @@ -510,8 +510,27 @@ spec: type: object subAgent: description: SubAgentToolBinding exposes a same-namespace - AgentTemplate as a logical tool. + AgentTemplate or Agent as a logical tool. properties: + agentRef: + description: AgentRef selects a Dedicated subagent + with its own Harness and Session, invoked over + A2A. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + x-kubernetes-validations: + - message: agentRef.name must not be empty + rule: has(self.name) && self.name != '' description: description: Description tells the parent when to route work to this binding. @@ -541,8 +560,11 @@ spec: required: - description - name - - templateRef type: object + x-kubernetes-validations: + - message: exactly one of templateRef or agentRef must + be specified + rule: has(self.templateRef) != has(self.agentRef) type: object x-kubernetes-validations: - message: exactly one of the fields in [mcp subAgent] must diff --git a/helm/kagent-crds/templates/api.kagent.dev_agenttemplates.yaml b/helm/kagent-crds/templates/api.kagent.dev_agenttemplates.yaml index 8e9e0c6683..d06e712ef4 100644 --- a/helm/kagent-crds/templates/api.kagent.dev_agenttemplates.yaml +++ b/helm/kagent-crds/templates/api.kagent.dev_agenttemplates.yaml @@ -438,8 +438,26 @@ spec: type: object subAgent: description: SubAgentToolBinding exposes a same-namespace AgentTemplate - as a logical tool. + or Agent as a logical tool. properties: + agentRef: + description: AgentRef selects a Dedicated subagent with + its own Harness and Session, invoked over A2A. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + x-kubernetes-validations: + - message: agentRef.name must not be empty + rule: has(self.name) && self.name != '' description: description: Description tells the parent when to route work to this binding. @@ -469,8 +487,10 @@ spec: required: - description - name - - templateRef type: object + x-kubernetes-validations: + - message: exactly one of templateRef or agentRef must be specified + rule: has(self.templateRef) != has(self.agentRef) type: object x-kubernetes-validations: - message: exactly one of the fields in [mcp subAgent] must be set From ba8e09ca4738f50e6ba5d3f2f213c94f06dd52bf Mon Sep 17 00:00:00 2001 From: Peter Boers Date: Wed, 25 Nov 2026 08:48:46 +0100 Subject: [PATCH 2/2] fix(translator): external remote agents require an EgressPolicy grant instead of granting egress The kagent.surf.net/remote-agents annotation only wires the remote-A2A tool. It no longer adds its origins to the compiled egress, which let anyone who can annotate an Agent open egress to any HTTP(S) origin. Compilation now fails with a validation error unless each external origin is granted by an EgressPolicy in the Agent's spec.egressPolicyRefs. Dedicated agentRef bindings are unchanged (controller origin already granted). ExternalRemoteAgents returns only the configs. The resolved policy origins reach Build through HarnessInput.EgressGrants; egress.Covers matches exact and leftmost-label wildcard origins. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Peter Boers --- go/core/internal/egress/destination.go | 28 +++++ go/core/internal/egress/destination_test.go | 25 ++++ .../internal/translator/adkconfig/builder.go | 16 ++- .../internal/translator/adkconfig/external.go | 27 ++--- .../translator/adkconfig/external_test.go | 11 +- go/core/internal/translator/compiler.go | 4 + go/core/internal/translator/compiler_test.go | 108 ++++++++++++------ 7 files changed, 160 insertions(+), 59 deletions(-) diff --git a/go/core/internal/egress/destination.go b/go/core/internal/egress/destination.go index 484a047460..62bc565082 100644 --- a/go/core/internal/egress/destination.go +++ b/go/core/internal/egress/destination.go @@ -61,6 +61,34 @@ func ParseOrigin(raw string) (*url.URL, error) { return u, nil } +// Covers reports whether origin falls under one of the granted origins. A +// grant covers an origin with the same scheme, port and host; a wildcard grant +// (https://*.example.com) covers hosts with exactly one more leftmost label, +// the semantics ParseOrigin accepts and Substrate enforces. +func Covers(grants []string, origin string) bool { + target, err := ParseOrigin(origin) + if err != nil { + return false + } + for _, raw := range grants { + grant, err := ParseOrigin(raw) + if err != nil || grant.Scheme != target.Scheme || grant.Port() != target.Port() { + continue + } + if rest, wildcard := strings.CutPrefix(grant.Hostname(), "*."); wildcard { + label, parent, found := strings.Cut(target.Hostname(), ".") + if found && label != "" && parent == rest { + return true + } + continue + } + if grant.Hostname() == target.Hostname() { + return true + } + } + return false +} + // Access is a compiled network grant. It contains references, // never Secret values. type Access struct { diff --git a/go/core/internal/egress/destination_test.go b/go/core/internal/egress/destination_test.go index e6fab1817c..3856f0f062 100644 --- a/go/core/internal/egress/destination_test.go +++ b/go/core/internal/egress/destination_test.go @@ -70,3 +70,28 @@ func TestOrigin(t *testing.T) { }) } } + +func TestCovers(t *testing.T) { + for _, tc := range []struct { + name string + grants []string + origin string + want bool + }{ + {name: "no grants", origin: "http://a.example.com:80"}, + {name: "exact", grants: []string{"http://a.example.com:80"}, origin: "http://a.example.com:80", want: true}, + {name: "default port is explicit", grants: []string{"https://a.example.com"}, origin: "https://a.example.com:443", want: true}, + {name: "other scheme", grants: []string{"https://a.example.com:80"}, origin: "http://a.example.com:80"}, + {name: "other port", grants: []string{"http://a.example.com:8080"}, origin: "http://a.example.com:80"}, + {name: "other host", grants: []string{"http://b.example.com:80"}, origin: "http://a.example.com:80"}, + {name: "wildcard covers one label", grants: []string{"https://*.example.com"}, origin: "https://a.example.com:443", want: true}, + {name: "wildcard does not cover the apex", grants: []string{"https://*.example.com"}, origin: "https://example.com:443"}, + {name: "wildcard does not cover two labels", grants: []string{"https://*.example.com"}, origin: "https://a.b.example.com:443"}, + {name: "wildcard keeps the port", grants: []string{"https://*.example.com:8443"}, origin: "https://a.example.com:443"}, + {name: "second grant matches", grants: []string{"http://b.example.com:80", "http://a.example.com:80"}, origin: "http://a.example.com:80", want: true}, + } { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, Covers(tc.grants, tc.origin)) + }) + } +} diff --git a/go/core/internal/translator/adkconfig/builder.go b/go/core/internal/translator/adkconfig/builder.go index 24051c63ff..58af6d1653 100644 --- a/go/core/internal/translator/adkconfig/builder.go +++ b/go/core/internal/translator/adkconfig/builder.go @@ -106,17 +106,28 @@ func (c *Builder) Build(ctx context.Context, input *translator.HarnessInput) (*R } // applyRemoteAgents adds the root agent's Dedicated subagents and the external -// A2A agents declared by annotation. Binding names are unique across all three +// A2A agents declared by annotation (which grant no egress themselves). Binding names are unique across all three // kinds of subagent because each becomes a tool of the same name. func (c *Builder) applyRemoteAgents(result *Result, input *translator.HarnessInput) error { if len(input.Root.Dedicated) > 0 && c.controlPlaneURL == "" { return fmt.Errorf("control plane URL is required for Dedicated subagents") } remote := DedicatedRemoteAgents(c.controlPlaneURL, input.Root.Template.Namespace, input.Root.Dedicated) - external, origins, err := ExternalRemoteAgents(c.controlPlaneURL, input.Annotations) + external, err := ExternalRemoteAgents(c.controlPlaneURL, input.Annotations) if err != nil { return translator.NewValidationError("%w", err) } + // An annotation is not an authorization: external origins must already be + // granted by an EgressPolicy the Agent references. + for _, agent := range external { + target, err := url.Parse(agent.Url) + if err != nil { + return translator.NewValidationError("remote agent %q: %w", agent.Name, err) + } + if origin := egress.Origin(target); !egress.Covers(input.EgressGrants, origin) { + return translator.NewValidationError("remote agent %q needs egress to %s, which must be granted by an EgressPolicy in spec.egressPolicyRefs", agent.Name, origin) + } + } remote = append(remote, external...) taken := map[string]struct{}{} for _, child := range result.Config.SubAgents { @@ -129,7 +140,6 @@ func (c *Builder) applyRemoteAgents(result *Result, input *translator.HarnessInp taken[agent.Name] = struct{}{} } result.Config.RemoteAgents = remote - result.Egress = append(result.Egress, origins...) return nil } diff --git a/go/core/internal/translator/adkconfig/external.go b/go/core/internal/translator/adkconfig/external.go index a5bf7bf7e2..3bc830b36d 100644 --- a/go/core/internal/translator/adkconfig/external.go +++ b/go/core/internal/translator/adkconfig/external.go @@ -5,7 +5,6 @@ import ( "fmt" "net/netip" "net/url" - "slices" "strings" "time" @@ -29,30 +28,29 @@ type externalRemoteAgent struct { } // ExternalRemoteAgents reads ExternalA2AAnnotation and returns the ADK remote -// agents plus the egress origins they need. controlPlaneURL is the controller: -// kagent Agents must be declared with subAgent.agentRef so the gateway -// authorizes the call. -func ExternalRemoteAgents(controlPlaneURL string, annotations map[string]string) ([]*configv1.ADKRemoteAgentConfig, []string, error) { +// agents. It grants no egress: the caller must check each agent's origin against +// the Agent's EgressPolicies. controlPlaneURL is the controller: kagent Agents +// must be declared with subAgent.agentRef so the gateway authorizes the call. +func ExternalRemoteAgents(controlPlaneURL string, annotations map[string]string) ([]*configv1.ADKRemoteAgentConfig, error) { raw := strings.TrimSpace(annotations[ExternalA2AAnnotation]) if raw == "" { - return nil, nil, nil + return nil, nil } var entries []externalRemoteAgent if err := json.Unmarshal([]byte(raw), &entries); err != nil { - return nil, nil, fmt.Errorf("annotation %s must be a JSON list of {name, description, url, timeoutSeconds}: %w", ExternalA2AAnnotation, err) + return nil, fmt.Errorf("annotation %s must be a JSON list of {name, description, url, timeoutSeconds}: %w", ExternalA2AAnnotation, err) } controller, err := url.Parse(controlPlaneURL) if err != nil { - return nil, nil, fmt.Errorf("parse control plane URL: %w", err) + return nil, fmt.Errorf("parse control plane URL: %w", err) } controllerOrigin := egress.Origin(controller) var agents []*configv1.ADKRemoteAgentConfig - var origins []string names := map[string]struct{}{} for i, entry := range entries { - fail := func(format string, args ...any) ([]*configv1.ADKRemoteAgentConfig, []string, error) { - return nil, nil, fmt.Errorf("annotation %s entry %d: %s", ExternalA2AAnnotation, i, fmt.Sprintf(format, args...)) + fail := func(format string, args ...any) ([]*configv1.ADKRemoteAgentConfig, error) { + return nil, fmt.Errorf("annotation %s entry %d: %s", ExternalA2AAnnotation, i, fmt.Sprintf(format, args...)) } switch { case entry.Name == "": @@ -71,8 +69,7 @@ func ExternalRemoteAgents(controlPlaneURL string, annotations map[string]string) if _, err := netip.ParseAddr(target.Hostname()); err == nil { return fail("url %q for %q uses an IP-literal host; Substrate egress requires a DNS name", entry.URL, entry.Name) } - origin := egress.Origin(target) - if origin == controllerOrigin { + if egress.Origin(target) == controllerOrigin { return fail("url %q for %q points at the controller: use subAgent.agentRef for kagent Agents", entry.URL, entry.Name) } timeout := remoteAgentTimeout @@ -85,8 +82,6 @@ func ExternalRemoteAgents(controlPlaneURL string, annotations map[string]string) agents = append(agents, &configv1.ADKRemoteAgentConfig{ Name: entry.Name, Description: entry.Description, Url: entry.URL, Timeout: durationpb.New(timeout), }) - origins = append(origins, origin) } - slices.Sort(origins) - return agents, slices.Compact(origins), nil + return agents, nil } diff --git a/go/core/internal/translator/adkconfig/external_test.go b/go/core/internal/translator/adkconfig/external_test.go index 8ad175f494..ba0c133320 100644 --- a/go/core/internal/translator/adkconfig/external_test.go +++ b/go/core/internal/translator/adkconfig/external_test.go @@ -13,18 +13,16 @@ func TestExternalRemoteAgents(t *testing.T) { name string annotations map[string]string wantAgents int - wantOrigins []string wantError string - check func(*testing.T, []string) }{ {name: "none"}, {name: "empty annotation", annotations: map[string]string{ExternalA2AAnnotation: ""}}, { name: "wfo-search", annotations: map[string]string{ExternalA2AAnnotation: "[" + wfo + "]"}, - wantAgents: 1, wantOrigins: []string{"http://wfo-search.troubleshooting.svc.cluster.local:8080"}, + wantAgents: 1, }, { - name: "missing timeoutSeconds", wantAgents: 1, wantOrigins: []string{"http://wfo.example.com:80"}, + name: "missing timeoutSeconds", wantAgents: 1, annotations: map[string]string{ExternalA2AAnnotation: `[{"name":"wfo","description":"W","url":"http://wfo.example.com/card.json"}]`}, }, { @@ -57,14 +55,13 @@ func TestExternalRemoteAgents(t *testing.T) { }, } { t.Run(tc.name, func(t *testing.T) { - agents, origins, err := ExternalRemoteAgents("http://kagent-controller.kagent:8083", tc.annotations) + agents, err := ExternalRemoteAgents("http://kagent-controller.kagent:8083", tc.annotations) if tc.wantError != "" { require.ErrorContains(t, err, tc.wantError) return } require.NoError(t, err) require.Len(t, agents, tc.wantAgents) - require.Equal(t, tc.wantOrigins, origins) if tc.wantAgents == 0 { require.Nil(t, agents) return @@ -76,7 +73,7 @@ func TestExternalRemoteAgents(t *testing.T) { } func TestExternalRemoteAgentsRejectsTheControllerOrigin(t *testing.T) { - _, _, err := ExternalRemoteAgents("http://kagent-controller.kagent:8083", map[string]string{ + _, err := ExternalRemoteAgents("http://kagent-controller.kagent:8083", map[string]string{ ExternalA2AAnnotation: `[{"name":"peer","description":"P","url":"http://kagent-controller.kagent:8083/agents/ns/peer/.well-known/agent-card.json"}]`, }) require.ErrorContains(t, err, "use subAgent.agentRef for kagent Agents") diff --git a/go/core/internal/translator/compiler.go b/go/core/internal/translator/compiler.go index 944f83d2f5..d3e140d369 100644 --- a/go/core/internal/translator/compiler.go +++ b/go/core/internal/translator/compiler.go @@ -74,6 +74,9 @@ type HarnessInput struct { // referenced AgentTemplate. Inline TemplateConfiguration has no Source, so the // Agent's own metadata cannot be read from the template. Annotations map[string]string + // EgressGrants are the origins granted by the Agent's referenced + // EgressPolicies (spec.egressPolicyRefs). + EgressGrants []string } // AgentInput contains resolved Kubernetes inputs for one agent. @@ -176,6 +179,7 @@ func (c *Compiler) compileConfiguration(ctx context.Context, agent *v1alpha3.Age } input.AgentName = agent.Name input.Annotations = effectiveAnnotations(agent, template) + input.EgressGrants = CompileEgressPolicies(c.ctx, c.collections, agent.Namespace, agent.Spec.EgressPolicyRefs).Access.Destinations image, err := harnessImage(harness, c.images) if err != nil { return nil, err diff --git a/go/core/internal/translator/compiler_test.go b/go/core/internal/translator/compiler_test.go index bce7c5a422..3466af8fe9 100644 --- a/go/core/internal/translator/compiler_test.go +++ b/go/core/internal/translator/compiler_test.go @@ -991,52 +991,94 @@ func TestCompileAgentExternalRemoteAgentsAnnotation(t *testing.T) { Substrate: v1alpha3.RuntimeSubstratePolicy{WorkerPoolRef: corev1.LocalObjectReference{Name: "default"}, SnapshotPolicy: v1alpha3.RuntimeSnapshotPolicy{Location: "snapshots"}}, }, } - value := `[{"name":"wfo_search","description":"W","url":"http://wfo-search.troubleshooting.svc.cluster.local:8080/.well-known/agent-card.json","timeoutSeconds":1800}]` - behavior := &v1alpha3.AgentTemplate{ObjectMeta: metav1.ObjectMeta{Name: "planner", Namespace: "test"}, Spec: v1alpha3.AgentTemplateSpec{ - ModelConfig: &v1alpha3.ObjectReference{Name: "default-model"}, SystemPrompt: "plan", - Tools: []v1alpha3.ToolBinding{{SubAgent: &v1alpha3.SubAgentToolBinding{Name: "wfo_search", Description: "d", AgentRef: &corev1.LocalObjectReference{Name: "peer"}}}}, - }} + const origin = "http://wfo-search.troubleshooting.svc.cluster.local:8080" + value := `[{"name":"wfo_search","description":"W","url":"` + origin + `/.well-known/agent-card.json","timeoutSeconds":1800}]` + policy := func(name string, origins ...string) *v1alpha3.EgressPolicy { + destinations := make([]v1alpha3.EgressDestination, 0, len(origins)) + for _, o := range origins { + destinations = append(destinations, v1alpha3.EgressDestination{Origin: o}) + } + return &v1alpha3.EgressPolicy{ObjectMeta: metav1.ObjectMeta{Namespace: "test", Name: name}, Spec: v1alpha3.EgressPolicySpec{Destinations: destinations}} + } plain := &v1alpha3.AgentTemplate{ObjectMeta: metav1.ObjectMeta{Name: "plain", Namespace: "test"}, Spec: v1alpha3.AgentTemplateSpec{ ModelConfig: &v1alpha3.ObjectReference{Name: "default-model"}, SystemPrompt: "plan", }} + dedicated := plain.DeepCopy() + dedicated.Spec.Tools = []v1alpha3.ToolBinding{{SubAgent: &v1alpha3.SubAgentToolBinding{Name: "wfo_search", Description: "d", AgentRef: &corev1.LocalObjectReference{Name: "peer"}}}} + refs := func(names ...string) []corev1.LocalObjectReference { + var refs []corev1.LocalObjectReference + for _, name := range names { + refs = append(refs, corev1.LocalObjectReference{Name: name}) + } + return refs + } + + for _, tc := range []struct { + name string + template *v1alpha3.AgentTemplate + annotations map[string]string + policies []*v1alpha3.EgressPolicy + refs []string + wantError []string + }{ + {name: "exact origin granted by a referenced policy", template: plain, annotations: map[string]string{adkconfig.ExternalA2AAnnotation: value}, + policies: []*v1alpha3.EgressPolicy{policy("wfo", origin)}, refs: []string{"wfo"}}, + {name: "wildcard origin granted by a referenced policy", template: plain, annotations: map[string]string{adkconfig.ExternalA2AAnnotation: value}, + policies: []*v1alpha3.EgressPolicy{policy("wfo", "http://*.troubleshooting.svc.cluster.local:8080")}, refs: []string{"wfo"}}, + {name: "no policy", template: plain, annotations: map[string]string{adkconfig.ExternalA2AAnnotation: value}, + wantError: []string{origin, "spec.egressPolicyRefs"}}, + {name: "policy exists but is not referenced", template: plain, annotations: map[string]string{adkconfig.ExternalA2AAnnotation: value}, + policies: []*v1alpha3.EgressPolicy{policy("wfo", origin)}, wantError: []string{origin}}, + {name: "referenced policy covers a different origin", template: plain, annotations: map[string]string{adkconfig.ExternalA2AAnnotation: value}, + policies: []*v1alpha3.EgressPolicy{policy("other", "http://other.example.com:8080")}, refs: []string{"other"}, wantError: []string{origin}}, + {name: "referenced policy covers another port", template: plain, annotations: map[string]string{adkconfig.ExternalA2AAnnotation: value}, + policies: []*v1alpha3.EgressPolicy{policy("wfo", "http://wfo-search.troubleshooting.svc.cluster.local:9090")}, refs: []string{"wfo"}, wantError: []string{origin}}, + {name: "names are unique across Dedicated and external agents", template: dedicated, annotations: map[string]string{adkconfig.ExternalA2AAnnotation: value}, + policies: []*v1alpha3.EgressPolicy{policy("wfo", origin)}, refs: []string{"wfo"}, wantError: []string{"duplicate"}}, + {name: "an invalid annotation is a validation error", template: plain, annotations: map[string]string{adkconfig.ExternalA2AAnnotation: "nope"}, + wantError: []string{adkconfig.ExternalA2AAnnotation}}, + } { + t.Run(tc.name, func(t *testing.T) { + agent := inlineAgent(harness, tc.template) + agent.Annotations = tc.annotations + agent.Spec.EgressPolicyRefs = refs(tc.refs...) + objects := []any{modelConfig(), harness} + for _, p := range tc.policies { + objects = append(objects, p) + } + revision, err := compiler(t, objects...).CompileAgent(t.Context(), agent) + if tc.wantError != nil { + var validationError *translator.ValidationError + require.ErrorAs(t, err, &validationError) + for _, want := range tc.wantError { + require.ErrorContains(t, err, want) + } + return + } + require.NoError(t, err) + var config configv1.ADKConfig + require.NoError(t, runtimeconfig.Unmarshal(revision.ConfigJSON, &config)) + require.Len(t, config.Agent.RemoteAgents, 1) + require.Equal(t, "wfo_search", config.Agent.RemoteAgents[0].Name) + // The revision's own egress never gains the origin; the EgressPolicy grants it live. + require.NotContains(t, revision.EgressDestinations, origin) + }) + } - t.Run("Agent annotation on an inline template", func(t *testing.T) { - agent := inlineAgent(harness, plain) - agent.Annotations = map[string]string{adkconfig.ExternalA2AAnnotation: value} - revision, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), agent) - require.NoError(t, err) - var config configv1.ADKConfig - require.NoError(t, runtimeconfig.Unmarshal(revision.ConfigJSON, &config)) - require.Len(t, config.Agent.RemoteAgents, 1) - require.Equal(t, "wfo_search", config.Agent.RemoteAgents[0].Name) - require.Contains(t, revision.EgressDestinations, "http://wfo-search.troubleshooting.svc.cluster.local:8080") - }) t.Run("AgentTemplate annotation on a referenced template", func(t *testing.T) { annotated := plain.DeepCopy() annotated.Annotations = map[string]string{adkconfig.ExternalA2AAnnotation: value} agent := &v1alpha3.Agent{ObjectMeta: metav1.ObjectMeta{Name: "runnable-agent", Namespace: "test"}, Spec: v1alpha3.AgentSpec{ - Template: v1alpha3.AgentTemplateSource{Ref: &corev1.LocalObjectReference{Name: annotated.Name}}, - HarnessRef: corev1.LocalObjectReference{Name: harness.Name}, + Template: v1alpha3.AgentTemplateSource{Ref: &corev1.LocalObjectReference{Name: annotated.Name}}, + HarnessRef: corev1.LocalObjectReference{Name: harness.Name}, + EgressPolicyRefs: refs("wfo"), }} - revision, err := compiler(t, modelConfig(), harness, annotated).CompileAgent(t.Context(), agent) + revision, err := compiler(t, modelConfig(), harness, annotated, policy("wfo", origin)).CompileAgent(t.Context(), agent) require.NoError(t, err) var config configv1.ADKConfig require.NoError(t, runtimeconfig.Unmarshal(revision.ConfigJSON, &config)) require.Len(t, config.Agent.RemoteAgents, 1) - }) - t.Run("names are unique across Dedicated and external agents", func(t *testing.T) { - agent := inlineAgent(harness, behavior) - agent.Annotations = map[string]string{adkconfig.ExternalA2AAnnotation: value} - _, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), agent) - require.ErrorContains(t, err, "duplicate") - }) - t.Run("an invalid annotation is a validation error", func(t *testing.T) { - agent := inlineAgent(harness, plain) - agent.Annotations = map[string]string{adkconfig.ExternalA2AAnnotation: "nope"} - _, err := compiler(t, modelConfig(), harness).CompileAgent(t.Context(), agent) - var validationError *translator.ValidationError - require.ErrorAs(t, err, &validationError) - require.ErrorContains(t, err, adkconfig.ExternalA2AAnnotation) + require.NotContains(t, revision.EgressDestinations, origin) }) }