Skip to content

Controller fails open in two places: a failed custom ActorTemplate falls back to the default template, and any secret-lookup error falls back to the server-wide API key #476

Closed

Description

@danofairanks

Version: main at 0cbfc3d (#469). Found while reading the controller; reproduced with a self-contained test against the in-process mock Substrate pattern already used in reconciler_test.go.

I hit two paths in internal/controller/reconciler.go where an error is turned into a different, less specific configuration with no error and no status condition. Both are small to fix. The other failure paths in Reconcile (atespace creation, actor creation, resume) set Phase=Failed and a condition; these two don't.

1. Custom ActorTemplate creation failure falls back to the default template

reconciler.go:177:

tmpl, err := r.client.EnsureActorTemplateWithImage(...)
if err != nil {
    slog.Warn("could not create custom ActorTemplate, falling back to default template", "error", err)
} else if tmpl != nil && tmpl.Metadata != nil { ... }

The custom template carries the task's image and the environment built in the lines above: task env, GEMINI_API_KEY, AX_TASK_YAML, AX_WORKSPACES_YAML. If creation fails (for example PermissionDenied, quota, a transient Substrate error), the actor is created from the default template instead, and Reconcile returns nil.

Observed (test below): with CreateActorTemplate returning PermissionDenied:

reconcile err=<nil> phase="Running" actor_template="default-template" (task asked image="registry.example/custom:1")
condition WorkspaceReady=False reason=Initializing
condition Ready=False reason=WorkspaceInitializing

Control (template creation succeeds): actor_template="t1-tmpl-971c4dad". Nothing in the task status records that the actor is running a different template than the task asked for. The default template has none of the task's image, env or workspace specs, and cmd/ax-task-runner/main.go:84 says missing AX_TASK_YAML / AX_WORKSPACES_YAML is "not an error". So I expect the runner to start with an empty configuration, but I have not run that end to end.

2. Any secret-lookup error falls back to the server's own GEMINI_API_KEY

reconciler.go:353-366 (lookupGeminiKey): the resolver is asked for gemini-api-secret in the task's atespace; on any error or empty value (403, timeout, not found) the code takes os.Getenv("GEMINI_API_KEY") from the ax-server process and the result is injected into the task's ActorTemplate env (reconciler.go:153-155). The only record is slog.Info("resolved GEMINI_API_KEY from server environment ...").

Observed (test below): atespace tenant-b, resolver returns a 403, server env GEMINI_API_KEY set:

err=<nil> server-wide key injected into tenant's ActorTemplate env=true

If the intent is "use the server key when the atespace has no secret of its own", that's reasonable, but the same branch also triggers when the lookup failed for a reason unrelated to absence (RBAC misconfiguration, API timeout). The effect is that a per-atespace credential is silently replaced by a shared one and the task runs with it.

Suggested direction (not tested)

  1. For the template path, treat the error like the neighbouring paths: set Phase=Failed and a condition such as ActorTemplateFailed, and return the error. If the fallback is intentional, record it in a condition so ax get task shows which template the actor uses.
  2. For the key path, fall back to the server key only when the resolver reports the secret does not exist (a typed not-found), log other errors at Warn with the atespace and error, and consider surfacing the source (atespace secret vs server env) in a condition.

I'm happy to send a patch with tests if you tell me which behaviour you want.

Repro

internal/controller/zz_probe_test.go (self-contained; it defines its own mock Control server; run with go test ./internal/controller -run TestProbe -v):

zz_probe_test.go
package controller_test

import (
	"context"
	"fmt"
	"net"
	"os"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/agent-substrate/substrate/pkg/proto/ateapipb"
	"github.com/google/ax/internal/controller"
	"github.com/google/ax/internal/substrate"
	"github.com/google/ax/pkg/apis/v1alpha1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/encoding/prototext"
)

type probeSrv struct {
	ateapipb.UnimplementedControlServer
	mu           sync.Mutex
	failTemplate bool
	templates    map[string]string // name -> prototext
	actorTmpl    map[string]string // actor -> template name
}

func (p *probeSrv) GetActorTemplate(_ context.Context, req *ateapipb.GetActorTemplateRequest) (*ateapipb.ActorTemplate, error) {
	p.mu.Lock(); defer p.mu.Unlock()
	n := req.GetActorTemplate().GetName()
	if _, ok := p.templates[n]; ok {
		return &ateapipb.ActorTemplate{Metadata: &ateapipb.ResourceMetadata{Name: n, Atespace: req.GetActorTemplate().GetAtespace()}}, nil
	}
	return nil, status.Error(codes.NotFound, "nf")
}
func (p *probeSrv) CreateActorTemplate(_ context.Context, req *ateapipb.CreateActorTemplateRequest) (*ateapipb.ActorTemplate, error) {
	p.mu.Lock(); defer p.mu.Unlock()
	if p.failTemplate {
		return nil, status.Error(codes.PermissionDenied, "quota exceeded / denied")
	}
	t := req.GetActorTemplate()
	p.templates[t.GetMetadata().GetName()] = prototext.Format(t)
	return t, nil
}
func (p *probeSrv) CreateAtespace(_ context.Context, req *ateapipb.CreateAtespaceRequest) (*ateapipb.Atespace, error) {
	return &ateapipb.Atespace{Metadata: &ateapipb.ResourceMetadata{Name: req.GetAtespace().GetMetadata().GetName()}}, nil
}
func (p *probeSrv) CreateActor(_ context.Context, req *ateapipb.CreateActorRequest) (*ateapipb.Actor, error) {
	p.mu.Lock(); defer p.mu.Unlock()
	p.actorTmpl[req.GetActor().GetMetadata().GetName()] = req.GetActor().GetActorTemplate().GetName()
	return &ateapipb.Actor{Metadata: req.GetActor().GetMetadata(), Status: &ateapipb.ActorStatus{State: ateapipb.ActorState_ACTOR_STATE_SUSPENDED}}, nil
}
func (p *probeSrv) ResumeActor(_ context.Context, req *ateapipb.ResumeActorRequest) (*ateapipb.ResumeActorResponse, error) {
	return &ateapipb.ResumeActorResponse{Resumed: true, Actor: &ateapipb.Actor{Metadata: &ateapipb.ResourceMetadata{Name: req.GetActor().GetName()},
		Status: &ateapipb.ActorStatus{State: ateapipb.ActorState_ACTOR_STATE_RUNNING, WorkerAssignment: &ateapipb.WorkerAssignment{WorkerPod: "w", WorkerPodIps: []string{"127.0.0.1:1"}}}}}, nil
}
func (p *probeSrv) SuspendActor(context.Context, *ateapipb.SuspendActorRequest) (*ateapipb.SuspendActorResponse, error) {
	return &ateapipb.SuspendActorResponse{}, nil
}
func (p *probeSrv) GetActor(_ context.Context, req *ateapipb.GetActorRequest) (*ateapipb.Actor, error) {
	return nil, status.Error(codes.NotFound, "nf")
}

func probeRun(t *testing.T, failTemplate bool, resolver controller.SecretResolver, atespace string) (*probeSrv, *v1alpha1.Task, error) {
	lis, _ := net.Listen("tcp", "127.0.0.1:0")
	p := &probeSrv{failTemplate: failTemplate, templates: map[string]string{}, actorTmpl: map[string]string{}}
	gs := grpc.NewServer(); ateapipb.RegisterControlServer(gs, p); go gs.Serve(lis); t.Cleanup(gs.Stop)
	c, err := substrate.NewClient(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil { t.Fatal(err) }
	t.Cleanup(func() { c.Close() })
	r := controller.NewTaskReconciler(c, "default-template", v1alpha1.DefaultSystemNamespace)
	r.SecretResolver = resolver
	r.WorkspaceReadyTimeout = 150 * time.Millisecond
	task := &v1alpha1.Task{ApiVersion: v1alpha1.APIVersion, Kind: v1alpha1.KindTask,
		Metadata: &v1alpha1.ObjectMeta{Name: "t1", Atespace: atespace},
		Spec: &v1alpha1.TaskSpec{Image: "registry.example/custom:1", Command: []string{"/bin/agent", "--goal", "x"},
			Env: []*v1alpha1.EnvVar{{Name: "CUSTOM", Value: "v"}}},
		Status: &v1alpha1.TaskStatus{Phase: "Running"}}
	out, err := r.Reconcile(context.Background(), task)
	return p, out, err
}

func TestProbeTemplateFallback(t *testing.T) {
	noSec := func(context.Context, string, string, string) (string, error) { return "", nil }
	p, out, err := probeRun(t, true, noSec, "default")
	fmt.Printf("P1 template create FAILS (PermissionDenied): reconcile err=%v phase=%q actor_template=%q (task asked image=%q)\n", err, out.GetStatus().GetPhase(), p.actorTmpl["t1"], "registry.example/custom:1")
	for _, c := range out.GetStatus().GetConditions() { fmt.Printf("   condition %s=%s reason=%s msg=%q\n", c.Type, c.Status, c.Reason, c.Message) }
	p2, out2, err2 := probeRun(t, false, noSec, "default")
	fmt.Printf("P1 control (template ok): err=%v phase=%q actor_template=%q\n", err2, out2.GetStatus().GetPhase(), p2.actorTmpl["t1"])
}

func TestProbeServerKeyFallback(t *testing.T) {
	os.Setenv("GEMINI_API_KEY", "SERVER-WIDE-KEY-123")
	defer os.Unsetenv("GEMINI_API_KEY")
	fail := func(context.Context, string, string, string) (string, error) { return "", fmt.Errorf("403 forbidden: serviceaccount cannot get secrets in namespace") }
	p, _, err := probeRun(t, false, fail, "tenant-b")
	found := false
	for _, v := range p.templates { if strings.Contains(v, "SERVER-WIDE-KEY-123") { found = true } }
	fmt.Printf("P2 tenant atespace=tenant-b, secret lookup returns 403, server env GEMINI_API_KEY set: err=%v server-wide key injected into tenant's ActorTemplate env=%v\n", err, found)
}

Activity

  1. added
    devx
    on Oct 15, 2026
  2. self-assigned this
    on Oct 23, 2026
  3. added a commit that references this issue on Oct 27, 2026
    785b592
  4. added a commit that references this issue on Oct 27, 2026
    33884fa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

devx

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions