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
14 changes: 14 additions & 0 deletions app/cli/cmd/trace_init.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,20 @@ cannot use them with --local. You can use --require-trace with --local.`,
return err
}

// The harness hooks are written relative to the repository root,
// so a root that is the user's home directory would rewrite the
// agent's user-level configuration (for example
// ~/.claude/settings.json) and the hooks would load in every
// session of that agent, in any project. Refuse before asking
// anything or writing anything.
userLevel, err := trace.IsUserLevelRoot(repoRoot)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The new trace init refusal has no command-level regression test. Add a test that runs newTraceInitCmd in a Git repository whose root is HOME (and checks that no hooks or .chainloop.yml are written), so this safety guard cannot be bypassed without detection.

(Based on your team's feedback about covering the real path and the step under test.) [4783126a-1127-49bd-9b99-f3d2848cd202]

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/cli/cmd/trace_init.go, line 112:

<comment>The new `trace init` refusal has no command-level regression test. Add a test that runs `newTraceInitCmd` in a Git repository whose root is `HOME` (and checks that no hooks or `.chainloop.yml` are written), so this safety guard cannot be bypassed without detection.

(Based on your team's feedback about covering the real path and the step under test.) [4783126a-1127-49bd-9b99-f3d2848cd202]</comment>

<file context>
@@ -103,6 +103,20 @@ cannot use them with --local. You can use --require-trace with --local.`,
+			// ~/.claude/settings.json) and the hooks would load in every
+			// session of that agent, in any project. Refuse before asking
+			// anything or writing anything.
+			userLevel, err := trace.IsUserLevelRoot(repoRoot)
+			if err != nil {
+				return fmt.Errorf("check repository root: %w", err)
</file context>

if err != nil {
return fmt.Errorf("check repository root: %w", err)
}
if userLevel {
return fmt.Errorf("refusing to initialize tracing in %q: that is a user-level directory, so the agent hooks would load in every session; run `chainloop trace init` inside a project repository instead", repoRoot)
}

// Local mode contacts no control plane, so the control-plane
// identity and workflow flags are contradictions rather than extra
// configuration. --require-trace is orthogonal and allowed.
Expand Down
88 changes: 88 additions & 0 deletions app/cli/internal/trace/userlevel.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
//
// Copyright 2026 The Chainloop Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package trace

import (
"os"
"path/filepath"
)

// IsUserLevelRoot reports whether root is a user-level directory: the user's
// home directory, or an agent's user-level configuration folder ($CODEX_HOME,
// $COPILOT_HOME, defaulting to ~/.codex and ~/.copilot).
//
// Trace installs agent hooks as files relative to the repository root, so a
// root that is the home directory would write the agent's user-level
// configuration (for example ~/.claude/settings.json) and the hooks would
// load in every session of that agent, in any project, instead of only in
// this repository. Callers should refuse such a root before installing
// anything. Symlinks are resolved on both sides, so a symlinked home
// directory is still caught.
func IsUserLevelRoot(root string) (bool, error) {
resolvedRoot, err := resolveDir(root)
if err != nil {
return false, err
}

for _, candidate := range userLevelDirs() {
resolved, err := resolveDir(candidate)
if err != nil {
continue
}
if resolvedRoot == resolved {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: String equality can miss the same directory on case-insensitive filesystems because symlink evaluation does not canonicalize case. A case-variant spelling of the home directory can therefore bypass this refusal and install hooks globally; compare the existing directories by filesystem identity, such as os.SameFile, instead.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/cli/internal/trace/userlevel.go, line 45:

<comment>String equality can miss the same directory on case-insensitive filesystems because symlink evaluation does not canonicalize case. A case-variant spelling of the home directory can therefore bypass this refusal and install hooks globally; compare the existing directories by filesystem identity, such as `os.SameFile`, instead.</comment>

<file context>
@@ -0,0 +1,88 @@
+		if err != nil {
+			continue
+		}
+		if resolvedRoot == resolved {
+			return true, nil
+		}
</file context>

return true, nil
}
}

return false, nil
}

// resolveDir returns the absolute path of dir with symlinks evaluated. When
// the path does not exist yet, EvalSymlinks fails and the cleaned absolute
// path is used instead, so callers can still compare it.
func resolveDir(path string) (string, error) {
abs, err := filepath.Abs(path)
if err != nil {
return "", err
}
if resolved, err := filepath.EvalSymlinks(abs); err == nil {
return resolved, nil
}
return abs, nil
}

// userLevelDirs lists the directories whose contents an agent loads for every
// session: the user's home directory first, then the agent-specific home
// folders where they apply.
func userLevelDirs() []string {
home, err := os.UserHomeDir()
if err != nil || home == "" {
return nil
}

dirs := []string{home}
if codexHome := os.Getenv("CODEX_HOME"); codexHome != "" {
dirs = append(dirs, codexHome)
} else {
dirs = append(dirs, filepath.Join(home, ".codex"))
}
if copilotHome := os.Getenv("COPILOT_HOME"); copilotHome != "" {
dirs = append(dirs, copilotHome)
} else {
dirs = append(dirs, filepath.Join(home, ".copilot"))
}
return dirs
}
Comment on lines +72 to +88

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: userLevelDirs stops before examining custom homes when os.UserHomeDir is unavailable. With CODEX_HOME or COPILOT_HOME set but no discoverable user home, a root equal to that configured user-level folder passes the guard and can receive hooks; add custom candidates independently and use defaults only when the home is known.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/cli/internal/trace/userlevel.go, line 72:

<comment>`userLevelDirs` stops before examining custom homes when `os.UserHomeDir` is unavailable. With `CODEX_HOME` or `COPILOT_HOME` set but no discoverable user home, a root equal to that configured user-level folder passes the guard and can receive hooks; add custom candidates independently and use defaults only when the home is known.</comment>

<file context>
@@ -0,0 +1,88 @@
+// folders where they apply.
+func userLevelDirs() []string {
+	home, err := os.UserHomeDir()
+	if err != nil || home == "" {
+		return nil
+	}
</file context>
Suggested change
if err != nil || home == "" {
return nil
}
dirs := []string{home}
if codexHome := os.Getenv("CODEX_HOME"); codexHome != "" {
dirs = append(dirs, codexHome)
} else {
dirs = append(dirs, filepath.Join(home, ".codex"))
}
if copilotHome := os.Getenv("COPILOT_HOME"); copilotHome != "" {
dirs = append(dirs, copilotHome)
} else {
dirs = append(dirs, filepath.Join(home, ".copilot"))
}
return dirs
}
home, err := os.UserHomeDir()
if err != nil {
home = ""
}
dirs := make([]string, 0, 3)
if home != "" {
dirs = append(dirs, home)
}
if codexHome := os.Getenv("CODEX_HOME"); codexHome != "" {
dirs = append(dirs, codexHome)
} else if home != "" {
dirs = append(dirs, filepath.Join(home, ".codex"))
}
if copilotHome := os.Getenv("COPILOT_HOME"); copilotHome != "" {
dirs = append(dirs, copilotHome)
} else if home != "" {
dirs = append(dirs, filepath.Join(home, ".copilot"))
}
return dirs

81 changes: 81 additions & 0 deletions app/cli/internal/trace/userlevel_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
//
// Copyright 2026 The Chainloop Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package trace

import (
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestIsUserLevelRoot(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("CODEX_HOME", "")
t.Setenv("COPILOT_HOME", "")

t.Run("home directory itself", func(t *testing.T) {
isUserLevel, err := IsUserLevelRoot(home)
require.NoError(t, err)
assert.True(t, isUserLevel)
})

t.Run("home directory through a symlink", func(t *testing.T) {
link := filepath.Join(t.TempDir(), "home-link")
require.NoError(t, os.Symlink(home, link))
isUserLevel, err := IsUserLevelRoot(link)
require.NoError(t, err)
assert.True(t, isUserLevel, "a symlinked home directory is still the home directory")
})

t.Run("project below home", func(t *testing.T) {
project := filepath.Join(home, "work", "myrepo")
require.NoError(t, os.MkdirAll(project, 0o755))
isUserLevel, err := IsUserLevelRoot(project)
require.NoError(t, err)
assert.False(t, isUserLevel)
})

t.Run("unrelated directory", func(t *testing.T) {
isUserLevel, err := IsUserLevelRoot(t.TempDir())
require.NoError(t, err)
assert.False(t, isUserLevel)
})

t.Run("agent home folders", func(t *testing.T) {
codexHome := filepath.Join(t.TempDir(), "codex-home")
copilotHome := filepath.Join(t.TempDir(), "copilot-home")
t.Setenv("CODEX_HOME", codexHome)
t.Setenv("COPILOT_HOME", copilotHome)

for _, dir := range []string{codexHome, copilotHome} {
isUserLevel, err := IsUserLevelRoot(dir)
require.NoError(t, err)
assert.True(t, isUserLevel, "%s is an agent user-level folder", dir)
}
})

t.Run("agent home defaults under home", func(t *testing.T) {
for _, dir := range []string{filepath.Join(home, ".codex"), filepath.Join(home, ".copilot")} {
isUserLevel, err := IsUserLevelRoot(dir)
require.NoError(t, err)
assert.True(t, isUserLevel, "%s is an agent user-level folder", dir)
}
})
}
13 changes: 13 additions & 0 deletions app/cli/pkg/action/trace_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,19 @@ func TraceRun(ctx context.Context, log zerolog.Logger, opts TraceRunOpts) error
return fmt.Errorf("no trace providers selected")
}

// The agent hooks are written relative to the repository root, so a root
// that is the user's home directory would rewrite the agent's user-level
// configuration (for example ~/.claude/settings.json) and the hooks would
// load in every session of that agent, in any project. Refuse before
// anything is installed, snapshotted, or run.
userLevel, err := trace.IsUserLevelRoot(opts.RepoRoot)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This guard runs too late to guarantee refusal before prompting or other setup: control-plane trace run calls ensureActionOpts before TraceRun, and that path can prompt for confirmation and save organization state. Validate the resolved root in the command before ensureActionOpts (or otherwise move this check ahead of that setup).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At app/cli/pkg/action/trace_run.go, line 112:

<comment>This guard runs too late to guarantee refusal before prompting or other setup: control-plane `trace run` calls `ensureActionOpts` before `TraceRun`, and that path can prompt for confirmation and save organization state. Validate the resolved root in the command before `ensureActionOpts` (or otherwise move this check ahead of that setup).</comment>

<file context>
@@ -104,6 +104,19 @@ func TraceRun(ctx context.Context, log zerolog.Logger, opts TraceRunOpts) error
+	// configuration (for example ~/.claude/settings.json) and the hooks would
+	// load in every session of that agent, in any project. Refuse before
+	// anything is installed, snapshotted, or run.
+	userLevel, err := trace.IsUserLevelRoot(opts.RepoRoot)
+	if err != nil {
+		return fmt.Errorf("check repository root: %w", err)
</file context>

if err != nil {
return fmt.Errorf("check repository root: %w", err)
}
if userLevel {
return fmt.Errorf("refusing to trace in %q: that is a user-level directory, so the agent hooks would load in every session; run `chainloop trace run` inside a project repository instead", opts.RepoRoot)
}

// Local mode reaches no control plane, so it skips the credential check and
// the up-front workflow creation: the session is recorded and written to
// disk either way.
Expand Down
38 changes: 38 additions & 0 deletions app/cli/pkg/action/trace_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package action

import (
"context"
"os"
"path/filepath"
"testing"
Expand All @@ -29,6 +30,43 @@ import (
"github.com/stretchr/testify/require"
)

// TestTraceRunRefusesUserLevelRoot covers both ways `trace run` can end up
// with the home directory as its root: run outside a git repository with the
// working directory at $HOME, and a git repository rooted at $HOME. Either
// way the agent hooks would land in the user-level configuration and load in
// every session, so the run must fail before anything is installed.
func TestTraceRunRefusesUserLevelRoot(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)

run := func(t *testing.T, store *state.Store) {
t.Helper()
err := TraceRun(context.Background(), zerolog.Nop(), TraceRunOpts{
Store: store,
RepoRoot: home,
Providers: []string{"claude-code"},
Command: []string{"true"},
Local: true,
})
require.Error(t, err)
assert.Contains(t, err.Error(), "user-level directory")
}

t.Run("no git repository, working directory at home", func(t *testing.T) {
run(t, state.NewOutOfTreeStore(filepath.Join(t.TempDir(), "state")))
})

t.Run("git repository rooted at home", func(t *testing.T) {
run(t, state.NewGitStore(filepath.Join(home, ".git")))
})

// Nothing was written to the home directory in either case.
_, err := os.Stat(filepath.Join(home, ".claude", "settings.json"))
assert.True(t, os.IsNotExist(err), "no agent hooks may be installed under home")
_, err = os.Stat(filepath.Join(home, ".git", "chainloop-trace"))
assert.True(t, os.IsNotExist(err), "no trace state may be created under home")
}

func TestTraceRunOwnsState(t *testing.T) {
t.Run("clean repo", func(t *testing.T) {
assert.True(t, traceRunOwnsState(state.NewGitStore(t.TempDir())))
Expand Down