fix(agent): fail-closed profile secret resolution + preserve user-modified profiles (#2839)
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
@@ -32,16 +32,16 @@ func (m *Manager) SetExecutorProfileReader(reader ExecutorProfileReader) {
|
||||
// launch request), so a user shell terminal opened on the workspace sees the
|
||||
// same tokens the agent and the repository setup script do.
|
||||
//
|
||||
// Resolution is best-effort: a missing reader, session, environment, profile, or
|
||||
// secret yields the entries that could be resolved rather than failing the
|
||||
// terminal.
|
||||
func (m *Manager) ExecutorProfileEnvForSession(ctx context.Context, sessionID, taskEnvironmentID string) map[string]string {
|
||||
// Resolution is best-effort for missing profile records. A secret failure is
|
||||
// returned so the terminal caller can fail closed instead of starting a shell
|
||||
// with an incomplete profile environment.
|
||||
func (m *Manager) ExecutorProfileEnvForSession(ctx context.Context, sessionID, taskEnvironmentID string) (map[string]string, error) {
|
||||
if m.executorProfileReader == nil {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
profileID := m.terminalExecutorProfileID(ctx, sessionID, taskEnvironmentID)
|
||||
if profileID == "" {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
profile, err := m.executorProfileReader.GetExecutorProfile(ctx, profileID)
|
||||
if err != nil {
|
||||
@@ -50,14 +50,22 @@ func (m *Manager) ExecutorProfileEnvForSession(ctx context.Context, sessionID, t
|
||||
zap.String("task_environment_id", taskEnvironmentID),
|
||||
zap.String("executor_profile_id", profileID),
|
||||
zap.Error(err))
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
if profile == nil || len(profile.EnvVars) == 0 {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
// ExecutorProfile.EnvVars and agent-profile env vars are the same type, so
|
||||
// the secret-revealing resolver is shared.
|
||||
return m.resolveAgentProfileEnvVars(ctx, profile.EnvVars)
|
||||
resolved, err := m.resolveAgentProfileEnvVars(ctx, profile.EnvVars)
|
||||
if err != nil {
|
||||
m.logger.Warn("failed to resolve executor profile environment for terminal",
|
||||
zap.String("session_id", sessionID),
|
||||
zap.String("executor_profile_id", profileID),
|
||||
zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
// terminalExecutorProfileID picks the executor profile the terminal should
|
||||
|
||||
@@ -76,7 +76,10 @@ func TestExecutorProfileEnvForSession_ResolvesValuesAndSecrets(t *testing.T) {
|
||||
}
|
||||
m := newExecutorProfileEnvManager(t, reader)
|
||||
|
||||
got := m.ExecutorProfileEnvForSession(context.Background(), "session-1", "env-1")
|
||||
got, err := m.ExecutorProfileEnvForSession(context.Background(), "session-1", "env-1")
|
||||
if err != nil {
|
||||
t.Fatalf("ExecutorProfileEnvForSession: %v", err)
|
||||
}
|
||||
|
||||
if got["PLAIN"] != "plain-value" {
|
||||
t.Fatalf("PLAIN = %q, want literal profile value", got["PLAIN"])
|
||||
@@ -101,7 +104,10 @@ func TestExecutorProfileEnvForSession_PrefersSessionProfileOverStaleEnvironmentR
|
||||
}
|
||||
m := newExecutorProfileEnvManager(t, reader)
|
||||
|
||||
got := m.ExecutorProfileEnvForSession(context.Background(), "session-2", "env-1")
|
||||
got, err := m.ExecutorProfileEnvForSession(context.Background(), "session-2", "env-1")
|
||||
if err != nil {
|
||||
t.Fatalf("ExecutorProfileEnvForSession: %v", err)
|
||||
}
|
||||
|
||||
if got["TOKEN"] != "current" {
|
||||
t.Fatalf("TOKEN = %q, want the session's profile value, not the stale environment row", got["TOKEN"])
|
||||
@@ -144,7 +150,10 @@ func TestExecutorProfileEnvForSession_FallsBackToEnvironmentRow(t *testing.T) {
|
||||
}
|
||||
m := newExecutorProfileEnvManager(t, tt.reader)
|
||||
|
||||
got := m.ExecutorProfileEnvForSession(context.Background(), tt.sessionID, "env-1")
|
||||
got, err := m.ExecutorProfileEnvForSession(context.Background(), tt.sessionID, "env-1")
|
||||
if err != nil {
|
||||
t.Fatalf("ExecutorProfileEnvForSession: %v", err)
|
||||
}
|
||||
|
||||
if got["TOKEN"] != "from-env-row" {
|
||||
t.Fatalf("TOKEN = %q, want environment-row fallback", got["TOKEN"])
|
||||
@@ -192,9 +201,33 @@ func TestExecutorProfileEnvForSession_EmptyCases(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
m := newExecutorProfileEnvManager(t, tt.reader)
|
||||
if got := m.ExecutorProfileEnvForSession(context.Background(), "", tt.envID); len(got) != 0 {
|
||||
if got, err := m.ExecutorProfileEnvForSession(context.Background(), "", tt.envID); err != nil {
|
||||
t.Fatalf("ExecutorProfileEnvForSession error = %v, want nil", err)
|
||||
} else if len(got) != 0 {
|
||||
t.Fatalf("got %#v, want empty", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorProfileEnvForSessionReturnsSecretFailure(t *testing.T) {
|
||||
reader := &fakeExecutorProfileReader{
|
||||
env: &models.TaskEnvironment{ID: "env-1", ExecutorProfileID: "prof-1"},
|
||||
profiles: map[string]*models.ExecutorProfile{
|
||||
"prof-1": {
|
||||
ID: "prof-1",
|
||||
EnvVars: []models.ProfileEnvVar{{Key: "TOKEN", SecretID: "deleted-secret"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
m := newExecutorProfileEnvManager(t, reader)
|
||||
|
||||
got, err := m.ExecutorProfileEnvForSession(context.Background(), "", "env-1")
|
||||
|
||||
if !errors.Is(err, ErrProfileSecretUnavailable) {
|
||||
t.Fatalf("error = %v, want ErrProfileSecretUnavailable", err)
|
||||
}
|
||||
if got != nil {
|
||||
t.Fatalf("environment = %#v, want nil on secret failure", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,9 @@ import (
|
||||
|
||||
// inMemorySecretStore implements secrets.SecretStore for testing.
|
||||
type inMemorySecretStore struct {
|
||||
store map[string]*secrets.SecretWithValue
|
||||
err error
|
||||
store map[string]*secrets.SecretWithValue
|
||||
err error
|
||||
revealErr error
|
||||
}
|
||||
|
||||
var _ secrets.SecretStore = (*inMemorySecretStore)(nil)
|
||||
@@ -45,6 +46,9 @@ func (s *inMemorySecretStore) Get(_ context.Context, id string) (*secrets.Secret
|
||||
|
||||
// Reveal returns the plaintext value for the given ID, or an error when absent.
|
||||
func (s *inMemorySecretStore) Reveal(_ context.Context, id string) (string, error) {
|
||||
if s.revealErr != nil {
|
||||
return "", s.revealErr
|
||||
}
|
||||
if sw, ok := s.store[id]; ok {
|
||||
return sw.Value, nil
|
||||
}
|
||||
|
||||
@@ -818,13 +818,6 @@ func (m *Manager) initializeCreatedExecution(
|
||||
// observe a half-initialised resume intent.
|
||||
applyResumeIntent(execution, preparation.request)
|
||||
|
||||
// Cache only agent-profile values for the best-effort configure fallback.
|
||||
// The effective runtime snapshot (including repository secrets) is already
|
||||
// captured by ToAgentExecution and must not be mislabeled as profile data.
|
||||
if preparation.profileInfo != nil && len(preparation.profileInfo.EnvVars) > 0 {
|
||||
m.cacheResolvedProfileEnv(execution, m.resolveAgentProfileEnvVars(ctx, preparation.profileInfo.EnvVars))
|
||||
}
|
||||
|
||||
if info.ACPSessionID != "" {
|
||||
execution.ACPSessionID = info.ACPSessionID
|
||||
}
|
||||
|
||||
@@ -1358,9 +1358,6 @@ func (m *Manager) launchInternal(ctx context.Context, req *LaunchRequest) (*Agen
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if profileInfo != nil && len(profileInfo.EnvVars) > 0 {
|
||||
m.cacheResolvedProfileEnv(execution, m.resolveAgentProfileEnvVars(ctx, profileInfo.EnvVars))
|
||||
}
|
||||
if !reqWithWorktree.IsPassthrough {
|
||||
if err := m.materializeRuntimeProjectMCP(ctx, execution, agentConfig); err != nil {
|
||||
m.rollbackLaunchExecution(ctx, rt, execInstance, execution, "project MCP materialization failed")
|
||||
@@ -1834,8 +1831,21 @@ func getAttachmentsFromMetadata(execution *AgentExecution) []MessageAttachment {
|
||||
// configureAndStartAgent configures the agent command and starts the agent subprocess.
|
||||
// Returns the effective boot command (full command with adapter args, or base command).
|
||||
func (m *Manager) configureAndStartAgent(ctx context.Context, execution *AgentExecution, approvalPolicy string) (string, error) {
|
||||
env := runtimeEnvFromMetadata(execution.MetadataSnapshot())
|
||||
m.mergeAgentProfileEnvForExecution(ctx, execution, env)
|
||||
env := execution.RuntimeEnvironment()
|
||||
metadataEnv := runtimeEnvFromMetadata(execution.MetadataSnapshot())
|
||||
if env == nil {
|
||||
env = metadataEnv
|
||||
if err := m.mergeAgentProfileEnvForExecution(ctx, execution, env); err != nil {
|
||||
m.updateExecutionError(execution.ID, "failed to resolve agent profile environment: "+err.Error())
|
||||
return "", fmt.Errorf("resolve agent profile environment: %w", err)
|
||||
}
|
||||
} else {
|
||||
// SetExecutionEnv carries per-run values such as repository credentials.
|
||||
// Overlay them on the launch snapshot without re-reading profile secrets.
|
||||
for key, value := range metadataEnv {
|
||||
env[key] = value
|
||||
}
|
||||
}
|
||||
if err := spillLargeWakePayloadEnv(env, execution.WorkspacePath, m.logger.Zap()); err != nil {
|
||||
m.updateExecutionError(execution.ID, "failed to prepare agent env: "+err.Error())
|
||||
return "", fmt.Errorf("failed to prepare agent env: %w", err)
|
||||
|
||||
@@ -491,6 +491,25 @@ func TestBuildEnvForExecution_ResolvesSecretBackedProfileEnv(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildEnvForExecution_FailsClosedWhenProfileSecretIsUnavailable(t *testing.T) {
|
||||
mgr := newTestManager(t)
|
||||
mgr.secretStore = newInMemorySecretStore()
|
||||
|
||||
_, err := mgr.buildEnvForExecution(
|
||||
context.Background(),
|
||||
"exec-1",
|
||||
&LaunchRequest{AgentProfileID: "profile-1"},
|
||||
nil,
|
||||
&AgentProfileInfo{EnvVars: []settingsmodels.ProfileEnvVar{{
|
||||
Key: "PROFILE_TOKEN",
|
||||
SecretID: "missing-secret",
|
||||
}}},
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("buildEnvForExecution succeeded with an unavailable profile secret")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildEnvForExecution_SeparatesOfficeAndExecutionProfiles(t *testing.T) {
|
||||
mgr := newTestManager(t)
|
||||
profileInfo := &AgentProfileInfo{
|
||||
@@ -818,6 +837,32 @@ func TestConfigureAndStartAgent_DoesNotSendTaskDescriptionEnv(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureAndStartAgentUsesRuntimeSnapshotWhenProfileSecretIsUnavailable(t *testing.T) {
|
||||
mgr := newTestManager(t)
|
||||
mgr.profileResolver = &mockPassthroughProfileResolver{
|
||||
envVars: []settingsmodels.ProfileEnvVar{{Key: "PROFILE_ONLY", SecretID: "deleted-secret"}},
|
||||
}
|
||||
var configuredEnv map[string]string
|
||||
client := newConfigureCaptureAgentctlClient(t, newTestLogger(), &configuredEnv)
|
||||
execution := &AgentExecution{
|
||||
ID: "exec-1",
|
||||
TaskID: "task-1",
|
||||
SessionID: "session-1",
|
||||
AgentProfileID: "profile-1",
|
||||
AgentCommand: "npx -y @agentclientprotocol/codex-acp",
|
||||
WorkspacePath: t.TempDir(),
|
||||
agentctl: client,
|
||||
}
|
||||
execution.setRuntimeEnvironment(map[string]string{"PROFILE_ONLY": "captured-value"})
|
||||
|
||||
if _, err := mgr.configureAndStartAgent(context.Background(), execution, "never"); err != nil {
|
||||
t.Fatalf("configureAndStartAgent() error = %v", err)
|
||||
}
|
||||
if configuredEnv["PROFILE_ONLY"] != "captured-value" {
|
||||
t.Fatalf("configured profile env = %q, want captured runtime value", configuredEnv["PROFILE_ONLY"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureAndStartAgent_SendsStructuredArgv(t *testing.T) {
|
||||
mgr := newTestManager(t)
|
||||
var captured []string
|
||||
|
||||
@@ -141,8 +141,9 @@ func (m *Manager) GetPassthroughBuffer(ctx context.Context, sessionID string) (s
|
||||
|
||||
// buildPassthroughEnv builds the environment map for a passthrough session,
|
||||
// including Kandev metadata and required credentials from the agent runtime config.
|
||||
func (m *Manager) buildPassthroughEnv(ctx context.Context, execution *AgentExecution, requiredEnv []string) map[string]string {
|
||||
func (m *Manager) buildPassthroughEnv(ctx context.Context, execution *AgentExecution, requiredEnv []string) (map[string]string, error) {
|
||||
env := execution.RuntimeEnvironment()
|
||||
hasRuntimeSnapshot := env != nil
|
||||
if env == nil {
|
||||
env = make(map[string]string)
|
||||
}
|
||||
@@ -150,7 +151,11 @@ func (m *Manager) buildPassthroughEnv(ctx context.Context, execution *AgentExecu
|
||||
env["KANDEV_SESSION_ID"] = execution.SessionID
|
||||
env["KANDEV_AGENT_PROFILE_ID"] = execution.officeProfileID()
|
||||
env["KANDEV_EXECUTION_PROFILE_ID"] = execution.AgentProfileID
|
||||
m.mergeAgentProfileEnv(ctx, execution.AgentProfileID, env)
|
||||
if !hasRuntimeSnapshot {
|
||||
if err := m.mergeAgentProfileEnvForExecution(ctx, execution, env); err != nil {
|
||||
return nil, fmt.Errorf("resolve passthrough profile environment: %w", err)
|
||||
}
|
||||
}
|
||||
if m.credsMgr != nil {
|
||||
for _, credKey := range requiredEnv {
|
||||
if value, err := m.credsMgr.GetCredentialValue(ctx, credKey); err == nil && value != "" {
|
||||
@@ -163,7 +168,7 @@ func (m *Manager) buildPassthroughEnv(ctx context.Context, execution *AgentExecu
|
||||
for key, value := range getPassthroughMCPEnv(execution) {
|
||||
env[key] = value
|
||||
}
|
||||
return env
|
||||
return env, nil
|
||||
}
|
||||
|
||||
// startPassthroughShell starts the shell session for a passthrough execution.
|
||||
@@ -739,7 +744,10 @@ func (m *Manager) startPassthroughSession(ctx context.Context, execution *AgentE
|
||||
zap.String("session_id", execution.SessionID),
|
||||
zap.Strings("full_command", redactPassthroughArgs(cmd.Args())))
|
||||
|
||||
env := m.buildPassthroughEnv(ctx, execution, rt.RequiredEnv)
|
||||
env, err := m.buildPassthroughEnv(ctx, execution, rt.RequiredEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
processInfo, err := m.startInteractiveProcess(ctx, execution, pt, env, cmd, rt.StripEnv)
|
||||
if err != nil {
|
||||
@@ -865,14 +873,26 @@ func (m *Manager) restartPassthroughProcess(ctx context.Context, execution *Agen
|
||||
zap.String("session_id", execution.SessionID),
|
||||
zap.String("old_process_id", execution.PassthroughProcessID))
|
||||
|
||||
// 1. Stop the current PTY process.
|
||||
// Clear PassthroughProcessID before stopping so that handlePassthroughStatus
|
||||
// doesn't trigger auto-restart for the deliberately-killed process.
|
||||
// 1. Resolve the replacement command and environment before touching the
|
||||
// current PTY. A profile-secret failure must leave the active session usable.
|
||||
interactiveRunner := m.GetInteractiveRunner()
|
||||
if interactiveRunner == nil {
|
||||
return fmt.Errorf("interactive runner not available")
|
||||
}
|
||||
|
||||
// Build fresh command (no SessionID, no Resume, no Prompt).
|
||||
pt, rt, cmd, err := m.freshPassthroughCommand(ctx, execution)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
env, err := m.buildPassthroughEnv(ctx, execution, rt.RequiredEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. Stop the current PTY process. Clear PassthroughProcessID before
|
||||
// stopping so handlePassthroughStatus does not trigger auto-restart for
|
||||
// the deliberately-killed process.
|
||||
oldProcessID := execution.PassthroughProcessID
|
||||
execution.PassthroughProcessID = ""
|
||||
execution.PassthroughStartedAt = time.Time{}
|
||||
@@ -884,14 +904,7 @@ func (m *Manager) restartPassthroughProcess(ctx context.Context, execution *Agen
|
||||
zap.Error(err))
|
||||
}
|
||||
|
||||
// 2. Build fresh command (no SessionID, no Resume, no Prompt)
|
||||
pt, rt, cmd, err := m.freshPassthroughCommand(ctx, execution)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. Start new PTY process with ImmediateStart (terminal is already connected)
|
||||
env := m.buildPassthroughEnv(ctx, execution, rt.RequiredEnv)
|
||||
startReq := buildInteractiveStartRequest(execution.SessionID, execution, pt, env, cmd, rt.StripEnv, true)
|
||||
|
||||
processInfo, err := interactiveRunner.Start(ctx, startReq)
|
||||
@@ -982,7 +995,10 @@ func (m *Manager) resumePassthroughSession(ctx context.Context, sessionID, expec
|
||||
zap.Bool("use_resume", useResume),
|
||||
zap.Strings("command", redactPassthroughArgs(cmd.Args())))
|
||||
|
||||
env := m.buildPassthroughEnv(ctx, execution, resolved.rt.RequiredEnv)
|
||||
env, err := m.buildPassthroughEnv(ctx, execution, resolved.rt.RequiredEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Always use immediate start on resume — the terminal WebSocket is already connected,
|
||||
// so we don't need to wait for a resize to get exact dimensions. The first resize
|
||||
@@ -1303,7 +1319,11 @@ func (m *Manager) attemptResumeFallbackForProcess(execution *AgentExecution, run
|
||||
return
|
||||
}
|
||||
|
||||
env := m.buildPassthroughEnv(ctx, execution, rt.RequiredEnv)
|
||||
env, err := m.buildPassthroughEnv(ctx, execution, rt.RequiredEnv)
|
||||
if err != nil {
|
||||
m.notifyFallbackInfrastructureFailure(runner, sessionID, "resolve profile environment", err)
|
||||
return
|
||||
}
|
||||
startReq := buildInteractiveStartRequest(sessionID, execution, pt, env, cmd, rt.StripEnv, true)
|
||||
|
||||
processInfo, err := runner.Start(ctx, startReq)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/executor"
|
||||
settingsmodels "github.com/kandev/kandev/internal/agent/settings/models"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/process"
|
||||
agentctltypes "github.com/kandev/kandev/internal/agentctl/types"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
@@ -173,6 +174,22 @@ func TestRestartPassthroughProcessClearsProcessIDBeforeStopping(t *testing.T) {
|
||||
require.Equal(t, v1.AgentStatusFailed, execution.Status)
|
||||
}
|
||||
|
||||
func TestRestartPassthroughProcessKeepsOldProcessWhenProfileSecretFails(t *testing.T) {
|
||||
mgr, _, execution := newPassthroughRunnerManager(t)
|
||||
mgr.profileResolver = &mockPassthroughProfileResolver{
|
||||
agentName: "claude-acp",
|
||||
cliPassthrough: true,
|
||||
envVars: []settingsmodels.ProfileEnvVar{{Key: "PROFILE_ONLY", SecretID: "deleted-secret"}},
|
||||
}
|
||||
execution.PassthroughProcessID = "pty-old"
|
||||
|
||||
err := mgr.restartPassthroughProcess(context.Background(), execution)
|
||||
|
||||
require.ErrorIs(t, err, ErrProfileSecretUnavailable)
|
||||
require.Equal(t, "pty-old", execution.PassthroughProcessID,
|
||||
"the old process must remain available when replacement preflight fails")
|
||||
}
|
||||
|
||||
func TestRestartPassthroughProcessWithoutRunner(t *testing.T) {
|
||||
mgr, execution, _ := newClaudePassthroughMCPTestManager(t)
|
||||
mgr.executorRegistry = nil
|
||||
|
||||
@@ -64,10 +64,12 @@ func TestBuildPassthroughEnvInjectsRequiredCredentialsAndMCPEnv(t *testing.T) {
|
||||
execution.setRuntimeEnvironment(map[string]string{
|
||||
"ANTHROPIC_BASE_URL": "https://proxy.internal",
|
||||
"HTTPS_PROXY": "http://proxy:3128",
|
||||
"PROFILE_ONLY": "profile-value",
|
||||
})
|
||||
setPassthroughMCPEnv(execution, map[string]string{"OPENCODE_CONFIG": "/tmp/opencode.json"})
|
||||
|
||||
env := mgr.buildPassthroughEnv(context.Background(), execution, []string{"ANTHROPIC_API_KEY", "MISSING_KEY"})
|
||||
env, err := mgr.buildPassthroughEnv(context.Background(), execution, []string{"ANTHROPIC_API_KEY", "MISSING_KEY"})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "https://proxy.internal", env["ANTHROPIC_BASE_URL"],
|
||||
"Agent.Runtime().Env must reach the passthrough subprocess")
|
||||
@@ -87,6 +89,23 @@ func TestBuildPassthroughEnvInjectsRequiredCredentialsAndMCPEnv(t *testing.T) {
|
||||
require.Contains(t, creds.requested, "MISSING_KEY")
|
||||
}
|
||||
|
||||
func TestBuildPassthroughEnvUsesRuntimeSnapshotWhenProfileSecretIsUnavailable(t *testing.T) {
|
||||
mgr := newTestManager(t)
|
||||
mgr.profileResolver = &mockPassthroughProfileResolver{
|
||||
envVars: []settingsmodels.ProfileEnvVar{{Key: "PROFILE_ONLY", SecretID: "deleted-secret"}},
|
||||
}
|
||||
execution := &AgentExecution{
|
||||
TaskID: "task-1",
|
||||
SessionID: "session-1",
|
||||
AgentProfileID: "profile-1",
|
||||
}
|
||||
execution.setRuntimeEnvironment(map[string]string{"PROFILE_ONLY": "captured-value"})
|
||||
|
||||
env, err := mgr.buildPassthroughEnv(context.Background(), execution, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "captured-value", env["PROFILE_ONLY"])
|
||||
}
|
||||
|
||||
func TestMarkPassthroughRunningPublishesOnceAndGuards(t *testing.T) {
|
||||
mgr := newTestManager(t)
|
||||
bus, ok := mgr.eventBus.(*MockEventBus)
|
||||
|
||||
@@ -462,7 +462,10 @@ func TestPassthroughOpenCodeInjectsConfigEnv(t *testing.T) {
|
||||
t.Fatalf("opencode config not written: %v", err)
|
||||
}
|
||||
// OPENCODE_CONFIG must be merged into the passthrough environment.
|
||||
env := mgr.buildPassthroughEnv(context.Background(), execution, nil)
|
||||
env, err := mgr.buildPassthroughEnv(context.Background(), execution, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("buildPassthroughEnv: %v", err)
|
||||
}
|
||||
if env["OPENCODE_CONFIG"] != files[0] {
|
||||
t.Fatalf("OPENCODE_CONFIG = %q, want %q", env["OPENCODE_CONFIG"], files[0])
|
||||
}
|
||||
@@ -1104,12 +1107,15 @@ func TestBuildPassthroughEnv_MergesProfileEnvVars(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
env := mgr.buildPassthroughEnv(context.Background(), &AgentExecution{
|
||||
env, err := mgr.buildPassthroughEnv(context.Background(), &AgentExecution{
|
||||
TaskID: "task-1",
|
||||
SessionID: "session-1",
|
||||
AgentProfileID: "profile-1",
|
||||
OfficeAgentProfileID: "office-cto",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("buildPassthroughEnv: %v", err)
|
||||
}
|
||||
|
||||
if env["PLAIN"] != "plain-value" {
|
||||
t.Fatalf("profile env var missing: %+v", env)
|
||||
@@ -1140,7 +1146,10 @@ func TestBuildPassthroughEnvIncludesEffectiveRuntimeEnv(t *testing.T) {
|
||||
"PATH": "/tmp/kandev-shim:/usr/bin",
|
||||
})
|
||||
|
||||
env := mgr.buildPassthroughEnv(context.Background(), execution, nil)
|
||||
env, err := mgr.buildPassthroughEnv(context.Background(), execution, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("buildPassthroughEnv: %v", err)
|
||||
}
|
||||
for key, want := range map[string]string{
|
||||
"KANDEV_GITHUB_CREDENTIAL_BROKER_URL": "http://127.0.0.1:9876",
|
||||
"GIT_CONFIG_COUNT": "1",
|
||||
|
||||
@@ -319,9 +319,13 @@ func (m *Manager) buildEnvForExecution(ctx context.Context, executionID string,
|
||||
}
|
||||
|
||||
if profileInfo != nil {
|
||||
m.mergeAgentProfileEnvFromInfo(ctx, profileInfo, env)
|
||||
if err := m.mergeAgentProfileEnvFromInfo(ctx, profileInfo, env); err != nil {
|
||||
return nil, fmt.Errorf("resolve agent profile environment: %w", err)
|
||||
}
|
||||
} else {
|
||||
m.mergeAgentProfileEnv(ctx, executionProfileID(req), env)
|
||||
if err := m.mergeAgentProfileEnv(ctx, executionProfileID(req), env); err != nil {
|
||||
return nil, fmt.Errorf("resolve agent profile environment: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Add standard variables for recovery after backend restart
|
||||
|
||||
@@ -2,56 +2,46 @@ package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
settingsmodels "github.com/kandev/kandev/internal/agent/settings/models"
|
||||
"github.com/kandev/kandev/internal/gitconfigenv"
|
||||
)
|
||||
|
||||
// metadataKeyProfileEnvResolved caches resolved profile env vars on an execution
|
||||
// so configureAndStartAgent does not re-resolve secrets on the same launch.
|
||||
const metadataKeyProfileEnvResolved = "profile_env_resolved"
|
||||
var ErrProfileSecretUnavailable = errors.New("BLOCKED_PROFILE_SECRET")
|
||||
|
||||
// mergeAgentProfileEnv fills missing keys in env from the agent profile's
|
||||
// env_vars. Existing keys in env (office tokens, executor profile env, etc.)
|
||||
// are never overwritten.
|
||||
func (m *Manager) mergeAgentProfileEnv(ctx context.Context, profileID string, env map[string]string) {
|
||||
func (m *Manager) mergeAgentProfileEnv(ctx context.Context, profileID string, env map[string]string) error {
|
||||
if profileID == "" || env == nil || m.profileResolver == nil {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
info, err := m.profileResolver.ResolveProfile(ctx, profileID)
|
||||
if err != nil || info == nil {
|
||||
return
|
||||
return err
|
||||
}
|
||||
m.mergeAgentProfileEnvFromInfo(ctx, info, env)
|
||||
return m.mergeAgentProfileEnvFromInfo(ctx, info, env)
|
||||
}
|
||||
|
||||
func (m *Manager) mergeAgentProfileEnvFromInfo(ctx context.Context, info *AgentProfileInfo, env map[string]string) {
|
||||
func (m *Manager) mergeAgentProfileEnvFromInfo(ctx context.Context, info *AgentProfileInfo, env map[string]string) error {
|
||||
if info == nil || env == nil || len(info.EnvVars) == 0 {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
resolved, err := m.resolveAgentProfileEnvVars(ctx, info.EnvVars)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resolved := m.resolveAgentProfileEnvVars(ctx, info.EnvVars)
|
||||
mergeEnvFillMissing(env, resolved)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) cacheResolvedProfileEnv(execution *AgentExecution, resolved map[string]string) {
|
||||
if execution == nil || len(resolved) == 0 {
|
||||
return
|
||||
}
|
||||
execution.setMetadataValue(metadataKeyProfileEnvResolved, cloneStringMap(resolved))
|
||||
}
|
||||
|
||||
func (m *Manager) mergeAgentProfileEnvForExecution(ctx context.Context, execution *AgentExecution, env map[string]string) {
|
||||
func (m *Manager) mergeAgentProfileEnvForExecution(ctx context.Context, execution *AgentExecution, env map[string]string) error {
|
||||
if execution == nil {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
value, _ := execution.metadataValue(metadataKeyProfileEnvResolved)
|
||||
if cached, ok := value.(map[string]string); ok && len(cached) > 0 {
|
||||
mergeEnvFillMissing(env, cached)
|
||||
return
|
||||
}
|
||||
m.mergeAgentProfileEnv(ctx, execution.AgentProfileID, env)
|
||||
return m.mergeAgentProfileEnv(ctx, execution.AgentProfileID, env)
|
||||
}
|
||||
|
||||
func mergeEnvFillMissing(dst, src map[string]string) {
|
||||
@@ -73,12 +63,11 @@ func mergeEnvFillMissing(dst, src map[string]string) {
|
||||
}
|
||||
|
||||
// resolveAgentProfileEnvVars resolves profile env entries. SecretID wins over
|
||||
// Value; if secret resolution fails, the entry is skipped rather than falling
|
||||
// back. Literal Value is used only when SecretID is empty, and empty keys are
|
||||
// ignored.
|
||||
func (m *Manager) resolveAgentProfileEnvVars(ctx context.Context, envVars []settingsmodels.ProfileEnvVar) map[string]string {
|
||||
// Value. A missing secret store or failed reveal aborts the whole profile
|
||||
// environment rather than falling back to a literal value or partial map.
|
||||
func (m *Manager) resolveAgentProfileEnvVars(ctx context.Context, envVars []settingsmodels.ProfileEnvVar) (map[string]string, error) {
|
||||
if len(envVars) == 0 {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
resolved := make(map[string]string, len(envVars))
|
||||
for _, ev := range envVars {
|
||||
@@ -88,16 +77,17 @@ func (m *Manager) resolveAgentProfileEnvVars(ctx context.Context, envVars []sett
|
||||
}
|
||||
if ev.SecretID != "" {
|
||||
if m.secretStore == nil {
|
||||
m.logger.Warn("secret store not configured for profile env var",
|
||||
zap.String("key", key))
|
||||
continue
|
||||
return nil, profileSecretError(key)
|
||||
}
|
||||
value, err := m.revealGlobalSecret(ctx, ev.SecretID)
|
||||
if err != nil {
|
||||
m.logger.Warn("failed to resolve secret for profile env var",
|
||||
zap.String("key", key),
|
||||
zap.Error(err))
|
||||
continue
|
||||
// Preserve caller cancellation identity. The sanitized sentinel is
|
||||
// for secret failures only; callers use context errors to stop work
|
||||
// without misclassifying a cancelled request as bad configuration.
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return nil, err
|
||||
}
|
||||
return nil, profileSecretError(key)
|
||||
}
|
||||
resolved[key] = value
|
||||
continue
|
||||
@@ -106,7 +96,11 @@ func (m *Manager) resolveAgentProfileEnvVars(ctx context.Context, envVars []sett
|
||||
resolved[key] = ev.Value
|
||||
}
|
||||
}
|
||||
return resolved
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
func profileSecretError(key string) error {
|
||||
return fmt.Errorf("%w: env key %q unavailable", ErrProfileSecretUnavailable, key)
|
||||
}
|
||||
|
||||
func (m *Manager) revealGlobalSecret(ctx context.Context, secretID string) (string, error) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
settingsmodels "github.com/kandev/kandev/internal/agent/settings/models"
|
||||
@@ -81,10 +82,13 @@ func TestResolveAgentProfileEnvVars_SecretAndValue(t *testing.T) {
|
||||
|
||||
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
|
||||
m := &Manager{logger: log, secretStore: store}
|
||||
resolved := m.resolveAgentProfileEnvVars(context.Background(), []settingsmodels.ProfileEnvVar{
|
||||
resolved, err := m.resolveAgentProfileEnvVars(context.Background(), []settingsmodels.ProfileEnvVar{
|
||||
{Key: "PLAIN", Value: "plain"},
|
||||
{Key: "FROM_SECRET", SecretID: "sec-1"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("resolveAgentProfileEnvVars: %v", err)
|
||||
}
|
||||
if resolved["PLAIN"] != "plain" {
|
||||
t.Fatalf("PLAIN: got %q", resolved["PLAIN"])
|
||||
}
|
||||
@@ -104,10 +108,44 @@ func TestResolveAgentProfileEnvVars_RejectsWorkspaceSecret(t *testing.T) {
|
||||
|
||||
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
|
||||
m := &Manager{logger: log, secretStore: store}
|
||||
resolved := m.resolveAgentProfileEnvVars(context.Background(), []settingsmodels.ProfileEnvVar{{
|
||||
resolved, err := m.resolveAgentProfileEnvVars(context.Background(), []settingsmodels.ProfileEnvVar{{
|
||||
Key: "WORKSPACE_ONLY", SecretID: "workspace-secret",
|
||||
}})
|
||||
if _, ok := resolved["WORKSPACE_ONLY"]; ok {
|
||||
if err == nil {
|
||||
t.Fatal("workspace secret resolved without an error")
|
||||
}
|
||||
if len(resolved) != 0 {
|
||||
t.Fatalf("workspace secret was resolved into profile environment: %#v", resolved)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveAgentProfileEnvVarsPreservesCancellation(t *testing.T) {
|
||||
for name, cause := range map[string]error{
|
||||
"canceled": context.Canceled,
|
||||
"deadline exceeded": context.DeadlineExceeded,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
store := newInMemorySecretStore()
|
||||
store.revealErr = cause
|
||||
_ = store.Create(context.Background(), &secrets.SecretWithValue{
|
||||
Secret: secrets.Secret{ID: "sec-cancel", Name: "cancel"},
|
||||
Value: "secret-value",
|
||||
})
|
||||
|
||||
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
|
||||
m := &Manager{logger: log, secretStore: store}
|
||||
resolved, err := m.resolveAgentProfileEnvVars(context.Background(), []settingsmodels.ProfileEnvVar{
|
||||
{Key: "FROM_SECRET", SecretID: "sec-cancel"},
|
||||
})
|
||||
if !errors.Is(err, cause) {
|
||||
t.Fatalf("error = %v, want %v", err, cause)
|
||||
}
|
||||
if errors.Is(err, ErrProfileSecretUnavailable) {
|
||||
t.Fatalf("cancellation was sanitized as a profile secret error: %v", err)
|
||||
}
|
||||
if resolved != nil {
|
||||
t.Fatalf("resolved = %#v, want nil", resolved)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,17 +367,20 @@ func (r *ProfileReconciler) seedDefaultProfile(
|
||||
zap.String("mode", profile.Mode))
|
||||
}
|
||||
|
||||
// healProfile validates the profile's model and mode against the cache and
|
||||
// auto-heals values that no longer exist. User-modified profiles are still
|
||||
// healed — we always keep profiles in a usable state; the "user_modified"
|
||||
// flag survives the write to retain user intent for other fields.
|
||||
// healProfile validates system-managed profile routes against the agent-wide
|
||||
// capability cache. Compatibility migrations run for every profile, while
|
||||
// catalog-driven route changes skip user-modified profiles because they can
|
||||
// use provider configuration that is not visible to the host probe.
|
||||
func (r *ProfileReconciler) healProfile(
|
||||
ctx context.Context,
|
||||
p *models.AgentProfile,
|
||||
caps hostutility.AgentCapabilities,
|
||||
agentID string,
|
||||
) {
|
||||
changed := healProfileName(p, caps)
|
||||
// Compatibility migrations describe persisted protocol identifiers, not
|
||||
// catalog-driven route choices. They must run even for user-modified
|
||||
// profiles so an agent bridge upgrade cannot leave an unusable mode/model.
|
||||
changed := false
|
||||
if model, options, migrated := acpcompat.MigrateCursorModel(agentID, p.Model, p.ConfigOptions); migrated {
|
||||
r.log.Info("migrating Cursor variant profile model",
|
||||
zap.String("profile_id", p.ID),
|
||||
@@ -387,6 +390,27 @@ func (r *ProfileReconciler) healProfile(
|
||||
p.ConfigOptions = options
|
||||
changed = true
|
||||
}
|
||||
if healCompatibilityMode(p, caps, agentID) {
|
||||
r.log.Info("migrating legacy agent mode",
|
||||
zap.String("profile_id", p.ID),
|
||||
zap.String("agent_id", agentID),
|
||||
zap.String("mode", p.Mode))
|
||||
changed = true
|
||||
}
|
||||
if p.UserModified {
|
||||
if !changed {
|
||||
return
|
||||
}
|
||||
if err := r.store.UpdateAgentProfile(ctx, p); err != nil {
|
||||
r.log.Warn("profile compatibility migration update failed",
|
||||
zap.String("profile_id", p.ID), zap.Error(err))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if healProfileName(p, caps) {
|
||||
changed = true
|
||||
}
|
||||
|
||||
// No-silent-model-fallback: a configured model that is no longer
|
||||
// advertised (e.g. provider auth expired) is KEPT, never overwritten
|
||||
@@ -430,6 +454,20 @@ func (r *ProfileReconciler) healProfile(
|
||||
}
|
||||
}
|
||||
|
||||
// healCompatibilityMode migrates a mode ID that belonged to the legacy Codex
|
||||
// bridge. "auto" was accepted by that bridge but is not advertised by the
|
||||
// current bridge. Custom modes on user profiles remain untouched.
|
||||
func healCompatibilityMode(p *models.AgentProfile, caps hostutility.AgentCapabilities, agentID string) bool {
|
||||
if p == nil || agentID != "codex-acp" || p.Mode != "auto" || caps.CurrentModeID == "" || caps.CurrentModeID == p.Mode {
|
||||
return false
|
||||
}
|
||||
if !modeExists(caps.CurrentModeID, caps.Modes) {
|
||||
return false
|
||||
}
|
||||
p.Mode = caps.CurrentModeID
|
||||
return true
|
||||
}
|
||||
|
||||
// healProfileName updates the profile name when it still matches the agent
|
||||
// display name (stale seed from before we started naming profiles after the
|
||||
// current model). Workspace-scoped and user-modified profiles are skipped.
|
||||
|
||||
@@ -532,6 +532,80 @@ func TestProfileReconciler_KeepsGoneFallbackModel(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileReconciler_PreservesUserModifiedCustomRouteOutsideAgentCatalog(t *testing.T) {
|
||||
st := newFakeStore()
|
||||
dbAgent := &models.Agent{Name: "opencode-acp"}
|
||||
_ = st.CreateAgent(context.Background(), dbAgent)
|
||||
existing := &models.AgentProfile{
|
||||
AgentID: dbAgent.ID,
|
||||
Name: "Custom route",
|
||||
Model: "custom-provider/model",
|
||||
Mode: "custom-mode",
|
||||
UserModified: true,
|
||||
}
|
||||
_ = st.CreateAgentProfile(context.Background(), existing)
|
||||
st.created = nil
|
||||
|
||||
ag := &mockInferenceAgent{id: "opencode-acp", displayName: "OpenCode", enabled: true}
|
||||
caps := &fakeCapReader{caps: map[string]hostutility.AgentCapabilities{
|
||||
"opencode-acp": {
|
||||
AgentType: "opencode-acp",
|
||||
Models: []hostutility.Model{{ID: "catalog-model", Name: "Catalog"}},
|
||||
CurrentModelID: "catalog-model",
|
||||
Modes: []hostutility.Mode{{ID: "agent", Name: "Agent"}},
|
||||
CurrentModeID: "agent",
|
||||
Status: hostutility.StatusOK,
|
||||
},
|
||||
}}
|
||||
|
||||
r := newReconciler(t, st, caps, ag)
|
||||
if err := r.Run(context.Background()); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(st.updated) != 0 {
|
||||
t.Fatalf("user-modified custom route was rewritten: %+v", st.updated)
|
||||
}
|
||||
if existing.Model != "custom-provider/model" || existing.Mode != "custom-mode" {
|
||||
t.Fatalf("custom route changed to model=%q mode=%q", existing.Model, existing.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileReconciler_LeavesUserModifiedEmptyRouteUnchanged(t *testing.T) {
|
||||
st := newFakeStore()
|
||||
dbAgent := &models.Agent{Name: "claude-acp"}
|
||||
_ = st.CreateAgent(context.Background(), dbAgent)
|
||||
existing := &models.AgentProfile{
|
||||
AgentID: dbAgent.ID,
|
||||
Name: "Use provider default",
|
||||
UserModified: true,
|
||||
}
|
||||
_ = st.CreateAgentProfile(context.Background(), existing)
|
||||
st.created = nil
|
||||
|
||||
ag := &mockInferenceAgent{id: "claude-acp", displayName: "Claude", enabled: true}
|
||||
caps := &fakeCapReader{caps: map[string]hostutility.AgentCapabilities{
|
||||
"claude-acp": {
|
||||
AgentType: "claude-acp",
|
||||
Models: []hostutility.Model{{ID: "claude-sonnet", Name: "Sonnet"}},
|
||||
CurrentModelID: "claude-sonnet",
|
||||
Modes: []hostutility.Mode{{ID: "default", Name: "Default"}},
|
||||
CurrentModeID: "default",
|
||||
Status: hostutility.StatusOK,
|
||||
},
|
||||
}}
|
||||
|
||||
r := newReconciler(t, st, caps, ag)
|
||||
if err := r.Run(context.Background()); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(st.updated) != 0 {
|
||||
t.Fatalf("user-modified empty route was rewritten: %+v", st.updated)
|
||||
}
|
||||
if existing.Model != "" || existing.Mode != "" {
|
||||
t.Fatalf("empty route changed to model=%q mode=%q", existing.Model, existing.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileReconciler_PreservesOfficeAgentName(t *testing.T) {
|
||||
profile := &models.AgentProfile{
|
||||
Name: "Researcher",
|
||||
@@ -599,6 +673,49 @@ func TestProfileReconciler_HealsStaleCodexModeAfterBridgeSwap(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileReconciler_HealsStaleCodexModeForUserModifiedProfile(t *testing.T) {
|
||||
st := newFakeStore()
|
||||
dbAgent := &models.Agent{Name: "codex-acp"}
|
||||
_ = st.CreateAgent(context.Background(), dbAgent)
|
||||
existing := &models.AgentProfile{
|
||||
AgentID: dbAgent.ID,
|
||||
Name: "Codex",
|
||||
Model: "gpt-5.6-sol",
|
||||
Mode: "auto",
|
||||
UserModified: true,
|
||||
}
|
||||
_ = st.CreateAgentProfile(context.Background(), existing)
|
||||
st.created = nil
|
||||
|
||||
ag := &mockInferenceAgent{id: "codex-acp", displayName: "Codex", enabled: true}
|
||||
caps := &fakeCapReader{
|
||||
caps: map[string]hostutility.AgentCapabilities{
|
||||
"codex-acp": {
|
||||
AgentType: "codex-acp",
|
||||
Status: hostutility.StatusOK,
|
||||
Models: []hostutility.Model{{ID: "gpt-5.6-sol", Name: "GPT 5.6 Sol"}},
|
||||
CurrentModelID: "gpt-5.6-sol",
|
||||
Modes: []hostutility.Mode{
|
||||
{ID: "read-only", Name: "Read Only"},
|
||||
{ID: "agent", Name: "Agent"},
|
||||
{ID: "agent-full-access", Name: "Agent Full Access"},
|
||||
},
|
||||
CurrentModeID: "agent",
|
||||
},
|
||||
},
|
||||
}
|
||||
r := newReconciler(t, st, caps, ag)
|
||||
if err := r.Run(context.Background()); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(st.updated) != 1 {
|
||||
t.Fatalf("expected 1 updated profile, got %d", len(st.updated))
|
||||
}
|
||||
if got := st.updated[0].Mode; got != "agent" {
|
||||
t.Fatalf("healed mode = %q, want agent", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileReconciler_CleansOrphanProfiles(t *testing.T) {
|
||||
st := newFakeStore()
|
||||
// Seed a DB row for an agent that is NOT registered in the registry.
|
||||
|
||||
@@ -416,18 +416,24 @@ func (h *TerminalHandler) startUserShellProcess(
|
||||
return "", http.StatusServiceUnavailable, err.Error()
|
||||
}
|
||||
|
||||
// Export the executor profile's env vars (secrets revealed) so the terminal
|
||||
// sees the same variables the agent subprocess and the repository setup
|
||||
// script get. Best-effort: an unresolvable profile just yields no extras.
|
||||
profileEnv := h.lifecycleMgr.ExecutorProfileEnvForSession(c.Request.Context(), sessionID, scopeID)
|
||||
shellEnv := execution.RuntimeEnvironment()
|
||||
profileEnv := map[string]string(nil)
|
||||
if shellEnv == nil {
|
||||
// The runtime snapshot is authoritative for a live execution. Only
|
||||
// older/recovered executions without a snapshot need profile lookup.
|
||||
var err error
|
||||
profileEnv, err = h.lifecycleMgr.ExecutorProfileEnvForSession(c.Request.Context(), sessionID, scopeID)
|
||||
if err != nil {
|
||||
h.logger.Warn("failed to resolve executor profile environment for terminal",
|
||||
zap.String("session_id", sessionID), zap.Error(err))
|
||||
return "", http.StatusServiceUnavailable, "executor profile environment unavailable"
|
||||
}
|
||||
shellEnv = make(map[string]string, len(profileEnv))
|
||||
}
|
||||
// The effective runtime environment is authoritative: it includes managed
|
||||
// Git credentials and the shim-first PATH selected for this execution.
|
||||
// Profile resolution remains a best-effort fallback for recovered or older
|
||||
// executions that do not have an in-memory runtime snapshot.
|
||||
// Profile resolution remains a fallback for recovered or older executions
|
||||
// that do not have an in-memory runtime snapshot.
|
||||
for key, value := range profileEnv {
|
||||
if _, exists := shellEnv[key]; !exists {
|
||||
shellEnv[key] = value
|
||||
|
||||
@@ -336,6 +336,49 @@ func TestStartUserShellProcessExportsExecutorProfileEnv(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartUserShellProcessFailsClosedOnExecutorProfileSecretFailure(t *testing.T) {
|
||||
log := testTerminalLogger(t)
|
||||
manager := lifecycle.NewManager(
|
||||
nil,
|
||||
bus.NewMemoryEventBus(log),
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
lifecycle.ExecutorFallbackDeny,
|
||||
t.TempDir(),
|
||||
log,
|
||||
)
|
||||
manager.SetExecutorProfileReader(&stubExecutorProfileReader{
|
||||
env: &taskmodels.TaskEnvironment{ID: "env-1", ExecutorProfileID: "prof-1"},
|
||||
profile: &taskmodels.ExecutorProfile{
|
||||
ID: "prof-1",
|
||||
EnvVars: []taskmodels.ProfileEnvVar{{Key: "TOKEN", SecretID: "deleted-secret"}},
|
||||
},
|
||||
})
|
||||
handler := NewTerminalHandler(manager, nil, nil, log)
|
||||
runner := process.NewInteractiveRunner(nil, log, 2*1024*1024)
|
||||
|
||||
execution := &lifecycle.AgentExecution{
|
||||
ID: "exec-1",
|
||||
SessionID: "session-1",
|
||||
TaskEnvironmentID: "env-1",
|
||||
WorkspacePath: t.TempDir(),
|
||||
}
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/terminal/environment/env-1?terminalId=term-1", nil)
|
||||
|
||||
processID, status, errMsg := handler.startUserShellProcess(c, execution, "env-1", "term-1", runner)
|
||||
if processID != "" || status != http.StatusServiceUnavailable || errMsg != "executor profile environment unavailable" {
|
||||
t.Fatalf("startUserShellProcess() = (%q, %d, %q), want service unavailable without a process", processID, status, errMsg)
|
||||
}
|
||||
if shells := runner.ListUserShells("env-1"); len(shells) != 0 {
|
||||
t.Fatalf("secret failure started user shells: %#v", shells)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartUserShellProcessExportsEffectiveRuntimeEnv(t *testing.T) {
|
||||
log := testTerminalLogger(t)
|
||||
manager := lifecycle.NewManager(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { test, expect } from "../../fixtures/office-fixture";
|
||||
import type { OfficeApiClient } from "../../helpers/office-api-client";
|
||||
|
||||
const ROUTING_PROFILE_WAIT_MS = 20_000;
|
||||
const ROUTING_MOCK_MODEL = "mock-fast";
|
||||
|
||||
test.describe("Tasks on mobile", () => {
|
||||
test("cleans only the stale profile from workspace routing", async ({
|
||||
@@ -15,20 +16,22 @@ test.describe("Tasks on mobile", () => {
|
||||
const { agents } = await apiClient.listAgents();
|
||||
const claudeAgent = agents.find((agent) => agent.name === "claude-acp");
|
||||
const codexAgent = agents.find((agent) => agent.name === "codex-acp");
|
||||
const claudeProfile = claudeAgent?.profiles[0];
|
||||
const codexProfile = codexAgent?.profiles[0];
|
||||
if (!claudeAgent || !claudeProfile || !codexAgent || !codexProfile) {
|
||||
throw new Error("E2E seed has no Claude and Codex profiles");
|
||||
if (!claudeAgent || !codexAgent) {
|
||||
throw new Error("E2E seed has no Claude and Codex agents");
|
||||
}
|
||||
|
||||
// User-modified profiles intentionally keep an empty model as "use the
|
||||
// provider default". Routing requires an explicit launch model, so use
|
||||
// the mock providers' advertised model instead of inheriting an optional
|
||||
// seed profile value.
|
||||
const profile = await apiClient.createAgentProfile(claudeAgent.id, "Routing cleanup profile", {
|
||||
model: claudeProfile.model,
|
||||
model: ROUTING_MOCK_MODEL,
|
||||
});
|
||||
const preservedProfile = await apiClient.createAgentProfile(
|
||||
codexAgent.id,
|
||||
"Preserved routing profile",
|
||||
{
|
||||
model: codexProfile.model,
|
||||
model: ROUTING_MOCK_MODEL,
|
||||
},
|
||||
);
|
||||
const routingProfile = await waitForRoutingProfile(
|
||||
|
||||
Reference in New Issue
Block a user