23 Commits
v0.1.0 ... main

Author SHA1 Message Date
Flo
cd2afdb308 feat: tests, device-not-found retry, remove Qubes CTAP2 warning
Add 20 BATS tests and 1 interactive test for v0.5.0 edge-case
fixes. FIDO2 keygen now prompts to retry on "device not found"
instead of exiting. Remove stale Qubes vhci_hcd warning. Update
hardware test matrix in README.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 04:22:52 -07:00
Flo
c5bbe5b44a feat: UX hardening for edge cases and pre-existing configurations
Guard user.useConfigOnly behind identity check, offer to unset
conflicting pull.rebase, use dedicated signing key names to avoid
colliding with auth keys, back up SSH config before changes, place
new SSH directives in Host * blocks, and prompt for email in
allowed_signers setup.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 03:25:48 -07:00
Flo
69707b4475 feat: keychain-aware credential helper, array refactor, cleanup
- Detect GCM (Git Credential Manager) as preferred cross-platform helper
- Recognize osxkeychain, GCM, libsecret, gnome-keyring as keychain-backed
- Print distro-specific install hints when no keychain helper found
- Refactor apply_setting_group and apply_ssh_directive_group to use bash
  arrays instead of sed-indexed newline-delimited strings
- Extract get_ssh_directive_value() to deduplicate SSH config parsing
- Fix stale function name in tests (apply_ssh_directive → apply_single_ssh_directive)
- Remove orphan comment in detect_existing_keys
- Bump version to 0.4.0

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 15:00:02 +02:00
Flo
ca4daa1539 feat: group SSH config directives with trade-off explanations
SSH config hardening now presents directives in logical groups
(matching the git config UX) with reasoning for each:
- Host Verification: TOFU rationale, known_hosts exfiltration risk
- Key & Agent Management: key enumeration attack, passphrase fatigue
- Algorithm Restrictions: downgrade attack, intentional RSA breakage

Each group batches its directives into a single prompt instead of
asking one-by-one.

Bump version to 0.3.1.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 09:14:57 -07:00
Flo
5ec19ec367 feat: FIDO2 key type auto-detection, fallback chain, and --reset-signing
FIDO2 hardware key generation now handles diverse security keys:
- Detect ed25519-sk vs ecdsa-sk support via ykman/fido2-token, with
  automatic fallback chain: ed25519-sk → ecdsa-sk → ecdsa-sk -O resident
- Detect FIDO hardware by HID usage page (0xF1D0) instead of hardcoded
  Yubico vendor ID — works with SoloKeys, Titan, Nitrokey, etc.
- Check libfido2 availability via ldconfig, dpkg-query, and rpm
- Warn on Qubes OS vhci_hcd USB passthrough (corrupts CTAP2 messages)
- Suppress admin recommendations when dependency is missing so install
  instructions stay visible
- Accept ecdsa-sk keys in signing key filter

New --reset-signing flag clears git signing config, removes
allowed_signers entries, and moves/deletes key files so a fresh key
can be generated.

Bump version to 0.3.0.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 08:45:38 -07:00
Flo
35ae641038 docs: add REASONING.md with trade-offs for every default
Document what each setting does, what attack it mitigates, what
could break, and why we chose this default. Covers all git config
settings, SSH directives, and audit-only checks.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 19:59:31 +02:00
Flo
55b7bf043a fix: e2e summary table alignment and color
IFS=$'\n\t' broke space-delimited read in summary and array join
in parallel status message. Use explicit IFS=' ' where needed.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 19:40:07 +02:00
Flo
cb72a5feca fix: skip Arch Linux e2e tests on ARM64
Arch Linux doesn't publish ARM64 container images. Auto-skip with
SKIP status on non-x86_64 architectures.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 18:53:35 +02:00
Flo
7eb697f1f2 feat: run e2e container tests in parallel
Build images sequentially (shared layer cache), then run BATS and
interactive tests across all distros in parallel. Output captured
to temp files, failures show log tail. Significantly faster for
multi-distro runs.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 18:43:25 +02:00
Flo
c967e75ffc docs: add full test suite instructions to README
Document all three test tiers (BATS, interactive, e2e containers)
with usage examples, flags, and requirements.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 18:38:50 +02:00
Flo
fb69304a9b fix: container interactive tests fail on empty GIT_CONFIG_GLOBAL
Only export GIT_CONFIG_GLOBAL in tmux sessions when already set.
An empty value tells git "no global config" vs unset (uses ~/.gitconfig).
Also fix stat format detection in SSH permissions test.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 18:37:15 +02:00
Flo
5bd5a74df9 fix: SSH permissions test failing in Linux containers
Use if/else for stat format detection instead of || which can fail
under set -e. Remove run wrapper for apply_ssh_config.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 18:29:40 +02:00
Flo
1e11105b5c feat: add --skip-host flag to e2e.sh
Skip host interactive tests when only running containers.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 18:11:18 +02:00
Flo
1795661975 fix: e2e.sh unbound variable on empty build_args
Use ${arr[@]+"${arr[@]}"} pattern for nounset-safe empty array expansion.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 18:08:21 +02:00
Flo
dd6257985b fix: v0.2.3 e2e distro loop, FIDO2 freeze, grouped prompts
Fix e2e.sh distro iteration broken by IFS setting (use bash array).
Fix FIDO2 detection freezing on macOS (check ssh-sk-helper, don't
invoke ssh-keygen). Group apply prompts into 6 categories. Fix Linux
gitleaks install hint.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 18:05:19 +02:00
Flo
e24206e0b5 chore: release v0.2.2
Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 17:49:15 +02:00
Flo
d8e7665e72 fix: FIDO2 detection no longer freezes on macOS
Detect Homebrew openssh by checking for ssh-sk-helper binary instead
of running ssh-keygen (which blocks waiting for a FIDO touch).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 17:47:11 +02:00
Flo
475faf23df fix: v0.2.1 FIDO2 macOS keygen, grouped prompts, Linux hints
Use Homebrew ssh-keygen for FIDO2 key generation on macOS instead of
searching for libsk-libfido2.dylib (removed in modern openssh). Group
interactive apply prompts into 6 categories with explanations. Fix
Linux gitleaks install hint to show apt/dnf instead of brew.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 17:39:14 +02:00
Flo
09f6369bec refactor: group apply prompts with explanations
Replace ~25 individual y/n prompts with 6 logical groups, each showing
a table of pending changes with one-line explanations before prompting.
Also fix FIDO2 middleware detection (needs brew openssh, not just libfido2).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 15:30:00 +02:00
Flo
8037cb7908 feat: v0.2.0 expanded hardening
Add gitleaks pre-commit hook, global gitignore, plaintext credential
detection, SSH key hygiene audit, 8 new git config settings, and
safe.directory wildcard detection. Fix ssh-keygen macOS compatibility,
FIDO2 detection via ioreg, and interactive test isolation.

Implements docs/specs/2026-03-31-v0.2.0-expanded-hardening.md

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 14:03:29 +02:00
Flo
0e6d04fefb feat: add host-side interactive tests for macOS coverage
Add test/run-interactive.sh that runs tmux interactive tests on
the host in an isolated HOME. Covers macOS ssh-keygen which
cannot be tested in Linux containers. e2e.sh now runs host
interactive tests first, then container matrix. Skips gracefully
if tmux is not installed.

Closes: #23

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 12:41:08 +02:00
Flo
26ea0bc106 fix: run interactive tmux tests in e2e pipeline
e2e.sh now runs both BATS and interactive tests per distro:
build -> BATS -> interactive. Failure stage shown in summary.

Closes: #22

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 11:39:43 +02:00
Flo
f1b9d0183d feat: add e2e container test harness
Implements spec docs/specs/2026-03-30-e2e-container-tests.md:
- 5 Containerfiles (ubuntu, debian, fedora, alpine, arch)
- test/e2e.sh runner with --runtime, --rebuild, single-distro mode
- tmux-based interactive tests (full accept, safety gate decline,
  signing generate, signing skip)
- All scripts pass shellcheck

Closes: #18, #19, #20

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-03-31 11:30:40 +02:00
22 changed files with 4583 additions and 183 deletions

View File

@@ -4,7 +4,80 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.1.0] - 2026-03-31 ## [0.5.0] - 2026-04-05
### Added
- Identity guard: prompt for `user.name`/`user.email` before enabling `user.useConfigOnly=true` to prevent commit lockout
- Apply phase offers to unset `pull.rebase` when it conflicts with `pull.ff=only`
- SSH config backup (`~/.ssh/config.pre-harden-*`) before applying SSH directives
- `core.hooksPath` gets its own prompt with explicit warning about overriding per-repo hooks (husky, lefthook, pre-commit)
- Allowed signers setup prompts for email when `user.email` is not configured globally
### Changed
- Signing keys use dedicated names (`id_ed25519_signing`, `id_ed25519_sk_signing`, `id_ecdsa_sk_signing`) to avoid colliding with existing authentication keys
- "Key already exists" messages changed from `[WARN]` to `[INFO]` with clearer guidance ("using existing key")
- New SSH directives are placed inside a `Host *` block instead of appended bare to EOF
- `--reset-signing` now cleans the actual configured `user.signingkey` path in addition to well-known key names
### Removed
- Qubes OS CTAP2/vhci_hcd warning (PIN-protected keys work over USB passthrough)
### Fixed
- `readonly VERSION` variable conflict when sourcing `/etc/os-release` (replaced `.` with `sed` parse)
- FIDO2 key generation now offers retry when security key is not plugged in ("device not found")
- Admin recommendations suppressed when signing setup was skipped or failed
### Tests
- 20 new BATS tests (112 total) covering identity guard, pull.rebase unset, SSH `Host *` placement, SSH config backup, dedicated signing key names, core.hooksPath separation, reset-signing with configured paths
- New interactive test: identity guard flow (missing name/email prompts)
- Updated existing tests for dedicated signing key names and inter-test isolation
## [0.4.0] - 2026-04-04
### Added
- GCM (Git Credential Manager) detection — preferred cross-platform credential helper
- `is_keychain_credential_helper()` recognizes osxkeychain, GCM, libsecret, and gnome-keyring
- Distro-specific install hints when no keychain-backed credential helper is found (Debian/Ubuntu, Fedora/RHEL, Arch, openSUSE, Alpine)
- Audit labels keychain-backed helpers as `(keychain-backed)` for clarity
### Changed
- Harden step skips credential.helper prompt when user already has a keychain-backed helper
- Audit messaging improved: clearer descriptions for missing, insecure, and unknown helpers
- FIDO2 signing wizard, grouped SSH config directives, REASONING.md (prior unreleased work)
## [0.2.3] - 2026-03-31
### Fixed
- Fix e2e.sh distro loop not splitting on spaces (#39)
- FIDO2 key generation on macOS — detect Homebrew's openssh via `ssh-sk-helper` (no freeze), use its `ssh-keygen` binary for hardware key generation
- Linux gitleaks install hint now shows `apt`/`dnf` instead of `brew`
- e2e test runner distro loop broken by `IFS` setting — use bash array
### Changed
- Group interactive apply prompts into 6 categories with one-line explanations (replaces ~25 individual prompts)
## [0.2.0] - 2026-03-31
### Added
- Add REASONING.md documenting trade-offs for each hardening default (#48)
- Gitleaks pre-commit hook installation — creates `~/.config/git/hooks/pre-commit` with `SKIP_GITLEAKS` bypass
- Global gitignore creation (`~/.config/git/ignore`) with security patterns (`.env`, `*.pem`, `*.key`, credentials, Terraform state)
- Audit of existing global gitignore for missing security patterns
- 8 new git config settings: `user.useConfigOnly`, `protocol.version=2`, `transfer.bundleURI=false`, `init.defaultBranch=main`, `core.symlinks=false` (interactive-only), `fetch.prune=true`, `gc.reflogExpire=180.days`, `gc.reflogExpireUnreachable=90.days`
- Combined signing enablement into single prompt (replaces 3 individual prompts)
- 26 new BATS tests (90 total)
### Security
- SSH key hygiene audit — scans `~/.ssh/*.pub` and `IdentityFile` entries, warns about DSA/ECDSA/weak RSA keys
- Plaintext credential file detection — warns about `~/.git-credentials`, `~/.netrc`, `~/.npmrc` (auth tokens), `~/.pypirc` (passwords)
- `safe.directory = *` wildcard detection and removal (CVE-2022-24765)
### Fixed
- `ssh-keygen` calls fail on macOS with `--` end-of-options separator (removed)
- Interactive tests fail on macOS due to tmux resetting `HOME` in login shells
- Interactive tests race condition with tmux session cleanup between tests
## [0.1.0] - 2026-03-30
### Added ### Added
- Interactive shell script that audits and hardens global git config - Interactive shell script that audits and hardens global git config
@@ -32,5 +105,3 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- SSH config value parsing handles inline comments and quoted paths - SSH config value parsing handles inline comments and quoted paths
- Version comparison uses base-10 arithmetic to prevent octal interpretation - Version comparison uses base-10 arithmetic to prevent octal interpretation
- Temp file cleanup trap in SSH config updates - Temp file cleanup trap in SSH config updates
- `--` separator before path arguments in `ssh-keygen` calls
- Removed unused exported `SIGNING_KEY_PATH` variable

View File

@@ -38,16 +38,23 @@ The script runs in two phases:
| Category | What it does | | Category | What it does |
|---|---| |---|---|
| **Object integrity** | Validates all objects on fetch/push/receive (`transfer.fsckObjects`, etc.) | | **Identity** | `user.useConfigOnly=true` — prevents commits without explicit identity |
| **Protocol restrictions** | Default-deny policy: only HTTPS and SSH allowed. Blocks `git://` (unencrypted) and `ext://` (arbitrary command execution) | | **Object integrity** | `fsckObjects` on transfer/fetch/receive, `transfer.bundleURI=false`, `fetch.prune=true` |
| **Filesystem protection** | Enables `core.protectNTFS`, `core.protectHFS`, disables `core.fsmonitor` | | **Protocol restrictions** | Default-deny policy: only HTTPS and SSH. Blocks `git://` and `ext://`. Forces `protocol.version=2` |
| **Filesystem protection** | `core.protectNTFS`, `core.protectHFS`, `core.fsmonitor=false`, `core.symlinks=false` (interactive-only) |
| **Hook control** | Redirects `core.hooksPath` to `~/.config/git/hooks` so repo-local hooks can't execute | | **Hook control** | Redirects `core.hooksPath` to `~/.config/git/hooks` so repo-local hooks can't execute |
| **Repository safety** | `safe.bareRepository=explicit`, `submodule.recurse=false` | | **Pre-commit hook** | Installs gitleaks secret scanner as global pre-commit hook (with `SKIP_GITLEAKS` bypass) |
| **Pull/merge hardening** | `pull.ff=only`, `merge.ff=only` — refuses non-fast-forward merges, surfacing rewritten history | | **Repository safety** | `safe.bareRepository=explicit`, `submodule.recurse=false`, detects/removes `safe.directory=*` wildcard |
| **Pull/merge hardening** | `pull.ff=only`, `merge.ff=only` — refuses non-fast-forward merges |
| **Transport security** | Rewrites `http://` to `https://`, enforces `http.sslVerify=true` | | **Transport security** | Rewrites `http://` to `https://`, enforces `http.sslVerify=true` |
| **Credential storage** | Platform-detected secure helper (`osxkeychain` on macOS, `libsecret` on Linux). Warns if using plaintext `store` | | **Credential storage** | Platform-detected secure helper (`osxkeychain` on macOS, `libsecret` on Linux). Warns if using plaintext `store` |
| **Credential hygiene** | Warns about plaintext `~/.git-credentials`, `~/.netrc`, `~/.npmrc` (tokens), `~/.pypirc` (passwords) |
| **Global gitignore** | Creates `~/.config/git/ignore` with patterns for secrets, credentials, and OS/IDE artifacts |
| **Defaults** | `init.defaultBranch=main` |
| **Forensic readiness** | Extended reflog retention (`gc.reflogExpire=180.days`, `gc.reflogExpireUnreachable=90.days`) |
| **Commit signing** | SSH-based signing with interactive key setup wizard (software or FIDO2 hardware key) | | **Commit signing** | SSH-based signing with interactive key setup wizard (software or FIDO2 hardware key) |
| **SSH hardening** | `StrictHostKeyChecking=accept-new`, `HashKnownHosts=yes`, `IdentitiesOnly=yes`, modern algorithm restrictions | | **SSH hardening** | `StrictHostKeyChecking=accept-new`, `HashKnownHosts=yes`, `IdentitiesOnly=yes`, modern algorithm restrictions |
| **SSH key hygiene** | Audits `~/.ssh/*.pub` for weak key types (DSA, ECDSA, short RSA) |
| **Visibility** | `log.showSignature=true` | | **Visibility** | `log.showSignature=true` |
A config backup is saved to `~/.config/git/pre-harden-backup-<timestamp>.txt` before any changes. A config backup is saved to `~/.config/git/pre-harden-backup-<timestamp>.txt` before any changes.
@@ -95,6 +102,7 @@ Options:
- Bash 3.2+ (compatible with macOS default bash) - Bash 3.2+ (compatible with macOS default bash)
Optional: Optional:
- `gitleaks` for pre-commit secret scanning (hook is installed regardless; scans run only if gitleaks is on `$PATH`)
- `ykman` or `fido2-token` for FIDO2 hardware key detection - `ykman` or `fido2-token` for FIDO2 hardware key detection
## Threat Model ## Threat Model
@@ -106,9 +114,11 @@ Optional:
- **Protocol downgrade** — blocks plaintext `git://` and dangerous `ext://` protocol - **Protocol downgrade** — blocks plaintext `git://` and dangerous `ext://` protocol
- **Hook-based RCE** — redirects hook execution away from repo-local `.git/hooks/` - **Hook-based RCE** — redirects hook execution away from repo-local `.git/hooks/`
- **Submodule attacks** — disables auto-recursion; submodules must be explicitly initialized - **Submodule attacks** — disables auto-recursion; submodules must be explicitly initialized
- **Credential theft** — ensures secure credential storage, warns about plaintext `store` - **Credential theft** — ensures secure credential storage, warns about plaintext `store`, detects leaked credentials in `~/.git-credentials`, `~/.netrc`, `~/.npmrc`, `~/.pypirc`
- **Secret leakage** — gitleaks pre-commit hook blocks commits containing secrets before they enter git history
- **Commit impersonation** — SSH signing proves key possession (anyone can fake `user.name`/`user.email`) - **Commit impersonation** — SSH signing proves key possession (anyone can fake `user.name`/`user.email`)
- **Filesystem tricks** — blocks NTFS/HFS+ path manipulation attacks - **Filesystem tricks** — blocks NTFS/HFS+/symlink path manipulation attacks
- **Weak SSH keys** — audits and warns about DSA, ECDSA, and short RSA keys
### What this does NOT protect against ### What this does NOT protect against
@@ -129,17 +139,74 @@ The script prints (but does not apply) server/org-level recommendations:
- Clone untrusted repos with `--no-recurse-submodules` - Clone untrusted repos with `--no-recurse-submodules`
- Use separate signing keys per org to prevent cross-platform identity correlation (OSINT) - Use separate signing keys per org to prevent cross-platform identity correlation (OSINT)
## Signing with FIDO2 hardware keys
The script includes an interactive wizard that:
1. Detects existing SSH keys (including custom-named keys from `~/.ssh/config`)
2. Detects FIDO2 hardware (YubiKey, etc.)
3. Offers two tiers:
- **Software SSH key** — use existing `ed25519` or generate one
- **FIDO2 hardware key** — generate `ed25519-sk` with touch-to-sign (if hardware detected)
4. Configures `user.signingkey`, `commit.gpgsign`, `tag.gpgsign`
5. Sets up `~/.config/git/allowed_signers` for local signature verification
These combinations of hardware and OS have been tested:
| Hardware | Firmware | OS | works? |
|----------|----------|----|--------|
| [Yubico Security Key USB C NFC](https://support.yubico.com/s/article/Security-Key-C-NFC) | 5.4.3 | macOS Tahoe | Yes |
| [Yubico Security Key USB C NFC](https://support.yubico.com/s/article/Security-Key-C-NFC) | 5.4.3 | Debian 13 Trixie | |
| [Yubico Security Key USB C NFC](https://support.yubico.com/s/article/Security-Key-C-NFC) | 5.4.3 | Fedora 42 | Yes |
| [Yubico Security Key USB A NFC](https://support.yubico.com/s/article/Security-Key-NFC) | 5.4.3 | macOS Tahoe | Yes |
| [Yubico Security Key USB A NFC](https://support.yubico.com/s/article/Security-Key-NFC) | 5.4.3 | Debian 13 Trixie | |
| [Yubico Security Key USB A NFC](https://support.yubico.com/s/article/Security-Key-NFC) | 5.4.3 | Fedora 42 | Yes |
| [Yubico Security Key USB A NFC](https://www.yubico.com/products/security-key-by-yubico/usb-a-nfc/) | 5.0.2 | macOS Tahoe | Yes |
| [Yubico Security Key USB A NFC](https://www.yubico.com/products/security-key-by-yubico/usb-a-nfc/) | 5.0.2 | Debian 13 Trixie | |
| [Yubico Security Key USB A NFC](https://www.yubico.com/products/security-key-by-yubico/usb-a-nfc/) | 5.0.2 | Fedora 42 | Yes |
| [Yubico YubiKey 5C nano](https://support.yubico.com/s/article/YubiKey-5C-Nano) | 5.4.3 | macOS Tahoe | Yes |
| [Yubico YubiKey 5C nano](https://support.yubico.com/s/article/YubiKey-5C-Nano) | 5.4.3 | Debian 13 Trixie | Yes |
| [Yubico YubiKey 5C nano](https://support.yubico.com/s/article/YubiKey-5C-Nano) | 5.4.3 | Fedora 42 | Yes |
| [Yubico YubiKey 5 NFC](https://support.yubico.com/s/article/YubiKey-5-NFC) | 5.1.2 | macOS Tahoe | Yes |
| [Yubico YubiKey 5 NFC](https://support.yubico.com/s/article/YubiKey-5-NFC) | 5.1.2 | Debian 13 Trixie| Yes |
| [Yubico YubiKey 5 NFC](https://support.yubico.com/s/article/YubiKey-5-NFC) | 5.1.2 | Fedora 42| Yes |
| [SoloKeys Solo 1 Tap USB-A](https://solokeys.com/collections/all/products/solo-tap-usb-a-preorder) | | Ubuntu 24.04 | Yes |
| [SoloKeys Solo 1 Tap USB-A](https://solokeys.com/collections/all/products/solo-tap-usb-a-preorder) | | Debian 13 Trixie | Yes |
| [SoloKeys Solo 1 Tap USB-A](https://solokeys.com/collections/all/products/solo-tap-usb-a-preorder) | | Fedora 42 | Yes |
| [SoloKeys Solo 1 Tap USB-A](https://solokeys.com/collections/all/products/solo-tap-usb-a-preorder) | | macOS Tahoe | Yes |
| [HYPERSECU HyperFIDO mini](https://033c2a7e-e1da-473d-a255-6132a1d3aa6e.filesusr.com/ugd/5aae8d_f4e8a196a99f45b1859e201a7cb40962.pdf) | | macOS Tahoe | Yes |
| [HYPERSECU HyperFIDO mini](https://033c2a7e-e1da-473d-a255-6132a1d3aa6e.filesusr.com/ugd/5aae8d_f4e8a196a99f45b1859e201a7cb40962.pdf) | | Ubuntu 24.04 | Yes |
| [HYPERSECU HyperFIDO mini](https://033c2a7e-e1da-473d-a255-6132a1d3aa6e.filesusr.com/ugd/5aae8d_f4e8a196a99f45b1859e201a7cb40962.pdf) | | Debian 13 Trixie | |
| [HYPERSECU HyperFIDO mini](https://033c2a7e-e1da-473d-a255-6132a1d3aa6e.filesusr.com/ugd/5aae8d_f4e8a196a99f45b1859e201a7cb40962.pdf) | | Fedora 42 | Yes |
## Running Tests ## Running Tests
```bash ```bash
# Run the BATS test suite (64 tests) # Init test framework submodules (first time only)
git submodule update --init --recursive
# Unit tests (BATS) — runs in isolated $HOME, never touches real config
./test/run.sh ./test/run.sh
# Requires bats-core submodules — init them if needed # Interactive tests (tmux) — tests the full interactive flow on macOS/Linux
git submodule update --init --recursive ./test/run-interactive.sh
# Full e2e matrix — containers + interactive tests across distros
# Requires docker or podman
./test/e2e.sh # All distros + host
./test/e2e.sh --skip-host ubuntu # Single distro, skip host
./test/e2e.sh --runtime podman --skip-host # All distros via podman
./test/e2e.sh --rebuild alpine # Force image rebuild
``` ```
Tests run in an isolated `$HOME` (via `mktemp`) and never touch your real git or SSH config. | Test tier | What it covers | Requirements |
|-----------|---------------|--------------|
| `test/run.sh` | 92 BATS unit tests — config audit, apply, signing, key detection | `bats-core` submodule |
| `test/run-interactive.sh` | 4 tmux-driven tests — full accept, safety gate, signing wizard | `tmux` |
| `test/e2e.sh` | Container matrix (Ubuntu, Debian, Fedora, Alpine, Arch) + host interactive | `docker` or `podman` |
All tests run in isolated environments and never modify your real git or SSH configuration.
## License ## License

397
docs/REASONING.md Normal file
View File

@@ -0,0 +1,397 @@
# Reasoning: Why Each Default Was Chosen
Every setting `git-harden.sh` audits or applies exists because of a specific attack vector or operational risk. This document explains the trade-off behind each one.
Settings are grouped the same way they appear in the script's audit output.
---
## Identity
### `user.useConfigOnly = true`
**What it does:** Prevents git from falling back to system-level identity (hostname, login name) when `user.name` and `user.email` aren't set in `.gitconfig`.
**Attack/risk mitigated:** Accidental commits as `root@localhost` or `builduser@ci-runner-7` that pollute history with unattributable authorship. Common on fresh VMs, containers, and CI environments.
**What could break:** Commits will fail if you haven't run `git config user.name` and `git config user.email`. This is intentional friction — the first commit on a new machine requires explicit identity setup.
**Why this default:** The cost of one extra setup step is negligible. The cost of unattributable commits in a regulated codebase is an audit finding.
---
## Object Integrity
### `transfer.fsckObjects = true` / `fetch.fsckObjects = true` / `receive.fsckObjects = true`
**What it does:** Forces git to validate the structural integrity and hash consistency of every object (blob, tree, commit, tag) during transfer, fetch, and receive operations. Malformed objects are rejected.
**Attack/risk mitigated:** Malicious or corrupted packfiles that exploit parsing vulnerabilities in the git binary. Historical CVEs include integer overflows in packfile handling and crafted objects that trigger code execution. Also catches silent data corruption from disk/network errors.
**What could break:** Adds ~5-10% overhead to clone and fetch operations on large repositories. Some very old repositories with technically malformed (but benign) objects may fail to clone until the upstream runs `git fsck --full` and fixes them.
**Why this default:** The performance cost is small. The alternative — silently accepting corrupted objects — has no upside.
### `transfer.bundleURI = false`
**What it does:** Disables the bundle URI mechanism, which allows git servers to redirect clients to pre-packaged bundle files for faster initial clones.
**Attack/risk mitigated:** Reduces attack surface. Bundle URIs could redirect clients to attacker-controlled servers serving malicious bundles. The feature is relatively new (Git 2.39+) and not widely audited.
**What could break:** Initial clone performance for repositories hosted behind CDN-backed bundle URIs. GitHub does not currently use this feature for public repositories.
**Why this default:** No measurable benefit for most users. The feature's security properties are still maturing.
### `fetch.prune = true`
**What it does:** Automatically removes local remote-tracking references (e.g., `origin/feature-x`) when the corresponding remote branch has been deleted.
**Attack/risk mitigated:** Stale remote refs can be confusing and misleading. In a security context, a deleted branch that still appears locally may cause a developer to base work on abandoned or reverted code.
**What could break:** Nothing. This matches the behavior of `git fetch --prune`. Pruning only affects remote-tracking refs, not local branches.
**Why this default:** Pure hygiene with zero downside.
---
## Protocol Restrictions
### `protocol.version = 2`
**What it does:** Uses Git wire protocol v2 for client-server communication. Protocol v2 is more efficient (the server doesn't advertise all refs upfront) and has a smaller attack surface.
**Attack/risk mitigated:** Protocol v0/v1 sends the full ref advertisement on every connection, which leaks information about all branches and tags. Protocol v2 uses a capability-based negotiation that only transfers requested data.
**What could break:** Nothing in practice. Protocol v2 has been supported since Git 2.26 (April 2020) and all major hosting platforms support it. The client falls back gracefully if the server doesn't support v2.
**Why this default:** Strictly better. No known compatibility issues with any major git host.
### `protocol.allow = never` (default-deny)
### `protocol.https.allow = always` / `protocol.ssh.allow = always`
### `protocol.file.allow = user` / `protocol.git.allow = never` / `protocol.ext.allow = never`
**What it does:** Implements a default-deny protocol policy. Only HTTPS and SSH are permitted. The `file://` protocol is restricted to user-initiated operations. The unencrypted `git://` protocol and the `ext://` external transport helper are blocked entirely.
**Attack/risk mitigated:**
- `git://` transmits data unencrypted and unauthenticated — trivial MITM.
- `ext://` allows arbitrary command execution via transport helpers — this is by design, not a bug, but it's a dangerous capability that submodule URLs can exploit (e.g., CVE-2023-29007).
- `file://` is restricted because embedded bare repositories in cloned repos can be used for attacks (CVE-2022-39253).
**What could break:** Repositories that use `git://` URLs for remotes (rare — GitHub deprecated `git://` in 2022). The `url.https://.insteadOf` rewrite handles this automatically for HTTP URLs.
**Why this default:** The blocked protocols have no legitimate use case that can't be served by HTTPS or SSH. The risk/benefit ratio is extreme.
---
## Filesystem Protection
### `core.protectNTFS = true` / `core.protectHFS = true`
**What it does:** Blocks path manipulation attacks that exploit NTFS 8.3 short-name aliases (e.g., `GIT~1` resolving to `.git`) and HFS+ Unicode normalization (e.g., `.git` composed differently). Enabled on all platforms, not just Windows/macOS.
**Attack/risk mitigated:** CVE-2019-1352 (NTFS), various HFS+ attacks. A malicious repository can craft filenames that resolve to `.git/hooks/` on case-insensitive or normalizing filesystems, achieving code execution on clone.
**What could break:** Repositories containing filenames that happen to collide with NTFS 8.3 short names (extremely rare outside deliberate attacks).
**Why this default:** Enabled even on Linux because developers may clone repos onto external drives or share via mixed-OS teams.
### `core.fsmonitor = false`
**What it does:** Disables the filesystem monitor integration (fsmonitor, Watchman). This feature speeds up `git status` in large repos by using OS-level file change notifications.
**Attack/risk mitigated:** The fsmonitor hook (`core.fsmonitor--hook-version`) can execute arbitrary commands. A malicious repository could set this in its local config. Disabling it globally prevents this vector.
**What could break:** Performance of `git status` in very large repositories (100k+ files) where fsmonitor provides significant speedups. Developers working on such repos can override this per-repo.
**Why this default:** Most repositories are not large enough to notice the difference. The attack surface is not worth the performance gain for typical use.
### `core.symlinks = false` (interactive-only, skipped in `-y` mode)
**What it does:** Tells git to not create symbolic links in the working tree. Instead, symlinks are stored as plain text files containing the link target path.
**Attack/risk mitigated:** CVE-2024-32002 — repositories with crafted submodules could trick git into writing files outside the repository via symlink following during clone, achieving remote code execution on Windows and macOS.
**What could break:** Any project that relies on symlinks: Node.js monorepos (`node_modules/.bin/`), shared configuration files, many build systems. This is the most likely setting to cause real workflow breakage.
**Why this default:** **Not applied in `-y` mode** specifically because of breakage risk. In interactive mode, the user is asked with a clear warning. We already mitigate the primary CVE via `submodule.recurse = false`, so this is defense-in-depth, not the only protection.
---
## Hook Control
### `core.hooksPath = ~/.config/git/hooks`
**What it does:** Redirects git hook execution from each repository's `.git/hooks/` directory to a centralized, user-controlled directory.
**Attack/risk mitigated:** Malicious repositories can include hooks (e.g., `pre-commit`, `post-checkout`) that execute on clone, commit, or checkout. By redirecting to a user-managed directory, repo-local hooks are ignored unless explicitly installed.
**What could break:** Project-specific hooks defined in `.git/hooks/` or installed by frameworks like `husky`, `lefthook`, or `pre-commit`. Teams using these must either: (a) install their hooks into the global hooks directory, or (b) override `core.hooksPath` per-repo via `git config --local`.
**Why this default:** The attack is trivial to execute and devastating (arbitrary code execution). Teams that need repo-local hooks can override per-repo.
---
## Pre-commit Hook (gitleaks)
### Gitleaks pre-commit hook installation
**What it does:** Installs a pre-commit hook at `~/.config/git/hooks/pre-commit` that runs `gitleaks protect --staged` before every commit, scanning the staged diff for secrets (API keys, passwords, private keys, etc.).
**Attack/risk mitigated:** Secret leakage — the single most exploited vulnerability class in git. GitGuardian's 2026 report found 29 million new secrets on public GitHub in 2025. Median time-to-discovery by attackers: 20 seconds.
**What could break:** False positives on test fixtures or example credentials may require bypassing with `SKIP_GITLEAKS=1 git commit`. Adds ~1-2 seconds to each commit.
**Why this default:** Both research reports rank pre-commit secret scanning as the #1 workstation-level defense. The hook is safe without gitleaks installed (guards with `command -v`). The `SKIP_GITLEAKS` bypass avoids the need for `--no-verify` which skips ALL hooks.
---
## Repository Safety
### `safe.bareRepository = explicit`
**What it does:** Requires `--git-dir` to be explicitly specified when working with bare repositories. Prevents git from automatically detecting bare repositories in the current directory tree.
**Attack/risk mitigated:** An attacker who can write to a shared filesystem (e.g., `/tmp`, network drives) can plant a bare `.git` directory that git will auto-detect, allowing them to influence git operations of other users in that directory.
**What could break:** Scripts or workflows that `cd` into bare repositories without specifying `--git-dir`. Server-side hooks on self-hosted git servers may need adjustment.
**Why this default:** Bare repository auto-detection in untrusted directories is a documented attack vector. Most developers never interact with bare repos directly.
### `submodule.recurse = false`
**What it does:** Prevents git from automatically initializing and updating submodules during clone, checkout, and pull operations.
**Attack/risk mitigated:** CVE-2024-32002 (clone-time RCE via crafted submodules), CVE-2023-29007 (config injection via overlong submodule URLs), and the general risk of pulling untrusted code automatically. Submodules are the primary vector for filesystem-based git attacks.
**What could break:** Projects using submodules require manual `git submodule update --init`. This is a one-time setup cost per clone.
**Why this default:** Submodule auto-recursion is the enabler for multiple critical CVEs. Explicit initialization is a small price for eliminating an entire attack class.
### `safe.directory = *` detection and removal
**What it does:** Detects and offers to remove the `safe.directory = *` wildcard, which completely disables git's directory ownership safety check.
**Attack/risk mitigated:** CVE-2022-24765 — on shared systems, any user can plant a `.git` directory in a location another user will `cd` into, achieving arbitrary config injection and potentially code execution via hooks.
**What could break:** Removing the wildcard may surface ownership errors for repositories on network drives or external media. These should be added individually: `safe.directory = /path/to/specific/repo`.
**Why this default:** The wildcard is always wrong. It exists because people encounter the ownership error and google a quick fix without understanding what they're disabling.
---
## Pull/Merge Hardening
### `pull.ff = only` / `merge.ff = only`
**What it does:** Refuses non-fast-forward merges and pulls. If the remote branch has diverged, git will error instead of creating a merge commit or silently rebasing.
**Attack/risk mitigated:** Force-pushed branches (rewritten history) are surfaced as errors rather than silently merged. This makes history rewriting attacks visible — the developer must explicitly decide how to handle the divergence.
**What could break:** Workflows that routinely use merge commits will need to switch to `git pull --rebase` or `git merge --no-ff` explicitly. Some teams prefer merge commits for feature branch integration.
**Why this default:** Silent non-fast-forward merges hide potentially dangerous history rewrites. Making divergence explicit is strictly safer. Teams that want merge commits can override per-repo.
---
## Transport Security
### `url."https://".insteadOf = http://`
**What it does:** Automatically rewrites any `http://` remote URL to `https://`, ensuring all HTTP-based git operations use TLS encryption.
**Attack/risk mitigated:** Plaintext HTTP transmits credentials and code in the clear, enabling trivial MITM attacks on any network between the developer and the git server.
**What could break:** Repositories hosted on servers that genuinely only support HTTP (no TLS). This is increasingly rare and is itself a security concern.
**Why this default:** There is no legitimate reason to use unencrypted HTTP for git operations in 2026.
### `http.sslVerify = true`
**What it does:** Enforces TLS certificate verification for all HTTPS git operations. This is git's default, but the script audits it because `http.sslVerify = false` is a common "quick fix" that people forget to undo.
**Attack/risk mitigated:** Disabling SSL verification allows MITM attacks even over HTTPS — the attacker presents any certificate and git accepts it.
**What could break:** Self-signed certificates on internal git servers. The proper fix is to add the CA certificate to git's trust store (`http.sslCAInfo`), not to disable verification globally.
**Why this default:** Ensuring the default hasn't been overridden. This is a safety net, not a new restriction.
---
## Credential Storage
### Platform-specific credential helper (`osxkeychain` / `libsecret`)
**What it does:** Configures git to store credentials in the OS keychain (macOS Keychain, Linux libsecret/GNOME Keyring) instead of plaintext files.
**Attack/risk mitigated:** `git-credential-store` writes passwords to `~/.git-credentials` in plaintext. Modern infostealer malware specifically targets this file. OS keychains encrypt at rest and require authentication to access.
**What could break:** Nothing. Credential helpers are transparent to git operations. The only friction is initial keychain authentication on first use.
**Why this default:** Plaintext credential storage is the #1 workstation-level credential theft vector according to both research reports.
---
## Credential Hygiene (audit-only)
### Plaintext file detection (`~/.git-credentials`, `~/.netrc`, `~/.npmrc`, `~/.pypirc`)
**What it does:** Warns if plaintext credential files exist on the filesystem. Does not modify or delete them.
**Attack/risk mitigated:** These files are primary targets for infostealer malware and are trivially readable by any process running as the user.
**What could break:** Nothing — audit only.
**Why audit-only:** Deleting credential files could lock the user out of services. The script warns and lets the user decide.
---
## Global Gitignore
### `core.excludesFile = ~/.config/git/ignore`
**What it does:** Creates a global gitignore with patterns for common secret files (`.env`, `*.pem`, `*.key`, `credentials.json`), Terraform state (`*.tfstate`), and OS/IDE artifacts.
**Attack/risk mitigated:** Accidental commits of secrets and credentials. No amount of scanning catches what was never tracked in the first place.
**What could break:** Nothing — `.gitignore` only affects untracked files. Files already tracked are unaffected. The `!.env.example` negation allows committing example env files.
**Why this default:** A global gitignore is the simplest possible defense against the most common category of git security incidents.
---
## Defaults
### `init.defaultBranch = main`
**What it does:** Sets the default branch name for new repositories to `main` instead of `master`.
**Attack/risk mitigated:** None directly. This is an industry standardization that reduces confusion and aligns with GitHub's default (changed in October 2020).
**What could break:** Scripts that hardcode `master`. These should be updated regardless.
**Why this default:** Consistency with the ecosystem. Every major git hosting platform now defaults to `main`.
---
## Forensic Readiness
### `gc.reflogExpire = 180.days` / `gc.reflogExpireUnreachable = 90.days`
**What it does:** Extends git's reflog retention from the defaults (90 days reachable / 30 days unreachable) to 180/90 days. The reflog records every HEAD movement — commits, checkouts, resets, rebases.
**Attack/risk mitigated:** In a post-compromise investigation, the reflog is the primary tool for reconstructing what happened. Extended retention gives incident responders more time to discover and investigate force-push attacks, unauthorized commits, and branch manipulation.
**What could break:** Slightly more disk usage from retained reflog entries. The impact is negligible — reflogs are small text records.
**Why this default:** The Claude research report specifically recommends this for forensic readiness. The disk cost is trivial compared to the investigative value.
---
## Visibility
### `log.showSignature = true`
**What it does:** Shows GPG/SSH signature verification status in `git log` output by default.
**Attack/risk mitigated:** Makes unsigned or invalid signatures visible in normal workflow. Without this, developers must remember to use `git log --show-signature` to check.
**What could break:** Log output is slightly more verbose. Some terminal environments may not render the verification status cleanly.
**Why this default:** Signature verification is only useful if people see the results. Making it visible by default closes the gap between "we sign commits" and "we verify signatures."
---
## Signing Configuration
### `gpg.format = ssh`
**What it does:** Uses SSH keys (instead of GPG) for commit and tag signing.
**Attack/risk mitigated:** Same as GPG signing — proves key possession at commit time, preventing commit author impersonation (the PHP git server compromise of 2021 is the canonical example).
**Why SSH over GPG:** SSH keys are already managed by every developer. GPG requires a separate keyring, key server interaction, and has a notoriously steep learning curve. SSH signing (available since Git 2.34) provides equivalent cryptographic guarantees with dramatically less operational friction.
**Trade-off:** GPG has native support for key expiration and revocation. SSH signing on GitHub lacks automatic expiration — a compromised SSH key's signatures remain "Verified" even after the key is removed from the account. For high-security environments, GPG may be preferable despite the friction.
### `commit.gpgsign = true` / `tag.gpgsign = true` / `tag.forceSignAnnotated = true`
**What it does:** Automatically signs all commits and tags with the configured signing key.
**Attack/risk mitigated:** Without signing, anyone who can push to a repository can impersonate any other developer by setting `user.name` and `user.email` to their values. Signed commits prove the private key holder created the commit.
**What could break:** Commits will fail if no signing key is configured. The script only enables these settings when a key is available.
**Why this default:** Commit signing is an accountability control. In the PHP compromise, malicious commits were attributed to Rasmus Lerdorf and Nikita Popov — signing would have immediately flagged them as forgeries.
### `gpg.ssh.allowedSignersFile = ~/.config/git/allowed_signers`
**What it does:** Points git to a local file mapping email addresses to their authorized public keys, enabling local signature verification without a network round-trip.
**What could break:** Nothing — the file is additive. Without it, local verification simply doesn't work (signatures are only verified on the hosting platform).
---
## SSH Configuration
### `StrictHostKeyChecking = accept-new`
**What it does:** Automatically accepts host keys on first connection (TOFU — Trust On First Use) but rejects changed keys on subsequent connections.
**Trade-off:** `ask` (the default) prompts on every new host — most users blindly type "yes" without verifying the fingerprint, providing no real security benefit. `no` accepts anything, including MITM attacks. `accept-new` is the pragmatic middle ground: it stops the prompt fatigue while still detecting host key changes (the actual attack scenario).
### `HashKnownHosts = yes`
**What it does:** Stores host entries in `~/.ssh/known_hosts` as hashed values instead of plaintext hostnames.
**Attack/risk mitigated:** If the known_hosts file is exfiltrated, the attacker cannot enumerate which servers the developer connects to. Hashing makes the file useless for reconnaissance.
**What could break:** Manual inspection of `known_hosts` becomes impossible. `ssh-keygen -F hostname` still works for lookups.
### `IdentitiesOnly = yes`
**What it does:** Only offers SSH keys explicitly configured in `~/.ssh/config` (via `IdentityFile`) or specified on the command line. Without this, ssh-agent offers ALL loaded keys to every server.
**Attack/risk mitigated:** A malicious SSH server can enumerate which keys a client holds by observing which public keys are offered during authentication. With many keys loaded, this leaks information about which services the developer has access to.
**What could break:** Connections that rely on ssh-agent offering the right key automatically will need explicit `IdentityFile` entries in `~/.ssh/config`. This is good practice regardless.
### `AddKeysToAgent = yes`
**What it does:** Automatically adds keys to the SSH agent after first use, so the passphrase is only entered once per session.
**Why this default:** Reduces friction for passphrase-protected keys. Without this, developers either skip passphrases entirely (worse security) or get frustrated re-entering them (leads to workarounds).
### `PubkeyAcceptedAlgorithms = ssh-ed25519,sk-ssh-ed25519@openssh.com,...`
**What it does:** Restricts which public key algorithms the SSH client will offer and accept. Limited to ed25519, ed25519-sk (FIDO2), and ECDSA NIST P-256 variants (including sk).
**Attack/risk mitigated:** Prevents negotiation down to weak algorithms (DSA, RSA with SHA-1). Forces modern cryptography.
**What could break:** Connections to legacy servers that only support RSA. These servers should be upgraded; RSA-SHA1 is deprecated by OpenSSH since version 8.7.
**Why these algorithms:** Ed25519 is the recommended default (fast, small keys, no parameter pitfalls). ECDSA P-256 is included because some FIDO2 hardware keys only support it. RSA is excluded because accepting it creates a fallback path to weaker cryptography.
---
## SSH Key Hygiene (audit-only)
### Weak key detection (DSA, ECDSA, short RSA)
**What it does:** Scans `~/.ssh/*.pub` and keys referenced in `~/.ssh/config` for deprecated or weak key types.
**Why audit-only:** Key migration requires generating new keys, updating authorized_keys on all servers, and reconfiguring services. This is too impactful to automate.
---
## Admin Recommendations (informational only)
These settings require server/org-level access and cannot be applied by a workstation tool:
- **Branch protection rules** — prevent direct pushes to main
- **Vigilant mode** — flag unsigned commits visibly on the hosting platform
- **Force-push restrictions** — prevent history rewriting on protected branches
- **Fine-grained, short-lived tokens** — reduce blast radius of token compromise
- **Signed commit requirements** — enforce signing at the server level
- **Separate signing keys per org** — prevent cross-platform identity correlation (OSINT)

View File

@@ -0,0 +1,483 @@
# Git Security Hardening: A Practitioner's Reference
**The single most impactful thing an organization can do to harden its git security posture is enable push-time secret scanning.** GitGuardian's 2026 State of Secrets Sprawl report found **29 million new hardcoded secrets** on public GitHub in 2025 alone — a 34% year-over-year increase — with 64% of secrets from 2022 still unrevoked. Secret exposure remains the highest-likelihood, highest-impact attack surface because it requires zero sophistication to exploit: attackers scan public commits in real time, with a median time-to-discovery of **20 seconds** (Meli et al., NDSS 2019). Combined with branch protection enforcement, commit signing, and least-privilege token management, organizations can eliminate the most common git-related breach vectors with moderate effort.
This report covers the full git attack surface — from developer workstations through hosted platforms to CI/CD integration points — with platform-specific guidance for GitHub, GitLab, and Azure DevOps. Each section includes a threat model, numbered hardening checklist, real-world incident motivation, and residual risk assessment.
---
## Executive summary: ten highest-impact hardening measures
Ranked by risk reduction per unit of implementation effort for a typical 1050 developer organization:
1. **Enable push-time secret scanning** (GitHub Secret Protection or GitLab Ultimate push protection). Blocks the most frequently exploited vulnerability class before it enters the repository. ~1 hour to enable org-wide.
2. **Require pull request reviews on default and release branches** with dismissal of stale approvals. Prevents direct pushes of malicious or vulnerable code. ~30 minutes per repository, automatable via rulesets.
3. **Replace classic PATs with fine-grained, short-lived tokens** (GitHub fine-grained PATs, GitLab project tokens, or GitHub Apps). Eliminates the "keys to the kingdom" single-token failure mode that enabled the tj-actions and Trivy compromises. ~1 day for audit and migration.
4. **Enforce 2FA/MFA for all organization members.** Prevents account takeover — the root cause of the Gentoo GitHub compromise. ~1 hour to enable; budget 2 weeks for member compliance.
5. **Install a pre-commit hook stack** (gitleaks + framework) on all developer machines. Catches secrets before they enter git history, where removal is costly. ~2 hours via `core.hooksPath`.
6. **Pin GitHub Actions to full commit SHAs**, not version tags. Prevents supply-chain injection via mutable tags, as exploited in the tj-actions/changed-files and Trivy incidents. ~1 day for audit and update.
7. **Enable SSH commit signing with ed25519 keys.** Prevents commit author impersonation — the attack vector in the PHP git server compromise. ~1 hour per developer.
8. **Deploy a hardened `.gitconfig` template** org-wide (`fsckObjects`, `safe.bareRepository = explicit`, protocol restrictions). Blocks multiple client-side attack classes including CVE-2024-32002. ~30 minutes.
9. **Stream audit logs to a SIEM** (or at minimum, enable and review them weekly). Provides detection of privilege escalation, branch protection tampering, and anomalous clone activity. ~4 hours for initial setup.
10. **Restrict AI coding agent permissions** — enforce least-privilege tokens, prevent `--no-verify` bypasses, and require PR review for all AI-generated commits. Addresses the fastest-growing secret exposure vector (AI-assisted commits leak secrets at **2× the baseline rate**).
For organizations that can implement only five changes this quarter, start with items 1, 2, 3, 4, and 5.
---
## Table of contents
1. [Secret exposure](#1-secret-exposure)
2. [Authentication and access control](#2-authentication-and-access-control)
3. [Commit integrity](#3-commit-integrity)
4. [Branch protection and code review enforcement](#4-branch-protection-and-code-review-enforcement)
5. [Supply chain attacks via git](#5-supply-chain-attacks-via-git)
6. [Git hosting platform hardening](#6-git-hosting-platform-hardening)
7. [Developer workstation git security](#7-developer-workstation-git-security)
8. [Audit, monitoring, and incident response](#8-audit-monitoring-and-incident-response)
9. [Platform security feature comparison](#9-github-vs-gitlab-vs-azure-devops-security-feature-comparison)
10. [Appendix A: Minimal `.gitconfig` hardening template](#appendix-a-minimal-gitconfig-hardening-template)
11. [Appendix B: Pre-commit hook stack recommendation](#appendix-b-pre-commit-hook-stack-recommendation)
---
## 1. Secret exposure
### Threat model
**Who:** Any attacker scanning public repositories, or an insider with read access to private repos. **What:** Credentials, API keys, private keys, database connection strings committed to git history. **How:** Automated scanning of commits in real time (bots monitor the GitHub Events API), manual inspection after a breach, or scraping of repository history.
The scale of this problem is staggering. The landmark NDSS 2019 study by Meli et al. ("How Bad Can It Git?") found over **100,000 repositories** with leaked secrets, with a median of **1,793 unique new keys appearing per day** across public GitHub. Of these, **89% were genuinely sensitive** — not test keys. GitGuardian's 2026 report shows the problem is accelerating: **29 million new secrets** detected in 2025, and repositories using AI coding assistants exhibit a **6.4% secret leakage rate** versus a 1.5% baseline.
The Uber 2016 breach is the canonical cautionary tale: attackers found **hardcoded AWS access keys** in a private GitHub repository (accessed via credential-stuffed passwords on accounts without MFA). Those keys unlocked an S3 bucket containing 57 million user records. The result: a **$148 million FTC fine** and the criminal conviction of Uber's CISO for concealing the breach.
### Hardening checklist
**1. Enable push-time secret scanning on the hosting platform.** GitHub Secret Protection ($19/committer/month, now available on Team plans) blocks pushes containing detected secret patterns before they enter the repository. GitLab Ultimate provides equivalent push protection via server-side pre-receive hooks. Azure DevOps offers GitHub Advanced Security for Azure DevOps with similar capabilities. Push-time blocking is dramatically more effective than post-commit alerting — GitGuardian data shows **70% of secrets leaked in 2022 remained active** through 2025, indicating that alert-only approaches fail due to slow remediation.
**2. Deploy a pre-commit secret scanning tool** on all developer workstations (see Appendix B for detailed tool selection). This catches secrets before they reach the server, complementing platform-side scanning.
**3. Maintain comprehensive `.gitignore` patterns.** Every repository should exclude `.env`, `*.pem`, `*.key`, `*.p12`, `*.tfstate`, `credentials.json`, `service-account*.json`, `.npmrc`, `.pypirc`, and similar files. Use a global gitignore (`core.excludesfile`) for personal patterns plus repository-level `.gitignore` for project-specific ones.
**4. Understand and address the persistence problem.** Running `git rm secret.key && git commit` does **not** remove the secret from history. Git stores content as immutable blob objects; the original blob persists in packfiles and is cloned by every downstream user. **The primary remediation is always to rotate the secret immediately.** History rewriting is secondary cleanup. Use `git-filter-repo` (recommended by the Git project as the replacement for the deprecated `git filter-branch`) or BFG Repo-Cleaner. After rewriting, run `git reflog expire --expire=now --all && git gc --prune=now --aggressive`, force-push, and contact platform support to purge cached objects. Note that forks retain the pre-rewrite history, and all developers must delete and re-clone.
**5. Configure custom secret patterns** for organization-specific credential formats (internal API keys, database connection strings) beyond the default detection patterns provided by platforms.
### Residual risk
Push-time scanning catches only **known secret patterns**. Generic passwords, custom token formats, and secrets embedded in binary files evade pattern-based detection. The 2026 GitGuardian report notes that **58% of leaked credentials are "generic secrets"** that bypass standard detection. Defense-in-depth (pre-commit hooks + push protection + periodic full-history scans with TruffleHog's active verification) reduces but does not eliminate this residual risk. The operational cost is modest: pre-commit hooks add ~13 seconds to each commit, and occasional false positives require developer time to triage.
---
## 2. Authentication and access control
### Threat model
**Who:** External attackers via credential theft, phishing, or token leakage; insiders with excessive permissions. **What:** Unauthorized access to repositories, code modification, secret exfiltration. **How:** Compromised PATs, stolen SSH keys, OAuth token theft, or account takeover via password reuse.
The April 2022 Heroku/Travis CI OAuth token compromise demonstrated the blast radius of over-privileged tokens: stolen OAuth tokens from two integrators provided access to private repositories of dozens of organizations, including GitHub's own npm infrastructure. More recently, the March 2025 tj-actions/changed-files compromise (CVE-2025-30066) stemmed from a single compromised PAT belonging to a bot account — that one token affected **23,000+ downstream repositories**. The March 2026 Trivy supply-chain attack (CVE-2026-28353, CVSS 10.0) traced back to a single org-scoped PAT (`ORG_REPO_TOKEN`) used across 33 workflows; incomplete rotation after the first breach enabled a second, more devastating attack.
### Hardening checklist
**1. Use ed25519 SSH keys exclusively.** Ed25519 provides equivalent security to RSA-4096 with much smaller keys (68 vs. 544 characters), faster operations, and no parameter-selection pitfalls. Generate with `ssh-keygen -t ed25519 -C "user@company.com"`. GitHub blocks legacy RSA/SHA-1 signatures. For maximum security, use FIDO2 hardware-backed keys: `ssh-keygen -t ed25519-sk -O resident -O verify-required`.
**2. Replace classic PATs with fine-grained, scoped tokens.** GitHub classic PATs (`ghp_` prefix) with `repo` scope grant read/write access to **every repository the user can access** — a textbook violation of least privilege. GitHub fine-grained PATs (`github_pat_` prefix) scope to specific repositories with granular permissions and mandatory expiration. GitLab project/group access tokens provide similar scoping. Set maximum PAT lifetimes via org policy: 90 days for CI/CD, 30 days for one-off tasks.
**3. Prefer GitHub Apps over PATs for automation.** GitHub Apps generate **short-lived installation tokens** (1-hour expiry) with fine-grained, repository-scoped permissions — not tied to any human account. They survive employee departures without credential rotation and provide auditable "on behalf of" action trails. This is the single most effective control against the "over-privileged bot token" failure mode.
**4. Enforce SAML SSO and audit legacy credentials.** On GitHub Enterprise Cloud, PATs and SSH keys must be separately authorized for SSO after creation. Critical gap: on GitLab, project/group access tokens and deploy keys **bypass SSO enforcement entirely**. On Azure DevOps, PATs bypass device compliance and MFA requirements — only IP-fencing policies apply to non-interactive flows.
**5. Deploy SSH Certificate Authorities** (GitHub Enterprise Cloud). Certificates expire automatically (e.g., daily), eliminating key rotation as a manual process. CAs uploaded after March 2024 require certificate expiration dates.
**6. Implement IP allowlisting where feasible** (GitHub Enterprise Cloud, GitLab self-managed, Azure DevOps via Entra Conditional Access). Practical limitation: dynamic IPs for remote workers require VPN routing, and GitHub-hosted Actions runners have dynamic IPs — requiring self-hosted or larger runners with static IPs.
### Residual risk
SSO enforcement does not protect against all token types on all platforms. IP allowlisting is operationally expensive with distributed teams. Hardware security keys (FIDO2) provide the strongest authentication but introduce device-dependency risk. The operational cost of migrating from classic PATs to fine-grained PATs or GitHub Apps is moderate — budget 12 days for audit and migration per team.
---
## 3. Commit integrity
### Threat model
**Who:** Attackers with push access (via compromised credentials or server compromise) impersonating trusted developers. **What:** Forged commits attributed to maintainers, containing backdoors or malicious changes. **How:** Git allows arbitrary `user.name` and `user.email` configuration — without signing, anyone can commit as anyone.
The March 2021 PHP git server compromise is the definitive case study. Attackers pushed two commits to the official `php-src` repository on the self-hosted `git.php.net` server: one attributed to PHP creator Rasmus Lerdorf, another to core maintainer Nikita Popov. Both inserted a backdoor that would execute arbitrary PHP code via a specially crafted HTTP header. The commits had `Signed-off-by` trailers — but those are plain text, not cryptographic signatures. The PHP project subsequently migrated to GitHub and mandated 2FA.
### Hardening checklist
**1. Enable SSH commit signing org-wide** (recommended over GPG for simplicity). SSH signing, available since Git 2.34, uses keys developers already manage — no GPG keyring overhead. Configuration:
```
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
git config --global tag.gpgsign true
```
Maintain an `allowed_signers` file for local verification: `git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers`.
**2. Enable GitHub Vigilant Mode** (Settings → SSH and GPG keys → "Flag unsigned commits as unverified"). Without this, unsigned commits show no badge at all — making unsigned and forged commits visually indistinguishable from legitimate ones.
**3. Require signed commits via branch protection** on all default and release branches. GitHub supports this in both classic branch protection and rulesets. GitLab supports it via push rules. **Azure DevOps has no native commit signing verification** — signed commits are accepted but not validated or badged. Third-party pipeline decorators exist but are not equivalent.
**4. Understand what signing does and does not guarantee.** Signing proves **key possession at commit time** — it defeats impersonation and detects tampering. It does **not** prove the legitimate key owner was at the keyboard (a compromised machine with access to `ssh-agent` can produce valid signatures), and it does not prevent intentional malicious commits by a valid signer. Signing is an accountability control, not an authorization control.
**5. Monitor the SHA-1 to SHA-256 transition.** Git has used hardened SHA-1 (the `sha1collisiondetection` library) since Git 2.13.0, which detects known collision attack patterns with negligible false positive rates (< 2⁻⁹⁰). The SHA-1 chosen-prefix collision cost has fallen to approximately **$45,000** (Leurent & Peyrin, USENIX Security 2020, "SHA-1 is a Shambles"), and continues to decline with GPU advances. Git 3.0 (targeted for late 2026) will default new repositories to SHA-256, but **GitHub does not yet support SHA-256 repositories**, creating an ecosystem blocker. Practical risk today: low for most organizations due to the hardened SHA-1, but plan for migration.
### Residual risk
GitHub's squash-and-merge and rebase-and-merge operations create new unsigned commits, breaking signing chains. Sigstore/Gitsign offers keyless signing via OIDC identity, eliminating key management entirely, but GitHub does not yet display "Verified" badges for Gitsign signatures. For signing release artifacts (tarballs, binaries), signify or minisign are lightweight alternatives to GPG.
---
## 4. Branch protection and code review enforcement
### Threat model
**Who:** Malicious insiders, compromised accounts, or external attackers with any write access. **What:** Direct pushes of malicious code to production branches bypassing review. **How:** Pushing directly to unprotected branches, self-approving PRs, exploiting bypass vectors in branch protection configuration.
### Hardening checklist
**1. Require pull requests with at minimum one approving review** on default and release branches across all repositories. Use GitHub rulesets (preferred over classic branch protection — they aggregate restrictively, apply across fork networks, and support org-wide governance) or GitLab protected branches with "Allowed to push: No one."
**2. Enable "Dismiss stale approvals when new commits are pushed"** on all platforms. Without this, a developer can get approval, then push additional malicious commits and merge without re-review.
**3. Enable "Require approval of the most recent reviewable push"** (GitHub) or equivalent. This prevents a reviewer from pushing commits to a PR branch and then approving their own additions — a documented bypass vector identified by Legit Security that GitHub considers "working as expected."
**4. Check "Do not allow bypassing the above settings"** (GitHub) or restrict unprotect permissions (GitLab). By default, GitHub repository admins can bypass all branch protections. This single checkbox is the difference between "branch protection exists" and "branch protection is enforced."
**5. Use CODEOWNERS for security-critical paths** (authentication modules, cryptography, CI/CD configurations, the CODEOWNERS file itself). Protect the CODEOWNERS file with a self-referencing entry: `/.github/CODEOWNERS @security-team`. Validate that all listed code owners are active members with write permissions — invalid or departed users cause CODEOWNERS enforcement to fail silently.
**6. Require status checks before merging** (CI tests, SAST scans, secret scanning). Block merge unless all checks pass and branches are up to date with the target.
**7. Restrict force-push and branch deletion** on protected branches (default on GitHub and GitLab for protected branches, but verify explicitly).
### The "rubber stamp" problem
Branch protection is only as strong as the review process behind it. Research by Edmundson et al. (2013) found that **none of 30 developers** reviewing a web application found all seven known vulnerabilities, and more experience did not correlate with better detection. A 2024 study of OpenSSL and PHP code reviews found that even when security concerns were raised, **1820% went unfixed** due to disagreements. Code review becomes security theater when PRs are approved in under two minutes without comments, when reviewers lack security training, or when PR sizes exceed 400 lines.
Minimum viable security review: keep PRs under 400 lines, run automated SAST and secret scanning before human review, require conversation resolution before merge, and designate security-trained reviewers as CODEOWNERS for sensitive paths.
### Bypass vectors to monitor
Admin override (without "Do not allow bypassing"), GitHub Actions self-approval (a bot can use `GITHUB_TOKEN` to approve PRs — disable via org settings), PAT-based PR creation and approval (if a `repo`-scoped PAT exists in Actions secrets), and CODEOWNERS misconfiguration (invalid users, unprotected CODEOWNERS file, or the "Require review from Code Owners" toggle not enabled).
---
## 5. Supply chain attacks via git
### Threat model
**Who:** Nation-state actors (xz-utils pattern), opportunistic attackers (pwn requests), or automated bots. **What:** Injecting malicious code into software supply chains via git-hosted repositories, build systems, or CI/CD pipelines. **How:** Social engineering of maintainers, exploitation of CI workflow misconfigurations, fork-based object injection, or dependency confusion.
The **xz-utils backdoor** (CVE-2024-3094, CVSS 10.0) represents the most sophisticated git-related supply chain attack to date. An attacker using the identity "Jia Tan" spent **over two years** building trust in the xz-utils project through legitimate contributions, while sockpuppet accounts ("Jigar Kumar," "Dennis Ens") pressured the burned-out sole maintainer to grant commit access. The backdoor was injected via the build system (M4 macros in the release tarball, not visible in the git source), targeting SSH on Debian/Fedora x86_64 systems. Discovery was accidental: Microsoft engineer Andres Freund noticed SSH logins consuming 500ms instead of 100ms.
The **Codecov breach** (JanuaryApril 2021) demonstrated a different vector: attackers extracted a GCS credential from a Docker image layer, modified the Codecov bash uploader script to exfiltrate CI environment variables (including git credentials and tokens) from approximately **29,000 enterprise customers'** CI runners. A customer discovered the compromise by comparing the downloaded script's SHA-256 hash against the one on GitHub — they did not match.
### Hardening checklist
**1. Pin all GitHub Actions to full commit SHAs**, not version tags. Mutable tags are the primary attack vector in Actions supply-chain compromises: the tj-actions/changed-files attacker retroactively updated multiple version tags to reference malicious commits. Use `uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11` instead of `uses: actions/checkout@v4`.
**2. Set `GITHUB_TOKEN` permissions to read-only by default** at the organization level (Settings → Actions → General → Workflow permissions → Read repository contents and packages permissions). Grant write permissions explicitly per-workflow using the `permissions:` block.
**3. Never use `pull_request_target` with checkout of the PR head.** The `pull_request_target` trigger runs with full repository secrets and write tokens but can be tricked into executing attacker-controlled code from a fork PR. If `pull_request_target` is required, gate execution behind a maintainer-applied label (e.g., `safe-to-test`) and never check out `github.event.pull_request.head.sha`. The February 2026 "hackerbot-claw" campaign exploited exactly this misconfiguration to steal org-scoped PATs from the Trivy project.
**4. Restrict fork creation for sensitive repositories** and audit the fork network. GitHub forks share the underlying object store — data from deleted forks or private forks can remain accessible via commit SHA in the parent repository. This is documented behavior, not a bug. Run `trufflehog github-experimental --repo <URL> --object-discovery` to scan for cross-fork object reference (CFOR) exposures.
**5. Implement SLSA Level 2+ build provenance.** Use the `slsa-framework/slsa-github-generator` reusable workflow to generate signed provenance attestations for release artifacts. Verify with `slsa-verifier` or `gh attestation verify` in deployment pipelines. SLSA L3 (hardened, isolated builds) would have made the SolarWinds attack — where malware was injected at compile time by the SUNSPOT implant, not in the source repository — significantly harder.
**6. Run OpenSSF Scorecard** weekly on all repositories. The automated tool evaluates branch protection, dangerous workflow patterns (including `pull_request_target` misconfigurations), pinned dependencies, token permissions, and signed releases. Integrate via the `ossf/scorecard-action` GitHub Action.
**7. Review `.gitmodules` changes as high-risk in code review.** Submodule URL manipulation (including CVE-2023-29007, which allowed arbitrary git config injection via overlong submodule URLs) is an active attack vector. Prefer proper package managers over submodules where possible.
### Residual risk
The xz-utils pattern — years of social engineering culminating in build-system-only backdoors invisible in git source — is extremely difficult to defend against programmatically. Reproducible builds, multi-maintainer release signing, and comparing source against release tarballs are the best mitigations, but they require significant process maturity. The SLSA framework provides a graduated path toward build integrity.
---
## 6. Git hosting platform hardening
### Threat model
**Who:** External attackers targeting organization-wide misconfigurations; insiders exploiting overly permissive defaults. **What:** Mass data exfiltration, privilege escalation, or persistence via platform settings. **How:** Account takeover of admins (Gentoo pattern), exploitation of default-permissive organization settings, or abuse of integration permissions.
### Hardening checklist
**1. Enforce 2FA for all organization members.** Available on all GitHub tiers (Free, Team, Enterprise). The Gentoo GitHub compromise (June 2018) was enabled by a single admin account without 2FA — the attacker guessed the password using a predictable password scheme. Non-compliant members are removed (GitHub) or blocked (GitLab). Budget a 2-week compliance window.
**2. Set base member permissions to "No permission" or "Read"** rather than the default "Write." Grant additional permissions via teams.
**3. Restrict repository creation to organization owners** or specific teams. Prevent uncontrolled proliferation of repositories with inconsistent security settings.
**4. Disable forking of private repositories** unless specifically required. All forks of public repos are always public — this cannot be overridden.
**5. Set default repository visibility to "Private"** (or "Internal" on Enterprise) to prevent accidental public exposure.
**6. Enable audit log streaming to a SIEM** (see Section 8). GitHub Enterprise streams to Splunk, Datadog, Azure Sentinel, S3, and GCS. GitLab Ultimate streams to HTTP endpoints, S3, GCS, and Azure Event Hubs.
**7. Apply CIS Benchmarks** where available. The CIS GitHub Benchmark (v1.2.0) and CIS GitLab Benchmark (v1.0.1, with 125+ recommendations) provide audit-ready configuration checklists. GitLab provides an open-source CIS benchmark scanner CLI tool. No standalone CIS benchmark exists for Azure DevOps.
### Self-hosted versus cloud
Self-hosting (GitHub Enterprise Server, GitLab self-managed) provides network isolation and data sovereignty but **shifts the patching burden** to the organization. Recent GitLab self-managed CVEs underscore this risk: CVE-2025-25291/25292 (CVSS 8.8, SAML authentication bypass), CVE-2025-6948 (CVSS 8.7, CI/CD pipeline authorization bypass), and CVE-2025-0605 (2FA bypass via Git CLI). For organizations without dedicated security infrastructure teams — the typical Three Backticks Security client — **cloud-hosted platforms are usually more secure** because the vendor handles patching, and the latest security features ship immediately.
---
## 7. Developer workstation git security
### Threat model
**Who:** Attackers who can influence repository content (malicious hooks, crafted objects) or access developer machines. **What:** Code execution on developer machines via cloned repositories, credential theft from insecure storage. **How:** Malicious git hooks, crafted git objects exploiting parsing vulnerabilities, symlink attacks, or plaintext credential files.
**CVE-2024-32002** (Critical) demonstrated this risk: repositories with submodules could trick Git into executing a hook during clone, achieving remote code execution on Windows and macOS. The `git clone` command — seemingly safe — became an attack vector.
### Hardening checklist
**1. Use a secure credential helper.** Never use `git-credential-store` (stores credentials as plaintext in `~/.git-credentials`). Per-platform recommendations: **Windows:** Git Credential Manager (bundled with Git for Windows). **macOS:** `osxkeychain` or GCM. **Linux:** `libsecret` or GCM. For CI/CD, use environment variables or short-lived tokens.
**2. Deploy the hardened `.gitconfig` template** from Appendix A org-wide. Critical directives: `transfer.fsckObjects = true` (verifies integrity of all transferred objects, catching malformed or crafted objects), `safe.bareRepository = explicit` (prevents embedded bare repository attacks), `protocol.git.allow = never` (disables the unencrypted, unauthenticated `git://` protocol), and `core.hooksPath` pointing to a centralized, organization-managed hooks directory.
**3. Never set `safe.directory = *`.** This wildcard **completely disables** the ownership safety check introduced in Git 2.35.2 (CVE-2022-24765), allowing any user on a shared system to exploit a planted `.git` directory. Add specific trusted directories individually.
**4. Set `core.hooksPath` to a centralized, version-controlled hooks directory.** This overrides per-repository `.git/hooks/` directories, preventing execution of untrusted hooks from cloned repos. Distribute standardized hooks (pre-commit secret scanning, commit message validation) via this path.
**5. Enable path traversal protections**: `core.protectNTFS = true` and `core.protectHFS = true` even on Linux servers, to protect developers on mixed-OS teams from NTFS 8.3 short-name attacks (CVE-2019-1352) and HFS+ Unicode normalization attacks.
### AI coding agents require specific controls
AI coding agents are now a material attack surface. Claude Code alone accounts for **over 4% of all public GitHub commits** as of March 2026. GitGuardian reports AI-assisted commits leak secrets at **double the baseline rate** (~3.2% vs. ~1.5%). Key risks and mitigations:
- **Agents bypass pre-commit hooks.** Cursor and Cline are documented to append `--no-verify` to git commits. Mitigation: enforce secret scanning server-side (push protection), not just client-side hooks. Consider the `block-no-verify` package or Claude Code's `PreToolUse` hooks.
- **Agents with overprivileged tokens.** AI agents given broad PATs can be exploited via prompt injection in repository content (issues, README files, code comments, `.cursorrules` files). The IDEsaster research (December 2025) found **100% of tested AI coding tools** vulnerable to prompt injection, with CVE-2025-53773 (CVSS 9.6) affecting GitHub Copilot. Mitigation: scope agent tokens to read-only on specific repositories; use ephemeral, OAuth-scoped credentials.
- **Agents performing destructive operations.** Reports document Cursor running `git push --force-with-lease --no-verify` without permission. Mitigation: use Claude Code's auto mode (which blocks force-pushes via a classifier) or restrict agent git permissions to exclude force-push.
- **62% of AI-generated C programs contain vulnerabilities** (FormAI-v2 dataset, 2024). Treat all AI-generated code as untrusted — enforce the same review requirements as human-authored code.
---
## 8. Audit, monitoring, and incident response
### Threat model
**Who:** Any attacker who has gained access — detection depends on monitoring coverage. **What:** Detecting and responding to compromised accounts, unauthorized changes, and data exfiltration. **How:** Audit log analysis, anomaly detection, and git forensics.
### Hardening checklist
**1. Enable and stream audit logs.** GitHub Enterprise streams to Splunk, Datadog, Azure Sentinel, S3, and GCS. GitLab Ultimate streams structured JSON to HTTP endpoints, S3, GCS, and Azure Event Hubs. Azure DevOps streams to Log Analytics, Splunk, and Event Grid (90-day default retention; audit streaming must be explicitly enabled — it is off by default).
**2. Monitor these critical events**: branch protection rule changes (`protected_branch.destroy`), force-pushes to default branches, repository visibility changes to public, new deploy key creation, PAT creation followed by mass cloning (correlated detection), admin role self-assignment, webhook creation/modification, and SSO/2FA policy changes.
**3. Extend reflog retention for forensic readiness.** Default retention is 90 days (reachable commits) and 30 days (unreachable). Extend with:
```
git config --global gc.reflogExpire 180.days
git config --global gc.reflogExpireUnreachable 90.days
```
**4. Know the forensic toolkit for post-compromise investigation.** `git reflog --date=iso` shows every change to HEAD with timestamps. Force-push events appear as "forced-update" in `git reflog show origin/main`. `git fsck --unreachable --no-reflogs` finds truly orphaned commits that may contain evidence. **Disable garbage collection immediately** during an investigation: `git config gc.auto 0`.
**5. Integrate git events into existing SIEM detection rules.** Pre-built integrations exist for Microsoft Sentinel (sentinel4github), Datadog Cloud SIEM (native GitHub rules), Panther (Python detection-as-code), Elastic Security (git hook execution detection on Linux endpoints), and Google SecOps (YARA-L rules for GitHub audit logs).
### Residual risk
Audit logs capture platform events, not all git operations. A sophisticated attacker who clones a repository via an authorized token and exfiltrates code will appear as normal `git.clone` activity. Anomaly detection (e.g., mass cloning of multiple private repositories in a short window) is the primary detection mechanism for data exfiltration, but tuning thresholds to avoid alert fatigue requires operational investment.
---
## 9. GitHub vs GitLab vs Azure DevOps security feature comparison
| Security capability | GitHub | GitLab | Azure DevOps |
|---|---|---|---|
| **MFA enforcement** | Org/Enterprise (all tiers); blocks non-compliant members | Instance/Group (all tiers); grace period configurable | Via Entra Conditional Access (not native) |
| **SSO/SAML** | Enterprise Cloud only | All tiers (self-managed); group-level (SaaS) | Native via Entra ID |
| **Fine-grained tokens** | Fine-grained PATs + GitHub Apps | Project/Group tokens | Scoped PATs (no repo-level scoping) |
| **Branch protection** | Rulesets (org-wide) + classic rules | Protected branches + push rules (Premium+) | Branch policies with build validation |
| **Commit signing verification** | ✅ GPG + SSH + S/MIME badges | ✅ GPG + SSH badges | ❌ No native support |
| **Secret scanning** | 200+ types; push protection ($19/committer/mo) | Secret detection; push protection (Ultimate) | Via GHAzDO ($19/committer/mo) |
| **SAST (code scanning)** | CodeQL ($30/committer/mo) | Multiple engines (Ultimate, $99/user/mo) | CodeQL via GHAzDO ($30/committer/mo) |
| **DAST** | Third-party only | ✅ Native (Ultimate) | Third-party only |
| **Container scanning** | Third-party only | ✅ Native (Ultimate) | Third-party only |
| **Fuzz testing** | Third-party only | ✅ Web API fuzzing (Ultimate) | Third-party only |
| **Dependency scanning** | Dependabot (free for alerts) | Native (Ultimate) | Via GHAzDO |
| **Compliance frameworks** | Rulesets | ✅ Centralized frameworks (Ultimate) | Branch policies only |
| **Audit log streaming** | Enterprise only | Ultimate only | Log Analytics, Splunk, Event Grid |
| **IP allowlisting** | Enterprise Cloud | Self-managed (network level) | Entra Conditional Access |
| **CIS Benchmark** | ✅ v1.2.0 | ✅ v1.0.1 (with scanner tool) | ❌ None |
| **Self-hosted option** | Enterprise Server | Self-managed CE/EE | Azure DevOps Server |
| **Security pricing** | Base $21/user + GHAS $49/committer/mo | Ultimate $99/user/mo (all inclusive) | Free base + GHAzDO $49/committer/mo |
**Key takeaway for Three Backticks Security clients:** GitHub offers the most granular token management (fine-grained PATs, GitHub Apps) and the strongest commit signing ecosystem. GitLab Ultimate provides the broadest native scanner coverage (DAST, container scanning, fuzzing) at a simpler all-inclusive price point. Azure DevOps lags significantly in git-specific security — no commit signing verification, no native MFA enforcement, and limited audit capabilities compared to the other two platforms.
---
## Appendix A: Minimal `.gitconfig` hardening template
```ini
# ============================================================
# SECURITY-HARDENED ~/.gitconfig — Three Backticks Security
# Deploy org-wide via configuration management
# ============================================================
[user]
name = Your Name
email = your.email@company.com
# Prevent commits without explicit identity
useConfigOnly = true
[credential]
# OS-native secure storage (never use 'store')
# Windows: manager | macOS: osxkeychain | Linux: libsecret
helper = osxkeychain
[core]
# Centralized hooks — overrides per-repo .git/hooks/
hooksPath = ~/.config/git/hooks
# Path traversal protections (enable on ALL platforms)
protectNTFS = true
protectHFS = true
# Disable symlinks to prevent symlink-based attacks
symlinks = false
[transfer]
# Verify integrity of ALL transferred objects
fsckObjects = true
# Disable bundle URI fetching
bundleURI = false
[fetch]
fsckObjects = true
prune = true
[receive]
fsckObjects = true
[protocol]
version = 2
[protocol "file"]
# Restrict local file protocol (CVE-2022-39253)
allow = user
[protocol "git"]
# DISABLE unencrypted, unauthenticated git:// protocol
allow = never
[protocol "ext"]
# Disable external transport helpers
allow = never
[safe]
# Require explicit --git-dir for bare repos
bareRepository = explicit
# NEVER add: directory = *
[commit]
gpgsign = true
[tag]
gpgsign = true
[gpg]
# SSH signing (simpler than GPG)
format = ssh
[gpg "ssh"]
allowedSignersFile = ~/.config/git/allowed_signers
[push]
default = current
autoSetupRemote = true
[init]
templateDir = ~/.config/git/template
defaultBranch = main
[url "https://"]
# Force HTTPS for any git:// URLs
insteadOf = git://
```
---
## Appendix B: Pre-commit hook stack recommendation
### Recommended stack: gitleaks via the pre-commit framework
**Why gitleaks over alternatives:** Gitleaks (Go, MIT license, 160+ built-in detectors) is the best general-purpose pre-commit secret scanner for most organizations. It strikes the optimal balance: fast execution (Go binary, no runtime dependencies), low false-positive rate, extensible TOML configuration, and active maintenance. TruffleHog v3 is more comprehensive (800+ detectors, active API verification) but its AGPL license and heavier runtime make it better suited for CI pipeline scanning than developer-workstation pre-commit hooks. detect-secrets (Yelp) excels in legacy codebases with its baseline approach but requires Python. git-secrets (AWS Labs) is AWS-focused and showing reduced maintenance (272+ unresolved issues).
### Installation via pre-commit framework
```yaml
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.21.2
hooks:
- id: gitleaks
```
```bash
# Install pre-commit framework
pip install pre-commit
# Install hooks in the repository
pre-commit install
# Run against all files (first-time scan)
pre-commit run --all-files
```
### Organization-wide deployment via `core.hooksPath`
For enforcement beyond individual repositories:
```bash
# Create centralized hooks directory
mkdir -p ~/.config/git/hooks
# Create pre-commit hook that runs gitleaks
cat > ~/.config/git/hooks/pre-commit << 'EOF'
#!/bin/bash
# Org-wide pre-commit secret scanning
if command -v gitleaks &> /dev/null; then
gitleaks protect --staged --redact --verbose
if [ $? -ne 0 ]; then
echo "❌ Secret detected. Commit blocked."
echo "If false positive, use: SKIP=gitleaks git commit"
exit 1
fi
fi
EOF
chmod +x ~/.config/git/hooks/pre-commit
# Set globally
git config --global core.hooksPath ~/.config/git/hooks
```
### Complementary CI pipeline scanning
Add TruffleHog in CI for deeper scanning with active verification:
```yaml
# GitHub Actions
- name: TruffleHog scan
uses: trufflesecurity/trufflehog@main
with:
extra_args: --only-verified --results=verified,unknown
```
### Tool selection matrix
| Criterion | gitleaks | TruffleHog v3 | detect-secrets | git-secrets |
|---|---|---|---|---|
| **Best role** | Pre-commit hook | CI pipeline scan | Legacy codebase onboarding | AWS-only environments |
| **Speed** | Fast (Go binary) | Moderate (verification adds latency) | Fast (diff-only) | Fast (bash/grep) |
| **False positive rate** | Low | Very low (verification) | Low (baseline filtering) | Moderate |
| **Maintenance status** | Active | Active | Active | Low maintenance |
| **License** | MIT | AGPL 3.0 | Apache 2.0 | Apache 2.0 |
| **Operational cost** | ~12s per commit | ~1030s per scan | ~1s per commit | ~1s per commit |
The recommended stack for a Three Backticks Security client is: **gitleaks as pre-commit hook** (developer workstation) + **TruffleHog v3 in CI** (verified scanning) + **platform push protection** (server-side enforcement). This three-layer approach provides defense-in-depth against the most common and damaging class of git security vulnerabilities.
---
*Prepared by Three Backticks Security. This document reflects the state of git security tooling and platform features as of March 2026. Platform features, pricing, and tool versions should be verified against current vendor documentation before implementation.*

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,330 @@
# git-harden.sh v0.2.0 — Expanded Hardening Features
## Motivation
Gap analysis of two independent research reports (Claude Opus 4.6 and Gemini 3.1 Pro, March 2026) against the v0.1.0 script identified six feature areas where the script falls short of current best-practice recommendations. All additions follow the existing audit+apply pattern and require no new CLI flags.
### Source Reports
- `docs/research/Claude Opus 4.6 report.md`
- `docs/research/Gemini 3.1 Pro report.md`
## Scope
All changes are additive — no existing behavior changes. The v0.2.0 script will:
1. Install a gitleaks pre-commit hook
2. Create and configure a global gitignore
3. Detect plaintext credential files
4. Audit SSH key hygiene
5. Add 8 new git config settings
6. Detect dangerous `safe.directory = *` wildcard
Version bump: `0.1.0``0.2.0`.
---
## Feature 1: Pre-commit Hook Installation (gitleaks)
### Background
Both reports rank pre-commit secret scanning as the single most impactful workstation-level defense. The v0.1.0 script sets `core.hooksPath = ~/.config/git/hooks` but installs no hooks, leaving the directory empty.
### Audit Behavior
- Check if `~/.config/git/hooks/pre-commit` exists and is executable.
- If it exists, check whether it contains a `gitleaks` invocation (grep for `gitleaks`).
- `[OK]` if pre-commit hook exists and references gitleaks.
- `[WARN]` if pre-commit hook exists but does NOT reference gitleaks (user-managed hook — don't touch).
- `[MISS]` if no pre-commit hook exists.
### Apply Behavior
- Check if `gitleaks` is on `$PATH` via `command -v gitleaks`.
- If gitleaks is found and no pre-commit hook exists:
- Create `~/.config/git/hooks/pre-commit` with the following content:
```bash
#!/usr/bin/env bash
# Installed by git-harden.sh — global pre-commit secret scanning
# To bypass for a single commit: SKIP_GITLEAKS=1 git commit
set -o errexit
set -o nounset
set -o pipefail
if [ "${SKIP_GITLEAKS:-0}" = "1" ]; then
exit 0
fi
if command -v gitleaks >/dev/null 2>&1; then
gitleaks protect --staged --redact --verbose
fi
```
- `chmod +x` the hook.
- If gitleaks is NOT found:
- `[WARN]` with install instructions:
- macOS: `brew install gitleaks`
- Linux: `brew install gitleaks` or download from GitHub releases
- Still create the hook script (it guards with `command -v` so it's safe without gitleaks installed). Prompt the user before creating.
- If a pre-commit hook already exists (any content): warn and skip. Do not overwrite user-managed hooks.
### Bypass Mechanism
The `SKIP_GITLEAKS=1` environment variable allows a single commit to bypass the hook without `--no-verify` (which skips ALL hooks). This is documented in the hook script itself.
### Acceptance Criteria
- `--audit` reports status of pre-commit hook with gitleaks.
- Apply creates a working hook that blocks commits containing secrets.
- Existing user hooks are never overwritten.
- Hook is safe to install even if gitleaks is not yet installed.
---
## Feature 2: Global Gitignore
### Background
Both reports stress maintaining comprehensive `.gitignore` patterns for secrets. No amount of scanning catches what was never tracked in the first place.
### Audit Behavior
- Check if `core.excludesFile` is set in global git config.
- If not set: `[MISS]`.
- If set: check whether the referenced file contains key security patterns (`.env`, `*.pem`, `*.key`).
- `[OK]` if file exists and contains at least one security pattern.
- `[WARN]` if file exists but lacks security patterns: "Global gitignore at <path> lacks secret patterns (.env, *.pem, *.key). Consider adding them."
### Apply Behavior
- If `core.excludesFile` is not set:
- Create `~/.config/git/ignore` with the following patterns:
```gitignore
# === Security: secrets & credentials ===
.env
.env.*
!.env.example
*.pem
*.key
*.p12
*.pfx
*.jks
credentials.json
service-account*.json
.git-credentials
.netrc
.npmrc
.pypirc
# === Security: Terraform state (contains secrets) ===
*.tfstate
*.tfstate.backup
# === OS artifacts ===
.DS_Store
Thumbs.db
Desktop.ini
# === IDE artifacts ===
.idea/
.vscode/
*.swp
*.swo
*~
```
- Set `core.excludesFile = ~/.config/git/ignore` via `apply_git_setting`.
- If `core.excludesFile` is already set to a different path:
- Print `[INFO]` noting the existing path. Do not modify or overwrite.
- If the file lacks security patterns, print `[WARN]` with the missing patterns (informational only — no auto-append).
### Acceptance Criteria
- Audit reports whether `core.excludesFile` is configured.
- Audit checks existing gitignore files for security pattern coverage and warns if missing.
- Apply creates the file and sets the config only when nothing is configured.
- Existing configurations are never modified — warnings are informational.
- The `!.env.example` negation allows committing example env files.
---
## Feature 3: Plaintext Credential File Detection
### Background
Both reports warn that `git-credential-store` writes passwords to `~/.git-credentials` in plaintext. The Gemini report additionally calls out infostealer malware targeting this file. Adjacent credential files (.netrc, .npmrc, .pypirc) pose similar risks.
### Audit Behavior (audit-only, no apply action)
Check for existence and content of these files:
| File | Detection | Severity |
|------|-----------|----------|
| `~/.git-credentials` | File exists | `[WARN]` — "Plaintext git credentials. Migrate to credential helper (osxkeychain/libsecret) and delete this file." |
| `~/.netrc` | File exists | `[WARN]` — "Plaintext network credentials found. May contain git hosting tokens." |
| `~/.npmrc` | File contains `_authToken=` followed by a non-empty value (regex: `_authToken=.+`) | `[WARN]` — "npm registry token in plaintext. Use `npm config set` with env vars instead." |
| `~/.pypirc` | File contains `password` | `[WARN]` — "PyPI credentials in plaintext. Use keyring or token-based auth instead." |
### Apply Behavior
None. The script does not delete or modify user credential files. Warnings are informational only.
### Section Placement
New section: "Credential Hygiene" — placed after the existing "Credential Storage" audit.
### Acceptance Criteria
- Each detected file produces a specific, actionable warning.
- No false positives on files that don't contain credentials (e.g., .npmrc with only registry URL, no token).
- No files are modified or deleted.
---
## Feature 4: SSH Key Hygiene Audit
### Background
Both reports recommend ed25519 exclusively. The Claude report notes GitHub blocks legacy RSA/SHA-1 signatures. The Gemini report recommends banning DSA and ECDSA.
### Audit Behavior (audit-only, no apply action)
- Scan `~/.ssh/*.pub` files.
- Additionally, parse `IdentityFile` directives from `~/.ssh/config` (the v0.1.0 script already has this parsing logic in `detect_existing_keys`) and include any referenced `.pub` files not already covered by the glob.
- For each `.pub` file, read the first field to determine key type.
- Use `ssh-keygen -l -f <file>` to extract bit length for RSA keys.
- Report:
| Key Type | Verdict |
|----------|---------|
| `ssh-ed25519` | `[OK]` |
| `sk-ssh-ed25519@openssh.com` | `[OK]` |
| `ssh-rsa` with >= 2048 bits | `[WARN]` — "RSA key (%d bits). Consider migrating to ed25519." |
| `ssh-rsa` with < 2048 bits | `[WARN]` — "Weak RSA key (%d bits). Migrate to ed25519 immediately." |
| `ssh-dss` | `[WARN]` — "DSA key (deprecated). Migrate to ed25519." |
| `ecdsa-sha2-*` | `[WARN]` — "ECDSA key. Consider migrating to ed25519." |
| `sk-ecdsa-sha2-*` | `[OK]` — Hardware-backed ECDSA is acceptable. |
### Apply Behavior
None. Key migration is too risky to automate. Warnings are informational.
### Section Placement
New section: "SSH Key Hygiene" — placed after the existing "SSH Configuration" audit.
### Acceptance Criteria
- All `.pub` files in `~/.ssh/` are scanned and classified.
- RSA bit length is correctly extracted.
- No false warnings on ed25519 or ed25519-sk keys.
- No keys are modified or deleted.
---
## Feature 5: Additional Git Config Settings
### Background
Eight new settings recommended by one or both reports that the v0.1.0 script does not audit or apply.
### Settings
| Setting | Value | Rationale | Report Source | Section |
|---------|-------|-----------|---------------|---------|
| `user.useConfigOnly` | `true` | Prevent commits without explicit identity — forces user.name/email to be set, blocking accidental commits under system defaults | Claude | New: "Identity" |
| `gc.reflogExpire` | `180.days` | Extend reflog retention for forensic readiness (default 90 days) | Claude | New: "Forensic Readiness" |
| `gc.reflogExpireUnreachable` | `90.days` | Extend unreachable reflog retention (default 30 days) | Claude | New: "Forensic Readiness" |
| `transfer.bundleURI` | `false` | Disable bundle URI fetching — reduces attack surface | Claude | Existing: "Object Integrity" |
| `protocol.version` | `2` | Wire protocol v2 — better performance, reduced attack surface from reference advertisements | Gemini | Existing: "Protocol Restrictions" |
| `init.defaultBranch` | `main` | Modern default branch name | Claude | New: "Defaults" |
| `core.symlinks` | `false` | Prevent symlink-based attacks (relevant to CVE-2024-32002). **Interactive-only**: prompt with default=yes, but skip in `-y` mode (may break symlink-dependent workflows like Node.js monorepos) | Claude | Existing: "Filesystem Protection" |
| `fetch.prune` | `true` | Auto-prune stale remote-tracking refs on fetch | Claude | Existing: "Object Integrity" |
### Audit & Apply Behavior
Seven of eight follow the existing `audit_git_setting` / `apply_git_setting` pattern. `core.symlinks` is the exception:
- **Audit**: reports current value like all other settings.
- **Interactive mode**: prompts with default=yes ("Disable symlinks to prevent symlink-based attacks (CVE-2024-32002)? Note: this may break projects that use symlinks, e.g. Node.js monorepos. [Y/n]").
- **`-y` mode**: skips `core.symlinks` entirely (does not auto-apply). This is because disabling symlinks can silently break real workflows, and `-y` mode should not cause unexpected breakage.
### Acceptance Criteria
- All 8 settings appear in audit output under their respective sections.
- All 8 settings are applied (with prompt or auto) in apply mode.
- Existing tests updated to cover new settings.
---
## Feature 6: `safe.directory` Wildcard Detection
### Background
The Claude report explicitly warns: "Never set `safe.directory = *`." This wildcard completely disables the ownership safety check introduced in Git 2.35.2 (CVE-2022-24765), allowing any user on a shared system to exploit a planted `.git` directory.
### Audit Behavior
- Run `git config --global --get-all safe.directory` and check if any value is `*`.
- `[WARN]` if `*` is found: "safe.directory = * disables ownership checks (CVE-2022-24765). Remove this setting."
- No output if `*` is not found (this is not a setting we apply — absence of `*` is the correct state).
### Apply Behavior
- If `*` is detected, prompt the user: "Remove dangerous safe.directory = * setting?"
- If accepted, run `git config --global --unset safe.directory '*'` (note: must handle the case where multiple values exist — use `--unset-all` if needed, but only for the `*` value).
### Section Placement
Added to existing "Repository Safety" section.
### Acceptance Criteria
- Wildcard detected and warned about in audit mode.
- Apply mode offers to remove it.
- Non-wildcard `safe.directory` entries are not affected.
---
## Audit Section Order (v0.2.0)
Updated ordering with new sections integrated:
1. Identity (`user.useConfigOnly`)
2. Object Integrity (existing + `transfer.bundleURI`, `fetch.prune`)
3. Protocol Restrictions (existing + `protocol.version`)
4. Filesystem Protection (existing + `core.symlinks`)
5. Hook Control (existing)
6. **Pre-commit Hook** (new — gitleaks)
7. Repository Safety (existing + `safe.directory` wildcard detection)
8. Pull/Merge Hardening (existing)
9. Transport Security (existing)
10. Credential Storage (existing)
11. **Credential Hygiene** (new — plaintext file detection)
12. **Global Gitignore** (new)
13. **Defaults** (new — `init.defaultBranch`)
14. **Forensic Readiness** (new — reflog retention)
15. Visibility (existing)
16. Signing Configuration (existing)
17. SSH Configuration (existing)
18. **SSH Key Hygiene** (new)
---
## Non-Goals
- Package manager integration (no `brew install` or `apt install`).
- Modifying or deleting user files (credential files, SSH keys).
- Repository-level hardening (branch protection, CODEOWNERS — these remain in admin recommendations).
- CI/CD pipeline configuration.
- GPG signing support (the script remains SSH-signing focused).
## Compatibility
Same as v0.1.0: Bash 3.2+, macOS and Linux. No new dependencies. Gitleaks is optional — the hook is safe without it.
## Testing
- Extend existing BATS test suite to cover all new audit checks and apply actions.
- Add container test cases for gitleaks hook installation (with and without gitleaks present).
- Test `safe.directory = *` detection and removal.
- Test credential file detection with mock files.
- Test SSH key hygiene with various key types.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,25 @@
FROM alpine:3.21
RUN apk add --no-cache \
bash \
git \
openssh-client \
openssh-keygen \
tmux \
coreutils \
grep \
sed
RUN adduser -D -s /bin/bash testuser
COPY git-harden.sh /home/testuser/git-harden.sh
COPY test/ /home/testuser/test/
RUN chown -R testuser:testuser /home/testuser
USER testuser
WORKDIR /home/testuser
RUN git config --global user.name "Test User" \
&& git config --global user.email "test@example.com"
CMD ["bash", "test/run.sh"]

View File

@@ -0,0 +1,22 @@
FROM archlinux:base
RUN pacman -Syu --noconfirm \
bash \
git \
openssh \
tmux \
&& pacman -Scc --noconfirm
RUN useradd -m -s /bin/bash testuser
COPY git-harden.sh /home/testuser/git-harden.sh
COPY test/ /home/testuser/test/
RUN chown -R testuser:testuser /home/testuser
USER testuser
WORKDIR /home/testuser
RUN git config --global user.name "Test User" \
&& git config --global user.email "test@example.com"
CMD ["bash", "test/run.sh"]

View File

@@ -0,0 +1,22 @@
FROM debian:trixie
RUN apt-get update && apt-get install -y --no-install-recommends \
bash \
git \
openssh-client \
tmux \
&& rm -rf /var/lib/apt/lists/*
RUN useradd -m -s /bin/bash testuser
COPY git-harden.sh /home/testuser/git-harden.sh
COPY test/ /home/testuser/test/
RUN chown -R testuser:testuser /home/testuser
USER testuser
WORKDIR /home/testuser
RUN git config --global user.name "Test User" \
&& git config --global user.email "test@example.com"
CMD ["bash", "test/run.sh"]

View File

@@ -0,0 +1,22 @@
FROM fedora:42
RUN dnf install -y \
bash \
git \
openssh-clients \
tmux \
&& dnf clean all
RUN useradd -m -s /bin/bash testuser
COPY git-harden.sh /home/testuser/git-harden.sh
COPY test/ /home/testuser/test/
RUN chown -R testuser:testuser /home/testuser
USER testuser
WORKDIR /home/testuser
RUN git config --global user.name "Test User" \
&& git config --global user.email "test@example.com"
CMD ["bash", "test/run.sh"]

View File

@@ -0,0 +1,22 @@
FROM ubuntu:24.04
RUN apt-get update && apt-get install -y --no-install-recommends \
bash \
git \
openssh-client \
tmux \
&& rm -rf /var/lib/apt/lists/*
RUN useradd -m -s /bin/bash testuser
COPY git-harden.sh /home/testuser/git-harden.sh
COPY test/ /home/testuser/test/
RUN chown -R testuser:testuser /home/testuser
USER testuser
WORKDIR /home/testuser
RUN git config --global user.name "Test User" \
&& git config --global user.email "test@example.com"
CMD ["bash", "test/run.sh"]

385
test/e2e.sh Executable file
View File

@@ -0,0 +1,385 @@
#!/usr/bin/env bash
# test/e2e.sh — Run BATS tests inside containers across Linux distros
# Usage: test/e2e.sh [--runtime docker|podman] [--rebuild] [distro]
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
# ------------------------------------------------------------------------------
# Constants
# ------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
readonly SCRIPT_DIR
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
readonly REPO_ROOT
readonly CONTAINER_DIR="${SCRIPT_DIR}/containers"
readonly IMAGE_PREFIX="git-harden-test"
# Distro matrix
readonly DISTROS=(ubuntu debian fedora alpine arch)
# Colors (empty if not a terminal)
if [ -t 2 ]; then
readonly C_RED='\033[0;31m'
readonly C_GREEN='\033[0;32m'
readonly C_YELLOW='\033[0;33m'
readonly C_BOLD='\033[1m'
readonly C_RESET='\033[0m'
else
readonly C_RED=''
readonly C_GREEN=''
readonly C_YELLOW=''
readonly C_BOLD=''
readonly C_RESET=''
fi
# Mutable state
RUNTIME=""
REBUILD=false
SKIP_HOST=false
TARGET_DISTRO=""
# Results tracking (temp dir for parallel result files)
RESULTS_DIR=""
# ------------------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------------------
die() {
printf '%bError:%b %s\n' "$C_RED" "$C_RESET" "$1" >&2
exit 1
}
info() {
printf '%b[INFO]%b %s\n' "$C_YELLOW" "$C_RESET" "$1" >&2
}
# ------------------------------------------------------------------------------
# Argument parsing
# ------------------------------------------------------------------------------
parse_args() {
while [ $# -gt 0 ]; do
case "$1" in
--runtime)
[ $# -ge 2 ] || die "--runtime requires an argument (docker or podman)"
RUNTIME="$2"
shift 2
;;
--rebuild)
REBUILD=true
shift
;;
--skip-host)
SKIP_HOST=true
shift
;;
--help|-h)
usage
exit 0
;;
-*)
die "Unknown option: $1"
;;
*)
TARGET_DISTRO="$1"
shift
;;
esac
done
}
usage() {
cat >&2 <<'EOF'
Usage: test/e2e.sh [OPTIONS] [DISTRO]
Run BATS tests inside containers across Linux distributions.
Options:
--runtime <docker|podman> Container runtime (auto-detected if omitted)
--rebuild Force image rebuild ignoring cache
--skip-host Skip host interactive tests (run containers only)
--help, -h Show this help
Distros: ubuntu, debian, fedora, alpine, arch
Examples:
test/e2e.sh # Run all distros
test/e2e.sh alpine # Run Alpine only
test/e2e.sh --runtime podman fedora # Use Podman, Fedora only
EOF
}
# ------------------------------------------------------------------------------
# Runtime detection
# ------------------------------------------------------------------------------
detect_runtime() {
if [ -n "$RUNTIME" ]; then
if ! command -v "$RUNTIME" >/dev/null 2>&1; then
die "${RUNTIME} is not installed"
fi
return
fi
local has_docker=false
local has_podman=false
if command -v docker >/dev/null 2>&1; then
has_docker=true
fi
if command -v podman >/dev/null 2>&1; then
has_podman=true
fi
if [ "$has_docker" = true ]; then
RUNTIME="docker"
elif [ "$has_podman" = true ]; then
RUNTIME="podman"
else
die "Neither docker nor podman found. Install one of them:\n brew install docker\n brew install podman"
fi
# Verify the daemon is running
if ! "$RUNTIME" info >/dev/null 2>&1; then
die "${RUNTIME} daemon is not running. Is the ${RUNTIME} service started?"
fi
}
# ------------------------------------------------------------------------------
# Build & run
# ------------------------------------------------------------------------------
build_image() {
local distro="$1"
local containerfile="${CONTAINER_DIR}/Containerfile.${distro}"
local image_name="${IMAGE_PREFIX}:${distro}"
if [ ! -f "$containerfile" ]; then
die "Containerfile not found: $containerfile"
fi
local build_args=()
if [ "$REBUILD" = true ]; then
build_args+=("--no-cache")
fi
info "Building ${image_name}..."
if ! "$RUNTIME" build \
${build_args[@]+"${build_args[@]}"} \
-f "$containerfile" \
-t "$image_name" \
"$REPO_ROOT" 2>&1; then
return 1
fi
}
run_tests() {
local distro="$1"
local image_name="${IMAGE_PREFIX}:${distro}"
info "Running BATS tests on ${distro}..."
if ! "$RUNTIME" run \
--rm \
--network=none \
"$image_name" \
bash test/run.sh 2>&1; then
return 1
fi
}
run_interactive_tests() {
local distro="$1"
local image_name="${IMAGE_PREFIX}:${distro}"
info "Running interactive tests on ${distro}..."
if ! "$RUNTIME" run \
--rm \
--network=none \
"$image_name" \
bash test/interactive/run-all.sh 2>&1; then
return 1
fi
}
run_host_interactive() {
info "Running interactive tests on host ($(uname -s))..."
if ! bash "${SCRIPT_DIR}/run-interactive.sh" 2>&1; then
return 1
fi
}
# Generic entry that times a named test phase and records results.
# Output is written to a log file; result is recorded in RESULTS_DIR.
run_distro_entry() {
local distro="$1"
shift
# Remaining args are the function + args to run
local start_time
start_time="$(date +%s)"
local log_file="${RESULTS_DIR}/${distro}.log"
local status="PASS"
if ! "$@" > "$log_file" 2>&1; then
status="FAIL"
fi
local end_time
end_time="$(date +%s)"
local duration=$(( end_time - start_time ))
# Write result file (read by print_summary)
printf '%s %s %ds\n' "$distro" "$status" "$duration" > "${RESULTS_DIR}/${distro}.result"
# Print inline status
if [ "$status" = "PASS" ]; then
printf '%b ✓ %s passed (%ds)%b\n' "$C_GREEN" "$distro" "$duration" "$C_RESET" >&2
else
printf '%b ✗ %s FAIL (%ds)%b\n' "$C_RED" "$distro" "$duration" "$C_RESET" >&2
# Show last 20 lines of log on failure
printf '%b Log tail:%b\n' "$C_YELLOW" "$C_RESET" >&2
tail -20 "$log_file" >&2
fi
}
# ------------------------------------------------------------------------------
# Summary
# ------------------------------------------------------------------------------
print_summary() {
printf '\n%b══ Summary ══%b\n' "$C_BOLD" "$C_RESET" >&2
printf '%-12s %-8s %s\n' "DISTRO" "STATUS" "DURATION" >&2
printf '%-12s %-8s %s\n' "------" "------" "--------" >&2
local any_failed=false
local result_file
for result_file in "${RESULTS_DIR}"/*.result; do
[ -f "$result_file" ] || continue
local d s t
IFS=' ' read -r d s t < "$result_file"
local color="$C_GREEN"
if [ "$s" = "SKIP" ]; then
color="$C_YELLOW"
elif [ "$s" != "PASS" ]; then
color="$C_RED"
any_failed=true
fi
printf '%b%-12s %-8s %s%b\n' "$color" "$d" "$s" "$t" "$C_RESET" >&2
done
if [ "$any_failed" = true ]; then
return 1
fi
return 0
}
# ------------------------------------------------------------------------------
# Main
# ------------------------------------------------------------------------------
main() {
parse_args "$@"
detect_runtime
info "Using runtime: ${RUNTIME}"
# Set up results directory
RESULTS_DIR="$(mktemp -d)"
trap 'rm -rf "$RESULTS_DIR"' EXIT
# Run interactive tests on the host first (covers macOS ssh-keygen)
if [ "$SKIP_HOST" = true ]; then
info "Skipping host interactive tests (--skip-host)"
elif command -v tmux >/dev/null 2>&1; then
run_distro_entry "host" run_host_interactive
else
info "tmux not found — skipping host interactive tests (install with: brew install tmux)"
fi
# Determine which distros to run
local run_distros=()
if [ -n "$TARGET_DISTRO" ]; then
local valid=false
for d in "${DISTROS[@]}"; do
if [ "$d" = "$TARGET_DISTRO" ]; then
valid=true
break
fi
done
if [ "$valid" = false ]; then
die "Unknown distro: ${TARGET_DISTRO}. Available: ${DISTROS[*]}"
fi
run_distros=("$TARGET_DISTRO")
else
run_distros=("${DISTROS[@]}")
fi
# Filter out distros without images for this architecture
local arch
arch="$(uname -m)"
local filtered_distros=()
for d in "${run_distros[@]}"; do
if [ "$d" = "arch" ] && [ "$arch" != "x86_64" ]; then
info "Skipping arch (no image for ${arch})"
printf '%s SKIP 0s\n' "$d" > "${RESULTS_DIR}/${d}.result"
continue
fi
filtered_distros+=("$d")
done
run_distros=("${filtered_distros[@]}")
# Phase 1: Build images sequentially (benefits from shared layer cache)
info "Building ${#run_distros[@]} container image(s)..."
for d in "${run_distros[@]}"; do
if ! build_image "$d"; then
printf '%b ✗ %s build failed%b\n' "$C_RED" "$d" "$C_RESET" >&2
printf '%s FAIL 0s\n' "$d" > "${RESULTS_DIR}/${d}.result"
fi
done
# Phase 2: Run tests in parallel
local pids=()
local pid_distros=()
for d in "${run_distros[@]}"; do
# Skip distros that failed to build
[ -f "${RESULTS_DIR}/${d}.result" ] && continue
run_distro_entry "$d" run_container_test_phases "$d" &
pids+=($!)
pid_distros+=("$d")
done
if [ ${#pids[@]} -gt 0 ]; then
local distro_list
distro_list="$(IFS=' '; printf '%s' "${pid_distros[*]}")"
info "Running ${#pids[@]} distro(s) in parallel: ${distro_list}"
# Wait for all background jobs
local i=0
while [ "$i" -lt "${#pids[@]}" ]; do
wait "${pids[$i]}" 2>/dev/null || true
i=$((i + 1))
done
fi
print_summary
}
# Container test phases (without build — build is done in phase 1)
run_container_test_phases() {
local distro="$1"
if ! run_tests "$distro"; then
return 1
fi
if ! run_interactive_tests "$distro"; then
return 1
fi
}
main "$@"

View File

@@ -370,11 +370,12 @@ SSHEOF
# Apply: git config settings (-y mode) # Apply: git config settings (-y mode)
# =========================================================================== # ===========================================================================
@test "-y mode applies git config settings" { @test "-y mode applies setting group" {
source_functions source_functions
AUTO_YES=true AUTO_YES=true
run apply_git_setting "transfer.fsckObjects" "true" run apply_setting_group "Test Group" "Test description" \
"transfer.fsckObjects" "true" "Verify objects on transfer"
assert_success assert_success
local result local result
@@ -382,16 +383,17 @@ SSHEOF
[ "$result" = "true" ] [ "$result" = "true" ]
} }
@test "apply skips already-correct setting" { @test "apply_setting_group skips already-correct settings" {
git config --global transfer.fsckObjects true git config --global transfer.fsckObjects true
source_functions source_functions
AUTO_YES=true AUTO_YES=true
run apply_git_setting "transfer.fsckObjects" "true" run apply_setting_group "Test Group" "Test description" \
"transfer.fsckObjects" "true" "Verify objects on transfer"
assert_success assert_success
# Should produce no output (no "Set" message) # No changes needed — group should not print "Applied"
refute_output --partial "Set" refute_output --partial "Applied"
} }
# =========================================================================== # ===========================================================================
@@ -447,19 +449,27 @@ SSHEOF
source_functions source_functions
AUTO_YES=true AUTO_YES=true
run apply_ssh_config apply_ssh_config
assert_success
# Check directory exists with correct mode # Check directory exists with correct mode
[ -d "${TEST_HOME}/.ssh" ] [ -d "${TEST_HOME}/.ssh" ]
[ -f "${TEST_HOME}/.ssh/config" ] [ -f "${TEST_HOME}/.ssh/config" ]
# stat format differs: macOS uses -f '%Lp', Linux uses -c '%a'
local dir_perms local dir_perms
dir_perms="$(stat -f '%Lp' "${TEST_HOME}/.ssh" 2>/dev/null || stat -c '%a' "${TEST_HOME}/.ssh" 2>/dev/null)" if stat -f '%Lp' "${TEST_HOME}/.ssh" >/dev/null 2>&1; then
dir_perms="$(stat -f '%Lp' "${TEST_HOME}/.ssh")"
else
dir_perms="$(stat -c '%a' "${TEST_HOME}/.ssh")"
fi
[ "$dir_perms" = "700" ] [ "$dir_perms" = "700" ]
local file_perms local file_perms
file_perms="$(stat -f '%Lp' "${TEST_HOME}/.ssh/config" 2>/dev/null || stat -c '%a' "${TEST_HOME}/.ssh/config" 2>/dev/null)" if stat -f '%Lp' "${TEST_HOME}/.ssh/config" >/dev/null 2>&1; then
file_perms="$(stat -f '%Lp' "${TEST_HOME}/.ssh/config")"
else
file_perms="$(stat -c '%a' "${TEST_HOME}/.ssh/config")"
fi
[ "$file_perms" = "600" ] [ "$file_perms" = "600" ]
} }
@@ -487,7 +497,7 @@ SSHEOF
source_functions source_functions
AUTO_YES=true AUTO_YES=true
apply_ssh_directive "StrictHostKeyChecking" "accept-new" apply_single_ssh_directive "StrictHostKeyChecking" "accept-new"
# Should still have exactly one occurrence # Should still have exactly one occurrence
local count local count
@@ -505,7 +515,7 @@ SSHEOF
source_functions source_functions
AUTO_YES=true AUTO_YES=true
apply_ssh_directive "StrictHostKeyChecking" "accept-new" apply_single_ssh_directive "StrictHostKeyChecking" "accept-new"
# Verify updated # Verify updated
grep -q "StrictHostKeyChecking accept-new" "${TEST_HOME}/.ssh/config" grep -q "StrictHostKeyChecking accept-new" "${TEST_HOME}/.ssh/config"
@@ -515,6 +525,37 @@ SSHEOF
grep -q "HashKnownHosts no" "${TEST_HOME}/.ssh/config" grep -q "HashKnownHosts no" "${TEST_HOME}/.ssh/config"
} }
@test "audit recognises SSH directives using = separator" {
source_functions
cat > "${TEST_HOME}/.ssh/config" <<'SSHEOF'
StrictHostKeyChecking=accept-new
HashKnownHosts = yes
SSHEOF
run audit_ssh_directive "StrictHostKeyChecking" "accept-new"
assert_output --partial "[OK]"
run audit_ssh_directive "HashKnownHosts" "yes"
assert_output --partial "[OK]"
}
@test "apply skips SSH directives using = separator when value matches" {
cat > "${TEST_HOME}/.ssh/config" <<'SSHEOF'
StrictHostKeyChecking=accept-new
SSHEOF
source_functions
AUTO_YES=true
apply_single_ssh_directive "StrictHostKeyChecking" "accept-new"
# Should still have exactly one occurrence
local count
count="$(grep -c "StrictHostKeyChecking" "${TEST_HOME}/.ssh/config")"
[ "$count" -eq 1 ]
}
# =========================================================================== # ===========================================================================
# Signing: key detection # Signing: key detection
# =========================================================================== # ===========================================================================
@@ -529,18 +570,29 @@ SSHEOF
[ "$SIGNING_PUB_PATH" = "${TEST_HOME}/.ssh/id_ed25519.pub" ] [ "$SIGNING_PUB_PATH" = "${TEST_HOME}/.ssh/id_ed25519.pub" ]
} }
@test "detect_existing_keys prefers sk key over software key" { @test "detect_existing_keys prefers dedicated signing key over general key" {
ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519" -N "" -q ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519" -N "" -q
# Fake an sk key (can't generate real one without hardware) ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519_signing" -N "" -q
cp "${TEST_HOME}/.ssh/id_ed25519" "${TEST_HOME}/.ssh/id_ed25519_sk"
# Write a fake pub key with sk type prefix
printf 'sk-ssh-ed25519@openssh.com AAAAFakeKey test\n' > "${TEST_HOME}/.ssh/id_ed25519_sk.pub"
source_functions source_functions
detect_existing_keys detect_existing_keys
[ "$SIGNING_KEY_FOUND" = true ] [ "$SIGNING_KEY_FOUND" = true ]
[ "$SIGNING_PUB_PATH" = "${TEST_HOME}/.ssh/id_ed25519_sk.pub" ] [ "$SIGNING_PUB_PATH" = "${TEST_HOME}/.ssh/id_ed25519_signing.pub" ]
}
@test "detect_existing_keys prefers sk signing key over software key" {
ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519" -N "" -q
# Fake an sk signing key (can't generate real one without hardware)
cp "${TEST_HOME}/.ssh/id_ed25519" "${TEST_HOME}/.ssh/id_ed25519_sk_signing"
# Write a fake pub key with sk type prefix
printf 'sk-ssh-ed25519@openssh.com AAAAFakeKey test\n' > "${TEST_HOME}/.ssh/id_ed25519_sk_signing.pub"
source_functions
detect_existing_keys
[ "$SIGNING_KEY_FOUND" = true ]
[ "$SIGNING_PUB_PATH" = "${TEST_HOME}/.ssh/id_ed25519_sk_signing.pub" ]
} }
@test "detect_existing_keys finds key from IdentityFile directive" { @test "detect_existing_keys finds key from IdentityFile directive" {
@@ -650,15 +702,16 @@ SSHEOF
[ "$count" -eq 1 ] [ "$count" -eq 1 ]
} }
@test "setup_allowed_signers skips when no email set" { @test "setup_allowed_signers skips when no email provided" {
ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519" -N "" -q ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519" -N "" -q
git config --global --unset user.email git config --global --unset user.email
source_functions source_functions
SIGNING_PUB_PATH="${TEST_HOME}/.ssh/id_ed25519.pub" SIGNING_PUB_PATH="${TEST_HOME}/.ssh/id_ed25519.pub"
# In non-interactive context, read from /dev/tty fails — empty email
run setup_allowed_signers run setup_allowed_signers
assert_output --partial "user.email not set" assert_output --partial "No email provided"
} }
# =========================================================================== # ===========================================================================
@@ -820,3 +873,589 @@ SSHEOF
assert_output --partial "branch protection" assert_output --partial "branch protection"
assert_output --partial "vigilant mode" assert_output --partial "vigilant mode"
} }
# ===========================================================================
# v0.2.0: New git config settings
# ===========================================================================
@test "audit reports new v0.2.0 settings as MISS on fresh config" {
source_functions
detect_platform
detect_credential_helper
run audit_git_config
assert_output --partial "user.useConfigOnly"
assert_output --partial "transfer.bundleURI"
assert_output --partial "fetch.prune"
assert_output --partial "protocol.version"
assert_output --partial "init.defaultBranch"
assert_output --partial "gc.reflogExpire"
assert_output --partial "gc.reflogExpireUnreachable"
assert_output --partial "core.symlinks"
}
@test "-y mode applies new v0.2.0 settings" {
run bash "$SCRIPT" -y
assert_success
[ "$(git config --global user.useConfigOnly)" = "true" ]
[ "$(git config --global transfer.bundleURI)" = "false" ]
[ "$(git config --global fetch.prune)" = "true" ]
[ "$(git config --global protocol.version)" = "2" ]
[ "$(git config --global init.defaultBranch)" = "main" ]
[ "$(git config --global gc.reflogExpire)" = "180.days" ]
[ "$(git config --global gc.reflogExpireUnreachable)" = "90.days" ]
}
@test "-y mode does NOT apply core.symlinks" {
run bash "$SCRIPT" -y
assert_success
local symlinks
symlinks="$(git config --global --get core.symlinks 2>/dev/null || echo "unset")"
[ "$symlinks" = "unset" ]
}
# ===========================================================================
# v0.2.0: safe.directory wildcard detection
# ===========================================================================
@test "audit detects safe.directory = * wildcard" {
source_functions
detect_platform
detect_credential_helper
git config --global safe.directory '*'
run audit_git_config
assert_output --partial "safe.directory = * disables ownership checks"
}
@test "audit does not warn without safe.directory wildcard" {
source_functions
detect_platform
detect_credential_helper
git config --global safe.directory "/some/path"
run audit_git_config
refute_output --partial "safe.directory = * disables"
}
@test "-y mode removes safe.directory = * wildcard" {
git config --global safe.directory '*'
run bash "$SCRIPT" -y
assert_success
local safe_dirs
safe_dirs="$(git config --global --get-all safe.directory 2>/dev/null || echo "none")"
refute [ "$safe_dirs" = "*" ]
}
# ===========================================================================
# v0.2.0: Pre-commit hook
# ===========================================================================
@test "audit reports MISS when no pre-commit hook exists" {
source_functions
run audit_precommit_hook
assert_output --partial "No pre-commit hook"
}
@test "audit reports OK when gitleaks hook exists" {
source_functions
mkdir -p "${HOME}/.config/git/hooks"
cat > "${HOME}/.config/git/hooks/pre-commit" << 'EOF'
#!/usr/bin/env bash
gitleaks protect --staged
EOF
chmod +x "${HOME}/.config/git/hooks/pre-commit"
run audit_precommit_hook
assert_output --partial "[OK]"
assert_output --partial "gitleaks"
}
@test "audit reports WARN for non-gitleaks hook" {
source_functions
mkdir -p "${HOME}/.config/git/hooks"
printf '#!/usr/bin/env bash\necho custom hook\n' > "${HOME}/.config/git/hooks/pre-commit"
chmod +x "${HOME}/.config/git/hooks/pre-commit"
run audit_precommit_hook
assert_output --partial "does not reference gitleaks"
}
@test "apply does not overwrite existing pre-commit hook" {
source_functions
AUTO_YES=true
mkdir -p "${HOME}/.config/git/hooks"
printf '#!/usr/bin/env bash\necho my hook\n' > "${HOME}/.config/git/hooks/pre-commit"
run apply_precommit_hook
assert_output --partial "not overwriting"
# Verify original content preserved
run cat "${HOME}/.config/git/hooks/pre-commit"
assert_output --partial "my hook"
}
# ===========================================================================
# v0.2.0: Global gitignore
# ===========================================================================
@test "audit reports MISS when no excludesFile configured" {
source_functions
run audit_global_gitignore
assert_output --partial "no global gitignore configured"
}
@test "audit reports OK when excludesFile has security patterns" {
source_functions
mkdir -p "${HOME}/.config/git"
printf '.env\n*.pem\n*.key\n' > "${HOME}/.config/git/ignore"
git config --global core.excludesFile "~/.config/git/ignore"
run audit_global_gitignore
assert_output --partial "[OK]"
assert_output --partial "contains security patterns"
}
@test "audit warns when excludesFile lacks security patterns" {
source_functions
mkdir -p "${HOME}/.config/git"
printf '*.log\n*.tmp\n' > "${HOME}/.config/git/ignore"
git config --global core.excludesFile "~/.config/git/ignore"
run audit_global_gitignore
assert_output --partial "lacks secret patterns"
}
@test "-y mode creates global gitignore" {
run bash "$SCRIPT" -y
assert_success
[ -f "${HOME}/.config/git/ignore" ]
run cat "${HOME}/.config/git/ignore"
assert_output --partial ".env"
assert_output --partial "*.pem"
assert_output --partial "*.key"
assert_output --partial "!.env.example"
[ "$(git config --global core.excludesFile)" = "~/.config/git/ignore" ]
}
@test "-y mode skips gitignore when excludesFile already set" {
git config --global core.excludesFile "/some/other/path"
run bash "$SCRIPT" -y
assert_success
[ "$(git config --global core.excludesFile)" = "/some/other/path" ]
}
# ===========================================================================
# v0.2.0: Credential hygiene
# ===========================================================================
@test "audit warns about ~/.git-credentials" {
source_functions
printf 'https://user:token@github.com\n' > "${HOME}/.git-credentials"
run audit_credential_hygiene
assert_output --partial "git-credentials"
assert_output --partial "plaintext"
}
@test "audit warns about ~/.netrc" {
source_functions
printf 'machine github.com\nlogin user\npassword token\n' > "${HOME}/.netrc"
run audit_credential_hygiene
assert_output --partial ".netrc"
}
@test "audit warns about ~/.npmrc with auth token" {
source_functions
printf '//registry.npmjs.org/:_authToken=npm_abcdef123456\n' > "${HOME}/.npmrc"
run audit_credential_hygiene
assert_output --partial "npm registry token"
}
@test "audit does not warn about ~/.npmrc without token" {
source_functions
printf 'registry=https://registry.npmjs.org/\n' > "${HOME}/.npmrc"
run audit_credential_hygiene
refute_output --partial "npm registry token"
}
@test "audit warns about ~/.pypirc with password" {
source_functions
printf '[pypi]\nusername = user\npassword = secret123\n' > "${HOME}/.pypirc"
run audit_credential_hygiene
assert_output --partial "PyPI credentials"
}
@test "audit no warnings with clean credential state" {
source_functions
run audit_credential_hygiene
refute_output --partial "[WARN]"
}
# ===========================================================================
# v0.2.0: SSH key hygiene
# ===========================================================================
@test "SSH key hygiene: ed25519 reported as OK" {
source_functions
ssh-keygen -t ed25519 -f "${HOME}/.ssh/test_ed25519" -N "" -q
run audit_ssh_key_hygiene
assert_output --partial "[OK]"
assert_output --partial "ed25519"
}
@test "SSH key hygiene: RSA key reported as WARN" {
source_functions
ssh-keygen -t rsa -b 2048 -f "${HOME}/.ssh/test_rsa" -N "" -q
run audit_ssh_key_hygiene
assert_output --partial "[WARN]"
assert_output --partial "RSA"
assert_output --partial "migrating to ed25519"
}
@test "SSH key hygiene: no keys produces info message" {
source_functions
# Remove the default keys created in setup (there are none)
rm -f "${HOME}/.ssh/"*.pub
run audit_ssh_key_hygiene
assert_output --partial "No SSH public keys found"
}
@test "SSH key hygiene: picks up keys from IdentityFile in ssh config" {
source_functions
mkdir -p "${HOME}/.ssh/custom"
ssh-keygen -t ed25519 -f "${HOME}/.ssh/custom/my_key" -N "" -q
printf 'IdentityFile ~/.ssh/custom/my_key\n' > "${HOME}/.ssh/config"
run audit_ssh_key_hygiene
assert_output --partial "[OK]"
assert_output --partial "my_key"
}
# ===========================================================================
# v0.5.0: Identity guard (useConfigOnly)
# ===========================================================================
@test "audit warns when useConfigOnly=true but identity missing" {
git config --global --unset user.name
git config --global --unset user.email
source_functions
run audit_git_config
assert_output --partial "user.name/user.email not set"
}
@test "audit does not warn about identity when name and email set" {
source_functions
run audit_git_config
refute_output --partial "user.name/user.email not set"
}
@test "-y mode applies useConfigOnly when identity exists" {
source_functions
AUTO_YES=true
PLATFORM="macos"
DETECTED_CRED_HELPER="osxkeychain"
run apply_git_config
assert_success
[ "$(git config --global user.useConfigOnly)" = "true" ]
}
@test "-y mode skips useConfigOnly when user.name missing" {
git config --global --unset user.name
source_functions
AUTO_YES=true
PLATFORM="macos"
DETECTED_CRED_HELPER="osxkeychain"
run apply_git_config
assert_success
assert_output --partial "Skipping user.useConfigOnly"
local result
result="$(git config --global --get user.useConfigOnly 2>/dev/null || true)"
[ -z "$result" ]
}
@test "-y mode skips useConfigOnly when user.email missing" {
git config --global --unset user.email
source_functions
AUTO_YES=true
PLATFORM="macos"
DETECTED_CRED_HELPER="osxkeychain"
run apply_git_config
assert_success
assert_output --partial "Skipping user.useConfigOnly"
local result
result="$(git config --global --get user.useConfigOnly 2>/dev/null || true)"
[ -z "$result" ]
}
# ===========================================================================
# v0.5.0: pull.rebase unset during apply
# ===========================================================================
@test "-y mode unsets pull.rebase when set" {
git config --global pull.rebase true
source_functions
AUTO_YES=true
PLATFORM="macos"
DETECTED_CRED_HELPER="osxkeychain"
run apply_git_config
assert_success
assert_output --partial "Unset pull.rebase"
local result
result="$(git config --global --get pull.rebase 2>/dev/null || true)"
[ -z "$result" ]
}
@test "-y mode does not unset pull.rebase when not set" {
source_functions
AUTO_YES=true
PLATFORM="macos"
DETECTED_CRED_HELPER="osxkeychain"
run apply_git_config
assert_success
refute_output --partial "Unset pull.rebase"
}
# ===========================================================================
# v0.5.0: SSH directives in Host * block
# ===========================================================================
@test "apply places new SSH directive in Host * block when blocks exist" {
cat > "${TEST_HOME}/.ssh/config" <<'SSHEOF'
Host github.com
IdentityFile ~/.ssh/github_key
SSHEOF
source_functions
apply_single_ssh_directive "StrictHostKeyChecking" "accept-new"
# Should have created a Host * block
grep -q "^Host \*$" "${TEST_HOME}/.ssh/config"
grep -q "StrictHostKeyChecking accept-new" "${TEST_HOME}/.ssh/config"
}
@test "apply inserts into existing Host * block" {
cat > "${TEST_HOME}/.ssh/config" <<'SSHEOF'
Host *
HashKnownHosts yes
Host github.com
IdentityFile ~/.ssh/github_key
SSHEOF
source_functions
apply_single_ssh_directive "IdentitiesOnly" "yes"
# Should be inside Host * block (indented), not appended bare
grep -q "IdentitiesOnly yes" "${TEST_HOME}/.ssh/config"
# Only one Host * line
local count
count="$(grep -c '^Host \*$' "${TEST_HOME}/.ssh/config")"
[ "$count" -eq 1 ]
}
@test "apply appends bare when no Host/Match blocks exist" {
: > "${TEST_HOME}/.ssh/config"
source_functions
apply_single_ssh_directive "HashKnownHosts" "yes"
grep -q "HashKnownHosts yes" "${TEST_HOME}/.ssh/config"
# No Host * block should be created for a simple file
! grep -q "^Host" "${TEST_HOME}/.ssh/config"
}
# ===========================================================================
# v0.5.0: SSH config backup
# ===========================================================================
@test "apply_ssh_config creates backup of existing SSH config" {
printf 'StrictHostKeyChecking ask\n' > "${TEST_HOME}/.ssh/config"
source_functions
AUTO_YES=true
run apply_ssh_config
assert_success
assert_output --partial "SSH config backed up"
# Verify backup file exists
local backup_count
backup_count="$(find "${TEST_HOME}/.ssh" -name 'config.pre-harden-*' | wc -l | tr -d ' ')"
[ "$backup_count" -eq 1 ]
# Verify backup contains original content
local backup_file
backup_file="$(find "${TEST_HOME}/.ssh" -name 'config.pre-harden-*' -print -quit)"
grep -q "StrictHostKeyChecking ask" "$backup_file"
}
@test "apply_ssh_config does not create backup for new SSH config" {
rm -f "${TEST_HOME}/.ssh/config"
source_functions
AUTO_YES=true
run apply_ssh_config
assert_success
refute_output --partial "SSH config backed up"
}
# ===========================================================================
# v0.5.0: Dedicated signing key names
# ===========================================================================
@test "detect_existing_keys finds dedicated signing key" {
ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519_signing" -N "" -q
source_functions
detect_existing_keys
[ "$SIGNING_KEY_FOUND" = true ]
[ "$SIGNING_PUB_PATH" = "${TEST_HOME}/.ssh/id_ed25519_signing.pub" ]
}
@test "detect_existing_keys falls back to general key when no signing key" {
ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519" -N "" -q
source_functions
detect_existing_keys
[ "$SIGNING_KEY_FOUND" = true ]
[ "$SIGNING_PUB_PATH" = "${TEST_HOME}/.ssh/id_ed25519.pub" ]
}
@test "-y mode enables signing with dedicated signing key" {
ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519_signing" -N "" -q
source_functions
AUTO_YES=true
run apply_signing_config
assert_success
[ "$(git config --global commit.gpgsign)" = "true" ]
local sigkey
sigkey="$(git config --global user.signingkey)"
[[ "$sigkey" = *"id_ed25519_signing.pub"* ]]
}
# ===========================================================================
# v0.5.0: core.hooksPath separate prompt
# ===========================================================================
@test "-y mode applies core.hooksPath separately from filesystem group" {
source_functions
AUTO_YES=true
PLATFORM="macos"
DETECTED_CRED_HELPER="osxkeychain"
run apply_git_config
assert_success
[ "$(git config --global core.hooksPath)" = "~/.config/git/hooks" ]
}
@test "-y mode skips core.hooksPath when already set" {
git config --global core.hooksPath "~/.config/git/hooks"
source_functions
AUTO_YES=true
PLATFORM="macos"
DETECTED_CRED_HELPER="osxkeychain"
run apply_git_config
assert_success
refute_output --partial "Global Hooks Path"
}
# ===========================================================================
# v0.5.0: reset-signing cleans configured key path
# ===========================================================================
@test "reset-signing cleans actual configured key path" {
# Create a custom-named key
ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/my_org_key" -N "" -q
git config --global user.signingkey "${TEST_HOME}/.ssh/my_org_key.pub"
git config --global commit.gpgsign true
source_functions
AUTO_YES=true
run reset_signing
assert_success
# git config entries should be removed
local sigkey
sigkey="$(git config --global --get user.signingkey 2>/dev/null || true)"
[ -z "$sigkey" ]
# Key files should be listed for cleanup
assert_output --partial "my_org_key"
}
@test "reset-signing includes dedicated signing key names" {
# Create dedicated signing keys
ssh-keygen -t ed25519 -f "${TEST_HOME}/.ssh/id_ed25519_signing" -N "" -q
source_functions
AUTO_YES=true
run reset_signing
assert_success
assert_output --partial "id_ed25519_signing"
}
# ===========================================================================
# v0.5.0: Version bump
# ===========================================================================
@test "--version reports 0.5.0" {
run bash "$SCRIPT" --version
assert_output --partial "0.5.0"
}

109
test/interactive/helpers.sh Executable file
View File

@@ -0,0 +1,109 @@
#!/usr/bin/env bash
# Shared helpers for interactive tmux-driven tests
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
TMUX_SESSION="test-$$"
readonly SCRIPT_PATH="${HOME}/git-harden.sh"
# Colors
if [ -t 2 ]; then
readonly C_RED='\033[0;31m'
readonly C_GREEN='\033[0;32m'
readonly C_RESET='\033[0m'
else
readonly C_RED=''
readonly C_GREEN=''
readonly C_RESET=''
fi
# Wait for a string to appear in the tmux pane.
# Polls every 0.2s, times out after $2 seconds (default 10).
wait_for() {
local pattern="$1"
local timeout="${2:-10}"
local elapsed=0
while ! tmux capture-pane -t "$TMUX_SESSION" -p | grep -qF "$pattern"; do
sleep 0.2
elapsed=$(( elapsed + 1 ))
if (( elapsed > timeout * 5 )); then
printf 'TIMEOUT waiting for: %s\n' "$pattern" >&2
printf 'Current pane content:\n' >&2
tmux capture-pane -t "$TMUX_SESSION" -p >&2
return 1
fi
done
}
# Send keys to the tmux session
send() {
tmux send-keys -t "$TMUX_SESSION" "$@"
}
# Start git-harden.sh in a tmux session.
# Explicitly pass HOME and GIT_CONFIG_GLOBAL — tmux spawns a login shell
# which resets HOME from the passwd entry, breaking the isolated test env.
start_session() {
tmux kill-session -t "$TMUX_SESSION" 2>/dev/null || true
sleep 0.5
local env_setup="export HOME='${HOME}';"
if [ -n "${GIT_CONFIG_GLOBAL:-}" ]; then
env_setup="${env_setup} export GIT_CONFIG_GLOBAL='${GIT_CONFIG_GLOBAL}';"
fi
tmux new-session -d -s "$TMUX_SESSION" \
"${env_setup} bash '${SCRIPT_PATH}'"
# Keep the pane alive after the script exits so capture_output can read it
tmux set-option -t "$TMUX_SESSION" remain-on-exit on
sleep 0.5
# Verify session started
if ! tmux has-session -t "$TMUX_SESSION" 2>/dev/null; then
printf 'ERROR: tmux session "%s" failed to start\n' "$TMUX_SESSION" >&2
printf 'SCRIPT_PATH=%s\n' "$SCRIPT_PATH" >&2
printf 'HOME=%s\n' "$HOME" >&2
return 1
fi
}
# Wait for the script to exit and capture final output
capture_output() {
# Wait for the shell to become available (script exited)
local timeout=30
local elapsed=0
while tmux list-panes -t "$TMUX_SESSION" -F '#{pane_dead}' 2>/dev/null | grep -q '^0$'; do
sleep 0.5
elapsed=$(( elapsed + 1 ))
if (( elapsed > timeout * 2 )); then
printf 'TIMEOUT waiting for script to exit\n' >&2
tmux capture-pane -t "$TMUX_SESSION" -p >&2
return 1
fi
done
tmux capture-pane -t "$TMUX_SESSION" -p
}
# Clean up
cleanup() {
tmux kill-session -t "$TMUX_SESSION" 2>/dev/null || true
}
# Assert helper
assert_contains() {
local haystack="$1"
local needle="$2"
if printf '%s' "$haystack" | grep -qF "$needle"; then
return 0
fi
printf '%bFAIL:%b expected output to contain: %s\n' "$C_RED" "$C_RESET" "$needle" >&2
return 1
}
pass() {
printf '%b PASS:%b %s\n' "$C_GREEN" "$C_RESET" "$1" >&2
}
fail() {
printf '%b FAIL:%b %s\n' "$C_RED" "$C_RESET" "$1" >&2
}

30
test/interactive/run-all.sh Executable file
View File

@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Run all interactive tmux-driven tests
# Intended to be run inside a container (with tmux installed)
set -o nounset
set -o pipefail
IFS=$'\n\t'
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
passed=0
failed=0
total=0
for test_script in "${SCRIPT_DIR}"/test-*.sh; do
[ -f "$test_script" ] || continue
total=$((total + 1))
printf '\n── %s ──\n' "$(basename "$test_script")" >&2
if bash "$test_script"; then
passed=$((passed + 1))
else
failed=$((failed + 1))
fi
done
printf '\n── Interactive tests: %d passed, %d failed, %d total ──\n' "$passed" "$failed" "$total" >&2
if [ "$failed" -gt 0 ]; then
exit 1
fi

View File

@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# Interactive test: accept all prompts (safety gate + hardening + signing skip)
# Verifies: all settings applied, re-audit exits 0
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=helpers.sh
source "${SCRIPT_DIR}/helpers.sh"
main() {
trap cleanup EXIT
printf 'Test: Full interactive apply (accept all)\n' >&2
start_session
# Safety review gate — answer yes
wait_for "reviewed this script"
send "y" Enter
# Proceed with hardening — answer yes
wait_for "Proceed with hardening"
send "y" Enter
# Accept each setting prompt by sending "y" + Enter repeatedly.
# v0.2.0 adds more prompts (pre-commit hook, gitignore, core.symlinks),
# so we need enough iterations to get through all of them.
local pane_content
for _ in $(seq 1 50); do
sleep 0.3
pane_content="$(tmux capture-pane -t "$TMUX_SESSION" -p 2>/dev/null || true)"
if printf '%s' "$pane_content" | grep -qF "Signing key options"; then
break
fi
if printf '%s' "$pane_content" | grep -qF "Hardening complete"; then
break
fi
send "y" Enter
done
# Signing wizard — skip
wait_for "Signing key options" 20
send "s" Enter
# Wait for completion
sleep 2
capture_output >/dev/null 2>&1 || true
# Verify: re-run audit — signing won't pass (skipped) but git config should
if git config --global --get transfer.fsckObjects | grep -q true; then
pass "Full accept: git config settings applied (signing skipped as expected)"
else
fail "Full accept: settings not applied"
exit 1
fi
}
main

View File

@@ -0,0 +1,106 @@
#!/usr/bin/env bash
# Interactive test: identity guard prevents useConfigOnly lockout
# Verifies: when user.name/email are missing, the script prompts for them
# before enabling useConfigOnly; after providing both, useConfigOnly is set.
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=helpers.sh
source "${SCRIPT_DIR}/helpers.sh"
main() {
trap cleanup EXIT
printf 'Test: Identity guard — missing name/email\n' >&2
# Remove identity AND useConfigOnly so the guard triggers
git config --global --unset user.name 2>/dev/null || true
git config --global --unset user.email 2>/dev/null || true
git config --global --unset user.useConfigOnly 2>/dev/null || true
# Remove signing keys so wizard shows options (not existing key prompt)
rm -f "${HOME}/.ssh/id_ed25519_signing" "${HOME}/.ssh/id_ed25519_signing.pub"
rm -f "${HOME}/.ssh/id_ed25519" "${HOME}/.ssh/id_ed25519.pub"
start_session
# Safety review gate
wait_for "reviewed this script"
send "y" Enter
# Proceed with hardening
wait_for "Proceed with hardening"
send "y" Enter
# Accept settings until identity guard prompt appears
local pane_content
for _ in $(seq 1 50); do
sleep 0.3
pane_content="$(tmux capture-pane -t "$TMUX_SESSION" -p 2>/dev/null || true)"
if printf '%s' "$pane_content" | grep -qF "Enter your name"; then
break
fi
if printf '%s' "$pane_content" | grep -qF "Hardening complete"; then
fail "Identity guard did not trigger — reached completion"
exit 1
fi
send "y" Enter
done
# Identity guard: enter name
wait_for "Enter your name" 15
send "Test User" Enter
# Identity guard: enter email
wait_for "Enter your email" 10
send "test@example.com" Enter
# Continue accepting remaining prompts
for _ in $(seq 1 50); do
sleep 0.3
pane_content="$(tmux capture-pane -t "$TMUX_SESSION" -p 2>/dev/null || true)"
if printf '%s' "$pane_content" | grep -qF "Signing key options"; then
break
fi
if printf '%s' "$pane_content" | grep -qF "Hardening complete"; then
break
fi
send "y" Enter
done
# Skip signing
if tmux capture-pane -t "$TMUX_SESSION" -p | grep -qF "Signing key options"; then
send "s" Enter
fi
# Wait for completion
sleep 2
capture_output >/dev/null 2>&1 || true
# Verify: useConfigOnly was set
local use_config_only
use_config_only="$(git config --global --get user.useConfigOnly 2>/dev/null || true)"
if [ "$use_config_only" = "true" ]; then
pass "Identity guard: useConfigOnly=true set after providing name/email"
else
fail "Identity guard: useConfigOnly not set (expected true, got '${use_config_only}')"
exit 1
fi
# Verify: name and email were set
local name email
name="$(git config --global --get user.name 2>/dev/null || true)"
email="$(git config --global --get user.email 2>/dev/null || true)"
if [ "$name" = "Test User" ] && [ "$email" = "test@example.com" ]; then
pass "Identity guard: user.name and user.email configured"
else
fail "Identity guard: identity not configured (name='${name}', email='${email}')"
exit 1
fi
}
main

View File

@@ -0,0 +1,49 @@
#!/usr/bin/env bash
# Interactive test: decline safety review gate
# Verifies: script exits 0, prints AI review instructions, no config changes
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=helpers.sh
source "${SCRIPT_DIR}/helpers.sh"
main() {
trap cleanup EXIT
printf 'Test: Safety gate decline\n' >&2
# Snapshot current config
local config_before
config_before="$(git config --global --list 2>/dev/null || true)"
start_session
# Safety review gate — answer no (default)
wait_for "reviewed this script"
send "n" Enter
# Wait for exit
sleep 2
local output
output="$(capture_output)"
# Verify: output contains AI review instructions
assert_contains "$output" "claude"
assert_contains "$output" "gemini"
# Verify: no config changes
local config_after
config_after="$(git config --global --list 2>/dev/null || true)"
if [ "$config_before" = "$config_after" ]; then
pass "Safety gate decline: no config changes, instructions shown"
else
fail "Safety gate decline: config was modified"
exit 1
fi
}
main

View File

@@ -0,0 +1,98 @@
#!/usr/bin/env bash
# Interactive test: generate ed25519 key via signing wizard
# Verifies: key created, user.signingkey configured, commit.gpgsign=true
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=helpers.sh
source "${SCRIPT_DIR}/helpers.sh"
main() {
trap cleanup EXIT
printf 'Test: Signing wizard - generate ed25519 key\n' >&2
# Ensure identity is set (prior tests may have cleared it)
git config --global user.name "Test User" 2>/dev/null || true
git config --global user.email "test@example.com" 2>/dev/null || true
# Ensure no existing signing keys (new dedicated names + legacy)
rm -f "${HOME}/.ssh/id_ed25519_signing" "${HOME}/.ssh/id_ed25519_signing.pub"
rm -f "${HOME}/.ssh/id_ed25519" "${HOME}/.ssh/id_ed25519.pub"
start_session
# Safety review gate
wait_for "reviewed this script"
send "y" Enter
# Proceed with hardening
wait_for "Proceed with hardening"
send "y" Enter
# Accept settings until signing wizard (v0.2.0 adds more prompts)
local pane_content
for _ in $(seq 1 50); do
sleep 0.3
pane_content="$(tmux capture-pane -t "$TMUX_SESSION" -p 2>/dev/null || true)"
if printf '%s' "$pane_content" | grep -qF "Signing key options"; then
break
fi
if printf '%s' "$pane_content" | grep -qF "Hardening complete"; then
break
fi
send "y" Enter
done
# Signing wizard — option 1: generate ed25519
wait_for "Signing key options" 20
send "1" Enter
# ssh-keygen prompts for passphrase — enter empty twice
wait_for "Enter passphrase" 10
send "" Enter
wait_for "Enter same passphrase" 10
send "" Enter
# Signing wizard asks "Enable commit and tag signing?" — accept
wait_for "Enable commit and tag signing" 10
send "y" Enter
# Wait for completion
sleep 3
capture_output >/dev/null 2>&1 || true
# Verify key exists (new dedicated signing key name)
if [ -f "${HOME}/.ssh/id_ed25519_signing.pub" ]; then
pass "Key generated: ~/.ssh/id_ed25519_signing.pub exists"
else
fail "Key not generated"
exit 1
fi
# Verify signing key configured
local signing_key
signing_key="$(git config --global --get user.signingkey 2>/dev/null || true)"
if [ -n "$signing_key" ]; then
pass "user.signingkey configured: ${signing_key}"
else
fail "user.signingkey not configured"
exit 1
fi
# Verify gpgsign enabled
local gpgsign
gpgsign="$(git config --global --get commit.gpgsign 2>/dev/null || true)"
if [ "$gpgsign" = "true" ]; then
pass "commit.gpgsign=true"
else
fail "commit.gpgsign not set"
exit 1
fi
}
main

View File

@@ -0,0 +1,81 @@
#!/usr/bin/env bash
# Interactive test: skip signing wizard
# Verifies: no signing key configured, commit.gpgsign not set
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=helpers.sh
source "${SCRIPT_DIR}/helpers.sh"
main() {
trap cleanup EXIT
printf 'Test: Signing wizard - skip\n' >&2
# Remove any keys from prior tests so wizard shows key generation options
rm -f "${HOME}/.ssh/id_ed25519_signing" "${HOME}/.ssh/id_ed25519_signing.pub"
rm -f "${HOME}/.ssh/id_ed25519_sk_signing" "${HOME}/.ssh/id_ed25519_sk_signing.pub"
rm -f "${HOME}/.ssh/id_ecdsa_sk_signing" "${HOME}/.ssh/id_ecdsa_sk_signing.pub"
rm -f "${HOME}/.ssh/id_ed25519" "${HOME}/.ssh/id_ed25519.pub"
rm -f "${HOME}/.ssh/id_ed25519_sk" "${HOME}/.ssh/id_ed25519_sk.pub"
git config --global --unset user.signingkey 2>/dev/null || true
git config --global --unset commit.gpgsign 2>/dev/null || true
start_session
# Safety review gate
wait_for "reviewed this script"
send "y" Enter
# Proceed with hardening
wait_for "Proceed with hardening"
send "y" Enter
# Accept settings until signing wizard (v0.2.0 adds more prompts)
local pane_content
for _ in $(seq 1 50); do
sleep 0.3
pane_content="$(tmux capture-pane -t "$TMUX_SESSION" -p 2>/dev/null || true)"
if printf '%s' "$pane_content" | grep -qF "Signing key options"; then
break
fi
if printf '%s' "$pane_content" | grep -qF "Hardening complete"; then
break
fi
send "y" Enter
done
# Signing wizard — skip
wait_for "Signing key options" 20
send "s" Enter
# Wait for completion
sleep 2
capture_output >/dev/null 2>&1 || true
# Verify: no signing key
local signing_key
signing_key="$(git config --global --get user.signingkey 2>/dev/null || true)"
if [ -z "$signing_key" ]; then
pass "Signing skip: user.signingkey not set"
else
fail "Signing skip: user.signingkey was set unexpectedly: ${signing_key}"
exit 1
fi
# Verify: commit.gpgsign not set
local gpgsign
gpgsign="$(git config --global --get commit.gpgsign 2>/dev/null || true)"
if [ -z "$gpgsign" ]; then
pass "Signing skip: commit.gpgsign not set"
else
fail "Signing skip: commit.gpgsign was set unexpectedly: ${gpgsign}"
exit 1
fi
}
main

52
test/run-interactive.sh Executable file
View File

@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Run interactive tmux tests on the host in an isolated HOME.
# Covers macOS ssh-keygen and platform-specific behavior that
# cannot be tested inside Linux containers.
#
# Requires: tmux, git, ssh-keygen
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
readonly SCRIPT_DIR
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
readonly REPO_ROOT
die() {
printf 'Error: %s\n' "$1" >&2
exit 1
}
# Check dependencies
command -v tmux >/dev/null 2>&1 || die "tmux is required. Install with: brew install tmux"
command -v git >/dev/null 2>&1 || die "git is required"
command -v ssh-keygen >/dev/null 2>&1 || die "ssh-keygen is required"
# Create isolated HOME
TEST_HOME="$(mktemp -d)"
trap 'rm -rf "$TEST_HOME"' EXIT
# Set up the isolated environment
export HOME="$TEST_HOME"
export GIT_CONFIG_GLOBAL="${TEST_HOME}/.gitconfig"
mkdir -p "${TEST_HOME}/.ssh"
mkdir -p "${TEST_HOME}/.config/git"
# Copy the script into the test home (interactive helpers expect it at ~/git-harden.sh)
cp "${REPO_ROOT}/git-harden.sh" "${TEST_HOME}/git-harden.sh"
# Copy interactive test scripts
cp -r "${SCRIPT_DIR}/interactive" "${TEST_HOME}/test-interactive"
# Set up minimal git config
git config --global user.name "Test User"
git config --global user.email "test@example.com"
printf '── Running interactive tests on host (%s) ──\n' "$(uname -s)" >&2
# Run the interactive tests
exec bash "${TEST_HOME}/test-interactive/run-all.sh"