Skip to content

Secure shared .gtrconfig commands behind trust#163

Merged
helizaga merged 14 commits intomainfrom
tommy/pr-162-fixes
Apr 28, 2026
Merged

Secure shared .gtrconfig commands behind trust#163
helizaga merged 14 commits intomainfrom
tommy/pr-162-fixes

Conversation

@helizaga
Copy link
Copy Markdown
Collaborator

@helizaga helizaga commented Apr 3, 2026

Supersedes #162 because maintainers cannot update that branch (maintainerCanModify: false).

Summary

This PR adds a trust boundary for executable commands that come from a repository-owned .gtrconfig, while keeping personal git config trusted. It also removes unsafe adapter eval execution and tightens related filesystem/terminal handling.

Before

  • .gtrconfig hooks could define shell commands from shared repo config without an explicit review step.
  • .gtrconfig defaults.editor / defaults.ai could select executable commands such as npx --package=./malicious evilbin before any trust prompt.
  • Generic adapter command strings used eval, making command parsing harder to reason about.
  • Trust markers were initially content-only and did not fully protect against stale/partial marker edge cases.

After

  • git gtr trust reviews and approves .gtrconfig executable command entries before use.
  • .gtrconfig hooks, defaults.editor, and defaults.ai are ignored until trusted.
  • Trust markers are scoped by repository path plus reviewed command definitions, and are rewritten only through an atomic marker path.
  • Adapter commands are parsed into argv without shell evaluation; filesystem-path commands and shell wrapper forms are rejected.
  • Generated Bash/Zsh/Fish init wrappers use the same trust hash inputs as runtime code.

Evidence

  • git diff --check
  • shellcheck bin/gtr bin/git-gtr lib/*.sh lib/commands/*.sh adapters/editor/*.sh adapters/ai/*.sh
  • ./scripts/generate-completions.sh --check
  • bats tests/ (443 tests)
  • GitHub CI is green on head bae5e3b
  • All review threads are resolved

Summary by CodeRabbit

  • New Features

    • Added git gtr trust to review and approve executable commands in .gtrconfig; trust persists per-repo and requires re-approval on changes.
  • Improvements

    • Trust gates local hooks and editor/AI defaults; untrusted entries are skipped with guidance to run git gtr trust.
    • Safer adapter handling: reject unsafe path/wrapper forms and allow adapter flags to be preserved.
  • Documentation

    • Clarified configuration and safety rules for editor/AI defaults.
  • Tests

    • Added extensive tests covering trust flow, adapters, shell integrations, platform, and copy-safety.
  • Chores

    • Pinned CI actions to fixed commits and tightened workflow permissions.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 3, 2026

Walkthrough

Adds a new git gtr trust command and persistent per-repo trust markers for .gtrconfig hooks and editor/AI defaults; gates .gtrconfig-sourced hooks/defaults behind explicit approval, replaces eval-based adapter execution with parsed argv flow, tightens copy/platform handling, updates shell init/completions, tests, and pins CI actions.

Changes

Cohort / File(s) Summary
GitHub Actions
\.github/workflows/homebrew.yml, \.github/workflows/lint.yml
Add top-level permissions: read-all; pin actions (mislav/bump-homebrew-formula-action, actions/checkout) to specific commit SHAs.
CLI entry, docs & help
bin/git-gtr, README.md, lib/commands/help.sh, CHANGELOG.md, docs/configuration.md
Add trust subcommand dispatch, help text and README/docs updates describing trust lifecycle, re-approval rules, and disallowed command forms.
Shell completions & generation
completions/_git-gtr, completions/git-gtr.fish, completions/gtr.bash, scripts/generate-completions.sh
Register trust in generated completion outputs for Zsh/Bash/Fish and update the completion generation script.
Trust core & init integration
lib/commands/trust.sh, lib/hooks.sh, lib/commands/init.sh
New cmd_trust; compute SHA‑256 of relevant .gtrconfig entries, derive repo-scoped trust keys, persist markers under XDG config, gate inclusion of .gtrconfig hooks/defaults on trust, and emit trust checks in generated init code.
Adapter parsing & execution safety
lib/adapters.sh, adapters/ai/claude.sh, adapters/ai/cursor.sh, adapters/editor/nano.sh
Replace eval-based execution with _parse_configured_command + _run_configured_command, add safety validators, introduce GTR_EDITOR_CMD_ARGS/GTR_AI_CMD_ARGS, and pass parsed configured args into adapters.
Config/env & UI changes
lib/config.sh, lib/launch.sh, lib/ui.sh, lib/args.sh
Add cfg_default_trusted_file (trust-aware config lookup); use printenv for env fallback; replace eval assignments with printf -v; simplify IFS handling.
Copy & filesystem safety
lib/copy.sh
Tighten directory-exclude logic: ignore patterns producing empty suffixes, skip .git/*/.git targets, and avoid removing .git directories.
Platform / terminal spawn
lib/platform.sh
Refine terminal spawn wrapper: introduce SHELL_AFTER, handle empty vs non-empty commands, prefer bash -lc for multi-word commands, and avoid unnecessary shell wrappers; adjust Windows wt/cmd.exe invocation.
Tests
tests/*.bats, tests/cmd_trust.bats, tests/hooks.bats, tests/adapters.bats, tests/launch.bats, tests/platform.bats, tests/copy_safety.bats
Add and update Bats tests covering trust flows, adapter parsing/run, copy safety, init caching/generation, platform spawn args, and related helpers; new integration tests for cmd_trust and launch behavior.
Minor tooling / scaffolding
scripts/generate-completions.sh, completions/*
Update generated completion lists and generation script to include trust.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CLI as git gtr (CLI)
    participant Git as Git\n(.gtrconfig)
    participant Trust as TrustStore\n(XDG_CONFIG_HOME)
    participant Hooks as Hook Runner

    rect rgba(200,230,255,0.5)
    U->>CLI: git gtr trust
    CLI->>Git: locate & read `.gtrconfig` hooks/defaults
    end

    rect rgba(220,255,200,0.5)
    CLI->>CLI: compute SHA‑256 of relevant content
    CLI->>Trust: check for existing trust marker
    Trust-->>CLI: marker present? (yes/no)
    end

    alt not trusted
      CLI->>U: display executable commands + prompt_yes_no
      U-->>CLI: confirm
      CLI->>Trust: write trust marker
      Trust-->>CLI: success / failure
      CLI->>U: report result (exit 0/1)
    else already trusted
      CLI->>U: report hooks already trusted
    end

    rect rgba(255,240,200,0.5)
    Note right of Hooks: Later hook execution reads trust-aware hooks
    Hooks->>Trust: request trusted hooks for phase
    Trust-->>Hooks: return trusted `.gtrconfig` hooks + local git hooks
    Hooks->>Hooks: execute approved hooks
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐇 I hopped through configs, sniffed each hashed part,

I fenced the hooks and kept the defaults smart.
No eval mischief, parsed args in a row,
.git stays safe, and trust seeds will grow.
Approve the commands — then off they go.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.62% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Secure shared .gtrconfig commands behind trust' accurately and concisely describes the main feature added in this pull request: introducing a trust boundary for executable commands defined in .gtrconfig files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tommy/pr-162-fixes

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/adapters.sh (1)

307-360: ⚠️ Potential issue | 🟠 Major

Reject path separators in adapter names to prevent local command execution.

The metacharacter filter (lines 354–360) blocks shell operators but not slashes, so relative paths like ./tool and ../tool pass through. Since command -v accepts relative paths and the full name is later passed to eval in _run_configured_command(), a user-controlled config value (e.g., git gtr config set gtr.editor.default ./malicious) would execute arbitrary binaries from the current directory instead of only PATH-resolved commands. Reject / and \ in the first token, or validate that the resolved command is in PATH only.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/adapters.sh` around lines 307 - 360, The metacharacter check currently
blocks shell operators but allows path separators, letting relative paths like
"./tool" pass; update the validation in the adapter loader to reject path
separators for the configured command (check either "name" or the extracted
"cmd_name" for '/' and '\' characters) before accepting it, and return an error
like other checks; alternatively, resolve the command with "command -v" and
ensure the resolved path is a PATH-resolved command (not a relative/containment
path) before proceeding — reference the variables "name" and "cmd_name" and the
caller "_run_configured_command" when making this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/commands/init.sh`:
- Around line 275-277: The Fish wrapper's hardcoded subcommand list is out of
sync with the Bash list (the Bash block uses COMP_CWORD/COMPREPLY with compgen
and includes "trust"); update the Fish completion template in this file to match
the Bash subcommand list (add "trust" and any other missing entries) so that
running the init fish generator (git gtr init fish) produces the same
completions as the COMPREPLY/compgen block; alternatively, factor the subcommand
list into a single variable and reference it from both the COMP_CWORD/COMPREPLY
block and the Fish template so they stay synchronized.

In `@lib/commands/trust.sh`:
- Around line 13-40: cmd_trust reads and displays hooks then calls
_hooks_mark_trusted which re-hashes the file after the prompt; compute the
reviewed marker (e.g., call the hashing function/_get_marker used by
_hooks_mark_trusted) immediately after reading hook_content and before calling
prompt_yes_no, store that marker (and reviewed path if needed), show the hooks
as before, then after prompt_yes_no pass that stored marker into a new variant
of the marker-writer (or change _hooks_mark_trusted to accept a marker argument)
so you persist the exact reviewed marker instead of re-computing it
post-confirmation; keep _hooks_are_trusted usage unchanged but compare against
the stored marker where appropriate.

In `@lib/hooks.sh`:
- Around line 16-32: The trust marker key is currently content-only (via
_hooks_file_hash) which makes markers shared across repos; update
_hooks_trust_path to incorporate a repository-unique identifier (e.g.,
repository root path, remote URL, or git object like commit/slug) into the
computed key so the path becomes "$_GTR_TRUST_DIR/<repo-id>-<hash>" instead of
just "<hash>", and likewise update the wrapper generation in
lib/commands/init.sh to include the same repo identifier when creating trust
markers so markers are repo-scoped; keep using _hooks_file_hash for the content
part and prepend or append the chosen repo-id consistently.

---

Outside diff comments:
In `@lib/adapters.sh`:
- Around line 307-360: The metacharacter check currently blocks shell operators
but allows path separators, letting relative paths like "./tool" pass; update
the validation in the adapter loader to reject path separators for the
configured command (check either "name" or the extracted "cmd_name" for '/' and
'\' characters) before accepting it, and return an error like other checks;
alternatively, resolve the command with "command -v" and ensure the resolved
path is a PATH-resolved command (not a relative/containment path) before
proceeding — reference the variables "name" and "cmd_name" and the caller
"_run_configured_command" when making this change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 28b78bd9-7e2a-429d-863e-69b3767fa1e4

📥 Commits

Reviewing files that changed from the base of the PR and between c765e62 and 8bbf922.

📒 Files selected for processing (24)
  • .github/workflows/homebrew.yml
  • .github/workflows/lint.yml
  • README.md
  • bin/git-gtr
  • completions/_git-gtr
  • completions/git-gtr.fish
  • completions/gtr.bash
  • lib/adapters.sh
  • lib/args.sh
  • lib/commands/help.sh
  • lib/commands/init.sh
  • lib/commands/trust.sh
  • lib/config.sh
  • lib/copy.sh
  • lib/hooks.sh
  • lib/platform.sh
  • lib/ui.sh
  • scripts/generate-completions.sh
  • tests/adapters.bats
  • tests/cmd_trust.bats
  • tests/copy_safety.bats
  • tests/hooks.bats
  • tests/init.bats
  • tests/platform.bats

Comment thread lib/commands/init.sh
Comment thread lib/commands/trust.sh Outdated
Comment thread lib/hooks.sh Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (1)
lib/hooks.sh (1)

22-29: ⚠️ Potential issue | 🟠 Major

Path scoping still leaves stale approvals across content changes.

Hashing repo_root + hook hash fixes the old cross-path reuse, but it still does not re-prompt when the same checkout path starts executing different repo-local code. A trusted ./scripts/bootstrap survives branch updates or a fresh clone into the same directory as long as .gtrconfig is unchanged, and run_hooks() will then execute a payload the user never reviewed. This trust key needs a repository-state component that changes with the checked-out content, not just the path and hook string.

Also applies to: 41-59

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/hooks.sh` around lines 22 - 29, The current hook trust key uses only
path+hook content, so a different commit checked out at the same path reuses
approvals; update _hooks_file_hash to incorporate repository state by including
a stable commit identifier (e.g., git rev-parse --verify HEAD) or a tree hash of
the working tree when present, then pass that combined string into
_hooks_content_hash so any change to checked-out content invalidates prior
approvals; adjust callers like run_hooks to continue using _hooks_file_hash
unchanged so the trust key now reflects both .gtrconfig hook entries and the
current repository commit/tree state.
🧹 Nitpick comments (1)
lib/hooks.sh (1)

41-79: Keep the trust-key recipe single-sourced.

lib/hooks.sh and the generated helper in lib/commands/init.sh:129-155 now need to stay byte-for-byte aligned again. Since the last regression came from those drifting, I'd strongly prefer generating the wrapper helper from one shared source or template instead of maintaining two manual implementations.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/hooks.sh` around lines 41 - 79, The trust-key logic is duplicated between
lib/hooks.sh (functions _hooks_trust_key, _hooks_trust_key_for_content,
_hooks_trust_path, _hooks_trust_path_for_content) and the generated helper in
lib/commands/init.sh; consolidate to a single source by moving the core
trust-key recipe into one canonical implementation (either a shared template
file or a single library function) and change the generator to emit a thin
wrapper that calls that canonical implementation so both runtime and generated
code remain byte-for-byte aligned; ensure the generator references the canonical
symbol name (e.g., the single source function) when producing the wrapper and
remove the duplicate manual implementations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/adapters.sh`:
- Around line 307-318: The override-loading code currently sources the adapter
file using adapter_selector/adapter_file then returns early (return 0), which
drops the original full name (e.g., "nano -w") so flags never reach the generic
runner; change the flow to source the override but do NOT return
immediately—instead set a marker (e.g., ADAPTER_OVERRIDE_LOADED=1 or set
adapter_override_file="$adapter_file") and let the function continue so the full
name variable (the original name variable) is preserved and passed to the
generic runner; apply the same change for the second override branch that
mirrors this logic (the block that uses adapter_selector/adapter_file again).
- Around line 183-193: The validation allows shell builtins and wrapper commands
with flags which can be exploited because _run_configured_command uses eval "set
-- $command_string"; change the validation to use type -P instead of command -v
so only PATH executables (not builtins) are accepted, and add a check that the
command string contains no option flags (tokens starting with -) or disallowed
wrapper executables (e.g., sh, bash, eval, builtin) before allowing it to be
stored/used; update the validation logic that currently checks metacharacters
(refer to the validation function called before _run_configured_command) to
explicitly reject tokens beginning with '-' and to reject commands where type -P
returns empty or where the resolved command name matches a blacklist of shell
wrappers.

In `@lib/hooks.sh`:
- Around line 91-102: _hooks_write_trust_marker() currently creates the target
file path then writes to it, which can leave a partial/empty marker on failure;
change it to write atomically by creating a temp file in the same directory
(e.g. "${trust_path}.tmp"), write the payload to that temp file, flush it (fsync
the file) and then mv the temp into place, and optionally fsync the directory
(using _GTR_TRUST_DIR) to ensure durability; additionally, tighten
_hooks_are_trusted() to validate the stored payload (e.g. check file is
non-empty and matches the expected config_file or pattern) before treating it as
trusted so a truncated/empty marker cannot be accepted.

---

Duplicate comments:
In `@lib/hooks.sh`:
- Around line 22-29: The current hook trust key uses only path+hook content, so
a different commit checked out at the same path reuses approvals; update
_hooks_file_hash to incorporate repository state by including a stable commit
identifier (e.g., git rev-parse --verify HEAD) or a tree hash of the working
tree when present, then pass that combined string into _hooks_content_hash so
any change to checked-out content invalidates prior approvals; adjust callers
like run_hooks to continue using _hooks_file_hash unchanged so the trust key now
reflects both .gtrconfig hook entries and the current repository commit/tree
state.

---

Nitpick comments:
In `@lib/hooks.sh`:
- Around line 41-79: The trust-key logic is duplicated between lib/hooks.sh
(functions _hooks_trust_key, _hooks_trust_key_for_content, _hooks_trust_path,
_hooks_trust_path_for_content) and the generated helper in lib/commands/init.sh;
consolidate to a single source by moving the core trust-key recipe into one
canonical implementation (either a shared template file or a single library
function) and change the generator to emit a thin wrapper that calls that
canonical implementation so both runtime and generated code remain byte-for-byte
aligned; ensure the generator references the canonical symbol name (e.g., the
single source function) when producing the wrapper and remove the duplicate
manual implementations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: cc37536c-f564-4ebe-adc2-f74003eb714e

📥 Commits

Reviewing files that changed from the base of the PR and between 8bbf922 and f2b7249.

📒 Files selected for processing (8)
  • lib/adapters.sh
  • lib/commands/init.sh
  • lib/commands/trust.sh
  • lib/hooks.sh
  • tests/adapters.bats
  • tests/cmd_trust.bats
  • tests/hooks.bats
  • tests/init.bats
✅ Files skipped from review due to trivial changes (2)
  • tests/init.bats
  • lib/commands/trust.sh
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/hooks.bats
  • tests/adapters.bats
  • lib/commands/init.sh
  • tests/cmd_trust.bats

Comment thread lib/adapters.sh Outdated
Comment thread lib/adapters.sh Outdated
Comment thread lib/hooks.sh Outdated
@helizaga
Copy link
Copy Markdown
Collaborator Author

helizaga commented Apr 4, 2026

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 4, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/hooks.sh`:
- Around line 117-118: If _hooks_canonical_config_path fails after creating the
temp file, the temp file referenced by temp_path (created via mktemp
"$_GTR_TRUST_DIR/.trust.XXXXXX") is leaked; update the failure path so that when
canonical_config_file=$(_hooks_canonical_config_path "$config_file") returns
non-zero you remove the temp file (rm -f "$temp_path") before returning (or set
a local cleanup/trap that removes temp_path on early exit) to ensure no
temporary files are left behind.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 42772e88-3740-46a9-bd38-764b54ca23f5

📥 Commits

Reviewing files that changed from the base of the PR and between f2b7249 and e63c8a9.

📒 Files selected for processing (9)
  • adapters/ai/claude.sh
  • adapters/ai/cursor.sh
  • adapters/editor/nano.sh
  • lib/adapters.sh
  • lib/commands/init.sh
  • lib/hooks.sh
  • tests/adapters.bats
  • tests/hooks.bats
  • tests/init.bats
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/hooks.bats
  • tests/adapters.bats
  • lib/adapters.sh
  • tests/init.bats

Comment thread lib/hooks.sh Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/adapters.sh`:
- Around line 296-304: Remove the overly restrictive pre-parse validations:
delete the helper functions _configured_command_uses_path_arg and
_configured_command_has_safe_syntax and stop rejecting arguments like
"~/.toolrc" or raw metacharacters, and instead only validate the adapter command
name inside _load_adapter(); ensure _load_adapter() no longer calls those two
functions and only checks the command name token (leaving GTR_*_CMD_ARGS
handling to the adapter overrides) so argv-style execution via "$@" can accept
literal path-like args and metacharacters as safe data.

In `@lib/commands/init.sh`:
- Around line 174-180: The regex passed to string replace in the branch handling
linked worktrees is over-escaped ('/\\.git$') so Fish treats the backslash
literally; change the pattern to '/\.git$' (single backslash) in the string
replace -r call that operates on _gtr_git_common_dir so the trailing '/.git'
suffix is correctly stripped (i.e., update the expression string replace -r
'/\\.git$' '' -- "$_gtr_git_common_dir" to use '/\.git$' instead).

In `@lib/hooks.sh`:
- Around line 135-175: The code currently treats failures from
_hooks_current_trust_path as success (returning 0), merging “no hooks” with real
errors; change the error handling so that when _hooks_current_trust_path fails
it returns non-zero (fail closed). Specifically, in _hooks_are_trusted() replace
the trust_path assignment branch that uses "|| return 0" with "|| return 1" so
resolution errors mark hooks untrusted, and in _hooks_mark_trusted() do the same
(replace "trust_path=$(_hooks_current_trust_path \"$config_file\") || return 0"
with "|| return 1") so marker writes are aborted on resolution errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: cf8e3b93-1ea4-40b2-a342-d1d7f67142a8

📥 Commits

Reviewing files that changed from the base of the PR and between e63c8a9 and 01d23d3.

📒 Files selected for processing (8)
  • README.md
  • lib/adapters.sh
  • lib/commands/help.sh
  • lib/commands/init.sh
  • lib/commands/trust.sh
  • lib/hooks.sh
  • tests/adapters.bats
  • tests/init.bats
🚧 Files skipped from review as they are similar to previous changes (4)
  • README.md
  • lib/commands/help.sh
  • tests/init.bats
  • lib/commands/trust.sh

Comment thread lib/adapters.sh Outdated
Comment thread lib/commands/init.sh
Comment thread lib/hooks.sh
@shadowcodex
Copy link
Copy Markdown
Contributor

@NatoBoram just checking in. Need any support on this?

Comment thread lib/hooks.sh Outdated
Comment thread lib/adapters.sh Outdated
Comment thread lib/commands/init.sh Outdated
Copy link
Copy Markdown
Contributor

@averyjennings averyjennings left a comment

Choose a reason for hiding this comment

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

The trust model architecture is well-designed: repo-scoped key (SHA256(repo_root + "\n" + hook_content_hash)), atomic marker writes via mktemp + mv, and TOCTOU detection in cmd_trust are all solid. The eval removals throughout (printenv for config lookup, printf -v for UI input, hand-written tokenizer for adapter parsing) are correct and address the original PR 162 blockers.

Note on the CodeRabbit temp-file-leak concern: false positive in current code. _hooks_canonical_config_path is resolved on line 153 before mktemp on line 154 — there is no temp file to leak if canonical path resolution fails.

Three blockers remain from prior review rounds — inline comments with specific fixes attached.


F1 — Fish regex (lib/commands/init.sh:179): /\\.git$ in a <<'FISH' heredoc matches a literal backslash, not a dot. The .git suffix is never stripped for linked worktrees; Fish users see hooks permanently reported as untrusted even after running git gtr trust. The Bash/Zsh helpers (parameter expansion) are unaffected.

F2 — Trust gate fails open (lib/hooks.sh:140,172): _hooks_are_trusted and _hooks_mark_trusted use || return 0 as a catch-all that fires on any error, not just "no hooks defined." A stale worktree path that makes _hooks_repo_root fail is enough to trigger silent trust bypass for repos that have hook definitions.

F3 — .gtrconfig [defaults] bypasses the trust gate (lib/adapters.sh:299, lib/launch.sh:7-12): defaults.ai / defaults.editor are read from .gtrconfig via cfg_default without a trust check, and the adapter safety validator passes --flag=./value tokens. A repo-committed defaults.ai = npx --package=./malicious evilbin reaches _run_configured_command "$@" and executes without any git gtr trust prompt.

Comment thread lib/commands/init.sh Outdated
Comment thread lib/hooks.sh Outdated
Comment thread lib/adapters.sh Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
lib/commands/init.sh (1)

179-179: ⚠️ Potential issue | 🟠 Major

Fix the Fish regex on Line 179; it still won't strip /.git.

Because this code is emitted from a single-quoted heredoc, Fish receives /\\.git$ literally. In Fish regex syntax that matches a backslash, not the .git suffix, so linked worktrees resolve .gtrconfig under .../.git/.gtrconfig and trust-gated hooks stay broken in Fish.

Suggested fix
-    printf '%s/.gtrconfig\n' (string replace -r '/\\.git$' '' -- "$_gtr_git_common_dir")
+    printf '%s/.gtrconfig\n' (string replace -r '/\.git$' '' -- "$_gtr_git_common_dir")
#!/bin/bash
set -euo pipefail

command -v fish >/dev/null 2>&1 || exit 0

fish <<'FISH'
printf 'current: '
string replace -r '/\\.git$' '' -- '/tmp/repo/.git'
printf '\nfixed:   '
string replace -r '/\.git$' '' -- '/tmp/repo/.git'
printf '\n'
FISH
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/commands/init.sh` at line 179, The Fish regex used in the printf call
still contains an escaped backslash ('/\\.git$') so Fish matches a literal
backslash instead of the '.git' suffix; update the regex in the printf/string
replace invocation (the line calling string replace -r '/\\.git$' '' --
"$_gtr_git_common_dir") to use '/\.git$' (i.e., remove the extra backslash) so
Fish correctly strips '/.git' from linked worktree paths.
🧹 Nitpick comments (1)
tests/adapters.bats (1)

131-151: Consider extracting mock binary creation to a test helper (DRY).

The mktemp + cat + chmod + PATH scaffold repeats in several tests and can be centralized for easier maintenance.

♻️ Optional refactor sketch
+create_mock_bin() {
+  local name="$1"
+  local body="$2"
+  mock_bin_dir="${mock_bin_dir:-$(mktemp -d)}"
+  cat > "$mock_bin_dir/$name" <<EOF
+#!/usr/bin/env bash
+$body
+EOF
+  chmod +x "$mock_bin_dir/$name"
+  PATH="$mock_bin_dir:$PATH"
+}

 `@test` "_load_adapter allows generic commands with slash-bearing arguments" {
-  mock_bin_dir="$(mktemp -d)"
-  cat > "$mock_bin_dir/bunx" <<'EOF'
-#!/usr/bin/env bash
-exit 0
-EOF
-  chmod +x "$mock_bin_dir/bunx"
-  PATH="$mock_bin_dir:$PATH"
+  create_mock_bin "bunx" "exit 0"
   _load_adapter "ai" "bunx `@github/copilot`@latest" "AI tool" "$(_list_registry_names "$_AI_REGISTRY")" "bunx, gpt"
   [ "$GTR_AI_CMD" = "bunx `@github/copilot`@latest" ]
   [ "$GTR_AI_CMD_NAME" = "bunx" ]
 }

Also applies to: 159-165

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/adapters.bats` around lines 131 - 151, Extract the repeated "mktemp +
cat + chmod + PATH" scaffold into a reusable test helper (e.g., create_mock_bin
or setup_mock_bin) and call it from the tests instead of inlining the block;
specifically replace the repeated scaffolding around mock_bin_dir, creating an
executable (tool/bunx) and prepending it to PATH in the tests named
"_load_adapter ..." and "_load_adapter allows path-like literal arguments",
ensure the helper accepts the binary name and content, makes it executable,
updates PATH, and performs cleanup (or returns the temp dir for later cleanup)
so the duplicate code at the other occurrence (lines 159-165) is removed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@lib/commands/init.sh`:
- Line 179: The Fish regex used in the printf call still contains an escaped
backslash ('/\\.git$') so Fish matches a literal backslash instead of the '.git'
suffix; update the regex in the printf/string replace invocation (the line
calling string replace -r '/\\.git$' '' -- "$_gtr_git_common_dir") to use
'/\.git$' (i.e., remove the extra backslash) so Fish correctly strips '/.git'
from linked worktree paths.

---

Nitpick comments:
In `@tests/adapters.bats`:
- Around line 131-151: Extract the repeated "mktemp + cat + chmod + PATH"
scaffold into a reusable test helper (e.g., create_mock_bin or setup_mock_bin)
and call it from the tests instead of inlining the block; specifically replace
the repeated scaffolding around mock_bin_dir, creating an executable (tool/bunx)
and prepending it to PATH in the tests named "_load_adapter ..." and
"_load_adapter allows path-like literal arguments", ensure the helper accepts
the binary name and content, makes it executable, updates PATH, and performs
cleanup (or returns the temp dir for later cleanup) so the duplicate code at the
other occurrence (lines 159-165) is removed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2746854b-2562-4c9b-93fd-641eae58f1ff

📥 Commits

Reviewing files that changed from the base of the PR and between 01d23d3 and 475b9f0.

📒 Files selected for processing (7)
  • lib/adapters.sh
  • lib/commands/init.sh
  • lib/config.sh
  • lib/hooks.sh
  • tests/adapters.bats
  • tests/hooks.bats
  • tests/init.bats
🚧 Files skipped from review as they are similar to previous changes (4)
  • lib/config.sh
  • tests/hooks.bats
  • tests/init.bats
  • lib/adapters.sh

@helizaga helizaga changed the title fix: address PR 162 security regression blockers Secure shared .gtrconfig commands behind trust Apr 27, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
lib/commands/init.sh (1)

179-179: ⚠️ Potential issue | 🟠 Major

Fix Fish regex escaping for linked-worktree .gtrconfig resolution.

Line 179 still uses '/\\.git$'. In Fish regex, that pattern does not reliably strip the /.git suffix for linked-worktree git-common-dir values, which can produce the wrong .gtrconfig path.

💡 Proposed fix
-    printf '%s/.gtrconfig\n' (string replace -r '/\\.git$' '' -- "$_gtr_git_common_dir")
+    printf '%s/.gtrconfig\n' (string replace -r '/\.git$' '' -- "$_gtr_git_common_dir")
#!/bin/bash
set -euo pipefail

# 1) Inspect current generated Fish snippet
sed -n '174,181p' lib/commands/init.sh

# 2) Validate behavior directly in fish if available
if command -v fish >/dev/null 2>&1; then
  fish <<'FISH'
printf 'current: '
string replace -r '/\\.git$' '' -- '/tmp/repo/.git'
printf '\nfixed:   '
string replace -r '/\.git$' '' -- '/tmp/repo/.git'
printf '\n'
FISH
fi
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/commands/init.sh` at line 179, The Fish regex used in the printf line
that builds the .gtrconfig path wrongly uses '/\\.git$' so it fails to strip
linked-worktree `/.git`; update the `string replace -r` pattern in
lib/commands/init.sh (the printf containing `string replace -r ... --
"$_gtr_git_common_dir"`) to use the correct Fish regex '/\.git$' (single
backslash) so `/\.git$` matches and removes the trailing '/.git' from
linked-worktree `git-common-dir` values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@lib/commands/init.sh`:
- Line 179: The Fish regex used in the printf line that builds the .gtrconfig
path wrongly uses '/\\.git$' so it fails to strip linked-worktree `/.git`;
update the `string replace -r` pattern in lib/commands/init.sh (the printf
containing `string replace -r ... -- "$_gtr_git_common_dir"`) to use the correct
Fish regex '/\.git$' (single backslash) so `/\.git$` matches and removes the
trailing '/.git' from linked-worktree `git-common-dir` values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: a5fd7d05-7181-47f8-91e4-72abeae224b1

📥 Commits

Reviewing files that changed from the base of the PR and between 01d23d3 and 57eb199.

📒 Files selected for processing (21)
  • CHANGELOG.md
  • README.md
  • bin/git-gtr
  • completions/_git-gtr
  • completions/git-gtr.fish
  • completions/gtr.bash
  • docs/configuration.md
  • lib/adapters.sh
  • lib/commands/help.sh
  • lib/commands/init.sh
  • lib/commands/trust.sh
  • lib/config.sh
  • lib/copy.sh
  • lib/hooks.sh
  • lib/launch.sh
  • scripts/generate-completions.sh
  • tests/adapters.bats
  • tests/cmd_trust.bats
  • tests/hooks.bats
  • tests/init.bats
  • tests/launch.bats
✅ Files skipped from review due to trivial changes (6)
  • docs/configuration.md
  • CHANGELOG.md
  • completions/git-gtr.fish
  • completions/gtr.bash
  • scripts/generate-completions.sh
  • lib/hooks.sh
🚧 Files skipped from review as they are similar to previous changes (7)
  • bin/git-gtr
  • completions/_git-gtr
  • lib/commands/trust.sh
  • lib/copy.sh
  • tests/hooks.bats
  • tests/init.bats
  • lib/commands/help.sh

@helizaga helizaga merged commit 864d660 into main Apr 28, 2026
4 checks passed
@helizaga helizaga deleted the tommy/pr-162-fixes branch April 28, 2026 02:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants