diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c94b50e..153e2ae 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup GraalVM uses: graalvm/setup-graalvm@v1 @@ -27,20 +27,17 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} - name: Cache Maven - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-maven- - name: Run Tests - run: mvn test - - - name: Build JAR - run: mvn clean package -DskipTests + run: mvn verify -DskipNativeBuild=true - name: Test Native Compilation - run: mvn clean package -Pnative -DskipTests + run: mvn clean package -DskipTests - name: Test Binary (Unix) if: runner.os != 'Windows' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c0fe97f..2c983be 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -25,7 +25,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup GraalVM uses: graalvm/setup-graalvm@v1 @@ -36,14 +36,14 @@ jobs: native-image-job-reports: 'true' - name: Cache Maven - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-maven- - name: Build Native Binary - run: mvn clean package -Pnative -DskipTests + run: mvn clean verify - name: Rename Artifact (Unix) if: runner.os != 'Windows' @@ -66,7 +66,7 @@ jobs: "$($hash.Hash.ToLower()) ai-commit-${{ matrix.platform }}.exe" | Out-File -Encoding ASCII ai-commit-${{ matrix.platform }}.exe.sha256 - name: Upload Artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v6 with: name: ai-commit-${{ matrix.platform }} path: | @@ -83,10 +83,10 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Download Artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v7 with: path: artifacts merge-multiple: true @@ -94,13 +94,8 @@ jobs: - name: Display Structure run: ls -R artifacts || ls -R . - - name: Prepare Release Files - run: | - mkdir -p release-files - find . -name "ai-commit-*" -type f -exec cp {} release-files/ \; - - name: Create Release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: files: | artifacts/**/* @@ -113,6 +108,8 @@ jobs: **Linux:** ```bash curl -L https://github.com/${{ github.repository }}/releases/download/${{ github.ref_name }}/ai-commit-linux-amd64 -o ai-commit + curl -L https://github.com/${{ github.repository }}/releases/download/${{ github.ref_name }}/ai-commit-linux-amd64.sha256 -o ai-commit-linux-amd64.sha256 + sha256sum -c ai-commit-linux-amd64.sha256 chmod +x ai-commit sudo mv ai-commit /usr/local/bin/ ``` @@ -120,6 +117,8 @@ jobs: **macOS:** ```bash curl -L https://github.com/${{ github.repository }}/releases/download/${{ github.ref_name }}/ai-commit-macos-amd64 -o ai-commit + curl -L https://github.com/${{ github.repository }}/releases/download/${{ github.ref_name }}/ai-commit-macos-amd64.sha256 -o ai-commit-macos-amd64.sha256 + shasum -a 256 -c ai-commit-macos-amd64.sha256 chmod +x ai-commit sudo mv ai-commit /usr/local/bin/ ``` diff --git a/.gitignore b/.gitignore index 0b62bd9..d78fb55 100644 --- a/.gitignore +++ b/.gitignore @@ -56,4 +56,7 @@ ai-commit-*-amd64* # GraalVM graal_isolate.h -graal_isolate_dynamic.h \ No newline at end of file +graal_isolate_dynamic.h + +# Audit dossier (local-only, never push) +findings/ \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 042be9f..1ac3af2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Breaking +- Interactive confirmation is now fail-closed: empty input, end-of-stream, or read errors cancel the commit (`[c]` default). Explicit `y`/`yes` is required to commit. +- `hasStagedChanges()` now propagates git failures instead of returning `false`; non-repositories and timeouts surface as errors. +- Diffs over 64KB, containing secrets, binary content, or generated lockfiles are refused before any AI call. + +### Security +- Secret redaction: staged diffs are scanned locally (API keys, private keys, JWTs, bearer tokens, credential assignments, credentialed URLs) and blocked findings never leave the machine; only rule IDs, lengths, and fingerprints are logged. +- Provider base URLs validated: https required except loopback unless `AI_ALLOW_INSECURE_HTTP=true`; credentials in URLs rejected. +- AI credentials (`*_API_KEY`, `AI_*`) stripped from git hook environments. +- Dependency CVEs fixed: Spring AI 1.1.0 to 1.1.8 (CVE-2026-22738, CVE-2026-40967, CVE-2026-41705, CVE-2026-47835), Jackson 2.20.1 to 2.21.7 (CVE-2026-54512, CVE-2026-54514, CVE-2026-68497). +- Installers verify release SHA256 checksums, use `mktemp`/random temp names, validate version format, support `AI_COMMIT_VERSION` pinning and `--verify-only` mode. +- Residual risk: Spring AI CVE-2026-47851/47852/59294/59318 have no OSS 1.1.x fix (Enterprise 1.1.9 only); affected components (PDF outline reader, ONNX cache, tool-calling fallback, resource cache) are not used by this CLI. + +### Changed +- `AI_COMMAND_TIMEOUT` is the canonical git timeout setting; `AI_TIMEOUT` remains as a deprecated alias with a warning. +- `config --auto-commit/--auto-push` reject invalid values instead of silently treating them as off. +- AI providers use bounded timeouts (10s connect, 60s read, 120s for Ollama) and a 512-token output cap; 401/429/timeout/DNS failures map to actionable errors. +- Single staged-diff fetch per run; bounded process capture; release builds run `mvn clean verify` (tests + coverage gate, no skips). +- Dependency hygiene: slf4j 2.0.20, JUnit 6.1.3, Mockito 5.23.0, maven-compiler 3.15.0, maven-shade 3.6.2, maven-surefire 3.5.6, native-maven-plugin 0.11.5. +- GitHub Actions moved to Node 24 runtimes: checkout v5, cache v5, upload-artifact v6, download-artifact v7, gh-release v3 (setup-graalvm v1 already current). + +### Technical +- JaCoCo 0.8.15 enforces 90% line + branch coverage on `verify` (currently 96.2% line, 90.5% branch across 168 tests). +- CI runs `mvn verify -DskipNativeBuild=true`; release runs `mvn clean verify`. + ## [1.2.0] - 2025-11-29 ### Added diff --git a/README.md b/README.md index e23e8fb..8d6379e 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,8 @@ So I built this. A standalone CLI that works everywhere, supports any OpenAI-com ### Option 1: One-Line Installer (Easiest) +Installers verify the release SHA256 checksum before installing. Pin a version with `AI_COMMIT_VERSION=vX.Y.Z`, or verify without installing via `--verify-only`. + **Linux/macOS:** ```bash curl -fsSL https://raw.githubusercontent.com/kxng0109/ai-commit-cli/main/install.sh | bash @@ -70,6 +72,8 @@ Download the pre-built binary for your platform from [Releases](https://github.c **Linux:** ```bash curl -L https://github.com/kxng0109/ai-commit-cli/releases/latest/download/ai-commit-linux-amd64 -o ai-commit +curl -L https://github.com/kxng0109/ai-commit-cli/releases/latest/download/ai-commit-linux-amd64.sha256 -o ai-commit-linux-amd64.sha256 +sha256sum -c ai-commit-linux-amd64.sha256 chmod +x ai-commit sudo mv ai-commit /usr/local/bin/ ai-commit --version @@ -95,7 +99,7 @@ ai-commit --version **Requirements:** - GraalVM 25 (with native-image) -- Apache Maven 3.9.11 +- Apache Maven 3.9.16 - Java 25 **Steps:** @@ -103,7 +107,7 @@ ai-commit --version git clone https://github.com/kxng0109/ai-commit-cli.git cd ai-commit-cli -mvn clean package -Pnative +mvn clean verify # Binary location: target/ai-commit (or ai-commit.exe on Windows) sudo cp target/ai-commit /usr/local/bin/ # Linux/macOS @@ -115,7 +119,7 @@ ai-commit --version **Development build (JAR, faster):** ```bash mvn clean package -java -jar target/ai-commit-cli-1.0.0.jar --version +java -jar target/ai-commit-cli-1.2.0.jar --version ``` ## Quick Start @@ -166,7 +170,8 @@ ai-commit | Variable | Default | Range | |----------|---------|-------| | `AI_TEMPERATURE` | 0.1 | 0.0 - 2.0 | -| `AI_COMMAND_TIMEOUT` | 30 | 1 - 3600 seconds | +| `AI_COMMAND_TIMEOUT` | 30 | 1 - 3600 seconds (`AI_TIMEOUT` still works as a deprecated alias) | +| `AI_ALLOW_INSECURE_HTTP` | false | Set `true` only to allow plain-http AI endpoints for non-local hosts | | `AI_LOG_LEVEL` | WARN | ERROR, WARN, INFO, DEBUG | ### User Preferences (Persistent) @@ -215,14 +220,17 @@ Implement Google OAuth2 integration with JWT token handling and secure session management. ──────────────────────────────────────────────────────────── -Commit with this message? (y)es / (r)egenerate / (e)dit / (c)ancel [y]: +Commit with this message? (y)es / (r)egenerate / (e)dit / (c)ancel [c]: ``` +Fail-closed by design: empty input, end-of-stream, or a read error cancels +the commit. Only an explicit `y`/`yes` commits. + **Options:** -- **`y` (yes)** - Commit with the AI-generated message (default, just press Enter) +- **`y`/`yes`** - Commit with the AI-generated message (explicit confirmation required) - **`r` (regenerate)** - Generate a new message with different wording -- **`e` (edit)** - Manually edit the message before committing -- **`c` (cancel)** - Cancel and don't commit +- **`e` (edit)** - Manually edit the message before committing (`c` at the edit prompt cancels) +- **`c` (cancel)** - Cancel and don't commit (default, just press Enter) ### Auto-Commit Mode @@ -501,17 +509,17 @@ ai-commit config --auto-commit on ```bash # Build JAR (fast iteration) mvn clean package -java -jar target/ai-commit-cli-1.0.0.jar +java -jar target/ai-commit-cli-1.2.0.jar -# Build native binary -mvn clean package -Pnative +# Build native binary (GraalVM required; JaCoCo gate enforced via verify) +mvn clean verify # Run with debug logging export AI_LOG_LEVEL=DEBUG ./target/ai-commit -# Run tests -mvn test +# Run tests with the 90% line+branch coverage gate +mvn verify -DskipNativeBuild=true ``` ## FAQ @@ -523,7 +531,7 @@ A: It's excellent for IntelliJ users, but it limits you to their provider select A: Honestly, it's your choice. For instance, I use OpenRouter mainly since you can get really good models for free and have access to a lot of models with just one API key. Then I use ollama (or LM Studio) just for testing. You can get professional grade models, but you're limited by your system's hardware. **Q: Does this send my code to AI providers?** -A: It sends the git diff (changes only), not your entire codebase. Use Ollama for fully local processing with zero external API calls. +A: It sends the git diff (changes only), not your entire codebase. Before sending, the diff is scanned locally: secrets (API keys, private keys, tokens, credentialed URLs), binary content, generated lockfiles, and diffs over 64KB are refused and never leave your machine. Provider base URLs must be https except for loopback hosts. Use Ollama for fully local processing with zero external API calls. **Q: When should I use auto-commit vs interactive mode?** A: Use **auto-commit** for rapid development when you trust the AI (small, frequent commits). Use **interactive mode** when you want to review messages carefully (large changes, important commits). diff --git a/TEST_SUMMARY.md b/TEST_SUMMARY.md index 7d6d502..1253ec1 100644 --- a/TEST_SUMMARY.md +++ b/TEST_SUMMARY.md @@ -1,6 +1,8 @@ # Test Suite Summary -## Total Tests: 56 +## Total Tests: 168 + +JaCoCo gate on `verify`: 90% line + branch minimum (currently 96.2% line, 90.5% branch). --- @@ -61,14 +63,14 @@ ## Running Tests ```bash -# Run all tests -mvn test +# Run all tests with the coverage gate (skips native-image; needs JDK 25) +mvn verify -DskipNativeBuild=true # Run a specific test class -mvn test -Dtest=ConfigTest +mvn test "-Dtest=ConfigTest" "-Djacoco.skip=true" -# Skip tests during build -mvn package -DskipTests +# Full native build (GraalVM 25 required) +mvn clean verify ``` ## Test Dependencies @@ -77,19 +79,25 @@ mvn package -DskipTests org.junit.jupiter junit-jupiter - 6.0.1 + 6.1.3 test org.mockito mockito-core - 5.20.0 + 5.23.0 test org.mockito mockito-junit-jupiter - 5.20.0 + 5.23.0 + test + + + org.assertj + assertj-core + 3.27.7 test ``` @@ -99,11 +107,24 @@ mvn package -DskipTests | Class | Tests | Coverage | |---------------------------|-------|---------------------------------------------| | ConfigTest | 9 | ~100% provider/config logic and guards | +| ConfigPolicyTest | 10 | URL policy, loopback, truthy, timeout range | +| ConfigParsingTest | 10 | temperature/timeout parsing, isConfigured | | UserPreferencesTest | 10 | ~100% preference/state/formatting | +| AiCommitCliTest | 4 | toggle parsing, error description | +| AiCommitCliRunTest | 18 | run() paths: version/help/config/commit-flow| | AiProviderFactoryTest | 4 | ~100% provider selection/prioritization | +| AiProviderFactoryReliabilityTest | 6 | per-provider type, output caps, priority | | GitServiceTest | 6 | ~90% public GitService usage scenarios | +| GitServiceEnvTest | 2 | secret env scrubbing | +| GitServiceValidationTest | 7 | timeout/dir/message validation | +| GitServiceWorkingDirTest | 6 | directory resolution matrix | +| GitServiceProcessTest | 8 | timeout/interrupt/truncation/process errors | +| SecretScannerTest | 17 | secret patterns, caps, summary hygiene | | CommitServiceTest | 15 | ~95% workflow, interactive, AI | | CommitServiceAutoPushTest | 12 | ~100% all auto-commit/push paths | +| CommitServiceGuardTest | 9 | fail-closed consent, diff policy | +| CommitServiceReliabilityTest | 9 | AI error mapping, null stages, interrupt | +| CommitServiceEdgeTest | 6 | null diff/output, 5xx, edit edges | --- diff --git a/install.ps1 b/install.ps1 index 6be50c4..12f0d03 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,34 +1,72 @@ # AI Commit CLI Installer for Windows # Usage: irm https://raw.githubusercontent.com/kxng0109/ai-commit-cli/main/install.ps1 | iex +# Pinned version: $env:AI_COMMIT_VERSION = "v1.2.0"; irm ... | iex + +param( + [string]$Version = $env:AI_COMMIT_VERSION, + [switch]$VerifyOnly +) $ErrorActionPreference = "Stop" +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + $REPO = "kxng0109/ai-commit-cli" $INSTALL_DIR = "$env:LOCALAPPDATA\Programs\ai-commit" Write-Host "==> Installing AI Commit CLI..." -ForegroundColor Cyan -Write-Host "==> Fetching latest version..." -ForegroundColor Cyan -try { - $response = Invoke-RestMethod -Uri "https://api.github.com/repos/$REPO/releases/latest" - $VERSION = $response.tag_name - Write-Host "==> Latest version: $VERSION" -ForegroundColor Green -} catch { - Write-Host "Error: Failed to fetch latest version - $_" -ForegroundColor Red +if ([string]::IsNullOrWhiteSpace($Version)) { + Write-Host "==> Fetching latest version..." -ForegroundColor Cyan + try { + $response = Invoke-RestMethod -Uri "https://api.github.com/repos/$REPO/releases/latest" -UseBasicParsing + $Version = $response.tag_name + } catch { + Write-Host "Error: Failed to fetch latest version - $_" -ForegroundColor Red + exit 1 + } +} +if ($Version -notmatch '^v\d+\.\d+\.\d+$') { + Write-Host "Error: Refusing to use unexpected version value: $Version" -ForegroundColor Red exit 1 } +Write-Host "==> Version: $Version" -ForegroundColor Green -$URL = "https://github.com/$REPO/releases/download/$VERSION/ai-commit-windows-amd64.exe" -$TMP = "$env:TEMP\ai-commit-$PID.exe" +$ASSET = "ai-commit-windows-amd64.exe" +$URL = "https://github.com/$REPO/releases/download/$Version/$ASSET" +$SHA_URL = "$URL.sha256" +$TMP = Join-Path $env:TEMP ("ai-commit-" + [IO.Path]::GetRandomFileName() + ".exe") +$TMP_SHA = "$TMP.sha256" Write-Host "==> Downloading..." -ForegroundColor Cyan try { - Invoke-WebRequest -Uri $URL -OutFile $TMP + Invoke-WebRequest -Uri $URL -OutFile $TMP -UseBasicParsing + Invoke-WebRequest -Uri $SHA_URL -OutFile $TMP_SHA -UseBasicParsing } catch { Write-Host "Error: Download failed - $_" -ForegroundColor Red exit 1 } +Write-Host "==> Verifying checksum..." -ForegroundColor Cyan +$expected = ((Get-Content -LiteralPath $TMP_SHA -TotalCount 1).Split(' ')[0]).Trim().ToLower() +$actual = (Get-FileHash -LiteralPath $TMP -Algorithm SHA256).Hash.ToLower() +if ([string]::IsNullOrWhiteSpace($expected)) { + Write-Host "Error: Empty checksum file" -ForegroundColor Red + exit 1 +} +if ($actual -ne $expected) { + Write-Host "Error: Checksum mismatch (download may be tampered)" -ForegroundColor Red + exit 1 +} +Write-Host "==> Checksum OK" -ForegroundColor Green + +if ($VerifyOnly) { + Remove-Item -LiteralPath $TMP -ErrorAction SilentlyContinue + Write-Host "==> Verify-only mode: checksum valid, nothing installed" -ForegroundColor Green + exit 0 +} +Remove-Item -LiteralPath $TMP_SHA -ErrorAction SilentlyContinue + if (-not (Test-Path $INSTALL_DIR)) { New-Item -ItemType Directory -Path $INSTALL_DIR -Force | Out-Null } @@ -63,4 +101,4 @@ Write-Host '"' Write-Host ' 2. Configure API key: $env:OPENAI_API_KEY = "sk-..."' Write-Host " 3. Use: cd your-repo; git add .; ai-commit" Write-Host "" -Write-Host "Run 'ai-commit --help' for more info" \ No newline at end of file +Write-Host "Run 'ai-commit --help' for more info" diff --git a/install.sh b/install.sh index aee6eac..efb408b 100644 --- a/install.sh +++ b/install.sh @@ -1,11 +1,31 @@ #!/usr/bin/env bash # AI Commit CLI Installer for Linux/macOS # Usage: curl -fsSL https://raw.githubusercontent.com/kxng0109/ai-commit-cli/main/install.sh | bash +# Pinned version: AI_COMMIT_VERSION=v1.2.0 bash install.sh +# Verify only (no install): bash install.sh --verify-only [--version=v1.2.0] -set -e +set -euo pipefail REPO="kxng0109/ai-commit-cli" INSTALL_DIR="${INSTALL_DIR:-/usr/local/bin}" +PINNED_VERSION="${AI_COMMIT_VERSION:-}" +VERIFY_ONLY=0 + +usage() { + echo "Usage: install.sh [--verify-only] [--version=vX.Y.Z]" + echo " --verify-only Download and verify the checksum without installing" + echo " --version=... Install a pinned version instead of the latest release" + echo "Env: AI_COMMIT_VERSION pins the version, INSTALL_DIR overrides the target directory" +} + +for arg in "$@"; do + case "$arg" in + --verify-only) VERIFY_ONLY=1 ;; + --version=*) PINNED_VERSION="${arg#--version=}" ;; + -h|--help) usage; exit 0 ;; + *) echo "Error: Unknown option: $arg" >&2; usage >&2; exit 1 ;; + esac +done echo "==> Installing AI Commit CLI..." @@ -18,43 +38,81 @@ esac echo "==> Detected: $PLATFORM" -echo "==> Fetching latest version..." -VERSION=$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/') -if [ -z "$VERSION" ]; then - echo "Error: Failed to fetch latest version" >&2 +if [ -n "$PINNED_VERSION" ]; then + VERSION="$PINNED_VERSION" +else + echo "==> Fetching latest version..." + VERSION=$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/') +fi +if [[ ! "$VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Error: Refusing to use unexpected version value: ${VERSION:-}" >&2 exit 1 fi -echo "==> Latest version: $VERSION" +echo "==> Version: $VERSION" -URL="https://github.com/$REPO/releases/download/$VERSION/ai-commit-$PLATFORM" -TMP="/tmp/ai-commit-$" +ASSET="ai-commit-$PLATFORM" +URL="https://github.com/$REPO/releases/download/$VERSION/$ASSET" +SHA_URL="$URL.sha256" + +TMPDIR=$(mktemp -d -t ai-commit-install.XXXXXX) +cleanup() { + rm -rf "$TMPDIR" +} +trap cleanup EXIT echo "==> Downloading..." if command -v curl &> /dev/null; then - curl -fsSL "$URL" -o "$TMP" + curl -fsSL "$URL" -o "$TMPDIR/$ASSET" + curl -fsSL "$SHA_URL" -o "$TMPDIR/$ASSET.sha256" elif command -v wget &> /dev/null; then - wget -q "$URL" -O "$TMP" + wget -q "$URL" -O "$TMPDIR/$ASSET" + wget -q "$SHA_URL" -O "$TMPDIR/$ASSET.sha256" else echo "Error: Neither curl nor wget found" >&2 exit 1 fi -chmod +x "$TMP" +echo "==> Verifying checksum..." +EXPECTED=$(awk '{print $1}' "$TMPDIR/$ASSET.sha256") +if [ -z "$EXPECTED" ]; then + echo "Error: Empty checksum file" >&2 + exit 1 +fi +if command -v sha256sum &> /dev/null; then + ACTUAL=$(sha256sum "$TMPDIR/$ASSET" | awk '{print $1}') +elif command -v shasum &> /dev/null; then + ACTUAL=$(shasum -a 256 "$TMPDIR/$ASSET" | awk '{print $1}') +else + echo "Error: Neither sha256sum nor shasum found" >&2 + exit 1 +fi +if [ "$ACTUAL" != "$EXPECTED" ]; then + echo "Error: Checksum mismatch for $ASSET (download may be tampered)" >&2 + exit 1 +fi +echo "==> Checksum OK" + +if [ "$VERIFY_ONLY" -eq 1 ]; then + echo "==> Verify-only mode: checksum valid, nothing installed" + exit 0 +fi + +chmod 755 "$TMPDIR/$ASSET" echo "==> Installing to $INSTALL_DIR..." if [ -w "$INSTALL_DIR" ]; then - mv "$TMP" "$INSTALL_DIR/ai-commit" + mv "$TMPDIR/$ASSET" "$INSTALL_DIR/ai-commit" else echo " (requires sudo)" - sudo mv "$TMP" "$INSTALL_DIR/ai-commit" + sudo mv "$TMPDIR/$ASSET" "$INSTALL_DIR/ai-commit" fi if command -v ai-commit &> /dev/null; then INSTALLED_VERSION=$(ai-commit --version 2>&1 || echo "unknown") - echo "==> ✓ Installation complete: $INSTALLED_VERSION" + echo "==> Installation complete: $INSTALLED_VERSION" else - echo "==> ✓ Installed to $INSTALL_DIR/ai-commit" + echo "==> Installed to $INSTALL_DIR/ai-commit" echo " Note: You may need to restart your terminal" fi @@ -63,4 +121,4 @@ echo "Next steps:" echo " 1. Configure: export OPENAI_API_KEY=\"sk-...\"" echo " 2. Use: cd your-repo && git add . && ai-commit" echo "" -echo "Run 'ai-commit --help' for more info" \ No newline at end of file +echo "Run 'ai-commit --help' for more info" diff --git a/pom.xml b/pom.xml index 5deee05..f9e0cff 100644 --- a/pom.xml +++ b/pom.xml @@ -15,8 +15,10 @@ UTF-8 io.github.kxng0109.AiCommitCli - 1.1.0 - 2.20.1 + 1.1.8 + 2.21.7 + 0.8.15 + @@ -68,27 +70,34 @@ org.slf4j slf4j-simple - 2.0.17 + 2.0.20 org.junit.jupiter junit-jupiter - 6.0.1 + 6.1.3 test org.mockito mockito-core - 5.20.0 + 5.23.0 test org.mockito mockito-junit-jupiter - 5.20.0 + 5.23.0 + test + + + + org.assertj + assertj-core + 3.27.7 test @@ -105,7 +114,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.14.1 + 3.15.0 ${java.version} ${java.version} @@ -115,7 +124,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.6.0 + 3.6.2 package @@ -157,7 +166,7 @@ org.graalvm.buildtools native-maven-plugin - 0.11.3 + 0.11.5 true @@ -201,7 +210,57 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.4 + 3.5.6 + + @{argLine} + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + prepare-agent + + prepare-agent + + + + report + verify + + report + + + + check + verify + + check + + + + + BUNDLE + + + LINE + COVEREDRATIO + 0.90 + + + BRANCH + COVEREDRATIO + 0.90 + + + + + + + diff --git a/src/main/java/io/github/kxng0109/AiCommitCli.java b/src/main/java/io/github/kxng0109/AiCommitCli.java index dd7a9bb..dee6790 100644 --- a/src/main/java/io/github/kxng0109/AiCommitCli.java +++ b/src/main/java/io/github/kxng0109/AiCommitCli.java @@ -11,6 +11,7 @@ import java.io.IOException; import java.io.InputStream; +import java.util.Locale; import java.util.Properties; /** @@ -56,21 +57,37 @@ public class AiCommitCli { private static final String VERSION = loadVersion(); public static void main(String[] args) { + System.exit(run(args)); + } + + /** + * Runs the CLI and returns the process exit code without exiting the JVM. + *

+ * Separating execution from {@code System.exit} keeps the command flow testable. + *

+ * + * @param args the command-line arguments, may be {@code null} + * @return 0 on success, 1 on failure + */ + static int run(String[] args) { + if (args == null) { + args = new String[0]; + } if (args.length > 0) { String arg = args[0]; if (arg.equals("--version") || arg.equals("-v")) { System.out.println("ai-commit version " + VERSION); - System.exit(0); + return 0; } if (arg.equals("--help") || arg.equals("-h")) { printHelp(); - System.exit(0); + return 0; } if(arg.equals("config")){ handleConfigCommand(args); - System.exit(0); + return 0; } } @@ -82,14 +99,66 @@ public static void main(String[] args) { CommitService commitService = new CommitService(gitService, chatModel); commitService.generateAndCommit(); - System.exit(0); + return 0; } catch (IllegalStateException e) { - System.err.println("\nAn error occurred: " + e.getMessage()); - System.exit(1); + System.err.println("\nAn error occurred: " + describeError(e)); + return 1; } catch (Exception e) { log.error("Unexpected error occurred: {}", e.getMessage(), e); - System.err.println("\nAn error occurred: " + e.getMessage()); - System.exit(1); + System.err.println("\nAn error occurred: " + describeError(e)); + return 1; + } + } + + /** + * Resolves a raw log level name to an allowlisted slf4j-simple level. + * + * @param rawLevel the raw level value, may be {@code null} + * @return the upper-cased level when allowlisted, otherwise {@code WARN} + */ + static String resolveLogLevel(String rawLevel) { + String logLevel = rawLevel == null ? "WARN" : rawLevel.trim().toUpperCase(Locale.ROOT); + switch (logLevel) { + case "ERROR", "WARN", "INFO", "DEBUG": + return logLevel; + default: + return "WARN"; + } + } + + /** + * Describes an error for user-facing output without ever printing a blank message. + * + * @param e the error to describe, must not be {@code null} + * @return the error message, or the error type name when the message is blank + */ + static String describeError(Exception e) { + String message = e.getMessage(); + return (message == null || message.isBlank()) ? e.toString() : message; + } + + /** + * Parses a strict on/off switch value for configuration commands. + *

+ * Accepted values are {@code on}, {@code true}, {@code 1}, and {@code yes} for + * enabled, and {@code off}, {@code false}, {@code 0}, and {@code no} for disabled. + *

+ * + * @param value the raw switch value, must not be {@code null} + * @param flag the flag name used in error messages, must not be {@code null} + * @return {@code true} when enabled, {@code false} when disabled + * @throws IllegalArgumentException when the value is not a recognized switch + */ + static boolean parseToggle(String value, String flag) { + String normalized = value.trim().toLowerCase(Locale.ROOT); + switch (normalized) { + case "on", "true", "1", "yes": + return true; + case "off", "false", "0", "no": + return false; + default: + throw new IllegalArgumentException( + "Invalid value '" + value.trim() + "' for " + flag + "; expected on|off."); } } @@ -139,7 +208,14 @@ private static void handleConfigCommand(String[] args){ System.out.println("Current: " + (UserPreferences.isAutoCommitEnabled() ? "enabled" : "disabled")); System.out.println("Usage: ai-commit config --auto-commit [on|off]"); } else { - boolean enable = args[2].equalsIgnoreCase("on") || args[2].equalsIgnoreCase("true"); + boolean enable; + try { + enable = parseToggle(args[2], "--auto-commit"); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println("Usage: ai-commit config --auto-commit [on|off]"); + break; + } UserPreferences.setAutoCommit(enable); System.out.println("Auto-commit " + (enable ? "enabled" : "disabled")); if (enable) { @@ -153,7 +229,14 @@ private static void handleConfigCommand(String[] args){ System.out.println("Current: " + (UserPreferences.isAutoPushEnabled() ? "enabled" : "disabled")); System.out.println("Usage: ai-commit config --auto-push [on|off]"); } else { - boolean enable = args[2].equalsIgnoreCase("on") || args[2].equalsIgnoreCase("true"); + boolean enable; + try { + enable = parseToggle(args[2], "--auto-push"); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + System.out.println("Usage: ai-commit config --auto-push [on|off]"); + break; + } UserPreferences.setAutoPush(enable); System.out.println("Auto-push " + (enable ? "enabled" : "disabled")); if (enable) { @@ -276,8 +359,8 @@ private static String loadVersion() { * */ private static void configureLogging() { - String logLevel = System.getenv().getOrDefault("AI_LOG_LEVEL", "WARN"); - System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", logLevel); + String rawLevel = System.getenv().getOrDefault("AI_LOG_LEVEL", "WARN"); + System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", resolveLogLevel(rawLevel)); System.setProperty("org.slf4j.simpleLogger.showDateTime", "false"); System.setProperty("org.slf4j.simpleLogger.showThreadName", "false"); System.setProperty("org.slf4j.simpleLogger.showLogName", "false"); @@ -337,10 +420,11 @@ DEEPSEEK_API_KEY Your API key (required) OLLAMA_MODEL Model name (required, e.g., llama3, qwen2.5) OLLAMA_BASE_URL Server URL (default: http://localhost:11434) - Optional Settings: - AI_LOG_LEVEL Log level: ERROR, WARN, INFO, DEBUG (default: WARN) - AI_TEMPERATURE Model temperature 0.0-2.0 (default: 0.1) - AI_COMMAND_TIMEOUT Git command timeout seconds (default: 30) + Optional Settings: + AI_LOG_LEVEL Log level: ERROR, WARN, INFO, DEBUG (default: WARN) + AI_TEMPERATURE Model temperature 0.0-2.0 (default: 0.1) + AI_COMMAND_TIMEOUT Git command timeout seconds (default: 30) + AI_ALLOW_INSECURE_HTTP Allow plain http AI endpoints: true|false (default: false) CONFIGURATION: ai-commit config --show # View settings diff --git a/src/main/java/io/github/kxng0109/config/Config.java b/src/main/java/io/github/kxng0109/config/Config.java index e41251f..81cf2b2 100644 --- a/src/main/java/io/github/kxng0109/config/Config.java +++ b/src/main/java/io/github/kxng0109/config/Config.java @@ -1,5 +1,12 @@ package io.github.kxng0109.config; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Represents the main configuration object for an application integrating multiple AI services. * This configuration class aggregates settings for OpenAI, Anthropic, Google, Deepseek, Ollama, @@ -14,7 +21,7 @@ * @param deepseek configuration for Deepseek services, including the API key. * @param ollama configuration for Ollama services, including model and base URL. * @param temperature a double representing the AI's temperature (creativity level) ranging - * from 0.0 (deterministic) to 1.0 (high creativity). + * from 0.0 (deterministic) to 2.0 (high creativity). * @param commandTimeoutSeconds an integer specifying the timeout (in seconds) for AI command executions, * within a valid range of 1 to 3599 seconds. */ @@ -27,6 +34,7 @@ public record Config( double temperature, int commandTimeoutSeconds ) { + private static final Logger log = LoggerFactory.getLogger(Config.class); /** * Loads and constructs a {@link Config} object using the environment variables. * This method retrieves configuration data for various APIs (OpenAI, Anthropic, Google, @@ -38,37 +46,37 @@ public record Config( */ public static Config loadFromEnv() { OpenAiConfig openai = new OpenAiConfig( - System.getenv("OPENAI_API_KEY"), - getEnvOrDefault("OPENAI_BASE_URL", "https://api.openai.com"), + blankToNull(System.getenv("OPENAI_API_KEY")), + validateBaseUrl("OPENAI_BASE_URL", + getEnvOrDefault("OPENAI_BASE_URL", "https://api.openai.com")), getEnvOrDefault("OPENAI_MODEL", "gpt-4o-mini") ); AnthropicConfig anthropic = new AnthropicConfig( - System.getenv("ANTHROPIC_API_KEY"), + blankToNull(System.getenv("ANTHROPIC_API_KEY")), getEnvOrDefault("ANTHROPIC_MODEL", "claude-sonnet-4-0") ); GoogleConfig google = new GoogleConfig( - System.getenv("GOOGLE_API_KEY"), + blankToNull(System.getenv("GOOGLE_API_KEY")), getEnvOrDefault("GOOGLE_MODEL", "gemini-2.0-flash") ); DeepseekConfig deepseek = new DeepseekConfig( - System.getenv("DEEPSEEK_API_KEY") + blankToNull(System.getenv("DEEPSEEK_API_KEY")) ); OllamaConfig ollama = new OllamaConfig( - System.getenv("OLLAMA_MODEL"), - getEnvOrDefault("OLLAMA_BASE_URL", "http://localhost:11434") + blankToNull(System.getenv("OLLAMA_MODEL")), + validateBaseUrl("OLLAMA_BASE_URL", + getEnvOrDefault("OLLAMA_BASE_URL", "http://localhost:11434")) ); double temperature = parseDouble( getEnvOrDefault("AI_TEMPERATURE", "0.1") ); - int timeout = parseInt( - getEnvOrDefault("AI_TIMEOUT", "30") - ); + int timeout = parseTimeout(); return new Config( openai, @@ -93,7 +101,137 @@ public static Config loadFromEnv() { */ private static String getEnvOrDefault(String key, String defaultValue) { String value = System.getenv(key); - return (value == null || value.isBlank()) ? defaultValue : value; + return (value == null || value.isBlank()) ? defaultValue : value.trim(); + } + + /** + * Returns a trimmed value or {@code null} when blank, for optional secrets and names. + * + * @param value the raw value, may be {@code null} + * @return the trimmed value, or {@code null} when {@code null} or blank + */ + private static String blankToNull(String value) { + return (value == null || value.isBlank()) ? null : value.trim(); + } + + /** + * Validates a provider base URL and rejects SSRF-prone values. + *

+ * Only {@code http} and {@code https} schemes are accepted, credentials in the + * URL are rejected, and plain {@code http} is limited to loopback hosts unless + * {@code AI_ALLOW_INSECURE_HTTP} is truthy. + *

+ * + * @param name the environment variable name for error messages, must not be {@code null} + * @param value the URL value to validate, must not be {@code null} + * @return the trimmed valid URL + * @throws IllegalStateException when the URL is blank, malformed, or unsafe + */ + static String validateBaseUrl(String name, String value) { + return validateBaseUrl(name, value, isTruthy(System.getenv("AI_ALLOW_INSECURE_HTTP"))); + } + + /** + * Validates a provider base URL with an explicit insecure-http allowance. + *

+ * Only {@code http} and {@code https} schemes are accepted, credentials in the + * URL are rejected, and plain {@code http} is limited to loopback hosts unless + * {@code allowInsecureHttp} is {@code true}. + *

+ * + * @param name the environment variable name for error messages, must not be {@code null} + * @param value the URL value to validate, must not be {@code null} + * @param allowInsecureHttp whether plain http is accepted for non-loopback hosts + * @return the trimmed valid URL + * @throws IllegalStateException when the URL is blank, malformed, or unsafe + */ + static String validateBaseUrl(String name, String value, boolean allowInsecureHttp) { + String trimmed = value == null ? "" : value.trim(); + if (trimmed.isEmpty()) { + throw new IllegalStateException(name + " must not be blank."); + } + URI uri; + try { + uri = new URI(trimmed); + } catch (URISyntaxException e) { + throw new IllegalStateException(name + " is not a valid URL.", e); + } + String scheme = uri.getScheme(); + if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) { + throw new IllegalStateException(name + " must use http or https."); + } + if (uri.getUserInfo() != null) { + throw new IllegalStateException(name + " must not contain credentials."); + } + String host = uri.getHost(); + if (host == null || host.isBlank()) { + throw new IllegalStateException(name + " must include a host."); + } + if (scheme.equalsIgnoreCase("http") && !isLoopbackHost(host) && !allowInsecureHttp) { + throw new IllegalStateException(name + " uses plain http for a non-local host; " + + "use https or set AI_ALLOW_INSECURE_HTTP=true."); + } + return trimmed; + } + + /** + * Checks whether a host is a loopback address. + * + * @param host the host to check, must not be {@code null} + * @return {@code true} for localhost, 127.x, or ::1 forms + */ + static boolean isLoopbackHost(String host) { + String lower = host.toLowerCase(Locale.ROOT); + return lower.equals("localhost") || lower.startsWith("127.") + || lower.equals("::1") || lower.equals("[::1]"); + } + + /** + * Parses a truthy switch value such as on, true, 1, or yes. + * + * @param value the raw value, may be {@code null} + * @return {@code true} for on, true, 1, or yes (case-insensitive) + */ + static boolean isTruthy(String value) { + if (value == null) { + return false; + } + String normalized = value.trim().toLowerCase(Locale.ROOT); + return normalized.equals("true") || normalized.equals("1") + || normalized.equals("yes") || normalized.equals("on"); + } + + /** + * Resolves the git command timeout, preferring {@code AI_COMMAND_TIMEOUT}. + *

+ * {@code AI_TIMEOUT} remains accepted as a deprecated alias. + *

+ * + * @return the timeout in seconds between 1 and 3599, or 30 when unset or invalid + */ + static int parseTimeout() { + return parseTimeout(System.getenv("AI_COMMAND_TIMEOUT"), System.getenv("AI_TIMEOUT")); + } + + /** + * Resolves the git command timeout from explicit values, preferring the canonical name. + *

+ * {@code AI_TIMEOUT} remains accepted as a deprecated alias. + *

+ * + * @param canonical the {@code AI_COMMAND_TIMEOUT} value, may be {@code null} + * @param legacy the {@code AI_TIMEOUT} value, may be {@code null} + * @return the timeout in seconds between 1 and 3599, or 30 when unset or invalid + */ + static int parseTimeout(String canonical, String legacy) { + if (canonical != null && !canonical.isBlank()) { + return parseInt(canonical.trim()); + } + if (legacy != null && !legacy.isBlank()) { + log.warn("AI_TIMEOUT is deprecated; use AI_COMMAND_TIMEOUT."); + return parseInt(legacy.trim()); + } + return 30; } /** @@ -103,11 +241,16 @@ private static String getEnvOrDefault(String key, String defaultValue) { * @param value the string to be parsed into a double. * @return the parsed double value between 0.0 and 2.0 (inclusive), or 0.1 if the input is invalid or out of range. */ - private static double parseDouble(String value) { + static double parseDouble(String value) { try { - double parsed = Double.parseDouble(value); - return (parsed < 0.0 || parsed > 2.0) ? 0.1 : parsed; + double parsed = Double.parseDouble(value.trim()); + if (!Double.isFinite(parsed) || parsed < 0.0 || parsed > 2.0) { + log.warn("Invalid AI_TEMPERATURE; using default 0.1."); + return 0.1; + } + return parsed; } catch (NumberFormatException e) { + log.warn("Invalid AI_TEMPERATURE; using default 0.1."); return 0.1; } } @@ -119,11 +262,16 @@ private static double parseDouble(String value) { * @param value the string to be parsed into an integer. * @return the parsed integer value between 1 and 3599 (inclusive), or 30 if the input is invalid or out of range. */ - private static int parseInt(String value) { + static int parseInt(String value) { try { - int i = Integer.parseInt(value); - return (i > 0 && i < 3600) ? i : 30; + int i = Integer.parseInt(value.trim()); + if (i > 0 && i < 3600) { + return i; + } + log.warn("AI timeout out of range; using default 30 seconds."); + return 30; } catch (NumberFormatException e) { + log.warn("Invalid AI timeout; using default 30 seconds."); return 30; } } diff --git a/src/main/java/io/github/kxng0109/service/AiProviderFactory.java b/src/main/java/io/github/kxng0109/service/AiProviderFactory.java index 2ac6e47..daefa9d 100644 --- a/src/main/java/io/github/kxng0109/service/AiProviderFactory.java +++ b/src/main/java/io/github/kxng0109/service/AiProviderFactory.java @@ -1,6 +1,7 @@ package io.github.kxng0109.service; import com.google.genai.Client; +import com.google.genai.types.HttpOptions; import io.github.kxng0109.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,7 +20,11 @@ import org.springframework.ai.openai.OpenAiChatModel; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.api.OpenAiApi; +import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.DefaultResponseErrorHandler; +import org.springframework.web.client.RestClient; + +import java.time.Duration; /** * Factory class for creating instances of {@code ChatModel} based on configuration. @@ -50,10 +55,33 @@ public class AiProviderFactory { private static final Logger log = LoggerFactory.getLogger(AiProviderFactory.class); + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10); + private static final Duration READ_TIMEOUT = Duration.ofSeconds(60); + private static final Duration OLLAMA_READ_TIMEOUT = Duration.ofSeconds(120); + private static final int GOOGLE_TIMEOUT_MILLIS = 60_000; + private static final int MAX_OUTPUT_TOKENS = 512; + private AiProviderFactory() { throw new UnsupportedOperationException("Utility class"); } + /** + * Builds a {@code RestClient.Builder} with bounded connect and read timeouts. + *

+ * Uses {@code SimpleClientHttpRequestFactory} so no extra HTTP client dependency is needed. + *

+ * + * @param connect the connect timeout, must not be {@code null} + * @param read the read timeout, must not be {@code null} + * @return a configured builder + */ + private static RestClient.Builder timedRestClient(Duration connect, Duration read) { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(connect); + factory.setReadTimeout(read); + return RestClient.builder().requestFactory(factory); + } + /** * Creates a {@code ChatModel} instance based on the provided configuration. * This method automatically selects the appropriate AI provider (e.g., OpenAI, Anthropic, Google, Deepseek, or Ollama) @@ -139,15 +167,17 @@ public static ChatModel createChatModel(Config config) { */ private static ChatModel createOpenAiModel(Config config) { OpenAiApi api = OpenAiApi.builder() - .apiKey(config.openai().apiKey()) - .baseUrl(config.openai().baseUrl()) - .responseErrorHandler(new DefaultResponseErrorHandler()) - .build(); + .apiKey(config.openai().apiKey()) + .baseUrl(config.openai().baseUrl()) + .restClientBuilder(timedRestClient(CONNECT_TIMEOUT, READ_TIMEOUT)) + .responseErrorHandler(new DefaultResponseErrorHandler()) + .build(); OpenAiChatOptions options = OpenAiChatOptions.builder() - .model(config.openai().model()) - .temperature(config.temperature()) - .build(); + .model(config.openai().model()) + .temperature(config.temperature()) + .maxTokens(MAX_OUTPUT_TOKENS) + .build(); return OpenAiChatModel.builder() .openAiApi(api) @@ -165,14 +195,19 @@ private static ChatModel createOpenAiModel(Config config) { * @return a fully configured {@code ChatModel} for interacting with the Google Generative AI API */ private static ChatModel createGoogleModel(Config config) { + HttpOptions httpOptions = HttpOptions.builder() + .timeout(GOOGLE_TIMEOUT_MILLIS) + .build(); Client client = Client.builder() - .apiKey(config.google().apiKey()) - .build(); + .apiKey(config.google().apiKey()) + .httpOptions(httpOptions) + .build(); GoogleGenAiChatOptions options = GoogleGenAiChatOptions.builder() - .temperature(config.temperature()) - .model(config.google().model()) - .build(); + .temperature(config.temperature()) + .model(config.google().model()) + .maxOutputTokens(MAX_OUTPUT_TOKENS) + .build(); return GoogleGenAiChatModel.builder() .defaultOptions(options) @@ -191,14 +226,16 @@ private static ChatModel createGoogleModel(Config config) { */ private static ChatModel createAnthropicModel(Config config) { AnthropicApi api = AnthropicApi.builder() - .apiKey(config.anthropic().apiKey()) - .responseErrorHandler(new DefaultResponseErrorHandler()) - .build(); + .apiKey(config.anthropic().apiKey()) + .restClientBuilder(timedRestClient(CONNECT_TIMEOUT, READ_TIMEOUT)) + .responseErrorHandler(new DefaultResponseErrorHandler()) + .build(); AnthropicChatOptions options = AnthropicChatOptions.builder() - .model(config.anthropic().model()) - .temperature(config.temperature()) - .build(); + .model(config.anthropic().model()) + .temperature(config.temperature()) + .maxTokens(MAX_OUTPUT_TOKENS) + .build(); return AnthropicChatModel.builder() .defaultOptions(options) @@ -217,14 +254,16 @@ private static ChatModel createAnthropicModel(Config config) { */ private static ChatModel createDeepseekModel(Config config) { DeepSeekApi api = DeepSeekApi.builder() - .apiKey(config.deepseek().apiKey()) - .responseErrorHandler(new DefaultResponseErrorHandler()) - .build(); + .apiKey(config.deepseek().apiKey()) + .restClientBuilder(timedRestClient(CONNECT_TIMEOUT, READ_TIMEOUT)) + .responseErrorHandler(new DefaultResponseErrorHandler()) + .build(); DeepSeekChatOptions options = DeepSeekChatOptions.builder() - .model("deepseek-chat") - .temperature(config.temperature()) - .build(); + .model("deepseek-chat") + .temperature(config.temperature()) + .maxTokens(MAX_OUTPUT_TOKENS) + .build(); return DeepSeekChatModel.builder() .deepSeekApi(api) @@ -244,14 +283,16 @@ private static ChatModel createDeepseekModel(Config config) { */ private static ChatModel createOllamaModel(Config config) { OllamaApi api = OllamaApi.builder() - .baseUrl(config.ollama().baseUrl()) - .responseErrorHandler(new DefaultResponseErrorHandler()) - .build(); + .baseUrl(config.ollama().baseUrl()) + .restClientBuilder(timedRestClient(CONNECT_TIMEOUT, OLLAMA_READ_TIMEOUT)) + .responseErrorHandler(new DefaultResponseErrorHandler()) + .build(); OllamaChatOptions options = OllamaChatOptions.builder() - .model(config.ollama().model()) - .temperature(config.temperature()) - .build(); + .model(config.ollama().model()) + .temperature(config.temperature()) + .numPredict(MAX_OUTPUT_TOKENS) + .build(); return OllamaChatModel.builder() .ollamaApi(api) diff --git a/src/main/java/io/github/kxng0109/service/CommitService.java b/src/main/java/io/github/kxng0109/service/CommitService.java index 9183835..b932bb3 100644 --- a/src/main/java/io/github/kxng0109/service/CommitService.java +++ b/src/main/java/io/github/kxng0109/service/CommitService.java @@ -6,12 +6,17 @@ import org.springframework.ai.chat.messages.SystemMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.model.Generation; import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.web.client.RestClientResponseException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; import java.util.List; /** @@ -175,11 +180,17 @@ public CommitService(GitService gitService, ChatModel chatModel) { */ public void generateAndCommit() { log.info("Checking for staged changes..."); - if (!gitService.hasStagedChanges()) { + String diff; + try { + diff = gitService.getStagedDiff(); + } catch (RuntimeException e) { + throw new IllegalStateException("No staged changes found! Use the 'git add' to stage changes first.", e); + } + if (diff == null || diff.isBlank()) { throw new IllegalStateException("No staged changes found! Use the 'git add' to stage changes first."); } - String diff = gitService.getStagedDiff(); + guardDiff(diff); boolean autoCommit = UserPreferences.isAutoCommitEnabled(); boolean autoPush = UserPreferences.isAutoPushEnabled(); @@ -191,6 +202,26 @@ public void generateAndCommit() { } } + /** + * Guards a staged diff against oversize, binary, generated-file, and secret content. + *

+ * The check runs before any AI call so blocked content never leaves the machine. + * Findings are logged as rule identifiers with lengths and fingerprints only. + *

+ * + * @param diff the staged diff to guard, must not be {@code null} + * @throws IllegalStateException when the diff must not be sent to AI + */ + private void guardDiff(String diff) { + List findings = SecretScanner.scan(diff); + if (!findings.isEmpty()) { + String summary = SecretScanner.summarize(findings); + log.warn("Diff blocked from AI submission: {}", summary); + throw new IllegalStateException("Refusing to send diff to AI (" + summary + "). Remove secrets, " + + "generated files, or reduce staged changes («git diff --staged --stat») and retry."); + } + } + /** * Handles the process of automatically generating, committing, and optionally pushing changes based on a provided diff. *

@@ -223,8 +254,8 @@ private void handleAutoCommit(String diff, boolean autoPush) { handleAutoPush(autoPush); } catch (RuntimeException e) { - System.err.println("\nFailed to generate commit message: " + e.getMessage()); - System.err.println("Auto-commit aborted. No changes were committed."); + System.err.println("\nAuto-commit failed: " + e.getMessage()); + System.err.println("Auto-commit aborted."); log.error("Auto-commit failed: {}", e.getMessage(), e); throw e; } @@ -264,7 +295,7 @@ private void handleInteractiveCommit(String diff, boolean autoPush) { String choice = promptUser(); switch (choice) { - case "y": + case "y", "yes": log.info("Committing changes..."); String output = gitService.commit(commitMessage); @@ -275,12 +306,12 @@ private void handleInteractiveCommit(String diff, boolean autoPush) { handleAutoPush(autoPush); break; - case "r": + case "r", "regenerate": log.info("\nRegenerating commit message..."); commitMessage = null; break; - case "e": + case "e", "edit": commitMessage = editCommitMessage(commitMessage); if (commitMessage == null) { System.out.println("Edit cancelled."); @@ -288,7 +319,7 @@ private void handleInteractiveCommit(String diff, boolean autoPush) { break; } - if (!commitMessage.isEmpty()) { + if (!commitMessage.isBlank()) { log.info("Using edited message as commit message..."); String editOutput = gitService.commit(commitMessage); displayGitOutput(editOutput); @@ -299,7 +330,7 @@ private void handleInteractiveCommit(String diff, boolean autoPush) { } break; - case "c": + case "c", "cancel": System.out.println(); System.out.println("Cancelling commit..."); isCommitted = true; //Just to break out of the while loop @@ -346,40 +377,45 @@ private void handleAutoPush(boolean autoPush) { * Prompts the user for input regarding the next action to take with the provided commit message. *

* This method displays a set of options to the user: confirm the commit message (yes), regenerate, - * edit, or cancel. If the user provides no input or an invalid input, the default action is - * considered as "yes". In case of an error during input reading, the method also defaults to "yes". + * edit, or cancel. The method is fail-closed: empty input, end-of-stream, or read errors cancel + * the commit instead of committing unapproved text. *

* - * @return the user's choice as a lowercase string: "y", "r", "e", or "c". Defaults to "y" if no input - * is provided or an IOException occurs. + * @return the user's choice as a lowercase string such as "y", "yes", "r", "e", or "c". + * Defaults to "c" when input is empty or an IOException occurs. */ private String promptUser() { System.out.println(); - System.out.println("Commit with this message? (y)es / (r)egenerate / (e)dit / (c)ancel [y]: "); + System.out.println("Commit with this message? (y)es / (r)egenerate / (e)dit / (c)ancel [c]: "); System.out.flush(); try { String input = reader.readLine(); - if (input == null || input.isBlank() || input.trim().isEmpty()) { - return "y"; + if (input == null) { + return "c"; + } + String normalized = input.trim().toLowerCase(); + if (normalized.isEmpty()) { + return "c"; } - return input.trim().toLowerCase(); + return normalized; } catch (IOException e) { log.error("Failed to read user input: {}", e.getMessage()); - return "y"; + return "c"; } } /** * Allows the user to edit a commit message interactively through the console. *

- * This method displays the current commit message to the user and prompts them to either enter - * a new message or press Enter to keep the original message unchanged. If an input error occurs - * or the user does not provide a valid new message, the original message is returned by default. + * This method displays the current commit message to the user and prompts them to enter + * a new message, press Enter to keep the original message, or type {@code c} to cancel. + * End-of-stream and read errors cancel the edit and return {@code null} so the caller + * can abort instead of committing unapproved text. *

* * @param originalMessage the original commit message to be potentially modified by the user - * @return the new commit message provided by the user, or the original message if no valid input is given + * @return the new commit message, the original message when kept, or {@code null} when cancelled */ private String editCommitMessage(String originalMessage) { System.out.println(); @@ -388,22 +424,31 @@ private String editCommitMessage(String originalMessage) { System.out.println(originalMessage); System.out.println("=".repeat(60)); System.out.println(); - System.out.println("Enter new commit message or press Enter to keep current one:"); + System.out.println("Enter new commit message, Enter to keep current one, or c to cancel:"); System.out.println("> "); System.out.flush(); try { String newMessage = reader.readLine(); - if (newMessage == null || newMessage.trim().isEmpty()) { + if (newMessage == null) { + System.out.println("Edit cancelled."); + return null; + } + String trimmed = newMessage.trim(); + if (trimmed.equalsIgnoreCase("c") || trimmed.equalsIgnoreCase("cancel")) { + System.out.println("Edit cancelled."); + return null; + } + if (trimmed.isEmpty()) { System.out.println("Empty message. Using original commit message."); return originalMessage; } - return newMessage.trim(); + return trimmed; } catch (IOException e) { log.error("Failed to read user input: {}", e.getMessage()); - System.out.println("Error reading user input. Using original commit message."); - return originalMessage; + System.out.println("Error reading user input. Cancelling edit."); + return null; } } @@ -423,35 +468,78 @@ private String generateMessage(String diff) { ) ); - String message = chatModel.call(prompt) - .getResult() - .getOutput() - .getText(); + ChatResponse response = chatModel.call(prompt); + if (response == null) { + throw new IllegalStateException("AI returned no response"); + } + Generation result = response.getResult(); + if (result == null || result.getOutput() == null) { + throw new IllegalStateException("AI returned no message output"); + } + String message = result.getOutput().getText(); - if (message == null || message.isBlank() || message.trim().isEmpty()) { + if (message == null || message.isBlank()) { throw new IllegalStateException("AI returned an empty commit message"); } return message.trim(); } catch (Exception e) { + if (e instanceof InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new RuntimeException("AI request was interrupted.", interrupted); + } log.error("Failed to generate a commit message: {}", e.getMessage(), e); - if (e instanceof IllegalStateException) { - throw new IllegalStateException("AI returned an empty commit message"); + if (e instanceof IllegalStateException illegalState) { + throw new IllegalStateException(illegalState.getMessage(), e); } - Throwable cause = e.getCause(); + Throwable cause = e; while (cause != null) { + if (cause instanceof InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new RuntimeException("AI request was interrupted.", e); + } if (cause instanceof ConnectException) { throw new RuntimeException( "Cannot connect to AI provider. Check your internet connection and verify the provider is accessible.", e ); } + if (cause instanceof UnknownHostException unknownHost) { + throw new RuntimeException( + "Cannot resolve AI provider host '" + unknownHost.getMessage() + + "'. Check the base URL and DNS.", + e + ); + } + if (cause instanceof SocketTimeoutException) { + throw new RuntimeException( + "AI provider timed out. Check your connection or try a reachable provider.", + e + ); + } + if (cause instanceof RestClientResponseException responseError) { + int status = responseError.getRawStatusCode(); + if (status == 401) { + throw new RuntimeException( + "AI provider rejected the request (401 unauthorized). Check the API key.", + e + ); + } + if (status == 429) { + throw new RuntimeException( + "AI provider rate limit exceeded (429). Wait and retry.", + e + ); + } + } cause = cause.getCause(); } - throw new RuntimeException("Failed to generate a commit message: " + e.getMessage(), e); + String detail = e.getMessage(); + throw new RuntimeException( + "Failed to generate a commit message: " + (detail == null || detail.isBlank() ? e : detail), e); } } diff --git a/src/main/java/io/github/kxng0109/service/GitService.java b/src/main/java/io/github/kxng0109/service/GitService.java index 572848c..4ea9c40 100644 --- a/src/main/java/io/github/kxng0109/service/GitService.java +++ b/src/main/java/io/github/kxng0109/service/GitService.java @@ -3,10 +3,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Closeable; import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.nio.charset.StandardCharsets; +import java.util.Map; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; /** * The {@code GitService} class provides a simplified and programmatic approach to @@ -38,14 +43,21 @@ public class GitService { * Constructs a new {@code GitService} instance with a specified operation timeout and working directory. * This enables timeout control and specifies the directory where Git operations will be performed. * - * @param timeoutSeconds the maximum operation timeout in seconds; Git commands exceeding this duration - * will be forcefully terminated to prevent indefinite hangs + * @param timeoutSeconds the maximum operation timeout in seconds, from 1 to 3599; + * Git commands exceeding this duration are forcefully terminated * @param workingDirectory the absolute path of the directory where Git commands should be executed; - * this must be a valid and accessible directory path + * this must be an existing accessible directory + * @throws IllegalArgumentException when the timeout is out of range or the directory is invalid */ public GitService(int timeoutSeconds, String workingDirectory) { + if (timeoutSeconds < 1 || timeoutSeconds > 3599) { + throw new IllegalArgumentException("timeoutSeconds must be between 1 and 3599."); + } + if (workingDirectory == null || workingDirectory.isBlank()) { + throw new IllegalArgumentException("workingDirectory must not be blank."); + } this.timeoutSeconds = timeoutSeconds; - this.workingDirectory = workingDirectory; + this.workingDirectory = canonicalize(workingDirectory); } /** @@ -53,38 +65,91 @@ public GitService(int timeoutSeconds, String workingDirectory) { * The working directory for Git operations is automatically detected using * a platform-appropriate mechanism. * - * @param timeoutSeconds the maximum operation timeout in seconds. This value determines - * the duration after which Git commands are forcefully terminated - * to prevent hanging. + * @param timeoutSeconds the maximum operation timeout in seconds, from 1 to 3599. + * @throws IllegalArgumentException when the timeout is out of range or no usable directory exists */ public GitService(int timeoutSeconds) { this(timeoutSeconds, detectWorkingDirectory()); } /** - * Detects the current working directory by attempting to retrieve it using the `PWD` environment variable - * (primarily for Unix-like systems such as MacOS and Linux) or by falling back to the absolute path of the - * current directory if the `PWD` variable is unavailable or invalid. + * Detects the current working directory, preferring the JVM-controlled {@code user.dir}. + *

+ * The {@code PWD} environment variable is only used as a fallback when {@code user.dir} + * is unavailable, because it can be spoofed. The result is canonicalized. + *

* - * @return the absolute path to the detected working directory as a {@code String}. Returns the value of the `PWD` - * environment variable if valid and points to an existing directory; otherwise, falls back to the absolute path - * of the current directory. + * @return the canonical path to the detected working directory as a {@code String} + * @throws IllegalStateException when no usable working directory can be determined */ private static String detectWorkingDirectory() { - //For MacOS and Linux - String pwd = System.getenv("PWD"); - if (pwd != null && !pwd.isEmpty()) { + String userDir = null; + try { + userDir = System.getProperty("user.dir"); + } catch (SecurityException e) { + log.debug("Cannot read user.dir", e); + } + String fallback = new File(".").getAbsoluteFile().getParent(); + return resolveWorkingDirectory(userDir, System.getenv("PWD"), fallback); + } + + /** + * Resolves the working directory from explicit candidates, preferring the JVM value. + *

+ * The {@code PWD} environment variable is only used as a fallback when {@code user.dir} + * is unavailable, because it can be spoofed. The result is canonicalized. + *

+ * + * @param userDir the {@code user.dir} value, may be {@code null} + * @param pwd the {@code PWD} value, may be {@code null} + * @param fallback the last-resort path, may be {@code null} + * @return the canonical path to the resolved working directory + * @throws IllegalStateException when no usable working directory can be determined + */ + static String resolveWorkingDirectory(String userDir, String pwd, String fallback) { + if (userDir != null && !userDir.isBlank()) { + File userDirFile = new File(userDir); + if (userDirFile.isDirectory() && userDirFile.canRead()) { + log.debug("Detected working directory from user.dir"); + return canonicalize(userDir); + } + } + + if (pwd != null && !pwd.isBlank()) { File pwdFile = new File(pwd); - if (pwdFile.exists() && pwdFile.isDirectory()) { + if (pwdFile.isDirectory() && pwdFile.canRead()) { log.debug("Detected working directory from PWD: {}", pwd); - return pwd; + return canonicalize(pwd); } } - // Fallback: get absolute path of current directory - String fallback = new File(".").getAbsoluteFile().getParent(); - log.debug("Using fallback working directory: {}", fallback); - return new File(".").getAbsoluteFile().getParent(); + if (fallback != null && !fallback.isBlank()) { + File fallbackFile = new File(fallback); + if (fallbackFile.isDirectory() && fallbackFile.canRead()) { + log.debug("Using fallback working directory: {}", fallback); + return canonicalize(fallback); + } + } + throw new IllegalStateException("Cannot determine a usable working directory."); + } + + /** + * Canonicalizes a directory path, resolving symlinks and relative segments. + * + * @param path the path to canonicalize, must not be {@code null} + * @return the canonical path + * @throws IllegalArgumentException when the path is not an accessible directory + */ + private static String canonicalize(String path) { + File file = new File(path); + if (!file.isDirectory() || !file.canRead()) { + throw new IllegalArgumentException("workingDirectory must be an existing readable directory."); + } + try { + return file.getCanonicalPath(); + } catch (IOException e) { + throw new IllegalArgumentException("workingDirectory cannot be resolved.", e); + } } /** @@ -106,11 +171,16 @@ public String getStagedDiff() { * Commits the currently staged changes in the Git repository with the provided commit message. * This method invokes the Git command to commit changes and adds the specified message. * - * @param message the commit message describing the changes being committed + * @param message the commit message describing the changes being committed, + * must not be {@code null} or blank * @return the output of the Git commit command as a string, typically containing * information about the success of the commit operation + * @throws IllegalArgumentException when the message is {@code null} or blank */ public String commit(String message) { + if (message == null || message.isBlank()) { + throw new IllegalArgumentException("commit message must not be blank."); + } log.debug("Committing changes..."); return runCommand("git", "commit", "--message", message); } @@ -130,20 +200,18 @@ public String push(){ /** * Checks whether there are staged changes in the Git repository. - * This method determines if any files have been staged for commit by analyzing - * the output of a Git command retrieving staged differences. + *

+ * Fatal git failures (non-repository, missing binary, timeout) propagate as + * {@code RuntimeException} instead of masquerading as no changes. + *

* * @return {@code true} if there are staged changes in the repository, {@code false} otherwise. + * @throws RuntimeException when the underlying git command fails */ public boolean hasStagedChanges() { log.debug("Checking if staged changes..."); - try { - String diff = getStagedDiff(); - return diff != null && !diff.isEmpty(); - } catch (RuntimeException e) { - log.debug("Failed to check for staged changes", e); - return false; - } + String diff = getStagedDiff(); + return diff != null && !diff.isEmpty(); } /** @@ -167,6 +235,8 @@ private String runCommand(String... command) { // Disable Git pager to prevent interactive prompts processBuilder.environment().put("GIT_PAGER", "cat"); + // Never leak AI credentials to repo-controlled git hooks + scrubSecretEnv(processBuilder.environment()); Process process = null; try { @@ -174,24 +244,20 @@ private String runCommand(String... command) { StringBuilder outputBuilder = new StringBuilder(); StringBuilder errorBuilder = new StringBuilder(); + AtomicBoolean outputTruncated = new AtomicBoolean(false); + AtomicBoolean errorTruncated = new AtomicBoolean(false); Process finalProcess1 = process; Thread outputThread = new Thread(() -> { - try { - outputBuilder.append(new String(finalProcess1.getInputStream().readAllBytes(), StandardCharsets.UTF_8)); - } catch (IOException e) { - log.debug("Error reading output stream", e); - } - }); + drainBounded(finalProcess1.getInputStream(), outputBuilder, outputTruncated); + }, "git-stdout-drain"); + outputThread.setDaemon(true); Process finalProcess = process; Thread errorThread = new Thread(() -> { - try { - errorBuilder.append(new String(finalProcess.getErrorStream().readAllBytes(), StandardCharsets.UTF_8)); - } catch (IOException e) { - log.debug("Error reading error stream", e); - } - }); + drainBounded(finalProcess.getErrorStream(), errorBuilder, errorTruncated); + }, "git-stderr-drain"); + errorThread.setDaemon(true); outputThread.start(); errorThread.start(); @@ -199,13 +265,25 @@ private String runCommand(String... command) { // Just to prevent the process from hanging indefinitely boolean finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS); - outputThread.join(1000); - errorThread.join(1000); - if (!finished) { process.destroyForcibly(); + closeQuietly(process.getInputStream()); + closeQuietly(process.getErrorStream()); + closeQuietly(process.getOutputStream()); + outputThread.join(1000); + errorThread.join(1000); + throw new RuntimeException(String.format( + "Timeout waiting for %s after %d seconds.", describeCommand(command), timeoutSeconds)); + } + + outputThread.join(); + errorThread.join(); + + if (outputTruncated.get() || errorTruncated.get()) { throw new RuntimeException( - String.format("Timeout while waiting for process('%s') to finish", String.join(" ", command))); + String.format("Command ('%s') output exceeded %d bytes and was truncated; refusing to proceed. " + + "Reduce staged changes («git diff --staged --stat») and retry.", + String.join(" ", command), SecretScanner.MAX_DIFF_BYTES)); } String output = outputBuilder.toString().trim(); @@ -213,11 +291,14 @@ private String runCommand(String... command) { int exitCode = process.exitValue(); if (exitCode != 0) { + log.debug("Git command failed: {} exit={} stdout={} stderr={}", + describeCommand(command), exitCode, output, error); + String detail = error.isEmpty() ? output : error; throw new RuntimeException(String.format( - "Command ('%s') failed with exit code: %d\n %s", - String.join(" ", command), + "%s failed with exit code %d: %s", + describeCommand(command), exitCode, - error + truncate(detail, 500) )); } @@ -225,23 +306,106 @@ private String runCommand(String... command) { } catch (IOException e) { throw new RuntimeException( String.format( - "Failed to execute command: %s. %s \n %s ", - String.join(" ", command), - e.getMessage(), - e - ) + "Failed to start %s. Ensure git is installed and the directory is accessible.", + describeCommand(command) + ), + e ); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(String.format( - "Command ('%s') interrupted. %s", - String.join(" ", command), - e - )); + "%s interrupted.", + describeCommand(command) + ), e); } finally { if (process != null && process.isAlive()) { process.destroyForcibly(); } } } + + /** + * Closes a stream without throwing, to unblock stream-drain threads on timeout. + * + * @param stream the stream to close, may be {@code null} + */ + private static void closeQuietly(Closeable stream) { + if (stream == null) { + return; + } + try { + stream.close(); + } catch (IOException e) { + log.debug("Error closing process stream", e); + } + } + + /** + * Removes AI credentials from a process environment so repo-controlled git hooks inherit none. + *

+ * Entries ending in {@code _API_KEY} or starting with {@code AI_} are removed. + *

+ * + * @param environment the mutable process environment, must not be {@code null} + */ + static void scrubSecretEnv(Map environment) { + environment.keySet().removeIf(key -> key.endsWith("_API_KEY") || key.startsWith("AI_")); + } + + /** + * Describes a git command by binary and subcommand only, never logging arguments. + *

+ * Arguments may carry commit messages or paths, so they stay out of user-facing errors. + *

+ * + * @param command the command and arguments, must not be {@code null} + * @return a short description such as {@code git commit} + */ + private static String describeCommand(String... command) { + if (command.length > 1) { + return command[0] + " " + command[1]; + } + return command.length == 1 ? command[0] : "git"; + } + + /** + * Truncates text for user-facing messages. + * + * @param text the text to truncate, may be {@code null} + * @param maxLength the maximum length to keep + * @return the truncated text, or an empty string when {@code null} + */ + private static String truncate(String text, int maxLength) { + if (text == null) { + return ""; + } + return text.length() <= maxLength ? text : text.substring(0, maxLength) + "…"; + } + + /** + * Drains a process stream with a hard byte cap to prevent memory exhaustion. + *

+ * Reads up to {@code MAX_DIFF_BYTES + 1} bytes; when more data exists the + * remainder is discarded so the child never blocks on a full pipe, and the + * truncation flag is set for the caller to abort safely. + *

+ * + * @param stream the process stream to drain, must not be {@code null} + * @param target the accumulator for decoded text, must not be {@code null} + * @param truncated set to {@code true} when input exceeds the cap, must not be {@code null} + */ + private static void drainBounded(InputStream stream, StringBuilder target, AtomicBoolean truncated) { + try { + byte[] chunk = stream.readNBytes(SecretScanner.MAX_DIFF_BYTES + 1); + if (chunk.length > SecretScanner.MAX_DIFF_BYTES) { + truncated.set(true); + target.append(new String(chunk, 0, SecretScanner.MAX_DIFF_BYTES, StandardCharsets.UTF_8)); + stream.transferTo(OutputStream.nullOutputStream()); + } else { + target.append(new String(chunk, StandardCharsets.UTF_8)); + } + } catch (IOException e) { + log.debug("Error reading process stream", e); + } + } } \ No newline at end of file diff --git a/src/main/java/io/github/kxng0109/service/SecretScanner.java b/src/main/java/io/github/kxng0109/service/SecretScanner.java new file mode 100644 index 0000000..0ad3082 --- /dev/null +++ b/src/main/java/io/github/kxng0109/service/SecretScanner.java @@ -0,0 +1,156 @@ +package io.github.kxng0109.service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Scans staged diffs for secrets before they are sent to external AI providers. + *

+ * The scanner is dependency-free and uses standard library regular expressions + * only. It never logs or returns secret content; findings carry rule identifiers, + * safe hints, lengths, and one-way fingerprints instead. + *

+ */ +public final class SecretScanner { + + /** Maximum diff size in bytes accepted for AI submission. Larger diffs abort with instructions. */ + public static final int MAX_DIFF_BYTES = 64 * 1024; + + private static final Pattern PRIVATE_KEY = + Pattern.compile("-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----"); + private static final Pattern CERTIFICATE = + Pattern.compile("-----BEGIN CERTIFICATE-----"); + private static final Pattern AWS_ACCESS_KEY = Pattern.compile("AKIA[0-9A-Z]{16}"); + private static final Pattern GITHUB_TOKEN = Pattern.compile("gh[pousr]_[A-Za-z0-9]{36,}"); + private static final Pattern OPENAI_KEY = Pattern.compile("sk-(?:live-|test-|proj-)?[A-Za-z0-9]{20,}"); + private static final Pattern JWT = + Pattern.compile("eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+"); + private static final Pattern BEARER_TOKEN = + Pattern.compile("(?i)Bearer\\s+[A-Za-z0-9\\-._~+/=]{20,}"); + private static final Pattern GENERIC_ASSIGNMENT = Pattern.compile( + "(?i)(api[_-]?key|api[_-]?token|secret|client[_-]?secret|passwd|password|auth[_-]?token|access[_-]?token)\\s*(=|:|=>|:=).{1,200}"); + private static final Pattern CONNECTION_STRING = Pattern.compile( + "(?i)(mongodb|postgres|postgresql|mysql|redis)(\\+srv)?://[^\\s]+:[^\\s]+@[^\\s]+"); + private static final Pattern ADDED_FILE = + Pattern.compile("(?m)^\\+\\+\\+ b/(.+)$"); + + private static final String[] LOCKED_SUFFIXES = { + "package-lock.json", "pnpm-lock.yaml", "yarn.lock", "go.sum", + "Cargo.lock", "Gemfile.lock", "poetry.lock", ".min.js", ".min.css", ".map" + }; + + private SecretScanner() { + throw new UnsupportedOperationException("Utility class"); + } + + /** + * A single blocking finding without any secret content. + * + * @param ruleId the stable rule identifier such as {@code PRIVATE_KEY} or {@code OVERSIZE} + * @param hint safe context such as a filename or rule description, never secret content + * @param secretLength the matched length in characters, or the diff size for oversize findings + * @param fingerprint the first 8 hex characters of the SHA-256 of the match, for log correlation + */ + public record Finding(String ruleId, String hint, int secretLength, String fingerprint) { + } + + /** + * Scans the given diff for blocking findings. + * + * @param diff the staged diff to scan, must not be {@code null} + * @return an unmodifiable list of findings, empty when the diff is safe to send + * @throws NullPointerException when {@code diff} is {@code null} + */ + public static List scan(String diff) { + Objects.requireNonNull(diff, "diff must not be null"); + List findings = new ArrayList<>(); + int byteLength = diff.getBytes(StandardCharsets.UTF_8).length; + if (byteLength > MAX_DIFF_BYTES) { + findings.add(new Finding("OVERSIZE", "diff exceeds " + MAX_DIFF_BYTES + " bytes", byteLength, + fingerprint(Integer.toString(byteLength)))); + return Collections.unmodifiableList(findings); + } + if (diff.indexOf('\u0000') >= 0) { + findings.add(new Finding("BINARY", "diff contains binary content", byteLength, + fingerprint("binary:" + byteLength))); + return Collections.unmodifiableList(findings); + } + checkLockfiles(diff, findings); + match(PRIVATE_KEY, "PRIVATE_KEY", "private key block", diff, findings); + match(CERTIFICATE, "CERTIFICATE", "certificate block", diff, findings); + match(AWS_ACCESS_KEY, "AWS_ACCESS_KEY", "aws access key", diff, findings); + match(GITHUB_TOKEN, "GITHUB_TOKEN", "github token", diff, findings); + match(OPENAI_KEY, "API_KEY", "api key", diff, findings); + match(JWT, "JWT", "jwt", diff, findings); + match(BEARER_TOKEN, "BEARER_TOKEN", "bearer token", diff, findings); + match(GENERIC_ASSIGNMENT, "CREDENTIAL_ASSIGNMENT", "credential assignment", diff, findings); + match(CONNECTION_STRING, "CONNECTION_STRING", "credentialed connection string", diff, findings); + return Collections.unmodifiableList(findings); + } + + /** + * Summarizes findings for user-facing abort messages without secret content. + * + * @param findings the findings to summarize, must not be {@code null} + * @return a single-line summary such as {@code PRIVATE_KEY(len=48, fp=abc12345)} + * @throws NullPointerException when {@code findings} is {@code null} + */ + public static String summarize(List findings) { + Objects.requireNonNull(findings, "findings must not be null"); + StringBuilder summary = new StringBuilder(); + for (int i = 0; i < findings.size(); i++) { + Finding finding = findings.get(i); + if (i > 0) { + summary.append("; "); + } + summary.append(finding.ruleId()).append("(len=").append(finding.secretLength()) + .append(", fp=").append(finding.fingerprint()).append(')'); + } + return summary.toString(); + } + + private static void checkLockfiles(String diff, List findings) { + Matcher matcher = ADDED_FILE.matcher(diff); + while (matcher.find()) { + String filename = matcher.group(1).trim(); + for (String suffix : LOCKED_SUFFIXES) { + if (filename.endsWith(suffix)) { + findings.add(new Finding("LOCKFILE", "generated file " + filename, filename.length(), + fingerprint("lockfile:" + filename))); + break; + } + } + } + } + + private static void match(Pattern pattern, String ruleId, String hint, String diff, + List findings) { + Matcher matcher = pattern.matcher(diff); + while (matcher.find()) { + String matched = matcher.group(); + findings.add(new Finding(ruleId, hint, matched.length(), fingerprint(matched))); + } + } + + private static String fingerprint(String value) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(8); + for (int i = 0; i < 4; i++) { + hex.append(Character.forDigit((hash[i] >> 4) & 0xF, 16)); + hex.append(Character.forDigit(hash[i] & 0xF, 16)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 unavailable", e); + } + } +} diff --git a/src/test/java/io/github/kxng0109/AiCommitCliRunTest.java b/src/test/java/io/github/kxng0109/AiCommitCliRunTest.java new file mode 100644 index 0000000..03f4070 --- /dev/null +++ b/src/test/java/io/github/kxng0109/AiCommitCliRunTest.java @@ -0,0 +1,162 @@ +package io.github.kxng0109; + +import io.github.kxng0109.config.UserPreferences; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Guards for CLI entry paths in {@link AiCommitCli}. + */ +@DisplayName("AiCommitCli run") +public class AiCommitCliRunTest { + + @AfterEach + void cleanup() { + UserPreferences.reset(); + } + + @Test + @DisplayName("version flag returns success") + void versionFlag_returnsSuccess() { + assertThat(AiCommitCli.run(new String[]{"--version"})).isZero(); + assertThat(AiCommitCli.run(new String[]{"-v"})).isZero(); + } + + @Test + @DisplayName("help flag returns success") + void helpFlag_returnsSuccess() { + assertThat(AiCommitCli.run(new String[]{"--help"})).isZero(); + assertThat(AiCommitCli.run(new String[]{"-h"})).isZero(); + } + + @Test + @DisplayName("null args are treated as empty") + void nullArgs_treatedAsEmpty() { + assumeTrue(noProviderConfigured()); + + assertThat(AiCommitCli.run(null)).isOne(); + } + + @Test + @DisplayName("config without subcommand prints usage") + void configWithoutSubcommand_printsUsage() { + assertThat(AiCommitCli.run(new String[]{"config"})).isZero(); + } + + @Test + @DisplayName("config show returns success") + void configShow_returnsSuccess() { + assertThat(AiCommitCli.run(new String[]{"config", "--show"})).isZero(); + } + + @Test + @DisplayName("config help returns success") + void configHelp_returnsSuccess() { + assertThat(AiCommitCli.run(new String[]{"config", "--help"})).isZero(); + } + + @Test + @DisplayName("config auto-commit on then off round-trips") + void configAutoCommit_roundTrips() { + assertThat(AiCommitCli.run(new String[]{"config", "--auto-commit", "on"})).isZero(); + assertThat(UserPreferences.isAutoCommitEnabled()).isTrue(); + assertThat(AiCommitCli.run(new String[]{"config", "--auto-commit", "off"})).isZero(); + assertThat(UserPreferences.isAutoCommitEnabled()).isFalse(); + } + + @Test + @DisplayName("config auto-commit without value shows current") + void configAutoCommitWithoutValue_showsCurrent() { + assertThat(AiCommitCli.run(new String[]{"config", "--auto-commit"})).isZero(); + } + + @Test + @DisplayName("config auto-commit with invalid value keeps state") + void configAutoCommitInvalid_keepsState() { + assertThat(AiCommitCli.run(new String[]{"config", "--auto-commit", "banana"})).isZero(); + assertThat(UserPreferences.isAutoCommitEnabled()).isFalse(); + } + + @Test + @DisplayName("config auto-push on then off round-trips") + void configAutoPush_roundTrips() { + assertThat(AiCommitCli.run(new String[]{"config", "--auto-push", "on"})).isZero(); + assertThat(UserPreferences.isAutoPushEnabled()).isTrue(); + assertThat(AiCommitCli.run(new String[]{"config", "--auto-push", "off"})).isZero(); + assertThat(UserPreferences.isAutoPushEnabled()).isFalse(); + } + + @Test + @DisplayName("config auto-push without value shows current") + void configAutoPushWithoutValue_showsCurrent() { + assertThat(AiCommitCli.run(new String[]{"config", "--auto-push"})).isZero(); + } + + @Test + @DisplayName("config auto-push with invalid value keeps state") + void configAutoPushInvalid_keepsState() { + assertThat(AiCommitCli.run(new String[]{"config", "--auto-push", "maybe"})).isZero(); + assertThat(UserPreferences.isAutoPushEnabled()).isFalse(); + } + + @Test + @DisplayName("config auto-push notes inactive auto-commit") + void configAutoPush_notesInactiveAutoCommit() { + UserPreferences.setAutoCommit(false); + + assertThat(AiCommitCli.run(new String[]{"config", "--auto-push", "on"})).isZero(); + } + + @Test + @DisplayName("config reset returns success") + void configReset_returnsSuccess() { + UserPreferences.setAutoCommit(true); + + assertThat(AiCommitCli.run(new String[]{"config", "--reset"})).isZero(); + assertThat(UserPreferences.isAutoCommitEnabled()).isFalse(); + } + + @Test + @DisplayName("unknown config subcommand returns success") + void unknownSubcommand_returnsSuccess() { + assertThat(AiCommitCli.run(new String[]{"config", "--bogus"})).isZero(); + } + + @Test + @DisplayName("commit flow without provider returns failure") + void commitFlowWithoutProvider_returnsFailure() { + assumeTrue(noProviderConfigured()); + + assertThat(AiCommitCli.run(new String[0])).isOne(); + } + + @Test + @DisplayName("log level resolution allowlists known levels") + void logLevel_allowlisted() { + assertThat(AiCommitCli.resolveLogLevel("debug")).isEqualTo("DEBUG"); + assertThat(AiCommitCli.resolveLogLevel("ERROR")).isEqualTo("ERROR"); + assertThat(AiCommitCli.resolveLogLevel("info")).isEqualTo("INFO"); + assertThat(AiCommitCli.resolveLogLevel(null)).isEqualTo("WARN"); + assertThat(AiCommitCli.resolveLogLevel("verbose")).isEqualTo("WARN"); + assertThat(AiCommitCli.resolveLogLevel(" ")).isEqualTo("WARN"); + } + + @Test + @DisplayName("default constructor exists") + void defaultConstructor_exists() { + assertThat(new AiCommitCli()).isNotNull(); + } + + private static boolean noProviderConfigured() { + return System.getenv("OPENAI_API_KEY") == null + && System.getenv("ANTHROPIC_API_KEY") == null + && System.getenv("GOOGLE_API_KEY") == null + && System.getenv("DEEPSEEK_API_KEY") == null + && System.getenv("OLLAMA_MODEL") == null; + } +} diff --git a/src/test/java/io/github/kxng0109/AiCommitCliTest.java b/src/test/java/io/github/kxng0109/AiCommitCliTest.java new file mode 100644 index 0000000..9ff3058 --- /dev/null +++ b/src/test/java/io/github/kxng0109/AiCommitCliTest.java @@ -0,0 +1,53 @@ +package io.github.kxng0109; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Guards for CLI switch parsing and error description in {@link AiCommitCli}. + */ +@DisplayName("AiCommitCli policy") +public class AiCommitCliTest { + + @Test + @DisplayName("on forms enable the switch") + void onForms_enableSwitch() { + assertThat(AiCommitCli.parseToggle("on", "--auto-commit")).isTrue(); + assertThat(AiCommitCli.parseToggle("ON", "--auto-commit")).isTrue(); + assertThat(AiCommitCli.parseToggle("true", "--auto-commit")).isTrue(); + assertThat(AiCommitCli.parseToggle("1", "--auto-commit")).isTrue(); + assertThat(AiCommitCli.parseToggle("yes", "--auto-commit")).isTrue(); + assertThat(AiCommitCli.parseToggle(" on ", "--auto-commit")).isTrue(); + } + + @Test + @DisplayName("off forms disable the switch") + void offForms_disableSwitch() { + assertThat(AiCommitCli.parseToggle("off", "--auto-push")).isFalse(); + assertThat(AiCommitCli.parseToggle("OFF", "--auto-push")).isFalse(); + assertThat(AiCommitCli.parseToggle("false", "--auto-push")).isFalse(); + assertThat(AiCommitCli.parseToggle("0", "--auto-push")).isFalse(); + assertThat(AiCommitCli.parseToggle("no", "--auto-push")).isFalse(); + } + + @Test + @DisplayName("unknown switch value is rejected without state change") + void unknownValue_isRejected() { + assertThatThrownBy(() -> AiCommitCli.parseToggle("banana", "--auto-commit")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("on|off"); + assertThatThrownBy(() -> AiCommitCli.parseToggle("", "--auto-push")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @DisplayName("error description never blanks") + void errorDescription_neverBlanks() { + assertThat(AiCommitCli.describeError(new IllegalStateException("boom"))).isEqualTo("boom"); + assertThat(AiCommitCli.describeError(new IllegalStateException())).isNotBlank(); + assertThat(AiCommitCli.describeError(new IllegalStateException(" "))).isNotBlank(); + } +} diff --git a/src/test/java/io/github/kxng0109/config/ConfigParsingTest.java b/src/test/java/io/github/kxng0109/config/ConfigParsingTest.java new file mode 100644 index 0000000..83a99b0 --- /dev/null +++ b/src/test/java/io/github/kxng0109/config/ConfigParsingTest.java @@ -0,0 +1,102 @@ +package io.github.kxng0109.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Guards for parsing and provider state in {@link Config}. + */ +@DisplayName("Config parsing") +public class ConfigParsingTest { + + @Test + @DisplayName("temperature accepts boundaries and valid values") + void temperature_acceptsBoundaries() { + assertThat(Config.parseDouble("0.0")).isZero(); + assertThat(Config.parseDouble("2.0")).isEqualTo(2.0); + assertThat(Config.parseDouble(" 0.7 ")).isEqualTo(0.7); + } + + @Test + @DisplayName("temperature falls back on invalid input") + void temperature_fallsBackOnInvalid() { + assertThat(Config.parseDouble("-0.1")).isEqualTo(0.1); + assertThat(Config.parseDouble("2.1")).isEqualTo(0.1); + assertThat(Config.parseDouble("NaN")).isEqualTo(0.1); + assertThat(Config.parseDouble("Infinity")).isEqualTo(0.1); + assertThat(Config.parseDouble("-Infinity")).isEqualTo(0.1); + assertThat(Config.parseDouble("hot")).isEqualTo(0.1); + } + + @Test + @DisplayName("timeout accepts boundaries and valid values") + void timeout_acceptsBoundaries() { + assertThat(Config.parseInt("1")).isOne(); + assertThat(Config.parseInt("3599")).isEqualTo(3599); + assertThat(Config.parseInt(" 45 ")).isEqualTo(45); + } + + @Test + @DisplayName("timeout falls back on invalid input") + void timeout_fallsBackOnInvalid() { + assertThat(Config.parseInt("0")).isEqualTo(30); + assertThat(Config.parseInt("3600")).isEqualTo(30); + assertThat(Config.parseInt("-5")).isEqualTo(30); + assertThat(Config.parseInt("forever")).isEqualTo(30); + } + + @Test + @DisplayName("timeout prefers canonical name over legacy alias") + void timeout_prefersCanonical() { + assertThat(Config.parseTimeout("45", "60")).isEqualTo(45); + assertThat(Config.parseTimeout(" 45 ", "60")).isEqualTo(45); + assertThat(Config.parseTimeout(null, "60")).isEqualTo(60); + assertThat(Config.parseTimeout(" ", "60")).isEqualTo(60); + assertThat(Config.parseTimeout(null, null)).isEqualTo(30); + assertThat(Config.parseTimeout(null, " ")).isEqualTo(30); + assertThat(Config.parseTimeout("bogus", null)).isEqualTo(30); + } + + @Test + @DisplayName("insecure http is accepted behind explicit opt-in") + void insecureHttp_acceptedWithOptIn() { + assertThat(Config.validateBaseUrl("OPENAI_BASE_URL", "http://proxy.internal:8080", true)) + .isEqualTo("http://proxy.internal:8080"); + } + + @Test + @DisplayName("scheme-less value is rejected") + void schemeLess_rejected() { + assertThatThrownBy(() -> Config.validateBaseUrl("OPENAI_BASE_URL", "api.example.com", false)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("http or https"); + } + + @Test + @DisplayName("null value is rejected") + void nullValue_rejected() { + assertThatThrownBy(() -> Config.validateBaseUrl("OPENAI_BASE_URL", null, false)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not be blank"); + } + + @Test + @DisplayName("blank keys never count as configured") + void blankKeys_neverConfigured() { + assertThat(new Config.OpenAiConfig(" ", "https://api.openai.com", "gpt-4o-mini").isConfigured()) + .isFalse(); + assertThat(new Config.AnthropicConfig("", "claude-sonnet-4-0").isConfigured()).isFalse(); + assertThat(new Config.GoogleConfig(" ", "gemini-2.0-flash").isConfigured()).isFalse(); + assertThat(new Config.DeepseekConfig("").isConfigured()).isFalse(); + assertThat(new Config.OllamaConfig(" ", "http://localhost:11434").isConfigured()).isFalse(); + } + + @Test + @DisplayName("preferences holder instantiates") + void preferences_instantiates() { + assertThat(new UserPreferences()).isNotNull(); + } +} diff --git a/src/test/java/io/github/kxng0109/config/ConfigPolicyTest.java b/src/test/java/io/github/kxng0109/config/ConfigPolicyTest.java new file mode 100644 index 0000000..c7eda3a --- /dev/null +++ b/src/test/java/io/github/kxng0109/config/ConfigPolicyTest.java @@ -0,0 +1,104 @@ +package io.github.kxng0109.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Guards for provider URL policy and switch parsing in {@link Config}. + */ +@DisplayName("Config policy") +public class ConfigPolicyTest { + + @Test + @DisplayName("https provider URL is accepted") + void httpsUrl_isAccepted() { + assertThat(Config.validateBaseUrl("OPENAI_BASE_URL", "https://api.openai.com")) + .isEqualTo("https://api.openai.com"); + } + + @Test + @DisplayName("http loopback URL is accepted") + void httpLoopback_isAccepted() { + assertThat(Config.validateBaseUrl("OLLAMA_BASE_URL", "http://localhost:11434")) + .isEqualTo("http://localhost:11434"); + assertThat(Config.validateBaseUrl("OLLAMA_BASE_URL", "http://127.0.0.1:11434")) + .isEqualTo("http://127.0.0.1:11434"); + } + + @Test + @DisplayName("http remote URL is rejected") + void httpRemote_isRejected() { + assertThatThrownBy(() -> Config.validateBaseUrl("OPENAI_BASE_URL", "http://evil.example.com")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("plain http"); + } + + @Test + @DisplayName("URL with credentials is rejected") + void urlWithCredentials_isRejected() { + assertThatThrownBy( + () -> Config.validateBaseUrl("OPENAI_BASE_URL", "https://user:pass@api.example.com")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("credentials"); + } + + @Test + @DisplayName("non-http scheme is rejected") + void nonHttpScheme_isRejected() { + assertThatThrownBy(() -> Config.validateBaseUrl("OPENAI_BASE_URL", "ftp://api.example.com")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("http or https"); + } + + @Test + @DisplayName("blank URL is rejected") + void blankUrl_isRejected() { + assertThatThrownBy(() -> Config.validateBaseUrl("OPENAI_BASE_URL", " ")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not be blank"); + } + + @Test + @DisplayName("malformed URL is rejected") + void malformedUrl_isRejected() { + assertThatThrownBy(() -> Config.validateBaseUrl("OPENAI_BASE_URL", "https://exa mple.com")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not a valid URL"); + } + + @Test + @DisplayName("loopback detection covers common forms") + void loopback_detectionCoversCommonForms() { + assertThat(Config.isLoopbackHost("localhost")).isTrue(); + assertThat(Config.isLoopbackHost("LOCALHOST")).isTrue(); + assertThat(Config.isLoopbackHost("127.0.0.1")).isTrue(); + assertThat(Config.isLoopbackHost("127.0.0.2")).isTrue(); + assertThat(Config.isLoopbackHost("::1")).isTrue(); + assertThat(Config.isLoopbackHost("[::1]")).isTrue(); + assertThat(Config.isLoopbackHost("api.example.com")).isFalse(); + assertThat(Config.isLoopbackHost("localhost.evil.com")).isFalse(); + } + + @Test + @DisplayName("truthy parsing covers switch forms") + void truthy_parsesSwitchForms() { + assertThat(Config.isTruthy("true")).isTrue(); + assertThat(Config.isTruthy("1")).isTrue(); + assertThat(Config.isTruthy("yes")).isTrue(); + assertThat(Config.isTruthy("on")).isTrue(); + assertThat(Config.isTruthy(" ON ")).isTrue(); + assertThat(Config.isTruthy("false")).isFalse(); + assertThat(Config.isTruthy("0")).isFalse(); + assertThat(Config.isTruthy(null)).isFalse(); + assertThat(Config.isTruthy("maybe")).isFalse(); + } + + @Test + @DisplayName("timeout resolves within range") + void timeout_resolvesWithinRange() { + assertThat(Config.parseTimeout()).isBetween(1, 3599); + } +} diff --git a/src/test/java/io/github/kxng0109/service/AiProviderFactoryReliabilityTest.java b/src/test/java/io/github/kxng0109/service/AiProviderFactoryReliabilityTest.java new file mode 100644 index 0000000..3ba863f --- /dev/null +++ b/src/test/java/io/github/kxng0109/service/AiProviderFactoryReliabilityTest.java @@ -0,0 +1,142 @@ +package io.github.kxng0109.service; + +import io.github.kxng0109.config.Config; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.ai.anthropic.AnthropicChatModel; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.deepseek.DeepSeekChatModel; +import org.springframework.ai.google.genai.GoogleGenAiChatModel; +import org.springframework.ai.google.genai.GoogleGenAiChatOptions; +import org.springframework.ai.ollama.OllamaChatModel; +import org.springframework.ai.ollama.api.OllamaChatOptions; +import org.springframework.ai.openai.OpenAiChatModel; + +/** + * Guards for provider selection, output caps, and timeouts in {@link AiProviderFactory}. + */ +@DisplayName("AiProviderFactory reliability") +public class AiProviderFactoryReliabilityTest { + + @Test + @DisplayName("anthropic-only config selects anthropic with output cap") + void anthropicOnly_selectsAnthropicWithCap() { + ChatModel model = AiProviderFactory.createChatModel(configWithAnthropic()); + + assertThat(model).isInstanceOf(AnthropicChatModel.class); + assertThat(model.getDefaultOptions().getMaxTokens()).isEqualTo(512); + assertThat(model.getDefaultOptions().getModel()).isEqualTo("claude-sonnet-4-0"); + } + + @Test + @DisplayName("google-only config selects google with output cap") + void googleOnly_selectsGoogleWithCap() { + ChatModel model = AiProviderFactory.createChatModel(configWithGoogle()); + + assertThat(model).isInstanceOf(GoogleGenAiChatModel.class); + GoogleGenAiChatOptions options = (GoogleGenAiChatOptions) model.getDefaultOptions(); + assertThat(options.getMaxOutputTokens()).isEqualTo(512); + assertThat(options.getModel()).isEqualTo("gemini-2.0-flash"); + } + + @Test + @DisplayName("deepseek-only config selects deepseek with output cap") + void deepseekOnly_selectsDeepseekWithCap() { + ChatModel model = AiProviderFactory.createChatModel(configWithDeepseek()); + + assertThat(model).isInstanceOf(DeepSeekChatModel.class); + assertThat(model.getDefaultOptions().getMaxTokens()).isEqualTo(512); + } + + @Test + @DisplayName("ollama-only config selects ollama with native prediction cap") + void ollamaOnly_selectsOllamaWithCap() { + ChatModel model = AiProviderFactory.createChatModel(configWithOllama()); + + assertThat(model).isInstanceOf(OllamaChatModel.class); + OllamaChatOptions options = (OllamaChatOptions) model.getDefaultOptions(); + assertThat(options.getNumPredict()).isEqualTo(512); + assertThat(options.getModel()).isEqualTo("llama3"); + } + + @Test + @DisplayName("openai config carries output cap and model") + void openai_carriesCapAndModel() { + Config config = new Config( + new Config.OpenAiConfig("test-key", "https://api.openai.com", "gpt-4o-mini"), + new Config.AnthropicConfig(null, "claude-sonnet-4-0"), + new Config.GoogleConfig(null, "gemini-2.0-flash"), + new Config.DeepseekConfig(null), + new Config.OllamaConfig(null, "http://localhost:11434"), + 0.1, + 30); + + ChatModel model = AiProviderFactory.createChatModel(config); + + assertThat(model).isInstanceOf(OpenAiChatModel.class); + assertThat(model.getDefaultOptions().getMaxTokens()).isEqualTo(512); + assertThat(model.getDefaultOptions().getTemperature()).isEqualTo(0.1); + } + + @Test + @DisplayName("anthropic outranks google") + void anthropic_outranksGoogle() { + Config config = new Config( + new Config.OpenAiConfig(null, "https://api.openai.com", "gpt-4o-mini"), + new Config.AnthropicConfig("anthropic-key", "claude-sonnet-4-0"), + new Config.GoogleConfig("google-key", "gemini-2.0-flash"), + new Config.DeepseekConfig(null), + new Config.OllamaConfig(null, "http://localhost:11434"), + 0.1, + 30); + + assertThat(AiProviderFactory.createChatModel(config)).isInstanceOf(AnthropicChatModel.class); + } + + private static Config configWithAnthropic() { + return new Config( + new Config.OpenAiConfig(null, "https://api.openai.com", "gpt-4o-mini"), + new Config.AnthropicConfig("anthropic-key", "claude-sonnet-4-0"), + new Config.GoogleConfig(null, "gemini-2.0-flash"), + new Config.DeepseekConfig(null), + new Config.OllamaConfig(null, "http://localhost:11434"), + 0.2, + 30); + } + + private static Config configWithGoogle() { + return new Config( + new Config.OpenAiConfig(null, "https://api.openai.com", "gpt-4o-mini"), + new Config.AnthropicConfig(null, "claude-sonnet-4-0"), + new Config.GoogleConfig("google-key", "gemini-2.0-flash"), + new Config.DeepseekConfig(null), + new Config.OllamaConfig(null, "http://localhost:11434"), + 0.2, + 30); + } + + private static Config configWithDeepseek() { + return new Config( + new Config.OpenAiConfig(null, "https://api.openai.com", "gpt-4o-mini"), + new Config.AnthropicConfig(null, "claude-sonnet-4-0"), + new Config.GoogleConfig(null, "gemini-2.0-flash"), + new Config.DeepseekConfig("deepseek-key"), + new Config.OllamaConfig(null, "http://localhost:11434"), + 0.2, + 30); + } + + private static Config configWithOllama() { + return new Config( + new Config.OpenAiConfig(null, "https://api.openai.com", "gpt-4o-mini"), + new Config.AnthropicConfig(null, "claude-sonnet-4-0"), + new Config.GoogleConfig(null, "gemini-2.0-flash"), + new Config.DeepseekConfig(null), + new Config.OllamaConfig("llama3", "http://localhost:11434"), + 0.2, + 30); + } +} diff --git a/src/test/java/io/github/kxng0109/service/CommitServiceAutoPushTest.java b/src/test/java/io/github/kxng0109/service/CommitServiceAutoPushTest.java index 0d95ca2..d5afddc 100644 --- a/src/test/java/io/github/kxng0109/service/CommitServiceAutoPushTest.java +++ b/src/test/java/io/github/kxng0109/service/CommitServiceAutoPushTest.java @@ -51,7 +51,6 @@ void generateAndCommit_withBothDisabled_shouldNotPush() { BufferedReader mockReader = new BufferedReader(new StringReader("y\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit(anyString())).thenReturn("success"); @@ -72,7 +71,6 @@ void generateAndCommit_withInteractiveModeAndAutoPush_shouldPushAfterAccept() { BufferedReader mockReader = new BufferedReader(new StringReader("y\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit(anyString())).thenReturn("success"); when(gitService.push()).thenReturn("pushed"); @@ -94,7 +92,6 @@ void generateAndCommit_withInteractiveModeAutoPushAndRegenerate_shouldOnlyPushOn BufferedReader mockReader = new BufferedReader(new StringReader("r\ny\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit(anyString())).thenReturn("success"); when(gitService.push()).thenReturn("pushed"); @@ -120,7 +117,6 @@ void generateAndCommit_withInteractiveModeAutoPushAndEdit_shouldPushEditedMessag BufferedReader mockReader = new BufferedReader(new StringReader("e\n" + editedMessage + "\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit(editedMessage)).thenReturn("success"); when(gitService.push()).thenReturn("pushed"); @@ -142,7 +138,6 @@ void generateAndCommit_withInteractiveModeAutoPushAndCancel_shouldNotCommitOrPus BufferedReader mockReader = new BufferedReader(new StringReader("c\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); ChatResponse mockResponse = createMockChatResponse("feat: test"); @@ -162,7 +157,6 @@ void generateAndCommit_withInteractiveModeAutoPushButPushFails_shouldStillCommit BufferedReader mockReader = new BufferedReader(new StringReader("y\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit(anyString())).thenReturn("success"); when(gitService.push()).thenThrow(new RuntimeException("Push failed")); @@ -183,7 +177,6 @@ void generateAndCommit_withAutoCommitOnlyAndAutoPushOff_shouldCommitButNotPush() commitService = new CommitService(gitService, chatModel); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit(anyString())).thenReturn("success"); @@ -203,7 +196,6 @@ void generateAndCommit_withBothEnabled_shouldCommitAndPush() { commitService = new CommitService(gitService, chatModel); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit(anyString())).thenReturn("success"); when(gitService.push()).thenReturn("pushed"); @@ -224,7 +216,6 @@ void generateAndCommit_withBothEnabledButPushFails_shouldStillCommit() { commitService = new CommitService(gitService, chatModel); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit(anyString())).thenReturn("success"); when(gitService.push()).thenThrow(new RuntimeException("Push failed")); @@ -245,7 +236,6 @@ void generateAndCommit_withBothEnabledButAiFails_shouldNotCommitOrPush() { commitService = new CommitService(gitService, chatModel); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(chatModel.call(any(Prompt.class))).thenThrow(new RuntimeException("AI error")); @@ -263,7 +253,6 @@ void generateAndCommit_withAutoPushOnEmptyEditInInteractiveMode_shouldUseOrigina BufferedReader mockReader = new BufferedReader(new StringReader("e\n\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit("feat: original")).thenReturn("success"); when(gitService.push()).thenReturn("pushed"); @@ -285,7 +274,6 @@ void generateAndCommit_withMultipleRegenerationsAndAutoPush_shouldOnlyPushOnce() BufferedReader mockReader = new BufferedReader(new StringReader("r\nr\nr\ny\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn("diff"); when(gitService.commit(anyString())).thenReturn("success"); when(gitService.push()).thenReturn("pushed"); diff --git a/src/test/java/io/github/kxng0109/service/CommitServiceEdgeTest.java b/src/test/java/io/github/kxng0109/service/CommitServiceEdgeTest.java new file mode 100644 index 0000000..7a5f338 --- /dev/null +++ b/src/test/java/io/github/kxng0109/service/CommitServiceEdgeTest.java @@ -0,0 +1,148 @@ +package io.github.kxng0109.service; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.model.Generation; +import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; + +/** + * Guards for commit edge paths in {@link CommitService}. + */ +@ExtendWith(MockitoExtension.class) +@DisplayName("CommitService edges") +public class CommitServiceEdgeTest { + + @Mock + private GitService gitService; + + @Mock + private ChatModel chatModel; + + @Test + @DisplayName("null diff aborts as no staged changes") + void nullDiff_abortsAsNoChanges() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn(null); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No staged changes"); + } + + @Test + @DisplayName("null generation output aborts as empty") + void nullGenerationOutput_abortsAsEmpty() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + Generation generation = mock(Generation.class); + when(generation.getOutput()).thenReturn(null); + when(chatModel.call(any(Prompt.class))).thenReturn(new ChatResponse(List.of(generation))); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no message output"); + } + + @Test + @DisplayName("server error falls back to generic failure") + void serverError_fallsBackToGeneric() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + HttpClientErrorException error = + new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR); + when(chatModel.call(any(Prompt.class))).thenThrow(new RuntimeException("call failed", error)); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Failed to generate a commit message"); + } + + @Test + @DisplayName("direct interrupt aborts and restores flag") + void directInterrupt_abortsAndRestoresFlag() { + ChatModel interrupting = prompt -> { + CommitServiceEdgeTest.sneakyThrow(new InterruptedException("interrupted")); + return null; + }; + CommitService service = new CommitService(gitService, interrupting); + when(gitService.getStagedDiff()).thenReturn("diff"); + + try { + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("interrupted"); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + } finally { + Thread.interrupted(); + } + } + + @Test + @DisplayName("cancel word aborts the edit") + void cancelWord_abortsEdit() { + BufferedReader reader = new BufferedReader(new StringReader("e\ncancel\n")); + CommitService service = new CommitService(gitService, chatModel, reader); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))) + .thenReturn(new ChatResponse(List.of(new Generation(new AssistantMessage("feat: add feature"))))); + + service.generateAndCommit(); + + verify(gitService, never()).commit(anyString()); + } + + @Test + @DisplayName("edit read failure cancels the edit") + void editReadFailure_cancelsEdit() { + Reader flaky = new Reader() { + private int calls; + + @Override + public int read(char[] buffer, int offset, int length) throws IOException { + if (calls++ == 0) { + String line = "e\n"; + line.getChars(0, line.length(), buffer, offset); + return line.length(); + } + throw new IOException("boom"); + } + + @Override + public void close() { + } + }; + CommitService service = + new CommitService(gitService, chatModel, new BufferedReader(flaky)); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))) + .thenReturn(new ChatResponse(List.of(new Generation(new AssistantMessage("feat: add feature"))))); + + service.generateAndCommit(); + + verify(gitService, never()).commit(anyString()); + } + + @SuppressWarnings("unchecked") + private static void sneakyThrow(Throwable throwable) throws T { + throw (T) throwable; + } +} diff --git a/src/test/java/io/github/kxng0109/service/CommitServiceGuardTest.java b/src/test/java/io/github/kxng0109/service/CommitServiceGuardTest.java new file mode 100644 index 0000000..9d461e1 --- /dev/null +++ b/src/test/java/io/github/kxng0109/service/CommitServiceGuardTest.java @@ -0,0 +1,193 @@ +package io.github.kxng0109.service; + +import io.github.kxng0109.config.UserPreferences; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.model.Generation; +import org.springframework.ai.chat.prompt.Prompt; + +/** + * Guards for fail-closed consent and diff policy in {@link CommitService}. + */ +@ExtendWith(MockitoExtension.class) +@DisplayName("CommitService guards") +public class CommitServiceGuardTest { + + @Mock + private GitService gitService; + + @Mock + private ChatModel chatModel; + + @BeforeEach + void setUp() { + UserPreferences.reset(); + } + + @AfterEach + void cleanup() { + UserPreferences.reset(); + } + + @Test + @DisplayName("secret diff aborts before AI call") + void secretDiff_abortsBeforeAiCall() { + CommitService commitService = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("+-----BEGIN PRIVATE KEY-----\n+MIIE"); + + assertThatThrownBy(commitService::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Refusing to send diff"); + + verify(gitService).getStagedDiff(); + verify(chatModel, never()).call(any(Prompt.class)); + verify(gitService, never()).commit(anyString()); + } + + @Test + @DisplayName("oversize diff aborts before AI call") + void oversizeDiff_abortsBeforeAiCall() { + CommitService commitService = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("a".repeat(SecretScanner.MAX_DIFF_BYTES + 1)); + + assertThatThrownBy(commitService::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Refusing to send diff"); + + verify(chatModel, never()).call(any(Prompt.class)); + verify(gitService, never()).commit(anyString()); + } + + @Test + @DisplayName("lockfile diff aborts before AI call") + void lockfileDiff_abortsBeforeAiCall() { + CommitService commitService = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()) + .thenReturn("diff --git a/go.sum b/go.sum\n+++ b/go.sum\n+line"); + + assertThatThrownBy(commitService::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Refusing to send diff"); + + verify(chatModel, never()).call(any(Prompt.class)); + verify(gitService, never()).commit(anyString()); + } + + @Test + @DisplayName("end-of-stream cancels the commit") + void endOfStream_cancelsCommit() { + BufferedReader eofReader = new BufferedReader(new StringReader("")); + CommitService commitService = new CommitService(gitService, chatModel, eofReader); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))).thenReturn(response("feat: add feature")); + + commitService.generateAndCommit(); + + verify(gitService, never()).commit(anyString()); + } + + @Test + @DisplayName("read failure cancels the commit") + void readFailure_cancelsCommit() throws IOException { + Reader failing = new Reader() { + @Override + public int read(char[] buffer, int offset, int length) throws IOException { + throw new IOException("boom"); + } + + @Override + public void close() { + } + }; + CommitService commitService = + new CommitService(gitService, chatModel, new BufferedReader(failing)); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))).thenReturn(response("feat: add feature")); + + commitService.generateAndCommit(); + + verify(gitService, never()).commit(anyString()); + } + + @Test + @DisplayName("full yes word commits") + void yesWord_commits() { + BufferedReader reader = new BufferedReader(new StringReader("yes\n")); + CommitService commitService = new CommitService(gitService, chatModel, reader); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))).thenReturn(response("feat: add feature")); + when(gitService.commit("feat: add feature")).thenReturn("ok"); + + commitService.generateAndCommit(); + + verify(gitService).commit("feat: add feature"); + } + + @Test + @DisplayName("edit cancel aborts without commit") + void editCancel_abortsWithoutCommit() { + BufferedReader reader = new BufferedReader(new StringReader("e\nc\n")); + CommitService commitService = new CommitService(gitService, chatModel, reader); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))).thenReturn(response("feat: add feature")); + + commitService.generateAndCommit(); + + verify(gitService, never()).commit(anyString()); + } + + @Test + @DisplayName("binary diff aborts before AI call") + void binaryDiff_abortsBeforeAiCall() { + CommitService commitService = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff  content \u0000 here"); + + assertThatThrownBy(commitService::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Refusing to send diff"); + + verify(chatModel, never()).call(any(Prompt.class)); + } + + @Test + @DisplayName("abort message carries no secret content") + void abortMessage_carriesNoSecretContent() { + String secret = "AKIAIOSFODNN7EXAMPLE"; + CommitService commitService = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("+" + secret); + + assertThatThrownBy(commitService::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("AWS_ACCESS_KEY"); + + try { + commitService.generateAndCommit(); + } catch (IllegalStateException e) { + assertThat(e.getMessage()).doesNotContain(secret); + } + } + + private ChatResponse response(String text) { + return new ChatResponse(List.of(new Generation(new AssistantMessage(text)))); + } +} diff --git a/src/test/java/io/github/kxng0109/service/CommitServiceReliabilityTest.java b/src/test/java/io/github/kxng0109/service/CommitServiceReliabilityTest.java new file mode 100644 index 0000000..bc52dbf --- /dev/null +++ b/src/test/java/io/github/kxng0109/service/CommitServiceReliabilityTest.java @@ -0,0 +1,166 @@ +package io.github.kxng0109.service; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.model.Generation; +import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; + +/** + * Guards for AI failure mapping in {@link CommitService}. + */ +@ExtendWith(MockitoExtension.class) +@DisplayName("CommitService reliability") +public class CommitServiceReliabilityTest { + + @Mock + private GitService gitService; + + @Mock + private ChatModel chatModel; + + @Test + @DisplayName("unresolvable host maps to actionable error") + void unknownHost_mapsToActionableError() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))) + .thenThrow(new RuntimeException("call failed", new UnknownHostException("ai.example.com"))); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Cannot resolve AI provider host"); + } + + @Test + @DisplayName("socket timeout maps to actionable error") + void socketTimeout_mapsToActionableError() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))) + .thenThrow(new RuntimeException("call failed", new SocketTimeoutException("read timed out"))); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("timed out"); + } + + @Test + @DisplayName("connection refused maps to actionable error") + void connectFailure_mapsToActionableError() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))) + .thenThrow(new RuntimeException("call failed", new ConnectException("refused"))); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Cannot connect to AI provider"); + } + + @Test + @DisplayName("401 maps to api key error") + void unauthorized_mapsToApiKeyError() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + HttpClientErrorException error = new HttpClientErrorException(HttpStatus.UNAUTHORIZED); + when(chatModel.call(any(Prompt.class))).thenThrow(new RuntimeException("call failed", error)); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("401"); + } + + @Test + @DisplayName("429 maps to rate limit error") + void rateLimited_mapsToRateLimitError() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + HttpClientErrorException error = new HttpClientErrorException(HttpStatus.TOO_MANY_REQUESTS); + when(chatModel.call(any(Prompt.class))).thenThrow(new RuntimeException("call failed", error)); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("429"); + } + + @Test + @DisplayName("null response stage maps to empty message error") + void nullResponse_mapsToEmptyError() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))).thenReturn(null); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no response"); + } + + @Test + @DisplayName("null output stage maps to empty message error") + void nullOutput_mapsToEmptyError() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + ChatResponse response = mock(ChatResponse.class); + when(response.getResult()).thenReturn(null); + when(chatModel.call(any(Prompt.class))).thenReturn(response); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no message output"); + } + + @Test + @DisplayName("null text stage maps to empty message error") + void nullText_mapsToEmptyError() { + CommitService service = new CommitService(gitService, chatModel); + when(gitService.getStagedDiff()).thenReturn("diff"); + Generation generation = mock(Generation.class); + when(generation.getOutput()).thenReturn(new AssistantMessage((String) null)); + ChatResponse response = new ChatResponse(List.of(generation)); + when(chatModel.call(any(Prompt.class))).thenReturn(response); + + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("empty"); + } + + @Test + @DisplayName("interrupted cause restores flag and aborts") + void interruptedCause_restoresFlag() { + BufferedReader reader = new BufferedReader(new StringReader("y\n")); + CommitService service = new CommitService(gitService, chatModel, reader); + when(gitService.getStagedDiff()).thenReturn("diff"); + when(chatModel.call(any(Prompt.class))) + .thenThrow(new RuntimeException("call failed", new InterruptedException("interrupted"))); + + try { + assertThatThrownBy(service::generateAndCommit) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("interrupted"); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + } finally { + Thread.interrupted(); + } + } +} diff --git a/src/test/java/io/github/kxng0109/service/CommitServiceTest.java b/src/test/java/io/github/kxng0109/service/CommitServiceTest.java index ef5878f..bb673df 100644 --- a/src/test/java/io/github/kxng0109/service/CommitServiceTest.java +++ b/src/test/java/io/github/kxng0109/service/CommitServiceTest.java @@ -38,7 +38,7 @@ void constructor_shouldCreateService() { @Test void generateAndCommit_withNoStagedChanges_shouldThrowException() { commitService = new CommitService(gitService, chatModel); - when(gitService.hasStagedChanges()).thenReturn(false); + when(gitService.getStagedDiff()).thenReturn(""); IllegalStateException exception = assertThrows( IllegalStateException.class, @@ -46,8 +46,7 @@ void generateAndCommit_withNoStagedChanges_shouldThrowException() { ); assertTrue(exception.getMessage().contains("No staged changes found")); - verify(gitService).hasStagedChanges(); - verify(gitService, never()).getStagedDiff(); + verify(gitService).getStagedDiff(); verify(chatModel, never()).call(any(Prompt.class)); verify(gitService, never()).commit(anyString()); } @@ -61,7 +60,6 @@ void generateAndCommit_withStagedChanges_shouldCommitSuccessfully() { BufferedReader mockReader = new BufferedReader(new StringReader("y\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); when(gitService.commit(aiMessage)).thenReturn(commitOutput); @@ -70,7 +68,6 @@ void generateAndCommit_withStagedChanges_shouldCommitSuccessfully() { commitService.generateAndCommit(); - verify(gitService).hasStagedChanges(); verify(gitService).getStagedDiff(); verify(chatModel).call(any(Prompt.class)); verify(gitService).commit(aiMessage); @@ -81,7 +78,6 @@ void generateAndCommit_withEmptyAiResponse_shouldThrowException() { String diff = "diff --git a/test.txt\n+change"; commitService = new CommitService(gitService, chatModel); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); ChatResponse mockResponse = createMockChatResponse(""); @@ -93,7 +89,6 @@ void generateAndCommit_withEmptyAiResponse_shouldThrowException() { ); assertTrue(exception.getMessage().contains("AI returned an empty commit message")); - verify(gitService).hasStagedChanges(); verify(gitService).getStagedDiff(); verify(chatModel).call(any(Prompt.class)); verify(gitService, never()).commit(anyString()); @@ -104,7 +99,6 @@ void generateAndCommit_withNullAiResponse_shouldThrowException() { String diff = "diff --git a/test.txt\n+change"; commitService = new CommitService(gitService, chatModel); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); ChatResponse mockResponse = createMockChatResponse(null); @@ -124,7 +118,6 @@ void generateAndCommit_withWhitespaceOnlyResponse_shouldThrowException() { String diff = "diff --git a/test.txt\n+change"; commitService = new CommitService(gitService, chatModel); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); ChatResponse mockResponse = createMockChatResponse(" \n\t "); @@ -144,7 +137,6 @@ void generateAndCommit_withAiException_shouldWrapAndThrow() { String diff = "diff --git a/test.txt\n+change"; commitService = new CommitService(gitService, chatModel); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); when(chatModel.call(any(Prompt.class))).thenThrow(new RuntimeException("API error")); @@ -167,7 +159,6 @@ void generateAndCommit_withValidMessageContainingExtraWhitespace_shouldTrimAndCo BufferedReader mockReader = new BufferedReader(new StringReader("y\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); when(gitService.commit(trimmedMessage)).thenReturn(commitOutput); @@ -189,7 +180,6 @@ void generateAndCommit_withUserPressingR_shouldRegenerateMessage() { BufferedReader mockReader = new BufferedReader(new StringReader("r\ny\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); when(gitService.commit(secondMessage)).thenReturn(commitOutput); @@ -201,7 +191,6 @@ void generateAndCommit_withUserPressingR_shouldRegenerateMessage() { commitService.generateAndCommit(); - verify(gitService).hasStagedChanges(); verify(gitService).getStagedDiff(); verify(chatModel, times(2)).call(any(Prompt.class)); verify(gitService).commit(secondMessage); @@ -217,7 +206,6 @@ void generateAndCommit_withUserPressingE_shouldCommitEditedMessage() { BufferedReader mockReader = new BufferedReader(new StringReader("e\n" + editedMessage + "\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); when(gitService.commit(editedMessage)).thenReturn(commitOutput); @@ -226,7 +214,6 @@ void generateAndCommit_withUserPressingE_shouldCommitEditedMessage() { commitService.generateAndCommit(); - verify(gitService).hasStagedChanges(); verify(gitService).getStagedDiff(); verify(chatModel).call(any(Prompt.class)); verify(gitService).commit(editedMessage); @@ -241,7 +228,6 @@ void generateAndCommit_withUserPressingE_andEmptyEdit_shouldUseOriginalMessage() BufferedReader mockReader = new BufferedReader(new StringReader("e\n\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); when(gitService.commit(aiMessage)).thenReturn(commitOutput); @@ -250,7 +236,6 @@ void generateAndCommit_withUserPressingE_andEmptyEdit_shouldUseOriginalMessage() commitService.generateAndCommit(); - verify(gitService).hasStagedChanges(); verify(gitService).getStagedDiff(); verify(chatModel).call(any(Prompt.class)); verify(gitService).commit(aiMessage); @@ -264,7 +249,6 @@ void generateAndCommit_withUserPressingC_shouldCancelCommit() { BufferedReader mockReader = new BufferedReader(new StringReader("c\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); ChatResponse mockResponse = createMockChatResponse(aiMessage); @@ -272,34 +256,29 @@ void generateAndCommit_withUserPressingC_shouldCancelCommit() { commitService.generateAndCommit(); - verify(gitService).hasStagedChanges(); verify(gitService).getStagedDiff(); verify(chatModel).call(any(Prompt.class)); verify(gitService, never()).commit(anyString()); } @Test - void generateAndCommit_withEmptyUserInput_shouldDefaultToYes() { + void generateAndCommit_withEmptyUserInput_shouldCancel() { String diff = "diff --git a/test.txt\n+change"; String aiMessage = "feat: add feature"; - String commitOutput = "[main abc123] feat: add feature"; BufferedReader mockReader = new BufferedReader(new StringReader("\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); - when(gitService.commit(aiMessage)).thenReturn(commitOutput); ChatResponse mockResponse = createMockChatResponse(aiMessage); when(chatModel.call(any(Prompt.class))).thenReturn(mockResponse); commitService.generateAndCommit(); - verify(gitService).hasStagedChanges(); verify(gitService).getStagedDiff(); verify(chatModel).call(any(Prompt.class)); - verify(gitService).commit(aiMessage); + verify(gitService, never()).commit(anyString()); } @Test @@ -311,7 +290,6 @@ void generateAndCommit_withInvalidChoice_thenValidChoice_shouldRetryAndCommit() BufferedReader mockReader = new BufferedReader(new StringReader("x\ny\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); when(gitService.commit(aiMessage)).thenReturn(commitOutput); @@ -320,7 +298,6 @@ void generateAndCommit_withInvalidChoice_thenValidChoice_shouldRetryAndCommit() commitService.generateAndCommit(); - verify(gitService).hasStagedChanges(); verify(gitService).getStagedDiff(); verify(chatModel).call(any(Prompt.class)); verify(gitService).commit(aiMessage); @@ -337,7 +314,6 @@ void generateAndCommit_withMultipleRegenerations_shouldCommitFinalMessage() { BufferedReader mockReader = new BufferedReader(new StringReader("r\nr\ny\n")); commitService = new CommitService(gitService, chatModel, mockReader); - when(gitService.hasStagedChanges()).thenReturn(true); when(gitService.getStagedDiff()).thenReturn(diff); when(gitService.commit(thirdMessage)).thenReturn(commitOutput); @@ -351,7 +327,6 @@ void generateAndCommit_withMultipleRegenerations_shouldCommitFinalMessage() { commitService.generateAndCommit(); - verify(gitService).hasStagedChanges(); verify(gitService).getStagedDiff(); verify(chatModel, times(3)).call(any(Prompt.class)); verify(gitService).commit(thirdMessage); diff --git a/src/test/java/io/github/kxng0109/service/GitServiceEnvTest.java b/src/test/java/io/github/kxng0109/service/GitServiceEnvTest.java new file mode 100644 index 0000000..f838e53 --- /dev/null +++ b/src/test/java/io/github/kxng0109/service/GitServiceEnvTest.java @@ -0,0 +1,46 @@ +package io.github.kxng0109.service; + +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Guards for secret environment scrubbing in {@link GitService}. + */ +@DisplayName("GitService env scrub") +public class GitServiceEnvTest { + + @Test + @DisplayName("secret entries are removed, operational entries kept") + void secrets_areRemovedOperationalKept() { + Map environment = new HashMap<>(); + environment.put("OPENAI_API_KEY", "sk-secret"); + environment.put("ANTHROPIC_API_KEY", "sk-ant-secret"); + environment.put("AI_TEMPERATURE", "0.1"); + environment.put("AI_LOG_LEVEL", "DEBUG"); + environment.put("PATH", "/usr/bin"); + environment.put("GIT_PAGER", "cat"); + + GitService.scrubSecretEnv(environment); + + assertThat(environment) + .doesNotContainKeys("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "AI_TEMPERATURE", "AI_LOG_LEVEL") + .containsKeys("PATH", "GIT_PAGER"); + } + + @Test + @DisplayName("similar but safe names are kept") + void safeNames_areKept() { + Map environment = new HashMap<>(); + environment.put("MY_API_KEYS_BACKUP", "value"); + environment.put("OPENAI_BASE_URL", "https://api.openai.com"); + + GitService.scrubSecretEnv(environment); + + assertThat(environment).containsKeys("MY_API_KEYS_BACKUP", "OPENAI_BASE_URL"); + } +} diff --git a/src/test/java/io/github/kxng0109/service/GitServiceProcessTest.java b/src/test/java/io/github/kxng0109/service/GitServiceProcessTest.java new file mode 100644 index 0000000..2c9c120 --- /dev/null +++ b/src/test/java/io/github/kxng0109/service/GitServiceProcessTest.java @@ -0,0 +1,214 @@ +package io.github.kxng0109.service; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.*; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedConstruction; + +/** + * Guards for process failure paths in {@link GitService}. + */ +@DisplayName("GitService process failures") +public class GitServiceProcessTest { + + @TempDir + Path tempDir; + + @Test + @DisplayName("hung process fails with timeout") + void hungProcess_failsWithTimeout() { + GitService service = new GitService(5, tempDir.toString()); + Process process = mock(Process.class); + when(process.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0])); + when(process.getErrorStream()).thenReturn(new ByteArrayInputStream(new byte[0])); + when(process.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + try { + when(process.waitFor(anyLong(), any(TimeUnit.class))).thenReturn(false); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + when(process.isAlive()).thenReturn(false); + + try (MockedConstruction ignored = mockConstruction(ProcessBuilder.class, + (builder, context) -> { + when(builder.environment()).thenReturn(new HashMap<>()); + try { + when(builder.start()).thenReturn(process); + } catch (IOException e) { + throw new RuntimeException(e); + } + })) { + assertThatThrownBy(() -> invokeRunCommand(service, "git", "diff")) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Timeout waiting"); + } + + verify(process, atLeastOnce()).destroyForcibly(); + } + + @Test + @DisplayName("interrupted wait restores flag and aborts") + void interruptedWait_restoresFlag() { + GitService service = new GitService(5, tempDir.toString()); + Process process = mock(Process.class); + when(process.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0])); + when(process.getErrorStream()).thenReturn(new ByteArrayInputStream(new byte[0])); + when(process.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + try { + when(process.waitFor(anyLong(), any(TimeUnit.class))) + .thenThrow(new InterruptedException("interrupted")); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + try (MockedConstruction ignored = mockConstruction(ProcessBuilder.class, + (builder, context) -> { + when(builder.environment()).thenReturn(new HashMap<>()); + try { + when(builder.start()).thenReturn(process); + } catch (IOException e) { + throw new RuntimeException(e); + } + })) { + try { + assertThatThrownBy(() -> invokeRunCommand(service, "git", "diff")) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("interrupted"); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + } finally { + Thread.interrupted(); + } + } + } + + @Test + @DisplayName("oversize output aborts with truncation error") + void oversizeOutput_aborts() { + GitService service = new GitService(5, tempDir.toString()); + Process process = mock(Process.class); + when(process.getInputStream()) + .thenReturn(new ByteArrayInputStream(new byte[SecretScanner.MAX_DIFF_BYTES + 1024])); + when(process.getErrorStream()).thenReturn(new ByteArrayInputStream(new byte[0])); + try { + when(process.waitFor(anyLong(), any(TimeUnit.class))).thenReturn(true); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + when(process.exitValue()).thenReturn(0); + + try (MockedConstruction ignored = mockConstruction(ProcessBuilder.class, + (builder, context) -> { + when(builder.environment()).thenReturn(new HashMap<>()); + try { + when(builder.start()).thenReturn(process); + } catch (IOException e) { + throw new RuntimeException(e); + } + })) { + assertThatThrownBy(() -> invokeRunCommand(service, "git", "diff")) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("exceeded"); + } + } + + @Test + @DisplayName("missing binary maps to actionable error") + void missingBinary_mapsToActionableError() { + GitService service = new GitService(5, tempDir.toString()); + + assertThatThrownBy(() -> invokeRunCommand(service, "no-such-binary-xyz-123")) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Failed to start"); + } + + @Test + @DisplayName("failing stream is swallowed by drain") + void failingStream_swallowedByDrain() throws Exception { + Method drain = GitService.class.getDeclaredMethod( + "drainBounded", InputStream.class, StringBuilder.class, AtomicBoolean.class); + drain.setAccessible(true); + InputStream failing = mock(InputStream.class); + when(failing.readNBytes(anyInt())).thenThrow(new IOException("boom")); + + StringBuilder target = new StringBuilder(); + AtomicBoolean truncated = new AtomicBoolean(false); + + drain.invoke(null, failing, target, truncated); + + assertThat(target).isEmpty(); + assertThat(truncated.get()).isFalse(); + } + + @Test + @DisplayName("close helper tolerates null and failures") + void closeHelper_toleratesNullAndFailures() throws Exception { + Method close = GitService.class.getDeclaredMethod("closeQuietly", Closeable.class); + close.setAccessible(true); + + close.invoke(null, (Closeable) null); + + Closeable failing = mock(Closeable.class); + doThrow(new IOException("boom")).when(failing).close(); + close.invoke(null, failing); + } + + @Test + @DisplayName("command description covers arities") + void description_coversArities() throws Exception { + Method describe = GitService.class.getDeclaredMethod("describeCommand", String[].class); + describe.setAccessible(true); + + assertThat(describe.invoke(null, (Object) new String[]{"git", "commit"})).isEqualTo("git commit"); + assertThat(describe.invoke(null, (Object) new String[]{"git"})).isEqualTo("git"); + assertThat(describe.invoke(null, (Object) new String[0])).isEqualTo("git"); + } + + @Test + @DisplayName("truncate covers null and overflow") + void truncate_coversNullAndOverflow() throws Exception { + Method truncate = GitService.class.getDeclaredMethod("truncate", String.class, int.class); + truncate.setAccessible(true); + + assertThat(truncate.invoke(null, null, 5)).isEqualTo(""); + assertThat(truncate.invoke(null, "abc", 5)).isEqualTo("abc"); + assertThat((String) truncate.invoke(null, "abcdef", 5)).startsWith("abcde"); + } + + private static void invokeRunCommand(GitService service, String... command) { + try { + Method runCommand = GitService.class.getDeclaredMethod("runCommand", String[].class); + runCommand.setAccessible(true); + runCommand.invoke(service, (Object) command); + } catch (InvocationTargetException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException runtime) { + throw runtime; + } + if (cause instanceof Error error) { + throw error; + } + throw new RuntimeException(cause); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/io/github/kxng0109/service/GitServiceTest.java b/src/test/java/io/github/kxng0109/service/GitServiceTest.java index 85cf5f2..22a67a2 100644 --- a/src/test/java/io/github/kxng0109/service/GitServiceTest.java +++ b/src/test/java/io/github/kxng0109/service/GitServiceTest.java @@ -35,15 +35,14 @@ void constructor_shouldCreateServiceWithTimeout() { } @Test - void hasStagedChanges_inNonGitDirectory_shouldReturnFalse() throws IOException { + void hasStagedChanges_inNonGitDirectory_shouldThrow() throws IOException { Path nonGitDir = Files.createTempDirectory("non-git-test"); try { gitService = new GitService(5, nonGitDir.toString()); - boolean result = gitService.hasStagedChanges(); - - assertFalse(result, "Should return false for non-git directory"); + assertThrows(RuntimeException.class, () -> gitService.hasStagedChanges(), + "Fatal git failures must propagate, not masquerade as no changes"); } finally { deleteDirectoryWithRetry(nonGitDir); } diff --git a/src/test/java/io/github/kxng0109/service/GitServiceValidationTest.java b/src/test/java/io/github/kxng0109/service/GitServiceValidationTest.java new file mode 100644 index 0000000..53d7e56 --- /dev/null +++ b/src/test/java/io/github/kxng0109/service/GitServiceValidationTest.java @@ -0,0 +1,81 @@ +package io.github.kxng0109.service; + +import java.nio.file.Path; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Guards for fail-fast validation in {@link GitService}. + */ +@DisplayName("GitService validation") +public class GitServiceValidationTest { + + @TempDir + Path tempDir; + + @Test + @DisplayName("timeout below range is rejected") + void timeoutBelowRange_isRejected() { + assertThatThrownBy(() -> new GitService(0, tempDir.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("1 and 3599"); + } + + @Test + @DisplayName("timeout above range is rejected") + void timeoutAboveRange_isRejected() { + assertThatThrownBy(() -> new GitService(3600, tempDir.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("1 and 3599"); + } + + @Test + @DisplayName("blank working directory is rejected") + void blankDirectory_isRejected() { + assertThatThrownBy(() -> new GitService(5, " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("blank"); + } + + @Test + @DisplayName("missing working directory is rejected") + void missingDirectory_isRejected() { + Path missing = tempDir.resolve("does-not-exist"); + + assertThatThrownBy(() -> new GitService(5, missing.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("readable directory"); + } + + @Test + @DisplayName("null commit message is rejected before git") + void nullCommitMessage_isRejected() { + GitService service = new GitService(5, tempDir.toString()); + + assertThatThrownBy(() -> service.commit(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("blank"); + } + + @Test + @DisplayName("blank commit message is rejected before git") + void blankCommitMessage_isRejected() { + GitService service = new GitService(5, tempDir.toString()); + + assertThatThrownBy(() -> service.commit(" ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("blank"); + } + + @Test + @DisplayName("boundary timeouts are accepted") + void boundaryTimeouts_areAccepted() { + assertThat(new GitService(1, tempDir.toString())).isNotNull(); + assertThat(new GitService(3599, tempDir.toString())).isNotNull(); + } +} diff --git a/src/test/java/io/github/kxng0109/service/GitServiceWorkingDirTest.java b/src/test/java/io/github/kxng0109/service/GitServiceWorkingDirTest.java new file mode 100644 index 0000000..590c6ca --- /dev/null +++ b/src/test/java/io/github/kxng0109/service/GitServiceWorkingDirTest.java @@ -0,0 +1,74 @@ +package io.github.kxng0109.service; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Guards for working-directory resolution in {@link GitService}. + */ +@DisplayName("GitService working directory") +public class GitServiceWorkingDirTest { + + @TempDir + Path tempDir; + + @Test + @DisplayName("valid user dir wins over pwd") + void validUserDir_wins() throws Exception { + String resolved = GitService.resolveWorkingDirectory(tempDir.toString(), tempDir.toString(), null); + + assertThat(Path.of(resolved)).isEqualTo(tempDir.toRealPath()); + } + + @Test + @DisplayName("pwd is used when user dir is unusable") + void pwd_usedWhenUserDirUnusable() throws Exception { + String resolved = GitService.resolveWorkingDirectory( + tempDir.resolve("missing").toString(), tempDir.toString(), null); + + assertThat(Path.of(resolved)).isEqualTo(tempDir.toRealPath()); + } + + @Test + @DisplayName("fallback is used when user dir and pwd are blank") + void fallback_usedWhenOthersBlank() throws Exception { + String resolved = GitService.resolveWorkingDirectory(" ", null, tempDir.toString()); + + assertThat(Path.of(resolved)).isEqualTo(tempDir.toRealPath()); + } + + @Test + @DisplayName("all-invalid candidates throw") + void allInvalid_throw() { + assertThatThrownBy(() -> GitService.resolveWorkingDirectory( + tempDir.resolve("missing").toString(), + tempDir.resolve("also-missing").toString(), + tempDir.resolve("nope").toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("usable working directory"); + } + + @Test + @DisplayName("null fallback throws") + void nullFallback_throws() { + assertThatThrownBy(() -> GitService.resolveWorkingDirectory(null, null, null)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + @DisplayName("file path is rejected as working directory") + void filePath_rejected() throws Exception { + Path file = Files.createFile(tempDir.resolve("note.txt")); + + assertThatThrownBy(() -> new GitService(5, file.toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("readable directory"); + } +} diff --git a/src/test/java/io/github/kxng0109/service/SecretScannerTest.java b/src/test/java/io/github/kxng0109/service/SecretScannerTest.java new file mode 100644 index 0000000..8b7043b --- /dev/null +++ b/src/test/java/io/github/kxng0109/service/SecretScannerTest.java @@ -0,0 +1,186 @@ +package io.github.kxng0109.service; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * Guards for {@link SecretScanner} redaction and size policy. + */ +@DisplayName("SecretScanner") +public class SecretScannerTest { + + @Test + @DisplayName("clean diff returns no findings") + void cleanDiff_returnsNoFindings() { + String diff = "diff --git a/App.java b/App.java\n+fix: correct null handling"; + + assertThat(SecretScanner.scan(diff)).isEmpty(); + } + + @Test + @DisplayName("null diff is rejected") + @SuppressWarnings("DataFlowIssue") + void nullDiff_isRejected() { + assertThatThrownBy(() -> SecretScanner.scan(null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + @DisplayName("private key block is detected") + void privateKey_isDetected() { + String diff = "+-----BEGIN PRIVATE KEY-----\n+MIIEvwIBADANBgkqhkiG9w0BAQEFAASC"; + + List findings = SecretScanner.scan(diff); + + assertThat(findings).extracting(SecretScanner.Finding::ruleId).contains("PRIVATE_KEY"); + } + + @Test + @DisplayName("aws access key is detected") + void awsAccessKey_isDetected() { + String diff = "+AKIAIOSFODNN7EXAMPLE"; + + assertThat(SecretScanner.scan(diff)) + .extracting(SecretScanner.Finding::ruleId) + .contains("AWS_ACCESS_KEY"); + } + + @Test + @DisplayName("github token is detected") + void githubToken_isDetected() { + String diff = "+ghp_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + + assertThat(SecretScanner.scan(diff)) + .extracting(SecretScanner.Finding::ruleId) + .contains("GITHUB_TOKEN"); + } + + @Test + @DisplayName("api key is detected") + void apiKey_isDetected() { + String diff = "+sk-test-abcdefghijklmnopqrst"; + + assertThat(SecretScanner.scan(diff)) + .extracting(SecretScanner.Finding::ruleId) + .contains("API_KEY"); + } + + @Test + @DisplayName("jwt is detected") + void jwt_isDetected() { + String diff = "+eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.SflKxwRJ"; + + assertThat(SecretScanner.scan(diff)) + .extracting(SecretScanner.Finding::ruleId) + .contains("JWT"); + } + + @Test + @DisplayName("bearer token is detected") + void bearerToken_isDetected() { + String diff = "+Authorization: Bearer abcdefghijklmnopqrstuvwx"; + + assertThat(SecretScanner.scan(diff)) + .extracting(SecretScanner.Finding::ruleId) + .contains("BEARER_TOKEN"); + } + + @Test + @DisplayName("credential assignment is detected") + void credentialAssignment_isDetected() { + String diff = "+password = hunter2secretvalue"; + + assertThat(SecretScanner.scan(diff)) + .extracting(SecretScanner.Finding::ruleId) + .contains("CREDENTIAL_ASSIGNMENT"); + } + + @Test + @DisplayName("credentialed connection string is detected") + void connectionString_isDetected() { + String diff = "+postgres://appuser:pass123word@db.internal:5432/app"; + + assertThat(SecretScanner.scan(diff)) + .extracting(SecretScanner.Finding::ruleId) + .contains("CONNECTION_STRING"); + } + + @Test + @DisplayName("binary content is detected") + void binaryContent_isDetected() { + String diff = "diff --git a/logo.png b/logo.png\n binary content \u0000 here"; + + assertThat(SecretScanner.scan(diff)) + .extracting(SecretScanner.Finding::ruleId) + .contains("BINARY"); + } + + @Test + @DisplayName("generated lockfile is detected") + void lockfile_isDetected() { + String diff = "diff --git a/package-lock.json b/package-lock.json\n+++ b/package-lock.json\n+{}"; + + assertThat(SecretScanner.scan(diff)) + .extracting(SecretScanner.Finding::ruleId) + .contains("LOCKFILE"); + } + + @Test + @DisplayName("oversize diff is blocked") + void oversizeDiff_isBlocked() { + String diff = "a".repeat(SecretScanner.MAX_DIFF_BYTES + 1); + + List findings = SecretScanner.scan(diff); + + assertThat(findings).extracting(SecretScanner.Finding::ruleId).containsExactly("OVERSIZE"); + } + + @Test + @DisplayName("summary never contains secret content") + void summary_neverContainsSecretContent() { + String secret = "AKIAIOSFODNN7EXAMPLE"; + List findings = SecretScanner.scan("+" + secret); + + String summary = SecretScanner.summarize(findings); + + assertThat(summary).contains("AWS_ACCESS_KEY"); + assertThat(summary).doesNotContain(secret); + } + + @Test + @DisplayName("summary separates multiple findings") + void summary_separatesMultipleFindings() { + List findings = SecretScanner.scan( + "+AKIAIOSFODNN7EXAMPLE\n+ghp_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + + String summary = SecretScanner.summarize(findings); + + assertThat(summary).contains("AWS_ACCESS_KEY").contains("GITHUB_TOKEN").contains("; "); + } + + @Test + @DisplayName("findings list is unmodifiable") + void findings_areUnmodifiable() { + List findings = SecretScanner.scan("clean"); + + assertThatThrownBy(() -> findings.add(new SecretScanner.Finding("X", "y", 1, "fp"))) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + @DisplayName("utility constructor is guarded") + void constructor_isGuarded() { + assertThatThrownBy(() -> { + var constructor = SecretScanner.class.getDeclaredConstructor(); + constructor.setAccessible(true); + constructor.newInstance(); + }).isInstanceOf(InvocationTargetException.class) + .hasCauseInstanceOf(UnsupportedOperationException.class); + } +}