diff --git a/apps/backend/cmd/kandev/services.go b/apps/backend/cmd/kandev/services.go index eb845e8b4b..5c23e4ffee 100644 --- a/apps/backend/cmd/kandev/services.go +++ b/apps/backend/cmd/kandev/services.go @@ -87,6 +87,10 @@ func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories if err != nil { log.Warn("GitHub service initialization failed (non-fatal)", zap.Error(err)) } + if githubSvc != nil { + // Wire secret manager for token configuration + githubSvc.SetSecretManager(secretsAdapter) + } return &Services{ Task: taskSvc, @@ -162,7 +166,7 @@ func (a *startStepResolverAdapter) ResolveFirstStep(ctx context.Context, workflo return step.ID, nil } -// githubSecretAdapter adapts secrets.SecretStore to github.SecretProvider. +// githubSecretAdapter adapts secrets.SecretStore to github.SecretProvider and github.SecretManager. type githubSecretAdapter struct { store secrets.SecretStore } @@ -187,6 +191,28 @@ func (a *githubSecretAdapter) Reveal(ctx context.Context, id string) (string, er return a.store.Reveal(ctx, id) } +// Create creates a new secret with the given name and value. +func (a *githubSecretAdapter) Create(ctx context.Context, name, value string) (string, error) { + secret := &secrets.SecretWithValue{ + Secret: secrets.Secret{Name: name}, + Value: value, + } + if err := a.store.Create(ctx, secret); err != nil { + return "", err + } + return secret.ID, nil +} + +// Update updates an existing secret's value. +func (a *githubSecretAdapter) Update(ctx context.Context, id, value string) error { + return a.store.Update(ctx, id, &secrets.UpdateSecretRequest{Value: &value}) +} + +// Delete removes a secret by ID. +func (a *githubSecretAdapter) Delete(ctx context.Context, id string) error { + return a.store.Delete(ctx, id) +} + // workflowProviderAdapter adapts task service to workflow service's WorkflowProvider interface. type workflowProviderAdapter struct { svc *taskservice.Service diff --git a/apps/backend/dockerfiles/entrypoint.sh b/apps/backend/dockerfiles/entrypoint.sh index b62037eaab..f3b36d9891 100644 --- a/apps/backend/dockerfiles/entrypoint.sh +++ b/apps/backend/dockerfiles/entrypoint.sh @@ -15,6 +15,13 @@ if ! command -v codex &> /dev/null; then echo "WARNING: codex CLI not found" fi +# Run prepare script if provided (e.g., clone repo, configure git) +if [ -n "$KANDEV_PREPARE_SCRIPT" ]; then + echo "Running prepare script..." + eval "$KANDEV_PREPARE_SCRIPT" + echo "Prepare script completed." +fi + # Run agentctl HTTP server echo "Starting agentctl on port ${AGENTCTL_PORT:-39429}..." exec /usr/local/bin/agentctl diff --git a/apps/backend/internal/agent/lifecycle/container.go b/apps/backend/internal/agent/lifecycle/container.go index bdf4582045..adbd1f3fed 100644 --- a/apps/backend/internal/agent/lifecycle/container.go +++ b/apps/backend/internal/agent/lifecycle/container.go @@ -22,7 +22,7 @@ import ( // ContainerConfig holds configuration for launching a Docker container type ContainerConfig struct { AgentConfig agents.Agent - WorkspacePath string + WorkspacePath string // If empty, workspace is not mounted (will clone inside container) TaskID string TaskDescription string Model string @@ -33,6 +33,7 @@ type ContainerConfig struct { MainRepoGitDir string // Path to main repo's .git directory (for worktrees) McpServers []McpServerConfig McpMode string + PrepareScript string // Script to run inside container before agent starts (e.g., clone repo) BootstrapNonce string // one-time nonce for agentctl handshake (set internally) } @@ -279,6 +280,11 @@ func (cm *ContainerManager) buildContainerConfig(config ContainerConfig) (docker containerName := fmt.Sprintf("kandev-agent-%s", config.InstanceID[:8]) + // If a prepare script is provided, pass it as env var for the entrypoint to run + if config.PrepareScript != "" { + env = append(env, "KANDEV_PREPARE_SCRIPT="+config.PrepareScript) + } + containerCfg := docker.ContainerConfig{ Name: containerName, Image: imageName, @@ -381,13 +387,31 @@ func (cm *ContainerManager) buildEnvVars(config ContainerConfig) []string { env = append(env, fmt.Sprintf("AGENTCTL_PROTOCOL=%s", rt.Protocol)) } - // Configure Git to trust the workspace directory + // Configure Git settings via environment + // - Trust all directories (for mounted workspaces) + // - URL rewriting: SSH → HTTPS for GitHub (enables token auth) + // - Credential helper for GitHub HTTPS auth (uses GH_TOKEN env var) + gitConfigCount := 3 env = append(env, - "GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=safe.directory", "GIT_CONFIG_VALUE_0=*", + "GIT_CONFIG_KEY_1=url.https://github.com/.insteadOf", + "GIT_CONFIG_VALUE_1=git@github.com:", + "GIT_CONFIG_KEY_2=url.https://github.com/.insteadOf", + "GIT_CONFIG_VALUE_2=ssh://git@github.com/", ) + // If GitHub token is provided, add credential helper + // Use ${GH_TOKEN:-${GITHUB_TOKEN}} to support either env var being set + if config.Credentials["GH_TOKEN"] != "" || config.Credentials["GITHUB_TOKEN"] != "" { + env = append(env, + "GIT_CONFIG_KEY_3=credential.https://github.com.helper", + `GIT_CONFIG_VALUE_3=!f() { echo "username=x-access-token"; echo "password=${GH_TOKEN:-${GITHUB_TOKEN}}"; }; f`, + ) + gitConfigCount = 4 + } + env = append(env, fmt.Sprintf("GIT_CONFIG_COUNT=%d", gitConfigCount)) + // Inject credentials from the provided credentials map for k, v := range config.Credentials { env = append(env, fmt.Sprintf("%s=%s", k, v)) diff --git a/apps/backend/internal/agent/lifecycle/default_scripts.go b/apps/backend/internal/agent/lifecycle/default_scripts.go index 5d21dedd54..d60f130c1c 100644 --- a/apps/backend/internal/agent/lifecycle/default_scripts.go +++ b/apps/backend/internal/agent/lifecycle/default_scripts.go @@ -36,38 +36,31 @@ const defaultWorktreePrepareScript = `#!/bin/bash {{repository.setup_script}} ` -const defaultDockerPrepareScript = `#!/bin/bash -# Prepare Docker container environment -# This runs inside the Docker container after it starts +const defaultDockerPrepareScript = `#!/bin/sh +# Prepare Docker container environment (kandev/multi-agent image) +# git, node, and agentctl are already installed in the image -set -euo pipefail - -# ---- System dependencies ---- -apt-get update -qq -apt-get install -y -qq git curl ca-certificates > /dev/null 2>&1 - -# ---- Node.js (required for agentctl) ---- -if ! command -v node &> /dev/null; then - curl -fsSL https://deb.nodesource.com/setup_22.x | bash - > /dev/null 2>&1 - apt-get install -y -qq nodejs > /dev/null 2>&1 -fi +set -eu # ---- Git identity (optional) ---- {{git.identity_setup}} +# ---- Configure git/gh for HTTPS auth ---- +git config --global url."https://github.com/".insteadOf "git@github.com:" +git config --global url."https://github.com/".insteadOf "ssh://git@github.com/" + +# Configure GitHub token for gh CLI and git operations +{{github.auth_setup}} + # ---- Clone repository ---- git clone --depth=1 --branch {{repository.branch}} {{repository.clone_url}} {{workspace.path}} cd {{workspace.path}} +# Strip embedded token from remote URL to avoid persisting credentials in .git/config +git remote set-url origin "$(git remote get-url origin | sed 's|https://[^@]*@github.com/|https://github.com/|')" 2>/dev/null || true + # ---- Repository setup (if configured) ---- {{repository.setup_script}} - -# ---- Pre-install agent CLI(s) ---- -{{kandev.agents.install}} - -# ---- Install and start Kandev agent controller ---- -{{kandev.agentctl.install}} -{{kandev.agentctl.start}} ` const defaultSpritesPrepareScript = `#!/bin/bash @@ -87,10 +80,10 @@ ssh-keyscan -t ed25519 github.com gitlab.com bitbucket.org >> ~/.ssh/known_hosts # Rewrite SSH URLs to HTTPS so git clone git@github.com:... works via token auth git config --global url."https://github.com/".insteadOf "git@github.com:" git config --global url."https://github.com/".insteadOf "ssh://git@github.com/" -# Register gh as git credential helper (provides GITHUB_TOKEN to git for HTTPS) -gh auth setup-git 2>/dev/null || true -# Ensure gh CLI itself uses HTTPS for gh repo clone -gh config set git_protocol https --host github.com 2>/dev/null || true + +# Configure GitHub token for gh CLI and git operations +# GH_TOKEN is the primary env var for gh CLI authentication +{{github.auth_setup}} # ---- Install pnpm globally ---- npm install -g pnpm > /dev/null 2>&1 @@ -103,6 +96,9 @@ echo "Cloning {{repository.clone_url}} (branch: {{repository.branch}})..." git clone --depth=1 --quiet --branch {{repository.branch}} {{repository.clone_url}} {{workspace.path}} cd {{workspace.path}} +# Strip embedded token from remote URL to avoid persisting credentials in .git/config +git remote set-url origin "$(git remote get-url origin | sed 's|https://[^@]*@github.com/|https://github.com/|')" 2>/dev/null || true + # ---- Repository setup (if configured) ---- {{repository.setup_script}} diff --git a/apps/backend/internal/agent/lifecycle/executor_docker.go b/apps/backend/internal/agent/lifecycle/executor_docker.go index 8a04ec44e8..df3c8cfb59 100644 --- a/apps/backend/internal/agent/lifecycle/executor_docker.go +++ b/apps/backend/internal/agent/lifecycle/executor_docker.go @@ -11,11 +11,15 @@ import ( "github.com/kandev/kandev/internal/agent/docker" "github.com/kandev/kandev/internal/agent/executor" + agentctl "github.com/kandev/kandev/internal/agentctl/client" "github.com/kandev/kandev/internal/agentctl/server/process" "github.com/kandev/kandev/internal/common/config" "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/scriptengine" ) +const dockerWorkspacePath = "/workspace" + // getMetadataString retrieves a string value from metadata map. func getMetadataString(metadata map[string]interface{}, key string) string { if metadata == nil { @@ -121,21 +125,35 @@ func (r *DockerExecutor) CreateInstance(ctx context.Context, req *ExecutorCreate return nil, fmt.Errorf("docker unavailable: %w", err) } + // On resume, try to reconnect to the existing container + if req.PreviousExecutionID != "" { + instance, reconnectErr := r.reconnectToContainer(ctx, dockerClient, req) + if reconnectErr == nil { + return instance, nil + } + r.logger.Info("could not reconnect to previous container, creating new one", + zap.String("previous_execution_id", req.PreviousExecutionID), + zap.Error(reconnectErr)) + } + // Extract runtime-specific values from metadata - mainRepoGitDir := getMetadataString(req.Metadata, MetadataKeyMainRepoGitDir) worktreeID := getMetadataString(req.Metadata, MetadataKeyWorktreeID) worktreeBranch := getMetadataString(req.Metadata, MetadataKeyWorktreeBranch) + // Resolve prepare script for cloning repo inside container + prepareScript := r.resolvePrepareScript(req) + // Convert ExecutorCreateRequest to ContainerConfig + // Note: WorkspacePath is empty to skip mounting - we clone inside container containerCfg := ContainerConfig{ - AgentConfig: req.AgentConfig, - WorkspacePath: req.WorkspacePath, - TaskID: req.TaskID, - SessionID: req.SessionID, - InstanceID: req.InstanceID, - MainRepoGitDir: mainRepoGitDir, - Credentials: req.Env, // Env contains credentials from the caller - McpServers: req.McpServers, + AgentConfig: req.AgentConfig, + WorkspacePath: "", // Empty = no workspace mount, we'll clone instead + TaskID: req.TaskID, + SessionID: req.SessionID, + InstanceID: req.InstanceID, + Credentials: req.Env, // Env contains credentials from the caller + McpServers: req.McpServers, + PrepareScript: prepareScript, } // Use ContainerManager to launch container (includes nonce handshake) @@ -149,9 +167,10 @@ func (r *DockerExecutor) CreateInstance(ctx context.Context, req *ExecutorCreate // Build metadata metadata := make(map[string]interface{}) + metadata[MetadataKeyIsRemote] = true // Mark as remote for shell handling if worktreeID != "" { metadata["worktree_id"] = worktreeID - metadata["worktree_path"] = req.WorkspacePath + metadata["worktree_path"] = dockerWorkspacePath metadata["worktree_branch"] = worktreeBranch } @@ -168,12 +187,108 @@ func (r *DockerExecutor) CreateInstance(ctx context.Context, req *ExecutorCreate Client: result.Client, ContainerID: result.ContainerID, ContainerIP: containerIP, - WorkspacePath: "/workspace", // Docker mounts workspace to /workspace + WorkspacePath: dockerWorkspacePath, Metadata: metadata, AuthToken: result.AuthToken, }, nil } +// reconnectToContainer attempts to reconnect to an existing Docker container +// from a previous execution. Returns the reconnected instance if successful. +func (r *DockerExecutor) reconnectToContainer(ctx context.Context, dockerClient *docker.Client, req *ExecutorCreateRequest) (*ExecutorInstance, error) { + // Derive container name from previous execution ID (same pattern as LaunchContainer) + prevID := req.PreviousExecutionID + if len(prevID) < 8 { + return nil, fmt.Errorf("previous execution ID too short: %s", prevID) + } + containerName := fmt.Sprintf("kandev-agent-%s", prevID[:8]) + + // Check if the container is still running + running, err := dockerClient.IsContainerRunning(ctx, containerName) + if err != nil || !running { + return nil, fmt.Errorf("container %s not running", containerName) + } + + // Get the container IP + containerIP, err := dockerClient.GetContainerIP(ctx, containerName) + if err != nil { + return nil, fmt.Errorf("failed to get IP for container %s: %w", containerName, err) + } + + // Check if agentctl is healthy + ctl := agentctl.NewControlClient(containerIP, AgentCtlPort, r.logger) + if err := ctl.Health(ctx); err != nil { + return nil, fmt.Errorf("agentctl not healthy in container %s: %w", containerName, err) + } + + // Check if the previous instance is still alive + instancePort, reusingProcess, err := r.findExistingInstance(ctx, ctl, containerIP, prevID) + if err != nil { + return nil, fmt.Errorf("failed to find instance in container %s: %w", containerName, err) + } + + // Create client pointing to the instance port + client := agentctl.NewClient(containerIP, instancePort, r.logger, + agentctl.WithExecutionID(req.InstanceID), + agentctl.WithSessionID(req.SessionID)) + + // Get container info for the full container ID + info, err := dockerClient.GetContainerInfo(ctx, containerName) + if err != nil { + return nil, fmt.Errorf("failed to inspect container %s: %w", containerName, err) + } + + metadata := map[string]interface{}{ + MetadataKeyIsRemote: true, + "reuse_existing_process": reusingProcess, + } + + r.logger.Info("reconnected to existing docker container", + zap.String("container_name", containerName), + zap.String("container_id", info.ID), + zap.String("container_ip", containerIP), + zap.Int("instance_port", instancePort), + zap.Bool("reusing_process", reusingProcess)) + + return &ExecutorInstance{ + InstanceID: req.InstanceID, + TaskID: req.TaskID, + SessionID: req.SessionID, + RuntimeName: string(r.Name()), + Client: client, + ContainerID: info.ID, + ContainerIP: containerIP, + WorkspacePath: dockerWorkspacePath, + Metadata: metadata, + }, nil +} + +// findExistingInstance checks if a previous instance is still running in the container. +// Returns the instance port and whether the agent subprocess is also running. +func (r *DockerExecutor) findExistingInstance(ctx context.Context, ctl *agentctl.ControlClient, containerIP, prevExecutionID string) (int, bool, error) { + // Try to get the existing instance by its ID + instance, err := ctl.GetInstance(ctx, prevExecutionID) + if err == nil && instance != nil && instance.Port > 0 { + // Instance exists, check if agent subprocess is running + client := agentctl.NewClient(containerIP, instance.Port, r.logger) + status, statusErr := client.GetStatus(ctx) + processRunning := statusErr == nil && status != nil && status.IsAgentRunning() + return instance.Port, processRunning, nil + } + + // Instance not found — create a new instance in the existing container + createReq := &agentctl.CreateInstanceRequest{ + ID: prevExecutionID, + WorkspacePath: dockerWorkspacePath, + AutoStart: false, + } + resp, createErr := ctl.CreateInstance(ctx, createReq) + if createErr != nil { + return 0, false, fmt.Errorf("failed to create new instance: %w", createErr) + } + return resp.Port, false, nil +} + func (r *DockerExecutor) StopInstance(ctx context.Context, instance *ExecutorInstance, force bool) error { if instance.ContainerID == "" { return nil // No container to stop @@ -227,6 +342,64 @@ func (r *DockerExecutor) GetInteractiveRunner() *process.InteractiveRunner { return nil } -func (r *DockerExecutor) RequiresCloneURL() bool { return false } +func (r *DockerExecutor) RequiresCloneURL() bool { return true } func (r *DockerExecutor) ShouldApplyPreferredShell() bool { return false } -func (r *DockerExecutor) IsAlwaysResumable() bool { return false } +func (r *DockerExecutor) IsAlwaysResumable() bool { return true } + +// resolvePrepareScript builds the resolved prepare script using scriptengine. +// This script clones the repository inside the container. +func (r *DockerExecutor) resolvePrepareScript(req *ExecutorCreateRequest) string { + script := getMetadataString(req.Metadata, MetadataKeySetupScript) + if script == "" { + script = DefaultPrepareScript("local_docker") + } + if script == "" { + return "" + } + + resolver := scriptengine.NewResolver(). + WithProvider(scriptengine.WorkspaceProvider(dockerWorkspacePath)). + WithProvider(scriptengine.GitIdentityProvider(req.Metadata)). + WithProvider(scriptengine.GitHubAuthProvider(req.Env)). + WithProvider(scriptengine.RepositoryProvider( + req.Metadata, + req.Env, + getGitRemoteURL, + r.injectTokenIntoURL, + )). + // Docker image has agents and agentctl pre-installed; + // resolve these to empty so stored scripts with these placeholders don't break. + // The entrypoint handles agentctl startup, so install/start must be no-ops. + WithProvider(scriptengine.AgentInstallProvider(nil)). + WithStatic(map[string]string{ + "kandev.agentctl.port": "9999", + "kandev.agentctl.install": "", + "kandev.agentctl.start": "", + }) + + return resolver.Resolve(script) +} + +// injectTokenIntoURL adds a GitHub token to clone URLs for authentication. +// Handles both HTTPS and SSH URLs (converting SSH to authenticated HTTPS). +func (r *DockerExecutor) injectTokenIntoURL(cloneURL string, env map[string]string) string { + token := env["GITHUB_TOKEN"] + if token == "" { + token = env["GH_TOKEN"] + } + if token == "" { + return cloneURL + } + + // Convert SSH URLs to HTTPS first + if strings.HasPrefix(cloneURL, "git@github.com:") { + path := strings.TrimPrefix(cloneURL, "git@github.com:") + cloneURL = "https://github.com/" + path + } + + // Convert https://github.com/... to https://x-access-token:TOKEN@github.com/... + if strings.HasPrefix(cloneURL, "https://github.com/") { + return strings.Replace(cloneURL, "https://github.com/", "https://x-access-token:"+token+"@github.com/", 1) + } + return cloneURL +} diff --git a/apps/backend/internal/agent/lifecycle/executor_docker_test.go b/apps/backend/internal/agent/lifecycle/executor_docker_test.go index 5af094b72b..55b6fe14f0 100644 --- a/apps/backend/internal/agent/lifecycle/executor_docker_test.go +++ b/apps/backend/internal/agent/lifecycle/executor_docker_test.go @@ -3,6 +3,7 @@ package lifecycle import ( "context" "fmt" + "strings" "sync/atomic" "testing" @@ -343,3 +344,141 @@ func TestExecutorRegistry_CloseAll(t *testing.T) { registry.CloseAll() }) } + +func TestInjectTokenIntoURL(t *testing.T) { + log := newTestDockerLogger() + exec := NewDockerExecutor(config.DockerConfig{}, log) + + tests := []struct { + name string + url string + env map[string]string + expected string + }{ + { + name: "HTTPS URL with GITHUB_TOKEN", + url: "https://github.com/org/repo.git", + env: map[string]string{"GITHUB_TOKEN": "ghp_test123"}, + expected: "https://x-access-token:ghp_test123@github.com/org/repo.git", + }, + { + name: "HTTPS URL with GH_TOKEN fallback", + url: "https://github.com/org/repo.git", + env: map[string]string{"GH_TOKEN": "ghp_ghtoken"}, + expected: "https://x-access-token:ghp_ghtoken@github.com/org/repo.git", + }, + { + name: "GITHUB_TOKEN takes priority over GH_TOKEN", + url: "https://github.com/org/repo.git", + env: map[string]string{"GITHUB_TOKEN": "ghp_primary", "GH_TOKEN": "ghp_secondary"}, + expected: "https://x-access-token:ghp_primary@github.com/org/repo.git", + }, + { + name: "SSH URL converted to authenticated HTTPS", + url: "git@github.com:org/repo.git", + env: map[string]string{"GITHUB_TOKEN": "ghp_test123"}, + expected: "https://x-access-token:ghp_test123@github.com/org/repo.git", + }, + { + name: "no token returns URL unchanged", + url: "https://github.com/org/repo.git", + env: map[string]string{}, + expected: "https://github.com/org/repo.git", + }, + { + name: "nil env returns URL unchanged", + url: "https://github.com/org/repo.git", + env: nil, + expected: "https://github.com/org/repo.git", + }, + { + name: "non-GitHub URL unchanged", + url: "https://gitlab.com/org/repo.git", + env: map[string]string{"GITHUB_TOKEN": "ghp_test123"}, + expected: "https://gitlab.com/org/repo.git", + }, + { + name: "SSH URL without token unchanged", + url: "git@github.com:org/repo.git", + env: map[string]string{}, + expected: "git@github.com:org/repo.git", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := exec.injectTokenIntoURL(tt.url, tt.env) + if got != tt.expected { + t.Errorf("injectTokenIntoURL(%q) = %q, want %q", tt.url, got, tt.expected) + } + }) + } +} + +func TestReconnectToContainer_ValidationErrors(t *testing.T) { + log := newTestDockerLogger() + exec := NewDockerExecutor(config.DockerConfig{}, log) + + t.Run("short execution ID rejected", func(t *testing.T) { + req := &ExecutorCreateRequest{ + PreviousExecutionID: "short", + } + _, err := exec.reconnectToContainer(context.Background(), nil, req) + if err == nil { + t.Fatal("expected error for short execution ID") + } + if !strings.Contains(err.Error(), "too short") { + t.Errorf("expected 'too short' error, got: %v", err) + } + }) + + t.Run("empty execution ID rejected", func(t *testing.T) { + req := &ExecutorCreateRequest{ + PreviousExecutionID: "", + } + _, err := exec.reconnectToContainer(context.Background(), nil, req) + if err == nil { + t.Fatal("expected error for empty execution ID") + } + }) +} + +func TestResolvePrepareScript(t *testing.T) { + log := newTestDockerLogger() + exec := NewDockerExecutor(config.DockerConfig{}, log) + + t.Run("uses default docker script when no metadata", func(t *testing.T) { + req := &ExecutorCreateRequest{ + Metadata: map[string]interface{}{ + "repository_path": "/tmp/repo", + "base_branch": "main", + "repository_clone_url": "https://github.com/org/repo.git", + }, + Env: map[string]string{"GH_TOKEN": "ghp_test"}, + } + script := exec.resolvePrepareScript(req) + if script == "" { + t.Fatal("expected non-empty script") + } + // Should contain clone command + if !strings.Contains(script, "git clone") { + t.Error("expected git clone in script") + } + // Should contain token stripping + if !strings.Contains(script, "git remote set-url") { + t.Error("expected token stripping after clone") + } + }) + + t.Run("empty metadata uses defaults", func(t *testing.T) { + req := &ExecutorCreateRequest{ + Metadata: map[string]interface{}{}, + Env: map[string]string{}, + } + script := exec.resolvePrepareScript(req) + // Should still produce a script (default docker script) + if script == "" { + t.Fatal("expected non-empty default script") + } + }) +} diff --git a/apps/backend/internal/agent/lifecycle/executor_sprites_operations.go b/apps/backend/internal/agent/lifecycle/executor_sprites_operations.go index 3805fb08ce..4e5a1a728b 100644 --- a/apps/backend/internal/agent/lifecycle/executor_sprites_operations.go +++ b/apps/backend/internal/agent/lifecycle/executor_sprites_operations.go @@ -149,6 +149,7 @@ func (r *SpritesExecutor) resolvePrepareScript(req *ExecutorCreateRequest) strin WithProvider(scriptengine.WorkspaceProvider(spritesWorkspacePath)). WithProvider(scriptengine.AgentctlProvider(r.agentctlPort, spritesWorkspacePath)). WithProvider(scriptengine.GitIdentityProvider(req.Metadata)). + WithProvider(scriptengine.GitHubAuthProvider(req.Env)). WithProvider(scriptengine.AgentInstallProvider(installScripts)). WithProvider(scriptengine.RepositoryProvider( req.Metadata, diff --git a/apps/backend/internal/agentctl/server/process/runner.go b/apps/backend/internal/agentctl/server/process/runner.go index c039ce2767..1c2efd1021 100644 --- a/apps/backend/internal/agentctl/server/process/runner.go +++ b/apps/backend/internal/agentctl/server/process/runner.go @@ -509,7 +509,7 @@ func (r *ProcessRunner) readOutput(proc *commandProcess, reader io.ReadCloser, s // Goroutine Safety: // - Each process has exactly one wait() goroutine // - wait() is the sole authority for final status updates -// - Cleanup happens exactly once (no race with Stop()) +// - Cleanup happens after a delay to allow polling func (r *ProcessRunner) wait(proc *commandProcess) { err := proc.cmd.Wait() exitCode := 0 diff --git a/apps/backend/internal/agentctl/server/shell/session.go b/apps/backend/internal/agentctl/server/shell/session.go index 2b5b0a6e16..1165856bc9 100644 --- a/apps/backend/internal/agentctl/server/shell/session.go +++ b/apps/backend/internal/agentctl/server/shell/session.go @@ -79,7 +79,8 @@ type Status struct { StartedAt time.Time } -// detectShell returns the appropriate shell for the current OS +// detectShell returns the appropriate shell for the current OS. +// It validates that the shell exists before returning it. func detectShell() (string, []string) { if runtime.GOOS == "windows" { // Prefer PowerShell if available @@ -93,8 +94,12 @@ func detectShell() (string, []string) { } // Unix-like systems (Linux, macOS) + // Check $SHELL but only use it if the shell actually exists + // (host's $SHELL may not be installed in Docker containers) if shell := os.Getenv("SHELL"); shell != "" { - return shell, []string{"-l"} // Login shell + if _, err := exec.LookPath(shell); err == nil { + return shell, []string{"-l"} // Login shell + } } // Try common shells diff --git a/apps/backend/internal/agentctl/server/shell/session_test.go b/apps/backend/internal/agentctl/server/shell/session_test.go index fde0dc990d..0d40a765d7 100644 --- a/apps/backend/internal/agentctl/server/shell/session_test.go +++ b/apps/backend/internal/agentctl/server/shell/session_test.go @@ -75,6 +75,7 @@ func assertWindowsShell(t *testing.T, shell string) { } // TestDetectShellWithSHELLEnv tests shell detection respects SHELL env var on Unix +// when the shell actually exists. func TestDetectShellWithSHELLEnv(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("SHELL env var is not used on Windows") @@ -83,18 +84,47 @@ func TestDetectShellWithSHELLEnv(t *testing.T) { originalShell := os.Getenv("SHELL") defer func() { _ = os.Setenv("SHELL", originalShell) }() - // Test with custom SHELL - _ = os.Setenv("SHELL", "/bin/custom-shell") + // Test with a shell that actually exists (/bin/sh is always present) + _ = os.Setenv("SHELL", "/bin/sh") shell, args := detectShell() - if shell != "/bin/custom-shell" { - t.Errorf("expected shell from SHELL env, got %q", shell) + if shell != "/bin/sh" { + t.Errorf("expected shell from SHELL env (/bin/sh), got %q", shell) } if len(args) == 0 || args[0] != "-l" { t.Errorf("expected args to contain '-l', got %v", args) } } +// TestDetectShellWithNonExistentSHELL tests shell detection falls back when SHELL doesn't exist +func TestDetectShellWithNonExistentSHELL(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("SHELL env var is not used on Windows") + } + + originalShell := os.Getenv("SHELL") + defer func() { _ = os.Setenv("SHELL", originalShell) }() + + // Set SHELL to a non-existent path (like host's zsh in a minimal container) + _ = os.Setenv("SHELL", "/usr/bin/this-shell-does-not-exist") + shell, _ := detectShell() + + // Should fall back to a shell that exists, NOT the non-existent one + if shell == "/usr/bin/this-shell-does-not-exist" { + t.Errorf("expected fallback to an existing shell, but got non-existent %q", shell) + } + + // Should be one of the common fallback shells + validShells := map[string]bool{ + "/bin/bash": true, + "/bin/zsh": true, + "/bin/sh": true, + } + if !validShells[shell] { + t.Logf("Detected fallback shell: %q", shell) + } +} + // TestNewSession tests creating a new session func TestNewSession(t *testing.T) { if runtime.GOOS == "windows" { diff --git a/apps/backend/internal/agentctl/types/types.go b/apps/backend/internal/agentctl/types/types.go index 1d034cb696..b9bd9fb3e1 100644 --- a/apps/backend/internal/agentctl/types/types.go +++ b/apps/backend/internal/agentctl/types/types.go @@ -98,6 +98,9 @@ const ( // Process kinds ProcessKindAgentPassthrough = streams.ProcessKindAgentPassthrough + ProcessKindCustom = streams.ProcessKindCustom + ProcessKindCleanup = streams.ProcessKindCleanup + ProcessKindDev = streams.ProcessKindDev ) // PermissionRequest represents a permission request from the agent. diff --git a/apps/backend/internal/github/controller.go b/apps/backend/internal/github/controller.go index 26b1b48881..817f3fe806 100644 --- a/apps/backend/internal/github/controller.go +++ b/apps/backend/internal/github/controller.go @@ -28,6 +28,8 @@ func NewController(svc *Service, log *logger.Logger) *Controller { func (c *Controller) RegisterHTTPRoutes(router *gin.Engine) { api := router.Group("/api/v1/github") api.GET("/status", c.httpGetStatus) + api.POST("/token", c.httpConfigureToken) + api.DELETE("/token", c.httpClearToken) api.GET("/task-prs", c.httpListTaskPRs) api.GET("/task-prs/:taskId", c.httpGetTaskPR) @@ -78,6 +80,34 @@ func (c *Controller) httpGetStatus(ctx *gin.Context) { ctx.JSON(http.StatusOK, status) } +func (c *Controller) httpConfigureToken(ctx *gin.Context) { + var req ConfigureTokenRequest + if err := ctx.ShouldBindJSON(&req); err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload: token is required"}) + return + } + + if err := c.service.ConfigureToken(ctx.Request.Context(), req.Token); err != nil { + // Check if it's a validation error (invalid token) + if strings.Contains(err.Error(), "invalid token") { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + ctx.JSON(http.StatusOK, gin.H{"configured": true}) +} + +func (c *Controller) httpClearToken(ctx *gin.Context) { + if err := c.service.ClearToken(ctx.Request.Context()); err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + ctx.JSON(http.StatusOK, gin.H{"cleared": true}) +} + func (c *Controller) httpListTaskPRs(ctx *gin.Context) { // Workspace-scoped: returns all PRs for a workspace, triggers background refresh for stale ones workspaceID := ctx.Query("workspace_id") diff --git a/apps/backend/internal/github/models.go b/apps/backend/internal/github/models.go index 7a2145b826..ce85317f4e 100644 --- a/apps/backend/internal/github/models.go +++ b/apps/backend/internal/github/models.go @@ -228,10 +228,18 @@ type RepoBranch struct { // GitHubStatus represents GitHub connection status. type GitHubStatus struct { - Authenticated bool `json:"authenticated"` - Username string `json:"username"` - AuthMethod string `json:"auth_method"` // "gh_cli", "pat", "none" - Diagnostics *AuthDiagnostics `json:"diagnostics,omitempty"` + Authenticated bool `json:"authenticated"` + Username string `json:"username"` + AuthMethod string `json:"auth_method"` // "gh_cli", "pat", "none" + TokenConfigured bool `json:"token_configured"` + TokenSecretID string `json:"token_secret_id,omitempty"` + RequiredScopes []string `json:"required_scopes"` + Diagnostics *AuthDiagnostics `json:"diagnostics,omitempty"` +} + +// ConfigureTokenRequest is the request body for configuring a GitHub token. +type ConfigureTokenRequest struct { + Token string `json:"token" binding:"required"` } // AuthDiagnostics captures the output of gh auth status for troubleshooting. diff --git a/apps/backend/internal/github/service.go b/apps/backend/internal/github/service.go index 77f478dccd..1e1dee7178 100644 --- a/apps/backend/internal/github/service.go +++ b/apps/backend/internal/github/service.go @@ -32,6 +32,13 @@ type TaskSessionChecker interface { HasTaskSessions(ctx context.Context, taskID string) (bool, error) } +// SecretManager handles secret creation, update, and deletion. +type SecretManager interface { + Create(ctx context.Context, name, value string) (id string, err error) + Update(ctx context.Context, id, value string) error + Delete(ctx context.Context, id string) error +} + // prSyncFreshnessWindow is how long PR data is considered fresh (skip GitHub API). const prSyncFreshnessWindow = 30 * time.Second @@ -41,6 +48,7 @@ type Service struct { client Client authMethod string secrets SecretProvider + secretManager SecretManager store *Store eventBus bus.EventBus logger *logger.Logger @@ -72,6 +80,9 @@ func (s *Service) SetTaskDeleter(d TaskDeleter) { s.taskDeleter = d } // SetTaskSessionChecker sets the session checker for cleanup operations. func (s *Service) SetTaskSessionChecker(c TaskSessionChecker) { s.taskSessionChecker = c } +// SetSecretManager sets the secret manager for token configuration operations. +func (s *Service) SetSecretManager(m SecretManager) { s.secretManager = m } + // Client returns the underlying GitHub client (may be nil if not authenticated). func (s *Service) Client() Client { return s.client @@ -100,6 +111,9 @@ func (s *Service) AuthMethod() string { return s.authMethod } +// RequiredGitHubScopes lists the GitHub token scopes needed for full functionality. +var RequiredGitHubScopes = []string{"repo", "read:org"} + // GetStatus returns the current GitHub connection status. // If not authenticated, it retries client creation to pick up auth changes // (e.g. GITHUB_TOKEN secret added after startup). @@ -114,8 +128,15 @@ func (s *Service) GetStatus(ctx context.Context) (*GitHubStatus, error) { s.mu.Unlock() status := &GitHubStatus{ - AuthMethod: authMethod, + AuthMethod: authMethod, + RequiredScopes: RequiredGitHubScopes, } + + // Check if a GITHUB_TOKEN secret is configured + tokenSecretID, hasToken := s.findGitHubTokenSecret(ctx) + status.TokenConfigured = hasToken + status.TokenSecretID = tokenSecretID + if client == nil { status.Diagnostics = runGHDiagnostics(ctx) return status, nil @@ -136,6 +157,27 @@ func (s *Service) GetStatus(ctx context.Context) (*GitHubStatus, error) { return status, nil } +// findGitHubTokenSecret checks if a GITHUB_TOKEN secret exists in the secrets store. +// Returns the secret ID and whether a token is configured. +func (s *Service) findGitHubTokenSecret(ctx context.Context) (string, bool) { + if s.secrets == nil { + return "", false + } + items, err := s.secrets.List(ctx) + if err != nil { + return "", false + } + for _, item := range items { + if !item.HasValue { + continue + } + if item.Name == "GITHUB_TOKEN" || item.Name == "github_token" { + return item.ID, true + } + } + return "", false +} + // retryClientCreation attempts to create a GitHub client when not authenticated. // This picks up auth changes made after startup (secrets added, env vars set). func (s *Service) retryClientCreation(ctx context.Context) { @@ -167,6 +209,75 @@ func runGHDiagnostics(ctx context.Context) *AuthDiagnostics { return NewGHClient().RunAuthDiagnostics(ctx) } +// ConfigureToken saves or updates a GitHub Personal Access Token in the secrets store. +// It validates the token by making a test API call before saving. +func (s *Service) ConfigureToken(ctx context.Context, token string) error { + if s.secretManager == nil { + return fmt.Errorf("secret manager not configured") + } + + // Validate the token by testing authentication + testClient := NewPATClient(token) + user, err := testClient.GetAuthenticatedUser(ctx) + if err != nil { + return fmt.Errorf("invalid token: %w", err) + } + s.logger.Info("validated GitHub token", zap.String("user", user)) + + // Check if a GITHUB_TOKEN secret already exists + existingID, exists := s.findGitHubTokenSecret(ctx) + if exists { + // Update existing secret + if err := s.secretManager.Update(ctx, existingID, token); err != nil { + return fmt.Errorf("update token: %w", err) + } + s.logger.Info("updated GitHub token secret", zap.String("id", existingID)) + } else { + // Create new secret + newID, err := s.secretManager.Create(ctx, "GITHUB_TOKEN", token) + if err != nil { + return fmt.Errorf("create token: %w", err) + } + s.logger.Info("created GitHub token secret", zap.String("id", newID)) + } + + // Refresh the client to use the new token + s.mu.Lock() + s.client = testClient + s.authMethod = AuthMethodPAT + s.mu.Unlock() + + return nil +} + +// ClearToken removes the configured GitHub token from the secrets store. +func (s *Service) ClearToken(ctx context.Context) error { + if s.secretManager == nil { + return fmt.Errorf("secret manager not configured") + } + + existingID, exists := s.findGitHubTokenSecret(ctx) + if !exists { + return nil // No token to clear + } + + if err := s.secretManager.Delete(ctx, existingID); err != nil { + return fmt.Errorf("delete token: %w", err) + } + s.logger.Info("cleared GitHub token secret", zap.String("id", existingID)) + + // Reset to try gh CLI or other methods + s.mu.Lock() + s.client = nil + s.authMethod = AuthMethodNone + s.mu.Unlock() + + // Try to re-establish connection via other methods + s.retryClientCreation(ctx) + + return nil +} + // SubmitReview submits a review on a pull request. func (s *Service) SubmitReview(ctx context.Context, owner, repo string, number int, event, body string) error { if s.client == nil { diff --git a/apps/backend/internal/github/service_token_test.go b/apps/backend/internal/github/service_token_test.go new file mode 100644 index 0000000000..4d45d6dbf6 --- /dev/null +++ b/apps/backend/internal/github/service_token_test.go @@ -0,0 +1,264 @@ +package github + +import ( + "context" + "fmt" + "sync" + "testing" + + "github.com/kandev/kandev/internal/common/logger" +) + +// mockSecretManager implements SecretManager for testing. +type mockSecretManager struct { + secrets map[string]string // id -> value + names map[string]string // id -> name + nextID int + mu sync.Mutex +} + +func newMockSecretManager() *mockSecretManager { + return &mockSecretManager{ + secrets: make(map[string]string), + names: make(map[string]string), + } +} + +func (m *mockSecretManager) Create(_ context.Context, name, value string) (string, error) { + m.mu.Lock() + defer m.mu.Unlock() + m.nextID++ + id := fmt.Sprintf("secret-%d", m.nextID) + m.secrets[id] = value + m.names[id] = name + return id, nil +} + +func (m *mockSecretManager) Update(_ context.Context, id, value string) error { + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.secrets[id]; !ok { + return fmt.Errorf("secret not found: %s", id) + } + m.secrets[id] = value + return nil +} + +func (m *mockSecretManager) Delete(_ context.Context, id string) error { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.secrets, id) + delete(m.names, id) + return nil +} + +// mockSecretProvider implements SecretProvider for testing. +type mockSecretProvider struct { + mgr *mockSecretManager +} + +func (m *mockSecretProvider) List(_ context.Context) ([]*SecretListItem, error) { + m.mgr.mu.Lock() + defer m.mgr.mu.Unlock() + var items []*SecretListItem + for id, name := range m.mgr.names { + items = append(items, &SecretListItem{ + ID: id, + Name: name, + HasValue: m.mgr.secrets[id] != "", + }) + } + return items, nil +} + +func (m *mockSecretProvider) Reveal(_ context.Context, id string) (string, error) { + m.mgr.mu.Lock() + defer m.mgr.mu.Unlock() + if val, ok := m.mgr.secrets[id]; ok { + return val, nil + } + return "", fmt.Errorf("secret not found: %s", id) +} + +func TestFindGitHubTokenSecret(t *testing.T) { + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"}) + mgr := newMockSecretManager() + provider := &mockSecretProvider{mgr: mgr} + + svc := &Service{ + secrets: provider, + logger: log, + } + + // No secrets - should return empty + id, found := svc.findGitHubTokenSecret(context.Background()) + if found { + t.Error("expected no token to be found when secrets are empty") + } + if id != "" { + t.Errorf("expected empty id, got %q", id) + } + + // Add a GITHUB_TOKEN secret + secretID, _ := mgr.Create(context.Background(), "GITHUB_TOKEN", "ghp_test123") + + id, found = svc.findGitHubTokenSecret(context.Background()) + if !found { + t.Error("expected token to be found") + } + if id != secretID { + t.Errorf("expected id %q, got %q", secretID, id) + } +} + +func TestFindGitHubTokenSecret_LowerCase(t *testing.T) { + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"}) + mgr := newMockSecretManager() + provider := &mockSecretProvider{mgr: mgr} + + svc := &Service{ + secrets: provider, + logger: log, + } + + // Add a github_token (lowercase) secret + secretID, _ := mgr.Create(context.Background(), "github_token", "ghp_test456") + + id, found := svc.findGitHubTokenSecret(context.Background()) + if !found { + t.Error("expected token to be found with lowercase name") + } + if id != secretID { + t.Errorf("expected id %q, got %q", secretID, id) + } +} + +func TestGetStatus_WithTokenConfigured(t *testing.T) { + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"}) + mgr := newMockSecretManager() + provider := &mockSecretProvider{mgr: mgr} + + // Add a GITHUB_TOKEN secret + secretID, _ := mgr.Create(context.Background(), "GITHUB_TOKEN", "ghp_test789") + + svc := &Service{ + secrets: provider, + logger: log, + authMethod: AuthMethodNone, + } + + status, err := svc.GetStatus(context.Background()) + if err != nil { + t.Fatalf("GetStatus failed: %v", err) + } + + if !status.TokenConfigured { + t.Error("expected TokenConfigured to be true") + } + if status.TokenSecretID != secretID { + t.Errorf("expected TokenSecretID %q, got %q", secretID, status.TokenSecretID) + } + if len(status.RequiredScopes) == 0 { + t.Error("expected RequiredScopes to be populated") + } +} + +func TestGetStatus_WithoutToken(t *testing.T) { + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"}) + mgr := newMockSecretManager() + provider := &mockSecretProvider{mgr: mgr} + + svc := &Service{ + secrets: provider, + logger: log, + authMethod: AuthMethodNone, + } + + status, err := svc.GetStatus(context.Background()) + if err != nil { + t.Fatalf("GetStatus failed: %v", err) + } + + if status.TokenConfigured { + t.Error("expected TokenConfigured to be false") + } + if status.TokenSecretID != "" { + t.Errorf("expected empty TokenSecretID, got %q", status.TokenSecretID) + } +} + +func TestClearToken(t *testing.T) { + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"}) + mgr := newMockSecretManager() + provider := &mockSecretProvider{mgr: mgr} + + // Add a GITHUB_TOKEN secret + _, err := mgr.Create(context.Background(), "GITHUB_TOKEN", "ghp_toberemoved") + if err != nil { + t.Fatalf("failed to create secret: %v", err) + } + + svc := &Service{ + secrets: provider, + secretManager: mgr, + logger: log, + authMethod: AuthMethodPAT, + } + + // Verify token exists + _, found := svc.findGitHubTokenSecret(context.Background()) + if !found { + t.Fatal("expected token to exist before clearing") + } + + // Clear the token + err = svc.ClearToken(context.Background()) + if err != nil { + t.Fatalf("ClearToken failed: %v", err) + } + + // Verify token is gone + _, found = svc.findGitHubTokenSecret(context.Background()) + if found { + t.Error("expected token to be removed after clearing") + } + + // After ClearToken, authMethod should no longer be "pat" (it resets to "none" + // then retryClientCreation may set it to "gh_cli" if gh CLI is available). + if svc.authMethod == AuthMethodPAT { + t.Error("expected authMethod to no longer be PAT after clearing token") + } +} + +func TestClearToken_NoToken(t *testing.T) { + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"}) + mgr := newMockSecretManager() + provider := &mockSecretProvider{mgr: mgr} + + svc := &Service{ + secrets: provider, + secretManager: mgr, + logger: log, + } + + // Clearing when no token exists should not error + err := svc.ClearToken(context.Background()) + if err != nil { + t.Fatalf("ClearToken should not error when no token exists: %v", err) + } +} + +func TestClearToken_NoSecretManager(t *testing.T) { + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"}) + + svc := &Service{ + secrets: nil, + secretManager: nil, + logger: log, + } + + err := svc.ClearToken(context.Background()) + if err == nil { + t.Error("expected error when secretManager is nil") + } +} diff --git a/apps/backend/internal/orchestrator/executor/executor_credentials.go b/apps/backend/internal/orchestrator/executor/executor_credentials.go new file mode 100644 index 0000000000..ac0f26e068 --- /dev/null +++ b/apps/backend/internal/orchestrator/executor/executor_credentials.go @@ -0,0 +1,234 @@ +package executor + +import ( + "context" + "encoding/json" + "fmt" + "os/exec" + "strings" + "time" + + "go.uber.org/zap" +) + +const ( + // envGitHubToken is the environment variable name for GitHub authentication tokens. + envGitHubToken = "GITHUB_TOKEN" + // envGHToken is the gh CLI compatible environment variable name. + envGHToken = "GH_TOKEN" +) + +// injectGitHubToken injects GITHUB_TOKEN and GH_TOKEN into the request env for remote executors. +// It looks for a GITHUB_TOKEN secret in the secrets store and injects it if found. +// Both env vars are set for compatibility: GITHUB_TOKEN for git, GH_TOKEN for gh CLI. +func (e *Executor) injectGitHubToken(ctx context.Context, req *LaunchAgentRequest) { + if req.Env == nil { + req.Env = make(map[string]string) + } + + // Skip if already set (user configured explicitly in profile) + if req.Env[envGitHubToken] != "" || req.Env[envGHToken] != "" { + return + } + + if e.secretStore == nil { + return + } + + // Look for a GITHUB_TOKEN secret in the secrets store + items, err := e.secretStore.List(ctx) + if err != nil { + e.logger.Debug("failed to list secrets for GitHub token injection", zap.Error(err)) + return + } + + var tokenSecretID string + for _, item := range items { + if !item.HasValue { + continue + } + if item.Name == envGitHubToken || item.Name == "github_token" { + tokenSecretID = item.ID + break + } + } + if tokenSecretID == "" { + return + } + + token, err := e.secretStore.Reveal(ctx, tokenSecretID) + if err != nil || token == "" { + e.logger.Debug("failed to reveal GitHub token secret", zap.Error(err)) + return + } + + // Inject both env vars for compatibility + req.Env[envGitHubToken] = token + req.Env[envGHToken] = token + e.logger.Debug("injected GitHub token for remote executor") +} + +// injectGitHubTokenFromCLI is the final fallback that extracts a token from +// the local gh CLI if no other credential source provided a GitHub token. +// This enables "just works" behavior when the user has gh authenticated locally. +func (e *Executor) injectGitHubTokenFromCLI(_ context.Context, req *LaunchAgentRequest) { + if req.Env == nil { + req.Env = make(map[string]string) + } + + // Skip if already set by any previous method + if req.Env[envGitHubToken] != "" || req.Env[envGHToken] != "" { + return + } + + // Try to extract token from local gh CLI + token, err := detectGHToken() + if err != nil { + e.logger.Debug("no GitHub token from local gh CLI", zap.Error(err)) + return + } + + req.Env[envGitHubToken] = token + req.Env[envGHToken] = token + e.logger.Debug("injected GitHub token from local gh CLI") +} + +// resolveRemoteCredentials handles profile-level remote auth credentials. +// It resolves remote_auth_secrets (secret-based env vars like gh_cli_env) +// and remote_credentials (including gh_cli_token which extracts from local gh CLI). +func (e *Executor) resolveRemoteCredentials(ctx context.Context, req *LaunchAgentRequest, metadata map[string]interface{}) { + if req.Env == nil { + req.Env = make(map[string]string) + } + + // 1. Resolve remote_auth_secrets (e.g., gh_cli_env method with a secret ID) + e.resolveAuthSecrets(ctx, req, metadata) + + // 2. Handle gh_cli_token from remote_credentials (extract from local gh CLI) + e.resolveGHCLIToken(req, metadata) +} + +// resolveAuthSecrets reads remote_auth_secrets from metadata and resolves secret values +// into environment variables (e.g., gh_cli_env -> GITHUB_TOKEN). +func (e *Executor) resolveAuthSecrets(ctx context.Context, req *LaunchAgentRequest, metadata map[string]interface{}) { + authSecretsJSON, _ := metadata["remote_auth_secrets"].(string) + if authSecretsJSON == "" { + return + } + + var authSecrets map[string]string + if err := json.Unmarshal([]byte(authSecretsJSON), &authSecrets); err != nil { + e.logger.Debug("failed to parse remote_auth_secrets", zap.Error(err)) + return + } + + for methodID, secretID := range authSecrets { + if secretID == "" { + continue + } + // Map method IDs to env var names + envVar := methodIDToEnvVar(methodID) + if envVar == "" { + continue + } + // Skip if already set + if req.Env[envVar] != "" { + continue + } + if e.secretStore == nil { + continue + } + + value, err := e.secretStore.Reveal(ctx, secretID) + if err != nil { + e.logger.Debug("failed to resolve auth secret", + zap.String("method_id", methodID), + zap.String("secret_id", secretID), + zap.Error(err)) + continue + } + req.Env[envVar] = value + // Also set GH_TOKEN for gh CLI compatibility + if envVar == envGitHubToken { + req.Env[envGHToken] = value + } + e.logger.Debug("resolved remote auth secret", zap.String("env_var", envVar)) + } +} + +// methodIDToEnvVar maps remote auth method IDs to environment variable names. +func methodIDToEnvVar(methodID string) string { + switch methodID { + case "gh_cli_env": + return envGitHubToken + default: + // For agent-specific methods like "agent:claude_code:env:ANTHROPIC_API_KEY" + if strings.HasPrefix(methodID, "agent:") && strings.Contains(methodID, ":env:") { + parts := strings.Split(methodID, ":env:") + if len(parts) == 2 { + return parts[1] + } + } + return "" + } +} + +// resolveGHCLIToken handles gh_cli_token from remote_credentials metadata. +// If selected, it extracts the token from the local gh CLI via `gh auth token`. +func (e *Executor) resolveGHCLIToken(req *LaunchAgentRequest, metadata map[string]interface{}) { + // Skip if either GITHUB_TOKEN or GH_TOKEN is already set (respect profile env vars priority) + if req.Env[envGitHubToken] != "" || req.Env[envGHToken] != "" { + return + } + + credsJSON, _ := metadata["remote_credentials"].(string) + if credsJSON == "" { + return + } + + var credentialIDs []string + if err := json.Unmarshal([]byte(credsJSON), &credentialIDs); err != nil { + e.logger.Debug("failed to parse remote_credentials", zap.Error(err)) + return + } + + // Check if gh_cli_token is selected + hasGHToken := false + for _, id := range credentialIDs { + if id == "gh_cli_token" { + hasGHToken = true + break + } + } + if !hasGHToken { + return + } + + // Extract token from local gh CLI + token, err := detectGHToken() + if err != nil { + e.logger.Debug("failed to detect gh token from local CLI", zap.Error(err)) + return + } + + req.Env[envGitHubToken] = token + req.Env[envGHToken] = token + e.logger.Debug("resolved GITHUB_TOKEN from local gh CLI") +} + +// detectGHToken runs `gh auth token` to extract the GitHub token from the local gh CLI. +func detectGHToken() (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + cmd := exec.CommandContext(ctx, "gh", "auth", "token") + out, err := cmd.Output() + if err != nil { + return "", err + } + token := strings.TrimSpace(string(out)) + if token == "" { + return "", fmt.Errorf("gh auth token returned empty") + } + return token, nil +} diff --git a/apps/backend/internal/orchestrator/executor/executor_credentials_test.go b/apps/backend/internal/orchestrator/executor/executor_credentials_test.go new file mode 100644 index 0000000000..2dcd8a1d37 --- /dev/null +++ b/apps/backend/internal/orchestrator/executor/executor_credentials_test.go @@ -0,0 +1,345 @@ +package executor + +import ( + "context" + "fmt" + "testing" + + "github.com/kandev/kandev/internal/secrets" +) + +func TestIsContainerizedExecutor(t *testing.T) { + tests := []struct { + executorType string + want bool + }{ + {"local_docker", true}, + {"remote_docker", true}, + {"sprites", true}, + {"local", false}, + {"worktree", false}, + {"", false}, + } + + for _, tt := range tests { + t.Run(tt.executorType, func(t *testing.T) { + got := isContainerizedExecutor(tt.executorType) + if got != tt.want { + t.Errorf("isContainerizedExecutor(%q) = %v, want %v", tt.executorType, got, tt.want) + } + }) + } +} + +func TestMethodIDToEnvVar(t *testing.T) { + tests := []struct { + methodID string + want string + }{ + {"gh_cli_env", envGitHubToken}, + {"agent:claude_code:env:ANTHROPIC_API_KEY", "ANTHROPIC_API_KEY"}, + {"agent:openai:env:OPENAI_API_KEY", "OPENAI_API_KEY"}, + {"unknown_method", ""}, + {"", ""}, + {"agent:invalid", ""}, + } + + for _, tt := range tests { + t.Run(tt.methodID, func(t *testing.T) { + got := methodIDToEnvVar(tt.methodID) + if got != tt.want { + t.Errorf("methodIDToEnvVar(%q) = %q, want %q", tt.methodID, got, tt.want) + } + }) + } +} + +func TestResolveAuthSecrets(t *testing.T) { + repo := newMockRepository() + agentManager := &mockAgentManager{} + executor := newTestExecutor(t, agentManager, repo) + + // Set up mock secret store + executor.secretStore = &mockSecretStore{ + secrets: map[string]string{ + "secret-gh": "ghp_testtoken123", + "secret-ai": "sk-test456", + }, + } + + tests := []struct { + name string + metadata map[string]interface{} + existingEnv map[string]string + wantEnv map[string]string + wantGHTokenSet bool + }{ + { + name: "no remote_auth_secrets", + metadata: map[string]interface{}{}, + wantEnv: map[string]string{}, + }, + { + name: "gh_cli_env secret resolved", + metadata: map[string]interface{}{ + "remote_auth_secrets": `{"gh_cli_env": "secret-gh"}`, + }, + wantEnv: map[string]string{ + envGitHubToken: "ghp_testtoken123", + envGHToken: "ghp_testtoken123", + }, + wantGHTokenSet: true, + }, + { + name: "agent env var resolved", + metadata: map[string]interface{}{ + "remote_auth_secrets": `{"agent:test:env:CUSTOM_KEY": "secret-ai"}`, + }, + wantEnv: map[string]string{ + "CUSTOM_KEY": "sk-test456", + }, + }, + { + name: "skip if already set", + metadata: map[string]interface{}{ + "remote_auth_secrets": `{"gh_cli_env": "secret-gh"}`, + }, + existingEnv: map[string]string{ + envGitHubToken: "existing-token", + }, + wantEnv: map[string]string{ + envGitHubToken: "existing-token", // Not overwritten + }, + }, + { + name: "invalid JSON ignored", + metadata: map[string]interface{}{ + "remote_auth_secrets": `{invalid json}`, + }, + wantEnv: map[string]string{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req := &LaunchAgentRequest{ + Env: tt.existingEnv, + } + if req.Env == nil { + req.Env = make(map[string]string) + } + + executor.resolveAuthSecrets(context.Background(), req, tt.metadata) + + for key, wantVal := range tt.wantEnv { + if gotVal := req.Env[key]; gotVal != wantVal { + t.Errorf("env[%q] = %q, want %q", key, gotVal, wantVal) + } + } + }) + } +} + +func TestResolveGHCLIToken(t *testing.T) { + repo := newMockRepository() + agentManager := &mockAgentManager{} + executor := newTestExecutor(t, agentManager, repo) + + tests := []struct { + name string + metadata map[string]interface{} + existingEnv map[string]string + expectSkip bool + }{ + { + name: "no remote_credentials", + metadata: map[string]interface{}{}, + expectSkip: true, + }, + { + name: "gh_cli_token not in list", + metadata: map[string]interface{}{ + "remote_credentials": `["other_credential"]`, + }, + expectSkip: true, + }, + { + name: "skip if GITHUB_TOKEN already set", + metadata: map[string]interface{}{ + "remote_credentials": `["gh_cli_token"]`, + }, + existingEnv: map[string]string{ + envGitHubToken: "existing", + }, + expectSkip: true, + }, + { + name: "skip if GH_TOKEN already set", + metadata: map[string]interface{}{ + "remote_credentials": `["gh_cli_token"]`, + }, + existingEnv: map[string]string{ + envGHToken: "existing-gh-token", + }, + expectSkip: true, + }, + { + name: "invalid JSON ignored", + metadata: map[string]interface{}{ + "remote_credentials": `{invalid}`, + }, + expectSkip: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req := &LaunchAgentRequest{ + Env: tt.existingEnv, + } + if req.Env == nil { + req.Env = make(map[string]string) + } + initialGHToken := req.Env[envGitHubToken] + initialGH := req.Env[envGHToken] + + executor.resolveGHCLIToken(req, tt.metadata) + + if tt.expectSkip { + if req.Env[envGitHubToken] != initialGHToken { + t.Errorf("expected GITHUB_TOKEN to remain %q, got %q", initialGHToken, req.Env[envGitHubToken]) + } + if req.Env[envGHToken] != initialGH { + t.Errorf("expected GH_TOKEN to remain %q, got %q", initialGH, req.Env[envGHToken]) + } + } + }) + } +} + +func TestInjectGitHubToken(t *testing.T) { + repo := newMockRepository() + agentManager := &mockAgentManager{} + executor := newTestExecutor(t, agentManager, repo) + + executor.secretStore = &mockSecretStore{ + secrets: map[string]string{"secret-1": "ghp_globaltoken"}, + names: map[string]string{"secret-1": envGitHubToken}, + } + + t.Run("injects token when not set", func(t *testing.T) { + req := &LaunchAgentRequest{Env: make(map[string]string)} + executor.injectGitHubToken(context.Background(), req) + if req.Env[envGitHubToken] != "ghp_globaltoken" { + t.Errorf("expected GITHUB_TOKEN to be set, got %q", req.Env[envGitHubToken]) + } + if req.Env[envGHToken] != "ghp_globaltoken" { + t.Errorf("expected GH_TOKEN to be set, got %q", req.Env[envGHToken]) + } + }) + + t.Run("skips if GITHUB_TOKEN already set", func(t *testing.T) { + req := &LaunchAgentRequest{Env: map[string]string{envGitHubToken: "existing-token"}} + executor.injectGitHubToken(context.Background(), req) + if req.Env[envGitHubToken] != "existing-token" { + t.Errorf("expected GITHUB_TOKEN to remain unchanged, got %q", req.Env[envGitHubToken]) + } + }) + + t.Run("skips if GH_TOKEN already set", func(t *testing.T) { + req := &LaunchAgentRequest{Env: map[string]string{envGHToken: "existing-gh-token"}} + executor.injectGitHubToken(context.Background(), req) + if req.Env[envGitHubToken] != "" { + t.Errorf("expected GITHUB_TOKEN to not be injected when GH_TOKEN is set, got %q", req.Env[envGitHubToken]) + } + }) +} + +func TestInjectGitHubTokenFromCLI(t *testing.T) { + repo := newMockRepository() + agentManager := &mockAgentManager{} + executor := newTestExecutor(t, agentManager, repo) + + t.Run("skips if GITHUB_TOKEN already set", func(t *testing.T) { + req := &LaunchAgentRequest{Env: map[string]string{envGitHubToken: "existing-token"}} + executor.injectGitHubTokenFromCLI(context.Background(), req) + if req.Env[envGitHubToken] != "existing-token" { + t.Errorf("expected GITHUB_TOKEN to remain unchanged, got %q", req.Env[envGitHubToken]) + } + }) + + t.Run("skips if GH_TOKEN already set", func(t *testing.T) { + req := &LaunchAgentRequest{Env: map[string]string{envGHToken: "existing-gh-token"}} + executor.injectGitHubTokenFromCLI(context.Background(), req) + if req.Env[envGHToken] != "existing-gh-token" { + t.Errorf("expected GH_TOKEN to remain unchanged, got %q", req.Env[envGHToken]) + } + }) +} + +// mockSecretStore implements secrets.SecretStore for testing +type mockSecretStore struct { + secrets map[string]string // id -> value + names map[string]string // id -> name +} + +func (m *mockSecretStore) Create(_ context.Context, secret *secrets.SecretWithValue) error { + if m.secrets == nil { + m.secrets = make(map[string]string) + } + if m.names == nil { + m.names = make(map[string]string) + } + m.secrets[secret.ID] = secret.Value + m.names[secret.ID] = secret.Name + return nil +} + +func (m *mockSecretStore) Get(_ context.Context, id string) (*secrets.Secret, error) { + if name, ok := m.names[id]; ok { + return &secrets.Secret{ID: id, Name: name}, nil + } + return nil, fmt.Errorf("secret not found") +} + +func (m *mockSecretStore) Reveal(_ context.Context, id string) (string, error) { + if val, ok := m.secrets[id]; ok { + return val, nil + } + return "", fmt.Errorf("secret not found") +} + +func (m *mockSecretStore) Update(_ context.Context, id string, req *secrets.UpdateSecretRequest) error { + if _, ok := m.secrets[id]; !ok { + return fmt.Errorf("secret not found") + } + if req.Value != nil { + m.secrets[id] = *req.Value + } + if req.Name != nil { + m.names[id] = *req.Name + } + return nil +} + +func (m *mockSecretStore) Delete(_ context.Context, id string) error { + delete(m.secrets, id) + delete(m.names, id) + return nil +} + +func (m *mockSecretStore) List(_ context.Context) ([]*secrets.SecretListItem, error) { + var items []*secrets.SecretListItem + for id, name := range m.names { + items = append(items, &secrets.SecretListItem{ + ID: id, + Name: name, + HasValue: m.secrets[id] != "", + }) + } + return items, nil +} + +func (m *mockSecretStore) Close() error { + return nil +} diff --git a/apps/backend/internal/orchestrator/executor/executor_execute.go b/apps/backend/internal/orchestrator/executor/executor_execute.go index 9494d256ab..a2e20d1985 100644 --- a/apps/backend/internal/orchestrator/executor/executor_execute.go +++ b/apps/backend/internal/orchestrator/executor/executor_execute.go @@ -28,6 +28,18 @@ func isConfigModeSession(session *models.TaskSession) bool { return ok && cm } +// isContainerizedExecutor returns true for executor types that run in containers. +// These executors need GitHub token injection for git operations since they don't +// have access to the host's git credentials. +func isContainerizedExecutor(executorType string) bool { + switch models.ExecutorType(executorType) { + case models.ExecutorTypeLocalDocker, models.ExecutorTypeRemoteDocker, models.ExecutorTypeSprites: + return true + default: + return false + } +} + // runAgentProcessAsync starts the agent subprocess in a background goroutine. // On error it marks both the session and task as FAILED. // On success it calls onSuccess with a non-cancellable context derived from ctx. @@ -517,6 +529,41 @@ func (e *Executor) buildLaunchAgentRequest(ctx context.Context, task *v1.Task, s } } + // For containerized executors, resolve credentials in this order: + // 1. Profile remote_auth_secrets (e.g., gh_cli_env method with secret) + // 2. Profile remote_credentials with gh_cli_token (extract from local gh CLI) + // 3. Global GITHUB_TOKEN secret (fallback) + // 4. Auto-extract from local gh CLI (final fallback) + if isContainerizedExecutor(execConfig.ExecutorType) { + e.applyContainerCredentials(ctx, req, metadata) + } + + metadata, err := e.applyRepositoryConfig(req, task, repoInfo, execConfig, metadata) + if err != nil { + return nil, execConfig, err + } + + // Activate config-mode MCP tools when config_mode is set in session metadata. + if isConfigModeSession(session) { + req.McpMode = McpModeConfig + } + + if len(metadata) > 0 { + req.Metadata = metadata + } + + return req, execConfig, nil +} + +// applyContainerCredentials resolves and injects credentials for containerized executors. +func (e *Executor) applyContainerCredentials(ctx context.Context, req *LaunchAgentRequest, metadata map[string]interface{}) { + e.resolveRemoteCredentials(ctx, req, metadata) + e.injectGitHubToken(ctx, req) // Fallback to global secret + e.injectGitHubTokenFromCLI(ctx, req) // Final fallback to local gh CLI +} + +// applyRepositoryConfig sets repository-related fields on the request and resolves clone URLs. +func (e *Executor) applyRepositoryConfig(req *LaunchAgentRequest, task *v1.Task, repoInfo *repoInfo, execConfig executorConfig, metadata map[string]interface{}) (map[string]interface{}, error) { if repoInfo.RepositoryPath != "" { req.UseWorktree = shouldUseWorktree(execConfig.ExecutorType) req.RepositoryPath = repoInfo.RepositoryPath @@ -541,21 +588,12 @@ func (e *Executor) buildLaunchAgentRequest(ctx context.Context, task *v1.Task, s if e.capabilities != nil && e.capabilities.RequiresCloneURL(execConfig.ExecutorType) && repoInfo.Repository != nil { cloneURL := repositoryCloneURL(repoInfo.Repository) if cloneURL == "" { - return nil, execConfig, ErrNoCloneURL + return metadata, ErrNoCloneURL } req.RepositoryURL = cloneURL } - // Activate config-mode MCP tools when config_mode is set in session metadata. - if isConfigModeSession(session) { - req.McpMode = McpModeConfig - } - - if len(metadata) > 0 { - req.Metadata = metadata - } - - return req, execConfig, nil + return metadata, nil } // startAgentOnExistingWorkspace handles the case where LaunchPreparedSession is called on a session diff --git a/apps/backend/internal/scriptengine/placeholders.go b/apps/backend/internal/scriptengine/placeholders.go index 1a8c03b972..0bc23c563f 100644 --- a/apps/backend/internal/scriptengine/placeholders.go +++ b/apps/backend/internal/scriptengine/placeholders.go @@ -124,4 +124,10 @@ var DefaultPlaceholders = []PlaceholderInfo{ Example: "8765", ExecutorTypes: []string{"local_docker", "remote_docker", "sprites"}, }, + { + Key: "github.auth_setup", + Description: "Expands to commands that configure gh CLI and git credential helper for GitHub token auth", + Example: "git config --global credential.https://github.com.helper '...'", + ExecutorTypes: []string{"local_docker", "remote_docker", "sprites"}, + }, } diff --git a/apps/backend/internal/scriptengine/providers.go b/apps/backend/internal/scriptengine/providers.go index 6b11f4637c..d371e8cf15 100644 --- a/apps/backend/internal/scriptengine/providers.go +++ b/apps/backend/internal/scriptengine/providers.go @@ -166,3 +166,41 @@ func AgentInstallProvider(installScripts []string) PlaceholderProvider { func shellSingleQuote(value string) string { return strings.ReplaceAll(value, "'", `'"'"'`) } + +// GitHubAuthProvider returns placeholders for GitHub authentication setup. +// It configures both the gh CLI and git credential helper to use the GitHub token. +func GitHubAuthProvider(env map[string]string) PlaceholderProvider { + return func() map[string]string { + vars := map[string]string{ + "github.auth_setup": "", + } + + // Check for GitHub token in env (either GH_TOKEN or GITHUB_TOKEN) + token := env["GH_TOKEN"] + if token == "" { + token = env["GITHUB_TOKEN"] + } + if token == "" { + // No token - output fallback commands that may work if gh is pre-authenticated + vars["github.auth_setup"] = `# No GitHub token configured - trying fallback methods +gh auth setup-git 2>/dev/null || true +gh config set git_protocol https --host github.com 2>/dev/null || true` + return vars + } + + // Build auth setup script that configures both gh CLI and git + // Use /bin/sh (not /bin/bash) for Alpine compatibility + // Use ${GH_TOKEN:-${GITHUB_TOKEN}} to support either env var being set + lines := []string{ + "# GitHub token authentication", + "# Configure git credential helper for GitHub HTTPS authentication", + `git config --global credential.https://github.com.helper '!/bin/sh -c "echo username=x-access-token; echo password=${GH_TOKEN:-${GITHUB_TOKEN}}"'`, + "# Configure gh CLI to use HTTPS protocol", + "gh config set git_protocol https --host github.com 2>/dev/null || true", + "# Register gh as git credential helper (backup method)", + "gh auth setup-git 2>/dev/null || true", + } + vars["github.auth_setup"] = strings.Join(lines, "\n") + return vars + } +} diff --git a/apps/backend/internal/scriptengine/providers_test.go b/apps/backend/internal/scriptengine/providers_test.go index d6006c2e64..c6156fe59f 100644 --- a/apps/backend/internal/scriptengine/providers_test.go +++ b/apps/backend/internal/scriptengine/providers_test.go @@ -1,6 +1,7 @@ package scriptengine import ( + "strings" "testing" ) @@ -51,3 +52,74 @@ func TestRepositoryProvider_UsesRepositorySetupScriptKey(t *testing.T) { t.Fatalf("repository.setup_script = %q, want %q", got, "npm ci") } } + +func TestGitHubAuthProvider(t *testing.T) { + t.Run("nil env returns fallback commands", func(t *testing.T) { + provider := GitHubAuthProvider(nil) + vars := provider() + setup := vars["github.auth_setup"] + if !strings.Contains(setup, "fallback") { + t.Errorf("expected fallback comment, got %q", setup) + } + if strings.Contains(setup, "credential") { + t.Error("expected no credential helper when no token") + } + }) + + t.Run("empty env returns fallback commands", func(t *testing.T) { + provider := GitHubAuthProvider(map[string]string{}) + vars := provider() + setup := vars["github.auth_setup"] + if !strings.Contains(setup, "fallback") { + t.Errorf("expected fallback comment, got %q", setup) + } + }) + + t.Run("GH_TOKEN present configures credential helper", func(t *testing.T) { + provider := GitHubAuthProvider(map[string]string{"GH_TOKEN": "ghp_test123"}) + vars := provider() + setup := vars["github.auth_setup"] + if !strings.Contains(setup, "credential.https://github.com.helper") { + t.Errorf("expected credential helper, got %q", setup) + } + // Must use /bin/sh, not /bin/bash + if strings.Contains(setup, "/bin/bash") { + t.Error("expected /bin/sh, not /bin/bash") + } + if !strings.Contains(setup, "/bin/sh") { + t.Error("expected /bin/sh in credential helper") + } + // Token must NOT be hardcoded in the output script + if strings.Contains(setup, "ghp_test123") { + t.Error("token value must not appear literally in the script") + } + // Must use env var fallback pattern + if !strings.Contains(setup, "${GH_TOKEN:-${GITHUB_TOKEN}}") { + t.Error("expected ${GH_TOKEN:-${GITHUB_TOKEN}} fallback pattern") + } + }) + + t.Run("GITHUB_TOKEN fallback configures credential helper", func(t *testing.T) { + provider := GitHubAuthProvider(map[string]string{"GITHUB_TOKEN": "ghp_fallback"}) + vars := provider() + setup := vars["github.auth_setup"] + if !strings.Contains(setup, "credential.https://github.com.helper") { + t.Errorf("expected credential helper with GITHUB_TOKEN fallback, got %q", setup) + } + if strings.Contains(setup, "ghp_fallback") { + t.Error("token value must not appear literally in the script") + } + }) + + t.Run("includes gh CLI setup", func(t *testing.T) { + provider := GitHubAuthProvider(map[string]string{"GH_TOKEN": "ghp_test"}) + vars := provider() + setup := vars["github.auth_setup"] + if !strings.Contains(setup, "gh config set git_protocol https") { + t.Error("expected gh CLI protocol config") + } + if !strings.Contains(setup, "gh auth setup-git") { + t.Error("expected gh auth setup-git backup") + } + }) +} diff --git a/apps/backend/internal/task/models/models.go b/apps/backend/internal/task/models/models.go index 5fc02b23fd..946905d7fe 100644 --- a/apps/backend/internal/task/models/models.go +++ b/apps/backend/internal/task/models/models.go @@ -393,10 +393,11 @@ const ( ) // IsRemoteExecutorType reports whether the given executor type represents -// a remote execution environment. +// a remote execution environment (including containerized environments like Docker). +// These environments run shells inside the container/VM, not on the host. func IsRemoteExecutorType(t ExecutorType) bool { switch t { - case ExecutorTypeSprites, ExecutorTypeRemoteDocker, ExecutorTypeMockRemote: + case ExecutorTypeSprites, ExecutorTypeRemoteDocker, ExecutorTypeLocalDocker, ExecutorTypeMockRemote: return true default: return false diff --git a/apps/web/components/github/github-status.tsx b/apps/web/components/github/github-status.tsx index cf820df81a..83cf29b9f6 100644 --- a/apps/web/components/github/github-status.tsx +++ b/apps/web/components/github/github-status.tsx @@ -1,10 +1,22 @@ "use client"; -import { IconCheck, IconX, IconRefresh } from "@tabler/icons-react"; +import { useState, useCallback } from "react"; +import { + IconCheck, + IconX, + IconRefresh, + IconKey, + IconTrash, + IconEye, + IconEyeOff, +} from "@tabler/icons-react"; import { Badge } from "@kandev/ui/badge"; import { Button } from "@kandev/ui/button"; +import { Input } from "@kandev/ui/input"; import { Spinner } from "@kandev/ui/spinner"; import { useGitHubStatus } from "@/hooks/domains/github/use-github-status"; +import { useToast } from "@/components/toast-provider"; +import { configureGitHubToken, clearGitHubToken } from "@/lib/api/domains/github-api"; import type { AuthDiagnostics } from "@/lib/types/github"; function DiagnosticsOutput({ diagnostics }: { diagnostics: AuthDiagnostics }) { @@ -31,8 +43,102 @@ function DiagnosticsOutput({ diagnostics }: { diagnostics: AuthDiagnostics }) { ); } +function TokenConfigForm({ onSuccess }: { onSuccess: () => void }) { + const [token, setToken] = useState(""); + const [showToken, setShowToken] = useState(false); + const [saving, setSaving] = useState(false); + const { toast } = useToast(); + + const handleSubmit = useCallback( + async (e: React.FormEvent) => { + e.preventDefault(); + if (!token.trim()) return; + + setSaving(true); + try { + await configureGitHubToken(token.trim()); + toast({ description: "GitHub token configured successfully", variant: "success" }); + setToken(""); + onSuccess(); + } catch (err) { + const message = err instanceof Error ? err.message : "Failed to configure token"; + toast({ description: message, variant: "error" }); + } finally { + setSaving(false); + } + }, + [token, toast, onSuccess], + ); + + return ( +
+ ); +} + export function GitHubStatusCard() { const { status, loaded, loading, refresh } = useGitHubStatus(); + const { toast } = useToast(); + const [clearing, setClearing] = useState(false); + + const handleClearToken = useCallback(async () => { + setClearing(true); + try { + await clearGitHubToken(); + toast({ description: "GitHub token removed", variant: "success" }); + refresh(); + } catch { + toast({ description: "Failed to clear token", variant: "error" }); + } finally { + setClearing(false); + } + }, [toast, refresh]); if (loading || !loaded) { return ( @@ -45,7 +151,7 @@ export function GitHubStatusCard() { if (!status || !status.authenticated) { return ( -Connect using one of these methods:
-Configure GitHub Token
+Other authentication methods:
+GITHUB_TOKEN or{" "}
- GH_TOKEN when starting Kandev
+ GITHUB_TOKEN when starting Kandev
GITHUB_TOKEN in{" "}
-
- Settings > Secrets
-
- , then click Refresh above
- gh and run{" "}
+ GitHub CLI — run{" "}
gh auth login
+ Token stored in secrets. This token is used by remote agents for GitHub operations. +
+ )}