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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions internal/runner/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -969,6 +969,9 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask)
return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("prepare git credentials: %v", gitErr)}, nil
}
defer cleanup()
if prepared.Command.Provider == "codex" {
argv = runtime.CodexRunGitArgv(argv, gitEnv)
}
for key, value := range gitEnv {
commandEnv[key] = value
}
Expand Down
8 changes: 6 additions & 2 deletions internal/runtime/git_ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,18 @@ func BindGitSSH(ctx context.Context, sandbox Sandbox, workspace string, environm
return gitwork.StartSSH(ctx, environment, keys, root, clientRoot)
}

func bindCommandGitSSH(ctx context.Context, sandbox Sandbox, workspace string, command CommandSpec, credentials RunCredentials) (func(), error) {
func bindCommandGitTransport(ctx context.Context, sandbox Sandbox, workspace string, command *CommandSpec, credentials RunCredentials) (func(), error) {
if slices.Contains(command.CredentialBindings, BindGitWorkspace) {
return bindWorkspaceGitSSH(ctx, sandbox, filepath.Clean(workspace), command.environment, credentials.GitSSHHostKeys)
}
if !slices.Contains(command.CredentialBindings, BindGit) {
return func() {}, nil
}
return BindGitSSH(ctx, sandbox, filepath.Clean(workspace), command.environment, credentials.GitSSHKeys)
stop, err := BindGitSSH(ctx, sandbox, filepath.Clean(workspace), command.environment, credentials.GitSSHKeys)
if err == nil && command.Provider == "codex" {
command.Argv = CodexRunGitArgv(command.Argv, command.environment)
}
return stop, err
}

// bindWorkspaceGitSSH starts the requester's SSH agent for every configured
Expand Down
47 changes: 47 additions & 0 deletions internal/runtime/provider_codex.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package runtime

import (
"encoding/json"
"fmt"
goruntime "runtime"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -115,6 +117,9 @@ func codexIsolationEnvKey(key string) bool {
return false
}
upper := strings.ToUpper(key)
if upper == SessionGatewayEnv || upper == GitHostsEnv {
return false // supplied by the live Git binding, never by profile set.*
}
if upper == "GIT_CEILING_DIRECTORIES" {
return true // a non-secret workspace boundary, needed by tool shells
}
Expand All @@ -131,6 +136,48 @@ func codexIsolationEnvKey(key string) bool {
}
}

// CodexRunGitArgv lets a SOP tool shell inherit its live Git binding by name.
// The per-command relay URL must stay out of argv and persisted Codex config.
func CodexRunGitArgv(argv []string, gitEnv map[string]string) []string {
if len(argv) < 2 || gitEnv[SessionGatewayEnv] == "" || gitEnv[GitHostsEnv] == "" {
return argv
}

// Codex applies include_only after set. Keep its core environment and
// the explicit isolation overrides already prepared for this invocation.
allowed := strings.Fields("PATH SHELL TMPDIR TEMP TMP HOME LANG LC_ALL LC_CTYPE LOGNAME USER")
if goruntime.GOOS == "windows" {
allowed = append(allowed, strings.Fields("PATHEXT COMSPEC SYSTEMROOT WINDIR SYSTEMDRIVE USERNAME USERDOMAIN USERPROFILE HOMEDRIVE HOMEPATH PROGRAMFILES PROGRAMFILES(X86) PROGRAMW6432 PROGRAMDATA LOCALAPPDATA APPDATA POWERSHELL PWSH")...)
}
for i := 1; i < len(argv)-1; i++ {
if argv[i-1] == "-c" && strings.HasPrefix(argv[i], "shell_environment_policy.set.") {
key, _, ok := strings.Cut(strings.TrimPrefix(argv[i], "shell_environment_policy.set."), "=")
if ok && codexIsolationEnvKey(key) && !strings.ContainsAny(key, "*?[]") {
allowed = append(allowed, key)
}
}
}
// SSH appends one URL rewrite per remote after the HTTPS helper entries.
count, _ := strconv.Atoi(gitEnv["GIT_CONFIG_COUNT"])
for i := range count {
suffix := strconv.Itoa(i)
allowed = append(allowed, "GIT_CONFIG_KEY_"+suffix, "GIT_CONFIG_VALUE_"+suffix)
}
for _, key := range []string{SessionGatewayEnv, GitHostsEnv, "GIT_TERMINAL_PROMPT",
"GIT_CONFIG_COUNT", "GIT_SSH_COMMAND", "GIT_SSH_VARIANT", "GIT_ALLOW_PROTOCOL",
"GIT_CONFIG_SYSTEM", "GIT_CONFIG_NOSYSTEM", "GH_CONFIG_DIR", "GLAB_CONFIG_DIR"} {
if _, bound := gitEnv[key]; bound {
allowed = append(allowed, key)
}
}
names, _ := json.Marshal(allowed)
out := append([]string{}, argv[:len(argv)-1]...)
out = append(out, "-c", `shell_environment_policy.inherit="all"`,
"-c", "shell_environment_policy.ignore_default_excludes=true",
"-c", "shell_environment_policy.include_only="+string(names))
return append(out, argv[len(argv)-1])
}

func (codexProvider) Protocol(ex domain.ExecutorDefinition, sink EventSink) *protocolAdapter {
return makeProtocolAdapter(ex, sink, protocolCodex, "codex-jsonl-v1")
}
Expand Down
106 changes: 106 additions & 0 deletions internal/runtime/run_git_credentials_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package runtime

import (
"context"
"encoding/json"
"net/http"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -71,3 +74,106 @@ func testHTTPSCredentials(token string) map[string]domain.GitHTTPExecutionCreden
}
return result
}

func TestCodexSOPGitBindingKeepsHelperInToolShell(t *testing.T) {
workspace := t.TempDir()
sandbox := &localSandbox{workspace: workspace}
const token = "fixture-sop-token"
credentials := RunCredentials{GitHTTPCredentials: testHTTPSCredentials(token), GitSSHKeys: terminalSSHTestKeys(t)}
credentials.GitSSHKeys["git@git.example.org:team/other.git"] = ""
command := CommandSpec{
Provider: "codex", Argv: withCodexIsolationEnv([]string{"codex", "exec", "prompt"}, map[string]string{
"ZDOTDIR": "/fixture/zdot", SessionGatewayEnv: "stale-profile-gateway", GitHostsEnv: "stale-profile-hosts",
}),
CredentialBindings: []CredentialBinding{BindGit},
}
bind := func(cmd CommandSpec, creds RunCredentials) CommandSpec {
t.Helper()
bound, err := bindCommand(t.Context(), sandbox, workspace, cmd, creds)
if err != nil {
t.Fatal(err)
}
stop, err := bindCommandGitTransport(t.Context(), sandbox, workspace, &bound, creds)
if err != nil {
t.Fatal(err)
}
t.Cleanup(stop)
return bound
}
sshOnly := bind(command, RunCredentials{GitSSHKeys: credentials.GitSSHKeys})
if !slices.Equal(sshOnly.Argv, command.Argv) {
t.Fatal("Codex policy changed without HTTPS credentials")
}
prepared, closeRelay, err := prepareRunGitBinding(t.Context(), sandbox, command, credentials)
if err != nil {
t.Fatal(err)
}
defer closeRelay()
credentials.GitHTTPHosts = runGitHosts(credentials)
bound := bind(prepared, credentials)
conversation := prepared
conversation.CredentialBindings = []CredentialBinding{BindGitWorkspace}
workspaceCommand := bind(conversation, credentials)
if !slices.Equal(workspaceCommand.Argv, command.Argv) {
t.Fatal("conversation Git binding changed Codex arguments")
}
var names []string
for _, arg := range bound.Argv {
if raw, ok := strings.CutPrefix(arg, "shell_environment_policy.include_only="); ok {
if err := json.Unmarshal([]byte(raw), &names); err != nil {
t.Fatal(err)
}
}
if strings.Contains(arg, token) || strings.Contains(arg, "stale-profile-") || strings.Contains(arg, bound.environment[SessionGatewayEnv]) {
t.Fatal("credential or relay URL in Codex arguments")
}
}
if !slices.Contains(names, "ZDOTDIR") || !slices.Contains(names, "PATH") || !containsArgPair(bound.Argv, "-c", `shell_environment_policy.inherit="all"`) {
t.Fatalf("missing Codex shell configuration: %v", names)
}
for _, key := range names {
if strings.ContainsAny(key, "*?[]") || key == "CODEX_API_KEY" || key == "GITHUB_TOKEN" {
t.Fatalf("unexpected inherited environment key %q", key)
}
}
// Use only the names Codex will pass to Git, including the empty helper
// reset. A pre-existing repository helper must not answer for another host.
git := func(input string, args ...string) ([]byte, error) {
cmd := exec.Command("git", args...)
cmd.Dir = workspace
cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir(), "GIT_CONFIG_NOSYSTEM=1"}
for _, key := range names {
if value, ok := bound.environment[key]; ok {
cmd.Env = append(cmd.Env, key+"="+value)
}
}
cmd.Stdin = strings.NewReader(input)
return cmd.CombinedOutput()
}
if out, err := git("", "init", "-q"); err != nil {
t.Fatalf("git init: %v: %s", err, out)
}
if out, err := git("", "status", "--short"); err != nil {
t.Fatalf("git status: %v: %s", err, out)
}
url, err := git("", "ls-remote", "--get-url", "git@git.example.org:team/app.git")
if err != nil || !strings.HasPrefix(string(url), "git@lf-") {
t.Fatalf("missing SSH remote rewrite: %q, %v", url, err)
}
for _, key := range []string{"GIT_SSH_COMMAND", "GIT_SSH_VARIANT", "GIT_ALLOW_PROTOCOL"} {
if !slices.Contains(names, key) {
t.Fatalf("missing SSH binding %s", key)
}
}
if _, err := git("", "config", "credential.helper", "!echo username=stale; echo password=stale"); err != nil {
t.Fatal(err)
}
got, err := git("protocol=https\nhost=git.example.com\n\n", "credential", "fill")
if err != nil || !strings.Contains(string(got), "password="+token) {
t.Fatalf("configured host did not get its SOP credential: %v", err)
}
got, err = git("protocol=https\nhost=unconfigured.invalid\n\n", "credential", "fill")
if err == nil || strings.Contains(string(got), "password=") {
t.Fatal("unconfigured host obtained a Git credential")
}
}
2 changes: 1 addition & 1 deletion internal/runtime/sandbox_local.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func ExecuteLocalCommand(ctx context.Context, workspace string, command CommandS
if err != nil {
return "", err
}
stopSSH, err := bindCommandGitSSH(ctx, sandbox, workspace, bound, credentials)
stopSSH, err := bindCommandGitTransport(ctx, sandbox, workspace, &bound, credentials)
if err != nil {
return "", err
}
Expand Down
2 changes: 1 addition & 1 deletion internal/runtime/sandbox_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ func (s *managedSandbox) Exec(ctx context.Context, command CommandSpec, sink Eve
if err != nil {
return "", err
}
cleanup, err := bindCommandGitSSH(ctx, s.Sandbox, s.workspace, bound, credentials)
cleanup, err := bindCommandGitTransport(ctx, s.Sandbox, s.workspace, &bound, credentials)
if err != nil {
return "", err
}
Expand Down