Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
350 changes: 350 additions & 0 deletions cmd/ateapi/internal/controlapi/egress_policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,350 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package controlapi

import (
"context"
"errors"
"fmt"
"net/netip"
"net/url"
"strings"

"github.com/agent-substrate/substrate/cmd/ateapi/internal/store"
"github.com/agent-substrate/substrate/internal/resources"
"github.com/agent-substrate/substrate/pkg/proto/ateapipb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/validation/field"
)

func (s *RPCService) GetActorEgressPolicy(ctx context.Context, req *ateapipb.GetActorEgressPolicyRequest) (*ateapipb.EgressPolicy, error) {
if errs := Validate_GetActorEgressPolicyRequest(ctx, operation.Operation{Type: operation.Create}, nil, req, nil); len(errs) > 0 {
return nil, toGRPCStatusError(errs)
}
policy, err := s.impl.GetEgressPolicy(ctx, resources.ActorRefFromObjectRef(req.GetActor()))
if errors.Is(err, store.ErrNotFound) {
return nil, status.Error(codes.NotFound, "EgressPolicy not found")
}
if err != nil {
return nil, fmt.Errorf("while getting Actor egress policy: %w", err)
}
return policy, nil
}

func (s *RPCService) CreateActorEgressPolicy(ctx context.Context, req *ateapipb.CreateActorEgressPolicyRequest) (*ateapipb.EgressPolicy, error) {
policy := req.GetEgressPolicy()
if policy != nil {
scrubResourceMetadataForCreate(policy.Metadata)
}
if errs := validateCreateActorEgressPolicyRequest(ctx, req); len(errs) > 0 {
return nil, toGRPCStatusError(errs)
}
actorRef := resources.ActorRefFromObjectRef(req.GetActor())
in := normalizeEgressPolicy(policy)
created, err := s.impl.CreateEgressPolicy(ctx, actorRef, in)
return mapEgressPolicyWrite(created, err)
}

func (s *RPCService) UpdateActorEgressPolicy(ctx context.Context, req *ateapipb.UpdateActorEgressPolicyRequest) (*ateapipb.EgressPolicy, error) {
policy := req.GetEgressPolicy()
if policy != nil {
scrubResourceMetadataForUpdate(policy.Metadata)
}
if errs := validateUpdateActorEgressPolicyRequest(ctx, req); len(errs) > 0 {
return nil, toGRPCStatusError(errs)
}
actorRef := resources.ActorRefFromObjectRef(req.GetActor())
in := normalizeEgressPolicy(policy)
updated, err := s.impl.UpdateEgressPolicy(ctx, actorRef, store.PreconditionFrom(in), func(toUpdate *ateapipb.EgressPolicy) error {
toUpdate.Rules = in.GetRules()
return nil
})
return mapEgressPolicyWrite(updated, err)
}

func (s *RPCService) DeleteActorEgressPolicy(ctx context.Context, req *ateapipb.DeleteActorEgressPolicyRequest) (*ateapipb.EgressPolicy, error) {
if errs := Validate_DeleteActorEgressPolicyRequest(ctx, operation.Operation{Type: operation.Create}, nil, req, nil); len(errs) > 0 {
return nil, toGRPCStatusError(errs)
}
policy, err := s.impl.DeleteEgressPolicy(ctx, resources.ActorRefFromObjectRef(req.GetActor()))
return mapEgressPolicyWrite(policy, err)
}

func (s *ServiceImpl) CreateEgressPolicy(ctx context.Context, actorRef resources.ActorRef, policy *ateapipb.EgressPolicy) (*ateapipb.EgressPolicy, error) {
return s.store.CreateEgressPolicy(ctx, actorRef, policy)
}

func (s *ServiceImpl) GetEgressPolicy(ctx context.Context, actorRef resources.ActorRef) (*ateapipb.EgressPolicy, error) {
return s.store.GetEgressPolicy(ctx, actorRef)
}

func (s *ServiceImpl) UpdateEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(*ateapipb.EgressPolicy) error) (*ateapipb.EgressPolicy, error) {
return s.store.UpdateEgressPolicy(ctx, actorRef, precondition, mutate)
}

func (s *ServiceImpl) DeleteEgressPolicy(ctx context.Context, actorRef resources.ActorRef) (*ateapipb.EgressPolicy, error) {
return s.store.DeleteEgressPolicy(ctx, actorRef)
}

func validateCreateActorEgressPolicyRequest(ctx context.Context, req *ateapipb.CreateActorEgressPolicyRequest) field.ErrorList {
errs := Validate_CreateActorEgressPolicyRequest(ctx, operation.Operation{Type: operation.Create}, nil, req, nil)
errs = append(errs, validateNoUnknownFields(req.GetEgressPolicy(), field.NewPath("egress_policy"))...)
return errs
}

func validateUpdateActorEgressPolicyRequest(ctx context.Context, req *ateapipb.UpdateActorEgressPolicyRequest) field.ErrorList {
errs := Validate_UpdateActorEgressPolicyRequest(ctx, operation.Operation{Type: operation.Create}, nil, req, nil)
errs = append(errs, validateNoUnknownFields(req.GetEgressPolicy(), field.NewPath("egress_policy"))...)
return errs
}

func ValidateCustom_CreateActorEgressPolicyRequest(_ context.Context, _ operation.Operation, p *field.Path, req, _ *ateapipb.CreateActorEgressPolicyRequest) field.ErrorList {
return validateEgressPolicyParentAtespace(req.GetActor(), req.GetEgressPolicy(), p)
}

func ValidateCustom_UpdateActorEgressPolicyRequest(_ context.Context, _ operation.Operation, p *field.Path, req, _ *ateapipb.UpdateActorEgressPolicyRequest) field.ErrorList {
return validateEgressPolicyParentAtespace(req.GetActor(), req.GetEgressPolicy(), p)
}

func validateEgressPolicyParentAtespace(actor *ateapipb.ObjectRef, policy *ateapipb.EgressPolicy, p *field.Path) field.ErrorList {
if actor == nil || policy.GetMetadata() == nil || actor.GetAtespace() == "" || policy.GetMetadata().GetAtespace() == "" || actor.GetAtespace() == policy.GetMetadata().GetAtespace() {
return nil
}
return field.ErrorList{field.Invalid(p.Child("egress_policy", "metadata", "atespace"), policy.GetMetadata().GetAtespace(), "must match actor.atespace")}
}

func ValidateCustom_EgressPolicy(_ context.Context, _ operation.Operation, root *field.Path, policy, _ *ateapipb.EgressPolicy) field.ErrorList {
var errs field.ErrorList
if name := policy.GetMetadata().GetName(); name != "" && name != "default" {
errs = append(errs, field.Invalid(root.Child("metadata", "name"), name, `must be "default"`))
}
seenHeaders := map[string]bool{}
for i, rule := range policy.GetRules() {
rulePath := root.Child("rules").Index(i)
if rule == nil {
continue
}
seenMatches := map[string]bool{}
onlyExactHostnames := len(rule.GetAllow()) > 0
for j, match := range rule.GetAllow() {
matchPath := rulePath.Child("allow").Index(j)
key, exactHostname := egressMatchKey(match)
onlyExactHostnames = onlyExactHostnames && exactHostname
if key != "" && seenMatches[key] {
errs = append(errs, field.Duplicate(matchPath, key))
}
seenMatches[key] = key != ""
}
effects := rule.GetEffects()
if effects == nil {
continue
}
if (len(effects.GetInjectStaticHeader()) > 0 || effects.GetInjectActorJwt() != nil) && !onlyExactHostnames {
errs = append(errs, field.Invalid(rulePath.Child("effects"), effects, "credential-bearing effects require only exact hostname predicates"))
}
for j, injection := range effects.GetInjectStaticHeader() {
p := rulePath.Child("effects", "inject_static_header").Index(j)
if injection == nil {
continue
}
errs = append(errs, recordInjectionHeader(injection.GetHeader(), p.Child("header"), seenHeaders)...)
}
if injection := effects.GetInjectActorJwt(); injection != nil {
p := rulePath.Child("effects", "inject_actor_jwt")
errs = append(errs, recordInjectionHeader(injection.GetHeader(), p.Child("header"), seenHeaders)...)
}
}
return errs
}

func egressMatchKey(match *ateapipb.EgressMatch) (string, bool) {
if match == nil {
return "", false
}
if match.GetAll() != nil {
return "all", false
}
if match.GetHostname() != nil {
normalized := strings.ToLower(strings.TrimSuffix(match.GetHostname().GetPattern(), "."))
return "hostname:" + normalized, normalized != "" && !strings.HasPrefix(normalized, "*.")
}
if match.GetIpBlock() != nil {
return "ip:" + match.GetIpBlock().GetCidr(), false
}
return "", false
}

func ValidateCustom_HostnameMatch(_ context.Context, _ operation.Operation, p *field.Path, match, _ *ateapipb.HostnameMatch) field.ErrorList {
_, _, errs := validateHostnameMatch(match, p)
return errs
}

func ValidateCustom_IPBlockMatch(_ context.Context, _ operation.Operation, p *field.Path, match, _ *ateapipb.IPBlockMatch) field.ErrorList {
cidr := match.GetCidr()
prefix, err := netip.ParsePrefix(cidr)
if err != nil || prefix.Masked().String() != cidr {
return field.ErrorList{field.Invalid(p.Child("cidr"), cidr, "must be a canonical IPv4 or IPv6 prefix")}
}
return nil
}

func validateHostnameMatch(match *ateapipb.HostnameMatch, p *field.Path) (string, bool, field.ErrorList) {
if match == nil {
return "", false, field.ErrorList{field.Required(p, "")}
}
raw := match.GetPattern()
normalized := strings.ToLower(strings.TrimSuffix(raw, "."))
wildcard := strings.HasPrefix(normalized, "*.")
name := strings.TrimPrefix(normalized, "*.")
invalid := raw == "" || strings.HasSuffix(raw, "..") || (strings.Contains(normalized, "*") && !wildcard) || len(validation.IsDNS1123Subdomain(name)) != 0
if _, err := netip.ParseAddr(name); err == nil {
invalid = true
}
if invalid {
return normalized, wildcard, field.ErrorList{field.Invalid(p.Child("pattern"), raw, "must be an exact ASCII DNS hostname or complete leftmost-label wildcard")}
}
return normalized, wildcard, nil
}

func validateStaticHeaderInjection(injection *ateapipb.StaticHeaderInjection, p *field.Path) field.ErrorList {
if injection == nil {
return field.ErrorList{field.Required(p, "")}
}
var errs field.ErrorList
if !validHeaderName(injection.GetHeader()) {
errs = append(errs, field.Invalid(p.Child("header"), injection.GetHeader(), "must be an HTTP header name"))
}
if !validHeaderValue(injection.GetPrefix()) {
errs = append(errs, field.Invalid(p.Child("prefix"), injection.GetPrefix(), "must not contain CR, LF, or NUL"))
}
if !validCredentialURI(injection.GetCredentialUri()) {
errs = append(errs, field.Invalid(p.Child("credential_uri"), injection.GetCredentialUri(), "must be substrate-secret://<provider-class>/<provider-name>/<provider-specific-tail>"))
}
return errs
}

func ValidateCustom_StaticHeaderInjection(_ context.Context, _ operation.Operation, p *field.Path, injection, _ *ateapipb.StaticHeaderInjection) field.ErrorList {
return validateStaticHeaderInjection(injection, p)
}

func validateActorTokenInjection(injection *ateapipb.ActorTokenInjection, p *field.Path) field.ErrorList {
var errs field.ErrorList
if !validHeaderName(injection.GetHeader()) {
errs = append(errs, field.Invalid(p.Child("header"), injection.GetHeader(), "must be an HTTP header name"))
}
if exchange := injection.GetRfc_8693Exchange(); exchange != nil {
u, err := url.Parse(exchange.GetUrl())
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Fragment != "" {
errs = append(errs, field.Invalid(p.Child("rfc_8693_exchange", "url"), exchange.GetUrl(), "must be an HTTPS URL without user information or a fragment"))
}
}
return errs
}

func ValidateCustom_ActorTokenInjection(_ context.Context, _ operation.Operation, p *field.Path, injection, _ *ateapipb.ActorTokenInjection) field.ErrorList {
return validateActorTokenInjection(injection, p)
}

func recordInjectionHeader(header string, p *field.Path, seen map[string]bool) field.ErrorList {
normalized := strings.ToLower(header)
if normalized == "" || !validHeaderName(normalized) {
return nil
}
if seen[normalized] {
return field.ErrorList{field.Duplicate(p, header)}
}
seen[normalized] = true
return nil
}

func validCredentialURI(raw string) bool {
u, err := url.Parse(raw)
if err != nil || u.Scheme != "substrate-secret" || u.Host == "" || u.Host != u.Hostname() || u.User != nil || u.RawQuery != "" || u.Fragment != "" || len(validation.IsDNS1123Subdomain(u.Host)) != 0 {
return false
}
escapedPath := u.EscapedPath()
if !strings.HasPrefix(escapedPath, "/") || strings.HasSuffix(escapedPath, "/") {
return false
}
parts := strings.Split(strings.TrimPrefix(escapedPath, "/"), "/")
if len(parts) < 2 {
return false
}
for _, part := range parts {
if part == "" {
return false
}
}
return true
}

func validHeaderName(value string) bool {
if value == "" {
return false
}
for _, c := range []byte(value) {
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || strings.ContainsRune("!#$%&'*+-.^_`|~", rune(c))) {
return false
}
}
return true
}

func validHeaderValue(value string) bool {
return !strings.ContainsAny(value, "\r\n\x00")
}

func normalizeEgressPolicy(policy *ateapipb.EgressPolicy) *ateapipb.EgressPolicy {
result := proto.Clone(policy).(*ateapipb.EgressPolicy)
for _, rule := range result.GetRules() {
for _, match := range rule.GetAllow() {
if hostname := match.GetHostname(); hostname != nil {
hostname.Pattern = strings.ToLower(strings.TrimSuffix(hostname.GetPattern(), "."))
}
}
for _, injection := range rule.GetEffects().GetInjectStaticHeader() {
injection.Header = strings.ToLower(injection.GetHeader())
}
if injection := rule.GetEffects().GetInjectActorJwt(); injection != nil {
injection.Header = strings.ToLower(injection.GetHeader())
}
}
return result
}

func mapEgressPolicyWrite(policy *ateapipb.EgressPolicy, err error) (*ateapipb.EgressPolicy, error) {
switch {
case err == nil:
return policy, nil
case errors.Is(err, store.ErrNotFound):
return nil, status.Error(codes.NotFound, "EgressPolicy not found")
case errors.Is(err, store.ErrAlreadyExists):
return nil, status.Error(codes.AlreadyExists, "EgressPolicy already exists")
case errors.Is(err, store.ErrVersionConflict):
return nil, status.Error(codes.Aborted, "EgressPolicy version conflict")
case errors.Is(err, store.ErrUIDConflict):
return nil, status.Error(codes.Aborted, "EgressPolicy UID conflict")
case errors.Is(err, store.ErrPreconditionRequired):
return nil, status.Error(codes.InvalidArgument, "EgressPolicy UID and version are required")
case errors.Is(err, store.ErrFailedPrecondition):
return nil, status.Error(codes.FailedPrecondition, "parent Actor does not exist")
default:
return nil, fmt.Errorf("while writing EgressPolicy: %w", err)
}
}
Loading