diff --git a/docs/architecture/configuration-and-compilation.md b/docs/architecture/configuration-and-compilation.md index bce898e434..daf99c7e5d 100644 --- a/docs/architecture/configuration-and-compilation.md +++ b/docs/architecture/configuration-and-compilation.md @@ -312,3 +312,47 @@ Agent's last successful revision. This replaces implicit label selection and the old template/Harness inputs as a breaking API change. SandboxTemplate hosting configuration is not part of this change. + +## Credential-free package origins + +Trusted Harness authors can configure `spec.extraHTTPSOrigins` for Codex and +Claude. This is a bounded list (at most 32 entries) of exact HTTPS DNS origins +on port 443. An omitted port and a root slash are accepted; hostnames are +lowercased and destinations sorted and deduplicated. Wildcards, IP addresses, +userinfo, queries, fragments, other ports and non-root paths are rejected during +compilation, before runtime preparation. Other harness types reject this field. +The schema also bounds entries and rejects unsupported URL shapes. + +For npm, PyPI and Go package downloads, an operator may explicitly grant: + +```yaml +spec: + extraHTTPSOrigins: + - https://registry.npmjs.org + - https://pypi.org + - https://files.pythonhosted.org + - https://proxy.golang.org + - https://sum.golang.org + - https://storage.googleapis.com +``` + +These entries join the existing provider, Git, MCP, skills and telemetry egress +destinations in the immutable prepared revision. Changing the destination list +changes revision identity. Existing Sessions retain their pinned policy. An +absent list preserves the default policy. The extra list creates no credential +bindings or runtime environment/configuration effects; a host already carrying +a provider, Git or MCP credential binding is rejected as an extra origin. + +Each grant allows the **whole host**, including `storage.googleapis.com`, rather +than a particular bucket, package, HTTP method or path. Audit the union of all +existing grants. Registry access does not enforce package approval or prevent +publishing or exfiltration to an allowed host. Unlisted redirect targets, VCS +sources and binary download hosts fail closed; obtain an explicit reviewed +policy change rather than adding suffix grants or automatic fallback hosts. + +Harness policy, including an inline Agent Harness, must remain controlled by +trusted configuration authors. Session requests and AgentTemplates cannot +supply this list. This field does not add actor authority to edit Harnesses or +Agents. Cluster gateway host configuration and live package-installation proof +are separate deployment work; this compiler contract alone does not demonstrate +registry reachability. diff --git a/go/api/config/crd/bases/api.kagent.dev_agents.yaml b/go/api/config/crd/bases/api.kagent.dev_agents.yaml index 717f332e0b..67e99d1551 100644 --- a/go/api/config/crd/bases/api.kagent.dev_agents.yaml +++ b/go/api/config/crd/bases/api.kagent.dev_agents.yaml @@ -95,6 +95,19 @@ spec: x-kubernetes-list-map-keys: - name x-kubernetes-list-type: map + extraHTTPSOrigins: + description: |- + ExtraHTTPSOrigins grants whole-host HTTPS access without credentials. + Only trusted Harness authors may configure it; each entry is an exact + DNS origin on port 443, with an optional root slash. No suffix grants. + Only the Codex and Claude adapters support it. + items: + maxLength: 273 + pattern: ^https://([A-Za-z0-9]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?(:443)?/?$ + type: string + maxItems: 32 + type: array + x-kubernetes-list-type: set git: description: |- Git lets sessions bootstrap a repository checkout into the workspace. @@ -338,6 +351,9 @@ spec: rule: '!has(self.byo) || size(self.workload.command) > 0' - message: git is supported only by the codex and claude harnesses rule: '!has(self.git) || has(self.codex) || has(self.claude)' + - message: extraHTTPSOrigins is supported only by the codex and claude + harnesses + rule: '!has(self.extraHTTPSOrigins) || has(self.codex) || has(self.claude)' harnessRef: description: |- LocalObjectReference contains enough information to let you locate the diff --git a/go/api/config/crd/bases/api.kagent.dev_harnesses.yaml b/go/api/config/crd/bases/api.kagent.dev_harnesses.yaml index d0d388080f..8761a3fd37 100644 --- a/go/api/config/crd/bases/api.kagent.dev_harnesses.yaml +++ b/go/api/config/crd/bases/api.kagent.dev_harnesses.yaml @@ -88,6 +88,19 @@ spec: x-kubernetes-list-map-keys: - name x-kubernetes-list-type: map + extraHTTPSOrigins: + description: |- + ExtraHTTPSOrigins grants whole-host HTTPS access without credentials. + Only trusted Harness authors may configure it; each entry is an exact + DNS origin on port 443, with an optional root slash. No suffix grants. + Only the Codex and Claude adapters support it. + items: + maxLength: 273 + pattern: ^https://([A-Za-z0-9]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?(:443)?/?$ + type: string + maxItems: 32 + type: array + x-kubernetes-list-type: set git: description: |- Git lets sessions bootstrap a repository checkout into the workspace. @@ -330,6 +343,9 @@ spec: rule: '!has(self.byo) || size(self.workload.command) > 0' - message: git is supported only by the codex and claude harnesses rule: '!has(self.git) || has(self.codex) || has(self.claude)' + - message: extraHTTPSOrigins is supported only by the codex and claude + harnesses + rule: '!has(self.extraHTTPSOrigins) || has(self.codex) || has(self.claude)' status: description: HarnessStatus reports controller-derived capabilities and current health. diff --git a/go/api/v1alpha3/harness_types.go b/go/api/v1alpha3/harness_types.go index 0ead8f8018..d0d979017d 100644 --- a/go/api/v1alpha3/harness_types.go +++ b/go/api/v1alpha3/harness_types.go @@ -163,6 +163,7 @@ type HarnessWorkload struct { // +kubebuilder:validation:XValidation:rule="(has(self.kagent) ? 1 : 0) + (has(self.codex) ? 1 : 0) + (has(self.claude) ? 1 : 0) + (has(self.byo) ? 1 : 0) == 1",message="exactly one of kagent, codex, claude, or byo must be specified" // +kubebuilder:validation:XValidation:rule="!has(self.byo) || size(self.workload.command) > 0",message="BYO harnesses must specify workload.command" // +kubebuilder:validation:XValidation:rule="!has(self.git) || has(self.codex) || has(self.claude)",message="git is supported only by the codex and claude harnesses" +// +kubebuilder:validation:XValidation:rule="!has(self.extraHTTPSOrigins) || has(self.codex) || has(self.claude)",message="extraHTTPSOrigins is supported only by the codex and claude harnesses" type HarnessSpec struct { // SessionIdleTTL overrides the controller default for all Sessions of this // Agent, including existing Sessions. Zero disables idle expiration. @@ -187,6 +188,17 @@ type HarnessSpec struct { // +optional Git *HarnessGit `json:"git,omitempty"` + // ExtraHTTPSOrigins grants whole-host HTTPS access without credentials. + // Only trusted Harness authors may configure it; each entry is an exact + // DNS origin on port 443, with an optional root slash. No suffix grants. + // Only the Codex and Claude adapters support it. + // +kubebuilder:validation:MaxItems=32 + // +kubebuilder:validation:items:MaxLength=273 + // +kubebuilder:validation:items:Pattern=`^https://([A-Za-z0-9]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?(:443)?/?$` + // +listType=set + // +optional + ExtraHTTPSOrigins []string `json:"extraHTTPSOrigins,omitempty"` + // +required Workload HarnessWorkload `json:"workload"` diff --git a/go/api/v1alpha3/zz_generated.deepcopy.go b/go/api/v1alpha3/zz_generated.deepcopy.go index 23bd0f785e..24b292e597 100644 --- a/go/api/v1alpha3/zz_generated.deepcopy.go +++ b/go/api/v1alpha3/zz_generated.deepcopy.go @@ -773,6 +773,11 @@ func (in *HarnessSpec) DeepCopyInto(out *HarnessSpec) { *out = new(HarnessGit) (*in).DeepCopyInto(*out) } + if in.ExtraHTTPSOrigins != nil { + in, out := &in.ExtraHTTPSOrigins, &out.ExtraHTTPSOrigins + *out = make([]string, len(*in)) + copy(*out, *in) + } in.Workload.DeepCopyInto(&out.Workload) if in.Env != nil { in, out := &in.Env, &out.Env diff --git a/go/core/internal/controller/environment.go b/go/core/internal/controller/environment.go index da20713b4d..18e46b08b9 100644 --- a/go/core/internal/controller/environment.go +++ b/go/core/internal/controller/environment.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "io" + "maps" "strings" atev1alpha1 "github.com/agent-substrate/substrate/pkg/api/v1alpha1" @@ -65,9 +66,7 @@ type EnvironmentPreparer struct { func NewEnvironmentPreparer(collections Collections, store runtimeRevisionStore, templates actorTemplateClient, catalog RuntimePayloadCatalog) *EnvironmentPreparer { copy := RuntimePayloadCatalog{} - for key, value := range catalog { - copy[key] = value - } + maps.Copy(copy, catalog) return &EnvironmentPreparer{collections: collections, store: store, templates: templates, catalog: copy} } diff --git a/go/core/internal/database/environment_test.go b/go/core/internal/database/environment_test.go index 773e50c9fc..1939e80c78 100644 --- a/go/core/internal/database/environment_test.go +++ b/go/core/internal/database/environment_test.go @@ -2,9 +2,10 @@ package database import ( "encoding/json" - "github.com/google/uuid" "testing" + "github.com/google/uuid" + apiv1alpha1 "github.com/kagent-dev/kagent/go/api/gen/kagent/api/v1alpha1" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" diff --git a/go/core/internal/grpcserver/control_auth_test.go b/go/core/internal/grpcserver/control_auth_test.go index 28f2740a65..6ab5bfef53 100644 --- a/go/core/internal/grpcserver/control_auth_test.go +++ b/go/core/internal/grpcserver/control_auth_test.go @@ -57,7 +57,7 @@ func TestControlAuthNativeAndWeb(t *testing.T) { const futurePublic = "/test.Public/Discover" policies[futurePublic] = pkgauth.AccessPublic server, err := New(Config{Listener: listener, Authenticator: provider, Reflection: true, MethodPolicies: policies, RegisterServices: func(registrar grpc.ServiceRegistrar) { - registrar.RegisterService(&grpc.ServiceDesc{ServiceName: "test.Public", HandlerType: (*interface{})(nil), Methods: []grpc.MethodDesc{{MethodName: "Discover"}}}, &struct{}{}) + registrar.RegisterService(&grpc.ServiceDesc{ServiceName: "test.Public", HandlerType: (*any)(nil), Methods: []grpc.MethodDesc{{MethodName: "Discover"}}}, &struct{}{}) }, SystemService: testSystemService(), SessionService: sessionsvc.NewService(store, policy, credentialTestWorkflow{})}) require.NoError(t, err) ctx, cancel := context.WithCancel(t.Context()) @@ -158,7 +158,6 @@ func TestControlAuthNativeAndWeb(t *testing.T) { require.False(t, called, fullMethod) } } - } // A stream must be refused before its handler receives the first message. diff --git a/go/core/internal/service/controlauth/policy.go b/go/core/internal/service/controlauth/policy.go index 818ce954bd..453c81b26b 100644 --- a/go/core/internal/service/controlauth/policy.go +++ b/go/core/internal/service/controlauth/policy.go @@ -64,7 +64,7 @@ func New(config Config) (*Policy, error) { for _, rule := range config.Credentials { origin, err := url.Parse(rule.Origin) _, patternErr := path.Match(rule.SecretNamePattern, "probe") - if rule.Namespace != config.Namespace || rule.SecretNamePattern == "" || patternErr != nil || rule.Key == "" || rule.Purpose != "mcp" || rule.Header != "authorization" || err != nil || (origin.Scheme != "https" && !(origin.Scheme == "http" && slices.Contains(config.CleartextMCPOrigins, rule.Origin))) || origin.Host == "" || origin.User != nil || origin.RawQuery != "" || origin.ForceQuery || origin.Fragment != "" || origin.Path != "" { + if rule.Namespace != config.Namespace || rule.SecretNamePattern == "" || patternErr != nil || rule.Key == "" || rule.Purpose != "mcp" || rule.Header != "authorization" || err != nil || (origin.Scheme != "https" && (origin.Scheme != "http" || !slices.Contains(config.CleartextMCPOrigins, rule.Origin))) || origin.Host == "" || origin.User != nil || origin.RawQuery != "" || origin.ForceQuery || origin.Fragment != "" || origin.Path != "" { return nil, errors.New("invalid approved credential tuple") } } @@ -121,12 +121,7 @@ func (p *Policy) approvedDevelopmentImage(image string) bool { if !qualified { return false } - for _, allowed := range p.config.DevelopmentEnvironmentRegistries { - if registry == allowed { - return true - } - } - return false + return slices.Contains(p.config.DevelopmentEnvironmentRegistries, registry) } // CheckDevelopmentEnvironment validates all caller selection fields before any @@ -144,12 +139,7 @@ func (p *Policy) agent(namespace, name string) bool { if namespace != p.config.Namespace { return false } - for _, allowed := range p.config.Agents { - if name == allowed { - return true - } - } - return false + return slices.Contains(p.config.Agents, name) } func internal(ctx context.Context) bool { diff --git a/go/core/internal/translator/claude/compiler.go b/go/core/internal/translator/claude/compiler.go index 8fa028ad80..22ae97f48d 100644 --- a/go/core/internal/translator/claude/compiler.go +++ b/go/core/internal/translator/claude/compiler.go @@ -38,6 +38,10 @@ func (c *Compiler) Compile(ctx context.Context, input *v2translator.HarnessInput if input == nil || input.Harness == nil || input.Root == nil || input.Root.Template == nil || input.Root.ResolvedModelConfig == nil || input.Root.ResolvedModelConfig.Config == nil { return nil, fmt.Errorf("claude compiler requires a resolved Harness, AgentTemplate, and ModelConfig") } + extraEgress, err := v2translator.CompileExtraHTTPSOrigins(input.Harness.Spec.ExtraHTTPSOrigins) + if err != nil { + return nil, err + } model := input.Root.ResolvedModelConfig.Config if strings.TrimSpace(model.Spec.Model) == "" { return nil, v2translator.NewValidationError("Claude ModelConfig model is required") @@ -125,6 +129,10 @@ func (c *Compiler) Compile(ctx context.Context, input *v2translator.HarnessInput return nil, err } + if err := v2translator.ValidateExtraHTTPSCredentials(extraEgress, credentials); err != nil { + return nil, err + } + egress = append(egress, extraEgress...) egress = append(egress, skillEgress...) egress = append(egress, mcp.egress...) egress = append(egress, gitEgress...) diff --git a/go/core/internal/translator/codex/compiler.go b/go/core/internal/translator/codex/compiler.go index 24655d0cc1..d6dd436018 100644 --- a/go/core/internal/translator/codex/compiler.go +++ b/go/core/internal/translator/codex/compiler.go @@ -55,6 +55,10 @@ func (c *Compiler) Compile(ctx context.Context, input *v2translator.HarnessInput if input == nil || input.Harness == nil || input.Root == nil || input.Root.Template == nil || input.Root.ResolvedModelConfig == nil || input.Root.ResolvedModelConfig.Config == nil { return nil, fmt.Errorf("codex compiler requires a resolved Harness, AgentTemplate, and ModelConfig") } + extraEgress, err := v2translator.CompileExtraHTTPSOrigins(input.Harness.Spec.ExtraHTTPSOrigins) + if err != nil { + return nil, err + } model := input.Root.ResolvedModelConfig.Config if strings.TrimSpace(model.Spec.Model) == "" { return nil, v2translator.NewValidationError("Codex ModelConfig model is required") @@ -143,6 +147,10 @@ func (c *Compiler) Compile(ctx context.Context, input *v2translator.HarnessInput if err != nil { return nil, err } + if err := v2translator.ValidateExtraHTTPSCredentials(extraEgress, credentials); err != nil { + return nil, err + } + egress = append(egress, extraEgress...) egress = append(egress, skillEgress...) egress = append(egress, mcp.egress...) egress = append(egress, gitEgress...) diff --git a/go/core/internal/translator/compiler.go b/go/core/internal/translator/compiler.go index 6ded9729a9..cf45f4d79a 100644 --- a/go/core/internal/translator/compiler.go +++ b/go/core/internal/translator/compiler.go @@ -155,6 +155,9 @@ func (c *Compiler) CompileAgent(ctx context.Context, agent *v1alpha3.Agent) (*Co // compileConfiguration compiles resolved configuration for the named Agent. // The Agent name owns runtime identity; template and Harness names are provenance. func (c *Compiler) compileConfiguration(ctx context.Context, agentName string, harness *HarnessConfiguration, template *TemplateConfiguration) (*CompileResult, error) { + if len(harness.Spec.ExtraHTTPSOrigins) != 0 && harnessType(harness) != HarnessTypeCodex && harnessType(harness) != HarnessTypeClaude { + return nil, NewValidationError("extraHTTPSOrigins is supported only by the codex and claude harnesses") + } harnessCompiler := c.harnessCompilers[harnessType(harness)] if harnessCompiler == nil { return nil, NewValidationError("Harness runtime is not supported by any compiler") diff --git a/go/core/internal/translator/compiler_test.go b/go/core/internal/translator/compiler_test.go index 3dc1aedeab..81c00a4f98 100644 --- a/go/core/internal/translator/compiler_test.go +++ b/go/core/internal/translator/compiler_test.go @@ -1114,3 +1114,76 @@ func TestSessionIdleTTLDoesNotChangeRuntimeRevision(t *testing.T) { }) } } + +func TestCompileAgentExtraHTTPSOrigins(t *testing.T) { + for _, harnessType := range []v2translator.HarnessType{v2translator.HarnessTypeCodex, v2translator.HarnessTypeClaude} { + t.Run(string(harnessType), func(t *testing.T) { + harness, template, model := runtimeFixture(harnessType) + harness.Spec.Git = &v1alpha3.HarnessGit{ + Origins: []string{"github.com"}, + CredentialSecretRef: &v1alpha3.SecretKeyReference{Name: "git-auth", Key: "authorization"}, + } + server := remoteMCPServer("packages-test-mcp", "https://mcp.example.com/mcp") + server.Spec.HeadersFrom = []v1alpha3.ValueRef{{Name: "Authorization", ValueFrom: &v1alpha3.ValueSource{Type: v1alpha3.SecretValueSource, Name: "mcp-auth", Key: "token"}}} + template.Spec.Tools = []v1alpha3.ToolBinding{{MCP: &v1alpha3.MCPToolBinding{Server: corev1.TypedLocalObjectReference{Kind: "RemoteMCPServer", Name: server.Name}, Tools: []string{"lookup"}}}} + objects := []any{model, server, + &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "test", Name: "mcp-auth"}, Data: map[string][]byte{"token": []byte("mcp-secret")}}, + &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "test", Name: "model-auth"}, Data: map[string][]byte{"api-key": []byte("secret")}}, + &atev1alpha1.WorkerPool{ObjectMeta: metav1.ObjectMeta{Namespace: "test", Name: "selected"}}, + } + compile := func(origins []string) *v2translator.CompileResult { + harness.Spec.ExtraHTTPSOrigins = origins + result, err := compiler(t, objects...).CompileAgent(t.Context(), inlineAgent(harness, template)) + require.NoError(t, err) + return result + } + baseline := compile(nil) + origins := []string{"https://registry.npmjs.org", "https://pypi.org", "https://files.pythonhosted.org", "https://proxy.golang.org", "https://sum.golang.org", "https://storage.googleapis.com"} + configured := compile(origins) + for _, origin := range origins { + require.Contains(t, configured.EgressDestinations, origin+":443") + } + for _, origin := range baseline.EgressDestinations { + require.Contains(t, configured.EgressDestinations, origin) + } + require.Equal(t, baseline.Credentials, configured.Credentials) + require.Equal(t, baseline.Environment, configured.Environment) + require.Equal(t, baseline.ConfigJSON, configured.ConfigJSON) + before, err := baseline.Digest() + require.NoError(t, err) + after, err := configured.Digest() + require.NoError(t, err) + require.NotEqual(t, before, after) + require.Equal(t, origins, harness.Spec.ExtraHTTPSOrigins) + reordered := slices.Clone(origins) + slices.Reverse(reordered) + reordered = append(reordered, "https://PYPI.org:443/") + normalized := compile(reordered) + require.Equal(t, configured.EgressDestinations, normalized.EgressDestinations) + // Source provenance retains authored spelling/order, independently of the + // canonical destinations used by the prepared policy. + for _, invalid := range []string{"http://pypi.org", "https://*.pypi.org", "https://pypi.org:8443", "https://127.0.0.1", "https://user@pypi.org", "https://pypi.org/simple", "https://github.com", "https://mcp.example.com", "https://api.openai.com", "https://api.anthropic.com"} { + if (invalid == "https://api.openai.com" && harnessType == v2translator.HarnessTypeClaude) || (invalid == "https://api.anthropic.com" && harnessType == v2translator.HarnessTypeCodex) { + continue + } + harness.Spec.ExtraHTTPSOrigins = []string{invalid} + result, err := compiler(t, objects...).CompileAgent(t.Context(), inlineAgent(harness, template)) + require.Error(t, err) + require.Nil(t, result) + require.ErrorAs(t, err, new(*v2translator.ValidationError)) + } + }) + } +} + +func TestCompileAgentRejectsExtraHTTPSOriginsForOtherHarnesses(t *testing.T) { + for _, harnessType := range []v2translator.HarnessType{v2translator.HarnessTypeKagent, v2translator.HarnessTypeBYO} { + t.Run(string(harnessType), func(t *testing.T) { + harness, template, _ := runtimeFixture(harnessType) + harness.Spec.ExtraHTTPSOrigins = []string{"https://pypi.org"} + result, err := compiler(t).CompileAgent(t.Context(), inlineAgent(harness, template)) + require.ErrorContains(t, err, "extraHTTPSOrigins is supported only") + require.Nil(t, result) + }) + } +} diff --git a/go/core/internal/translator/extra_https_origins.go b/go/core/internal/translator/extra_https_origins.go new file mode 100644 index 0000000000..b0a0166f6b --- /dev/null +++ b/go/core/internal/translator/extra_https_origins.go @@ -0,0 +1,55 @@ +package translator + +import ( + "net/netip" + "net/url" + "slices" + "strings" + + "github.com/kagent-dev/kagent/go/core/internal/egress" + "k8s.io/apimachinery/pkg/util/validation" +) + +// CompileExtraHTTPSOrigins validates trusted, credential-free whole-host grants +// and uses the same destination representation as the other egress contributors. +func CompileExtraHTTPSOrigins(origins []string) ([]string, error) { + if len(origins) > 32 { + return nil, NewValidationError("extraHTTPSOrigins must contain at most 32 origins") + } + var destinations []string + for _, origin := range origins { + u, err := url.Parse(origin) + if err != nil || len(origin) > 273 || !strings.HasPrefix(origin, "https://") || u.Scheme != "https" || u.User != nil || u.Opaque != "" || u.RawQuery != "" || u.ForceQuery || strings.Contains(origin, "#") || (u.Path != "" && u.Path != "/") || u.RawPath != "" { + return nil, NewValidationError("extraHTTPSOrigins entry must be an exact HTTPS DNS origin without credentials, query, fragment, or non-root path") + } + host := strings.ToLower(u.Hostname()) + _, ipErr := netip.ParseAddr(host) + if ipErr == nil || len(validation.IsDNS1123Subdomain(host)) != 0 || !strings.Contains(host, ".") || (u.Host != u.Hostname() && u.Host != u.Hostname()+":443") { + return nil, NewValidationError("extraHTTPSOrigins entry must use an exact DNS hostname and port 443") + } + labels := strings.Split(host, ".") + if last := labels[len(labels)-1]; last[0] < 'a' || last[0] > 'z' { + return nil, NewValidationError("extraHTTPSOrigins must use a DNS name with an alphabetic top-level label") + } + for _, label := range labels { + if len(label) > 63 { + return nil, NewValidationError("extraHTTPSOrigins DNS labels must contain at most 63 characters") + } + } + destinations = append(destinations, egress.Origin(&url.URL{Scheme: "https", Host: host})) + } + slices.Sort(destinations) + return slices.Compact(destinations), nil +} + +// ValidateExtraHTTPSCredentials prevents existing provider, Git, or MCP bindings +// from giving an extra origin credential effects through a shared hostname. +func ValidateExtraHTTPSCredentials(destinations []string, credentials []egress.Credential) error { + for _, credential := range credentials { + destination := egress.Origin(&url.URL{Scheme: "https", Host: credential.Hostname}) + if slices.Contains(destinations, destination) { + return NewValidationError("extraHTTPSOrigins host %q already has a credential binding", credential.Hostname) + } + } + return nil +} diff --git a/go/core/internal/translator/extra_https_origins_test.go b/go/core/internal/translator/extra_https_origins_test.go new file mode 100644 index 0000000000..b4894aeff7 --- /dev/null +++ b/go/core/internal/translator/extra_https_origins_test.go @@ -0,0 +1,48 @@ +package translator_test + +import ( + "strings" + "testing" + + "github.com/kagent-dev/kagent/go/core/internal/egress" + translator "github.com/kagent-dev/kagent/go/core/internal/translator" + "github.com/stretchr/testify/require" +) + +func TestCompileExtraHTTPSOrigins(t *testing.T) { + destinations, err := translator.CompileExtraHTTPSOrigins([]string{ + "https://PYPI.org/", "https://registry.npmjs.org:443", "https://pypi.org:443/", + }) + require.NoError(t, err) + require.Equal(t, []string{"https://pypi.org:443", "https://registry.npmjs.org:443"}, destinations) + empty, err := translator.CompileExtraHTTPSOrigins(nil) + require.NoError(t, err) + require.Nil(t, empty) +} + +func TestCompileExtraHTTPSOriginsRejectsInvalid(t *testing.T) { + for _, origin := range []string{ + "", "pypi.org", "http://pypi.org", "https://*.pypi.org", "https://pypi.org:80", "https://pypi.org:0443", "https://pypi.org:", + "https://127.0.0.1", "https://[::1]", "https://user:pass@pypi.org", "https://pypi.org/simple", "https://pypi.org//", + "https://pypi.org/%2f", "https://pypi.org?", "https://pypi.org?q=x", "https://pypi.org#", "https://pypi.org#x", + " https://pypi.org", "https://pypi.org ", "https://pypi.org.", "https://localhost", "https://-pypi.org", "https://pypi_.org", + "https://" + strings.Repeat("a", 64) + ".org", + } { + t.Run(origin, func(t *testing.T) { + destinations, err := translator.CompileExtraHTTPSOrigins([]string{origin}) + require.Error(t, err) + require.Nil(t, destinations) + require.ErrorAs(t, err, new(*translator.ValidationError)) + }) + } + _, err := translator.CompileExtraHTTPSOrigins(make([]string, 33)) + require.ErrorContains(t, err, "at most 32") +} + +func TestExtraHTTPSOriginsRejectCredentialOverlap(t *testing.T) { + for _, header := range []string{"authorization", "x-api-key", "x-mcp-token"} { + err := translator.ValidateExtraHTTPSCredentials([]string{"https://pypi.org:443"}, []egress.Credential{{Hostname: "pypi.org", Header: header}}) + require.ErrorContains(t, err, "already has a credential binding") + } + require.NoError(t, translator.ValidateExtraHTTPSCredentials([]string{"https://pypi.org:443"}, []egress.Credential{{Hostname: "api.openai.com", Header: "authorization"}})) +} diff --git a/go/core/internal/translator/extra_https_schema_test.go b/go/core/internal/translator/extra_https_schema_test.go new file mode 100644 index 0000000000..4655be3d31 --- /dev/null +++ b/go/core/internal/translator/extra_https_schema_test.go @@ -0,0 +1,52 @@ +package translator_test + +import ( + "os" + "strings" + "testing" + + "github.com/stretchr/testify/require" + apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + schemavalidation "k8s.io/apiextensions-apiserver/pkg/apiserver/validation" + "k8s.io/apimachinery/pkg/util/validation/field" + "sigs.k8s.io/yaml" +) + +func TestExtraHTTPSOriginsGeneratedSchemas(t *testing.T) { + for _, kind := range []string{"harnesses", "agents"} { + t.Run(kind, func(t *testing.T) { + filename := "api.kagent.dev_" + kind + ".yaml" + source, err := os.ReadFile("../../../api/config/crd/bases/" + filename) + require.NoError(t, err) + helm, err := os.ReadFile("../../../../helm/kagent-crds/templates/" + filename) + require.NoError(t, err) + require.Equal(t, source, helm) + var crd apiextensionsv1.CustomResourceDefinition + require.NoError(t, yaml.Unmarshal(source, &crd)) + spec := crd.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["spec"] + if kind == "agents" { + spec = spec.Properties["harness"] + } + schema := spec.Properties["extraHTTPSOrigins"] + require.NotNil(t, schema.MaxItems) + require.EqualValues(t, 32, *schema.MaxItems) + require.Equal(t, "set", *schema.XListType) + var internal apiextensions.JSONSchemaProps + require.NoError(t, apiextensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(&schema, &internal, nil)) + validator, _, err := schemavalidation.NewSchemaValidator(&internal) + require.NoError(t, err) + for _, host := range []string{"registry.npmjs.org", "pypi.org", "files.pythonhosted.org", "proxy.golang.org", "sum.golang.org", "storage.googleapis.com"} { + for _, origin := range []string{"https://" + host, "https://" + strings.ToUpper(host) + ":443/"} { + require.Empty(t, schemavalidation.ValidateCustomResource(field.NewPath("extraHTTPSOrigins"), []any{origin}, validator), origin) + } + } + for _, origin := range []string{"http://pypi.org", "https://*.pypi.org", "https://pypi.org:80", "https://127.0.0.1", "https://[::1]", "https://user@pypi.org", "https://pypi.org/simple", "https://pypi.org?", "https://pypi.org#", "https://" + strings.Repeat("a", 64) + ".org"} { + require.NotEmpty(t, schemavalidation.ValidateCustomResource(field.NewPath("extraHTTPSOrigins"), []any{origin}, validator), origin) + } + require.NotEmpty(t, schemavalidation.ValidateCustomResource(field.NewPath("extraHTTPSOrigins"), make([]any, 33), validator)) + require.Contains(t, spec.XValidations, apiextensionsv1.ValidationRule{Rule: "!has(self.extraHTTPSOrigins) || has(self.codex) || has(self.claude)", Message: "extraHTTPSOrigins is supported only by the codex and claude harnesses"}) + // Credential overlap needs resolved external inputs, so compiler tests own it. + }) + } +} diff --git a/go/core/pkg/app/service_auth_test.go b/go/core/pkg/app/service_auth_test.go index 62d62f066c..e2743a1bd3 100644 --- a/go/core/pkg/app/service_auth_test.go +++ b/go/core/pkg/app/service_auth_test.go @@ -1,14 +1,15 @@ package app import ( - authimpl "github.com/kagent-dev/kagent/go/core/internal/httpserver/auth" - "github.com/kagent-dev/kagent/go/core/internal/service/controlauth" - "github.com/kagent-dev/kagent/go/core/pkg/auth" - "github.com/stretchr/testify/require" "os" "path/filepath" "strings" "testing" + + authimpl "github.com/kagent-dev/kagent/go/core/internal/httpserver/auth" + "github.com/kagent-dev/kagent/go/core/internal/service/controlauth" + "github.com/kagent-dev/kagent/go/core/pkg/auth" + "github.com/stretchr/testify/require" ) func TestServiceAuthenticatorDefaultsToScopedPolicy(t *testing.T) { diff --git a/helm/kagent-crds/templates/api.kagent.dev_agents.yaml b/helm/kagent-crds/templates/api.kagent.dev_agents.yaml index 717f332e0b..67e99d1551 100644 --- a/helm/kagent-crds/templates/api.kagent.dev_agents.yaml +++ b/helm/kagent-crds/templates/api.kagent.dev_agents.yaml @@ -95,6 +95,19 @@ spec: x-kubernetes-list-map-keys: - name x-kubernetes-list-type: map + extraHTTPSOrigins: + description: |- + ExtraHTTPSOrigins grants whole-host HTTPS access without credentials. + Only trusted Harness authors may configure it; each entry is an exact + DNS origin on port 443, with an optional root slash. No suffix grants. + Only the Codex and Claude adapters support it. + items: + maxLength: 273 + pattern: ^https://([A-Za-z0-9]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?(:443)?/?$ + type: string + maxItems: 32 + type: array + x-kubernetes-list-type: set git: description: |- Git lets sessions bootstrap a repository checkout into the workspace. @@ -338,6 +351,9 @@ spec: rule: '!has(self.byo) || size(self.workload.command) > 0' - message: git is supported only by the codex and claude harnesses rule: '!has(self.git) || has(self.codex) || has(self.claude)' + - message: extraHTTPSOrigins is supported only by the codex and claude + harnesses + rule: '!has(self.extraHTTPSOrigins) || has(self.codex) || has(self.claude)' harnessRef: description: |- LocalObjectReference contains enough information to let you locate the diff --git a/helm/kagent-crds/templates/api.kagent.dev_harnesses.yaml b/helm/kagent-crds/templates/api.kagent.dev_harnesses.yaml index d0d388080f..8761a3fd37 100644 --- a/helm/kagent-crds/templates/api.kagent.dev_harnesses.yaml +++ b/helm/kagent-crds/templates/api.kagent.dev_harnesses.yaml @@ -88,6 +88,19 @@ spec: x-kubernetes-list-map-keys: - name x-kubernetes-list-type: map + extraHTTPSOrigins: + description: |- + ExtraHTTPSOrigins grants whole-host HTTPS access without credentials. + Only trusted Harness authors may configure it; each entry is an exact + DNS origin on port 443, with an optional root slash. No suffix grants. + Only the Codex and Claude adapters support it. + items: + maxLength: 273 + pattern: ^https://([A-Za-z0-9]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]([-A-Za-z0-9]{0,61}[A-Za-z0-9])?(:443)?/?$ + type: string + maxItems: 32 + type: array + x-kubernetes-list-type: set git: description: |- Git lets sessions bootstrap a repository checkout into the workspace. @@ -330,6 +343,9 @@ spec: rule: '!has(self.byo) || size(self.workload.command) > 0' - message: git is supported only by the codex and claude harnesses rule: '!has(self.git) || has(self.codex) || has(self.claude)' + - message: extraHTTPSOrigins is supported only by the codex and claude + harnesses + rule: '!has(self.extraHTTPSOrigins) || has(self.codex) || has(self.claude)' status: description: HarnessStatus reports controller-derived capabilities and current health.