diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..1017ee3 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 + +[*.go] +indent_style = tab + +[Makefile] +indent_style = tab diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..7f0b543 --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +ATTACKPATH_VISUALIZER_UI= +ATTACKPATH_VISUALIZER_DB= diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..68236f6 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +*.go text eol=lf +*.mod text eol=lf +*.sum text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.txt text eol=lf +*.md text eol=lf diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..ef108f9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,15 @@ +--- +name: Bug report +description: Report a reproducible issue using synthetic or sanitized data +labels: bug +--- + +## Expected behavior + +## Actual behavior + +## Reproduction steps + +## OS and application version + +Do not include credentials, personal data, or production inventories. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..e05a9af --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,11 @@ +--- +name: Feature request +description: Suggest a focused product improvement +labels: enhancement +--- + +## Problem to solve + +## Proposed behavior + +## Alternatives considered diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..47fbc07 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,13 @@ +## Summary + +## Verification evidence +- CI per OS: +- Screenshot artifact: +- What is unverified: + +## Security and data impact + +## Checklist +- [ ] Tests and docs updated +- [ ] No sensitive real-world data included +- [ ] No unsupported platform or security claims diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml new file mode 100644 index 0000000..febedcd --- /dev/null +++ b/.github/workflows/beta-release.yml @@ -0,0 +1,215 @@ +name: Beta release +on: + push: + tags: ["v*"] +permissions: + contents: read +jobs: + package: + name: package (${{ matrix.platform }}) + strategy: + fail-fast: false + matrix: + include: + - runner: ubuntu-latest + platform: linux-x64 + target: linux + - runner: macos-latest + platform: macos-arm64 + target: darwin + - runner: windows-latest + platform: windows-x64 + target: windows + runs-on: ${{ matrix.runner }} + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + - name: Install Linux GUI build prerequisites + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y bc gcc libgl1-mesa-dev libwayland-dev libx11-dev libxkbcommon-dev xorg-dev xvfb language-pack-en + - name: Install Windows C compiler + if: runner.os == 'Windows' + uses: msys2/setup-msys2@v2 + with: + msystem: MINGW64 + install: mingw-w64-x86_64-gcc + update: true + - name: Verify native runner architecture + if: matrix.target == 'darwin' + run: test "$(uname -m)" = "arm64" + - name: Run tests and static analysis before packaging + shell: bash + run: | + set -euo pipefail + go test ./... + go vet ./... + - name: Collect dependency license texts + shell: bash + run: | + set -euo pipefail + license_output=third-party-license-output + test ! -e "$license_output" + if ! go run github.com/google/go-licenses@v1.6.0 save --ignore=modernc.org/mathutil --save_path "$license_output" ./cmd/attackpath-visualizer > license-save.log 2>&1; then + diagnostics=$(tail -n 80 license-save.log) + diagnostics=${diagnostics//'%'/'%25'} + diagnostics=${diagnostics//$'\r'/'%0D'} + diagnostics=${diagnostics//$'\n'/'%0A'} + printf '::error title=go-licenses save::%s\n' "$diagnostics" + exit 1 + fi + cat license-save.log + rm license-save.log + mkdir -p assets/licenses + cp LICENSE assets/licenses/AttackPath-Visualizer-MIT.txt + test -s assets/licenses/modernc-mathutil-BSD-3-Clause.txt + if ! cp -R "$license_output"/. assets/licenses/; then + echo '::error title=license bundle::Failed to copy generated license texts into assets/licenses.' + exit 1 + fi + cp THIRD_PARTY_NOTICES.md assets/docs/THIRD_PARTY_NOTICES.md + - name: Build GUI package and bundle required files + shell: bash + run: | + set -Eeuo pipefail + report_packaging_failure() { + status=$? + command=$BASH_COMMAND + line=${BASH_LINENO[0]:-unknown} + trap - ERR + printf 'Packaging failed (exit %s) at line %s: %s\n' "$status" "$line" "$command" >> "$GITHUB_STEP_SUMMARY" + annotation=$command + annotation=${annotation//'%'/'%25'} + annotation=${annotation//$'\r'/'%0D'} + annotation=${annotation//$'\n'/'%0A'} + printf '::error title=Packaging command failed::exit %s at line %s: %s\n' "$status" "$line" "$annotation" + exit "$status" + } + trap report_packaging_failure ERR + test -s assets/icons/icon.png + mkdir -p release-output + if ! (cd cmd/attackpath-visualizer && go run fyne.io/tools/cmd/fyne@v1.7.4 package --target "${{ matrix.target }}" --release) > fyne-package.log 2>&1; then + cat fyne-package.log + { + echo '## Fyne package failure' + echo '```text' + tail -n 100 fyne-package.log + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + diagnostics=$(tail -n 80 fyne-package.log) + diagnostics=${diagnostics//'%'/'%25'} + diagnostics=${diagnostics//$'\r'/'%0D'} + diagnostics=${diagnostics//$'\n'/'%0A'} + printf '::error title=Fyne package (%s)::%s\n' "${{ matrix.platform }}" "$diagnostics" + exit 1 + fi + cat fyne-package.log + case "${{ matrix.target }}" in + windows) + exe="cmd/attackpath-visualizer/AttackPath Visualizer.exe" + test -s "$exe" + mkdir -p release-output/windows-bundle/licenses release-output/windows-bundle/docs + cp "$exe" release-output/windows-bundle/ + cp README.md LICENSE THIRD_PARTY_NOTICES.md release-output/windows-bundle/ + cp docs/USAGE.md docs/LICENSES.md release-output/windows-bundle/docs/ + cp -R assets/licenses/. release-output/windows-bundle/licenses/ + test -s release-output/windows-bundle/LICENSE + test -s release-output/windows-bundle/THIRD_PARTY_NOTICES.md + test -n "$(find release-output/windows-bundle/licenses -type f -print -quit)" + if ! pwsh -NoProfile -Command '$ErrorActionPreference = "Stop"; Add-Type -AssemblyName System.Drawing; $icon = [System.Drawing.Icon]::ExtractAssociatedIcon("release-output/windows-bundle/AttackPath Visualizer.exe"); if ($null -eq $icon) { throw "No executable icon resource was found" }; $stream = [System.IO.File]::Create("release-output/windows-icon-check.ico"); try { $icon.Save($stream) } finally { $stream.Dispose() }; if ((Get-Item "release-output/windows-icon-check.ico").Length -lt 100) { throw "Extracted application icon is unexpectedly small" }' > windows-icon-check.log 2>&1; then + cat windows-icon-check.log + diagnostics=$(tail -n 80 windows-icon-check.log) + diagnostics=${diagnostics//'%'/'%25'} + diagnostics=${diagnostics//$'\r'/'%0D'} + diagnostics=${diagnostics//$'\n'/'%0A'} + printf '::error title=Windows executable icon verification::%s\n' "$diagnostics" + exit 1 + fi + cat windows-icon-check.log + pwsh -NoProfile -Command "Compress-Archive -Path 'release-output/windows-bundle/*' -DestinationPath 'release-output/attackpath-visualizer-windows-x64.zip' -Force" + test -s release-output/attackpath-visualizer-windows-x64.zip + ;; + darwin) + app="cmd/attackpath-visualizer/AttackPath Visualizer.app" + test -s "$app/Contents/Info.plist" + icon=$(find "$app/Contents/Resources" -type f -iname '*.icns' -print -quit) + test -n "$icon" + mkdir -p release-output/macos-bundle/licenses release-output/macos-bundle/docs + cp -R "$app" release-output/macos-bundle/ + cp README.md LICENSE THIRD_PARTY_NOTICES.md release-output/macos-bundle/ + cp docs/USAGE.md docs/LICENSES.md release-output/macos-bundle/docs/ + cp -R assets/licenses/. release-output/macos-bundle/licenses/ + test -s release-output/macos-bundle/LICENSE + test -s release-output/macos-bundle/THIRD_PARTY_NOTICES.md + test -n "$(find release-output/macos-bundle/licenses -type f -print -quit)" + tar -czf release-output/attackpath-visualizer-macos-arm64.tar.gz -C release-output/macos-bundle . + test -s release-output/attackpath-visualizer-macos-arm64.tar.gz + ;; + linux) + app_archive='cmd/attackpath-visualizer/AttackPath Visualizer.tar.xz' + test -s "$app_archive" + mkdir -p release-output/linux-bundle/licenses release-output/linux-bundle/docs + tar -xJf "$app_archive" -C release-output/linux-bundle + cp README.md LICENSE THIRD_PARTY_NOTICES.md release-output/linux-bundle/ + cp docs/USAGE.md docs/LICENSES.md release-output/linux-bundle/docs/ + cp -R assets/licenses/. release-output/linux-bundle/licenses/ + test -s release-output/linux-bundle/LICENSE + test -s release-output/linux-bundle/THIRD_PARTY_NOTICES.md + test -n "$(find release-output/linux-bundle/licenses -type f -print -quit)" + icon=$(find release-output/linux-bundle -type f \( -iname '*.png' -o -iname '*.svg' \) -print -quit) + test -n "$icon" + tar -czf release-output/attackpath-visualizer-linux-x64.tar.gz -C release-output/linux-bundle . + test -s release-output/attackpath-visualizer-linux-x64.tar.gz + ;; + esac + - uses: actions/upload-artifact@v4 + with: + name: beta-package-${{ matrix.platform }} + path: release-output/attackpath-visualizer-* + if-no-files-found: error + publish: + name: publish public pre-release + needs: package + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/download-artifact@v4 + with: + pattern: beta-package-* + path: dist + merge-multiple: true + - name: Verify tag, packages, checksums, and existing release state + shell: bash + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + set -euo pipefail + tag="$GITHUB_REF_NAME" + tagged_commit=$(git rev-parse "${GITHUB_REF}^{commit}") + test "$tagged_commit" = "$GITHUB_SHA" + if gh release view "$tag" --repo "$GH_REPO" >/dev/null 2>&1; then + echo "::error::Refusing to overwrite existing release $tag" + exit 1 + fi + test -s dist/attackpath-visualizer-linux-x64.tar.gz + test -s dist/attackpath-visualizer-macos-arm64.tar.gz + test -s dist/attackpath-visualizer-windows-x64.zip + (cd dist && sha256sum attackpath-visualizer-linux-x64.tar.gz attackpath-visualizer-macos-arm64.tar.gz attackpath-visualizer-windows-x64.zip > SHA256SUMS) + (cd dist && sha256sum --check SHA256SUMS) + cat dist/SHA256SUMS + - name: Create public pre-release without overwriting + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: gh release create "$GITHUB_REF_NAME" dist/attackpath-visualizer-linux-x64.tar.gz dist/attackpath-visualizer-macos-arm64.tar.gz dist/attackpath-visualizer-windows-x64.zip dist/SHA256SUMS --prerelease --title "AttackPath Visualizer v0.1.0-dev (dev beta)" --notes-file docs/RELEASE_NOTES.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5bc3ce5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,110 @@ +name: CI +on: + push: + branches: [main, "arena/65bc6e5a-attackpath-visualizer"] + pull_request: +permissions: + contents: read +jobs: + checks: + name: checks (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.27.3' + cache: true + - name: Install GUI build prerequisites from Fyne CI documentation + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y bc gcc libgl1-mesa-dev libwayland-dev libx11-dev libxkbcommon-dev xorg-dev xvfb language-pack-en + - name: Install Windows C compiler + if: runner.os == 'Windows' + uses: msys2/setup-msys2@v2 + with: + msystem: MINGW64 + install: mingw-w64-x86_64-gcc + update: true + - name: Verify module metadata + run: go mod tidy -diff + - name: Resolve module checksums + run: go mod download all + - name: Verify downloaded modules + run: go mod verify + - name: Verify formatting + shell: bash + run: | + files=$(gofmt -l $(git ls-files '*.go')) + if [ -n "$files" ]; then + echo "::error title=Go formatting::Unformatted files: $files" + exit 1 + fi + - name: Static analysis + shell: bash + run: | + set +e + go vet ./... > /tmp/go-vet.log 2>&1 + status=$? + cat /tmp/go-vet.log + if [ "$status" -ne 0 ]; then + while IFS= read -r line; do printf '::error::%s\n' "$line"; done < /tmp/go-vet.log + exit "$status" + fi + - name: Unit and integration tests + shell: bash + run: | + set +e + go test ./... > /tmp/go-test.log 2>&1 + status=$? + cat /tmp/go-test.log + if [ "$status" -ne 0 ]; then + awk '/^--- FAIL:/ { remaining=12 } /^FAIL[[:space:]]/ { print; next } remaining > 0 { print; remaining-- }' /tmp/go-test.log > /tmp/go-test-diagnostics.log + if [ ! -s /tmp/go-test-diagnostics.log ]; then tail -n 20 /tmp/go-test.log > /tmp/go-test-diagnostics.log; fi + while IFS= read -r line; do printf '::error::%s\n' "$line"; done < /tmp/go-test-diagnostics.log + exit "$status" + fi + - name: Build CLI-only and native GUI variants + shell: bash + run: go build -tags nogui ./... && go build ./... + - name: Render all dashboard screens with software renderer + if: runner.os == 'Linux' + run: go run ./cmd/render-screenshots -out artifacts/ui + - name: Upload screenshot evidence + if: runner.os == 'Linux' + uses: actions/upload-artifact@v4 + with: + name: attackpath-visualizer-ui-screenshots + path: artifacts/ui/*.png + if-no-files-found: error + - name: Dependency vulnerability scan + if: runner.os == 'Linux' + shell: bash + run: | + go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 + "$(go env GOPATH)/bin/govulncheck" ./... || { echo "::error title=govulncheck::Dependency vulnerability scan failed"; exit 1; } + race: + name: race detector (Linux) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.27.3' + - name: Install GUI build prerequisites from Fyne CI documentation + run: sudo apt-get update && sudo apt-get install -y bc gcc libgl1-mesa-dev libwayland-dev libx11-dev libxkbcommon-dev xorg-dev xvfb language-pack-en + - run: go mod download all + - name: Race-enabled tests + shell: bash + run: | + set +e + go test -race ./... > /tmp/go-race.log 2>&1 + status=$? + cat /tmp/go-race.log + if [ "$status" -ne 0 ]; then + while IFS= read -r line; do printf '::error::%s\n' "$line"; done < /tmp/go-race.log + exit "$status" + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..1afd40f --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,145 @@ +name: Release packages +on: + workflow_dispatch: +permissions: + contents: read +jobs: + package: + name: package (${{ matrix.platform }}) + permissions: + contents: read + strategy: + fail-fast: false + matrix: + include: + - runner: windows-latest + platform: windows-x64 + target: windows + - runner: macos-latest + platform: macos-arm64 + target: darwin + - runner: ubuntu-latest + platform: linux-x64 + target: linux + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + - name: Install Linux GUI build prerequisites + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y bc gcc libgl1-mesa-dev libwayland-dev libx11-dev libxkbcommon-dev xorg-dev xvfb language-pack-en + - name: Install Windows C compiler + if: runner.os == 'Windows' + uses: msys2/setup-msys2@v2 + with: + msystem: MINGW64 + install: mingw-w64-x86_64-gcc + update: true + - name: Verify native runner architecture + if: matrix.target == 'darwin' + run: test "$(uname -m)" = "arm64" + - name: Collect build dependency licenses + shell: bash + run: | + license_output=third-party-license-output + test ! -e "$license_output" + if ! go run github.com/google/go-licenses@v1.6.0 save --ignore=modernc.org/mathutil --save_path "$license_output" ./cmd/attackpath-visualizer > license-save.log 2>&1; then + diagnostics=$(tail -n 80 license-save.log) + diagnostics=${diagnostics//'%'/'%25'} + diagnostics=${diagnostics//$'\r'/'%0D'} + diagnostics=${diagnostics//$'\n'/'%0A'} + printf '::error title=go-licenses save::%s\n' "$diagnostics" + exit 1 + fi + cat license-save.log + rm license-save.log + mkdir -p assets/licenses + cp LICENSE assets/licenses/AttackPath-Visualizer-MIT.txt + test -s assets/licenses/modernc-mathutil-BSD-3-Clause.txt + if ! cp -R "$license_output"/. assets/licenses/; then + echo '::error title=license bundle::Failed to copy generated license texts into assets/licenses.' + exit 1 + fi + cp THIRD_PARTY_NOTICES.md assets/docs/THIRD_PARTY_NOTICES.md + - name: Build release packages + shell: bash + run: | + set -euo pipefail + mkdir -p release-output + if [ "${{ matrix.target }}" = "windows" ]; then + go build -tags nogui -o "release-output/attackpath-visualizer-cli-${{ matrix.platform }}.exe" ./cmd/attackpath-visualizer + else + go build -tags nogui -o "release-output/attackpath-visualizer-cli-${{ matrix.platform }}" ./cmd/attackpath-visualizer + fi + (cd cmd/attackpath-visualizer && go run fyne.io/tools/cmd/fyne@v1.7.4 package --target "${{ matrix.target }}" --release) + mkdir -p release-output/cli-bundle/licenses release-output/cli-bundle/docs + cli_name="attackpath-visualizer-cli-${{ matrix.platform }}" + if [ "${{ matrix.target }}" = "windows" ]; then cli_name="${cli_name}.exe"; fi + cp "release-output/${cli_name}" release-output/cli-bundle/ + cp README.md LICENSE THIRD_PARTY_NOTICES.md release-output/cli-bundle/ + cp docs/USAGE.md docs/LICENSES.md release-output/cli-bundle/docs/ + cp -R assets/licenses/. release-output/cli-bundle/licenses/ + if [ "${{ matrix.target }}" = "windows" ]; then + cp "cmd/attackpath-visualizer/AttackPath Visualizer.exe" release-output/attackpath-visualizer-windows-x64.exe + mkdir -p release-output/windows-bundle/licenses release-output/windows-bundle/docs + cp release-output/attackpath-visualizer-windows-x64.exe release-output/windows-bundle/ + cp README.md LICENSE THIRD_PARTY_NOTICES.md release-output/windows-bundle/ + cp docs/USAGE.md docs/LICENSES.md release-output/windows-bundle/docs/ + cp -R assets/licenses/. release-output/windows-bundle/licenses/ + pwsh -NoProfile -Command '$ErrorActionPreference = "Stop"; Add-Type -AssemblyName System.Drawing; $icon = [System.Drawing.Icon]::ExtractAssociatedIcon("release-output/windows-bundle/AttackPath Visualizer.exe"); if ($null -eq $icon) { throw "No executable icon resource was found" }; $stream = [System.IO.File]::Create("release-output/windows-icon-check.ico"); try { $icon.Save($stream) } finally { $stream.Dispose() }; if ((Get-Item "release-output/windows-icon-check.ico").Length -lt 100) { throw "Extracted application icon is unexpectedly small" }' + powershell -NoProfile -Command "Compress-Archive -Path 'release-output/cli-bundle/*' -DestinationPath 'release-output/attackpath-visualizer-cli-windows-x64.zip' -Force" + powershell -NoProfile -Command "Compress-Archive -Path 'release-output/windows-bundle/*' -DestinationPath 'release-output/attackpath-visualizer-windows-x64.zip' -Force" + elif [ "${{ matrix.target }}" = "darwin" ]; then + mkdir -p release-output/macos-bundle/licenses release-output/macos-bundle/docs + cp -R "cmd/attackpath-visualizer/AttackPath Visualizer.app" release-output/macos-bundle/ + cp README.md LICENSE THIRD_PARTY_NOTICES.md release-output/macos-bundle/ + cp docs/USAGE.md docs/LICENSES.md release-output/macos-bundle/docs/ + cp -R assets/licenses/. release-output/macos-bundle/licenses/ + tar -czf release-output/attackpath-visualizer-macos-arm64.tar.gz -C release-output/macos-bundle . + tar -czf release-output/attackpath-visualizer-cli-macos-arm64.tar.gz -C release-output/cli-bundle . + else + mkdir -p release-output/linux-bundle/licenses release-output/linux-bundle/docs + tar -xJf 'cmd/attackpath-visualizer/AttackPath Visualizer.tar.xz' -C release-output/linux-bundle + cp README.md LICENSE THIRD_PARTY_NOTICES.md release-output/linux-bundle/ + cp docs/USAGE.md docs/LICENSES.md release-output/linux-bundle/docs/ + cp -R assets/licenses/. release-output/linux-bundle/licenses/ + tar -czf release-output/attackpath-visualizer-linux-x64.tar.gz -C release-output/linux-bundle . + tar -czf release-output/attackpath-visualizer-cli-linux-x64.tar.gz -C release-output/cli-bundle . + fi + rm -rf release-output/cli-bundle release-output/windows-bundle release-output/macos-bundle release-output/linux-bundle + rm -f "release-output/${cli_name}" + - name: Upload platform packages for review + uses: actions/upload-artifact@v4 + with: + name: attackpath-visualizer-release-${{ matrix.platform }} + path: release-output/* + if-no-files-found: error + draft-release: + name: attach packages to a draft pre-release + needs: package + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + pattern: attackpath-visualizer-release-* + path: release-output + merge-multiple: true + - name: Verify package set and create checksums + run: | + set -euo pipefail + test -f release-output/attackpath-visualizer-windows-x64.exe + test -f release-output/attackpath-visualizer-macos-arm64.tar.gz + test -f release-output/attackpath-visualizer-linux-x64.tar.gz + (cd release-output && find . -maxdepth 1 -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS) + cat release-output/SHA256SUMS + - name: Create draft pre-release + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create v0.1.0-dev release-output/* --draft --prerelease --target "${GITHUB_SHA}" --title "AttackPath Visualizer v0.1.0-dev (dev beta)" --notes-file docs/RELEASE_NOTES.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb23d18 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +/bin/ +/dist/ +*.db +*.db-shm +*.db-wal +.DS_Store +Thumbs.db +*.exe +*.app/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..1872d0a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,8 @@ +# Changelog + +## Unreleased + +- Added native Fyne dashboard, terminal navigation, launch chooser, keyboard shortcuts, custom icon/theme/fonts, offline help, and sanitized diagnostics. +- Added durable SQLite graph storage, versioned SQL migrations, bounded/validated JSON import, import history, reports, and deterministic offline demo data. +- Added in-app notification rules and opt-in per-user OS delivery using a read-only database connection. +- Added Linux/macOS/Windows CI, software-rendered UI screenshot artifacts, dependency checks, branch lockfile automation, and a manual draft-release workflow for native GUI and CLI-only packages. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..871a30e --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,15 @@ +# Contributor Covenant Code of Conduct + +## Our pledge +We pledge to make participation in this project a respectful experience for everyone, regardless of background or identity. + +## Our standards +Examples of positive behavior include empathy, constructive feedback, and respect for differing viewpoints. Unacceptable behavior includes harassment, discriminatory language, personal attacks, publishing private information, and disruptive conduct. + +## Responsibilities and enforcement +Maintainers are responsible for clarifying standards and taking fair corrective action. They may remove, edit, or reject contributions that violate this code and may temporarily or permanently exclude contributors for behavior they consider inappropriate. + +## Scope and reporting +This code applies in project spaces and when someone represents the project. Report unacceptable behavior privately to a repository maintainer through GitHub. Maintainers will review reports respectfully and confidentially. For reporting a security vulnerability, follow the preferred private-advisory and backup-channel instructions in [`SECURITY.md`](SECURITY.md). + +This text is adapted from Contributor Covenant v2.1, licensed CC BY 4.0. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0ab1988 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,7 @@ +# Contributing + +Use focused branches and conventional commit subjects (`feat:`, `fix:`, `docs:`, `test:`, `build:`). Open an issue for substantial changes and a pull request with scope, test evidence, platform coverage, and risks. Never include real inventory, credentials, or customer data in fixtures. + +Install Go 1.23+, then run `gofmt -w` on changed Go files, `go vet ./...`, and `go test -race ./...`. The full `make check` target also builds the CLI. Keep domain behavior independent from UI and persistence packages. Add deterministic tests for errors and boundaries. Do not add source comments; document behavior in package names, tests, and docs. + +Security-sensitive changes must validate untrusted input, preserve local-only defaults, avoid logging content or secrets, and include threat-model updates. Review dependencies and licenses before adding modules. Pull requests should state any checks or platforms that could not be run. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..69f5d17 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 NexzaDev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..95d3dc3 --- /dev/null +++ b/Makefile @@ -0,0 +1,19 @@ +.PHONY: format lint test build check demo + +format: + gofmt -w $$(find . -name '*.go' -not -path './vendor/*') + +lint: + go vet ./... + +test: + go test -race ./... + +build: + mkdir -p bin + go build -o bin/attackpath-visualizer ./cmd/attackpath-visualizer + +check: format lint test build + +demo: + go run ./cmd/attackpath-visualizer overview diff --git a/README.md b/README.md index 10f63e2..fb52026 100644 --- a/README.md +++ b/README.md @@ -1 +1,110 @@ -# attackpath-visualizer +# AttackPath Visualizer + +AttackPath Visualizer is a local-first defensive tool for exploring potential exposure paths across assets, identities, configuration findings, and evidence. It is an inventory relationship analyzer—not an attack executor, vulnerability scanner, or proof of exploitability. It makes no network requests at runtime and requires no account, paid service, API key, or cloud component. + +The original product brief and acceptance criteria are preserved unchanged in [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md). The implementation status and platform verification are tracked in [`docs/ROADMAP.md`](docs/ROADMAP.md) and the project pull request. + +## Features + +- Native Go command-line interface and Fyne desktop dashboard, plus a terminal menu; choose a front end at launch, remember a choice, or override it with `--ui=gui`, `--ui=tui`, or `--ask`. +- Directed asset/identity graph with validated misconfigurations, findings, required edge evidence, explainable impact/confidence scoring, cycle-safe bounded path ranking, and deterministic synthetic demo inventory. +- Local SQLite storage, versioned migrations, strict bounded JSON ingestion, atomic graph replacement, detailed import/validation history, and graph export. +- Overview, graph workspace, paths, assets, evidence, remediation, imports, reports, notifications, settings, About, usage guide, and sanitized diagnostics views. +- In-app event notifications and optional per-user OS notifications. The background notifier is off by default, uses a read-only database connection and a private local delivery ledger, and makes no network calls. +- Custom application icon, offline Noto Sans font assets, light/dark themes, keyboard shortcuts, and accessible text alternatives. +- CI coverage for Linux, macOS, and Windows, software-rendered dashboard screenshots, a tag-triggered public beta workflow, and a manually triggered draft-release workflow. + +## Requirements + +- Go 1.25 or newer. +- Native Fyne GUI build prerequisites. On Ubuntu, CI installs `bc`, `gcc`, `libgl1-mesa-dev`, `libwayland-dev`, `libx11-dev`, `libxkbcommon-dev`, `xorg-dev`, `xvfb`, and `language-pack-en`. These are build/test prerequisites only; the CLI-only build does not require the GUI stack. +- No network access is required to run the application after it has been built. First-time Go module downloads and release packaging do need network access. + +## Run + +From the repository root: + +```sh +go run ./cmd/attackpath-visualizer --ask +go run ./cmd/attackpath-visualizer --ui=tui +go run ./cmd/attackpath-visualizer --ui=gui +go run ./cmd/attackpath-visualizer overview --json +go run ./cmd/attackpath-visualizer paths --json +go run ./cmd/attackpath-visualizer help +``` + +Launching with no subcommand opens the configured front end or asks which one to use when appropriate. A remembered choice can be cleared with `go run ./cmd/attackpath-visualizer config reset-ui`. `ATTACKPATH_VISUALIZER_UI=gui|tui` overrides the saved preference. Use `--db PATH` after a CLI subcommand (for example, `overview --db ./graph.db`) or after a launcher option (for example, `--ui=gui --db ./graph.db`) to choose a different SQLite file; `ATTACKPATH_VISUALIZER_DB` is the corresponding environment override. + +The first launch initializes a clearly labeled synthetic demo graph. Demo data is deterministic and stays local. It is safe to replace it with authorized inventory through the Import view or the CLI. Imports accept JSON up to 8 MiB, validate the complete graph before changing stored data, and replace the current graph only after explicit confirmation. The CLI form is `attackpath-visualizer import --yes inventory.json`; omit `--yes` in an interactive terminal to confirm at the prompt. Export writes the local graph as JSON to standard output. + +Inventory JSON accepts `schema_version: 1` (versionless legacy JSON is interpreted as version 1) and the arrays `assets`, `identities`, `misconfigurations`, `findings`, and `edges`. Assets and identities have unique IDs, names, kinds, and impact tiers from 1 to 5. Misconfigurations and findings must reference valid assets and optional identities; findings can point to a misconfiguration. Edges can connect assets and identities, must have confidence from 0 to 100, and require source, finding, and observed evidence. Unknown fields, trailing JSON, missing references, duplicate IDs, invalid ranges, missing evidence, malformed JSON, and empty inventories are rejected with an error recorded alongside the import source in SQLite. + +Ingestion is limited to 8 MiB, 10,000 assets, 10,000 identities, 50,000 edges, 50,000 findings, and 50,000 misconfigurations. Path enumeration is cycle-safe, capped at depth 32, output limit 1,000, and a 250,000-edge-expansion budget. It retains the highest-ranked simple paths under the cap and marks truncation. Path confidence is compounded edge-by-edge using integer floor at each step; score is the maximum node impact tier multiplied by that compounded confidence. Each ranked path carries its exact impact tier and ordered per-edge confidence inputs in the path object. Scores are prioritization aids, not exploitability claims. + +## Build and verify + +The commands below work from the repository root on each native OS. The default build includes the desktop GUI; the `nogui` build is for servers and terminals. + +### Linux and macOS + +```sh +mkdir -p bin +go test ./... +go vet ./... +go build -o ./bin/attackpath-visualizer ./cmd/attackpath-visualizer +go build -tags nogui -o ./bin/attackpath-visualizer-cli ./cmd/attackpath-visualizer +go run ./cmd/attackpath-visualizer --ask +``` + +On Ubuntu, install the Fyne native build prerequisites listed above before building the GUI. + +### Windows PowerShell + +```powershell +New-Item -ItemType Directory -Force bin | Out-Null +go test ./... +go vet ./... +go build -o .\bin\attackpath-visualizer.exe .\cmd\attackpath-visualizer +go build -tags nogui -o .\bin\attackpath-visualizer-cli.exe .\cmd\attackpath-visualizer +go run .\cmd\attackpath-visualizer --ask +``` + +For formatting in PowerShell, run `Get-ChildItem -Recurse -Filter *.go | ForEach-Object { gofmt -w $_.FullName }`. Native Fyne builds on Windows require a C compiler; CI installs MinGW-w64 GCC. + +The common full check sequence is: + +```sh +gofmt -w $(find . -name '*.go' -not -path './.git/*') +go vet ./... +go test ./... +go test -race ./... +go build -tags nogui ./... +go build ./... +go run ./cmd/render-screenshots -out artifacts/ui +``` + +`make check` runs the local formatting, analysis, test, and build gate. `go build -tags nogui ./...` builds the server-friendly CLI/TUI variant; `go build ./...` includes the native GUI. The GitHub Actions workflow runs the platform matrix on Go 1.27.3, uses Xvfb/software rendering for headless Linux UI checks, and uploads PNG screenshots as `attackpath-visualizer-ui-screenshots`. CI checks module metadata and verifies downloaded modules. Screenshot artifacts are design evidence, not proof of desktop runtime behavior. Check the pull request for actual per-OS CI results before relying on a build. + +## Notifications + +Notifications are opt-in. In Settings, explicitly enable the background notifier, or run `attackpath-visualizer notifier install --db PATH`. The available commands are `notifier run`, `notifier install`, `notifier uninstall`, and `notifier status`. Installation creates a per-user startup entry without administrator privileges. The background process polls the local database every 15 minutes, observes configured severity and quiet-hour rules, and stores delivery de-duplication state in the OS user configuration directory. It does not write to the graph database or make network calls. In-app notices remain available when OS delivery is off. + +## Release packages + +The tag-triggered `Beta release` workflow runs tests and packages the GUI on native Linux x64, macOS ARM64, and Windows x64 runners, includes the custom icon and license materials, creates `SHA256SUMS`, and publishes a public **pre-release**. The separate `Release packages` workflow remains a manual draft-only path and never publishes automatically. See [`docs/RELEASING.md`](docs/RELEASING.md) for tagging, phone/desktop GitHub steps, package contents, checksum verification, and unsigned-binary warnings. No signing or notarization is claimed. + +## Data, security, and recovery + +- The database and user preferences remain on the local machine. No telemetry or third-party integration is configured. +- Import validation completes before a transaction replaces stored graph rows. Keep an exported JSON backup before importing data you cannot recreate. +- Diagnostics contain only application/build version, OS/architecture, Go runtime, and a sanitized local configuration status. Review the report before sharing it. +- Use only systems and inventories you are authorized to assess. A relationship graph can be incomplete or stale and should be reviewed by a human. +- See [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md), [`docs/USAGE.md`](docs/USAGE.md), and [`SECURITY.md`](SECURITY.md) for security boundaries, detailed workflows, and reporting guidance. + +### Reporting a vulnerability + +Use the [GitHub private vulnerability advisory form](https://github.com/NexzaDev/attackpath-visualizer/security/advisories/new) first; please do not report vulnerabilities in public issues. If you cannot use the GitHub form, send the report to **SuperMcDuck@proton.me**. See [`SECURITY.md`](SECURITY.md) for supported versions, scope, response targets, and disclosure guidance. + +## License + +The application is MIT-licensed; third-party and font license texts are listed in [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md), [`docs/LICENSES.md`](docs/LICENSES.md), and the `licenses/` directory. Release builds gather the platform-specific transitive Go module licenses. See [`LICENSE`](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..211627d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,29 @@ +# Security policy + +## Supported versions + +The project is in development. Until a stable release is declared, only the latest `v0.1.0-dev` pre-release and the current default-branch source are considered for security fixes. Older development builds are unsupported; update to the latest available version before reporting. + +## Private vulnerability reporting + +GitHub private vulnerability reporting is the preferred channel: [Report a vulnerability](https://github.com/NexzaDev/attackpath-visualizer/security/advisories/new). Please do not disclose suspected vulnerabilities in public issues, discussions, or pull requests. + +### Backup channel: email + +If you cannot use the GitHub form, send the report to **SuperMcDuck@proton.me**. + +## What to include + +Include the affected version or commit, affected component, clear reproduction steps using synthetic data, expected and actual behavior, impact assessment, and a proposed mitigation if known. Do not send real asset inventories, credentials, tokens, or personal data. Redact sensitive details and attach only the minimum synthetic proof needed to reproduce the issue. + +## Response expectations + +For this volunteer-run project, maintainers target acknowledging reports within 7 days and providing an initial assessment within 14 days. These are targets, not guarantees. The assessment will identify severity, affected versions, next steps, and an expected timeline where possible. + +## Scope + +In scope are local inventory parsing and validation, SQLite persistence and migrations, path/scoring/remediation logic, data exported by the application, diagnostics, desktop/terminal launch behavior, release packaging, and the opt-in background notifier. The application is not a vulnerability scanner, does not execute attack techniques, and does not contact assessed systems. Third-party dependencies should be reported to their upstream maintainers as well; include a project report when the dependency issue affects this application. + +## Disclosure + +Please allow maintainers reasonable time to investigate, prepare a fix, and coordinate disclosure before publishing technical details. We will coordinate a disclosure date with the reporter and credit them if they want attribution. Do not access, alter, or retain data that is not yours while validating a report. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..fa6c06c --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,14 @@ +# Third-party notices + +This application bundles the direct dependencies and assets listed below. The BSD 3-Clause text for transitive `modernc.org/mathutil v1.6.0` is manually included because `go-licenses` cannot discover it in the module cache; the v1.6.0 license source is mirrored at [val1/mirror-modernc-mathutil](https://github.com/val1/mirror-modernc-mathutil/tree/v1.6.0). The release workflow checks that file and uses `go-licenses save` to collect other transitive module license texts. + +| Component | Version / origin | License | +|---|---|---| +| Fyne | `fyne.io/fyne/v2 v2.6.3` | BSD 3-Clause | +| modernc SQLite | `modernc.org/sqlite v1.34.5` | BSD 3-Clause | +| modernc mathutil (transitive) | `modernc.org/mathutil v1.6.0` | BSD 3-Clause (`licenses/modernc-mathutil-BSD-3-Clause.txt`) | +| beeep | `github.com/gen2brain/beeep v0.10.0` | MIT | +| Noto Sans bundled font family | Fyne v2.6.3 theme font assets | SIL Open Font License 1.1 | +| AttackPath Visualizer custom artwork | Original project artwork | MIT | + +Full direct dependency and font licenses are included in `licenses/` and in `docs/LICENSES.md` for offline display. diff --git a/assets/assets.go b/assets/assets.go new file mode 100644 index 0000000..bff2a0c --- /dev/null +++ b/assets/assets.go @@ -0,0 +1,6 @@ +package assets + +import "embed" + +//go:embed icons/icon.svg icons/icon.png icons/icon.ico icons/icon.icns icons/icon-*.png icons/nav/*.svg fonts/*.ttf fonts/OFL.txt docs/README.md docs/USAGE.md docs/LICENSE.md docs/LICENSES.md docs/THIRD_PARTY_NOTICES.md all:licenses demo.json linux/attackpath-visualizer.desktop +var Files embed.FS diff --git a/assets/demo.json b/assets/demo.json new file mode 100644 index 0000000..e6304bf --- /dev/null +++ b/assets/demo.json @@ -0,0 +1,50 @@ +{ + "schema_version": 1, + "assets": [ + {"id":"internet-edge","name":"Synthetic public edge","kind":"network-boundary","impact":2,"description":"Fictional ingress boundary used only by the offline demo"}, + {"id":"api-gateway","name":"Customer API gateway","kind":"service","impact":3,"description":"Synthetic internet-facing application entry point"}, + {"id":"workload-cluster","name":"Application workload cluster","kind":"compute","impact":3,"description":"Fictional service runtime with a deployment identity"}, + {"id":"build-runner","name":"Release build runner","kind":"compute","impact":3,"description":"Synthetic build worker that publishes application artifacts"}, + {"id":"artifact-store","name":"Release artifact store","kind":"storage","impact":4,"description":"Fictional package repository containing deployment artifacts"}, + {"id":"secret-store","name":"Application secret store","kind":"vault","impact":4,"description":"Synthetic secret service with a stale credential finding"}, + {"id":"customer-db","name":"Customer records database","kind":"database","impact":5,"description":"Fictional high-impact data store; no real customer data is present"}, + {"id":"backup-bucket","name":"Encrypted backup bucket","kind":"storage","impact":5,"description":"Synthetic backup destination with an advisory access finding"}, + {"id":"monitoring","name":"Operations monitoring service","kind":"service","impact":2,"description":"Fictional monitoring reader used as a low-impact comparison path"} + ], + "identities": [ + {"id":"deploy-bot","name":"Deployment automation identity","kind":"workload","impact":4,"description":"Synthetic principal with release and configuration permissions"}, + {"id":"analytics-reader","name":"Analytics reader identity","kind":"service-account","impact":4,"description":"Fictional application identity with read access to sensitive data"}, + {"id":"backup-service","name":"Backup service identity","kind":"service-account","impact":3,"description":"Synthetic principal that writes encrypted backups"}, + {"id":"external-partner","name":"External partner identity","kind":"federated","impact":2,"description":"Fictional federated principal used to illustrate a lower-confidence relationship"} + ], + "misconfigurations": [ + {"id":"misconfig-public-api","asset_id":"api-gateway","title":"Public ingress requires review","severity":3,"description":"Synthetic demo advisory; validate intended exposure and authentication policy."}, + {"id":"misconfig-deploy-scope","asset_id":"build-runner","identity_id":"deploy-bot","title":"Deployment permissions are broader than the demo baseline","severity":4,"description":"Synthetic demo advisory; review the minimum publish and deploy permissions."}, + {"id":"misconfig-backup-policy","asset_id":"backup-bucket","identity_id":"backup-service","title":"Backup access policy needs periodic review","severity":4,"description":"Synthetic demo advisory; verify encryption and principal scoping."}, + {"id":"misconfig-stale-secret","asset_id":"secret-store","identity_id":"deploy-bot","title":"Stale credential reference","severity":3,"description":"Synthetic demo advisory; rotate or remove unused credential references."} + ], + "findings": [ + {"id":"finding-ingress","asset_id":"api-gateway","title":"Public route observed in fixture","severity":3,"source":"demo://network-inventory","observed":"2026-10-15T09:00:00Z"}, + {"id":"finding-publish","asset_id":"artifact-store","identity_id":"deploy-bot","misconfiguration_id":"misconfig-deploy-scope","title":"Publish permission present","severity":4,"source":"demo://permission-review","observed":"2026-10-15T09:05:00Z"}, + {"id":"finding-secret","asset_id":"secret-store","identity_id":"deploy-bot","misconfiguration_id":"misconfig-stale-secret","title":"Stale credential reference detected","severity":3,"source":"demo://configuration-audit","observed":"2026-10-15T09:10:00Z"}, + {"id":"finding-data-read","asset_id":"customer-db","identity_id":"analytics-reader","title":"Read permission present in synthetic policy","severity":5,"source":"demo://data-access-review","observed":"2026-10-15T09:15:00Z"}, + {"id":"finding-backup","asset_id":"backup-bucket","identity_id":"backup-service","misconfiguration_id":"misconfig-backup-policy","title":"Backup write permission present","severity":4,"source":"demo://storage-review","observed":"2026-10-15T09:20:00Z"} + ], + "edges": [ + {"id":"edge-internet-api","from":"internet-edge","to":"api-gateway","relation":"routes requests to","confidence":98,"evidence":{"source":"demo://network-inventory","finding":"Fictional ingress route connects to the API gateway","observed":"2026-10-15T09:00:00Z"}}, + {"id":"edge-api-workload","from":"api-gateway","to":"workload-cluster","relation":"forwards authenticated workload traffic to","confidence":91,"evidence":{"source":"demo://service-map","finding":"Synthetic service map records the gateway-to-workload dependency","observed":"2026-10-15T09:02:00Z"}}, + {"id":"edge-workload-deploy","from":"workload-cluster","to":"deploy-bot","relation":"uses workload identity","confidence":88,"evidence":{"source":"demo://identity-inventory","finding":"Fictional runtime is associated with deployment identity","observed":"2026-10-15T09:04:00Z"}}, + {"id":"edge-deploy-runner","from":"deploy-bot","to":"build-runner","relation":"can start release jobs on","confidence":93,"evidence":{"source":"demo://permission-review","finding":"Synthetic policy grants release-job access","observed":"2026-10-15T09:05:00Z"}}, + {"id":"edge-runner-artifact","from":"build-runner","to":"artifact-store","relation":"publishes packages to","confidence":94,"evidence":{"source":"demo://build-inventory","finding":"Fictional build runner publishes to the artifact store","observed":"2026-10-15T09:07:00Z"}}, + {"id":"edge-deploy-secrets","from":"deploy-bot","to":"secret-store","relation":"can read configuration from","confidence":78,"evidence":{"source":"demo://permission-review","finding":"Synthetic policy permits reading application configuration","observed":"2026-10-15T09:10:00Z"}}, + {"id":"edge-secret-analytics","from":"secret-store","to":"analytics-reader","relation":"contains credential for","confidence":71,"evidence":{"source":"demo://configuration-audit","finding":"Fictional secret reference maps to analytics identity","observed":"2026-10-15T09:12:00Z"}}, + {"id":"edge-analytics-db","from":"analytics-reader","to":"customer-db","relation":"can read records from","confidence":96,"evidence":{"source":"demo://data-access-review","finding":"Synthetic access policy grants database read access","observed":"2026-10-15T09:15:00Z"}}, + {"id":"edge-db-backup","from":"customer-db","to":"backup-bucket","relation":"exports scheduled backup to","confidence":83,"evidence":{"source":"demo://data-flow","finding":"Fictional scheduled backup workflow connects the data store to backup storage","observed":"2026-10-15T09:17:00Z"}}, + {"id":"edge-workload-backup","from":"workload-cluster","to":"backup-service","relation":"invokes backup job as","confidence":85,"evidence":{"source":"demo://service-map","finding":"Synthetic workload invokes the backup service","observed":"2026-10-15T09:18:00Z"}}, + {"id":"edge-backup-write","from":"backup-service","to":"backup-bucket","relation":"writes encrypted snapshots to","confidence":92,"evidence":{"source":"demo://storage-review","finding":"Fictional backup identity can write encrypted snapshots","observed":"2026-10-15T09:20:00Z"}}, + {"id":"edge-deploy-backup","from":"deploy-bot","to":"backup-service","relation":"can assume backup identity","confidence":64,"evidence":{"source":"demo://identity-inventory","finding":"Synthetic trust policy permits a deployment-to-backup identity transition","observed":"2026-10-15T09:22:00Z"}}, + {"id":"edge-monitor-db","from":"monitoring","to":"customer-db","relation":"reads health metadata from","confidence":55,"evidence":{"source":"demo://monitoring-map","finding":"Low-confidence fixture relationship is limited to health metadata","observed":"2026-10-15T09:24:00Z"}}, + {"id":"edge-partner-api","from":"external-partner","to":"api-gateway","relation":"federates to","confidence":67,"evidence":{"source":"demo://federation-inventory","finding":"Fictional partner trust is represented for analysis only","observed":"2026-10-15T09:26:00Z"}}, + {"id":"edge-partner-db","from":"external-partner","to":"customer-db","relation":"has legacy read grant","confidence":28,"evidence":{"source":"demo://access-review","finding":"Low-confidence stale grant included to demonstrate evidence-sensitive ranking","observed":"2026-10-15T09:28:00Z"}} + ] +} diff --git a/assets/docs/LICENSE.md b/assets/docs/LICENSE.md new file mode 100644 index 0000000..69f5d17 --- /dev/null +++ b/assets/docs/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 NexzaDev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/assets/docs/LICENSES.md b/assets/docs/LICENSES.md new file mode 100644 index 0000000..8bfff4a --- /dev/null +++ b/assets/docs/LICENSES.md @@ -0,0 +1,130 @@ +# Offline dependency and asset licenses + +The following full license texts apply to bundled direct dependencies and fonts. The final release archive also contains license texts for every transitive module in that platform's build. + +## Fyne — BSD 3-Clause + +BSD 3-Clause License + +Copyright (C) 2018 Fyne.io developers (see AUTHORS) +All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Fyne.io nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +## modernc SQLite — BSD 3-Clause + +Copyright (c) 2017 The Sqlite Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +## beeep — MIT + +Copyright (c) 2017, Milan Nikolic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +## Noto Sans — SIL Open Font License 1.1 + +—————————————————————————————- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +—————————————————————————————- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. + +DEFINITIONS +“Font Software” refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. + +“Reserved Font Name” refers to any names specified as such after the copyright statement(s). + +“Original Version” refers to the collection of Font Software components as distributed by the Copyright Holder(s). + +“Modified Version” refers to any derivative made by adding to, deleting, or substituting—in part or in whole—any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +“Author” refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. + +5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/assets/docs/README.md b/assets/docs/README.md new file mode 100644 index 0000000..b4bd767 --- /dev/null +++ b/assets/docs/README.md @@ -0,0 +1,104 @@ +# AttackPath Visualizer + +AttackPath Visualizer is a local-first defensive tool for exploring potential exposure paths across assets, identities, configuration findings, and evidence. It is an inventory relationship analyzer—not an attack executor, vulnerability scanner, or proof of exploitability. It makes no network requests at runtime and requires no account, paid service, API key, or cloud component. + +The original product brief and acceptance criteria are preserved unchanged in [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md). The implementation status and platform verification are tracked in [`docs/ROADMAP.md`](docs/ROADMAP.md) and the project pull request. + +## Features + +- Native Go command-line interface and Fyne desktop dashboard, plus a terminal menu; choose a front end at launch, remember a choice, or override it with `--ui=gui`, `--ui=tui`, or `--ask`. +- Directed asset graph with validation, explainable potential paths, evidence, confidence, impact, severity, remediation summaries, and deterministic offline demo data. +- Local SQLite storage, schema migrations, bounded JSON import, atomic graph replacement, import history, and JSON export. +- Overview, graph workspace, paths, assets, evidence, remediation, imports, reports, notifications, settings, About, usage guide, and sanitized diagnostics views. +- In-app event notifications and optional per-user OS notifications. The background notifier is off by default, uses a read-only database connection and a private local delivery ledger, and makes no network calls. +- Custom application icon, offline Noto Sans font assets, light/dark themes, keyboard shortcuts, and accessible text alternatives. +- CI coverage for Linux, macOS, and Windows, software-rendered dashboard screenshots, and a manually triggered draft-release workflow. + +## Requirements + +- Go 1.23 or newer. +- Native Fyne GUI build prerequisites. On Ubuntu, CI installs `bc`, `gcc`, `libgl1-mesa-dev`, `libwayland-dev`, `libx11-dev`, `libxkbcommon-dev`, `xorg-dev`, `xvfb`, and `language-pack-en`. These are build/test prerequisites only; the CLI-only build does not require the GUI stack. +- No network access is required to run the application after it has been built. First-time Go module downloads and release packaging do need network access. + +## Run + +From the repository root: + +```sh +go run ./cmd/attackpath-visualizer --ask +go run ./cmd/attackpath-visualizer --ui=tui +go run ./cmd/attackpath-visualizer --ui=gui +go run ./cmd/attackpath-visualizer overview --json +go run ./cmd/attackpath-visualizer paths --json +go run ./cmd/attackpath-visualizer help +``` + +Launching with no subcommand opens the configured front end or asks which one to use when appropriate. A remembered choice can be cleared with `go run ./cmd/attackpath-visualizer config reset-ui`. `ATTACKPATH_VISUALIZER_UI=gui|tui` overrides the saved preference. Use `--db PATH` after a CLI subcommand (for example, `overview --db ./graph.db`) or after a launcher option (for example, `--ui=gui --db ./graph.db`) to choose a different SQLite file; `ATTACKPATH_VISUALIZER_DB` is the corresponding environment override. + +The first launch initializes a clearly labeled synthetic demo graph. Demo data is deterministic and stays local. It is safe to replace it with authorized inventory through the Import view or the CLI. Imports accept JSON up to 8 MiB, validate the complete graph before changing stored data, and replace the current graph only after explicit confirmation. The CLI form is `attackpath-visualizer import --yes inventory.json`; omit `--yes` in an interactive terminal to confirm at the prompt. Export writes the local graph as JSON to standard output. + +The graph schema has `assets` and `edges` arrays. An asset has a unique `id`, `name`, `kind`, impact from 1 to 5, and optional description. An edge has a unique `id`, `from`, `to`, relationship, confidence from 0 to 100, and optional source/finding/observed evidence. Self-edges, missing endpoints, duplicate IDs, invalid ranges, malformed JSON, and oversized imports are rejected. Paths are bounded simple directed paths, ranked by maximum asset impact multiplied by compounded edge confidence. Scores are prioritization aids, not exploitability claims. + +## Build and verify + +The commands below work from the repository root on each native OS. The default build includes the desktop GUI; the `nogui` build is for servers and terminals. + +### Linux and macOS + +```sh +mkdir -p bin +go test ./... +go vet ./... +go build -o ./bin/attackpath-visualizer ./cmd/attackpath-visualizer +go build -tags nogui -o ./bin/attackpath-visualizer-cli ./cmd/attackpath-visualizer +go run ./cmd/attackpath-visualizer --ask +``` + +On Ubuntu, install the Fyne native build prerequisites listed above before building the GUI. + +### Windows PowerShell + +```powershell +New-Item -ItemType Directory -Force bin | Out-Null +go test ./... +go vet ./... +go build -o .\bin\attackpath-visualizer.exe .\cmd\attackpath-visualizer +go build -tags nogui -o .\bin\attackpath-visualizer-cli.exe .\cmd\attackpath-visualizer +go run .\cmd\attackpath-visualizer --ask +``` + +For formatting in PowerShell, run `Get-ChildItem -Recurse -Filter *.go | ForEach-Object { gofmt -w $_.FullName }`. Native Fyne builds on Windows require a C compiler; CI installs MinGW-w64 GCC. + +The common full check sequence is: + +```sh +gofmt -w $(find . -name '*.go' -not -path './.git/*') +go vet ./... +go test ./... +go test -race ./... +go build -tags nogui ./... +go build ./... +go run ./cmd/render-screenshots -out artifacts/ui +``` + +`make check` runs the local formatting, analysis, test, and build gate. `go build -tags nogui ./...` builds the server-friendly CLI/TUI variant; `go build ./...` includes the native GUI. The GitHub Actions workflow runs the platform matrix, uses Xvfb/software rendering for headless Linux UI checks, and uploads PNG screenshots as `attackpath-visualizer-ui-screenshots`. Screenshot artifacts are design evidence, not proof of desktop runtime behavior. Check the pull request for actual per-OS CI results before relying on a build. + +## Notifications + +Notifications are opt-in. In Settings, explicitly enable the background notifier, or run `attackpath-visualizer notifier install --db PATH`. The available commands are `notifier run`, `notifier install`, `notifier uninstall`, and `notifier status`. Installation creates a per-user startup entry without administrator privileges. The background process polls the local database every 15 minutes, observes configured severity and quiet-hour rules, and stores delivery de-duplication state in the OS user configuration directory. It does not write to the graph database or make network calls. In-app notices remain available when OS delivery is off. + +## Release packages + +Maintainers run the `Release packages` workflow manually from the default branch in GitHub Actions. It packages the GUI on native Windows, macOS ARM64, and Linux x64 runners, creates the CLI-only package, includes offline documentation and dependency license material, calculates `SHA256SUMS`, and attaches the results to a **draft pre-release**. The workflow does not publish a release automatically. See [`docs/RELEASING.md`](docs/RELEASING.md) for exact phone/desktop GitHub steps and unsigned-binary warnings. No signing or notarization is claimed. + +## Data, security, and recovery + +- The database and user preferences remain on the local machine. No telemetry or third-party integration is configured. +- Import validation completes before a transaction replaces stored graph rows. Keep an exported JSON backup before importing data you cannot recreate. +- Diagnostics contain only application/build version, OS/architecture, Go runtime, and a sanitized local configuration status. Review the report before sharing it. +- Use only systems and inventories you are authorized to assess. A relationship graph can be incomplete or stale and should be reviewed by a human. +- See [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md), [`docs/USAGE.md`](docs/USAGE.md), and [`SECURITY.md`](SECURITY.md) for security boundaries, detailed workflows, and reporting guidance. + +## License + +The application is MIT-licensed; third-party and font license texts are listed in [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md), [`docs/LICENSES.md`](docs/LICENSES.md), and the `licenses/` directory. Release builds gather the platform-specific transitive Go module licenses. See [`LICENSE`](LICENSE). diff --git a/assets/docs/THIRD_PARTY_NOTICES.md b/assets/docs/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..ab9b019 --- /dev/null +++ b/assets/docs/THIRD_PARTY_NOTICES.md @@ -0,0 +1,13 @@ +# Third-party notices + +This application bundles the following direct dependencies and assets. Transitive Go modules are listed by CI and their license texts are included in each release package using `go-licenses save`. + +| Component | Version / origin | License | +|---|---|---| +| Fyne | `fyne.io/fyne/v2 v2.6.3` | BSD 3-Clause | +| modernc SQLite | `modernc.org/sqlite v1.34.5` | BSD 3-Clause | +| beeep | `github.com/gen2brain/beeep v0.10.0` | MIT | +| Noto Sans bundled font family | Fyne v2.6.3 theme font assets | SIL Open Font License 1.1 | +| AttackPath Visualizer custom artwork | Original project artwork | MIT | + +Full direct dependency and font licenses are included in `licenses/` and in `docs/LICENSES.md` for offline display. diff --git a/assets/docs/USAGE.md b/assets/docs/USAGE.md new file mode 100644 index 0000000..1ed4e4e --- /dev/null +++ b/assets/docs/USAGE.md @@ -0,0 +1,37 @@ +# Offline usage guide + +AttackPath Visualizer analyzes relationships from synthetic or authorized inventory. It does not scan systems, exploit vulnerabilities, or contact remote services. + +## Choose a front end + +Launch with no arguments to choose Dashboard or Terminal. `--ui gui` and `--ui tui` select directly; `--ask` shows the chooser, `--no-prompt` uses the saved/default choice, and `ATTACKPATH_VISUALIZER_UI` can set a preference. A headless session uses the terminal interface. Explicit commands such as `overview`, `paths`, `assets`, `import`, `export`, `about`, and `diagnostics` do not show the launcher. + +## Data and imports + +The first launch creates a local SQLite database and loads labeled synthetic demo data. Use Settings to inspect the data location. JSON graph files contain an `assets` array and an `edges` array. Asset impacts are 1–5; edge confidence is 0–100. Imports are validated and replace the graph in one transaction. A malformed file is rejected without partial replacement. The maximum import size is 8 MiB. + +## Dashboard categories + +- **Overview** summarizes stored assets, edges, path rankings, high-impact records, and import freshness. +- **Graph** displays the relationship inventory and a keyboard-accessible node list; selecting a node focuses its direct relationships. +- **Paths** shows ranked directed paths, confidence, impact, and the exact score breakdown; selecting a path opens its edge evidence. +- **Assets** lists stored asset identity, type, impact, and description. +- **Evidence** links every relationship to its source record and finding text. +- **Remediation** ranks edges by how many calculated paths they participate in; suggestions are advisory and never modify inventory. +- **Imports** validates JSON files and lists recent import outcomes. +- **Reports** exports the stored graph or ranked paths to a user-selected JSON file. +- **Notifications** lists local app events, severity, read state, and links to related records. +- **About** provides this guide, shortcuts, diagnostics, source links, and dependency licenses. +- **Settings** controls appearance and launcher preference. + +## CLI + +Run `attackpath-visualizer help` for commands. `--json` prints machine-readable output. `--db PATH` selects a separate SQLite file. `import FILE` or `import --db PATH < inventory.json` imports local JSON. `export` writes the graph as JSON. `about` and `diagnostics` do not include imported file contents or secrets. + +## Scoring and limits + +A path's impact is its highest asset impact. Confidence is the product of edge confidences, compounded in order; score is impact multiplied by confidence. The score is a prioritization heuristic, not exploitability probability. Path enumeration is bounded by depth and result limits. Review all evidence and inventory context before acting. + +## Notifications and privacy + +In-app notices are local. Background notifications are disabled until explicitly enabled or installed from the CLI. The notifier reads the database read-only on a bounded interval, displays minimal local text, and makes no network requests. It does not place evidence, credentials, or indicators in notification text. diff --git a/assets/fonts/NotoSans-Bold.ttf b/assets/fonts/NotoSans-Bold.ttf new file mode 100644 index 0000000..ab11d31 Binary files /dev/null and b/assets/fonts/NotoSans-Bold.ttf differ diff --git a/assets/fonts/NotoSans-BoldItalic.ttf b/assets/fonts/NotoSans-BoldItalic.ttf new file mode 100644 index 0000000..6dfd1e6 Binary files /dev/null and b/assets/fonts/NotoSans-BoldItalic.ttf differ diff --git a/assets/fonts/NotoSans-Italic.ttf b/assets/fonts/NotoSans-Italic.ttf new file mode 100644 index 0000000..1639ad7 Binary files /dev/null and b/assets/fonts/NotoSans-Italic.ttf differ diff --git a/assets/fonts/NotoSans-Regular.ttf b/assets/fonts/NotoSans-Regular.ttf new file mode 100644 index 0000000..a1b8994 Binary files /dev/null and b/assets/fonts/NotoSans-Regular.ttf differ diff --git a/assets/fonts/OFL.txt b/assets/fonts/OFL.txt new file mode 100644 index 0000000..26004ca --- /dev/null +++ b/assets/fonts/OFL.txt @@ -0,0 +1,38 @@ +—————————————————————————————- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +—————————————————————————————- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. + +DEFINITIONS +“Font Software” refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. + +“Reserved Font Name” refers to any names specified as such after the copyright statement(s). + +“Original Version” refers to the collection of Font Software components as distributed by the Copyright Holder(s). + +“Modified Version” refers to any derivative made by adding to, deleting, or substituting—in part or in whole—any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +“Author” refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. + +5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/icons/icon-1024.png b/assets/icons/icon-1024.png new file mode 100644 index 0000000..389a608 Binary files /dev/null and b/assets/icons/icon-1024.png differ diff --git a/assets/icons/icon-128.png b/assets/icons/icon-128.png new file mode 100644 index 0000000..a117907 Binary files /dev/null and b/assets/icons/icon-128.png differ diff --git a/assets/icons/icon-16.png b/assets/icons/icon-16.png new file mode 100644 index 0000000..cacbd60 Binary files /dev/null and b/assets/icons/icon-16.png differ diff --git a/assets/icons/icon-24.png b/assets/icons/icon-24.png new file mode 100644 index 0000000..65e5d83 Binary files /dev/null and b/assets/icons/icon-24.png differ diff --git a/assets/icons/icon-256.png b/assets/icons/icon-256.png new file mode 100644 index 0000000..c7d5170 Binary files /dev/null and b/assets/icons/icon-256.png differ diff --git a/assets/icons/icon-32.png b/assets/icons/icon-32.png new file mode 100644 index 0000000..a29c036 Binary files /dev/null and b/assets/icons/icon-32.png differ diff --git a/assets/icons/icon-48.png b/assets/icons/icon-48.png new file mode 100644 index 0000000..f77ce55 Binary files /dev/null and b/assets/icons/icon-48.png differ diff --git a/assets/icons/icon-512.png b/assets/icons/icon-512.png new file mode 100644 index 0000000..901bf92 Binary files /dev/null and b/assets/icons/icon-512.png differ diff --git a/assets/icons/icon-64.png b/assets/icons/icon-64.png new file mode 100644 index 0000000..7f9cd3c Binary files /dev/null and b/assets/icons/icon-64.png differ diff --git a/assets/icons/icon.icns b/assets/icons/icon.icns new file mode 100644 index 0000000..9c84999 Binary files /dev/null and b/assets/icons/icon.icns differ diff --git a/assets/icons/icon.ico b/assets/icons/icon.ico new file mode 100644 index 0000000..92e7efe Binary files /dev/null and b/assets/icons/icon.ico differ diff --git a/assets/icons/icon.png b/assets/icons/icon.png new file mode 100644 index 0000000..901bf92 Binary files /dev/null and b/assets/icons/icon.png differ diff --git a/assets/icons/icon.svg b/assets/icons/icon.svg new file mode 100644 index 0000000..de8de88 --- /dev/null +++ b/assets/icons/icon.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/assets/icons/nav/about.svg b/assets/icons/nav/about.svg new file mode 100644 index 0000000..9b29e1f --- /dev/null +++ b/assets/icons/nav/about.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/assets.svg b/assets/icons/nav/assets.svg new file mode 100644 index 0000000..77008e1 --- /dev/null +++ b/assets/icons/nav/assets.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/evidence.svg b/assets/icons/nav/evidence.svg new file mode 100644 index 0000000..d36f821 --- /dev/null +++ b/assets/icons/nav/evidence.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/graph.svg b/assets/icons/nav/graph.svg new file mode 100644 index 0000000..52c4eef --- /dev/null +++ b/assets/icons/nav/graph.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/imports.svg b/assets/icons/nav/imports.svg new file mode 100644 index 0000000..ca1b117 --- /dev/null +++ b/assets/icons/nav/imports.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/notifications.svg b/assets/icons/nav/notifications.svg new file mode 100644 index 0000000..4e54089 --- /dev/null +++ b/assets/icons/nav/notifications.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/overview.svg b/assets/icons/nav/overview.svg new file mode 100644 index 0000000..7b3d81c --- /dev/null +++ b/assets/icons/nav/overview.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/paths.svg b/assets/icons/nav/paths.svg new file mode 100644 index 0000000..f45b604 --- /dev/null +++ b/assets/icons/nav/paths.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/remediation.svg b/assets/icons/nav/remediation.svg new file mode 100644 index 0000000..669d936 --- /dev/null +++ b/assets/icons/nav/remediation.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/reports.svg b/assets/icons/nav/reports.svg new file mode 100644 index 0000000..9cde5a7 --- /dev/null +++ b/assets/icons/nav/reports.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/settings.svg b/assets/icons/nav/settings.svg new file mode 100644 index 0000000..517c9e7 --- /dev/null +++ b/assets/icons/nav/settings.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/severity-critical.svg b/assets/icons/nav/severity-critical.svg new file mode 100644 index 0000000..ab1a149 --- /dev/null +++ b/assets/icons/nav/severity-critical.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/severity-high.svg b/assets/icons/nav/severity-high.svg new file mode 100644 index 0000000..aa1d569 --- /dev/null +++ b/assets/icons/nav/severity-high.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/severity-info.svg b/assets/icons/nav/severity-info.svg new file mode 100644 index 0000000..163798b --- /dev/null +++ b/assets/icons/nav/severity-info.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/severity-low.svg b/assets/icons/nav/severity-low.svg new file mode 100644 index 0000000..a52cb55 --- /dev/null +++ b/assets/icons/nav/severity-low.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/nav/severity-medium.svg b/assets/icons/nav/severity-medium.svg new file mode 100644 index 0000000..4088ff3 --- /dev/null +++ b/assets/icons/nav/severity-medium.svg @@ -0,0 +1 @@ + diff --git a/assets/licenses/AttackPath-Visualizer-MIT.txt b/assets/licenses/AttackPath-Visualizer-MIT.txt new file mode 100644 index 0000000..69f5d17 --- /dev/null +++ b/assets/licenses/AttackPath-Visualizer-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 NexzaDev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/assets/licenses/Fyne-BSD-3-Clause.txt b/assets/licenses/Fyne-BSD-3-Clause.txt new file mode 100644 index 0000000..5f07129 --- /dev/null +++ b/assets/licenses/Fyne-BSD-3-Clause.txt @@ -0,0 +1,27 @@ +BSD 3-Clause License + +Copyright (C) 2018 Fyne.io developers (see AUTHORS) +All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Fyne.io nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/assets/licenses/NotoSans-OFL-1.1.txt b/assets/licenses/NotoSans-OFL-1.1.txt new file mode 100644 index 0000000..26004ca --- /dev/null +++ b/assets/licenses/NotoSans-OFL-1.1.txt @@ -0,0 +1,38 @@ +—————————————————————————————- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +—————————————————————————————- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. + +DEFINITIONS +“Font Software” refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. + +“Reserved Font Name” refers to any names specified as such after the copyright statement(s). + +“Original Version” refers to the collection of Font Software components as distributed by the Copyright Holder(s). + +“Modified Version” refers to any derivative made by adding to, deleting, or substituting—in part or in whole—any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +“Author” refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. + +5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/licenses/beeep-MIT.txt b/assets/licenses/beeep-MIT.txt new file mode 100644 index 0000000..9d4a922 --- /dev/null +++ b/assets/licenses/beeep-MIT.txt @@ -0,0 +1,23 @@ +Copyright (c) 2017, Milan Nikolic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/assets/licenses/modernc-mathutil-BSD-3-Clause.txt b/assets/licenses/modernc-mathutil-BSD-3-Clause.txt new file mode 100644 index 0000000..128a1b6 --- /dev/null +++ b/assets/licenses/modernc-mathutil-BSD-3-Clause.txt @@ -0,0 +1,27 @@ +Copyright (c) 2014 The mathutil Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the names of the authors nor the names of the +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/assets/licenses/modernc-sqlite-BSD-3-Clause.txt b/assets/licenses/modernc-sqlite-BSD-3-Clause.txt new file mode 100644 index 0000000..867b0f3 --- /dev/null +++ b/assets/licenses/modernc-sqlite-BSD-3-Clause.txt @@ -0,0 +1,26 @@ +Copyright (c) 2017 The Sqlite Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/assets/linux/attackpath-visualizer.desktop b/assets/linux/attackpath-visualizer.desktop new file mode 100644 index 0000000..fad83fe --- /dev/null +++ b/assets/linux/attackpath-visualizer.desktop @@ -0,0 +1,8 @@ +[Desktop Entry] +Type=Application +Name=AttackPath Visualizer +Comment=Local defensive exposure relationship graph explorer +Exec=attackpath-visualizer +Icon=attackpath-visualizer +Terminal=false +Categories=Security;Utility; diff --git a/cmd/attackpath-visualizer/FyneApp.toml b/cmd/attackpath-visualizer/FyneApp.toml new file mode 100644 index 0000000..51bca4a --- /dev/null +++ b/cmd/attackpath-visualizer/FyneApp.toml @@ -0,0 +1,8 @@ +Website = "https://github.com/NexzaDev/attackpath-visualizer" + +[Details] +Name = "AttackPath Visualizer" +ID = "dev.nexza.attackpathvisualizer" +Version = "0.1.0" +Build = 1 +Icon = "../../assets/icons/icon.png" diff --git a/cmd/attackpath-visualizer/gui_disabled.go b/cmd/attackpath-visualizer/gui_disabled.go new file mode 100644 index 0000000..ef1ddf2 --- /dev/null +++ b/cmd/attackpath-visualizer/gui_disabled.go @@ -0,0 +1,20 @@ +//go:build nogui + +package main + +import ( + "errors" + "fmt" + "os" + + "github.com/NexzaDev/attackpath-visualizer/tui" +) + +func launchGUI(string) error { + return errors.New("the graphical dashboard is unavailable in this nogui build; rebuild without -tags nogui") +} + +func launchChooser(dbPath string) error { + fmt.Fprintln(os.Stderr, "The graphical dashboard is unavailable in this nogui build; opening the terminal interface.") + return tui.Run(dbPath) +} diff --git a/cmd/attackpath-visualizer/gui_enabled.go b/cmd/attackpath-visualizer/gui_enabled.go new file mode 100644 index 0000000..c275984 --- /dev/null +++ b/cmd/attackpath-visualizer/gui_enabled.go @@ -0,0 +1,13 @@ +//go:build !nogui + +package main + +import "github.com/NexzaDev/attackpath-visualizer/gui" + +func launchGUI(dbPath string) error { + return gui.Run(dbPath) +} + +func launchChooser(dbPath string) error { + return gui.ShowChooser(dbPath) +} diff --git a/cmd/attackpath-visualizer/main.go b/cmd/attackpath-visualizer/main.go new file mode 100644 index 0000000..18bbdf8 --- /dev/null +++ b/cmd/attackpath-visualizer/main.go @@ -0,0 +1,318 @@ +package main + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "runtime" + "strings" + "time" + + "github.com/NexzaDev/attackpath-visualizer/internal/config" + "github.com/NexzaDev/attackpath-visualizer/internal/launcher" + "github.com/NexzaDev/attackpath-visualizer/internal/meta" + "github.com/NexzaDev/attackpath-visualizer/internal/notifier" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" + "github.com/NexzaDev/attackpath-visualizer/internal/service" + "github.com/NexzaDev/attackpath-visualizer/tui" +) + +func main() { + args := os.Args[1:] + launch, options, dbPath, err := launcher.ParseLaunchArgs(args) + if err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(2) + } + if launch { + options.EnvUI = os.Getenv("ATTACKPATH_VISUALIZER_UI") + options.Saved = launcher.ReadPreference() + options.TTY = launcher.InteractiveStdin() + options.Headless = launcher.Headless() || os.Getenv("CI") != "" + if os.Getenv("CI") != "" { + options.NoPrompt = true + } + decision, decideErr := launcher.Decide(options) + if decideErr != nil { + fmt.Fprintln(os.Stderr, "error:", decideErr) + os.Exit(2) + } + if decision.Prompt { + decision.Mode, err = launcher.Prompt(os.Stdin, os.Stdout, options.Saved) + if err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(2) + } + } + if decision.Message != "" { + fmt.Fprintln(os.Stderr, decision.Message) + } + if decision.Chooser { + err = launchChooser(dbPath) + } else if decision.Mode == "tui" { + err = tui.Run(dbPath) + } else { + err = launchGUI(dbPath) + } + if err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } + return + } + if err := run(args, os.Stdout, os.Stderr); err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} + +func run(args []string, stdout, stderr io.Writer) error { + if len(args) == 0 { + args = []string{"help"} + } + if args[0] == "--version" || args[0] == "version" { + fmt.Fprintf(stdout, "%s %s\n", meta.Name, meta.Version) + return nil + } + if args[0] == "--help" || args[0] == "help" { + printHelp(stdout) + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if args[0] == "about" { + fmt.Fprintf(stdout, "%s\nVersion: %s\nLicense: %s\n%s\nRepository: %s\nBuild: %s/%s; Go %s\n", meta.Name, meta.Version, meta.License, meta.Copyright, meta.Repository, runtime.GOOS, runtime.GOARCH, runtime.Version()) + return nil + } + if args[0] == "diagnostics" { + fmt.Fprintf(stdout, "App: %s\nVersion: %s\nOS/architecture: %s/%s\nGo runtime: %s\nConfiguration: local SQLite; no credentials configured\n", meta.Name, meta.Version, runtime.GOOS, runtime.GOARCH, runtime.Version()) + return nil + } + if args[0] == "config" { + if len(args) != 2 || args[1] != "reset-ui" { + return errors.New("usage: attackpath-visualizer config reset-ui") + } + if err := launcher.SavePreference(""); err != nil { + return err + } + fmt.Fprintln(stdout, "Saved launch preference cleared.") + return nil + } + if args[0] == "notifier" { + return runNotifier(args[1:], stdout) + } + fs := flag.NewFlagSet(args[0], flag.ContinueOnError) + fs.SetOutput(stderr) + dbPath := fs.String("db", "", "SQLite database path") + jsonOutput := fs.Bool("json", false, "write machine-readable JSON") + formatOutput := fs.String("format", "markdown", "report format: markdown or json") + confirmImport := fs.Bool("yes", false, "confirm replacing the stored graph during import") + if err := fs.Parse(args[1:]); err != nil { + return err + } + if args[0] != "import" && fs.NArg() != 0 { + return fmt.Errorf("unexpected arguments: %s", strings.Join(fs.Args(), " ")) + } + path, err := config.DatabasePath(*dbPath) + if err != nil { + return err + } + store, err := repository.Open(path) + if err != nil { + return err + } + defer store.Close() + app := service.Service{Store: store} + graph, err := store.Graph(ctx) + if err != nil { + return err + } + if len(graph.Assets)+len(graph.Identities) == 0 { + history, historyErr := store.ImportHistory(ctx) + if historyErr != nil { + return historyErr + } + if len(history) == 0 { + if err = app.LoadDemo(ctx); err != nil { + return fmt.Errorf("initialize demo data: %w", err) + } + graph, err = store.Graph(ctx) + if err != nil { + return err + } + } + } + history, err := store.ImportHistory(ctx) + if err != nil { + return err + } + mode := "local data" + if len(history) > 0 && history[0]["source"] == "demo fixture" { + mode = "demo data" + } + switch args[0] { + case "overview": + summary, err := app.Overview(ctx) + if err != nil { + return err + } + return printValue(stdout, *jsonOutput, map[string]any{"mode": mode, "assets": len(graph.Assets), "identities": len(graph.Identities), "relationships": len(graph.Edges), "paths": summary.Paths, "paths_by_impact": summary.PathsByImpact, "confidence_distribution": summary.Confidence, "remediation": summary.Remediation}) + case "assets": + return printValue(stdout, *jsonOutput, graph.Nodes()) + case "paths": + if len(graph.Assets)+len(graph.Identities) == 0 { + return errors.New("no graph nodes are available") + } + analysis, err := app.Analyze(ctx, 8, 100) + if err != nil { + return err + } + return printValue(stdout, *jsonOutput, analysis.Paths) + case "remediation": + analysis, err := app.Analyze(ctx, 16, 1000) + if err != nil { + return err + } + return printValue(stdout, *jsonOutput, analysis.Remediation) + case "report": + format := *formatOutput + if *jsonOutput { + format = "json" + } + data, err := app.RenderReport(ctx, format) + if err != nil { + return err + } + _, err = stdout.Write(data) + return err + case "import": + if fs.NArg() > 1 { + return fmt.Errorf("import accepts at most one file argument, got %d", fs.NArg()) + } + input := io.Reader(os.Stdin) + if len(graph.Assets)+len(graph.Identities) > 0 && !*confirmImport { + if !launcher.InteractiveStdin() { + return errors.New("import replaces the current graph; pass --yes to confirm in non-interactive use") + } + fmt.Fprint(stdout, "Import replaces the current graph. Continue? [y/N]: ") + confirmationReader := bufio.NewReader(os.Stdin) + answer, readErr := confirmationReader.ReadString('\n') + if fs.NArg() == 0 { + input = confirmationReader + } + if readErr != nil && readErr != io.EOF { + return fmt.Errorf("read import confirmation: %w", readErr) + } + if !strings.EqualFold(strings.TrimSpace(answer), "y") && !strings.EqualFold(strings.TrimSpace(answer), "yes") { + fmt.Fprintln(stdout, "Import cancelled.") + return nil + } + } + if file := fs.Arg(0); file != "" { + f, openErr := os.Open(file) + if openErr != nil { + return openErr + } + defer f.Close() + input = f + } + if err := app.Import(ctx, input, "user import"); err != nil { + return err + } + fmt.Fprintln(stdout, "Import validated and saved.") + return nil + case "export": + return printValue(stdout, true, graph) + default: + return fmt.Errorf("unknown command %q; run 'attackpath-visualizer help'", args[0]) + } +} + +func runNotifier(args []string, stdout io.Writer) error { + if len(args) == 0 { + return errors.New("usage: attackpath-visualizer notifier run|install|uninstall|status") + } + switch args[0] { + case "install": + flags := flag.NewFlagSet("notifier install", flag.ContinueOnError) + flags.SetOutput(os.Stderr) + dbPath := flags.String("db", "", "SQLite database path") + if err := flags.Parse(args[1:]); err != nil { + return err + } + if flags.NArg() != 0 { + return fmt.Errorf("unexpected notifier install arguments: %s", strings.Join(flags.Args(), " ")) + } + executable, err := os.Executable() + if err != nil { + return fmt.Errorf("find application executable: %w", err) + } + resolvedDB, err := config.DatabasePath(*dbPath) + if err != nil { + return err + } + if _, err = os.Stat(resolvedDB); err != nil { + return fmt.Errorf("initialize the local database before installing background notifications: %w", err) + } + path, err := notifier.Install(executable, resolvedDB) + if err != nil { + return err + } + fmt.Fprintf(stdout, "Opt-in background notifier installed at %s. It reads the local database and makes no network calls.\n", path) + return nil + case "uninstall": + path, err := notifier.Uninstall() + if err != nil { + return err + } + fmt.Fprintf(stdout, "Background notifier entry removed: %s\n", path) + return nil + case "status": + path, enabled, err := notifier.Status() + if err != nil { + return err + } + state := "disabled" + if enabled { + state = "installed" + } + fmt.Fprintf(stdout, "Notifier %s · %s\n", state, path) + return nil + case "run": + flags := flag.NewFlagSet("notifier run", flag.ContinueOnError) + flags.SetOutput(os.Stderr) + dbPath := flags.String("db", "", "SQLite database path") + if err := flags.Parse(args[1:]); err != nil { + return err + } + if flags.NArg() != 0 { + return fmt.Errorf("unexpected notifier arguments: %s", strings.Join(flags.Args(), " ")) + } + return notifier.RunUntilSignal(*dbPath) + default: + return fmt.Errorf("unknown notifier action %q; use run, install, uninstall, or status", args[0]) + } +} + +func printValue(w io.Writer, jsonOutput bool, value any) error { + if jsonOutput { + encoder := json.NewEncoder(w) + encoder.SetIndent("", " ") + return encoder.Encode(value) + } + data, err := json.MarshalIndent(value, "", " ") + if err != nil { + return err + } + _, err = fmt.Fprintln(w, string(data)) + return err +} + +func printHelp(w io.Writer) { + fmt.Fprintf(w, "%s %s\n%s\n\nUsage: attackpath-visualizer [options]\n\nCommands:\n overview Summarize local demo or imported data\n paths List ranked potential paths\n remediation Rank path-breaking relationship suggestions\n report Write a JSON or Markdown analysis report\n assets List inventoried assets and identities\n import [file] Import a graph JSON file or stdin\n export Export the stored graph as JSON\n about Show version and project information\n diagnostics Show a sanitized local runtime report\n notifier Run or manage the opt-in background notifier\n config reset-ui Clear the remembered launcher choice\n help Show this help\n\nOptions: --db PATH, --json, --format markdown|json (report), --yes (confirm graph replacement)\n", meta.Name, meta.Version, meta.Purpose) +} diff --git a/cmd/attackpath-visualizer/main_test.go b/cmd/attackpath-visualizer/main_test.go new file mode 100644 index 0000000..91e242b --- /dev/null +++ b/cmd/attackpath-visualizer/main_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "bytes" + "encoding/json" + "path/filepath" + "strings" + "testing" +) + +func TestAnalysisCommandsUseStoredGraph(t *testing.T) { + database := filepath.Join(t.TempDir(), "cli.db") + var output bytes.Buffer + if err := run([]string{"remediation", "--db", database, "--json"}, &output, &output); err != nil { + t.Fatal(err) + } + var remediation struct { + Suggestions []struct { + EdgeID string `json:"edge_id"` + PathsAffected int `json:"paths_affected"` + } `json:"suggestions"` + } + if err := json.Unmarshal(output.Bytes(), &remediation); err != nil { + t.Fatal(err) + } + if len(remediation.Suggestions) == 0 || remediation.Suggestions[0].EdgeID == "" || remediation.Suggestions[0].PathsAffected == 0 { + t.Fatalf("remediation command returned no ranked choke points: %s", output.String()) + } + + output.Reset() + if err := run([]string{"report", "--db", database, "--format", "markdown"}, &output, &output); err != nil { + t.Fatal(err) + } + for _, expected := range []string{"Ranked paths", "Ranked remediation suggestions", "demo://"} { + if !strings.Contains(output.String(), expected) { + t.Errorf("Markdown report omitted %q", expected) + } + } + + output.Reset() + if err := run([]string{"report", "--db", database, "--json"}, &output, &output); err != nil { + t.Fatal(err) + } + var report struct { + PathCount int `json:"path_count"` + } + if err := json.Unmarshal(output.Bytes(), &report); err != nil { + t.Fatal(err) + } + if report.PathCount == 0 { + t.Fatal("JSON report has no paths") + } +} diff --git a/cmd/render-screenshots/main.go b/cmd/render-screenshots/main.go new file mode 100644 index 0000000..0525b93 --- /dev/null +++ b/cmd/render-screenshots/main.go @@ -0,0 +1,22 @@ +//go:build !nogui + +package main + +import ( + "flag" + "fmt" + "os" + + "fyne.io/fyne/v2/test" + "github.com/NexzaDev/attackpath-visualizer/gui" +) + +func main() { + output := flag.String("out", "artifacts/ui", "screenshot output directory") + flag.Parse() + application := test.NewApp() + if err := gui.RenderScreenshots(*output, application); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..97ed225 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,13 @@ +# Architecture + +The application is local-first. `internal/domain` validates assets and directed edges and enumerates bounded simple paths. The score is maximum impact (1–5) multiplied by compounded edge confidence (0–100); score components are retained as an explanation. `internal/service` applies input size limits and coordinates imports. `internal/repository` owns SQLite schema initialization, indexed adjacency columns, atomic graph replacement, and import history. `cmd/attackpath-visualizer` is the CLI boundary. + +Data flows from a JSON fixture or authorized JSON import through validation, into a single SQLite transaction, then back into graph queries and JSON/text output. SQLite uses WAL mode, a five-second busy timeout, a single connection per process, and foreign-key references. The database is created under the user's configuration directory with a private parent directory. The engine has no listener and no external service dependencies. + +The desktop and terminal interfaces are planned as separate front ends calling the same service. The CLI currently forms the implemented UI. The graph source/evidence fields are user-provided data and are not trusted as evidence of exploitability. Imports are bounded to 8 MiB and invalid data is rejected before stored state is changed. + +## Decisions + +- Go is the application language; `modernc.org/sqlite` provides a pure-Go SQLite driver to avoid a required C compiler for CLI builds. +- Directed simple paths are enumerated to bounded depth and count; cycles are suppressed per traversal. The current demo graph and realistic small inventories fit this model. A large-graph indexing/benchmark plan remains on the roadmap. +- No HTTP API is exposed. The interactive local clients need no listener, authentication surface, or network policy. diff --git a/docs/LICENSES.md b/docs/LICENSES.md new file mode 100644 index 0000000..8b8c9ea --- /dev/null +++ b/docs/LICENSES.md @@ -0,0 +1,160 @@ +# Offline dependency and asset licenses + +The following full license texts apply to bundled direct dependencies, fonts, and the manually included `modernc.org/mathutil v1.6.0` transitive license. The final release archive also contains license texts for the other transitive Go modules discovered by `go-licenses` for that platform's build. + +## modernc mathutil — BSD 3-Clause (transitive) + +Copyright (c) 2014 The mathutil Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the names of the authors nor the names of the +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +## Fyne — BSD 3-Clause + +BSD 3-Clause License + +Copyright (C) 2018 Fyne.io developers (see AUTHORS) +All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Fyne.io nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +## modernc SQLite — BSD 3-Clause + +Copyright (c) 2017 The Sqlite Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +## beeep — MIT + +Copyright (c) 2017, Milan Nikolic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +## Noto Sans — SIL Open Font License 1.1 + +—————————————————————————————- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +—————————————————————————————- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. + +DEFINITIONS +“Font Software” refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. + +“Reserved Font Name” refers to any names specified as such after the copyright statement(s). + +“Original Version” refers to the collection of Font Software components as distributed by the Copyright Holder(s). + +“Modified Version” refers to any derivative made by adding to, deleting, or substituting—in part or in whole—any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +“Author” refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. + +5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md new file mode 100644 index 0000000..ec2cca3 --- /dev/null +++ b/docs/RELEASE_NOTES.md @@ -0,0 +1,11 @@ +# AttackPath Visualizer v0.1.0-dev (dev beta) + +This is an early development pre-release. Not every planned feature is present, and the GUI packages have not been opened on physical Windows, macOS, or Linux machines. Review the README and offline Usage guide before importing real inventory. Potential paths are prioritization leads, not proof of exploitability. + +The release contains native GUI packages for Linux x64, macOS ARM64, and Windows x64, plus a `SHA256SUMS` file covering each package. The Windows package is a ZIP containing the GUI executable and required license files. Builds are unsigned and not notarized. + +- **macOS:** Gatekeeper may warn. Verify the checksum, then right-click the app and choose **Open** the first time. +- **Windows:** SmartScreen may warn. Verify the checksum, then choose **More info → Run anyway** only if you trust the downloaded package. +- **Linux:** Extract the archive, verify the checksum, and run `chmod +x ` if the executable bit was not preserved. + +Import only inventory you are authorized to use. Export a backup before replacing stored graph data. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..bb4c4b4 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,47 @@ +# Release procedure + +The repository provides two separate release paths. **Beta release** is triggered by pushing a new `v*` tag and publishes a public pre-release. **Release packages** is a manual workflow that attaches packages to a draft pre-release and never publishes it automatically. Both use native operating-system runners and pin `fyne.io/tools/cmd/fyne` to `v1.7.4`, which includes newer `golang.org/x/tools` support required by the configured Go toolchain. `cmd/attackpath-visualizer/FyneApp.toml` must place app fields under `[Details]`; its icon path is resolved relative to the app metadata. + +The Ubuntu GUI prerequisite list comes from the Fyne v2.6.3 upstream `.github/workflows/platform_tests.yml`: `bc`, `gcc`, `libgl1-mesa-dev`, `libwayland-dev`, `libx11-dev`, `libxkbcommon-dev`, `xorg-dev`, `xvfb`, and `language-pack-en`. + +## Public dev-beta release + +Only tag a commit after CI has passed on Linux, macOS, and Windows and the Linux race detector is green. The tag workflow independently runs `go test ./...` and `go vet ./...` on each native runner before packaging. It verifies the app icon and package contents, uploads matrix artifacts, creates `SHA256SUMS`, then publishes a public GitHub pre-release. + +For the initial release, use tag `v0.1.0-dev` on the verified PR head. Never force-update or reuse a tag. The publishing job checks that the tag resolves to the workflow commit and fails if a release with that tag already exists. If any package job fails, follow the project release instructions: remove a failed release and tag before pushing a corrected tag; do not bypass a failing check. + +Expected public assets: + +- `attackpath-visualizer-linux-x64.tar.gz` +- `attackpath-visualizer-macos-arm64.tar.gz` +- `attackpath-visualizer-windows-x64.zip` (contains the GUI executable and required license files) +- `SHA256SUMS` (checksums for all three packages) + +Each GUI package includes the app and custom icon plus `LICENSE`, `THIRD_PARTY_NOTICES.md`, `licenses/`, README, and offline Usage documentation. The package job validates the icon resource and required license files before upload. The Windows archive is used so the executable and licenses travel together. + +After publication, inspect the GitHub Release page and confirm the **Pre-release** badge, title `AttackPath Visualizer v0.1.0-dev (dev beta)`, all four asset names, plausible non-zero sizes, and checksum lines. Download each package on a supported machine, run `sha256sum -c SHA256SUMS`, inspect its contents, and record actual test results. Do not claim a package was opened on an OS unless it was actually run there. + +## Manual draft release from a phone or desktop + +The **Release packages** workflow is manual-only and must be present on the default branch before GitHub makes it dispatchable. Use this path to prepare a reviewable draft without publishing it: + +1. Open `NexzaDev/attackpath-visualizer` in GitHub or its mobile browser and select **Actions**. +2. Choose **Release packages**. If it is absent, it is not present/enabled on the default branch. +3. Select **Run workflow**, choose `main`, and confirm. +4. Wait for the Windows x64, macOS ARM64, Linux x64, and draft-attachment jobs to finish. Any failed/cancelled job means its package was not produced. +5. Review the draft **AttackPath Visualizer v0.1.0-dev (dev beta)**, expected package names, `SHA256SUMS`, and release notes. Check the package contents and checksums before manually publishing. +6. The workflow never publishes the draft automatically. Publish only after review and maintainer approval. + +## Unsigned build warnings + +Packages are unsigned and macOS builds are not notarized. Verify checksums before opening downloaded files. + +- **macOS:** Gatekeeper may warn. Right-click the app and choose **Open** the first time. +- **Windows:** SmartScreen may warn. Choose **More info → Run anyway** only if you trust the package and verified its checksum. +- **Linux:** Extract the archive and run `chmod +x ` if necessary. + +No signing key or notarization credentials are used. + +## Verification limits + +A green runner proves the commands completed on that runner; it does not prove installation or runtime behavior on a physical desktop. Record the actual workflow URL, commit, assets, sizes, checksums, and any failed-to-start jobs. macOS x64 is not included until a supported Intel runner is available. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..2cdd203 --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,8 @@ +# Roadmap + +1. **Local graph core and CLI** — graph validation, bounded explainable path scoring, local SQLite persistence, versioned SQL migrations, JSON import/export, import history, and deterministic offline demo data are implemented in this branch. Unit and cross-platform integration evidence is pending CI. +2. **Native desktop and terminal front ends** — Fyne dashboard, terminal menu, chooser, graph/path/evidence/remediation workflows, imports/reports/settings, accessibility aids, offline About/diagnostics, custom icon/theme, and headless screenshot capture are implemented in this branch. Native builds, screenshots, and desktop runtime behavior are not verified until CI and real-device checks complete. +3. **Notifications and releases** — in-app rules and event history, opt-in read-only background notifier, platform startup entries, and manually triggered draft-release packaging are implemented in this branch. Notification delivery, release packages, and real platform behavior remain unverified until workflow runs and package review. +4. **Scale and operability** — benchmark documented workloads, improve large graph traversal and table responsiveness, broaden import formats only with complete validation/fixtures, and record user feedback. + +Completion evidence is recorded in CI and the pull request body. Do not treat code presence or source inspection as proof of builds, tests, package outputs, screenshot quality, or runtime behavior. diff --git a/docs/SPECIFICATION.md b/docs/SPECIFICATION.md new file mode 100644 index 0000000..13f06bd --- /dev/null +++ b/docs/SPECIFICATION.md @@ -0,0 +1,545 @@ +# AttackPath-Visualizer — Exposure Relationship Graph + +**Repository:** `attackpath-visualizer` + +**GitHub description:** A defensive graph-analysis tool that connects assets, identities, misconfigurations, and exposure findings to explain potential attack paths. + +## Language stack + +| Layer | Choice | Responsibility | +|---|---|---| +| Core/backend | Go | Domain logic, performance-sensitive work, APIs, integrations, and background tasks | +| Interface | Go CLI/TUI + native desktop dashboard GUI with Fyne (required) | Native desktop application plus terminal UI, chosen at launch; no browser frontend | +| Persistence | SQLite with indexed relational tables and adjacency lists | Durable application data and queryable history | + +Go owns ingestion, graph query orchestration, explainable scoring, and APIs. SQLite stores relationships; the terminal UI renders paths. + +## What this repository is + +This README contains the project specification and the complete prompt intended for an AI coding agent. It does not claim the application has already been implemented. + +## Product scope + +Build graph-based risk exploration that ingests synthetic or authorized inventory, models assets and relationships, computes explainable potential paths, ranks them by impact/confidence, and links edges to source evidence. Include demo data and remediation suggestions without executing attacks. + +## Non-negotiable delivery constraints + +- This is **not a website, web app, SaaS product, or hosted dashboard**. Do not create a browser frontend, React app, or public-facing web server. +- Deliver a local-first application with two front ends over one service layer: a polished **native desktop dashboard GUI** and a **CLI/TUI**, chosen at launch. No website or browser frontend. Any optional listener must be disabled by default and bind to loopback only unless explicitly configured. +- The complete core workflow must run for **€0** on a normal developer computer. Use free/open-source tools and libraries, with no required paid API keys, subscriptions, cloud accounts, hosted databases, or commercial services. +- Default to local files and SQLite where persistence is needed. External integrations must be optional adapters, never required for core functionality; provide fixtures and a fully usable offline/demo mode. +- Do not require paid CI, hosting, domains, premium IDEs, or paid threat-intelligence feeds. Document optional free-tier limits honestly and never make a free-tier account mandatory. +- Use a free, OS-supported build/test workflow. State the exact local prerequisites and commands needed to build, test, and run the project. + +## Cross-platform and product-quality requirements + +- **Supported operating systems:** Linux, macOS, and Windows. The project must have documented build, test, and run instructions for all three, including architecture-specific notes where relevant. +- **Fast, suitable implementation languages:** Go is the default for network tools, collectors, services, and concurrent workloads; Rust is preferred for memory-sensitive, parsing-heavy, or performance-critical components. Do not use Python as the main implementation language. Use it only for optional developer scripts if there is a clear reason. +- **No website:** Do not create a website, hosted dashboard, SaaS product, browser frontend, or public web server. This is a local application/tool. +- **Professional interface:** Provide a polished CLI/TUI with consistent command naming, useful help, clear errors, structured output, progress indicators, and accessible color handling, and a required native desktop dashboard GUI built with Fyne, not a browser-based UI. Follow the mandatory desktop application UI section for the launcher, navigation, icons, About, and design rules. Visual tools must have a real interface, not just a placeholder screen. +- **Distinctive, production-quality UX:** Use a coherent design system, deliberate spacing and typography, restrained colors, meaningful empty/loading/error/success states, keyboard navigation, sensible defaults, accessible contrast, responsive layouts, and realistic sample data. Avoid generic AI-generated dashboard templates, gratuitous gradients, meaningless charts, fake metrics, placeholder buttons, lorem ipsum, and decorative features that do not work. +- **Real functionality only:** Every visible control must work. Use representative local fixtures for demos; label demo data clearly. Do not invent integrations, results, benchmarks, or completed tests. +- **Cross-platform verification:** CI must build and test on Linux, macOS, and Windows where supported. Use portable filesystem paths, signal handling, process management, permissions, and networking APIs. Test path handling and platform-specific behavior. Do not claim a platform is supported until its build/test path is documented and verified. +- **€0 operation:** Core functionality must run locally using free/open-source dependencies without paid API keys, subscriptions, cloud accounts, hosted databases, domains, or commercial services. External integrations are optional and must have an offline/demo alternative. +- **Performance discipline:** Profile before optimizing; use bounded concurrency, cancellation, timeouts, streaming for large inputs, and benchmarks for genuinely hot paths. Avoid unnecessary allocations and heavyweight dependencies, but do not trade correctness or maintainability for synthetic benchmark numbers. +- **No source-code comments:** Keep source files free of comments as requested. Express design intent through clear names, small cohesive modules, tests, and documentation outside source files. +- **No AI slop:** Do not fabricate features or inflate scope/LOC. Prefer a small set of complete, tested workflows over many incomplete screens. Use consistent naming, idiomatic language patterns, explicit error handling, deterministic tests, dependency/license review, and a clean release process. + +## Product polish, branding, and support features + +- **Custom icon and identity:** Create an original project-specific application icon (required; no generic placeholder). Provide editable SVG source artwork plus platform assets (Windows `.ico`, macOS `.icns`, Linux SVG/PNG and desktop-entry assets) and use it for the window, taskbar or dock, packaging metadata, and About. Do not use third-party trademarks. +- **Source access:** GUI applications must have a visible **Source Code** action in About that opens the real public GitHub repository URL configured for the project. Keep the URL in one central metadata/config location. If it is not configured, show an honest fallback rather than a fabricated URL. CLI-only tools must provide an `about` command with version, license, project URL when configured, OS and build details. +- **About page/dialog:** Every GUI application must include an About screen/dialog showing app name, icon, version, purpose, license, maintainer/copyright only when known, repository link, dependency notices, and build/runtime information where useful. Include a **“Found a bug? Please report it on GitHub.”** action that opens the repository issue tracker when configured. Never fabricate repository URLs. +- **Support and diagnostics:** Include a previewable, copyable diagnostic report with app version, OS, architecture, runtime/build versions and sanitized configuration status. Do not include credentials, tokens, personal file contents, or sensitive host/network data by default. +- **Useful product features:** Contextual help, searchable help for complex tools, keyboard shortcuts, copy/export actions, safe settings defaults, first-run guidance, actionable errors, cancellation, confirmation for destructive actions, and clear empty/loading/error/success states. +- **Accessibility:** Keyboard navigation, readable contrast, scalable text, visible focus indicators, and screen-reader labels where supported. Do not rely on color alone to communicate severity. +- **Security and privacy:** No telemetry by default. Disclose external network requests, redact secrets from logs, use OS-appropriate config directories and restrictive permissions, and provide dry-run mode for potentially disruptive operations. +- **Release quality:** Versioning, changelog, checksums and signed release artifacts where feasible with free tools, reproducible build guidance, dependency/license inventory, uninstall/reset instructions, and platform-specific troubleshooting. +- **Honest completeness:** No fake buttons, fake charts, fabricated performance numbers, placeholder links, or screens disconnected from real functionality. Label demo data clearly and omit features that are not implemented. + +## Application interface: native desktop dashboard and terminal UI + +AttackPath Visualizer ships as one local application with two front ends over the same service layer: a native desktop dashboard with a graph workspace (built with Fyne) and a terminal UI. At launch the user chooses which one to open. There is no website, browser frontend, or hosted service. The full rules are in the mandatory desktop application UI section of the prompt below. + +| Category | Icon (Lucide-style name) | What it shows | +|---|---|---| +| Overview | `layout-dashboard` | Exposure summary: potential paths by impact tier, top-ranked paths, choke points, import freshness | +| Graph | `waypoints` | Interactive relationship graph of assets and edges with pan, zoom, filter, and focus | +| Paths | `route` | Ranked potential paths with an explainable score breakdown | +| Assets | `server` | Asset inventory and relationships | +| Evidence | `file-search` | Source evidence behind every edge | +| Remediation | `wrench` | Ranked suggestions, for example the edge whose removal breaks the most paths | +| Imports | `upload` | Ingestion history, validation results, demo-data label | +| Reports | `file-text` | Exported path and remediation reports | +| About | `info` | App identity, offline Usage guide, Source Code, bug reporting | +| Settings | `settings-2` | Appearance, density, launch preference, data location, safe defaults | + +## Engineering quality, correctness, and release gates + +- **No promise of zero bugs:** Software cannot be guaranteed bug-free. The engineering process must systematically reduce defects, catch regressions, and document known limitations instead of claiming perfection. +- **Requirements before implementation:** Convert every feature into acceptance criteria and test cases. Keep a traceable checklist linking requirements to code, tests, documentation, and release status. +- **Small, complete increments:** Implement vertical slices that compile and work end-to-end. Do not generate the whole application in one unverified pass or leave placeholder modules and stubbed workflows. +- **Compile and test continuously:** After each meaningful change, run formatter, compiler, static analysis/linter, unit tests, integration tests, and the relevant platform build. Fix failures before moving forward; never suppress a failure just to get a green result. +- **Defensive engineering:** Validate all external input, handle malformed files and partial network failures, set explicit timeouts, cancel work cleanly, bound concurrency and memory, avoid races, and return actionable errors. Never silently swallow errors. +- **Test design:** Cover normal behavior, boundary cases, invalid input, empty input, large inputs, permission failures, cancellation, timeouts, corrupt state, offline mode, and regression cases. Use deterministic tests, fixtures, fuzz/property testing where appropriate, and race/concurrency checks for Go or Rust tools as applicable. +- **Cross-platform correctness:** Build and test on Linux, macOS, and Windows. Test paths, permissions, signals, line endings, process handling, sockets, and packaging on the actual target platforms. If a platform cannot be tested, disclose it instead of claiming full verification. +- **Security assurance:** Perform threat modeling, dependency vulnerability review, secret scanning, static analysis, safe parsing, least-privilege design, secure defaults, and checks for path traversal, command injection, unsafe deserialization, data leakage, and unintended network exposure. +- **Performance validation:** Set realistic performance goals and benchmark representative workloads with reproducible commands and hardware/context notes. Profile bottlenecks before optimization. Never invent benchmark numbers or sacrifice correctness for synthetic speed. +- **Code review and maintainability:** Use idiomatic Go/Rust, clear module boundaries, explicit ownership and error contracts, minimal dependencies, no dead code, no duplicated logic, no unexplained magic values, and no artificial LOC padding. Source code must contain no comments as requested; use descriptive names, tests, and external docs. +- **Release blocking gates:** A release must not be marked ready if required builds/tests/lints/security checks fail, core flows are untested, documentation is inconsistent, or critical/high-severity known defects remain unresolved without explicit risk acceptance. +- **Honest reporting:** Report exactly which commands ran, which platforms were tested, what passed/failed, any skipped checks, known issues, and remaining risks. Never claim a test, scan, benchmark, or build ran unless it actually ran. + +## Proposed codebase layout + +```text +attackpath-visualizer/ +├── README.md +├── LICENSE +├── CONTRIBUTING.md +├── SECURITY.md +├── CODE_OF_CONDUCT.md +├── CHANGELOG.md +├── .editorconfig +├── .gitignore +├── .env.example +├── Makefile +├── cmd/ +│ └── attackpath-visualizer/ +├── internal/ +│ ├── config/ +│ ├── domain/ +│ ├── service/ +│ ├── repository/ +│ ├── transport/ +│ └── observability/ +├── api/ +├── tui/ +│ ├── views/ +│ ├── components/ +│ ├── formatting/ +│ └── tests/ +├── migrations/ +├── tests/ +│ ├── unit/ +│ ├── integration/ +│ └── e2e/ +├── testdata/ +├── scripts/ +├── assets/ +│ ├── icons/ +│ │ ├── icon.svg +│ │ ├── icon.png +│ │ ├── icon.ico +│ │ └── icon.icns +│ └── branding/ +├── docs/ +│ ├── ARCHITECTURE.md +│ ├── THREAT_MODEL.md +│ └── ROADMAP.md +└── .github/ + ├── workflows/ + ├── ISSUE_TEMPLATE/ + └── PULL_REQUEST_TEMPLATE.md +``` + +## Engineering and open-source requirements + +The implementation must include: +- `README.md`, `LICENSE` (MIT, subject to dependency/asset license review), `CONTRIBUTING.md`, `SECURITY.md`, `CODE_OF_CONDUCT.md`, and `CHANGELOG.md`. +- `.github/workflows/` CI for formatting, linting/static analysis, tests, and builds on Linux, macOS, and Windows where supported, plus issue and pull request templates. +- `docs/ARCHITECTURE.md`, `docs/THREAT_MODEL.md`, and `docs/ROADMAP.md`. +- A `Makefile` or equivalent cross-platform task runner, `.editorconfig`, `.gitignore`, `.env.example`, tests, sanitized fixtures, centralized app/repository metadata, and documented release packaging for Linux/macOS/Windows. +- No comments in source code, no hardcoded secrets, no filler code, and no claims of passing tests unless the tests were run. + +## Full prompt for Arena.ai/Agent + +Copy the entire prompt below into Arena.ai/Agent: + +--- + +# AttackPath-Visualizer — Exposure Relationship Graph + +**Suggested GitHub repository:** `attackpath-visualizer` + +**GitHub description:** A defensive graph-analysis tool that connects assets, identities, misconfigurations, and exposure findings to explain potential attack paths. + +## Languages and technology decisions + +- **Primary language:** Go for the core domain, concurrent network work, ingestion, and performance-sensitive processing. Choose Rust instead when memory safety or parsing throughput makes it a better fit. Do not use Python as the core application language. +- **User interface:** Go CLI/TUI + native desktop dashboard GUI with Fyne (required). Build a local application whose front end, desktop dashboard or terminal UI, is chosen at launch; do not build a website, browser frontend, SaaS, or hosted service. +- **Persistence:** SQLite with indexed relational tables and adjacency lists. +- **Language rationale:** Go owns ingestion, graph query orchestration, explainable scoring, and APIs. SQLite stores relationships; the terminal UI renders paths. +- Prefer compiled, statically typed, performance-conscious code for the core. Do not make Python the primary application language. Python may be used only for a clearly justified auxiliary script or offline experiment; it must not be required to run the main product. +- Choose mature, maintained libraries rather than writing cryptography, protocol implementations, parsers, or database abstractions from scratch. +- Pin or bound dependencies, explain major choices, and avoid adding frameworks or dependencies without a concrete need. + +## Your role + +Act as a principal software engineer, systems architect, cybersecurity specialist, network engineer, performance engineer, QA lead, and open-source maintainer. Work with the discipline expected of a production engineering team. Be persistent and confident, but prove progress with working code, measured behavior, reproducible tests, and accurate documentation. The goal is a high-quality open-source project, not an impressive-looking scaffold. + +## Product mission + +Build graph-based risk exploration that ingests synthetic or authorized inventory, models assets and relationships, computes explainable potential paths, ranks them by impact/confidence, and links edges to source evidence. Include demo data and remediation suggestions without executing attacks. + +## Mandatory product constraints: no website and €0 operating cost + +- Do not build a website, web application, browser frontend, SaaS, or hosted service. The deliverable is a local application with a native desktop dashboard GUI and a CLI/TUI, built only with free tools. +- All essential functionality must work locally for €0. Do not require paid APIs, paid cloud services, subscriptions, commercial databases, paid scanners, paid feeds, or paid developer tools. +- Use free/open-source dependencies and local storage (SQLite/files) by default. Optional integrations must have an offline alternative using documented fixtures; never make credentials mandatory for the basic workflow. +- Do not make the user deploy or host anything. No required Docker image registry, domain, VPS, cloud account, or externally hosted service. +- If a local HTTP endpoint is genuinely necessary for an integration, it must be optional, disabled by default, and bind to 127.0.0.1 by default. Prefer CLI/TUI interaction over HTTP. +- Document a zero-cost setup, build, test, and run path. Be explicit about optional integrations and any limits of free tiers. + +## Mandatory cross-platform, professional UX, and zero-cost constraints + +1. Support **Linux, macOS, and Windows**. Provide exact build, test, package, and run commands for each OS. Add CI jobs for all three platforms where technically supported, and report platform gaps honestly. +2. Use **Go** as the default primary language for network/security tooling and concurrent collectors. Use **Rust** when memory safety, parsing throughput, or performance makes it the better fit. Python must not be the core application language. Do not add multiple languages without a clear architectural reason. +3. Do not build a website, browser frontend, SaaS, hosted service, or public web server. Deliver a local-first application with a professional CLI/TUI and a required cross-platform **native desktop dashboard GUI** (Fyne); do not use a browser-based UI. +4. The UI must look intentionally designed and production-ready: consistent typography and spacing, a restrained palette, clear hierarchy, useful navigation, keyboard support, accessible contrast, real loading/empty/error/success states, useful filtering/search, and coherent interactions. Avoid generic AI dashboard templates, gratuitous gradients, fake charts/metrics, lorem ipsum, placeholder buttons, and visual clutter. +5. Every visible control must perform a real action. Demo data must be clearly labeled. All core workflows must work offline with local files/SQLite and included fixtures. Do not require paid API keys, paid services, subscriptions, cloud accounts, hosting, domains, or a hosted database. +6. Performance must be demonstrated with reproducible benchmarks and realistic workloads, not unsupported speed claims. Use bounded concurrency, cancellation, timeouts, streaming for large inputs, and profiling where appropriate. +7. Use portable filesystem, process, signal, permission, and networking behavior. Add tests for Windows path semantics and platform-specific code. Do not claim OS support until the relevant build/test workflow passes. +8. No source-code comments, no hardcoded secrets, no fabricated capabilities, no fake test results, and no artificial LOC padding. Prefer fewer complete features with high reliability over a large number of unfinished features. +9. Include an accessible local demo mode, deterministic fixtures, dependency and license review, release packaging instructions for Linux/macOS/Windows, and clear troubleshooting docs. +10. The core workflow must cost **€0**. Optional external integrations must be clearly marked optional and must have a usable offline alternative. + +## Mandatory application identity, About, source, and reporting features + +1. Create a **custom original application icon** for this project (required). Supply editable SVG source and platform assets: `.ico` for Windows, `.icns` for macOS, and SVG/PNG plus desktop-entry integration for Linux. No generic placeholder icon or third-party trademark. +2. Every GUI application must include an **About** screen/dialog accessible from the main menu or settings. Show app name, icon, version, purpose, license, maintainer/copyright only when known, build/runtime details where useful, and dependency/license notices. +3. Add a **Source Code** action in About that opens the actual GitHub repository URL configured for the project. Add a separate **“Found a bug? Please report it on GitHub.”** action that opens the repository issue tracker/new-issue page when configured. Store URLs centrally. Never invent or hardcode a fake URL; if the repository is not configured, show an honest fallback and disable the external action. +4. For CLI-only tools, provide an `about` command displaying name, version, license, repository URL if configured, OS/architecture, and build information. Provide `--help`, `--version`, stable exit codes, and machine-readable JSON output where useful. +5. Include a safe **Copy diagnostic report** feature for GUI apps and a `diagnostics` command for CLI tools. Preview before saving/copying. Include app version, OS/architecture, runtime/build details and sanitized settings status only. Never include secrets, tokens, personal file contents, or sensitive network data by default. +6. Add contextual help, searchable help where useful, keyboard shortcuts, copy/export, safe settings defaults, first-run guidance, actionable errors with next steps, cancellation, and confirmation for destructive actions. +7. No telemetry or analytics by default. Disclose external network requests, redact secrets from logs, use OS-appropriate config directories and restrictive file permissions, and provide dry-run mode for risky operations. +8. Every UI action must have real behavior and tests. No decorative controls, fake metrics, placeholder links, fabricated test results, or UI shell disconnected from functionality. +9. Add version/changelog and platform-specific install, upgrade, uninstall, reset, and troubleshooting instructions. Provide checksums and signed artifacts where feasible using free tools. +10. Keep all existing constraints: Linux/macOS/Windows support, high-performance Go/Rust core, no website/browser frontend, no required paid services, €0 core operation, no source-code comments, MIT license, SECURITY.md, CONTRIBUTING.md, tests, and professional visual design. + +## Mandatory professional engineering workflow: correctness first + +1. Do not attempt to generate the entire product in one pass. First write requirements, acceptance criteria, threat model, architecture decisions, and a prioritized implementation plan. Then implement small, complete, testable increments. +2. Before each feature is considered complete, ensure it compiles, passes its tests, handles failure cases, is documented, and works end-to-end. No TODO-only implementation, fake functionality, empty handlers, stubbed return values, or buttons that only look functional. +3. Maintain a requirements-to-tests checklist. Every requirement must map to an implementation and a test, or be explicitly marked out of scope. Add regression tests for every discovered bug. +4. Run and fix the full relevant quality suite: formatter, compiler/build, linter/static analysis, unit tests, integration tests, end-to-end tests where appropriate, dependency audit, secret scan, and platform builds. Do not suppress warnings/errors just to make CI pass. +5. Test valid, invalid, empty, boundary, malformed, oversized, interrupted, timed-out, offline, permission-denied, and partial-failure scenarios. Use deterministic fixtures. Add fuzz/property tests for parsers and input-heavy code; use race/concurrency checks where supported. +6. Validate all untrusted inputs and paths. Use timeouts, cancellation, bounded concurrency, explicit resource limits, safe defaults, least privilege, redacted logs, and actionable errors. Do not silently swallow errors or expose secrets in output. +7. Support Linux, macOS, and Windows with actual CI jobs where possible. Test OS-specific path handling, process management, permissions, signals, networking and packaging. State clearly when a platform or check has not been tested. +8. Benchmark only after correctness is established. Include reproducible benchmarks and describe the test workload and environment. Never invent speed claims, coverage percentages, test results, or security scan results. +9. Before release, require passing builds, tests, lint/static analysis and security checks; no unresolved critical/high-severity defects unless explicitly documented with an accepted risk and mitigation. Include release notes, known issues, rollback/recovery guidance, and checksums where feasible. +10. At the end of the work, provide a truthful quality report listing the exact commands run, platforms tested, pass/fail counts, skipped checks, known limitations, and remaining risks. Do not claim “bug-free” or “fully tested” without evidence. +11. Keep all product constraints: high-performance Go/Rust core, professional functional UI, custom icon and About/source/bug-report links, zero-cost local-first core, no website, Linux/macOS/Windows support, no source-code comments, MIT license, SECURITY.md, CONTRIBUTING.md, and well-structured documentation. + +## Required codebase structure + +Use the following as the starting point and adapt it to the application’s real needs. Every included directory must have a real purpose; do not create empty scaffolding. + +```text +attackpath-visualizer/ +├── README.md +├── LICENSE +├── CONTRIBUTING.md +├── SECURITY.md +├── CODE_OF_CONDUCT.md +├── CHANGELOG.md +├── .editorconfig +├── .gitignore +├── .env.example +├── Makefile +├── cmd/ +│ └── attackpath-visualizer/ +├── internal/ +│ ├── config/ +│ ├── domain/ +│ ├── service/ +│ ├── repository/ +│ ├── transport/ +│ └── observability/ +├── api/ +├── tui/ +│ ├── views/ +│ ├── components/ +│ ├── formatting/ +│ └── tests/ +├── migrations/ +├── tests/ +│ ├── unit/ +│ ├── integration/ +│ └── e2e/ +├── testdata/ +├── scripts/ +├── docs/ +│ ├── ARCHITECTURE.md +│ ├── THREAT_MODEL.md +│ └── ROADMAP.md +└── .github/ + ├── workflows/ + ├── ISSUE_TEMPLATE/ + └── PULL_REQUEST_TEMPLATE.md +``` + +### Structural rules +- `cmd/` contains executable entry points only. +- `internal/domain/` contains core models and business rules independent of transport/UI. +- `internal/service/` contains use cases and orchestration. +- `internal/repository/` contains persistence and external data adapters behind clear interfaces. +- `internal/transport/` contains HTTP, CLI, or protocol transport boundaries. +- `tui/` contains the terminal UI and must not duplicate authoritative business rules. +- `api/` contains OpenAPI or protocol definitions where applicable. +- `migrations/` contains versioned database migrations. +- `tests/` contains integration and end-to-end tests; keep unit tests close to their packages if that is idiomatic. +- `testdata/` contains synthetic, sanitized fixtures only. +- `scripts/` contains reproducible developer/CI helpers, not hidden deployment side effects. +- Keep modules cohesive, avoid giant files and circular dependencies, and document deviations from this layout. + +## Mandatory desktop application UI (dashboard), launcher, icon, and About + +This section is mandatory. It overrides any earlier wording that calls the desktop GUI optional or conditional. The dashboard described here is a native window of a local application built with Fyne; it is not a website. Hosted dashboards, browser frontends, and web servers remain forbidden. + +### 1. One application, two front ends, chosen at launch + +- Build one application with two front ends, a native desktop dashboard with a graph workspace and a terminal UI, both calling the same service layer. Neither front end contains business rules. Add `gui/`, `launcher/`, `assets/` (icons, fonts, embedded docs), and one central metadata module `internal/meta/meta.go` next to the existing `tui/` code. +- **Launcher.** Running the application with no arguments must let the user choose how to open it: + - Started from a desktop or start menu (no terminal attached): show a small native chooser window titled "How do you want to open AttackPath Visualizer?" with two clearly labeled choices, **Dashboard (graphical window)** and **Terminal (text interface)**, a **Remember my choice** checkbox, and a Quit button. + - Choosing Terminal opens the platform terminal emulator running the TUI: Windows Terminal with a `cmd.exe` fallback, macOS Terminal via `open`, Linux via `$TERMINAL`, `x-terminal-emulator`, then a documented list of common emulators. If none can be found, show the exact command to run manually; do not fail silently. + - Started from a terminal with no arguments: print a short numbered prompt (1 Dashboard window, 2 Terminal UI) with the remembered or default choice on Enter. On a headless session (SSH, no display server), skip the prompt, open the TUI, and print one line saying why. + - Flags and environment: `--ui gui|tui`, `--ask` to force the chooser, `--no-prompt` to use the remembered or default front end, and an `ATTACKPATH_VISUALIZER_UI` environment variable. Any explicit CLI subcommand (scan, import, export, about, diagnostics, and so on) never shows the chooser. Non-interactive stdin and CI never prompt. + - The remembered choice lives in the OS user config directory with restrictive permissions. Settings has an **Ask me every time** switch, and `config reset-ui` clears it. + - Both front ends offer a menu action to relaunch in the other mode. + - Both front ends share one SQLite database with WAL mode and a busy timeout; if the other front end holds the database, show a clear notice instead of failing. +- Provide the `nogui` build tag (a build with `-tags nogui` omits the GUI and does not need cgo). Document the GUI build prerequisites for each OS, and do not claim the GUI is verified on a platform unless it was built and tested there. + +### 2. Application shell and navigation + +- Left navigation sidebar. Every category has an **icon next to its label**. The sidebar collapses to icons with tooltips, remembers its state, and marks the active item by shape and weight as well as color. About and Settings sit at the bottom. +- Top bar: global search, a data-mode chip when relevant (Demo data, Fixture, Simulation, Read-only), and a help entry. +- Keyboard: Ctrl/Cmd+1 to 9 jump to categories, Ctrl/Cmd+F search, Ctrl/Cmd+, Settings, F1 Usage guide. Show shortcuts in tooltips and in a shortcuts list. +- Persist window size, position, sidebar state, selected theme, and table preferences. + +### 3. AttackPath Visualizer-specific interface (dashboard with a graph workspace) + +| Category | Icon (Lucide-style name) | What it shows | +|---|---|---| +| Overview | `layout-dashboard` | Exposure summary: potential paths by impact tier, top-ranked paths, choke points, import freshness | +| Graph | `waypoints` | Interactive relationship graph of assets and edges with pan, zoom, filter, and focus | +| Paths | `route` | Ranked potential paths with an explainable score breakdown | +| Assets | `server` | Asset inventory and relationships | +| Evidence | `file-search` | Source evidence behind every edge | +| Remediation | `wrench` | Ranked suggestions, for example the edge whose removal breaks the most paths | +| Imports | `upload` | Ingestion history, validation results, demo-data label | +| Reports | `file-text` | Exported path and remediation reports | +| About | `info` | App identity, offline Usage guide, Source Code, bug reporting | +| Settings | `settings-2` | Appearance, density, launch preference, data location, safe defaults | + +**Overview screen (first screen after launch).** Answer "what needs attention now" with dense, information-first content computed from the real data store: + +- Potential paths per impact tier (each tile opens the filtered list) +- Top-ranked paths table with score and confidence +- Choke points that break the most paths +- Confidence distribution and data freshness of the last import + +**Signature views.** + +- Graph canvas with a keyboard-accessible node list as an alternative view +- Path detail: edge-by-edge evidence links and the exact score components + +### 4. Visual design system (professional, not template-looking) + +- Define a custom theme in code (tokens for color, spacing, type scale, radius, and elevation) and do not ship the toolkit's default look. Provide light and dark themes and follow the OS setting by default. +- Use a 4/8 px spacing scale, one accent color, and a restrained neutral palette. Use 1 px hairline borders, one small consistent corner radius, and elevation only for overlays. Use bundled open-license fonts (record their licenses) with a system fallback and a defined type scale. +- Severity and status always combine an icon and a text label with color. Meet WCAG AA contrast (4.5:1 text, 3:1 UI components) and keep colors distinguishable for common color-vision deficiencies. +- Tables are the primary surface: sortable, filterable, column chooser, row detail side panel, keyboard row navigation, copy and export actions, a compact and comfortable density switch, and virtualization for large data sets. +- Charts show real stored data only, have labeled axes and units, a text or table alternative, and are never used where a number or a table is clearer. Build them from toolkit canvas primitives or a permissively licensed library. +- Every screen has meaningful loading, empty (with the next action), error (with a fix), and success states. +- Avoid: gradients, glow, glassmorphism, emoji as icons, stock illustrations, identical rounded card grids on every page, decorative sparklines, random or hardcoded numbers, donut charts for two categories, placeholder text, and controls that do nothing. + +### 5. Icons + +- Use one consistent icon set for navigation, actions, and status: either a permissively licensed set embedded as SVG (Lucide under ISC or Tabler under MIT; record the license in `THIRD_PARTY_NOTICES`) or original icons drawn to the same grid and stroke width. Never mix sets and never use emoji. The names in the table above are Lucide-style suggestions; choose the nearest available icon. +- **Custom application icon (required).** Create an original icon for AttackPath Visualizer. Concept: three nodes joined by a bent path that ends in a target ring. Supply editable SVG source, a simplified version that stays legible at 16 px, `.ico` (Windows), `.icns` (macOS), PNG sizes from 16 to 1024, and Linux SVG/PNG with a desktop entry. Use it for the window, taskbar or dock, the launcher chooser, and About. No third-party trademarks, no generic placeholder, no stock art. + +### 6. About, Usage guide, and bug reporting + +- Reachable from the sidebar (info icon) and from the Help menu. About has these tabs: **Overview** (icon, name, version, build info, license, purpose, maintainer or copyright only when known), **Usage guide**, **Shortcuts**, **Diagnostics**, and **Licenses & notices**. +- **Usage guide** renders the bundled `docs/USAGE.md` offline inside the app (embedded at build time), with a table of contents and search, and an **Open full documentation on GitHub** link. It covers the launcher, the dashboard, the terminal UI, and every category above. Add screenshots to the docs only if they were captured from the running application with demo data. +- Central metadata in `internal/meta/meta.go` holds the repository URL `https://github.com/NexzaDev/attackpath-visualizer`; it is the single source for every link. About provides **Source Code** (opens the repository) and **Found a bug? Please report it on GitHub.** (opens `https://github.com/NexzaDev/attackpath-visualizer/issues/new`). +- The bug report action first shows a preview of exactly what will be included (app version, OS, architecture, build info, sanitized settings status), then opens the new-issue page with a prefilled title and body. If the prefilled body would exceed a safe URL length, copy it to the clipboard and open the blank new-issue page. Never attach logs, evidence, credentials, tokens, host data, or file contents automatically. +- External links open only on an explicit click, only for URLs under the configured repository, using the OS default handler, after a confirmation showing the full URL. + +### 7. Accessibility and quality + +- Full keyboard operation, visible focus indicators, text scaling, reduced-motion support, labeled controls, and no information conveyed by color alone. Test with a screen reader where the toolkit supports it and state the limits honestly where it does not. +- Every visible control performs a real action. Demo or simulated data is labeled wherever it appears. + +### 8. UI structure and tests + +- View models and formatting live outside the toolkit code so they are unit-testable. Add table-driven tests for the launcher decision (TTY or not, flags, environment, saved preference, headless), a test that About links are limited to the configured repository, tests that every navigation category resolves to a screen, and GUI smoke tests with the toolkit's headless test driver. In CI, build the GUI on the operating systems the runners support, and document what was and was not verified. + +### 9. UI acceptance criteria + +- The chooser and both front ends work from a clean checkout using demo data, with no paid service and no network access. +- All categories above exist, have icons, and show real data. +- About shows the offline Usage guide, Source Code, and the bug-report action pointing to `https://github.com/NexzaDev/attackpath-visualizer`. +- The graph stays usable at 1,000 nodes; document the measured interaction performance +- Every edge opens its source evidence record; no control executes or simulates an attack + +### 10. Building the GUI when the sandbox is limited + +Your execution sandbox may be unable to download the toolkit's dependencies, install system graphics libraries, or open a display. If so, do not skip the GUI and do not fake verification. Use GitHub Actions for everything the sandbox cannot do: + +- Add a lockfile workflow that runs in CI with network access and commits `go.sum` back to the branch. A workflow_dispatch-only workflow cannot be started from a non-default branch, so trigger it on push to your own branch (limited to changes in `go.mod` or the workflow file) with `contents: write` as the only elevated permission, commit only when the file actually changed so it cannot loop, and push a follow-up commit afterwards because pushes made with the workflow token do not start other workflows. Remove or disable it at the end and say so in the PR body; if you cannot disable it, tell the maintainer exactly how. Never add vanity-host replace directives or vendored hacks to work around the sandbox. +- Keep the CLI/TUI buildable and fully tested without the GUI through the `nogui` build tag, so a GUI problem never blocks the rest of the product. +- In CI, build the GUI on Ubuntu, macOS, and Windows where the runners allow it, and run headless GUI tests. Take the system package list for Linux from the toolkit's official documentation at the time of the work and record it. +- Render every main screen headlessly with Fyne's software renderer from its test packages, using demo data only, and upload the PNG files as workflow artifacts. List the artifact names in the PR body so the maintainer can review the design from a phone. Treat these screenshots as design evidence, not as proof that the application runs on a real desktop. +- Report exactly what CI proved and what remains unverified, for example real window behavior, OS-specific launch, icon display in the taskbar, and the terminal-emulator launch path. Do not claim visual or platform verification that CI did not perform. +- If every CI job fails at startup with a billing or spending-limit message, stop immediately, say so in one line, and do not keep pushing. If only macOS jobs cannot start, continue and mark macOS as unverified everywhere it is mentioned. Never describe a platform as verified because the job was defined. +- Read CI failures through check-run annotations: make failing steps print each finding as a GitHub error annotation so you can read them without log access. +- The custom theme must genuinely replace the toolkit defaults for colors, type, and spacing as described in section 4; a theme that only wraps the default theme and adds a few colors does not satisfy this section. Review your own rendered screenshots for clipped text, overlaps, empty areas, and weak contrast before finishing. +- Do not finish while any CI job on the final commit is red. After the last push, check every job on every operating system. For each red job, read its annotations, fix the real cause, push, and check again. If a job still fails, say so at the top of the final report with the job name and the exact error, and do not describe the project as finished. +- If the GUI cannot be completed this way, deliver the CLI/TUI fully, document the blocker and a precise plan in `docs/ROADMAP.md`, and state that the GUI is not delivered. + +### 11. Notifications (in the app and outside it) + +Add notifications where they fit this product. Events for attackpath-visualizer: a new critical path appears after an import; an import fails validation. Add a **Notifications** category (icon `bell`) to the navigation table. + +- **Inside the app:** a bell in the top bar with an unread count and a Notifications category listing every notification with a severity icon plus text, filters, mark-as-read, and a link to the relevant record. Notification rules are configurable per event type with a severity threshold, quiet hours, and de-duplication so a repeated condition does not flood the list. +- **Outside the app (opt-in):** a background notifier that reports while the dashboard is closed: `attackpath-visualizer notifier run|install|uninstall|status`. `install` creates a per-user autostart entry without administrator rights (Windows Startup or Task Scheduler, macOS LaunchAgent, Linux XDG autostart). It is off by default and needs explicit consent in Settings or on the command line. It reads the local database read-only on a bounded interval, makes no network calls of its own, and sends operating-system notifications. +- **Privacy:** notification text is minimal by default (for example "2 new critical findings") with a setting for more detail. Never include secrets, credentials, evidence content, or full indicators in notification text, and never send a notification to any external service. +- **Tests:** test rule evaluation, de-duplication, quiet hours, and install/uninstall logic with an injected notifier and a temporary directory. State that real OS notification display is unverified on each platform unless CI proves it. +- Use one small permissively licensed notification library if one is needed, and record it in the dependency decision record, `THIRD_PARTY_NOTICES`, and the threat model. + +### 12. Release packages for Windows, macOS, and Linux + +Deliver real downloadable packages built by GitHub Actions, not only source code. The agent does not build these on its own machine; the workflow does. + +- Add a manually triggered release workflow (workflow_dispatch) on the default branch's workflow set that builds the GUI application on each operating system's own runner with the `fyne package` tool from `fyne.io/tools/cmd/fyne` pinned to an exact version, so the icon is embedded in the Windows `.exe` and in the macOS `.app` bundle. +- Outputs (follow the pattern already proven on the Argus ASM release, and keep these exact asset names): `attackpath-visualizer-windows-x64.exe`, `attackpath-visualizer-macos-arm64.tar.gz` (add `attackpath-visualizer-macos-x64.tar.gz` when a runner for it is available), and `attackpath-visualizer-linux-x64.tar.gz`, plus `SHA256SUMS`. Each package contains the application with the custom icon embedded where the platform supports it (Windows `.exe` resource, macOS `.app` bundle inside the archive when the packaging tool produces one, Linux desktop entry and icon in the archive), the license files of the application and of every third-party module in that platform's build, a short `README`, and the Usage guide. The Windows `.exe` may be a single file. +- Mark the release as a **pre-release** named " v0.1.0-dev (dev beta)" with release notes that say it is an early build, that not every planned feature exists, and how to open unsigned binaries (macOS: right-click and choose Open the first time; Windows: choose More info and Run anyway; Linux: run `chmod +x ` after extracting). +- The background notifier is part of the same binary (`attackpath-visualizer notifier ...`); no separate service or installer that needs administrator rights. +- Write a `SHA256SUMS` file covering every package, and attach the packages and checksums to a **draft** GitHub Release. Never publish it automatically. +- Document the unsigned-binary warnings (Windows SmartScreen, macOS Gatekeeper) and how a user opens an unsigned app on each system. Do not claim code signing or notarization unless it was really done with a key the maintainer controls. +- Document, in `docs/RELEASING.md`, the exact steps for the maintainer to run the workflow and publish the draft release using only a phone and the GitHub website. +- Build the `nogui` or headless variant too and attach it, so a CLI/TUI-only package exists for servers. +- Report honestly which packages the workflow produced, which job could not start (for example macOS because of billing), and which results were never run or never opened on a real machine. + +## Engineering standards: no vibe coding +- Make evidence-based engineering decisions. Do not invent features, test results, benchmarks, integrations, or security claims. +- Do not generate filler code to inflate line count. Favor complete vertical slices, maintainability, performance, and correctness. +- Inspect the repository first; preserve valid existing work and identify the current state before changing files. +- Write a short plan, then implement and verify the product. Do not stop at a plan, mockup, or architecture diagram. +- Use clear module boundaries, typed interfaces, cohesive packages, explicit error handling, input validation, structured logging, migrations, and reproducible builds. +- Avoid giant files, god objects, circular dependencies, duplicated business logic, unnecessary abstractions, dead code, fake data in production paths, and placeholder buttons. +- Add unit, integration, API, and end-to-end tests appropriate to the system. Test invalid inputs, edge cases, permissions, failure modes, and security boundaries. +- Run formatter, linter, static analysis/type checks, tests, dependency checks, and production build. Fix failures and report only checks actually run. +- No comments in application or test source code: no inline comments, block comments, or commented-out code. Express intent through names, types, tests, and external documentation. Keep required license headers only if legally necessary and place licensing in LICENSE rather than adding routine source comments. +- Never claim the code is bug-free. Provide verified test evidence and list remaining limitations honestly. +- Do not optimize for a target line count. Do not claim 457,000+ LOC unless measured by a reproducible tool and supported by real, non-generated functionality. + +## Required repository files +- `README.md`: purpose, scope, features, architecture summary, supported platforms, prerequisites, setup, configuration, commands, screenshots placeholders only if no real screenshots exist, API/CLI usage, tests, troubleshooting, limitations, and roadmap. +- `LICENSE`: MIT License, only if the author intends to distribute this project under MIT. Verify that all bundled dependencies and copied assets are compatible; do not claim third-party code is MIT. +- `CONTRIBUTING.md`: development setup, branch/commit conventions, issue and PR expectations, testing requirements, code style, security-sensitive changes, and review checklist. +- `SECURITY.md`: supported versions, private vulnerability reporting instructions using a repository-appropriate contact/channel placeholder, response expectations, scope, and responsible disclosure guidance. Do not invent an email address. +- `CODE_OF_CONDUCT.md`: Contributor Covenant or a clearly documented equivalent. +- `CHANGELOG.md`: versioned user-visible changes, starting with an initial unreleased section. +- `docs/ARCHITECTURE.md`: components, data flow, trust boundaries, storage, deployment, and design decisions. +- `docs/THREAT_MODEL.md`: assets, adversaries, trust boundaries, abuse cases, mitigations, residual risks, and assumptions. +- `docs/ROADMAP.md`: prioritized milestones with measurable completion criteria. +- `.github/`: CI workflows for formatting/linting, tests, static checks, build, and dependency/security scanning where supported; issue and pull request templates. +- `.editorconfig`, `.gitignore`, and `.env.example` with placeholders only. +- Tests, fixtures, migrations, and scripts organized in predictable directories. + +## Required architecture and repository layout +Use this as the default shape, adapting it to the chosen language and project. Do not create empty directories merely to match a template. + +```text +. +├── README.md +├── LICENSE +├── CONTRIBUTING.md +├── SECURITY.md +├── CODE_OF_CONDUCT.md +├── CHANGELOG.md +├── .editorconfig +├── .gitignore +├── .env.example +├── Makefile +├── cmd/ +├── internal/ +├── pkg/ +├── api/ +├── tui/ +├── migrations/ +├── tests/ +├── testdata/ +├── scripts/ +├── docs/ +│ ├── ARCHITECTURE.md +│ ├── THREAT_MODEL.md +│ └── ROADMAP.md +└── .github/ + ├── workflows/ + ├── ISSUE_TEMPLATE/ + └── PULL_REQUEST_TEMPLATE.md +``` + +Adapt directories where the framework requires another convention; explain important architectural choices in documentation. Keep core business logic independent from HTTP handlers and UI components. Do not expose internal packages as public APIs without a reason. + +## Security and open-source release bar +- Secure defaults, least privilege, authentication and authorization where applicable, parameterized database access, safe output encoding, rate limiting, audit logging, and explicit secret redaction. +- No hardcoded credentials, production tokens, personal data, unsafe default scan targets, or external network calls in tests unless explicitly mocked. +- Use pinned or bounded dependencies, generate a dependency inventory/SBOM where practical, review licenses, and document update policy. +- CI must run on a clean checkout. Provide deterministic seed data and a local demo mode. +- Include a `Makefile` or equivalent task runner with documented targets such as `test`, `lint`, `format`, `typecheck`, `build`, and `check`. +- Provide OpenAPI documentation for HTTP APIs or complete CLI help for CLI-first tools. +- Keep UI accessible and responsive; all displayed operational metrics must come from real application data or clearly labeled demo fixtures. +- Use conventional commits or document the selected commit convention. Make pull requests reviewable and changes focused. + + +## Project-specific acceptance criteria +- Deliver a locally runnable end-to-end MVP using synthetic demo data without paid accounts or production credentials. +- Provide the core domain workflow, persistence where appropriate, API or CLI, and a usable responsive UI when a UI is relevant. +- Implement actual behavior behind every visible control; no fake buttons or hardcoded production metrics. +- Include migrations, seed data, health/readiness checks, structured logs, graceful shutdown, and sensible timeouts where appropriate. +- Add API contract tests and document API authentication, authorization, and rate limits. +- Include a `.env.example` with placeholders only and fail safely when required configuration is missing. +- Include the required open-source governance and security files listed above. The MIT license must be a valid standard license text and must not misrepresent third-party dependencies or assets. +- Use GitHub Actions CI to run formatting, linting/static checks, tests, build, and dependency/license checks where practical. Use least-privilege workflow permissions. +- Document how to run each verification command locally and make CI reproducible. +- Include a short architecture decision record for significant choices such as storage, queueing, parsing, or provider abstractions. + +## Execution protocol +1. Inspect the repository and report its state in your working notes; do not overwrite useful work. +2. Create a prioritized plan and implement the highest-value vertical slice immediately. +3. Compile/build early and often. Run tests after each meaningful subsystem; do not defer all validation to the end. +4. Perform a security review of trust boundaries, auth, validation, secret handling, dependencies, and dangerous defaults. +5. Review the complete diff. Search for TODO/FIXME, placeholders, commented-out code, leaked secrets, duplicated logic, and unsupported claims. +6. Run formatting, lint/static analysis, tests, type checks if relevant, production build, and dependency/license checks. Fix discovered issues and rerun. +7. Update README and docs to match the implementation, not the intended future state. +8. Finish with an honest report of completed functionality, exact commands and outcomes, known limitations, and prioritized next milestones. + +## Final rule + +Do not settle for vibe-coded output. Do not generate filler to inflate LOC, do not pretend incomplete features are finished, do not guarantee zero bugs, and do not report checks that were not actually run. If the full product is too large for one execution, deliver a correct and testable foundation first and then proceed through the roadmap in ranked milestones. Keep all active and test source code free of comments, as requested. + + +--- + +## Release checklist + +- [ ] Main workflow works end to end with local demo data. +- [ ] Clean-checkout setup instructions have been tested. +- [ ] Formatting, lint/static checks, tests, and production build pass. +- [ ] CI workflows run with least privilege. +- [ ] `SECURITY.md` provides a real maintainer-controlled reporting path before public release. +- [ ] MIT licensing and third-party license compatibility have been reviewed. +- [ ] Documentation describes implemented behavior and known limitations accurately. +- [ ] No secrets, private data, commented-out code, or unexplained stubs are present. +- [ ] Launcher decision tests pass; the chooser works from a desktop launch and from a terminal; headless fallback is tested. +- [ ] Every navigation category has an icon from one consistent set, and icon licenses are recorded. +- [ ] Custom application icon assets (SVG, `.ico`, `.icns`, PNG sizes, Linux desktop entry) are present and used by the window, taskbar or dock, and About. +- [ ] About shows the offline Usage guide, Source Code, and the bug-report action for the configured repository. +- [ ] The GUI was built and smoke-tested on every operating system claimed; other platforms are documented as unverified. +- [ ] If the GUI was built through CI, the lockfile workflow is documented or removed, and screenshot artifacts are listed in the PR body. +- [ ] Notifications work in the app, and the opt-in background notifier installs and uninstalls cleanly; real OS display is reported as verified only where it was actually shown. +- [ ] The release workflow has produced Windows, macOS, and Linux packages with the icon embedded, plus SHA256SUMS, as a draft release; anything not produced or not run is listed as unverified. diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md new file mode 100644 index 0000000..b47dfda --- /dev/null +++ b/docs/THREAT_MODEL.md @@ -0,0 +1,21 @@ +# Threat model + +## Assets and trust boundaries + +Protected assets are the user's local inventory database, imported configuration/evidence documents, application settings, and integrity of graph explanations. Trust boundaries are the command line/import file to parser, parser to graph validator, graph service to SQLite, and local outputs/diagnostics to the user's terminal. Inputs may be malformed or misleading. The program does not access a production environment or execute attack techniques. + +## Adversaries and abuse cases + +A malicious or malformed inventory could exceed memory limits, contain duplicate identifiers, point edges at nonexistent assets, or attempt to alter database relationships. A local user could set a path to an unintended database. A future notifier could disclose sensitive data if notification text becomes overly detailed. Dependency compromise is also in scope. + +## Mitigations + +Imports are capped at 8 MiB, decoded into typed records, validated for identifiers, ranges, duplicates, self-edges, and dangling references, then persisted in one transaction using parameterized SQL. SQLite uses indexed foreign-key columns and local WAL mode. Runtime diagnostics do not read imported files or reveal paths/host data. There is no telemetry, default listener, credential requirement, or outbound network operation. CI runs tests, vet, and vulnerability checks. + +## Residual risks and assumptions + +Inventory text can contain false or sensitive information and remains the operator's responsibility. Local users/processes with access to the account can read or change the database. Platform permissions depend on the OS configuration directory. The graph score is a prioritization heuristic, not a calibrated probability or proof of reachability. Packaging/signing and real-desktop behavior are not yet verified. + +## Reporting a vulnerability + +Use the [GitHub private vulnerability advisory form](https://github.com/NexzaDev/attackpath-visualizer/security/advisories/new) first; do not disclose suspected vulnerabilities publicly. If you cannot use the GitHub form, send the report to **SuperMcDuck@proton.me**. Supported versions, report contents, response targets, scope, and disclosure coordination are defined in [`SECURITY.md`](../SECURITY.md). diff --git a/docs/USAGE.md b/docs/USAGE.md new file mode 100644 index 0000000..d7b5838 --- /dev/null +++ b/docs/USAGE.md @@ -0,0 +1,57 @@ +# Offline usage guide + +AttackPath Visualizer analyzes relationships from synthetic or authorized inventory. It does not scan systems, exploit vulnerabilities, or contact remote services. Its scores are human-review prioritization aids, not proof of exploitability. + +## Choose a front end + +Launch with no arguments to choose Dashboard or Terminal. `--ui gui` and `--ui tui` select directly; `--ask` opens the chooser and `--no-prompt` uses the saved/default choice. `ATTACKPATH_VISUALIZER_UI=gui|tui` overrides the saved preference. In a headless session, the terminal front end is selected automatically. Explicit commands such as `overview`, `paths`, `assets`, `import`, `export`, `about`, and `diagnostics` do not open the launcher. Use `config reset-ui` to clear the remembered choice. + +## Local data and imports + +The first launch creates a local SQLite database under the OS user configuration directory and loads the clearly labeled, deterministic synthetic graph. Use Settings or the TUI Settings view to inspect the active database path. `--db PATH` chooses another database; `ATTACKPATH_VISUALIZER_DB` is the environment override. + +Graph JSON supports `assets`, `identities`, `misconfigurations`, `findings`, and `edges`. Node impact and finding severity are integers from 1 to 5; edge confidence is 0–100. Edges connect existing, distinct asset or identity IDs and require source, finding, and observation evidence. Duplicate IDs, missing endpoints, self-edges, invalid ranges, malformed or multiple JSON documents, entity-count excesses, and documents over 8 MiB are rejected. Validation completes before graph replacement. In the CLI, use `import --yes FILE` for a confirmed non-interactive replacement; an interactive terminal asks before replacing. The desktop import dialog also asks for confirmation. A rejected import is recorded without partially replacing the current graph. + +The CLI `export` command writes graph JSON to standard output. The CLI `report` command writes a JSON or Markdown path-and-remediation report (`--format markdown|json`, or `--json`). In the TUI, Reports asks which format and destination to use and confirms before overwriting. In the dashboard Reports view, export the graph or complete analysis report to a user-selected file, or explicitly confirm copying JSON or Markdown to the clipboard; these exports may contain inventory identifiers and evidence. + +## Dashboard categories + +- **Overview** summarizes stored assets, identities, relationships, impact and confidence distributions, ranked paths, remediation choke points, and import freshness. Distribution tiles filter the ranked paths. +- **Graph** shows a scrollable relationship canvas, accessible asset-and-identity list, edge evidence, zoom controls, and selected-node details including linked findings. +- **Paths** ranks directed paths and shows confidence, impact, exact score components, and per-edge evidence; selecting a row opens its local evidence. Filtering is available by impact and confidence band. +- **Assets** lists assets and identities with type, impact, description, and linked findings. +- **Evidence** links relationships to their source record and finding text. +- **Remediation** ranks relationships by paths affected, critical paths, and weighted risk points. Suggestions are advisory and never change inventory. +- **Imports** validates local JSON and lists recent import outcomes. +- **Reports** exports the graph or ranked paths to JSON files or, after confirmation, the clipboard. +- **Notifications** lists local app events with severity, read state, global-search filtering, and links to related records. +- **Settings** controls light/dark appearance, compact table rows, launcher preference, local database location, notification rules, and opt-in OS notification delivery. +- **About** bundles the README, this Usage guide, keyboard shortcuts, sanitized diagnostics, application identity, and offline license texts. + +Click a table heading to sort by that column. The global search field filters relevant assets, paths, evidence, notifications, and graph nodes. Use the sidebar buttons for every category; `Ctrl/Cmd+1` through `Ctrl/Cmd+9` opens the first nine categories, `Ctrl/Cmd+F` focuses search, `Ctrl/Cmd+,` opens Settings, and `F1` opens About. On macOS, `Cmd` is used instead of `Ctrl`. + +## CLI + +Run `attackpath-visualizer help` for all commands. Examples: + +```sh +attackpath-visualizer overview --json +attackpath-visualizer paths --db ./graph.db --json +attackpath-visualizer remediation --db ./graph.db --json +attackpath-visualizer report --format markdown --db ./graph.db +attackpath-visualizer report --format json --db ./graph.db +attackpath-visualizer import --yes inventory.json +attackpath-visualizer export --db ./graph.db +attackpath-visualizer notifier status +attackpath-visualizer diagnostics +``` + +`about` and `diagnostics` do not include imported file contents or secrets. Diagnostics report only application/build version, OS/architecture, Go runtime, and sanitized local configuration status. + +## Scoring and limits + +A path's impact component is the highest impact tier among its asset and identity nodes. Confidence is compounded across edges in path order, flooring the integer percentage after each edge; score is impact tier multiplied by the resulting confidence percentage. The explanation and report expose each edge confidence and the final components. Enumeration is cycle-safe, deduplicated, bounded to 32 edges and 1,000 results, and also has a 250,000-edge-expansion budget; limited results identify truncation. Review inventory freshness, relationships, and evidence before acting. + +## Notifications and privacy + +In-app notifications are local. The background notifier is off until explicitly enabled in Settings or installed with `notifier install`. It creates a per-user startup entry without administrator rights and polls every 15 minutes. It opens SQLite in read-only mode; a separate private configuration file records which event IDs were delivered, so the graph database is not modified by the notifier. Severity thresholds, quiet hours, and minimal/detailed message preference are configurable per event type. Notification delivery makes no network calls. Use `notifier uninstall` to remove the startup entry; `notifier status` reports whether it is present. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5eab0ea --- /dev/null +++ b/go.mod @@ -0,0 +1,58 @@ +module github.com/NexzaDev/attackpath-visualizer + +go 1.25.0 + +require ( + fyne.io/fyne/v2 v2.6.3 + github.com/gen2brain/beeep v0.10.0 + modernc.org/sqlite v1.34.5 +) + +require ( + fyne.io/systray v1.11.0 // indirect + git.sr.ht/~jackmordaunt/go-toast v1.1.2 // indirect + github.com/BurntSushi/toml v1.4.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/esiqveland/notify v0.13.3 // indirect + github.com/fredbi/uri v1.1.0 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/fyne-io/gl-js v0.2.0 // indirect + github.com/fyne-io/glfw-js v0.3.0 // indirect + github.com/fyne-io/image v0.1.1 // indirect + github.com/fyne-io/oksvg v0.1.0 // indirect + github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71 // indirect + github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/go-text/render v0.2.0 // indirect + github.com/go-text/typesetting v0.2.1 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/hack-pad/go-indexeddb v0.3.2 // indirect + github.com/hack-pad/safejs v0.1.0 // indirect + github.com/jeandeaual/go-locale v0.0.0-20250612000132-0ef82f21eade // indirect + github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect + github.com/nicksnyder/go-i18n/v2 v2.5.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rymdport/portal v0.4.1 // indirect + github.com/sergeymakinen/go-bmp v1.0.0 // indirect + github.com/sergeymakinen/go-ico v1.0.0-beta.0 // indirect + github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c // indirect + github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect + github.com/stretchr/testify v1.10.0 // indirect + github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect + github.com/yuin/goldmark v1.7.8 // indirect + golang.org/x/image v0.45.0 // indirect + golang.org/x/net v0.35.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + modernc.org/libc v1.55.3 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.8.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..283a46d --- /dev/null +++ b/go.sum @@ -0,0 +1,144 @@ +fyne.io/fyne/v2 v2.6.3 h1:cvtM2KHeRuH+WhtHiA63z5wJVBkQ9+Ay0UMl9PxFHyA= +fyne.io/fyne/v2 v2.6.3/go.mod h1:NGSurpRElVoI1G3h+ab2df3O5KLGh1CGbsMMcX0bPIs= +fyne.io/systray v1.11.0 h1:D9HISlxSkx+jHSniMBR6fCFOUjk1x/OOOJLa9lJYAKg= +fyne.io/systray v1.11.0/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs= +git.sr.ht/~jackmordaunt/go-toast v1.1.2 h1:/yrfI55LRt1M7H1vkaw+NaH1+L1CDxrqDltwm5euVuE= +git.sr.ht/~jackmordaunt/go-toast v1.1.2/go.mod h1:jA4OqHKTQ4AFBdwrSnwnskUIIS3HYzlJSgdzCKqfavo= +github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= +github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/esiqveland/notify v0.13.3 h1:QCMw6o1n+6rl+oLUfg8P1IIDSFsDEb2WlXvVvIJbI/o= +github.com/esiqveland/notify v0.13.3/go.mod h1:hesw/IRYTO0x99u1JPweAl4+5mwXJibQVUcP0Iu5ORE= +github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= +github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= +github.com/fredbi/uri v1.1.0 h1:OqLpTXtyRg9ABReqvDGdJPqZUxs8cyBDOMXBbskCaB8= +github.com/fredbi/uri v1.1.0/go.mod h1:aYTUoAXBOq7BLfVJ8GnKmfcuURosB1xyHDIfWeC/iW4= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/fyne-io/gl-js v0.2.0 h1:+EXMLVEa18EfkXBVKhifYB6OGs3HwKO3lUElA0LlAjs= +github.com/fyne-io/gl-js v0.2.0/go.mod h1:ZcepK8vmOYLu96JoxbCKJy2ybr+g1pTnaBDdl7c3ajI= +github.com/fyne-io/glfw-js v0.3.0 h1:d8k2+Y7l+zy2pc7wlGRyPfTgZoqDf3AI4G+2zOWhWUk= +github.com/fyne-io/glfw-js v0.3.0/go.mod h1:Ri6te7rdZtBgBpxLW19uBpp3Dl6K9K/bRaYdJ22G8Jk= +github.com/fyne-io/image v0.1.1 h1:WH0z4H7qfvNUw5l4p3bC1q70sa5+YWVt6HCj7y4VNyA= +github.com/fyne-io/image v0.1.1/go.mod h1:xrfYBh6yspc+KjkgdZU/ifUC9sPA5Iv7WYUBzQKK7JM= +github.com/fyne-io/oksvg v0.1.0 h1:7EUKk3HV3Y2E+qypp3nWqMXD7mum0hCw2KEGhI1fnBw= +github.com/fyne-io/oksvg v0.1.0/go.mod h1:dJ9oEkPiWhnTFNCmRgEze+YNprJF7YRbpjgpWS4kzoI= +github.com/gen2brain/beeep v0.10.0 h1:sR/rgmJjHVOVABgpbuICvw7SVtI13RRNnQPv+wiaoMg= +github.com/gen2brain/beeep v0.10.0/go.mod h1:UzRwrHPeN99aobEPCjiuBossVv32YViFiytGwaA1EO0= +github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71 h1:5BVwOaUSBTlVZowGO6VZGw2H/zl9nrd3eCZfYV+NfQA= +github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71/go.mod h1:9YTyiznxEY1fVinfM7RvRcjRHbw2xLBJ3AAGIT0I4Nw= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a h1:vxnBhFDDT+xzxf1jTJKMKZw3H0swfWk9RpWbBbDK5+0= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/go-text/render v0.2.0 h1:LBYoTmp5jYiJ4NPqDc2pz17MLmA3wHw1dZSVGcOdeAc= +github.com/go-text/render v0.2.0/go.mod h1:CkiqfukRGKJA5vZZISkjSYrcdtgKQWRa2HIzvwNN5SU= +github.com/go-text/typesetting v0.2.1 h1:x0jMOGyO3d1qFAPI0j4GSsh7M0Q3Ypjzr4+CEVg82V8= +github.com/go-text/typesetting v0.2.1/go.mod h1:mTOxEwasOFpAMBjEQDhdWRckoLLeI/+qrQeBCTGEt6M= +github.com/go-text/typesetting-utils v0.0.0-20241103174707-87a29e9e6066 h1:qCuYC+94v2xrb1PoS4NIDe7DGYtLnU2wWiQe9a1B1c0= +github.com/go-text/typesetting-utils v0.0.0-20241103174707-87a29e9e6066/go.mod h1:DDxDdQEnB70R8owOx3LVpEFvpMK9eeH1o2r0yZhFI9o= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hack-pad/go-indexeddb v0.3.2 h1:DTqeJJYc1usa45Q5r52t01KhvlSN02+Oq+tQbSBI91A= +github.com/hack-pad/go-indexeddb v0.3.2/go.mod h1:QvfTevpDVlkfomY498LhstjwbPW6QC4VC/lxYb0Kom0= +github.com/hack-pad/safejs v0.1.0 h1:qPS6vjreAqh2amUqj4WNG1zIw7qlRQJ9K10eDKMCnE8= +github.com/hack-pad/safejs v0.1.0/go.mod h1:HdS+bKF1NrE72VoXZeWzxFOVQVUSqZJAG0xNCnb+Tio= +github.com/jeandeaual/go-locale v0.0.0-20250612000132-0ef82f21eade h1:FmusiCI1wHw+XQbvL9M+1r/C3SPqKrmBaIOYwVfQoDE= +github.com/jeandeaual/go-locale v0.0.0-20250612000132-0ef82f21eade/go.mod h1:ZDXo8KHryOWSIqnsb/CiDq7hQUYryCgdVnxbj8tDG7o= +github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25 h1:YLvr1eE6cdCqjOe972w/cYF+FjW34v27+9Vo5106B4M= +github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25/go.mod h1:kLgvv7o6UM+0QSf0QjAse3wReFDsb9qbZJdfexWlrQw= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= +github.com/nicksnyder/go-i18n/v2 v2.5.1 h1:IxtPxYsR9Gp60cGXjfuR/llTqV8aYMsC472zD0D1vHk= +github.com/nicksnyder/go-i18n/v2 v2.5.1/go.mod h1:DrhgsSDZxoAfvVrBVLXoxZn/pN5TXqaDbq7ju94viiQ= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA= +github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rymdport/portal v0.4.1 h1:2dnZhjf5uEaeDjeF/yBIeeRo6pNI2QAKm7kq1w/kbnA= +github.com/rymdport/portal v0.4.1/go.mod h1:kFF4jslnJ8pD5uCi17brj/ODlfIidOxlgUDTO5ncnC4= +github.com/sergeymakinen/go-bmp v1.0.0 h1:SdGTzp9WvCV0A1V0mBeaS7kQAwNLdVJbmHlqNWq0R+M= +github.com/sergeymakinen/go-bmp v1.0.0/go.mod h1:/mxlAQZRLxSvJFNIEGGLBE/m40f3ZnUifpgVDlcUIEY= +github.com/sergeymakinen/go-ico v1.0.0-beta.0 h1:m5qKH7uPKLdrygMWxbamVn+tl2HfiA3K6MFJw4GfZvQ= +github.com/sergeymakinen/go-ico v1.0.0-beta.0/go.mod h1:wQ47mTczswBO5F0NoDt7O0IXgnV4Xy3ojrroMQzyhUk= +github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c h1:km8GpoQut05eY3GiYWEedbTT0qnSxrCjsVbb7yKY1KE= +github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c/go.mod h1:cNQ3dwVJtS5Hmnjxy6AgTPd0Inb3pW05ftPSX7NZO7Q= +github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef h1:Ch6Q+AZUxDBCVqdkI8FSpFyZDtCVBc2VmejdNrm5rRQ= +github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef/go.mod h1:nXTWP6+gD5+LUJ8krVhhoeHjvHTutPxMYl5SvkcnJNE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk= +github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o= +github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= +github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0= +golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4= +golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= +golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= +golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= +golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= +modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= +modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= +modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= +modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= +modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= +modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= +modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= +modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g= +modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE= +modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= +modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/gui/dashboard.go b/gui/dashboard.go new file mode 100644 index 0000000..e25f204 --- /dev/null +++ b/gui/dashboard.go @@ -0,0 +1,1238 @@ +//go:build !nogui + +package gui + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "image" + "image/color" + "image/png" + "io" + "io/fs" + "net/url" + "os" + "os/exec" + "path/filepath" + "runtime" + "sort" + "strconv" + "strings" + "time" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/canvas" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/dialog" + "fyne.io/fyne/v2/widget" + "github.com/NexzaDev/attackpath-visualizer/assets" + "github.com/NexzaDev/attackpath-visualizer/internal/domain" + "github.com/NexzaDev/attackpath-visualizer/internal/launcher" + "github.com/NexzaDev/attackpath-visualizer/internal/meta" + "github.com/NexzaDev/attackpath-visualizer/internal/notifier" + "github.com/NexzaDev/attackpath-visualizer/internal/remediation" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" + "github.com/NexzaDev/attackpath-visualizer/internal/service" +) + +type Category struct { + ID string + Label string +} + +var Categories = []Category{ + {ID: "overview", Label: "Overview"}, + {ID: "graph", Label: "Graph"}, + {ID: "paths", Label: "Paths"}, + {ID: "assets", Label: "Assets"}, + {ID: "evidence", Label: "Evidence"}, + {ID: "remediation", Label: "Remediation"}, + {ID: "imports", Label: "Imports"}, + {ID: "reports", Label: "Reports"}, + {ID: "notifications", Label: "Notifications"}, + {ID: "about", Label: "About"}, + {ID: "settings", Label: "Settings"}, +} + +type Dashboard struct { + app fyne.App + window fyne.Window + store *repository.Store + service service.Service + graph domain.Graph + paths []domain.Path + summary service.Summary + impactFilter int + confidenceFilter int + history []map[string]any + notices []repository.Notification + search string + current string + collapsed bool + zoom float32 + demo bool + switchMode func(string) error + content *fyne.Container + modeLabel *widget.Label + searchBox *widget.Entry +} + +func NewDashboard(app fyne.App, window fyne.Window, store *repository.Store, switchMode func(string) error) (*Dashboard, error) { + dashboard := &Dashboard{app: app, window: window, store: store, service: service.Service{Store: store}, current: "overview", switchMode: switchMode} + if err := dashboard.refresh(); err != nil { + return nil, err + } + dashboard.collapsed = app.Preferences().BoolWithFallback("sidebar.collapsed", false) + dashboard.zoom = float32(app.Preferences().FloatWithFallback("graph.zoom", 1)) + if dashboard.zoom < 0.5 || dashboard.zoom > 2 { + dashboard.zoom = 1 + } + return dashboard, nil +} + +func (d *Dashboard) refresh() error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + history, err := d.store.ImportHistory(ctx) + if err != nil { + return err + } + summary, err := d.service.Overview(ctx) + if err != nil { + return err + } + if len(summary.Graph.Assets)+len(summary.Graph.Identities) == 0 && len(history) == 0 { + if err = d.service.LoadDemo(ctx); err != nil { + return err + } + summary, err = d.service.Overview(ctx) + if err != nil { + return err + } + history, err = d.store.ImportHistory(ctx) + if err != nil { + return err + } + } + notices, err := d.store.Notifications(ctx, 200) + if err != nil { + return err + } + d.summary = summary + d.graph = summary.Graph + d.paths = summary.Paths.Paths + d.history = history + d.notices = notices + d.demo = len(history) > 0 && history[0]["source"] == "demo fixture" + return nil +} + +func (d *Dashboard) Content() fyne.CanvasObject { + return d.shell() +} + +func (d *Dashboard) Screen(id string) fyne.CanvasObject { + for _, category := range Categories { + if category.ID == id { + return d.screen(category.ID) + } + } + return d.emptyState("Screen unavailable", "Choose a category from the navigation.") +} + +func (d *Dashboard) shell() fyne.CanvasObject { + d.content = container.NewMax(d.screen(d.current)) + nav := d.navigation() + top := d.topbar() + return container.NewBorder(top, nil, nav, nil, d.content) +} + +func (d *Dashboard) topbar() fyne.CanvasObject { + d.searchBox = widget.NewEntry() + d.searchBox.SetPlaceHolder("Search assets, paths and evidence") + d.searchBox.OnChanged = func(value string) { + d.search = strings.ToLower(strings.TrimSpace(value)) + d.renderCurrent() + } + d.modeLabel = widget.NewLabel("LOCAL DATA") + if d.demo { + d.modeLabel.SetText("DEMO DATA") + } + unread, _ := d.store.UnreadCount(context.Background()) + bell, _ := icon("notifications") + notificationsButton := widget.NewButtonWithIcon(fmt.Sprintf("Notifications · %d", unread), bell, func() { d.show("notifications") }) + return container.NewBorder(nil, widget.NewSeparator(), nil, container.NewHBox(d.modeLabel, notificationsButton), container.NewPadded(d.searchBox)) +} + +func (d *Dashboard) navigation() fyne.CanvasObject { + items := make([]fyne.CanvasObject, 0, len(Categories)+3) + for i, category := range Categories { + if i == 9 { + items = append(items, widget.NewSeparator()) + } + resource, _ := icon(category.ID) + label := category.Label + if d.collapsed { + label = "" + } + button := widget.NewButtonWithIcon(label, resource, func(id string) func() { return func() { d.show(id) } }(category.ID)) + if category.ID == d.current { + button.Importance = widget.HighImportance + } + items = append(items, button) + } + collapseLabel := "Collapse sidebar" + if d.collapsed { + collapseLabel = "Expand sidebar" + } + collapse := widget.NewButton(collapseLabel, func() { + d.collapsed = !d.collapsed + d.app.Preferences().SetBool("sidebar.collapsed", d.collapsed) + d.window.SetContent(d.shell()) + }) + items = append(items, collapse) + logoBytes, _ := assets.Files.ReadFile("icons/icon.png") + logo := canvas.NewImageFromImage(decodePNG(logoBytes)) + logo.SetMinSize(fyne.NewSize(34, 34)) + brand := container.NewHBox(logo, widget.NewLabelWithStyle("ATTACKPATH", fyne.TextAlignLeading, fyne.TextStyle{Bold: true})) + if d.collapsed { + brand = container.NewHBox(logo) + } + return container.NewBorder(container.NewPadded(brand), container.NewPadded(collapse), nil, nil, container.NewVScroll(container.NewVBox(items...))) +} + +func (d *Dashboard) renderCurrent() { + if d.content == nil { + return + } + d.content.Objects = []fyne.CanvasObject{d.screen(d.current)} + d.content.Refresh() +} + +func (d *Dashboard) show(id string) { + d.current = id + if d.window != nil { + d.window.SetContent(d.shell()) + return + } + if d.content != nil { + d.content.Objects = []fyne.CanvasObject{d.screen(id)} + d.content.Refresh() + } +} + +func (d *Dashboard) screen(id string) fyne.CanvasObject { + switch id { + case "overview": + return d.overview() + case "graph": + return d.graphScreen() + case "paths": + return d.pathsScreen() + case "assets": + return d.assetsScreen() + case "evidence": + return d.evidenceScreen() + case "remediation": + return d.remediationScreen() + case "imports": + return d.importsScreen() + case "reports": + return d.reportsScreen() + case "notifications": + return d.notificationsScreen() + case "about": + return d.aboutScreen() + case "settings": + return d.settingsScreen() + default: + return d.emptyState("Screen unavailable", "Choose a category from the navigation.") + } +} + +func (d *Dashboard) heading(title, subtitle string) fyne.CanvasObject { + return container.NewVBox(widget.NewLabelWithStyle(title, fyne.TextAlignLeading, fyne.TextStyle{Bold: true}), widget.NewLabel(subtitle), widget.NewSeparator()) +} + +func (d *Dashboard) overview() fyne.CanvasObject { + critical := d.summary.PathsByImpact[3] + d.summary.PathsByImpact[4] + latest := "No imports recorded" + if len(d.history) > 0 { + latest = fmt.Sprintf("%v · %v assets · %v identities · %v relationships", d.history[0]["imported_at"], d.history[0]["assets"], d.history[0]["identities"], d.history[0]["edges"]) + } + metrics := container.NewGridWithColumns(5, + metric("Assets", fmt.Sprint(len(d.graph.Assets)), "Stored inventory"), + metric("Identities", fmt.Sprint(len(d.graph.Identities)), "Stored principals"), + metric("Relationships", fmt.Sprint(len(d.graph.Edges)), "Evidence-linked edges"), + metric("Potential paths", fmt.Sprint(len(d.paths)), "Ranked simple paths"), + metric("High impact", fmt.Sprint(critical), "Path impact tier 4–5"), + ) + impactTiles := make([]fyne.CanvasObject, 5) + for tier := 1; tier <= 5; tier++ { + tier := tier + impactTiles[tier-1] = widget.NewButton(fmt.Sprintf("Impact %d/5 · %d paths", tier, d.summary.PathsByImpact[tier-1]), func() { + d.impactFilter, d.confidenceFilter = tier, 0 + d.show("paths") + }) + } + confidenceTiles := make([]fyne.CanvasObject, len(d.summary.Confidence)) + for index, band := range d.summary.Confidence { + index, band := index, band + confidenceTiles[index] = widget.NewButton(fmt.Sprintf("%s · %d paths", band.Label, band.Count), func() { + d.confidenceFilter, d.impactFilter = index+1, 0 + d.show("paths") + }) + } + rows := make([][]string, 0, len(d.paths)) + visiblePaths := make([]domain.Path, 0, len(d.paths)) + for _, path := range d.paths { + if len(rows) == 8 { + break + } + if !d.matchesPath(path) { + continue + } + visiblePaths = append(visiblePaths, path) + rows = append(rows, []string{pathLabel(path), fmt.Sprintf("%d", path.Score), fmt.Sprintf("%d%%", path.Confidence), fmt.Sprintf("Impact %d/5", path.Impact)}) + } + table := stringTable([]string{"Potential path", "Score", "Confidence", "Impact"}, rows, []float32{340, 70, 100, 100}, func(row int) { + if row >= 0 && row < len(visiblePaths) { + d.showPathDetails(visiblePaths[row]) + } + }) + freshness := widget.NewCard("Import freshness", "Latest recorded input", widget.NewLabel(latest)) + choke := widget.NewCard("Relationship choke points", "Suggestions rank paths affected then risk points", d.chokePoints()) + confidence := widget.NewCard("Confidence distribution", "Enumerated paths by compounded confidence", container.NewGridWithColumns(5, confidenceTiles...)) + impact := widget.NewCard("Paths by impact tier", "Select a tier to filter ranked paths", container.NewGridWithColumns(5, impactTiles...)) + lower := container.NewGridWithColumns(2, freshness, choke) + body := container.NewVBox(d.heading("Exposure overview", "Attention summary computed from the current local graph."), metrics, impact, confidence, container.NewHBox(widget.NewLabelWithStyle("Highest-ranked paths", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}), widget.NewButton("View all paths", func() { d.impactFilter, d.confidenceFilter = 0, 0; d.show("paths") })), table, lower) + return container.NewVScroll(container.NewPadded(body)) +} + +func metric(title, value, note string) fyne.CanvasObject { + return widget.NewCard(title, note, widget.NewLabelWithStyle(value, fyne.TextAlignLeading, fyne.TextStyle{Bold: true})) +} + +func (d *Dashboard) graphScreen() fyne.CanvasObject { + nodes := d.filteredNodes() + selected := widget.NewLabel("Select a node to focus its direct relationships.") + list := widget.NewList(func() int { return len(nodes) }, func() fyne.CanvasObject { return widget.NewLabel("template") }, func(id widget.ListItemID, object fyne.CanvasObject) { + node := nodes[id] + object.(*widget.Label).SetText(fmt.Sprintf("%s · %s/%s · impact %d/5", node.Name, node.EntityType, node.Kind, node.Impact)) + }) + list.OnSelected = func(id widget.ListItemID) { + if id < 0 || id >= len(nodes) { + return + } + selected.SetText(d.nodeDetails(nodes[id])) + } + zoomLabel := widget.NewLabel(fmt.Sprintf("%d%%", int(d.zoom*100))) + zoom := func(delta float32) { + d.zoom += delta + if d.zoom < 0.5 { + d.zoom = 0.5 + } + if d.zoom > 2 { + d.zoom = 2 + } + d.app.Preferences().SetFloat("graph.zoom", float64(d.zoom)) + d.renderCurrent() + } + zoomControls := container.NewHBox(widget.NewButton("−", func() { zoom(-0.1) }), zoomLabel, widget.NewButton("+", func() { zoom(0.1) })) + mapPage := container.NewBorder(widget.NewLabel(fmt.Sprintf("Relationship map · %d visible nodes of %d · scroll to pan", min(len(nodes), 160), len(d.graph.Nodes()))), nil, nil, nil, container.NewScroll(d.graphCanvas(nodes))) + mapPage = container.NewBorder(zoomControls, nil, nil, nil, mapPage) + listPage := container.NewBorder(widget.NewLabel(fmt.Sprintf("Node inventory · %d assets and identities · global search filters this list", len(nodes))), nil, nil, nil, list) + edges := d.filteredEdges() + edgeList := widget.NewList(func() int { return len(edges) }, func() fyne.CanvasObject { return widget.NewLabel("template") }, func(id widget.ListItemID, object fyne.CanvasObject) { + edge := edges[id] + object.(*widget.Label).SetText(fmt.Sprintf("%s → %s · %s · confidence %d%%", edge.From, edge.To, edge.Relation, edge.Confidence)) + }) + edgeList.OnSelected = func(id widget.ListItemID) { + if id >= 0 && id < len(edges) { + edge := edges[id] + dialog.ShowInformation("Relationship evidence", fmt.Sprintf("%s → %s\nRelationship: %s\nConfidence: %d%%\nSource: %s\nFinding: %s\nObserved: %s", edge.From, edge.To, edge.Relation, edge.Confidence, edge.Evidence.Source, edge.Evidence.Finding, edge.Evidence.Observed), d.window) + } + } + edgePage := container.NewBorder(widget.NewLabel(fmt.Sprintf("All %d matching relationships · select a row for evidence", len(edges))), nil, nil, nil, edgeList) + tabs := container.NewAppTabs(container.NewTabItem("Graph canvas", mapPage), container.NewTabItem("Accessible node list", listPage), container.NewTabItem("Edges & evidence", edgePage)) + if len(nodes) == 0 { + return d.emptyState("No graph records", "Import a JSON inventory or restore a demo database to populate the graph.") + } + return container.NewPadded(container.NewBorder(d.heading("Relationship graph", "Pan by scrolling · zoom with + / − · select a node to focus relationships."), nil, nil, nil, container.NewGridWithColumns(2, tabs, container.NewVScroll(selected)))) +} + +func (d *Dashboard) graphCanvas(nodes []domain.Node) fyne.CanvasObject { + const maxVisible = 160 + visible := nodes + if len(visible) > maxVisible { + visible = visible[:maxVisible] + } + const columns = 5 + baseWidth := float32(210) * d.zoom + baseHeight := float32(80) * d.zoom + gapX := float32(42) * d.zoom + gapY := float32(66) * d.zoom + mapWidth := float32(columns)*(baseWidth+gapX) + 36 + rows := (len(visible) + columns - 1) / columns + mapHeight := float32(rows)*(baseHeight+gapY) + 40 + background := canvas.NewRectangle(color.NRGBA{R: 248, G: 250, B: 253, A: 255}) + if d.app != nil && d.app.Preferences().BoolWithFallback("appearance.dark", false) { + background.FillColor = color.NRGBA{R: 20, G: 31, B: 47, A: 255} + } + background.SetMinSize(fyne.NewSize(mapWidth, mapHeight)) + background.Resize(fyne.NewSize(mapWidth, mapHeight)) + objects := []fyne.CanvasObject{background} + positions := make(map[string]fyne.Position, len(visible)) + for index, node := range visible { + column, row := index%columns, index/columns + position := fyne.NewPos(18+float32(column)*(baseWidth+gapX), 18+float32(row)*(baseHeight+gapY)) + positions[node.ID] = position + } + for _, edge := range d.graph.Edges { + from, fromOK := positions[edge.From] + to, toOK := positions[edge.To] + if !fromOK || !toOK { + continue + } + line := canvas.NewLine(color.NRGBA{R: 105, G: 128, B: 157, A: 255}) + line.StrokeWidth = 1.5 * d.zoom + line.Position1 = fyne.NewPos(from.X+baseWidth, from.Y+baseHeight/2) + line.Position2 = fyne.NewPos(to.X, to.Y+baseHeight/2) + objects = append(objects, line) + } + for index, node := range visible { + position := positions[node.ID] + status := fmt.Sprintf("Impact %d/5 · %s/%s", node.Impact, node.EntityType, node.Kind) + button := widget.NewButton(node.Name+"\n"+status, func(record domain.Node) func() { + return func() { dialog.ShowInformation(record.Name, d.nodeDetails(record), d.window) } + }(node)) + button.Resize(fyne.NewSize(baseWidth, baseHeight)) + button.Move(position) + if index%2 == 0 { + button.Importance = widget.MediumImportance + } + objects = append(objects, button) + } + return container.NewWithoutLayout(objects...) +} + +func (d *Dashboard) nodeDetails(node domain.Node) string { + lines := []string{fmt.Sprintf("ID: %s", node.ID), fmt.Sprintf("Entity: %s", node.EntityType), fmt.Sprintf("Type: %s", node.Kind), fmt.Sprintf("Impact: %d/5", node.Impact), node.Description, "", "Direct relationships:"} + related := 0 + for _, edge := range d.graph.Edges { + if edge.From == node.ID || edge.To == node.ID { + lines = append(lines, fmt.Sprintf("%s — %s → %s · %s · %d%%", edge.ID, edge.From, edge.To, edge.Relation, edge.Confidence)) + related++ + } + } + for _, item := range d.graph.Misconfigurations { + if item.AssetID == node.ID || item.IdentityID == node.ID { + lines = append(lines, fmt.Sprintf("Misconfiguration · severity %d · %s", item.Severity, item.Title)) + related++ + } + } + for _, item := range d.graph.Findings { + if item.AssetID == node.ID || item.IdentityID == node.ID { + lines = append(lines, fmt.Sprintf("Finding · severity %d · %s · %s", item.Severity, item.Title, item.Source)) + related++ + } + } + if related == 0 { + lines = append(lines, "No direct relationships or findings are recorded.") + } + return strings.Join(lines, "\n") +} + +func (d *Dashboard) pathsScreen() fyne.CanvasObject { + rows := make([][]string, 0, len(d.paths)) + visible := make([]domain.Path, 0, len(d.paths)) + for _, path := range d.paths { + if d.matchesPath(path) { + visible = append(visible, path) + rows = append(rows, []string{pathLabel(path), fmt.Sprint(path.Score), fmt.Sprintf("%d%%", path.Confidence), path.Explanation}) + } + } + table := stringTable([]string{"Directed path", "Score", "Confidence", "Score breakdown"}, rows, []float32{340, 70, 90, 320}, func(row int) { + if row >= 0 && row < len(visible) { + d.showPathDetails(visible[row]) + } + }) + subtitle := "Impact tier × compounded edge confidence · select a row for exact components and evidence" + if d.summary.Paths.Truncated { + subtitle += " · result capped; rankings cover the bounded path set" + } + heading := []fyne.CanvasObject{d.heading("Ranked potential paths", subtitle)} + if d.impactFilter > 0 || d.confidenceFilter > 0 { + filterLabel := "Filtered path results" + if d.impactFilter > 0 { + filterLabel = fmt.Sprintf("Impact tier %d/5", d.impactFilter) + } + if d.confidenceFilter > 0 && d.confidenceFilter <= len(d.summary.Confidence) { + filterLabel = d.summary.Confidence[d.confidenceFilter-1].Label + " confidence" + } + heading = append(heading, container.NewHBox(widget.NewLabel("Filter: "+filterLabel), widget.NewButton("Clear filter", func() { d.impactFilter, d.confidenceFilter = 0, 0; d.show("paths") }))) + } + return container.NewPadded(container.NewBorder(container.NewVBox(heading...), nil, nil, nil, table)) +} + +func (d *Dashboard) assetsScreen() fyne.CanvasObject { + nodes := d.filteredNodes() + rows := make([][]string, len(nodes)) + for i, node := range nodes { + rows[i] = []string{node.Name, node.EntityType, node.Kind, fmt.Sprintf("%d/5", node.Impact), node.Description} + } + table := stringTable([]string{"Node", "Entity", "Type", "Impact", "Description"}, rows, []float32{210, 80, 120, 70, 300}, func(row int) { + if row >= 0 && row < len(nodes) { + dialog.ShowInformation(nodes[row].Name, d.nodeDetails(nodes[row]), d.window) + } + }) + return container.NewPadded(container.NewBorder(d.heading("Assets and identities", "Inventory records and linked relationships from the current local graph."), nil, nil, nil, table)) +} + +func (d *Dashboard) evidenceScreen() fyne.CanvasObject { + edges := d.filteredEdges() + rows := make([][]string, len(edges)) + for i, edge := range edges { + rows[i] = []string{edge.From + " → " + edge.To, edge.Relation, edge.Evidence.Source, edge.Evidence.Finding} + } + table := stringTable([]string{"Relationship", "Type", "Source", "Finding"}, rows, []float32{220, 150, 190, 340}, func(row int) { + if row >= 0 && row < len(edges) { + edge := edges[row] + dialog.ShowInformation("Relationship evidence", fmt.Sprintf("Edge: %s\n%s → %s\nRelationship: %s\nConfidence: %d%%\nSource: %s\nFinding: %s\nObserved: %s", edge.ID, edge.From, edge.To, edge.Relation, edge.Confidence, edge.Evidence.Source, edge.Evidence.Finding, edge.Evidence.Observed), d.window) + } + }) + return container.NewPadded(container.NewBorder(d.heading("Evidence", "Source records attached to every relationship."), nil, nil, nil, table)) +} + +func (d *Dashboard) remediationScreen() fyne.CanvasObject { + result := d.summary.Remediation + visible := make([]remediation.Suggestion, 0, len(result.Suggestions)) + rows := make([][]string, 0, len(result.Suggestions)) + for _, item := range result.Suggestions { + if d.search != "" && !strings.Contains(strings.ToLower(item.Relation+" "+item.EdgeID+" "+item.From+" "+item.To), d.search) { + continue + } + visible = append(visible, item) + rows = append(rows, []string{item.From + " → " + item.To, item.Relation, fmt.Sprint(item.PathsAffected), fmt.Sprint(item.CriticalPaths), fmt.Sprint(item.WeightedRiskPoints), item.EdgeID}) + } + table := stringTable([]string{"Relationship", "Permission", "Paths affected", "Critical", "Risk points", "Edge ID"}, rows, []float32{210, 170, 100, 80, 100, 170}, func(row int) { + if row >= 0 && row < len(visible) { + item := visible[row] + detail := fmt.Sprintf("%s\n\nPaths affected: %d\nCritical paths: %d\nWeighted risk points: %d\n\nThis is an advisory; the app does not modify inventory.", item.Recommendation, item.PathsAffected, item.CriticalPaths, item.WeightedRiskPoints) + for _, edge := range d.graph.Edges { + if edge.ID == item.EdgeID { + detail += fmt.Sprintf("\n\nEvidence source: %s\nFinding: %s\nObserved: %s", edge.Evidence.Source, edge.Evidence.Finding, edge.Evidence.Observed) + break + } + } + dialog.ShowInformation("Advisory remediation", detail, d.window) + } + }) + note := "Suggestions rank choke points by the number of enumerated paths affected, then weighted risk points." + if result.PathsTruncated { + note += " Path enumeration was truncated; rankings cover the displayed bounded result only." + } + return container.NewPadded(container.NewBorder(d.heading("Remediation priorities", note), nil, nil, nil, table)) +} + +func (d *Dashboard) importsScreen() fyne.CanvasObject { + open := widget.NewButton("Import graph JSON…", func() { d.openImport() }) + rows := make([][]string, 0, len(d.history)) + for _, item := range d.history { + rows = append(rows, []string{fmt.Sprint(item["imported_at"]), fmt.Sprint(item["source"]), fmt.Sprint(item["assets"]), fmt.Sprint(item["edges"]), fmt.Sprint(item["status"]), fmt.Sprint(item["message"])}) + } + table := stringTable([]string{"Imported at", "Source", "Assets", "Relationships", "Result", "Validation"}, rows, []float32{190, 190, 70, 110, 90, 290}, nil) + if len(rows) == 0 { + return container.NewPadded(container.NewVBox(d.heading("Imports", "Load synthetic or authorized JSON inventory."), open, d.emptyState("No import history", "The initial demo graph is loaded automatically on first run."))) + } + return container.NewPadded(container.NewBorder(container.NewVBox(d.heading("Imports", "Import history and validation status."), open), nil, nil, nil, table)) +} + +func (d *Dashboard) reportsScreen() fyne.CanvasObject { + graphButton := widget.NewButton("Export graph JSON…", func() { d.saveReport("graph") }) + copyGraph := widget.NewButton("Copy graph JSON", func() { d.copyReport("graph") }) + jsonButton := widget.NewButton("Export analysis JSON…", func() { d.saveReport("report-json") }) + copyJSON := widget.NewButton("Copy analysis JSON", func() { d.copyReport("report-json") }) + markdownButton := widget.NewButton("Export Markdown…", func() { d.saveReport("markdown") }) + copyMarkdown := widget.NewButton("Copy Markdown", func() { d.copyReport("markdown") }) + return container.NewPadded(container.NewVBox(d.heading("Reports", "Export local inventory, scored paths, evidence, and remediation advice to JSON or Markdown."), widget.NewCard("Graph export", "Assets, identities, relationships, and source evidence", container.NewHBox(graphButton, copyGraph)), widget.NewCard("Analysis report", "Ranked paths with exact score components and evidence", container.NewHBox(jsonButton, copyJSON)), widget.NewCard("Markdown report", "Human-readable path and choke-point remediation report", container.NewHBox(markdownButton, copyMarkdown)))) +} + +func (d *Dashboard) copyReport(kind string) { + var data []byte + var err error + label := "graph" + switch kind { + case "graph": + data, err = json.MarshalIndent(d.graph, "", " ") + case "report-json": + data, err = d.service.RenderReport(context.Background(), "json") + label = "analysis JSON report" + case "markdown": + data, err = d.service.RenderReport(context.Background(), "markdown") + label = "Markdown report" + default: + err = fmt.Errorf("unknown report kind %q", kind) + } + if err != nil { + dialog.ShowError(err, d.window) + return + } + dialog.ShowConfirm("Copy local data?", fmt.Sprintf("The %s includes local inventory data and evidence. Copy it to the clipboard?", label), func(ok bool) { + if ok { + d.window.Clipboard().SetContent(string(data)) + dialog.ShowInformation("Copied", fmt.Sprintf("The %s is on the clipboard.", label), d.window) + } + }, d.window) +} + +func (d *Dashboard) notificationsScreen() fyne.CanvasObject { + filtered := make([]repository.Notification, 0, len(d.notices)) + for _, item := range d.notices { + if d.matchesText(item.Title + " " + item.Detail + " " + item.Type + " " + fmt.Sprint(item.Severity)) { + filtered = append(filtered, item) + } + } + markRead := widget.NewButton("Mark all as read", func() { + if err := d.store.MarkAllNotificationsRead(context.Background()); err != nil { + dialog.ShowError(err, d.window) + return + } + _ = d.refresh() + d.show("notifications") + }) + settings := widget.NewButton("Notification rules…", func() { d.notificationRulesDialog() }) + if len(filtered) == 0 { + return container.NewPadded(container.NewVBox(d.heading("Notifications", "Local events · no external destinations"), container.NewHBox(markRead, settings), d.emptyState("You're up to date", "New critical paths and rejected imports appear here."))) + } + list := widget.NewList(func() int { return len(filtered) }, func() fyne.CanvasObject { + return widget.NewButtonWithIcon("Notification template", nil, nil) + }, func(id widget.ListItemID, object fyne.CanvasObject) { + if id < 0 || id >= len(filtered) { + return + } + item := filtered[id] + severityName, severityResource := severityIcon(item.Severity) + state := "Unread" + if item.Read { + state = "Read" + } + button := object.(*widget.Button) + button.Text = fmt.Sprintf("%s · %s · %s · %s", severityName, item.Title, state, item.CreatedAt.Local().Format("2006-01-02 15:04")) + button.Icon = severityResource + button.OnTapped = func() { + dialog.ShowConfirm(item.Title, item.Detail+"\n\nOpen the related local record?", func(open bool) { + _ = d.store.MarkNotificationRead(context.Background(), item.ID) + _ = d.refresh() + if open { + if item.Type == "critical_path" { + d.show("paths") + } else { + d.show("imports") + } + } else { + d.show("notifications") + } + }, d.window) + } + button.Refresh() + }) + return container.NewPadded(container.NewBorder(container.NewVBox(d.heading("Notifications", "Severity icon and text · local events · no external destinations"), container.NewHBox(markRead, settings)), nil, nil, nil, list)) +} + +func severityIcon(severity int) (string, fyne.Resource) { + name := "info" + label := "Informational" + switch { + case severity >= 5: + name, label = "critical", "Critical" + case severity == 4: + name, label = "high", "High" + case severity == 3: + name, label = "medium", "Medium" + case severity == 2: + name, label = "low", "Low" + } + resource, _ := icon("severity-" + name) + return fmt.Sprintf("%s %d", label, severity), resource +} + +func (d *Dashboard) aboutScreen() fyne.CanvasObject { + iconData, _ := assets.Files.ReadFile("icons/icon.png") + logo := canvas.NewImageFromImage(decodePNG(iconData)) + logo.SetMinSize(fyne.NewSize(72, 72)) + diagnostics := diagnosticReport() + diagPreview := widget.NewMultiLineEntry() + diagPreview.SetText(diagnostics) + diagPreview.Disable() + copyReport := widget.NewButton("Copy diagnostic report", func() { + dialog.ShowConfirm("Preview diagnostics", diagnostics+"\n\nOnly this sanitized report will be copied.", func(ok bool) { + if ok { + d.window.Clipboard().SetContent(diagnostics) + } + }, d.window) + }) + securityContact := widget.NewCard("Security vulnerability reporting", "Preferred: submit a private GitHub advisory. Backup: if you cannot use the GitHub form, email SuperMcDuck@proton.me.", widget.NewButton("Report a vulnerability privately", func() { d.confirmOpenURL(meta.SecurityAdvisory) })) + overview := container.NewVBox(container.NewHBox(logo, container.NewVBox(widget.NewLabelWithStyle(meta.Name, fyne.TextAlignLeading, fyne.TextStyle{Bold: true}), widget.NewLabel("Version "+meta.Version), widget.NewLabel(meta.Purpose))), widget.NewLabel(meta.License+" License · "+meta.Copyright), widget.NewLabel("Build: "+runtime.GOOS+"/"+runtime.GOARCH+" · "+runtime.Version()), widget.NewLabel("The application and third-party license texts are bundled for offline review."), widget.NewButton("Source Code", func() { d.confirmOpenURL(meta.Repository) }), widget.NewButton("Found a bug? Please report it on GitHub.", func() { d.previewBugReport() }), securityContact) + usage, _ := assets.Files.ReadFile("docs/USAGE.md") + usageSearch := widget.NewEntry() + usageSearch.SetPlaceHolder("Find in the offline usage guide") + usageText := widget.NewMultiLineEntry() + usageText.SetText(string(usage)) + usageText.Disable() + usageSearch.OnChanged = func(search string) { + if strings.TrimSpace(search) == "" { + usageText.SetText(string(usage)) + return + } + lines := strings.Split(string(usage), "\n") + matches := make([]string, 0) + for index, line := range lines { + if strings.Contains(strings.ToLower(line), strings.ToLower(search)) { + start := index - 1 + if start < 0 { + start = 0 + } + end := index + 2 + if end > len(lines) { + end = len(lines) + } + matches = append(matches, strings.Join(lines[start:end], "\n")) + } + } + if len(matches) == 0 { + usageText.SetText("No matching guidance was found.") + } else { + usageText.SetText(strings.Join(matches, "\n\n---\n\n")) + } + } + usagePage := container.NewBorder(usageSearch, widget.NewButton("Open full documentation on GitHub", func() { d.confirmOpenURL(meta.Repository + "/blob/main/docs/USAGE.md") }), nil, nil, usageText) + shortcuts := widget.NewMultiLineEntry() + shortcuts.SetText("Ctrl/Cmd+1 … 9 Navigate categories\nCtrl/Cmd+F Focus global search\nCtrl/Cmd+, Open Settings\nF1 Open Usage guide\nEnter Open selected table record") + shortcuts.Disable() + readmeText := widget.NewMultiLineEntry() + readmeData, _ := assets.Files.ReadFile("docs/README.md") + readmeText.SetText(string(readmeData)) + readmeText.Disable() + licenseText := widget.NewMultiLineEntry() + licenseData, _ := assets.Files.ReadFile("docs/LICENSES.md") + licenseText.SetText(string(licenseData)) + licenseText.Disable() + thirdPartyNotices, _ := assets.Files.ReadFile("docs/THIRD_PARTY_NOTICES.md") + licenseOptions := []string{"Offline license summary", "Third-party dependency inventory"} + _ = fs.WalkDir(assets.Files, "licenses", func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if !entry.IsDir() { + licenseOptions = append(licenseOptions, strings.TrimPrefix(path, "licenses/")) + } + return nil + }) + licenseChoice := widget.NewSelect(licenseOptions, func(name string) { + if name == "Offline license summary" { + licenseText.SetText(string(licenseData)) + return + } + if name == "Third-party dependency inventory" { + licenseText.SetText(string(thirdPartyNotices)) + return + } + data, err := assets.Files.ReadFile("licenses/" + name) + if err != nil { + licenseText.SetText("Could not read the bundled license: " + err.Error()) + return + } + licenseText.SetText(string(data)) + }) + licenseChoice.SetSelected("Offline license summary") + licensePage := container.NewBorder(licenseChoice, nil, nil, nil, licenseText) + tabs := container.NewAppTabs(container.NewTabItem("Overview", overview), container.NewTabItem("README", readmeText), container.NewTabItem("Usage guide", usagePage), container.NewTabItem("Shortcuts", shortcuts), container.NewTabItem("Diagnostics", container.NewVBox(diagPreview, copyReport)), container.NewTabItem("Licenses & notices", licensePage)) + return container.NewPadded(container.NewBorder(d.heading("About", "Application identity, offline help, and sanitized diagnostics."), nil, nil, nil, tabs)) +} + +func (d *Dashboard) settingsScreen() fyne.CanvasObject { + dark := d.app.Preferences().BoolWithFallback("appearance.dark", false) + appearance := widget.NewCheck("Use dark appearance", func(value bool) { + d.app.Preferences().SetBool("appearance.dark", value) + if value { + d.app.Settings().SetTheme(productTheme{dark: true}) + } else { + d.app.Settings().SetTheme(productTheme{}) + } + }) + appearance.SetChecked(dark) + compact := widget.NewCheck("Use compact table rows", func(value bool) { + d.app.Preferences().SetBool("table.compact", value) + d.show(d.current) + }) + compact.SetChecked(d.app.Preferences().BoolWithFallback("table.compact", false)) + windowInfo := widget.NewLabel("Window size is restored between sessions; the platform window manager controls window position.") + ask := widget.NewCheck("Ask me every time at launch", func(value bool) { + if value { + _ = launcher.SavePreference("") + } else { + _ = launcher.SavePreference("gui") + } + }) + ask.SetChecked(launcher.ReadPreference() == "") + reset := widget.NewButton("Reset saved launch choice", func() { + if err := launcher.SavePreference(""); err != nil { + dialog.ShowError(err, d.window) + return + } + dialog.ShowInformation("Launcher preference reset", "The next launch will ask you to choose a front end.", d.window) + ask.SetChecked(true) + }) + dbPath := d.store.Path() + installedPath, installed, installErr := notifier.Status() + if installErr != nil { + installedPath = "Status unavailable: " + installErr.Error() + } + var background *widget.Check + background = widget.NewCheck("Enable opt-in background OS notifications", func(value bool) { + if value { + dialog.ShowConfirm("Install background notifier?", "This installs a per-user startup entry. The notifier reads the local database every 15 minutes, sends OS notifications, and makes no network calls. Continue?", func(ok bool) { + if !ok { + background.SetChecked(false) + return + } + executable, err := os.Executable() + if err == nil { + _, err = notifier.Install(executable, d.store.Path()) + } + if err != nil { + background.SetChecked(false) + dialog.ShowError(err, d.window) + return + } + dialog.ShowInformation("Notifier installed", "Background notifications are enabled for this user.", d.window) + }, d.window) + } else { + dialog.ShowConfirm("Uninstall background notifier?", "The per-user startup entry will be removed. Existing in-app notifications will remain.", func(ok bool) { + if !ok { + background.SetChecked(true) + return + } + _, err := notifier.Uninstall() + if err != nil { + background.SetChecked(true) + dialog.ShowError(err, d.window) + return + } + dialog.ShowInformation("Notifier uninstalled", "The per-user startup entry was removed.", d.window) + }, d.window) + } + }) + background.SetChecked(installed) + appearancePanel := widget.NewCard("Appearance", "Custom light and dark themes use the bundled Noto Sans family.", container.NewVBox(appearance, compact, windowInfo)) + launchPanel := widget.NewCard("Launch behavior", "Preferences are stored in the OS user configuration directory with private permissions.", container.NewVBox(ask, reset)) + dataPanel := widget.NewCard("Data location", "SQLite data stays on this device.", widget.NewLabel(dbPath)) + notifierPanel := widget.NewCard("Background notifications", "Opt-in only · 15-minute polling · local database read-only · no network calls", container.NewVBox(background, widget.NewLabel(installedPath))) + privacy := widget.NewLabel("No telemetry or integrations are configured. Destructive inventory changes require an explicit import; imported graphs replace stored relationships atomically.") + return container.NewPadded(container.NewVBox(d.heading("Settings", "Appearance, launcher defaults, local data and notification status."), appearancePanel, launchPanel, dataPanel, notifierPanel, privacy)) +} + +func (d *Dashboard) openImport() { + fileDialog := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) { + if err != nil { + dialog.ShowError(err, d.window) + return + } + if reader == nil { + return + } + data, readErr := io.ReadAll(io.LimitReader(reader, 8<<20+1)) + closeErr := reader.Close() + if readErr == nil { + readErr = closeErr + } + if readErr != nil { + dialog.ShowError(readErr, d.window) + return + } + dialog.ShowConfirm("Replace local graph?", "The selected JSON file will replace the currently stored assets and relationships after validation. Invalid input leaves the existing graph unchanged.", func(confirmed bool) { + if !confirmed { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + if err := d.service.Import(ctx, bytes.NewReader(data), "user JSON import"); err != nil { + dialog.ShowError(err, d.window) + _ = d.refresh() + d.show("imports") + return + } + if err := d.refresh(); err != nil { + dialog.ShowError(err, d.window) + return + } + d.show("imports") + dialog.ShowInformation("Import complete", "The graph was validated and saved atomically.", d.window) + }, d.window) + }, d.window) + fileDialog.SetFilter(storageJSONFilter{}) + fileDialog.Show() +} + +type storageJSONFilter struct{} + +func (storageJSONFilter) Matches(uri fyne.URI) bool { + return strings.EqualFold(filepath.Ext(uri.Name()), ".json") +} + +func (storageJSONFilter) Add(uri fyne.URI) { +} + +func (storageJSONFilter) Includes(uri fyne.URI) bool { + return storageJSONFilter{}.Matches(uri) +} + +func (d *Dashboard) saveReport(kind string) { + var data []byte + var err error + extension := ".json" + switch kind { + case "graph": + data, err = json.MarshalIndent(d.graph, "", " ") + case "report-json": + data, err = d.service.RenderReport(context.Background(), "json") + case "markdown": + data, err = d.service.RenderReport(context.Background(), "markdown") + extension = ".md" + default: + err = fmt.Errorf("unknown report kind %q", kind) + } + if err != nil { + dialog.ShowError(err, d.window) + return + } + fileDialog := dialog.NewFileSave(func(writer fyne.URIWriteCloser, err error) { + if err != nil { + dialog.ShowError(err, d.window) + return + } + if writer == nil { + return + } + defer writer.Close() + if _, err := writer.Write(data); err != nil { + dialog.ShowError(err, d.window) + return + } + dialog.ShowInformation("Report exported", "The report was saved to the selected file.", d.window) + }, d.window) + fileDialog.SetFileName("attackpath-" + kind + extension) + if extension == ".json" { + fileDialog.SetFilter(storageJSONFilter{}) + } + fileDialog.Show() +} + +func (d *Dashboard) notificationRulesDialog() { + ctx := context.Background() + rules, err := d.store.NotificationRules(ctx) + if err != nil { + dialog.ShowError(err, d.window) + return + } + critical := rules["critical_path"] + validation := rules["validation_failed"] + criticalCheck := widget.NewCheck("Notify in app for new critical paths", nil) + criticalCheck.SetChecked(critical.Enabled) + criticalSelect := widget.NewSelect([]string{"Severity 1+", "Severity 2+", "Severity 3+", "Severity 4+", "Severity 5"}, nil) + criticalSelect.SetSelectedIndex(critical.MinimumSeverity - 1) + validationCheck := widget.NewCheck("Notify in app for invalid imports", nil) + validationCheck.SetChecked(validation.Enabled) + validationSelect := widget.NewSelect([]string{"Severity 1+", "Severity 2+", "Severity 3+", "Severity 4+", "Severity 5"}, nil) + validationSelect.SetSelectedIndex(validation.MinimumSeverity - 1) + detailCheck := widget.NewCheck("Include extra detail in OS notification text", nil) + detailCheck.SetChecked(critical.DetailedText) + start := widget.NewEntry() + start.SetText(critical.QuietStart) + start.SetPlaceHolder("22:00") + end := widget.NewEntry() + end.SetText(critical.QuietEnd) + end.SetPlaceHolder("07:00") + quiet := container.NewGridWithColumns(2, start, end) + content := container.NewVBox(widget.NewLabel("Severity combines a number and label. Quiet hours apply to background OS notices; in-app events remain visible."), criticalCheck, criticalSelect, validationCheck, validationSelect, detailCheck, widget.NewLabel("Quiet hours (local time, HH:MM)"), quiet) + dialog.ShowCustomConfirm("Notification rules", "Save", "Cancel", content, func(ok bool) { + if !ok { + return + } + if _, err := time.Parse("15:04", start.Text); err != nil { + dialog.ShowInformation("Invalid quiet-hours start", "Enter a local time in HH:MM format.", d.window) + return + } + if _, err := time.Parse("15:04", end.Text); err != nil { + dialog.ShowInformation("Invalid quiet-hours end", "Enter a local time in HH:MM format.", d.window) + return + } + critical.MinimumSeverity = criticalSelect.SelectedIndex() + 1 + critical.Enabled = criticalCheck.Checked + critical.DetailedText = detailCheck.Checked + critical.QuietStart, critical.QuietEnd = start.Text, end.Text + validation.MinimumSeverity = validationSelect.SelectedIndex() + 1 + validation.Enabled = validationCheck.Checked + validation.DetailedText = detailCheck.Checked + validation.QuietStart, validation.QuietEnd = start.Text, end.Text + if err := d.store.SaveNotificationRule(ctx, "critical_path", critical); err != nil { + dialog.ShowError(err, d.window) + return + } + if err := d.store.SaveNotificationRule(ctx, "validation_failed", validation); err != nil { + dialog.ShowError(err, d.window) + return + } + dialog.ShowInformation("Notification rules saved", "New events will follow the configured severity and quiet hours.", d.window) + }, d.window) +} + +func (d *Dashboard) previewBugReport() { + diagnostics := diagnosticReport() + title := url.QueryEscape("Bug report: AttackPath Visualizer") + body := url.QueryEscape("## Description\n\n## Steps to reproduce\n\n## Sanitized diagnostics\n" + diagnostics) + issueURL := meta.Issues + "?title=" + title + "&body=" + body + if len(issueURL) > 7000 { + d.window.Clipboard().SetContent(diagnostics) + issueURL = meta.Issues + dialog.ShowInformation("Diagnostics copied", "The report was too long for a safe URL. The sanitized diagnostics were copied; the blank issue form will open next.", d.window) + } + d.confirmOpenURL(issueURL) +} + +func (d *Dashboard) confirmOpenURL(target string) { + if !AllowedRepositoryURL(target) { + dialog.ShowInformation("External link unavailable", "The configured repository link is invalid; no external page was opened.", d.window) + return + } + dialog.ShowConfirm("Open external page?", "The operating-system browser will open:\n"+target, func(ok bool) { + if ok { + if err := openExternal(target); err != nil { + dialog.ShowError(err, d.window) + } + } + }, d.window) +} + +func AllowedRepositoryURL(target string) bool { + parsed, err := url.Parse(target) + if err != nil || parsed.Scheme != "https" || parsed.Host != "github.com" { + return false + } + return parsed.Path == "/NexzaDev/attackpath-visualizer" || strings.HasPrefix(parsed.Path, "/NexzaDev/attackpath-visualizer/") +} + +func openExternal(target string) error { + var command string + var args []string + switch runtime.GOOS { + case "windows": + command, args = "rundll32", []string{"url.dll,FileProtocolHandler", target} + case "darwin": + command, args = "open", []string{target} + default: + command, args = "xdg-open", []string{target} + } + if _, err := exec.LookPath(command); err != nil { + return fmt.Errorf("no OS browser handler was found; open this URL manually: %s", target) + } + if err := exec.Command(command, args...).Start(); err != nil { + return fmt.Errorf("open external link: %w", err) + } + return nil +} + +func pathLabel(path domain.Path) string { + labels := make([]string, len(path.Nodes)) + for index, node := range path.Nodes { + labels[index] = fmt.Sprintf("%s [%s]", node.Name, node.ID) + } + return strings.Join(labels, " → ") +} + +func (d *Dashboard) showPathDetails(path domain.Path) { + lines := []string{path.Explanation, fmt.Sprintf("Impact component: tier %d/5", path.Components.ImpactTier), fmt.Sprintf("Edge confidence components: %v", path.Components.EdgeConfidences), fmt.Sprintf("Compounded confidence: %d%%", path.Components.CompoundedConfidence), fmt.Sprintf("Score: %d points", path.Components.Score), "", "Evidence by edge:"} + for _, edge := range path.Edges { + lines = append(lines, fmt.Sprintf("• %s → %s · %s · %d%%", edge.From, edge.To, edge.Relation, edge.Confidence), fmt.Sprintf(" Source: %s", edge.Evidence.Source), fmt.Sprintf(" Finding: %s", edge.Evidence.Finding), fmt.Sprintf(" Observed: %s", edge.Evidence.Observed)) + } + dialog.ShowInformation("Potential path details", strings.Join(lines, "\n"), d.window) +} + +func (d *Dashboard) chokePoints() fyne.CanvasObject { + items := make([]fyne.CanvasObject, 0, 4) + for index, suggestion := range d.summary.Remediation.Suggestions { + if index == 4 { + break + } + items = append(items, widget.NewLabel(fmt.Sprintf("%d paths · %s — %s → %s · %d risk points", suggestion.PathsAffected, suggestion.EdgeID, suggestion.From, suggestion.To, suggestion.WeightedRiskPoints))) + } + if len(items) == 0 { + return widget.NewLabel("No path-affecting edges are currently available.") + } + return container.NewVBox(items...) +} + +func (d *Dashboard) filteredNodes() []domain.Node { + all := d.graph.Nodes() + result := make([]domain.Node, 0, len(all)) + for _, node := range all { + value := node.Name + " " + node.EntityType + " " + node.Kind + " " + node.ID + " " + node.Description + for _, item := range d.graph.Misconfigurations { + if item.AssetID == node.ID || item.IdentityID == node.ID { + value += fmt.Sprintf(" %s %s severity %d", item.Title, item.Description, item.Severity) + } + } + for _, item := range d.graph.Findings { + if item.AssetID == node.ID || item.IdentityID == node.ID { + value += fmt.Sprintf(" %s %s %s %s severity %d", item.Title, item.Source, item.Observed, item.MisconfigurationID, item.Severity) + } + } + if d.search == "" || strings.Contains(strings.ToLower(value), d.search) { + result = append(result, node) + } + } + return result +} + +func (d *Dashboard) filteredEdges() []domain.Edge { + result := make([]domain.Edge, 0, len(d.graph.Edges)) + for _, edge := range d.graph.Edges { + value := strings.ToLower(edge.ID + " " + edge.From + " " + edge.To + " " + edge.Relation + " " + edge.Evidence.Source + " " + edge.Evidence.Finding + " " + edge.Evidence.Observed) + if d.search == "" || strings.Contains(value, d.search) { + result = append(result, edge) + } + } + return result +} + +func (d *Dashboard) matchesPath(path domain.Path) bool { + if d.impactFilter > 0 && path.Impact != d.impactFilter { + return false + } + if d.confidenceFilter > 0 && min(path.Confidence/20, 4)+1 != d.confidenceFilter { + return false + } + value := pathLabel(path) + " " + path.Explanation + for _, node := range path.Nodes { + value += " " + node.Name + " " + node.ID + } + for _, edge := range path.Edges { + value += " " + edge.Relation + " " + edge.Evidence.Finding + " " + edge.Evidence.Source + } + return d.matchesText(value) +} + +func (d *Dashboard) matchesText(value string) bool { + return d.search == "" || strings.Contains(strings.ToLower(value), d.search) +} + +func (d *Dashboard) emptyState(title, detail string) fyne.CanvasObject { + return container.NewCenter(widget.NewCard(title, "No records to show", widget.NewLabel(detail))) +} + +func stringTable(headers []string, rows [][]string, widths []float32, selected func(int)) *widget.Table { + rowOrder := make([]int, len(rows)) + for index := range rows { + rowOrder[index] = index + } + table := widget.NewTable(func() (int, int) { return len(rows) + 1, len(headers) }, func() fyne.CanvasObject { + return widget.NewLabel("template") + }, func(id widget.TableCellID, object fyne.CanvasObject) { + label := object.(*widget.Label) + label.Wrapping = fyne.TextWrapOff + if id.Row == 0 { + label.SetText(headers[id.Col] + " ↕") + label.TextStyle = fyne.TextStyle{Bold: true} + return + } + if id.Row-1 < 0 || id.Row-1 >= len(rowOrder) { + label.SetText("") + return + } + row := rowOrder[id.Row-1] + if row < 0 || row >= len(rows) || id.Col >= len(rows[row]) { + label.SetText("") + return + } + label.TextStyle = fyne.TextStyle{} + label.SetText(rows[row][id.Col]) + }) + for index, width := range widths { + table.SetColumnWidth(index, width) + } + rowHeight := float32(38) + if app := fyne.CurrentApp(); app != nil && app.Preferences().BoolWithFallback("table.compact", false) { + rowHeight = 27 + } + table.SetRowHeight(-1, rowHeight) + sortedColumn := -1 + ascending := true + table.OnSelected = func(id widget.TableCellID) { + if id.Row == 0 && id.Col >= 0 && id.Col < len(headers) { + if sortedColumn == id.Col { + ascending = !ascending + } else { + sortedColumn = id.Col + ascending = true + } + sort.SliceStable(rowOrder, func(left, right int) bool { + leftRow := rows[rowOrder[left]] + rightRow := rows[rowOrder[right]] + if id.Col >= len(leftRow) || id.Col >= len(rightRow) { + return false + } + leftText := strings.ToLower(leftRow[id.Col]) + rightText := strings.ToLower(rightRow[id.Col]) + leftNumber, leftErr := strconv.ParseFloat(strings.TrimSuffix(leftText, "%"), 64) + rightNumber, rightErr := strconv.ParseFloat(strings.TrimSuffix(rightText, "%"), 64) + if leftErr == nil && rightErr == nil { + if ascending { + return leftNumber < rightNumber + } + return leftNumber > rightNumber + } + if ascending { + return leftText < rightText + } + return leftText > rightText + }) + table.UnselectAll() + table.Refresh() + return + } + if id.Row > 0 && selected != nil && id.Row-1 < len(rowOrder) { + selected(rowOrder[id.Row-1]) + } + } + return table +} + +func decodePNG(data []byte) image.Image { + imageData, err := png.Decode(bytes.NewReader(data)) + if err != nil { + return nil + } + return imageData +} + +func icon(name string) (fyne.Resource, error) { + data, err := assets.Files.ReadFile("icons/nav/" + name + ".svg") + if err != nil { + return nil, err + } + if app := fyne.CurrentApp(); app != nil && app.Preferences().BoolWithFallback("appearance.dark", false) { + svg := string(data) + for original, replacement := range map[string]string{"#334155": "#D4DFED", "#b4232e": "#FF9095", "#c44e28": "#FFAA7A", "#9a6b11": "#F4D078", "#3f6a9f": "#8FBCF7", "#52657e": "#BBC9DB"} { + svg = strings.ReplaceAll(svg, original, replacement) + } + data = []byte(svg) + } + return fyne.NewStaticResource(name+".svg", data), nil +} + +func diagnosticReport() string { + return fmt.Sprintf("Application: %s\nVersion: %s\nOS: %s\nArchitecture: %s\nGo runtime: %s\nConfiguration: local SQLite enabled; no credentials configured\nTelemetry: disabled", meta.Name, meta.Version, runtime.GOOS, runtime.GOARCH, runtime.Version()) +} diff --git a/gui/dashboard_test.go b/gui/dashboard_test.go new file mode 100644 index 0000000..aad7607 --- /dev/null +++ b/gui/dashboard_test.go @@ -0,0 +1,103 @@ +//go:build !nogui + +package gui + +import ( + "context" + "os" + "path/filepath" + "testing" + + "fyne.io/fyne/v2/test" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" + "github.com/NexzaDev/attackpath-visualizer/internal/service" +) + +func TestEveryNavigationCategoryBuildsARealScreen(t *testing.T) { + application := test.NewApp() + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err = (service.Service{Store: store}).LoadDemo(context.Background()); err != nil { + t.Fatal(err) + } + dashboard, err := NewDashboard(application, nil, store, nil) + if err != nil { + t.Fatal(err) + } + seen := make(map[string]bool) + for _, category := range Categories { + if dashboard.Screen(category.ID) == nil { + t.Errorf("category %q has no screen", category.ID) + } + seen[category.ID] = true + } + if len(seen) != 11 { + t.Fatalf("expected 11 navigation screens, got %d", len(seen)) + } +} + +func TestGlobalSearchFindsNodesThroughLinkedFindings(t *testing.T) { + application := test.NewApp() + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err = (service.Service{Store: store}).LoadDemo(context.Background()); err != nil { + t.Fatal(err) + } + dashboard, err := NewDashboard(application, nil, store, nil) + if err != nil { + t.Fatal(err) + } + dashboard.search = "stale credential reference" + found := make(map[string]bool) + for _, node := range dashboard.filteredNodes() { + found[node.ID] = true + } + if !found["secret-store"] || !found["deploy-bot"] { + t.Fatalf("global search did not match nodes through their linked finding: %#v", found) + } +} + +func TestAboutLinksStayWithinConfiguredRepository(t *testing.T) { + allowed := []string{ + "https://github.com/NexzaDev/attackpath-visualizer", + "https://github.com/NexzaDev/attackpath-visualizer/issues/new", + "https://github.com/NexzaDev/attackpath-visualizer/blob/main/docs/USAGE.md", + "https://github.com/NexzaDev/attackpath-visualizer/security/advisories/new", + } + for _, target := range allowed { + if !AllowedRepositoryURL(target) { + t.Errorf("expected configured link to pass: %s", target) + } + } + blocked := []string{ + "http://github.com/NexzaDev/attackpath-visualizer", + "https://github.com.evil.example/NexzaDev/attackpath-visualizer", + "https://github.com/another/project", + "https://github.com/NexzaDev/attackpath-visualizer.evil", + "javascript:alert(1)", + } + for _, target := range blocked { + if AllowedRepositoryURL(target) { + t.Errorf("unexpectedly allowed external link: %s", target) + } + } +} + +func TestSoftwareRendererProducesAllScreenImages(t *testing.T) { + application := test.NewApp() + output := t.TempDir() + if err := RenderScreenshots(output, application); err != nil { + t.Fatal(err) + } + for _, category := range Categories { + if _, err := os.Stat(filepath.Join(output, category.ID+".png")); err != nil { + t.Errorf("missing screenshot for %s: %v", category.ID, err) + } + } +} diff --git a/gui/run.go b/gui/run.go new file mode 100644 index 0000000..cfae7d5 --- /dev/null +++ b/gui/run.go @@ -0,0 +1,194 @@ +//go:build !nogui + +package gui + +import ( + "fmt" + "os" + "runtime" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/app" + "fyne.io/fyne/v2/container" + "fyne.io/fyne/v2/dialog" + "fyne.io/fyne/v2/driver/desktop" + "fyne.io/fyne/v2/widget" + "github.com/NexzaDev/attackpath-visualizer/assets" + "github.com/NexzaDev/attackpath-visualizer/internal/config" + "github.com/NexzaDev/attackpath-visualizer/internal/launcher" + "github.com/NexzaDev/attackpath-visualizer/internal/meta" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" +) + +func Run(requestedDB string) error { + application := app.NewWithID(meta.ID) + application.Settings().SetTheme(productTheme{}) + path, err := config.DatabasePath(requestedDB) + if err != nil { + return err + } + store, err := repository.Open(path) + if err != nil { + return err + } + defer store.Close() + window := application.NewWindow(meta.Name) + setAppIcon(application, window) + dashboard, err := NewDashboard(application, window, store, func(mode string) error { + if mode == "tui" { + if err := launcher.StartTerminal(); err != nil { + return err + } + application.Quit() + } + return nil + }) + if err != nil { + return err + } + window.Resize(savedWindowSize(application)) + window.CenterOnScreen() + window.SetOnClosed(func() { saveWindowSize(application, window) }) + window.SetContent(dashboard.Content()) + setMenu(window, dashboard) + setShortcuts(window, dashboard) + window.ShowAndRun() + return nil +} + +func ShowChooser(requestedDB string) error { + application := app.NewWithID(meta.ID) + application.Settings().SetTheme(productTheme{}) + window := application.NewWindow("How do you want to open AttackPath Visualizer?") + setAppIcon(application, window) + remember := widget.NewCheck("Remember my choice", nil) + remember.SetChecked(launcher.ReadPreference() != "") + launch := func(mode string) { + if remember.Checked { + if err := launcher.SavePreference(mode); err != nil { + dialog.ShowError(err, window) + return + } + } else if err := launcher.SavePreference(""); err != nil { + dialog.ShowError(err, window) + return + } + if mode == "tui" { + if err := launcher.StartTerminal(); err != nil { + dialog.ShowInformation("Terminal not found", err.Error(), window) + return + } + application.Quit() + return + } + path, err := config.DatabasePath(requestedDB) + if err != nil { + dialog.ShowError(err, window) + return + } + store, err := repository.Open(path) + if err != nil { + dialog.ShowError(err, window) + return + } + dashboardWindow := application.NewWindow(meta.Name) + setAppIcon(application, dashboardWindow) + dashboard, err := NewDashboard(application, dashboardWindow, store, func(mode string) error { + if mode == "tui" { + if err := launcher.StartTerminal(); err != nil { + return err + } + application.Quit() + } + return nil + }) + if err != nil { + store.Close() + dialog.ShowError(err, window) + return + } + window.Hide() + dashboardWindow.Resize(savedWindowSize(application)) + dashboardWindow.CenterOnScreen() + dashboardWindow.SetContent(dashboard.Content()) + setMenu(dashboardWindow, dashboard) + setShortcuts(dashboardWindow, dashboard) + dashboardWindow.SetOnClosed(func() { + saveWindowSize(application, dashboardWindow) + if closeErr := store.Close(); closeErr != nil { + fmt.Fprintln(os.Stderr, "close database:", closeErr) + } + application.Quit() + }) + dashboardWindow.Show() + } + dashboardButton := widget.NewButton("Dashboard (graphical window)", func() { launch("gui") }) + dashboardButton.Importance = widget.HighImportance + terminalButton := widget.NewButton("Terminal (text interface)", func() { launch("tui") }) + quitButton := widget.NewButton("Quit", application.Quit) + iconData, _ := assets.Files.ReadFile("icons/icon.png") + logo := widget.NewIcon(fyne.NewStaticResource("attackpath-visualizer.png", iconData)) + window.SetContent(container.NewCenter(container.NewVBox(container.NewCenter(logo), widget.NewLabelWithStyle("How do you want to open AttackPath Visualizer?", fyne.TextAlignCenter, fyne.TextStyle{Bold: true}), dashboardButton, terminalButton, remember, quitButton))) + window.Resize(fyne.NewSize(480, 330)) + window.CenterOnScreen() + window.ShowAndRun() + return nil +} + +func savedWindowSize(application fyne.App) fyne.Size { + width := application.Preferences().FloatWithFallback("window.width", 1360) + height := application.Preferences().FloatWithFallback("window.height", 900) + if width < 900 || width > 4000 { + width = 1360 + } + if height < 600 || height > 3000 { + height = 900 + } + return fyne.NewSize(float32(width), float32(height)) +} + +func saveWindowSize(application fyne.App, window fyne.Window) { + size := window.Canvas().Size() + if size.Width >= 900 && size.Height >= 600 { + application.Preferences().SetFloat("window.width", float64(size.Width)) + application.Preferences().SetFloat("window.height", float64(size.Height)) + } +} + +func setAppIcon(application fyne.App, window fyne.Window) { + iconData, err := assets.Files.ReadFile("icons/icon.png") + if err == nil { + resource := fyne.NewStaticResource("attackpath-visualizer.png", iconData) + application.SetIcon(resource) + window.SetIcon(resource) + } +} + +func setMenu(window fyne.Window, dashboard *Dashboard) { + fileMenu := fyne.NewMenu("Application", fyne.NewMenuItem("Export graph…", func() { dashboard.saveReport("graph") }), fyne.NewMenuItem("Switch to Terminal", func() { + if dashboard.switchMode != nil { + if err := dashboard.switchMode("tui"); err != nil { + dialog.ShowError(err, window) + } + } + }), fyne.NewMenuItem("Quit", func() { window.Close() })) + helpMenu := fyne.NewMenu("Help", fyne.NewMenuItem("Usage guide F1", func() { dashboard.show("about") }), fyne.NewMenuItem("About", func() { dashboard.show("about") })) + window.SetMainMenu(fyne.NewMainMenu(fileMenu, helpMenu)) +} + +func setShortcuts(window fyne.Window, dashboard *Dashboard) { + modifier := fyne.KeyModifierControl + if runtime.GOOS == "darwin" { + modifier = fyne.KeyModifierSuper + } + for index, category := range Categories[:9] { + id := category.ID + window.Canvas().AddShortcut(&desktop.CustomShortcut{KeyName: fyne.KeyName(fmt.Sprint(index + 1)), Modifier: modifier}, func(fyne.Shortcut) { dashboard.show(id) }) + } + window.Canvas().AddShortcut(&desktop.CustomShortcut{KeyName: fyne.KeyF, Modifier: modifier}, func(fyne.Shortcut) { + dashboard.searchBox.FocusGained() + window.Canvas().Focus(dashboard.searchBox) + }) + window.Canvas().AddShortcut(&desktop.CustomShortcut{KeyName: fyne.KeyComma, Modifier: modifier}, func(fyne.Shortcut) { dashboard.show("settings") }) + window.Canvas().AddShortcut(&desktop.CustomShortcut{KeyName: fyne.KeyF1}, func(fyne.Shortcut) { dashboard.show("about") }) +} diff --git a/gui/screenshots.go b/gui/screenshots.go new file mode 100644 index 0000000..c5c787e --- /dev/null +++ b/gui/screenshots.go @@ -0,0 +1,54 @@ +//go:build !nogui + +package gui + +import ( + "context" + "fmt" + "image/png" + "os" + "path/filepath" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/driver/software" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" + "github.com/NexzaDev/attackpath-visualizer/internal/service" +) + +func RenderScreenshots(outputDir string, app fyne.App) error { + if err := os.MkdirAll(outputDir, 0700); err != nil { + return fmt.Errorf("create screenshot directory: %w", err) + } + store, err := repository.Open(":memory:") + if err != nil { + return err + } + defer store.Close() + if err = (service.Service{Store: store}).LoadDemo(context.Background()); err != nil { + return err + } + dashboard, err := NewDashboard(app, nil, store, nil) + if err != nil { + return err + } + for _, category := range Categories { + dashboard.current = category.ID + canvas := software.NewCanvas() + canvas.SetPadded(false) + canvas.Resize(fyne.NewSize(1440, 900)) + canvas.SetContent(dashboard.Content()) + imageData := software.RenderCanvas(canvas, productTheme{}) + file, err := os.Create(filepath.Join(outputDir, category.ID+".png")) + if err != nil { + return fmt.Errorf("create %s screenshot: %w", category.ID, err) + } + if err = png.Encode(file, imageData); err != nil { + file.Close() + return fmt.Errorf("write %s screenshot: %w", category.ID, err) + } + if err = file.Close(); err != nil { + return fmt.Errorf("close %s screenshot: %w", category.ID, err) + } + } + return nil +} diff --git a/gui/theme.go b/gui/theme.go new file mode 100644 index 0000000..912d11d --- /dev/null +++ b/gui/theme.go @@ -0,0 +1,110 @@ +//go:build !nogui + +package gui + +import ( + "image/color" + + "fyne.io/fyne/v2" + "fyne.io/fyne/v2/theme" + "github.com/NexzaDev/attackpath-visualizer/assets" +) + +type productTheme struct { + dark bool +} + +func (t productTheme) Color(name fyne.ThemeColorName, variant fyne.ThemeVariant) color.Color { + dark := t.dark || variant == theme.VariantDark + if dark { + switch name { + case theme.ColorNameBackground: + return color.NRGBA{R: 15, G: 24, B: 39, A: 255} + case theme.ColorNameForeground: + return color.NRGBA{R: 231, G: 237, B: 245, A: 255} + case theme.ColorNamePrimary, theme.ColorNameFocus, theme.ColorNameHyperlink: + return color.NRGBA{R: 125, G: 151, B: 255, A: 255} + case theme.ColorNameButton, theme.ColorNameHeaderBackground, theme.ColorNameInputBackground: + return color.NRGBA{R: 29, G: 43, B: 62, A: 255} + case theme.ColorNameSeparator, theme.ColorNameInputBorder: + return color.NRGBA{R: 55, G: 72, B: 93, A: 255} + case theme.ColorNameDisabled, theme.ColorNamePlaceHolder: + return color.NRGBA{R: 147, G: 161, B: 180, A: 255} + case theme.ColorNameSelection: + return color.NRGBA{R: 45, G: 75, B: 118, A: 255} + case theme.ColorNameError: + return color.NRGBA{R: 255, G: 128, B: 126, A: 255} + default: + return color.NRGBA{R: 23, G: 35, B: 52, A: 255} + } + } + switch name { + case theme.ColorNameBackground: + return color.NRGBA{R: 247, G: 249, B: 252, A: 255} + case theme.ColorNameForeground: + return color.NRGBA{R: 28, G: 41, B: 59, A: 255} + case theme.ColorNamePrimary, theme.ColorNameFocus, theme.ColorNameHyperlink: + return color.NRGBA{R: 55, G: 88, B: 176, A: 255} + case theme.ColorNameButton, theme.ColorNameHeaderBackground, theme.ColorNameInputBackground: + return color.NRGBA{R: 255, G: 255, B: 255, A: 255} + case theme.ColorNameSeparator, theme.ColorNameInputBorder: + return color.NRGBA{R: 218, G: 225, B: 234, A: 255} + case theme.ColorNameDisabled, theme.ColorNamePlaceHolder: + return color.NRGBA{R: 95, G: 110, B: 131, A: 255} + case theme.ColorNameSelection: + return color.NRGBA{R: 223, G: 232, B: 250, A: 255} + case theme.ColorNameError: + return color.NRGBA{R: 176, G: 38, B: 48, A: 255} + default: + return color.NRGBA{R: 242, G: 245, B: 249, A: 255} + } +} + +func (productTheme) Font(style fyne.TextStyle) fyne.Resource { + name := "fonts/NotoSans-Regular.ttf" + if style.Bold && style.Italic { + name = "fonts/NotoSans-BoldItalic.ttf" + } else if style.Bold { + name = "fonts/NotoSans-Bold.ttf" + } else if style.Italic { + name = "fonts/NotoSans-Italic.ttf" + } + data, err := assets.Files.ReadFile(name) + if err != nil { + return theme.DefaultTheme().Font(style) + } + return fyne.NewStaticResource(name, data) +} + +func (productTheme) Icon(name fyne.ThemeIconName) fyne.Resource { + return theme.DefaultTheme().Icon(name) +} + +func (productTheme) Size(name fyne.ThemeSizeName) float32 { + switch name { + case theme.SizeNamePadding: + return 8 + case theme.SizeNameInnerPadding: + return 6 + case theme.SizeNameInlineIcon: + return 18 + case theme.SizeNameText: + return 13 + case theme.SizeNameCaptionText: + return 11 + case theme.SizeNameHeadingText: + return 25 + case theme.SizeNameSubHeadingText: + return 17 + case theme.SizeNameLineSpacing: + return 4 + case theme.SizeNameSeparatorThickness: + return 1 + case theme.SizeNameScrollBar: + return 8 + case theme.SizeNameScrollBarSmall: + return 4 + default: + return 6 + } +} diff --git a/internal/config/paths.go b/internal/config/paths.go new file mode 100644 index 0000000..900d94c --- /dev/null +++ b/internal/config/paths.go @@ -0,0 +1,21 @@ +package config + +import ( + "fmt" + "os" + "path/filepath" +) + +func DatabasePath(requested string) (string, error) { + if requested != "" { + return requested, nil + } + if configured := os.Getenv("ATTACKPATH_VISUALIZER_DB"); configured != "" { + return configured, nil + } + base, err := os.UserConfigDir() + if err != nil { + return "", fmt.Errorf("find user configuration directory: %w", err) + } + return filepath.Join(base, "AttackPathVisualizer", "graph.db"), nil +} diff --git a/internal/domain/graph.go b/internal/domain/graph.go new file mode 100644 index 0000000..a1eb11d --- /dev/null +++ b/internal/domain/graph.go @@ -0,0 +1,475 @@ +package domain + +import ( + "container/heap" + "errors" + "fmt" + "sort" + "strings" + "unicode" + + "github.com/NexzaDev/attackpath-visualizer/internal/scoring" +) + +const ( + maxPathDepth = 32 + maxPathCount = 1000 +) + +type Asset struct { + ID string `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` + Impact int `json:"impact"` + Description string `json:"description"` +} + +type Identity struct { + ID string `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` + Impact int `json:"impact"` + Description string `json:"description"` +} + +type Misconfiguration struct { + ID string `json:"id"` + AssetID string `json:"asset_id"` + IdentityID string `json:"identity_id,omitempty"` + Title string `json:"title"` + Severity int `json:"severity"` + Description string `json:"description"` +} + +type Finding struct { + ID string `json:"id"` + AssetID string `json:"asset_id"` + IdentityID string `json:"identity_id,omitempty"` + MisconfigurationID string `json:"misconfiguration_id,omitempty"` + Title string `json:"title"` + Severity int `json:"severity"` + Source string `json:"source"` + Observed string `json:"observed"` +} + +type Evidence struct { + Source string `json:"source"` + Finding string `json:"finding"` + Observed string `json:"observed"` +} + +type Edge struct { + ID string `json:"id"` + From string `json:"from"` + To string `json:"to"` + Relation string `json:"relation"` + Confidence int `json:"confidence"` + Evidence Evidence `json:"evidence"` +} + +type Graph struct { + SchemaVersion int `json:"schema_version,omitempty"` + Assets []Asset `json:"assets"` + Identities []Identity `json:"identities,omitempty"` + Misconfigurations []Misconfiguration `json:"misconfigurations,omitempty"` + Findings []Finding `json:"findings,omitempty"` + Edges []Edge `json:"edges"` +} + +type Node struct { + ID string `json:"id"` + Name string `json:"name"` + EntityType string `json:"entity_type"` + Kind string `json:"kind"` + Impact int `json:"impact"` + Description string `json:"description"` +} + +type ScoreBreakdown struct { + ImpactTier int `json:"impact_tier"` + EdgeConfidences []int `json:"edge_confidences"` + CompoundedConfidence int `json:"compounded_confidence"` + Score int `json:"score"` +} + +type Path struct { + Nodes []Node `json:"nodes"` + Assets []Asset `json:"assets,omitempty"` + Edges []Edge `json:"edges"` + Impact int `json:"impact"` + Confidence int `json:"confidence"` + Score int `json:"score"` + Components ScoreBreakdown `json:"components"` + Explanation string `json:"explanation"` +} + +type PathResult struct { + Paths []Path `json:"paths"` + Truncated bool `json:"truncated"` + Expanded int `json:"expanded"` +} + +func (g Graph) Validate() error { + nodes := make(map[string]Node, len(g.Assets)+len(g.Identities)) + for _, asset := range g.Assets { + if err := validateNode(asset.ID, asset.Name, asset.Kind, asset.Impact); err != nil { + return fmt.Errorf("asset %q: %w", asset.ID, err) + } + if err := addNode(nodes, Node{ID: asset.ID, Name: asset.Name, EntityType: "asset", Kind: asset.Kind, Impact: asset.Impact, Description: asset.Description}); err != nil { + return fmt.Errorf("asset %q: %w", asset.ID, err) + } + } + for _, identity := range g.Identities { + if err := validateNode(identity.ID, identity.Name, identity.Kind, identity.Impact); err != nil { + return fmt.Errorf("identity %q: %w", identity.ID, err) + } + if err := addNode(nodes, Node{ID: identity.ID, Name: identity.Name, EntityType: "identity", Kind: identity.Kind, Impact: identity.Impact, Description: identity.Description}); err != nil { + return fmt.Errorf("identity %q: %w", identity.ID, err) + } + } + ids := make(map[string]string, len(nodes)+len(g.Misconfigurations)+len(g.Findings)+len(g.Edges)) + for id := range nodes { + ids[id] = "node" + } + misconfigurations := make(map[string]Misconfiguration, len(g.Misconfigurations)) + for _, item := range g.Misconfigurations { + if err := validateID(item.ID); err != nil || !validText(item.Title) || !validText(item.Description) || item.Severity < 1 || item.Severity > 5 { + return fmt.Errorf("misconfiguration %q requires an id, title, description, and severity from 1 to 5", item.ID) + } + if err := addID(ids, item.ID, "misconfiguration"); err != nil { + return err + } + if _, ok := nodeKind(nodes, item.AssetID, "asset"); !ok { + return fmt.Errorf("misconfiguration %q references missing asset %q", item.ID, item.AssetID) + } + if item.IdentityID != "" { + if _, ok := nodeKind(nodes, item.IdentityID, "identity"); !ok { + return fmt.Errorf("misconfiguration %q references missing identity %q", item.ID, item.IdentityID) + } + } + misconfigurations[item.ID] = item + } + for _, item := range g.Findings { + if err := validateID(item.ID); err != nil || !validText(item.Title) || item.Severity < 1 || item.Severity > 5 || !validText(item.Source) || !validText(item.Observed) { + return fmt.Errorf("finding %q requires an id, title, source, observed value, and severity from 1 to 5", item.ID) + } + if err := addID(ids, item.ID, "finding"); err != nil { + return err + } + if _, ok := nodeKind(nodes, item.AssetID, "asset"); !ok { + return fmt.Errorf("finding %q references missing asset %q", item.ID, item.AssetID) + } + if item.IdentityID != "" { + if _, ok := nodeKind(nodes, item.IdentityID, "identity"); !ok { + return fmt.Errorf("finding %q references missing identity %q", item.ID, item.IdentityID) + } + } + if item.MisconfigurationID != "" { + if _, ok := misconfigurations[item.MisconfigurationID]; !ok { + return fmt.Errorf("finding %q references missing misconfiguration %q", item.ID, item.MisconfigurationID) + } + } + } + for _, edge := range g.Edges { + if err := validateID(edge.ID); err != nil || !validText(edge.Relation) || edge.Confidence < 0 || edge.Confidence > 100 { + return fmt.Errorf("edge %q requires an id, relation, and confidence from 0 to 100", edge.ID) + } + if err := addID(ids, edge.ID, "edge"); err != nil { + return err + } + if _, exists := nodes[edge.From]; !exists { + return fmt.Errorf("edge %q references missing source node %q", edge.ID, edge.From) + } + if _, exists := nodes[edge.To]; !exists { + return fmt.Errorf("edge %q references missing target node %q", edge.ID, edge.To) + } + if edge.From == edge.To { + return fmt.Errorf("edge %q cannot connect a node to itself", edge.ID) + } + if !validText(edge.Evidence.Source) || !validText(edge.Evidence.Finding) || !validText(edge.Evidence.Observed) { + return fmt.Errorf("edge %q requires source, finding, and observed evidence", edge.ID) + } + } + return nil +} + +func (g Graph) AllPaths(maxDepth, limit int) ([]Path, error) { + result, err := g.EnumeratePaths(maxDepth, limit) + return result.Paths, err +} + +func (g Graph) EnumeratePaths(maxDepth, limit int) (PathResult, error) { + if maxDepth < 1 || maxDepth > maxPathDepth || limit < 1 || limit > maxPathCount { + return PathResult{}, errors.New("max depth must be 1–32 and limit must be 1–1000") + } + if err := g.Validate(); err != nil { + return PathResult{}, err + } + nodes := g.nodes() + adjacency := g.adjacency() + incoming := make(map[string]bool, len(nodes)) + neighbors := make(map[string][]string, len(nodes)) + for _, edge := range g.Edges { + incoming[edge.To] = true + neighbors[edge.From] = append(neighbors[edge.From], edge.To) + neighbors[edge.To] = append(neighbors[edge.To], edge.From) + } + ids := make([]string, 0, len(nodes)) + for id := range nodes { + ids = append(ids, id) + } + sort.Strings(ids) + sources := make([]string, 0, len(ids)) + componentVisited := make(map[string]bool, len(ids)) + for _, first := range ids { + if componentVisited[first] { + continue + } + component := []string{first} + componentVisited[first] = true + for index := 0; index < len(component); index++ { + for _, neighbor := range neighbors[component[index]] { + if !componentVisited[neighbor] { + componentVisited[neighbor] = true + component = append(component, neighbor) + } + } + } + componentRoots := make([]string, 0) + for _, id := range component { + if !incoming[id] { + componentRoots = append(componentRoots, id) + } + } + if len(componentRoots) == 0 { + sources = append(sources, component...) + } else { + sources = append(sources, componentRoots...) + } + } + sort.Strings(sources) + candidates := &pathHeap{} + heap.Init(candidates) + seen := make(map[string]struct{}) + result := PathResult{} + for _, source := range sources { + if err := g.findPaths(nodes, adjacency, source, "", maxDepth, limit, &result.Expanded, &result.Truncated, seen, candidates); err != nil { + return PathResult{}, err + } + } + result.Paths = append([]Path(nil), (*candidates)...) + sortPaths(result.Paths) + return result, nil +} + +func (g Graph) FindPaths(source, target string, maxDepth, limit int) ([]Path, error) { + if maxDepth < 1 || maxDepth > maxPathDepth || limit < 1 || limit > maxPathCount { + return nil, errors.New("max depth must be 1–32 and limit must be 1–1000") + } + if err := g.Validate(); err != nil { + return nil, err + } + nodes := g.nodes() + if _, exists := nodes[source]; !exists { + return nil, fmt.Errorf("unknown source node %q", source) + } + if target != "" { + if _, exists := nodes[target]; !exists { + return nil, fmt.Errorf("unknown target node %q", target) + } + } + candidates := &pathHeap{} + heap.Init(candidates) + expanded := 0 + truncated := false + err := g.findPaths(nodes, g.adjacency(), source, target, maxDepth, limit, &expanded, &truncated, make(map[string]struct{}), candidates) + paths := append([]Path(nil), (*candidates)...) + sortPaths(paths) + return paths, err +} + +func (g Graph) adjacency() map[string][]Edge { + adjacency := make(map[string][]Edge) + for _, edge := range g.Edges { + adjacency[edge.From] = append(adjacency[edge.From], edge) + } + for id := range adjacency { + sort.Slice(adjacency[id], func(i, j int) bool { return adjacency[id][i].ID < adjacency[id][j].ID }) + } + return adjacency +} + +func (g Graph) findPaths(nodes map[string]Node, adjacency map[string][]Edge, source, target string, maxDepth, limit int, expanded *int, truncated *bool, seen map[string]struct{}, candidates *pathHeap) error { + visited := map[string]bool{source: true} + chainNodes := []Node{nodes[source]} + chainEdges := make([]Edge, 0, maxDepth) + var walk func(string) error + walk = func(at string) error { + if at != source && (target == "" || at == target) { + signature := pathSignature(chainEdges) + if _, duplicate := seen[signature]; !duplicate { + seen[signature] = struct{}{} + path, err := makePath(chainNodes, chainEdges) + if err != nil { + return err + } + if candidates.Len() == limit { + *truncated = true + } + candidates.add(path, limit) + } + if target != "" { + return nil + } + } + if len(chainEdges) == maxDepth { + return nil + } + for _, edge := range adjacency[at] { + if visited[edge.To] { + continue + } + *expanded = *expanded + 1 + if *expanded > 250000 { + return errors.New("path enumeration exceeded the 250000 edge-expansion budget; reduce graph size or path depth") + } + visited[edge.To] = true + chainEdges = append(chainEdges, edge) + chainNodes = append(chainNodes, nodes[edge.To]) + if err := walk(edge.To); err != nil { + return err + } + chainNodes = chainNodes[:len(chainNodes)-1] + chainEdges = chainEdges[:len(chainEdges)-1] + delete(visited, edge.To) + } + return nil + } + return walk(source) +} + +func makePath(nodes []Node, edges []Edge) (Path, error) { + impact := 1 + confidences := make([]int, len(edges)) + assets := make([]Asset, 0, len(nodes)) + for _, node := range nodes { + if node.Impact > impact { + impact = node.Impact + } + if node.EntityType == "asset" { + assets = append(assets, Asset{ID: node.ID, Name: node.Name, Kind: node.Kind, Impact: node.Impact, Description: node.Description}) + } + } + for index, edge := range edges { + confidences[index] = edge.Confidence + } + result, err := scoring.Score(impact, confidences) + if err != nil { + return Path{}, err + } + return Path{Nodes: append([]Node(nil), nodes...), Assets: assets, Edges: append([]Edge(nil), edges...), Impact: impact, Confidence: result.CompoundedConfidence, Score: result.Score, Components: ScoreBreakdown{ImpactTier: result.ImpactTier, EdgeConfidences: result.EdgeConfidences, CompoundedConfidence: result.CompoundedConfidence, Score: result.Score}, Explanation: result.Explanation}, nil +} + +func (g Graph) Nodes() []Node { + nodes := g.nodes() + result := make([]Node, 0, len(nodes)) + for _, node := range nodes { + result = append(result, node) + } + sort.Slice(result, func(i, j int) bool { + if result[i].Name == result[j].Name { + return result[i].ID < result[j].ID + } + return result[i].Name < result[j].Name + }) + return result +} + +func (g Graph) nodes() map[string]Node { + nodes := make(map[string]Node, len(g.Assets)+len(g.Identities)) + for _, asset := range g.Assets { + nodes[asset.ID] = Node{ID: asset.ID, Name: asset.Name, EntityType: "asset", Kind: asset.Kind, Impact: asset.Impact, Description: asset.Description} + } + for _, identity := range g.Identities { + nodes[identity.ID] = Node{ID: identity.ID, Name: identity.Name, EntityType: "identity", Kind: identity.Kind, Impact: identity.Impact, Description: identity.Description} + } + return nodes +} + +func pathSignature(edges []Edge) string { + ids := make([]string, len(edges)) + for index, edge := range edges { + ids[index] = edge.ID + } + return strings.Join(ids, "\x00") +} + +func sortPaths(paths []Path) { + sort.SliceStable(paths, func(i, j int) bool { return pathBetter(paths[i], paths[j]) }) +} + +func pathBetter(left, right Path) bool { + if left.Score != right.Score { + return left.Score > right.Score + } + if left.Confidence != right.Confidence { + return left.Confidence > right.Confidence + } + return pathSignature(left.Edges) < pathSignature(right.Edges) +} + +func validateNode(id, name, kind string, impact int) error { + if err := validateID(id); err != nil || !validText(name) || !validText(kind) || impact < 1 || impact > 5 { + return errors.New("requires an id, name, kind, and impact from 1 to 5") + } + return nil +} + +func validateID(value string) error { + if !validText(value) || len(value) > 256 { + return errors.New("id must contain 1 to 256 non-control characters") + } + return nil +} + +func validText(value string) bool { + if strings.TrimSpace(value) == "" || len(value) > 4096 { + return false + } + for _, r := range value { + if unicode.IsControl(r) && r != '\n' && r != '\t' { + return false + } + } + return true +} + +func addNode(nodes map[string]Node, node Node) error { + if _, exists := nodes[node.ID]; exists { + return fmt.Errorf("duplicate node id %q", node.ID) + } + nodes[node.ID] = node + return nil +} + +func addID(ids map[string]string, id, kind string) error { + if previous, exists := ids[id]; exists { + return fmt.Errorf("duplicate id %q used by %s and %s", id, previous, kind) + } + ids[id] = kind + return nil +} + +func nodeKind(nodes map[string]Node, id, kind string) (Node, bool) { + node, exists := nodes[id] + if !exists { + return Node{}, false + } + if kind == "asset" && node.EntityType != "asset" { + return Node{}, false + } + if kind == "identity" && node.EntityType != "identity" { + return Node{}, false + } + return node, true +} diff --git a/internal/domain/graph_test.go b/internal/domain/graph_test.go new file mode 100644 index 0000000..dac44e3 --- /dev/null +++ b/internal/domain/graph_test.go @@ -0,0 +1,134 @@ +package domain + +import "testing" + +func TestFindPathsRanksAndExplains(t *testing.T) { + graph := Graph{ + Assets: []Asset{{ID: "a", Name: "Public gateway", Kind: "service", Impact: 2}, {ID: "b", Name: "Identity provider", Kind: "identity", Impact: 4}, {ID: "c", Name: "Data store", Kind: "database", Impact: 5}}, + Edges: []Edge{ + {ID: "ab", From: "a", To: "b", Relation: "assumes role", Confidence: 90, Evidence: testEvidence("trust policy")}, + {ID: "bc", From: "b", To: "c", Relation: "reads", Confidence: 80, Evidence: testEvidence("read permission")}, + }, + } + paths, err := graph.FindPaths("a", "c", 8, 10) + if err != nil { + t.Fatal(err) + } + if len(paths) != 1 || paths[0].Confidence != 72 || paths[0].Score != 360 { + t.Fatalf("unexpected path result: %#v", paths) + } + if len(paths[0].Components.EdgeConfidences) != 2 || paths[0].Components.ImpactTier != 5 { + t.Fatalf("score components are incomplete: %#v", paths[0].Components) + } + if len(paths[0].Nodes) != 3 || len(paths[0].Edges) != 2 { + t.Fatalf("path is missing nodes or edges: %#v", paths[0]) + } +} + +func TestAllPathsDeduplicatesAndReportsBound(t *testing.T) { + graph := Graph{ + Assets: []Asset{{ID: "a", Name: "A", Kind: "service", Impact: 1}, {ID: "b", Name: "B", Kind: "service", Impact: 2}, {ID: "c", Name: "C", Kind: "database", Impact: 5}}, + Edges: []Edge{ + {ID: "ab", From: "a", To: "b", Relation: "connects", Confidence: 100, Evidence: testEvidence("ab")}, + {ID: "bc", From: "b", To: "c", Relation: "connects", Confidence: 100, Evidence: testEvidence("bc")}, + {ID: "ac", From: "a", To: "c", Relation: "connects", Confidence: 80, Evidence: testEvidence("ac")}, + }, + } + result, err := graph.EnumeratePaths(8, 1) + if err != nil { + t.Fatal(err) + } + if len(result.Paths) != 1 || !result.Truncated { + t.Fatalf("expected one bounded path and a truncation marker: %#v", result) + } + paths, err := graph.FindPaths("a", "c", 8, 10) + if err != nil { + t.Fatal(err) + } + if len(paths) != 2 || paths[0].Score != 500 || paths[1].Score != 400 { + t.Fatalf("expected deterministic ranking of the two distinct paths: %#v", paths) + } +} + +func TestAllPathsIncludesDisconnectedCycleComponents(t *testing.T) { + graph := Graph{ + Assets: []Asset{{ID: "root", Name: "Root", Kind: "service", Impact: 2}, {ID: "leaf", Name: "Leaf", Kind: "database", Impact: 3}, {ID: "cycle-a", Name: "Cycle A", Kind: "service", Impact: 2}, {ID: "cycle-b", Name: "Cycle B", Kind: "service", Impact: 3}}, + Edges: []Edge{ + {ID: "root-leaf", From: "root", To: "leaf", Relation: "connects", Confidence: 100, Evidence: testEvidence("root-leaf")}, + {ID: "cycle-ab", From: "cycle-a", To: "cycle-b", Relation: "connects", Confidence: 100, Evidence: testEvidence("cycle-ab")}, + {ID: "cycle-ba", From: "cycle-b", To: "cycle-a", Relation: "connects", Confidence: 100, Evidence: testEvidence("cycle-ba")}, + }, + } + paths, err := graph.AllPaths(8, 20) + if err != nil { + t.Fatal(err) + } + foundCycle := false + for _, path := range paths { + if len(path.Nodes) == 2 && path.Nodes[0].ID == "cycle-a" && path.Nodes[1].ID == "cycle-b" { + foundCycle = true + } + } + if !foundCycle { + t.Fatalf("a disconnected cyclic component was skipped: %#v", paths) + } +} + +func TestValidateRejectsDanglingNodesAndEvidence(t *testing.T) { + graph := Graph{ + Assets: []Asset{{ID: "a", Name: "A", Kind: "service", Impact: 1}}, + Edges: []Edge{{ID: "e", From: "a", To: "missing", Relation: "connects", Confidence: 100, Evidence: testEvidence("test")}}, + } + if err := graph.Validate(); err == nil { + t.Fatal("expected invalid edge error") + } + graph = Graph{Assets: []Asset{{ID: "a", Name: "A", Kind: "service", Impact: 1}, {ID: "b", Name: "B", Kind: "service", Impact: 2}}, Edges: []Edge{{ID: "e", From: "a", To: "b", Relation: "connects", Confidence: 100}}} + if err := graph.Validate(); err == nil { + t.Fatal("expected missing evidence error") + } +} + +func TestValidatesIdentityMisconfigurationAndFindingReferences(t *testing.T) { + graph := Graph{ + Assets: []Asset{{ID: "db", Name: "Database", Kind: "database", Impact: 5}}, + Identities: []Identity{{ID: "workload", Name: "Workload identity", Kind: "workload", Impact: 3}}, + Misconfigurations: []Misconfiguration{{ID: "misconfig", AssetID: "db", IdentityID: "workload", Title: "Overbroad access", Severity: 4, Description: "Synthetic access issue"}}, + Findings: []Finding{{ID: "finding", AssetID: "db", IdentityID: "workload", MisconfigurationID: "misconfig", Title: "Read access observed", Severity: 4, Source: "fixture://permissions", Observed: "synthetic"}}, + Edges: []Edge{{ID: "access", From: "workload", To: "db", Relation: "reads", Confidence: 90, Evidence: testEvidence("read access")}}, + } + if err := graph.Validate(); err != nil { + t.Fatal(err) + } + paths, err := graph.FindPaths("workload", "db", 4, 4) + if err != nil || len(paths) != 1 { + t.Fatalf("paths=%v err=%v", paths, err) + } + if paths[0].Nodes[0].EntityType != "identity" || paths[0].Nodes[0].Kind != "workload" || paths[0].Nodes[1].Kind != "database" { + t.Fatalf("typed identities are missing from graph paths: %#v", paths[0].Nodes) + } + graph.Findings[0].MisconfigurationID = "missing" + if err := graph.Validate(); err == nil { + t.Fatal("expected missing misconfiguration reference error") + } +} + +func TestFindPathsRejectsCyclesAndInvalidLimits(t *testing.T) { + graph := Graph{ + Assets: []Asset{{ID: "a", Name: "A", Kind: "service", Impact: 1}, {ID: "b", Name: "B", Kind: "service", Impact: 2}}, + Edges: []Edge{ + {ID: "ab", From: "a", To: "b", Relation: "connects", Confidence: 100, Evidence: testEvidence("ab")}, + {ID: "ba", From: "b", To: "a", Relation: "connects", Confidence: 100, Evidence: testEvidence("ba")}, + }, + } + paths, err := graph.FindPaths("a", "", 4, 10) + if err != nil || len(paths) != 1 { + t.Fatalf("paths=%v err=%v", paths, err) + } + if _, err := graph.FindPaths("a", "", 0, 10); err == nil { + t.Fatal("expected depth validation") + } +} + +func testEvidence(finding string) Evidence { + return Evidence{Source: "fixture://test", Finding: finding, Observed: "synthetic"} +} diff --git a/internal/domain/path_heap.go b/internal/domain/path_heap.go new file mode 100644 index 0000000..b7b4cc9 --- /dev/null +++ b/internal/domain/path_heap.go @@ -0,0 +1,33 @@ +package domain + +import "container/heap" + +type pathHeap []Path + +func (paths pathHeap) Len() int { return len(paths) } + +func (paths pathHeap) Less(i, j int) bool { + return pathBetter(paths[j], paths[i]) +} + +func (paths pathHeap) Swap(i, j int) { paths[i], paths[j] = paths[j], paths[i] } + +func (paths *pathHeap) Push(value any) { *paths = append(*paths, value.(Path)) } + +func (paths *pathHeap) Pop() any { + old := *paths + last := old[len(old)-1] + *paths = old[:len(old)-1] + return last +} + +func (paths *pathHeap) add(path Path, limit int) { + if paths.Len() < limit { + heap.Push(paths, path) + return + } + if pathBetter(path, (*paths)[0]) { + (*paths)[0] = path + heap.Fix(paths, 0) + } +} diff --git a/internal/ingestion/json.go b/internal/ingestion/json.go new file mode 100644 index 0000000..0dafd7b --- /dev/null +++ b/internal/ingestion/json.go @@ -0,0 +1,83 @@ +package ingestion + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + + "github.com/NexzaDev/attackpath-visualizer/internal/domain" +) + +const ( + MaxDocumentBytes = 8 << 20 + MaxAssets = 10000 + MaxIdentities = 10000 + MaxEdges = 50000 + MaxFindings = 50000 + MaxMisconfigs = 50000 + CurrentVersion = 1 +) + +type Validation struct { + SchemaVersion int `json:"schema_version"` + Assets int `json:"assets"` + Identities int `json:"identities"` + Edges int `json:"edges"` + Findings int `json:"findings"` + Misconfigurations int `json:"misconfigurations"` + DocumentBytes int `json:"document_bytes"` +} + +func Read(reader io.Reader) (domain.Graph, Validation, error) { + data, err := io.ReadAll(io.LimitReader(reader, MaxDocumentBytes+1)) + if err != nil { + return domain.Graph{}, Validation{}, fmt.Errorf("read inventory: %w", err) + } + if len(data) == 0 { + return domain.Graph{}, Validation{}, errors.New("inventory is empty; provide a JSON graph with at least one asset or identity") + } + if len(data) > MaxDocumentBytes { + return domain.Graph{}, Validation{}, fmt.Errorf("inventory exceeds the %d byte limit", MaxDocumentBytes) + } + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + var graph domain.Graph + if err = decoder.Decode(&graph); err != nil { + return domain.Graph{}, Validation{}, fmt.Errorf("inventory JSON schema: %w", err) + } + var trailing any + if err = decoder.Decode(&trailing); err != io.EOF { + if err == nil { + return domain.Graph{}, Validation{}, errors.New("inventory must contain exactly one JSON object") + } + return domain.Graph{}, Validation{}, fmt.Errorf("inventory has trailing data: %w", err) + } + if graph.SchemaVersion != 0 && graph.SchemaVersion != CurrentVersion { + return domain.Graph{}, Validation{}, fmt.Errorf("unsupported schema_version %d; supported versions are 1 and legacy versionless JSON", graph.SchemaVersion) + } + if len(graph.Assets)+len(graph.Identities) == 0 { + return domain.Graph{}, Validation{}, errors.New("inventory must contain at least one asset or identity") + } + for _, item := range []struct { + name string + count int + limit int + }{ + {name: "assets", count: len(graph.Assets), limit: MaxAssets}, + {name: "identities", count: len(graph.Identities), limit: MaxIdentities}, + {name: "edges", count: len(graph.Edges), limit: MaxEdges}, + {name: "findings", count: len(graph.Findings), limit: MaxFindings}, + {name: "misconfigurations", count: len(graph.Misconfigurations), limit: MaxMisconfigs}, + } { + if item.count > item.limit { + return domain.Graph{}, Validation{}, fmt.Errorf("inventory contains %d %s; the limit is %d", item.count, item.name, item.limit) + } + } + if err = graph.Validate(); err != nil { + return domain.Graph{}, Validation{}, fmt.Errorf("validate inventory: %w", err) + } + graph.SchemaVersion = CurrentVersion + return graph, Validation{SchemaVersion: CurrentVersion, Assets: len(graph.Assets), Identities: len(graph.Identities), Edges: len(graph.Edges), Findings: len(graph.Findings), Misconfigurations: len(graph.Misconfigurations), DocumentBytes: len(data)}, nil +} diff --git a/internal/ingestion/json_test.go b/internal/ingestion/json_test.go new file mode 100644 index 0000000..c622638 --- /dev/null +++ b/internal/ingestion/json_test.go @@ -0,0 +1,62 @@ +package ingestion + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" + "testing" + + "github.com/NexzaDev/attackpath-visualizer/internal/domain" +) + +func TestReadAcceptsTypedSyntheticInventory(t *testing.T) { + input := `{"schema_version":1,"assets":[{"id":"db","name":"Data","kind":"database","impact":5}],"identities":[{"id":"workload","name":"Builder","kind":"workload","impact":3}],"misconfigurations":[{"id":"m1","asset_id":"db","identity_id":"workload","title":"Wide read access","severity":4,"description":"Fixture finding"}],"findings":[{"id":"f1","asset_id":"db","identity_id":"workload","misconfiguration_id":"m1","title":"Read access observed","severity":4,"source":"fixture://inventory","observed":"synthetic"}],"edges":[{"id":"e1","from":"workload","to":"db","relation":"reads","confidence":85,"evidence":{"source":"fixture://permissions","finding":"Read permission present","observed":"synthetic"}}]}` + graph, result, err := Read(strings.NewReader(input)) + if err != nil { + t.Fatal(err) + } + if len(graph.Assets) != 1 || len(graph.Identities) != 1 || len(graph.Misconfigurations) != 1 || len(graph.Findings) != 1 || len(graph.Edges) != 1 { + t.Fatalf("incomplete inventory: %#v", graph) + } + if result.SchemaVersion != 1 || result.DocumentBytes != len(input) || result.Identities != 1 { + t.Fatalf("unexpected validation result: %#v", result) + } +} + +func TestReadRejectsMalformedAndOutOfSchemaDocuments(t *testing.T) { + for _, test := range []struct { + name string + data string + }{ + {name: "malformed JSON", data: `{"assets":[`}, + {name: "unknown field", data: `{"assets":[{"id":"a","name":"A","kind":"service","impact":1,"secret":"x"}],"edges":[]}`}, + {name: "trailing JSON object", data: `{"assets":[{"id":"a","name":"A","kind":"service","impact":1}],"edges":[]}{}`}, + {name: "unsupported version", data: `{"schema_version":2,"assets":[{"id":"a","name":"A","kind":"service","impact":1}],"edges":[]}`}, + {name: "empty inventory", data: `{"assets":[],"edges":[]}`}, + {name: "missing evidence", data: `{"assets":[{"id":"a","name":"A","kind":"service","impact":1},{"id":"b","name":"B","kind":"database","impact":3}],"edges":[{"id":"e","from":"a","to":"b","relation":"reads","confidence":100}]}`}, + } { + t.Run(test.name, func(t *testing.T) { + if _, _, err := Read(strings.NewReader(test.data)); err == nil { + t.Fatal("expected inventory validation error") + } + }) + } +} + +func TestReadRejectsOversizedDocumentAndRecordCount(t *testing.T) { + if _, _, err := Read(strings.NewReader(strings.Repeat(" ", MaxDocumentBytes+1))); err == nil || !strings.Contains(err.Error(), "byte limit") { + t.Fatalf("oversized input error = %v", err) + } + assets := make([]domain.Asset, MaxAssets+1) + for index := range assets { + assets[index] = domain.Asset{ID: fmt.Sprintf("a-%d", index), Name: fmt.Sprintf("Asset %d", index), Kind: "service", Impact: 1} + } + data, err := json.Marshal(domain.Graph{Assets: assets}) + if err != nil { + t.Fatal(err) + } + if _, _, err = Read(bytes.NewReader(data)); err == nil || !strings.Contains(err.Error(), "10000") || !strings.Contains(err.Error(), "assets") { + t.Fatalf("record-count error = %v", err) + } +} diff --git a/internal/launcher/decision.go b/internal/launcher/decision.go new file mode 100644 index 0000000..12b662f --- /dev/null +++ b/internal/launcher/decision.go @@ -0,0 +1,140 @@ +package launcher + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" +) + +type Options struct { + UI string + EnvUI string + Saved string + Ask bool + NoPrompt bool + TTY bool + Headless bool +} + +type Decision struct { + Mode string + Prompt bool + Chooser bool + Message string +} + +func Decide(options Options) (Decision, error) { + mode := strings.ToLower(options.UI) + if mode == "" { + mode = strings.ToLower(options.EnvUI) + } + if mode != "" && mode != "gui" && mode != "tui" { + return Decision{}, fmt.Errorf("UI must be gui or tui, got %q", mode) + } + if mode != "" && !options.Ask { + return Decision{Mode: mode}, nil + } + if options.Ask { + if options.Headless && !options.TTY { + return Decision{Mode: "tui", Message: "No display server or interactive terminal detected; opening the terminal interface."}, nil + } + if options.TTY { + return Decision{Mode: preferred(options.Saved), Prompt: true}, nil + } + return Decision{Mode: preferred(options.Saved), Chooser: true}, nil + } + if options.Headless { + return Decision{Mode: "tui", Message: "No display server detected; opening the terminal interface."}, nil + } + if options.NoPrompt { + return Decision{Mode: preferred(options.Saved)}, nil + } + if options.TTY { + return Decision{Mode: preferred(options.Saved), Prompt: true}, nil + } + return Decision{Mode: preferred(options.Saved), Chooser: true}, nil +} + +func preferred(saved string) string { + if saved == "gui" || saved == "tui" { + return saved + } + return "gui" +} + +func ConfigPath() (string, error) { + base, err := os.UserConfigDir() + if err != nil { + return "", fmt.Errorf("find configuration directory: %w", err) + } + return filepath.Join(base, "AttackPathVisualizer", "launcher.json"), nil +} + +func ReadPreference() string { + path, err := ConfigPath() + if err != nil { + return "" + } + data, err := os.ReadFile(path) + if err != nil { + return "" + } + var preference struct { + Mode string `json:"mode"` + } + if json.Unmarshal(data, &preference) != nil || (preference.Mode != "gui" && preference.Mode != "tui") { + return "" + } + return preference.Mode +} + +func SavePreference(mode string) error { + if mode != "gui" && mode != "tui" && mode != "" { + return errors.New("saved UI must be gui, tui, or empty") + } + path, err := ConfigPath() + if err != nil { + return err + } + if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil { + return fmt.Errorf("create preferences directory: %w", err) + } + if mode == "" { + if err = os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("clear launcher preference: %w", err) + } + return nil + } + data, err := json.Marshal(struct { + Mode string `json:"mode"` + }{Mode: mode}) + if err != nil { + return err + } + if err = os.WriteFile(path, data, 0600); err != nil { + return fmt.Errorf("save launcher preference: %w", err) + } + if err = os.Chmod(path, 0600); err != nil { + return fmt.Errorf("restrict launcher preference permissions: %w", err) + } + return nil +} + +func Headless() bool { + if runtime.GOOS == "windows" { + return false + } + if runtime.GOOS == "darwin" { + return false + } + return os.Getenv("DISPLAY") == "" && os.Getenv("WAYLAND_DISPLAY") == "" +} + +func InteractiveStdin() bool { + file, err := os.Stdin.Stat() + return err == nil && file.Mode()&os.ModeCharDevice != 0 +} diff --git a/internal/launcher/decision_test.go b/internal/launcher/decision_test.go new file mode 100644 index 0000000..39988b0 --- /dev/null +++ b/internal/launcher/decision_test.go @@ -0,0 +1,72 @@ +package launcher + +import ( + "os" + "path/filepath" + "runtime" + "testing" +) + +func TestDecideTable(t *testing.T) { + tests := []struct { + name string + options Options + want Decision + }{ + {name: "explicit flag", options: Options{UI: "tui", TTY: true}, want: Decision{Mode: "tui"}}, + {name: "environment selection", options: Options{EnvUI: "gui", TTY: true}, want: Decision{Mode: "gui"}}, + {name: "saved terminal preference prompt", options: Options{Saved: "tui", TTY: true}, want: Decision{Mode: "tui", Prompt: true}}, + {name: "desktop chooser", options: Options{Saved: "gui"}, want: Decision{Mode: "gui", Chooser: true}}, + {name: "headless terminal", options: Options{Headless: true}, want: Decision{Mode: "tui", Message: "No display server detected; opening the terminal interface."}}, + {name: "forced prompt", options: Options{UI: "gui", Ask: true, TTY: true}, want: Decision{Mode: "gui", Prompt: true}}, + {name: "ask without display or terminal", options: Options{Ask: true, Headless: true}, want: Decision{Mode: "tui", Message: "No display server or interactive terminal detected; opening the terminal interface."}}, + {name: "noninteractive terminal fallback", options: Options{}, want: Decision{Mode: "gui", Chooser: true}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got, err := Decide(test.options) + if err != nil { + t.Fatal(err) + } + if got != test.want { + t.Fatalf("got %#v, want %#v", got, test.want) + } + }) + } +} + +func TestSavedLauncherPreferenceUsesPrivateUserConfig(t *testing.T) { + directory := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", directory) + t.Setenv("APPDATA", directory) + t.Setenv("HOME", directory) + if err := SavePreference("tui"); err != nil { + t.Fatal(err) + } + if ReadPreference() != "tui" { + t.Fatal("saved terminal preference was not loaded") + } + path, err := ConfigPath() + if err != nil { + t.Fatal(err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if runtime.GOOS != "windows" && info.Mode().Perm()&0077 != 0 { + t.Fatalf("launcher preference is not private: %v", info.Mode().Perm()) + } + if err = SavePreference(""); err != nil { + t.Fatal(err) + } + if _, err = os.Stat(filepath.Clean(path)); !os.IsNotExist(err) { + t.Fatalf("preference was not removed: %v", err) + } +} + +func TestDecideRejectsUnknownUI(t *testing.T) { + if _, err := Decide(Options{UI: "browser"}); err == nil { + t.Fatal("expected invalid UI error") + } +} diff --git a/internal/launcher/parse.go b/internal/launcher/parse.go new file mode 100644 index 0000000..4d0e768 --- /dev/null +++ b/internal/launcher/parse.go @@ -0,0 +1,47 @@ +package launcher + +import ( + "fmt" + "strings" +) + +func ParseLaunchArgs(args []string) (bool, Options, string, error) { + if len(args) == 0 { + return true, Options{}, "", nil + } + if args[0] != "--ui" && args[0] != "--ask" && args[0] != "--no-prompt" && args[0] != "--db" && !strings.HasPrefix(args[0], "--ui=") { + return false, Options{}, "", nil + } + options := Options{} + dbPath := "" + for index := 0; index < len(args); index++ { + argument := args[index] + switch argument { + case "--ask": + options.Ask = true + case "--no-prompt": + options.NoPrompt = true + case "--ui": + index++ + if index >= len(args) { + return false, Options{}, "", fmt.Errorf("--ui requires gui or tui") + } + options.UI = args[index] + case "--db": + index++ + if index >= len(args) { + return false, Options{}, "", fmt.Errorf("--db requires a path") + } + dbPath = args[index] + case "--ui=gui": + options.UI = "gui" + default: + if strings.HasPrefix(argument, "--ui=") { + options.UI = strings.TrimPrefix(argument, "--ui=") + } else { + return false, Options{}, "", fmt.Errorf("unexpected launcher argument %q", argument) + } + } + } + return true, options, dbPath, nil +} diff --git a/internal/launcher/terminal.go b/internal/launcher/terminal.go new file mode 100644 index 0000000..1f385a1 --- /dev/null +++ b/internal/launcher/terminal.go @@ -0,0 +1,106 @@ +package launcher + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "os/exec" + "runtime" + "strings" +) + +func StartGUI() error { + executable, err := os.Executable() + if err != nil { + return fmt.Errorf("find application executable: %w", err) + } + if err = exec.Command(executable, "--ui", "gui", "--no-prompt").Start(); err != nil { + return fmt.Errorf("start dashboard: %w", err) + } + return nil +} + +func StartTerminal() error { + executable, err := os.Executable() + if err != nil { + return fmt.Errorf("find application executable: %w", err) + } + appArgs := []string{executable, "--ui", "tui", "--no-prompt"} + commands := terminalCommands(appArgs) + for _, candidate := range commands { + path, lookupErr := exec.LookPath(candidate[0]) + if lookupErr != nil { + continue + } + if err := exec.Command(path, candidate[1:]...).Start(); err == nil { + return nil + } + } + return fmt.Errorf("no supported terminal emulator was found; run this command manually: %s --ui tui", executable) +} + +func terminalCommands(appArgs []string) [][]string { + switch runtime.GOOS { + case "windows": + if _, err := exec.LookPath("wt.exe"); err == nil { + return [][]string{{"wt.exe", "new-tab", "--title", "AttackPath Visualizer", appArgs[0], appArgs[1], appArgs[2], appArgs[3]}} + } + return [][]string{{"cmd.exe", "/k", appArgs[0], appArgs[1], appArgs[2], appArgs[3]}} + case "darwin": + return [][]string{{"open", "-a", "Terminal", "--args", appArgs[0], appArgs[1], appArgs[2], appArgs[3]}} + default: + result := make([][]string, 0, 8) + if terminal := strings.Fields(os.Getenv("TERMINAL")); len(terminal) > 0 { + result = append(result, append(append([]string(nil), terminal...), append([]string{"-e"}, appArgs...)...)) + } + for _, candidate := range []struct { + name string + args []string + }{{"x-terminal-emulator", []string{"-e"}}, {"gnome-terminal", []string{"--"}}, {"konsole", []string{"-e"}}, {"xfce4-terminal", []string{"-e"}}, {"xterm", []string{"-e"}}} { + result = append(result, append(append([]string{candidate.name}, candidate.args...), appArgs...)) + } + return result + } +} + +func Prompt(input io.Reader, output io.Writer, saved string) (string, error) { + defaultMode := preferred(saved) + defaultChoice := "1" + if defaultMode == "tui" { + defaultChoice = "2" + } + if _, err := fmt.Fprintf(output, "How do you want to open AttackPath Visualizer?\n1 Dashboard (graphical window)\n2 Terminal UI\nChoice [%s]: ", defaultChoice); err != nil { + return "", err + } + reader := bufio.NewReader(input) + line, err := reader.ReadString('\n') + if err != nil && !errors.Is(err, io.EOF) { + return "", fmt.Errorf("read launcher choice: %w", err) + } + choice := strings.TrimSpace(line) + mode := defaultMode + if choice == "1" { + mode = "gui" + } else if choice == "2" { + mode = "tui" + } else if choice != "" { + return "", errors.New("choose 1 for Dashboard or 2 for Terminal UI") + } + if _, err = fmt.Fprint(output, "Remember this choice? [y/N]: "); err != nil { + return "", err + } + remember, readErr := reader.ReadString('\n') + if readErr != nil && !errors.Is(readErr, io.EOF) { + return "", fmt.Errorf("read preference choice: %w", readErr) + } + if strings.EqualFold(strings.TrimSpace(remember), "y") || strings.EqualFold(strings.TrimSpace(remember), "yes") { + if err := SavePreference(mode); err != nil { + return "", err + } + } else if err := SavePreference(""); err != nil { + return "", err + } + return mode, nil +} diff --git a/internal/meta/meta.go b/internal/meta/meta.go new file mode 100644 index 0000000..10bf1eb --- /dev/null +++ b/internal/meta/meta.go @@ -0,0 +1,11 @@ +package meta + +const Name = "AttackPath Visualizer" +const ID = "dev.nexza.attackpathvisualizer" +const Version = "0.1.0-dev" +const License = "MIT" +const Copyright = "Copyright © 2026 NexzaDev" +const Repository = "https://github.com/NexzaDev/attackpath-visualizer" +const Issues = Repository + "/issues/new" +const SecurityAdvisory = Repository + "/security/advisories/new" +const Purpose = "A local-first defensive exposure relationship graph explorer." diff --git a/internal/notifications/rules.go b/internal/notifications/rules.go new file mode 100644 index 0000000..e08cc44 --- /dev/null +++ b/internal/notifications/rules.go @@ -0,0 +1,58 @@ +package notifications + +import ( + "crypto/sha256" + "encoding/hex" + "time" +) + +type Event struct { + Type string + Severity int + Title string + Detail string + Related string + Key string +} + +type Rule struct { + Enabled bool + MinimumSeverity int + QuietStart string + QuietEnd string + DetailedText bool +} + +func Key(event Event) string { + if event.Key != "" { + return event.Key + } + sum := sha256.Sum256([]byte(event.Type + "\x00" + event.Related + "\x00" + event.Title)) + return hex.EncodeToString(sum[:]) +} + +func Allowed(event Event, rule Rule, now time.Time) bool { + if !rule.Enabled || event.Severity < rule.MinimumSeverity { + return false + } + return !Quiet(now, rule.QuietStart, rule.QuietEnd) +} + +func Quiet(now time.Time, start, end string) bool { + startAt, startErr := time.Parse("15:04", start) + endAt, endErr := time.Parse("15:04", end) + if startErr != nil || endErr != nil || start == end { + return false + } + current := now.Hour()*60 + now.Minute() + startMinute := startAt.Hour()*60 + startAt.Minute() + endMinute := endAt.Hour()*60 + endAt.Minute() + if startMinute < endMinute { + return current >= startMinute && current < endMinute + } + return current >= startMinute || current < endMinute +} + +func Deduplicated(last, now time.Time, window time.Duration) bool { + return !last.IsZero() && now.Sub(last) >= 0 && now.Sub(last) < window +} diff --git a/internal/notifications/rules_test.go b/internal/notifications/rules_test.go new file mode 100644 index 0000000..46dc4ed --- /dev/null +++ b/internal/notifications/rules_test.go @@ -0,0 +1,41 @@ +package notifications + +import ( + "testing" + "time" +) + +func TestAllowedSeverityAndQuietHours(t *testing.T) { + now := time.Date(2026, 10, 31, 23, 0, 0, 0, time.UTC) + rule := Rule{Enabled: true, MinimumSeverity: 3, QuietStart: "22:00", QuietEnd: "07:00"} + if Allowed(Event{Severity: 5}, rule, now) { + t.Fatal("quiet hours must suppress notification") + } + now = time.Date(2026, 10, 31, 8, 0, 0, 0, time.UTC) + if !Allowed(Event{Severity: 5}, rule, now) { + t.Fatal("eligible event should pass") + } + if Allowed(Event{Severity: 2}, rule, now) { + t.Fatal("low severity should be filtered") + } +} + +func TestDeduplicationWindow(t *testing.T) { + now := time.Now() + if !Deduplicated(now.Add(-time.Minute), now, 10*time.Minute) { + t.Fatal("recent duplicate should be suppressed") + } + if Deduplicated(now.Add(-time.Hour), now, 10*time.Minute) { + t.Fatal("old event should not be suppressed") + } +} + +func TestKeyIsStableAndDistinct(t *testing.T) { + first := Key(Event{Type: "critical_path", Related: "asset-a", Title: "Critical"}) + if first != Key(Event{Type: "critical_path", Related: "asset-a", Title: "Critical"}) { + t.Fatal("same event must have same key") + } + if first == Key(Event{Type: "validation_failed", Related: "asset-a", Title: "Critical"}) { + t.Fatal("different events must differ") + } +} diff --git a/internal/notifier/delivery_state.go b/internal/notifier/delivery_state.go new file mode 100644 index 0000000..bc3bc49 --- /dev/null +++ b/internal/notifier/delivery_state.go @@ -0,0 +1,97 @@ +package notifier + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "time" + + "github.com/NexzaDev/attackpath-visualizer/internal/repository" +) + +type deliveryState struct { + Delivered map[string]bool `json:"delivered"` +} + +func statePath(databasePath string) (string, error) { + home, err := os.UserConfigDir() + if err != nil { + return "", fmt.Errorf("find notifier state directory: %w", err) + } + absolute, err := filepath.Abs(databasePath) + if err != nil { + return "", fmt.Errorf("resolve database path for notifier state: %w", err) + } + digest := sha256.Sum256([]byte(absolute)) + return filepath.Join(home, "AttackPathVisualizer", "notifier", hex.EncodeToString(digest[:])+".json"), nil +} + +func loadDeliveryState(path string) (deliveryState, error) { + state := deliveryState{Delivered: make(map[string]bool)} + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + return state, nil + } + return state, fmt.Errorf("read notifier delivery state: %w", err) + } + if err = json.Unmarshal(data, &state); err != nil { + return state, fmt.Errorf("parse notifier delivery state: %w", err) + } + if state.Delivered == nil { + state.Delivered = make(map[string]bool) + } + return state, nil +} + +func saveDeliveryState(path string, state deliveryState) error { + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + return fmt.Errorf("create notifier state directory: %w", err) + } + keys := make([]string, 0, len(state.Delivered)) + for key, delivered := range state.Delivered { + if delivered { + keys = append(keys, key) + } + } + sort.Strings(keys) + for len(keys) > 2000 { + delete(state.Delivered, keys[0]) + keys = keys[1:] + } + data, err := json.Marshal(state) + if err != nil { + return fmt.Errorf("encode notifier delivery state: %w", err) + } + temporary, err := os.CreateTemp(filepath.Dir(path), ".notifier-state-*") + if err != nil { + return fmt.Errorf("create notifier state file: %w", err) + } + name := temporary.Name() + if err = temporary.Chmod(0600); err == nil { + _, err = temporary.Write(data) + } + if closeErr := temporary.Close(); err == nil { + err = closeErr + } + if err != nil { + os.Remove(name) + return fmt.Errorf("write notifier state file: %w", err) + } + if err = os.Rename(name, path); err != nil { + os.Remove(path) + if err = os.Rename(name, path); err != nil { + os.Remove(name) + return fmt.Errorf("save notifier state file: %w", err) + } + } + return nil +} + +func notificationKey(item repository.Notification) string { + return fmt.Sprintf("%020d:%s", item.ID, item.CreatedAt.UTC().Format(time.RFC3339Nano)) +} diff --git a/internal/notifier/install.go b/internal/notifier/install.go new file mode 100644 index 0000000..d9fe1fd --- /dev/null +++ b/internal/notifier/install.go @@ -0,0 +1,122 @@ +package notifier + +import ( + "encoding/xml" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" +) + +func Entry(goos, executable, home string, database ...string) (string, []byte, error) { + databasePath := "" + if len(database) > 0 { + databasePath = database[0] + } + if home == "" || executable == "" { + return "", nil, errors.New("home directory and application executable are required") + } + switch goos { + case "linux": + path := filepath.Join(home, ".config", "autostart", "attackpath-visualizer-notifier.desktop") + command := escapeDesktop(executable) + " notifier run" + if databasePath != "" { + command += " --db " + escapeDesktop(databasePath) + } + return path, []byte("[Desktop Entry]\nType=Application\nName=AttackPath Visualizer Notifications\nComment=Opt-in local graph notifications\nExec=" + command + "\nTerminal=false\nX-GNOME-Autostart-enabled=true\n"), nil + case "darwin": + path := filepath.Join(home, "Library", "LaunchAgents", "dev.nexza.attackpathvisualizer.notifier.plist") + args := "" + escapeXML(executable) + "notifierrun" + if databasePath != "" { + args += "--db" + escapeXML(databasePath) + "" + } + return path, []byte("\n\nLabeldev.nexza.attackpathvisualizer.notifierProgramArguments" + args + "RunAtLoadStartInterval900\n"), nil + case "windows": + appData := os.Getenv("APPDATA") + if appData == "" { + appData = filepath.Join(home, "AppData", "Roaming") + } + path := filepath.Join(appData, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "attackpath-visualizer-notifier.cmd") + quoted := strings.ReplaceAll(executable, "\"", "\"\"") + arguments := "notifier run" + if databasePath != "" { + databaseQuoted := strings.ReplaceAll(databasePath, "\"", "\"\"") + arguments += " --db \"" + databaseQuoted + "\"" + } + return path, []byte("@echo off\r\nstart \"\" \"" + quoted + "\" " + arguments + "\r\n"), nil + default: + return "", nil, fmt.Errorf("background notifier installation is unsupported on %s", goos) + } +} + +func Install(executable string, database ...string) (string, error) { + databasePath := "" + if len(database) > 0 { + databasePath = database[0] + } + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("find user home: %w", err) + } + path, contents, err := Entry(runtime.GOOS, executable, home, databasePath) + if err != nil { + return "", err + } + if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil { + return "", fmt.Errorf("create autostart directory: %w", err) + } + mode := os.FileMode(0600) + if runtime.GOOS == "linux" { + mode = 0700 + } + if err = os.WriteFile(path, contents, mode); err != nil { + return "", fmt.Errorf("install notifier autostart entry: %w", err) + } + return path, nil +} + +func Uninstall() (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("find user home: %w", err) + } + path, _, err := Entry(runtime.GOOS, "attackpath-visualizer", home) + if err != nil { + return "", err + } + if err = os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return "", fmt.Errorf("remove notifier autostart entry: %w", err) + } + return path, nil +} + +func Status() (string, bool, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", false, err + } + path, _, err := Entry(runtime.GOOS, "attackpath-visualizer", home) + if err != nil { + return "", false, err + } + _, err = os.Stat(path) + if err == nil { + return path, true, nil + } + if errors.Is(err, os.ErrNotExist) { + return path, false, nil + } + return path, false, err +} + +func escapeDesktop(value string) string { + return "\"" + strings.NewReplacer("\\", "\\\\", "\"", "\\\"", "`", "\\`", "$", "\\$", "%", "%%").Replace(value) + "\"" +} + +func escapeXML(value string) string { + var output strings.Builder + _ = xml.EscapeText(&output, []byte(value)) + return output.String() +} diff --git a/internal/notifier/install_test.go b/internal/notifier/install_test.go new file mode 100644 index 0000000..207ff1b --- /dev/null +++ b/internal/notifier/install_test.go @@ -0,0 +1,57 @@ +package notifier + +import ( + "encoding/xml" + "strings" + "testing" +) + +func TestEntryForEachPlatform(t *testing.T) { + tests := []struct { + goos string + path string + text string + }{ + {goos: "linux", path: ".config/autostart/attackpath-visualizer-notifier.desktop", text: "notifier run"}, + {goos: "darwin", path: "Library/LaunchAgents/dev.nexza.attackpathvisualizer.notifier.plist", text: "StartInterval"}, + {goos: "windows", path: "Startup/attackpath-visualizer-notifier.cmd", text: "@echo off"}, + } + for _, test := range tests { + t.Run(test.goos, func(t *testing.T) { + path, body, err := Entry(test.goos, "/Users/Example App/attackpath-visualizer", "/Users/example", "/var/data/graph file.db") + if err != nil { + t.Fatal(err) + } + portablePath := strings.ReplaceAll(path, "\\", "/") + if !strings.Contains(portablePath, test.path) || !strings.Contains(string(body), test.text) || !strings.Contains(string(body), "graph file.db") { + t.Fatalf("path=%q body=%q", path, body) + } + }) + } +} + +func TestMacLaunchAgentEscapesArgumentsAsXML(t *testing.T) { + _, body, err := Entry("darwin", "/Applications/A&B.app", "/Users/example", "/data/one&two.db") + if err != nil { + t.Fatal(err) + } + var parsed struct { + Arguments []string `xml:"dict>array>string"` + } + if err = xml.Unmarshal(body, &parsed); err != nil { + t.Fatalf("invalid launch agent XML: %v", err) + } + want := []string{"/Applications/A&B.app", "notifier", "run", "--db", "/data/one&two.db"} + if strings.Join(parsed.Arguments, "\x00") != strings.Join(want, "\x00") { + t.Fatalf("arguments = %q", parsed.Arguments) + } +} + +func TestEntryRejectsIncompleteAndUnknownPlatforms(t *testing.T) { + if _, _, err := Entry("linux", "", "/tmp/home"); err == nil { + t.Fatal("expected missing executable error") + } + if _, _, err := Entry("plan9", "/app", "/tmp/home"); err == nil { + t.Fatal("expected unsupported OS error") + } +} diff --git a/internal/notifier/notifier.go b/internal/notifier/notifier.go new file mode 100644 index 0000000..346e0cc --- /dev/null +++ b/internal/notifier/notifier.go @@ -0,0 +1,102 @@ +package notifier + +import ( + "context" + "errors" + "fmt" + "os" + "os/signal" + "time" + + "github.com/NexzaDev/attackpath-visualizer/internal/config" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" + "github.com/gen2brain/beeep" +) + +const DefaultInterval = 15 * time.Minute + +type Sender func(string, string) error + +func Run(ctx context.Context, requestedDB string, interval time.Duration, sender Sender) error { + if interval <= 0 || interval > time.Hour { + return errors.New("notifier interval must be between one nanosecond and one hour") + } + path, err := config.DatabasePath(requestedDB) + if err != nil { + return err + } + store, err := repository.OpenReadOnly(path) + if err != nil { + return err + } + defer store.Close() + if sender == nil { + sender = func(title, message string) error { return beeep.Notify(title, message, nil) } + } + for { + if _, err = DeliverPending(ctx, store, sender); err != nil { + return err + } + timer := time.NewTimer(interval) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } +} + +func RunUntilSignal(requestedDB string) error { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + err := Run(ctx, requestedDB, DefaultInterval, nil) + if errors.Is(err, context.Canceled) { + return nil + } + return err +} + +func DeliverPending(ctx context.Context, store *repository.Store, sender Sender) (int, error) { + items, err := store.PendingNotifications(ctx) + if err != nil { + return 0, err + } + rules, err := store.NotificationRules(ctx) + if err != nil { + return 0, err + } + path, err := statePath(store.Path()) + if err != nil { + return 0, err + } + state, err := loadDeliveryState(path) + if err != nil { + return 0, err + } + delivered := 0 + for _, item := range items { + key := notificationKey(item) + if state.Delivered[key] { + continue + } + title, message := "AttackPath Visualizer", "New local findings are available" + if item.Type == "validation_failed" { + message = "An import failed validation" + } else { + message = "A new critical potential path was found" + } + if rule, ok := rules[item.Type]; ok && rule.DetailedText && item.Detail != "" { + message = item.Detail + } + if err := sender(title, message); err != nil { + return delivered, fmt.Errorf("send operating-system notification: %w", err) + } + state.Delivered[key] = true + if err := saveDeliveryState(path, state); err != nil { + return delivered, err + } + delivered++ + } + return delivered, nil +} diff --git a/internal/notifier/notifier_test.go b/internal/notifier/notifier_test.go new file mode 100644 index 0000000..eed4a43 --- /dev/null +++ b/internal/notifier/notifier_test.go @@ -0,0 +1,100 @@ +package notifier + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/NexzaDev/attackpath-visualizer/internal/notifications" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" +) + +func TestDeliverPendingUsesMinimalTextAndPersistsDeliveryOutsideDatabase(t *testing.T) { + isolateDeliveryState(t) + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + ctx := context.Background() + if _, err = store.AddNotification(ctx, notifications.Event{Type: "critical_path", Severity: 5, Title: "New critical potential path", Detail: "Never shown in minimal text", Related: "paths"}, time.Minute); err != nil { + t.Fatal(err) + } + var message string + count, err := DeliverPending(ctx, store, func(_, text string) error { + message = text + return nil + }) + if err != nil || count != 1 { + t.Fatalf("count=%d err=%v", count, err) + } + if message != "A new critical potential path was found" { + t.Fatalf("unexpected notification text %q", message) + } + pending, err := store.PendingNotifications(ctx) + if err != nil || len(pending) != 1 { + t.Fatalf("read-only delivery unexpectedly changed the database: pending=%v err=%v", pending, err) + } + secondCount, err := DeliverPending(ctx, store, func(string, string) error { + t.Fatal("already delivered notification was sent twice") + return nil + }) + if err != nil || secondCount != 0 { + t.Fatalf("second delivery count=%d err=%v", secondCount, err) + } +} + +func isolateDeliveryState(t *testing.T) { + directory := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", directory) + t.Setenv("APPDATA", directory) + t.Setenv("HOME", directory) +} + +func TestDetailedNotificationPreferenceUsesConfiguredText(t *testing.T) { + isolateDeliveryState(t) + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + ctx := context.Background() + if err = store.SaveNotificationRule(ctx, "validation_failed", notifications.Rule{Enabled: true, MinimumSeverity: 1, DetailedText: true}); err != nil { + t.Fatal(err) + } + if _, err = store.AddNotification(ctx, notifications.Event{Type: "validation_failed", Severity: 3, Title: "Import failed", Detail: "The JSON field assets is missing.", Related: "imports"}, time.Minute); err != nil { + t.Fatal(err) + } + var message string + if _, err = DeliverPending(ctx, store, func(_, text string) error { + message = text + return nil + }); err != nil { + t.Fatal(err) + } + if message != "The JSON field assets is missing." { + t.Fatalf("detailed notification text = %q", message) + } +} + +func TestDeliveryFailureDoesNotRecordDeliveredState(t *testing.T) { + isolateDeliveryState(t) + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + ctx := context.Background() + if _, err = store.AddNotification(ctx, notifications.Event{Type: "validation_failed", Severity: 3, Title: "Import failed validation", Related: "imports"}, time.Minute); err != nil { + t.Fatal(err) + } + failure := errors.New("notification service unavailable") + if _, err = DeliverPending(ctx, store, func(string, string) error { return failure }); !errors.Is(err, failure) { + t.Fatalf("expected sender failure, got %v", err) + } + pending, err := store.PendingNotifications(ctx) + if err != nil || len(pending) != 1 { + t.Fatalf("pending=%v err=%v", pending, err) + } +} diff --git a/internal/remediation/rank.go b/internal/remediation/rank.go new file mode 100644 index 0000000..c6dad24 --- /dev/null +++ b/internal/remediation/rank.go @@ -0,0 +1,77 @@ +package remediation + +import ( + "fmt" + "sort" + + "github.com/NexzaDev/attackpath-visualizer/internal/domain" +) + +type Suggestion struct { + EdgeID string `json:"edge_id"` + From string `json:"from"` + To string `json:"to"` + Relation string `json:"relation"` + PathsAffected int `json:"paths_affected"` + CriticalPaths int `json:"critical_paths"` + WeightedRiskPoints int `json:"weighted_risk_points"` + Recommendation string `json:"recommendation"` +} + +type Result struct { + Suggestions []Suggestion `json:"suggestions"` + PathsConsidered int `json:"paths_considered"` + PathsTruncated bool `json:"paths_truncated"` +} + +type edgeImpact struct { + edge domain.Edge + paths int + critical int + points int +} + +func Rank(graph domain.Graph, pathSet domain.PathResult) Result { + impacts := make(map[string]*edgeImpact, len(graph.Edges)) + for _, edge := range graph.Edges { + impacts[edge.ID] = &edgeImpact{edge: edge} + } + for _, path := range pathSet.Paths { + for _, edge := range path.Edges { + impact := impacts[edge.ID] + if impact == nil { + continue + } + impact.paths++ + impact.points += path.Score + if path.Impact >= 4 && path.Confidence >= 60 { + impact.critical++ + } + } + } + suggestions := make([]Suggestion, 0, len(impacts)) + for _, impact := range impacts { + if impact.paths == 0 { + continue + } + suggestions = append(suggestions, Suggestion{ + EdgeID: impact.edge.ID, From: impact.edge.From, To: impact.edge.To, Relation: impact.edge.Relation, + PathsAffected: impact.paths, CriticalPaths: impact.critical, WeightedRiskPoints: impact.points, + Recommendation: fmt.Sprintf("Review and, where appropriate, restrict or remove the %q relationship; it appears in %d enumerated paths.", impact.edge.Relation, impact.paths), + }) + } + sort.Slice(suggestions, func(i, j int) bool { + left, right := suggestions[i], suggestions[j] + if left.PathsAffected != right.PathsAffected { + return left.PathsAffected > right.PathsAffected + } + if left.WeightedRiskPoints != right.WeightedRiskPoints { + return left.WeightedRiskPoints > right.WeightedRiskPoints + } + if left.CriticalPaths != right.CriticalPaths { + return left.CriticalPaths > right.CriticalPaths + } + return left.EdgeID < right.EdgeID + }) + return Result{Suggestions: suggestions, PathsConsidered: len(pathSet.Paths), PathsTruncated: pathSet.Truncated} +} diff --git a/internal/remediation/rank_test.go b/internal/remediation/rank_test.go new file mode 100644 index 0000000..a936bc8 --- /dev/null +++ b/internal/remediation/rank_test.go @@ -0,0 +1,49 @@ +package remediation + +import ( + "testing" + + "github.com/NexzaDev/attackpath-visualizer/internal/domain" +) + +func TestRankPrioritizesChokePointByPathsBrokenAndRisk(t *testing.T) { + graph := domain.Graph{ + Assets: []domain.Asset{ + {ID: "a", Name: "Entry", Kind: "service", Impact: 1}, + {ID: "b", Name: "Broker", Kind: "service", Impact: 2}, + {ID: "c", Name: "Worker", Kind: "compute", Impact: 3}, + {ID: "d", Name: "Customer data", Kind: "database", Impact: 5}, + {ID: "e", Name: "Backup data", Kind: "storage", Impact: 5}, + }, + Edges: []domain.Edge{ + {ID: "entry-broker", From: "a", To: "b", Relation: "connects", Confidence: 100, Evidence: evidence("entry")}, + {ID: "broker-data", From: "b", To: "d", Relation: "reads", Confidence: 90, Evidence: evidence("database")}, + {ID: "broker-worker", From: "b", To: "c", Relation: "invokes", Confidence: 95, Evidence: evidence("worker")}, + {ID: "worker-data", From: "c", To: "d", Relation: "reads", Confidence: 90, Evidence: evidence("database")}, + {ID: "worker-backup", From: "c", To: "e", Relation: "writes", Confidence: 80, Evidence: evidence("backup")}, + }, + } + paths, err := graph.EnumeratePaths(8, 100) + if err != nil { + t.Fatal(err) + } + if len(paths.Paths) != 5 { + t.Fatalf("expected five source-rooted path prefixes, got %d", len(paths.Paths)) + } + paths.Truncated = true + result := Rank(graph, paths) + if len(result.Suggestions) != 5 || result.PathsConsidered != 5 || !result.PathsTruncated { + t.Fatalf("unexpected remediation result: %#v", result) + } + first := result.Suggestions[0] + if first.EdgeID != "entry-broker" || first.PathsAffected != 5 || first.WeightedRiskPoints == 0 { + t.Fatalf("shared choke point was not ranked first: %#v", first) + } + if first.CriticalPaths != 3 || first.Recommendation == "" { + t.Fatalf("critical paths/recommendation missing: %#v", first) + } +} + +func evidence(finding string) domain.Evidence { + return domain.Evidence{Source: "fixture://test", Finding: finding, Observed: "synthetic"} +} diff --git a/internal/reports/reports.go b/internal/reports/reports.go new file mode 100644 index 0000000..655e544 --- /dev/null +++ b/internal/reports/reports.go @@ -0,0 +1,86 @@ +package reports + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" + + "github.com/NexzaDev/attackpath-visualizer/internal/domain" + "github.com/NexzaDev/attackpath-visualizer/internal/remediation" +) + +const SchemaVersion = 1 + +type Bundle struct { + SchemaVersion int `json:"schema_version"` + PathCount int `json:"path_count"` + PathsTruncated bool `json:"paths_truncated"` + Expansions int `json:"edge_expansions"` + Paths []domain.Path `json:"paths"` + Remediation remediation.Result `json:"remediation"` +} + +func Build(paths domain.PathResult, ranked remediation.Result) Bundle { + return Bundle{SchemaVersion: SchemaVersion, PathCount: len(paths.Paths), PathsTruncated: paths.Truncated, Expansions: paths.Expanded, Paths: paths.Paths, Remediation: ranked} +} + +func JSON(bundle Bundle) ([]byte, error) { + var output bytes.Buffer + encoder := json.NewEncoder(&output) + encoder.SetEscapeHTML(false) + encoder.SetIndent("", " ") + if err := encoder.Encode(bundle); err != nil { + return nil, fmt.Errorf("encode path and remediation report: %w", err) + } + return output.Bytes(), nil +} + +func Markdown(bundle Bundle) string { + var output strings.Builder + output.WriteString("# AttackPath Visualizer — Path and Remediation Report\n\n") + output.WriteString("Potential relationships are advisory and are not proof of exploitability. No changes are made to the inventory.\n\n") + output.WriteString(fmt.Sprintf("- Paths included: %d\n- Enumeration expansions: %d\n- Results truncated: %t\n- Scoring: maximum node impact tier × compounded edge confidence; integer floor after each edge\n\n", bundle.PathCount, bundle.Expansions, bundle.PathsTruncated)) + output.WriteString("## Ranked paths\n\n") + if len(bundle.Paths) == 0 { + output.WriteString("No directed paths were found within the configured depth and expansion limits.\n\n") + } else { + output.WriteString("| Rank | Path | Impact | Edge confidence components | Confidence | Score |\n|---:|---|---:|---|---:|---:|\n") + for index, path := range bundle.Paths { + labels := make([]string, len(path.Nodes)) + for nodeIndex, node := range path.Nodes { + labels[nodeIndex] = fmt.Sprintf("%s (`%s`)", node.Name, node.ID) + } + confidences := make([]string, len(path.Components.EdgeConfidences)) + for edgeIndex, confidence := range path.Components.EdgeConfidences { + confidences[edgeIndex] = fmt.Sprintf("%d%%", confidence) + } + output.WriteString(fmt.Sprintf("| %d | %s | %d/5 | %s | %d%% | %d |\n", index+1, cell(strings.Join(labels, " → ")), path.Components.ImpactTier, cell(strings.Join(confidences, " × ")), path.Components.CompoundedConfidence, path.Components.Score)) + } + output.WriteString("\n") + for index, path := range bundle.Paths { + output.WriteString(fmt.Sprintf("### Path %d evidence\n\n", index+1)) + output.WriteString(path.Explanation + "\n\n") + for _, edge := range path.Edges { + output.WriteString(fmt.Sprintf("- `%s`: `%s` → `%s` — %s (%d%% confidence). Source: %s. Finding: %s. Observed: %s.\n", edge.ID, edge.From, edge.To, edge.Relation, edge.Confidence, cell(edge.Evidence.Source), cell(edge.Evidence.Finding), cell(edge.Evidence.Observed))) + } + output.WriteString("\n") + } + } + output.WriteString("## Ranked remediation suggestions\n\n") + if len(bundle.Remediation.Suggestions) == 0 { + output.WriteString("No path-affecting relationships are available for ranking.\n") + } else { + output.WriteString("Suggestions rank relationship choke points by enumerated paths affected, then weighted risk points. Validate with the asset owner before changing access.\n\n") + output.WriteString("| Rank | Edge | Relationship | Paths affected | Critical paths | Weighted risk points | Recommendation |\n|---:|---|---|---:|---:|---:|---|\n") + for index, item := range bundle.Remediation.Suggestions { + output.WriteString(fmt.Sprintf("| %d | `%s` | %s | %d | %d | %d | %s |\n", index+1, item.EdgeID, cell(item.Relation), item.PathsAffected, item.CriticalPaths, item.WeightedRiskPoints, cell(item.Recommendation))) + } + } + return output.String() +} + +func cell(value string) string { + value = strings.ReplaceAll(value, "|", "\\|") + return strings.ReplaceAll(strings.ReplaceAll(value, "\r", " "), "\n", " ") +} diff --git a/internal/reports/reports_test.go b/internal/reports/reports_test.go new file mode 100644 index 0000000..5c46bca --- /dev/null +++ b/internal/reports/reports_test.go @@ -0,0 +1,50 @@ +package reports + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/NexzaDev/attackpath-visualizer/internal/domain" + "github.com/NexzaDev/attackpath-visualizer/internal/remediation" +) + +func TestReportsIncludeScoreComponentsEvidenceAndCoverage(t *testing.T) { + path := domain.Path{ + Nodes: []domain.Node{{ID: "entry", Name: "Entry", EntityType: "asset", Kind: "service", Impact: 1}, {ID: "data", Name: "Data", EntityType: "asset", Kind: "database", Impact: 5}}, + Edges: []domain.Edge{{ID: "read-edge", From: "entry", To: "data", Relation: "reads", Confidence: 80, Evidence: domain.Evidence{Source: "fixture://access", Finding: "Read grant", Observed: "synthetic"}}}, + Impact: 5, Confidence: 80, Score: 400, Components: domain.ScoreBreakdown{ImpactTier: 5, EdgeConfidences: []int{80}, CompoundedConfidence: 80, Score: 400}, + Explanation: "Impact tier 5 × compounded confidence 80% (80%; floor after each edge) = 400 points", + } + paths := domain.PathResult{Paths: []domain.Path{path}, Truncated: true, Expanded: 25} + ranked := remediation.Result{PathsConsidered: 1, PathsTruncated: true, Suggestions: []remediation.Suggestion{{EdgeID: "read-edge", From: "entry", To: "data", Relation: "reads", PathsAffected: 1, CriticalPaths: 1, WeightedRiskPoints: 400, Recommendation: "Review read access"}}} + bundle := Build(paths, ranked) + data, err := JSON(bundle) + if err != nil { + t.Fatal(err) + } + var decoded Bundle + if err = json.Unmarshal(data, &decoded); err != nil { + t.Fatal(err) + } + if decoded.PathCount != 1 || !decoded.PathsTruncated || decoded.Expansions != 25 || decoded.Paths[0].Components.EdgeConfidences[0] != 80 || decoded.Remediation.Suggestions[0].WeightedRiskPoints != 400 { + t.Fatalf("JSON report lost ranked analysis data: %#v", decoded) + } + markdown := Markdown(bundle) + for _, required := range []string{"## Ranked paths", "Edge confidence components", "80%", "fixture://access", "Read grant", "## Ranked remediation suggestions", "read-edge", "400", "Results truncated: true"} { + if !strings.Contains(markdown, required) { + t.Fatalf("Markdown report does not include %q:\n%s", required, markdown) + } + } +} + +func TestMarkdownReportHandlesEmptyPathsAndEscapesCells(t *testing.T) { + bundle := Build(domain.PathResult{}, remediation.Result{}) + markdown := Markdown(bundle) + if !strings.Contains(markdown, "No directed paths were found") || !strings.Contains(markdown, "No path-affecting relationships") { + t.Fatalf("empty report lacks useful states: %s", markdown) + } + if got := cell("alpha|beta\ngamma"); got != "alpha\\|beta gamma" { + t.Fatalf("cell escaping = %q", got) + } +} diff --git a/internal/repository/migration.go b/internal/repository/migration.go new file mode 100644 index 0000000..b972b18 --- /dev/null +++ b/internal/repository/migration.go @@ -0,0 +1,105 @@ +package repository + +import ( + "context" + "database/sql" + "fmt" + "strconv" + "strings" + + "github.com/NexzaDev/attackpath-visualizer/migrations" +) + +func runMigrations(db *sql.DB) error { + if _, err := db.Exec("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)"); err != nil { + return fmt.Errorf("initialize schema migration table: %w", err) + } + files, err := migrations.Files.ReadDir(".") + if err != nil { + return fmt.Errorf("list embedded migrations: %w", err) + } + for _, file := range files { + if file.IsDir() || !strings.HasSuffix(file.Name(), ".sql") { + continue + } + versionText := strings.SplitN(file.Name(), "_", 2)[0] + version, parseErr := strconv.Atoi(versionText) + if parseErr != nil || version < 1 { + return fmt.Errorf("invalid migration filename %q", file.Name()) + } + var applied int + if err = db.QueryRow("SELECT COUNT(*) FROM schema_migrations WHERE version=?", version).Scan(&applied); err != nil { + return fmt.Errorf("check migration %d: %w", version, err) + } + if applied != 0 { + continue + } + data, readErr := migrations.Files.ReadFile(file.Name()) + if readErr != nil { + return fmt.Errorf("read migration %q: %w", file.Name(), readErr) + } + tx, beginErr := db.BeginTx(context.Background(), nil) + if beginErr != nil { + return fmt.Errorf("begin migration %d: %w", version, beginErr) + } + if version == 2 { + if err = ensureColumnTx(tx, "imports", "status", "TEXT NOT NULL DEFAULT 'success'"); err == nil { + err = ensureColumnTx(tx, "imports", "error_message", "TEXT NOT NULL DEFAULT ''") + } + } + if err == nil { + for _, statement := range strings.Split(string(data), ";") { + statement = strings.TrimSpace(statement) + if statement == "" { + continue + } + if _, err = tx.Exec(statement); err != nil { + break + } + } + } + if err == nil { + _, err = tx.Exec("INSERT INTO schema_migrations(version) VALUES(?)", version) + } + if err != nil { + tx.Rollback() + return fmt.Errorf("apply migration %q: %w", file.Name(), err) + } + if err = tx.Commit(); err != nil { + return fmt.Errorf("commit migration %q: %w", file.Name(), err) + } + } + return nil +} + +func ensureColumnTx(tx *sql.Tx, table, name, definition string) error { + rows, err := tx.Query("PRAGMA table_info(" + table + ")") + if err != nil { + return err + } + found := false + for rows.Next() { + var index, notNull, primary int + var columnName, columnType string + var defaultValue sql.NullString + if err = rows.Scan(&index, &columnName, &columnType, ¬Null, &defaultValue, &primary); err != nil { + rows.Close() + return err + } + if columnName == name { + found = true + } + } + if err = rows.Err(); err != nil { + rows.Close() + return err + } + if err = rows.Close(); err != nil { + return err + } + if found { + return nil + } + _, err = tx.Exec("ALTER TABLE " + table + " ADD COLUMN " + name + " " + definition) + return err +} diff --git a/internal/repository/migration_test.go b/internal/repository/migration_test.go new file mode 100644 index 0000000..d76e10e --- /dev/null +++ b/internal/repository/migration_test.go @@ -0,0 +1,60 @@ +package repository + +import ( + "context" + "database/sql" + "path/filepath" + "testing" +) + +func TestLegacySchemaMigratesWithoutLosingGraph(t *testing.T) { + path := filepath.Join(t.TempDir(), "legacy.db") + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + for _, statement := range []string{ + `CREATE TABLE assets (id TEXT PRIMARY KEY, name TEXT NOT NULL, kind TEXT NOT NULL, impact INTEGER NOT NULL, description TEXT NOT NULL)`, + `CREATE TABLE edges (id TEXT PRIMARY KEY, source_id TEXT NOT NULL, target_id TEXT NOT NULL, relation TEXT NOT NULL, confidence INTEGER NOT NULL, evidence_json TEXT NOT NULL)`, + `CREATE TABLE imports (id INTEGER PRIMARY KEY, source TEXT NOT NULL, asset_count INTEGER NOT NULL, edge_count INTEGER NOT NULL, imported_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)`, + `INSERT INTO assets(id,name,kind,impact,description) VALUES('legacy','Legacy node','service',4,'preserved')`, + `INSERT INTO assets(id,name,kind,impact,description) VALUES('legacy-target','Legacy target','database',5,'preserved')`, + `INSERT INTO edges(id,source_id,target_id,relation,confidence,evidence_json) VALUES('legacy-edge','legacy','legacy-target','reads',70,'{}')`, + } { + if _, err = db.Exec(statement); err != nil { + t.Fatal(err) + } + } + if err = db.Close(); err != nil { + t.Fatal(err) + } + store, err := Open(path) + if err != nil { + t.Fatal(err) + } + defer store.Close() + graph, err := store.Graph(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(graph.Assets) != 2 || graph.Assets[0].ID != "legacy" || len(graph.Edges) != 1 || graph.Edges[0].Evidence.Source != "legacy://no-recorded-evidence" { + t.Fatalf("legacy graph was not preserved and normalized: %#v", graph) + } + if err = graph.Validate(); err != nil { + t.Fatalf("migrated legacy graph is not valid: %v", err) + } + if err = store.RecordFailedImport(context.Background(), "invalid input"); err != nil { + t.Fatal(err) + } + history, err := store.ImportHistory(context.Background()) + if err != nil || len(history) != 1 || history[0]["status"] != "failed" { + t.Fatalf("history=%v err=%v", history, err) + } + var version int + if err = store.db.QueryRow("SELECT MAX(version) FROM schema_migrations").Scan(&version); err != nil { + t.Fatal(err) + } + if version != 4 { + t.Fatalf("migration version = %d", version) + } +} diff --git a/internal/repository/notifications.go b/internal/repository/notifications.go new file mode 100644 index 0000000..2d95cf0 --- /dev/null +++ b/internal/repository/notifications.go @@ -0,0 +1,204 @@ +package repository + +import ( + "context" + "database/sql" + "fmt" + "net/url" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/NexzaDev/attackpath-visualizer/internal/notifications" +) + +type Notification struct { + ID int64 `json:"id"` + Type string `json:"type"` + Severity int `json:"severity"` + Title string `json:"title"` + Detail string `json:"detail"` + RelatedID string `json:"related_id"` + CreatedAt time.Time `json:"created_at"` + Read bool `json:"read"` +} + +func readOnlySQLiteURI(path string) string { + path = filepath.ToSlash(path) + uri := &url.URL{Scheme: "file"} + if runtime.GOOS == "windows" && strings.HasPrefix(path, "//") { + unc := strings.TrimPrefix(path, "//") + uri.Host, path, _ = strings.Cut(unc, "/") + path = "/" + path + } else if runtime.GOOS == "windows" && len(path) > 1 && path[1] == ':' { + path = "/" + path + } + uri.Path = path + query := uri.Query() + query.Set("mode", "ro") + uri.RawQuery = query.Encode() + return uri.String() +} + +func OpenReadOnly(path string) (*Store, error) { + uri := readOnlySQLiteURI(path) + db, err := sql.Open("sqlite", uri) + if err != nil { + return nil, fmt.Errorf("open read-only database: %w", err) + } + db.SetMaxOpenConns(1) + if _, err = db.Exec("PRAGMA busy_timeout=5000"); err != nil { + db.Close() + return nil, fmt.Errorf("set read timeout: %w", err) + } + if err = db.Ping(); err != nil { + db.Close() + return nil, fmt.Errorf("read-only database is unavailable: %w", err) + } + return &Store{db: db, path: path}, nil +} + +func (s *Store) AddNotification(ctx context.Context, event notifications.Event, window time.Duration) (bool, error) { + key := notifications.Key(event) + now := time.Now().UTC() + var last string + err := s.db.QueryRowContext(ctx, "SELECT created_at FROM notifications WHERE dedup_key=? ORDER BY id DESC LIMIT 1", key).Scan(&last) + if err != nil && err != sql.ErrNoRows { + return false, fmt.Errorf("check notification duplicates: %w", err) + } + if err == nil { + parsed, parseErr := time.Parse(time.RFC3339Nano, last) + if parseErr == nil && notifications.Deduplicated(parsed, now, window) { + return false, nil + } + } + _, err = s.db.ExecContext(ctx, "INSERT INTO notifications(event_type,severity,title,detail,related_id,dedup_key,created_at) VALUES(?,?,?,?,?,?,?)", event.Type, event.Severity, event.Title, event.Detail, event.Related, key, now.Format(time.RFC3339Nano)) + if err != nil { + return false, fmt.Errorf("save notification: %w", err) + } + return true, nil +} + +func (s *Store) Notifications(ctx context.Context, limit int) ([]Notification, error) { + if limit < 1 || limit > 500 { + limit = 100 + } + rows, err := s.db.QueryContext(ctx, "SELECT id,event_type,severity,title,detail,related_id,created_at,read_at FROM notifications ORDER BY id DESC LIMIT ?", limit) + if err != nil { + return nil, fmt.Errorf("read notifications: %w", err) + } + defer rows.Close() + items := make([]Notification, 0) + for rows.Next() { + var item Notification + var created, readAt string + if err = rows.Scan(&item.ID, &item.Type, &item.Severity, &item.Title, &item.Detail, &item.RelatedID, &created, &readAt); err != nil { + return nil, fmt.Errorf("read notification: %w", err) + } + item.CreatedAt, err = time.Parse(time.RFC3339Nano, created) + if err != nil { + return nil, fmt.Errorf("parse notification time: %w", err) + } + item.Read = readAt != "" + items = append(items, item) + } + return items, rows.Err() +} + +func (s *Store) UnreadCount(ctx context.Context) (int, error) { + var count int + if err := s.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM notifications WHERE read_at='' ").Scan(&count); err != nil { + return 0, fmt.Errorf("count unread notifications: %w", err) + } + return count, nil +} + +func (s *Store) MarkNotificationRead(ctx context.Context, id int64) error { + _, err := s.db.ExecContext(ctx, "UPDATE notifications SET read_at=? WHERE id=?", time.Now().UTC().Format(time.RFC3339Nano), id) + if err != nil { + return fmt.Errorf("mark notification read: %w", err) + } + return nil +} + +func (s *Store) MarkAllNotificationsRead(ctx context.Context) error { + _, err := s.db.ExecContext(ctx, "UPDATE notifications SET read_at=? WHERE read_at=''", time.Now().UTC().Format(time.RFC3339Nano)) + if err != nil { + return fmt.Errorf("mark notifications read: %w", err) + } + return nil +} + +func (s *Store) NotificationRules(ctx context.Context) (map[string]notifications.Rule, error) { + rows, err := s.db.QueryContext(ctx, "SELECT event_type,enabled,minimum_severity,quiet_start,quiet_end,detailed_text FROM notification_rules ORDER BY event_type") + if err != nil { + return nil, fmt.Errorf("read notification rules: %w", err) + } + defer rows.Close() + rules := make(map[string]notifications.Rule) + for rows.Next() { + var eventType string + var enabled, severity, detailed int + var start, end string + if err = rows.Scan(&eventType, &enabled, &severity, &start, &end, &detailed); err != nil { + return nil, err + } + rules[eventType] = notifications.Rule{Enabled: enabled != 0, MinimumSeverity: severity, QuietStart: start, QuietEnd: end, DetailedText: detailed != 0} + } + return rules, rows.Err() +} + +func (s *Store) SaveNotificationRule(ctx context.Context, eventType string, rule notifications.Rule) error { + _, err := s.db.ExecContext(ctx, "INSERT INTO notification_rules(event_type,enabled,minimum_severity,quiet_start,quiet_end,detailed_text) VALUES(?,?,?,?,?,?) ON CONFLICT(event_type) DO UPDATE SET enabled=excluded.enabled,minimum_severity=excluded.minimum_severity,quiet_start=excluded.quiet_start,quiet_end=excluded.quiet_end,detailed_text=excluded.detailed_text", eventType, boolInt(rule.Enabled), rule.MinimumSeverity, rule.QuietStart, rule.QuietEnd, boolInt(rule.DetailedText)) + if err != nil { + return fmt.Errorf("save notification rule: %w", err) + } + return nil +} + +func (s *Store) PendingNotifications(ctx context.Context) ([]Notification, error) { + rules, err := s.NotificationRules(ctx) + if err != nil { + return nil, err + } + rows, err := s.db.QueryContext(ctx, "SELECT id,event_type,severity,title,detail,related_id,created_at,read_at FROM notifications WHERE delivered_at='' AND read_at='' ORDER BY id") + if err != nil { + return nil, fmt.Errorf("read pending notifications: %w", err) + } + defer rows.Close() + now := time.Now() + items := make([]Notification, 0) + for rows.Next() { + var item Notification + var created, readAt string + if err = rows.Scan(&item.ID, &item.Type, &item.Severity, &item.Title, &item.Detail, &item.RelatedID, &created, &readAt); err != nil { + return nil, fmt.Errorf("read pending notification: %w", err) + } + item.CreatedAt, err = time.Parse(time.RFC3339Nano, created) + if err != nil { + return nil, fmt.Errorf("parse notification time: %w", err) + } + item.Read = readAt != "" + rule, ok := rules[item.Type] + if ok && notifications.Allowed(notifications.Event{Severity: item.Severity}, rule, now) { + items = append(items, item) + } + } + return items, rows.Err() +} + +func (s *Store) MarkNotificationDelivered(ctx context.Context, id int64) error { + _, err := s.db.ExecContext(ctx, "UPDATE notifications SET delivered_at=? WHERE id=?", time.Now().UTC().Format(time.RFC3339Nano), id) + if err != nil { + return fmt.Errorf("mark notification delivered: %w", err) + } + return nil +} + +func boolInt(value bool) int { + if value { + return 1 + } + return 0 +} diff --git a/internal/repository/readonly_test.go b/internal/repository/readonly_test.go new file mode 100644 index 0000000..e70760c --- /dev/null +++ b/internal/repository/readonly_test.go @@ -0,0 +1,40 @@ +package repository + +import ( + "context" + "path/filepath" + "testing" + "time" + + "github.com/NexzaDev/attackpath-visualizer/internal/notifications" +) + +func TestOpenReadOnlyAllowsReadsAndRejectsWrites(t *testing.T) { + path := filepath.Join(t.TempDir(), "graph.db") + writer, err := Open(path) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if _, err = writer.AddNotification(ctx, notifications.Event{Type: "critical_path", Severity: 5, Title: "Critical", Related: "paths"}, time.Minute); err != nil { + t.Fatal(err) + } + if err = writer.Close(); err != nil { + t.Fatal(err) + } + reader, err := OpenReadOnly(path) + if err != nil { + t.Fatal(err) + } + defer reader.Close() + if reader.Path() != path { + t.Fatalf("read-only store path = %q", reader.Path()) + } + items, err := reader.Notifications(ctx, 10) + if err != nil || len(items) != 1 { + t.Fatalf("items=%v err=%v", items, err) + } + if err = reader.MarkNotificationDelivered(ctx, items[0].ID); err == nil { + t.Fatal("read-only database accepted a write") + } +} diff --git a/internal/repository/store.go b/internal/repository/store.go new file mode 100644 index 0000000..7671b77 --- /dev/null +++ b/internal/repository/store.go @@ -0,0 +1,273 @@ +package repository + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/NexzaDev/attackpath-visualizer/internal/domain" + _ "modernc.org/sqlite" +) + +type Store struct { + db *sql.DB + path string +} + +type ImportResult struct { + SchemaVersion int + IdentityCount int + FindingCount int + MisconfigurationCount int + DocumentBytes int +} + +func Open(path string) (*Store, error) { + if path != ":memory:" { + directory := filepath.Dir(path) + if directory != "." { + if err := os.MkdirAll(directory, 0700); err != nil { + return nil, fmt.Errorf("create data directory: %w", err) + } + } + } + db, err := sql.Open("sqlite", path) + if err != nil { + return nil, fmt.Errorf("open database: %w", err) + } + db.SetMaxOpenConns(1) + for _, statement := range []string{"PRAGMA journal_mode=WAL", "PRAGMA busy_timeout=5000", "PRAGMA foreign_keys=ON"} { + if _, err := db.Exec(statement); err != nil { + db.Close() + return nil, fmt.Errorf("configure database: %w", err) + } + } + if err = runMigrations(db); err != nil { + db.Close() + return nil, err + } + for _, rule := range []struct { + typeName string + severity int + }{{"critical_path", 4}, {"validation_failed", 3}} { + if _, err := db.Exec("INSERT OR IGNORE INTO notification_rules(event_type,enabled,minimum_severity,quiet_start,quiet_end,detailed_text) VALUES(?,1,?,'22:00','07:00',0)", rule.typeName, rule.severity); err != nil { + db.Close() + return nil, fmt.Errorf("initialize notification rules: %w", err) + } + } + if path != ":memory:" { + if err := os.Chmod(path, 0600); err != nil { + db.Close() + return nil, fmt.Errorf("restrict database permissions: %w", err) + } + } + return &Store{db: db, path: path}, nil +} + +func (s *Store) Close() error { return s.db.Close() } + +func (s *Store) Path() string { return s.path } + +func (s *Store) RecordFailedImport(ctx context.Context, source string) error { + return s.RecordImportFailure(ctx, source, "Graph document did not pass validation.") +} + +func (s *Store) RecordImportFailure(ctx context.Context, source, message string) error { + if source == "" { + source = "local JSON import" + } + if message == "" { + message = "Graph document did not pass validation." + } + _, err := s.db.ExecContext(ctx, "INSERT INTO imports(source,asset_count,edge_count,status,error_message) VALUES(?,0,0,'failed',?)", source, message) + if err != nil { + return fmt.Errorf("record failed import: %w", err) + } + return nil +} + +func (s *Store) ReplaceGraph(ctx context.Context, graph domain.Graph, source string) error { + return s.ReplaceGraphWithResult(ctx, graph, source, ImportResult{SchemaVersion: graph.SchemaVersion, IdentityCount: len(graph.Identities), FindingCount: len(graph.Findings), MisconfigurationCount: len(graph.Misconfigurations)}) +} + +func (s *Store) ReplaceGraphWithResult(ctx context.Context, graph domain.Graph, source string, result ImportResult) error { + if err := graph.Validate(); err != nil { + return err + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin import: %w", err) + } + defer tx.Rollback() + for _, statement := range []string{"DELETE FROM edges", "DELETE FROM findings", "DELETE FROM misconfigurations", "DELETE FROM identities", "DELETE FROM graph_nodes", "DELETE FROM assets"} { + if _, err = tx.ExecContext(ctx, statement); err != nil { + return fmt.Errorf("clear prior graph data: %w", err) + } + } + for _, asset := range graph.Assets { + if _, err = tx.ExecContext(ctx, "INSERT INTO assets(id,name,kind,impact,description) VALUES(?,?,?,?,?)", asset.ID, asset.Name, asset.Kind, asset.Impact, asset.Description); err != nil { + return fmt.Errorf("save asset %q: %w", asset.ID, err) + } + if _, err = tx.ExecContext(ctx, "INSERT INTO graph_nodes(id,entity_type,name,kind,impact,description) VALUES(?,'asset',?,?,?,?)", asset.ID, asset.Name, asset.Kind, asset.Impact, asset.Description); err != nil { + return fmt.Errorf("save graph node %q: %w", asset.ID, err) + } + } + for _, identity := range graph.Identities { + if _, err = tx.ExecContext(ctx, "INSERT INTO identities(id,name,kind,impact,description) VALUES(?,?,?,?,?)", identity.ID, identity.Name, identity.Kind, identity.Impact, identity.Description); err != nil { + return fmt.Errorf("save identity %q: %w", identity.ID, err) + } + if _, err = tx.ExecContext(ctx, "INSERT INTO graph_nodes(id,entity_type,name,kind,impact,description) VALUES(?,'identity',?,?,?,?)", identity.ID, identity.Name, identity.Kind, identity.Impact, identity.Description); err != nil { + return fmt.Errorf("save graph node %q: %w", identity.ID, err) + } + } + for _, item := range graph.Misconfigurations { + var identityID any + if item.IdentityID != "" { + identityID = item.IdentityID + } + if _, err = tx.ExecContext(ctx, "INSERT INTO misconfigurations(id,asset_id,identity_id,title,severity,description) VALUES(?,?,?,?,?,?)", item.ID, item.AssetID, identityID, item.Title, item.Severity, item.Description); err != nil { + return fmt.Errorf("save misconfiguration %q: %w", item.ID, err) + } + } + for _, item := range graph.Findings { + var identityID, misconfigurationID any + if item.IdentityID != "" { + identityID = item.IdentityID + } + if item.MisconfigurationID != "" { + misconfigurationID = item.MisconfigurationID + } + if _, err = tx.ExecContext(ctx, "INSERT INTO findings(id,asset_id,identity_id,misconfiguration_id,title,severity,source,observed) VALUES(?,?,?,?,?,?,?,?)", item.ID, item.AssetID, identityID, misconfigurationID, item.Title, item.Severity, item.Source, item.Observed); err != nil { + return fmt.Errorf("save finding %q: %w", item.ID, err) + } + } + for _, edge := range graph.Edges { + evidence, marshalErr := json.Marshal(edge.Evidence) + if marshalErr != nil { + return fmt.Errorf("encode evidence for %q: %w", edge.ID, marshalErr) + } + if _, err = tx.ExecContext(ctx, "INSERT INTO edges(id,source_id,target_id,relation,confidence,evidence_json) VALUES(?,?,?,?,?,?)", edge.ID, edge.From, edge.To, edge.Relation, edge.Confidence, evidence); err != nil { + return fmt.Errorf("save edge %q: %w", edge.ID, err) + } + } + if _, err = tx.ExecContext(ctx, "INSERT INTO imports(source,asset_count,edge_count,schema_version,identity_count,finding_count,misconfiguration_count,document_bytes) VALUES(?,?,?,?,?,?,?,?)", source, len(graph.Assets), len(graph.Edges), result.SchemaVersion, result.IdentityCount, result.FindingCount, result.MisconfigurationCount, result.DocumentBytes); err != nil { + return fmt.Errorf("record import: %w", err) + } + if err = tx.Commit(); err != nil { + return fmt.Errorf("commit import: %w", err) + } + return nil +} + +func (s *Store) Graph(ctx context.Context) (domain.Graph, error) { + graph := domain.Graph{SchemaVersion: 1, Assets: make([]domain.Asset, 0), Identities: make([]domain.Identity, 0), Misconfigurations: make([]domain.Misconfiguration, 0), Findings: make([]domain.Finding, 0), Edges: make([]domain.Edge, 0)} + rows, err := s.db.QueryContext(ctx, "SELECT id,name,kind,impact,description FROM assets ORDER BY name,id") + if err != nil { + return graph, fmt.Errorf("read assets: %w", err) + } + for rows.Next() { + var asset domain.Asset + if err = rows.Scan(&asset.ID, &asset.Name, &asset.Kind, &asset.Impact, &asset.Description); err != nil { + rows.Close() + return graph, fmt.Errorf("read asset: %w", err) + } + graph.Assets = append(graph.Assets, asset) + } + if err = rows.Err(); err != nil { + rows.Close() + return graph, fmt.Errorf("read assets: %w", err) + } + rows.Close() + rows, err = s.db.QueryContext(ctx, "SELECT id,name,kind,impact,description FROM identities ORDER BY name,id") + if err != nil { + return graph, fmt.Errorf("read identities: %w", err) + } + for rows.Next() { + var identity domain.Identity + if err = rows.Scan(&identity.ID, &identity.Name, &identity.Kind, &identity.Impact, &identity.Description); err != nil { + rows.Close() + return graph, fmt.Errorf("read identity: %w", err) + } + graph.Identities = append(graph.Identities, identity) + } + if err = rows.Err(); err != nil { + rows.Close() + return graph, fmt.Errorf("read identities: %w", err) + } + rows.Close() + rows, err = s.db.QueryContext(ctx, "SELECT id,asset_id,COALESCE(identity_id,''),title,severity,description FROM misconfigurations ORDER BY id") + if err != nil { + return graph, fmt.Errorf("read misconfigurations: %w", err) + } + for rows.Next() { + var item domain.Misconfiguration + if err = rows.Scan(&item.ID, &item.AssetID, &item.IdentityID, &item.Title, &item.Severity, &item.Description); err != nil { + rows.Close() + return graph, fmt.Errorf("read misconfiguration: %w", err) + } + graph.Misconfigurations = append(graph.Misconfigurations, item) + } + if err = rows.Err(); err != nil { + rows.Close() + return graph, fmt.Errorf("read misconfigurations: %w", err) + } + rows.Close() + rows, err = s.db.QueryContext(ctx, "SELECT id,asset_id,COALESCE(identity_id,''),COALESCE(misconfiguration_id,''),title,severity,source,observed FROM findings ORDER BY id") + if err != nil { + return graph, fmt.Errorf("read findings: %w", err) + } + for rows.Next() { + var item domain.Finding + if err = rows.Scan(&item.ID, &item.AssetID, &item.IdentityID, &item.MisconfigurationID, &item.Title, &item.Severity, &item.Source, &item.Observed); err != nil { + rows.Close() + return graph, fmt.Errorf("read finding: %w", err) + } + graph.Findings = append(graph.Findings, item) + } + if err = rows.Err(); err != nil { + rows.Close() + return graph, fmt.Errorf("read findings: %w", err) + } + rows.Close() + rows, err = s.db.QueryContext(ctx, "SELECT id,source_id,target_id,relation,confidence,evidence_json FROM edges ORDER BY id") + if err != nil { + return graph, fmt.Errorf("read relationships: %w", err) + } + defer rows.Close() + for rows.Next() { + var edge domain.Edge + var evidence string + if err = rows.Scan(&edge.ID, &edge.From, &edge.To, &edge.Relation, &edge.Confidence, &evidence); err != nil { + return graph, fmt.Errorf("read relationship: %w", err) + } + if err = json.Unmarshal([]byte(evidence), &edge.Evidence); err != nil { + return graph, fmt.Errorf("decode evidence for %q: %w", edge.ID, err) + } + graph.Edges = append(graph.Edges, edge) + } + if err = rows.Err(); err != nil { + return graph, fmt.Errorf("read relationships: %w", err) + } + return graph, nil +} + +func (s *Store) ImportHistory(ctx context.Context) ([]map[string]any, error) { + rows, err := s.db.QueryContext(ctx, "SELECT source,asset_count,edge_count,imported_at,status,error_message,schema_version,identity_count,finding_count,misconfiguration_count,document_bytes FROM imports ORDER BY id DESC LIMIT 50") + if err != nil { + return nil, fmt.Errorf("read import history: %w", err) + } + defer rows.Close() + items := make([]map[string]any, 0) + for rows.Next() { + var source, imported, status, message string + var assets, edges, schema, identities, findings, misconfigurations, bytes int + if err = rows.Scan(&source, &assets, &edges, &imported, &status, &message, &schema, &identities, &findings, &misconfigurations, &bytes); err != nil { + return nil, fmt.Errorf("read import result: %w", err) + } + items = append(items, map[string]any{"source": source, "assets": assets, "edges": edges, "identities": identities, "findings": findings, "misconfigurations": misconfigurations, "schema_version": schema, "document_bytes": bytes, "imported_at": imported, "status": status, "message": message}) + } + return items, rows.Err() +} diff --git a/internal/repository/store_test.go b/internal/repository/store_test.go new file mode 100644 index 0000000..2a3197e --- /dev/null +++ b/internal/repository/store_test.go @@ -0,0 +1,85 @@ +package repository + +import ( + "context" + "reflect" + "testing" + + "github.com/NexzaDev/attackpath-visualizer/internal/domain" +) + +func TestReplaceGraphAndImportHistory(t *testing.T) { + store, err := Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + graph := domain.Graph{Assets: []domain.Asset{{ID: "node", Name: "Synthetic node", Kind: "service", Impact: 3}}, Edges: []domain.Edge{}} + if err = store.ReplaceGraph(context.Background(), graph, "test fixture"); err != nil { + t.Fatal(err) + } + got, err := store.Graph(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(got.Assets) != 1 || got.Assets[0].ID != "node" { + t.Fatalf("unexpected graph: %#v", got) + } + history, err := store.ImportHistory(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(history) != 1 || history[0]["source"] != "test fixture" { + t.Fatalf("unexpected history: %#v", history) + } +} + +func TestReplaceGraphPersistsTypedEntitiesEvidenceAndValidationResult(t *testing.T) { + store, err := Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + graph := domain.Graph{ + SchemaVersion: 1, + Assets: []domain.Asset{{ID: "database", Name: "Synthetic database", Kind: "database", Impact: 5, Description: "Fixture"}}, + Identities: []domain.Identity{{ID: "workload", Name: "Synthetic workload", Kind: "service", Impact: 3, Description: "Fixture"}}, + Misconfigurations: []domain.Misconfiguration{{ID: "misconfig", AssetID: "database", IdentityID: "workload", Title: "Overbroad access", Severity: 4, Description: "Fixture only"}}, + Findings: []domain.Finding{{ID: "finding", AssetID: "database", IdentityID: "workload", MisconfigurationID: "misconfig", Title: "Read permission", Severity: 4, Source: "fixture://source", Observed: "synthetic"}}, + Edges: []domain.Edge{{ID: "reads", From: "workload", To: "database", Relation: "reads", Confidence: 85, Evidence: domain.Evidence{Source: "fixture://evidence", Finding: "Read permission", Observed: "synthetic"}}}, + } + result := ImportResult{SchemaVersion: 1, IdentityCount: 1, FindingCount: 1, MisconfigurationCount: 1, DocumentBytes: 512} + if err = store.ReplaceGraphWithResult(context.Background(), graph, "typed fixture", result); err != nil { + t.Fatal(err) + } + got, err := store.Graph(context.Background()) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(graph, got) { + t.Fatalf("round trip mismatch\nwant: %#v\n got: %#v", graph, got) + } + history, err := store.ImportHistory(context.Background()) + if err != nil || len(history) != 1 || history[0]["identities"] != 1 || history[0]["findings"] != 1 || history[0]["misconfigurations"] != 1 || history[0]["schema_version"] != 1 || history[0]["document_bytes"] != 512 { + t.Fatalf("validation history=%v err=%v", history, err) + } +} + +func TestReplaceGraphRejectsBeforeMutation(t *testing.T) { + store, err := Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + bad := domain.Graph{Assets: []domain.Asset{{ID: "bad", Name: "Bad", Kind: "host", Impact: 6}}} + if err = store.ReplaceGraph(context.Background(), bad, "bad input"); err == nil { + t.Fatal("expected validation error") + } + got, err := store.Graph(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(got.Assets) != 0 { + t.Fatalf("unexpected stored assets: %#v", got.Assets) + } +} diff --git a/internal/scoring/scoring.go b/internal/scoring/scoring.go new file mode 100644 index 0000000..75f5b4e --- /dev/null +++ b/internal/scoring/scoring.go @@ -0,0 +1,36 @@ +package scoring + +import ( + "errors" + "fmt" + "strings" +) + +type Result struct { + ImpactTier int `json:"impact_tier"` + EdgeConfidences []int `json:"edge_confidences"` + CompoundedConfidence int `json:"compounded_confidence"` + Score int `json:"score"` + Explanation string `json:"explanation"` +} + +func Score(impact int, edgeConfidences []int) (Result, error) { + if impact < 1 || impact > 5 { + return Result{}, errors.New("impact tier must be from 1 to 5") + } + if len(edgeConfidences) == 0 { + return Result{}, errors.New("a scored path must contain at least one edge confidence") + } + confidence := 100 + parts := make([]string, len(edgeConfidences)) + for index, value := range edgeConfidences { + if value < 0 || value > 100 { + return Result{}, fmt.Errorf("edge confidence %d must be from 0 to 100", index+1) + } + confidence = confidence * value / 100 + parts[index] = fmt.Sprintf("%d%%", value) + } + score := impact * confidence + explanation := fmt.Sprintf("Impact tier %d × compounded confidence %d%% (%s; floor after each edge) = %d points", impact, confidence, strings.Join(parts, " × "), score) + return Result{ImpactTier: impact, EdgeConfidences: append([]int(nil), edgeConfidences...), CompoundedConfidence: confidence, Score: score, Explanation: explanation}, nil +} diff --git a/internal/scoring/scoring_test.go b/internal/scoring/scoring_test.go new file mode 100644 index 0000000..2726e8f --- /dev/null +++ b/internal/scoring/scoring_test.go @@ -0,0 +1,57 @@ +package scoring + +import "testing" + +func TestScoreReportsExactComponentsForKnownPath(t *testing.T) { + result, err := Score(5, []int{90, 80}) + if err != nil { + t.Fatal(err) + } + if result.ImpactTier != 5 || result.CompoundedConfidence != 72 || result.Score != 360 { + t.Fatalf("unexpected score result: %#v", result) + } + if len(result.EdgeConfidences) != 2 || result.EdgeConfidences[0] != 90 || result.EdgeConfidences[1] != 80 { + t.Fatalf("edge components not preserved: %#v", result.EdgeConfidences) + } + want := "Impact tier 5 × compounded confidence 72% (90% × 80%; floor after each edge) = 360 points" + if result.Explanation != want { + t.Fatalf("explanation = %q, want %q", result.Explanation, want) + } +} + +func TestScoreFloorsAfterEachEdgeAndAcceptsZeroConfidence(t *testing.T) { + result, err := Score(3, []int{99, 99, 0}) + if err != nil { + t.Fatal(err) + } + if result.CompoundedConfidence != 0 || result.Score != 0 { + t.Fatalf("expected a zero-confidence score: %#v", result) + } + result, err = Score(2, []int{99, 99}) + if err != nil { + t.Fatal(err) + } + if result.CompoundedConfidence != 98 || result.Score != 196 { + t.Fatalf("expected explicit stepwise floor: %#v", result) + } +} + +func TestScoreRejectsInvalidInput(t *testing.T) { + for _, test := range []struct { + name string + impact int + confidences []int + }{ + {name: "impact too small", impact: 0, confidences: []int{100}}, + {name: "impact too large", impact: 6, confidences: []int{100}}, + {name: "no edges", impact: 1}, + {name: "confidence too small", impact: 1, confidences: []int{-1}}, + {name: "confidence too large", impact: 1, confidences: []int{101}}, + } { + t.Run(test.name, func(t *testing.T) { + if _, err := Score(test.impact, test.confidences); err == nil { + t.Fatal("expected validation error") + } + }) + } +} diff --git a/internal/securitycontact/email_test.go b/internal/securitycontact/email_test.go new file mode 100644 index 0000000..c664c9d --- /dev/null +++ b/internal/securitycontact/email_test.go @@ -0,0 +1,67 @@ +package securitycontact + +import ( + "io/fs" + "os" + "path/filepath" + "regexp" + "runtime" + "strings" + "testing" + "unicode/utf8" +) + +var emailAddress = regexp.MustCompile(`(?i)[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}`) + +const approvedBackupEmail = "SuperMcDuck@proton.me" + +func TestRepositoryEmailAddressesUseApprovedSecurityContact(t *testing.T) { + _, source, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("locate repository root") + } + root := filepath.Clean(filepath.Join(filepath.Dir(source), "../..")) + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.IsDir() { + switch entry.Name() { + case ".git", "licenses", "node_modules", "vendor": + return filepath.SkipDir + } + return nil + } + relative, err := filepath.Rel(root, path) + if err != nil { + return err + } + normalized := filepath.ToSlash(relative) + if normalized == "go.sum" || isThirdPartyLicenseText(normalized) { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + if !utf8.Valid(data) { + return nil + } + for _, match := range emailAddress.FindAllString(string(data), -1) { + lower := strings.ToLower(match) + if match == approvedBackupEmail || strings.HasSuffix(lower, "@users.noreply.github.com") || strings.HasSuffix(lower, "@noreply.github.com") { + continue + } + t.Errorf("unapproved email address %q in %s", match, normalized) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func isThirdPartyLicenseText(path string) bool { + base := strings.ToLower(filepath.Base(path)) + return base == "third_party_notices.md" || base == "licenses.md" +} diff --git a/internal/service/analysis.go b/internal/service/analysis.go new file mode 100644 index 0000000..74e312c --- /dev/null +++ b/internal/service/analysis.go @@ -0,0 +1,73 @@ +package service + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/NexzaDev/attackpath-visualizer/internal/domain" + "github.com/NexzaDev/attackpath-visualizer/internal/remediation" + "github.com/NexzaDev/attackpath-visualizer/internal/reports" +) + +type Analysis struct { + Graph domain.Graph `json:"graph"` + Paths domain.PathResult `json:"paths"` + Remediation remediation.Result `json:"remediation"` +} + +type ConfidenceBand struct { + Label string `json:"label"` + Count int `json:"count"` +} + +type Summary struct { + Analysis + PathsByImpact [5]int `json:"paths_by_impact"` + Confidence []ConfidenceBand `json:"confidence_distribution"` +} + +func (s Service) Analyze(ctx context.Context, maxDepth, limit int) (Analysis, error) { + graph, err := s.Store.Graph(ctx) + if err != nil { + return Analysis{}, err + } + paths, err := graph.EnumeratePaths(maxDepth, limit) + if err != nil { + return Analysis{}, fmt.Errorf("enumerate ranked paths: %w", err) + } + return Analysis{Graph: graph, Paths: paths, Remediation: remediation.Rank(graph, paths)}, nil +} + +func (s Service) Overview(ctx context.Context) (Summary, error) { + analysis, err := s.Analyze(ctx, 16, 1000) + if err != nil { + return Summary{}, err + } + summary := Summary{Analysis: analysis, Confidence: []ConfidenceBand{{Label: "0–19%", Count: 0}, {Label: "20–39%", Count: 0}, {Label: "40–59%", Count: 0}, {Label: "60–79%", Count: 0}, {Label: "80–100%", Count: 0}}} + for _, path := range analysis.Paths.Paths { + if path.Impact >= 1 && path.Impact <= 5 { + summary.PathsByImpact[path.Impact-1]++ + } + band := min(path.Confidence/20, 4) + summary.Confidence[band].Count++ + } + return summary, nil +} + +func (s Service) RenderReport(ctx context.Context, format string) ([]byte, error) { + analysis, err := s.Analyze(ctx, 16, 1000) + if err != nil { + return nil, err + } + bundle := reports.Build(analysis.Paths, analysis.Remediation) + switch strings.ToLower(strings.TrimSpace(format)) { + case "", "json": + return reports.JSON(bundle) + case "markdown", "md": + return []byte(reports.Markdown(bundle)), nil + default: + return nil, errors.New("report format must be json or markdown") + } +} diff --git a/internal/service/service.go b/internal/service/service.go new file mode 100644 index 0000000..1b6841f --- /dev/null +++ b/internal/service/service.go @@ -0,0 +1,120 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "strings" + "time" + + "github.com/NexzaDev/attackpath-visualizer/assets" + "github.com/NexzaDev/attackpath-visualizer/internal/domain" + "github.com/NexzaDev/attackpath-visualizer/internal/ingestion" + "github.com/NexzaDev/attackpath-visualizer/internal/notifications" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" +) + +type Service struct{ Store *repository.Store } + +func (s Service) LoadDemo(ctx context.Context) error { + data, err := assets.Files.ReadFile("demo.json") + if err != nil { + return fmt.Errorf("read embedded demo fixture: %w", err) + } + return s.Import(ctx, strings.NewReader(string(data)), "demo fixture") +} + +func (s Service) Import(ctx context.Context, reader io.Reader, source string) error { + if source == "" { + source = "local JSON import" + } + graph, validation, err := ingestion.Read(reader) + if err != nil { + return s.validationFailure(ctx, source, err) + } + previous, err := s.Store.Graph(ctx) + if err != nil { + return fmt.Errorf("read existing graph: %w", err) + } + result := repository.ImportResult{SchemaVersion: validation.SchemaVersion, IdentityCount: validation.Identities, FindingCount: validation.Findings, MisconfigurationCount: validation.Misconfigurations, DocumentBytes: validation.DocumentBytes} + if err = s.Store.ReplaceGraphWithResult(ctx, graph, source, result); err != nil { + return err + } + return s.recordNewCriticalPaths(ctx, previous, graph) +} + +func (s Service) validationFailure(ctx context.Context, source string, cause error) error { + if err := s.Store.RecordImportFailure(ctx, source, cause.Error()); err != nil { + return fmt.Errorf("%w; record validation result: %v", cause, err) + } + rules, err := s.Store.NotificationRules(ctx) + if err != nil { + return fmt.Errorf("%w; read notification rules: %v", cause, err) + } + rule, configured := rules["validation_failed"] + if configured && rule.Enabled && 3 >= rule.MinimumSeverity { + _, err = s.Store.AddNotification(ctx, notifications.Event{Type: "validation_failed", Severity: 3, Title: "Import failed validation", Detail: "The selected inventory could not be read or validated.", Related: "imports"}, 15*time.Minute) + if err != nil { + return fmt.Errorf("%w; save validation notification: %v", cause, err) + } + } + return cause +} + +func (s Service) recordNewCriticalPaths(ctx context.Context, previous, current domain.Graph) error { + before, err := previous.AllPaths(16, 1000) + if err != nil { + return err + } + known := make(map[string]bool, len(before)) + for _, path := range before { + if isCriticalPath(path) { + known[pathSignature(path)] = true + } + } + paths, err := current.AllPaths(16, 1000) + if err != nil { + return err + } + rules, err := s.Store.NotificationRules(ctx) + if err != nil { + return err + } + rule := rules["critical_path"] + if !rule.Enabled { + return nil + } + for _, path := range paths { + if !isCriticalPath(path) { + continue + } + signature := pathSignature(path) + if known[signature] { + continue + } + _, err = s.Store.AddNotification(ctx, notifications.Event{Type: "critical_path", Severity: 5, Title: "New critical potential path", Detail: "An import added a new high-impact relationship path.", Related: "paths", Key: signature}, 15*time.Minute) + if err != nil { + return fmt.Errorf("record new critical path: %w", err) + } + known[signature] = true + } + return nil +} + +func isCriticalPath(path domain.Path) bool { + return path.Impact >= 5 && path.Confidence >= 60 && path.Score >= 300 +} + +func pathSignature(path domain.Path) string { + parts := make([]string, 0, len(path.Nodes)+len(path.Edges)) + for _, node := range path.Nodes { + parts = append(parts, "node:"+node.ID) + } + for _, edge := range path.Edges { + parts = append(parts, "edge:"+edge.ID) + } + sum := sha256.Sum256([]byte(strings.Join(parts, "\x00"))) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/service/service_test.go b/internal/service/service_test.go new file mode 100644 index 0000000..52a8ac4 --- /dev/null +++ b/internal/service/service_test.go @@ -0,0 +1,118 @@ +package service + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/NexzaDev/attackpath-visualizer/internal/ingestion" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" +) + +func TestImportRejectsInvalidInputWithoutReplacingState(t *testing.T) { + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + app := Service{Store: store} + valid := `{"assets":[{"id":"a","name":"A","kind":"service","impact":1}],"edges":[]}` + if err = app.Import(context.Background(), strings.NewReader(valid), "fixture"); err != nil { + t.Fatal(err) + } + if err = app.Import(context.Background(), strings.NewReader(`{"assets":[`), "bad"); err == nil { + t.Fatal("expected malformed JSON error") + } + graph, err := store.Graph(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(graph.Assets) != 1 || graph.Assets[0].ID != "a" { + t.Fatalf("existing graph was changed: %#v", graph) + } + history, err := store.ImportHistory(context.Background()) + if err != nil || len(history) != 2 || history[0]["source"] != "bad" || history[0]["status"] != "failed" || !strings.Contains(fmt.Sprint(history[0]["message"]), "inventory JSON schema") { + t.Fatalf("validation history=%v err=%v", history, err) + } +} + +func TestImportNotificationsAreMinimalAndDeduplicated(t *testing.T) { + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + app := Service{Store: store} + invalid := `{"assets":[` + if err = app.Import(context.Background(), strings.NewReader(invalid), "bad input"); err == nil { + t.Fatal("expected invalid JSON") + } + if err = app.Import(context.Background(), strings.NewReader(invalid), "bad input"); err == nil { + t.Fatal("expected invalid JSON") + } + items, err := store.Notifications(context.Background(), 20) + if err != nil { + t.Fatal(err) + } + if len(items) != 1 || items[0].Title != "Import failed validation" || strings.Contains(items[0].Detail, invalid) { + t.Fatalf("unexpected validation notification: %#v", items) + } +} + +func TestImportRecordsNewHighImpactPaths(t *testing.T) { + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + app := Service{Store: store} + graph := `{"assets":[{"id":"entry","name":"Entry","kind":"service","impact":1},{"id":"data","name":"Sensitive dataset","kind":"database","impact":5}],"edges":[{"id":"relationship","from":"entry","to":"data","relation":"has access","confidence":95,"evidence":{"source":"fixture://test","finding":"Access path exists","observed":"synthetic"}}]}` + if err = app.Import(context.Background(), strings.NewReader(graph), "synthetic test"); err != nil { + t.Fatal(err) + } + items, err := store.Notifications(context.Background(), 20) + if err != nil { + t.Fatal(err) + } + if len(items) != 1 || items[0].Title != "New critical potential path" { + t.Fatalf("unexpected critical path notification: %#v", items) + } +} + +func TestImportNotifiesWhenExistingPathBecomesCritical(t *testing.T) { + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + app := Service{Store: store} + lowRisk := `{"assets":[{"id":"entry","name":"Entry","kind":"service","impact":1},{"id":"data","name":"Sensitive dataset","kind":"database","impact":5}],"edges":[{"id":"relationship","from":"entry","to":"data","relation":"has access","confidence":50,"evidence":{"source":"fixture://test","finding":"Access path exists","observed":"synthetic"}}]}` + if err = app.Import(context.Background(), strings.NewReader(lowRisk), "low risk"); err != nil { + t.Fatal(err) + } + highRisk := strings.Replace(lowRisk, `"confidence":50`, `"confidence":95`, 1) + if err = app.Import(context.Background(), strings.NewReader(highRisk), "increased confidence"); err != nil { + t.Fatal(err) + } + items, err := store.Notifications(context.Background(), 20) + if err != nil || len(items) != 1 { + t.Fatalf("items=%v err=%v", items, err) + } +} + +func TestImportRejectsOversizedDocument(t *testing.T) { + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + app := Service{Store: store} + if err := app.Import(context.Background(), strings.NewReader(strings.Repeat("x", ingestion.MaxDocumentBytes+1)), "large"); err == nil || !strings.Contains(err.Error(), "byte limit") { + t.Fatalf("expected size error, got %v", err) + } + history, err := store.ImportHistory(context.Background()) + if err != nil || len(history) != 1 || history[0]["source"] != "large" || history[0]["status"] != "failed" || !strings.Contains(fmt.Sprint(history[0]["message"]), "byte limit") { + t.Fatalf("oversized validation history=%v err=%v", history, err) + } +} diff --git a/internal/service/workflow_test.go b/internal/service/workflow_test.go new file mode 100644 index 0000000..ee688e9 --- /dev/null +++ b/internal/service/workflow_test.go @@ -0,0 +1,79 @@ +package service + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "github.com/NexzaDev/attackpath-visualizer/internal/reports" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" +) + +func TestImportRankRemediationAndReportsEndToEnd(t *testing.T) { + store, err := repository.Open(":memory:") + if err != nil { + t.Fatal(err) + } + defer store.Close() + app := Service{Store: store} + inventory := `{"schema_version":1,"assets":[{"id":"entry","name":"Synthetic entry","kind":"service","impact":1},{"id":"broker","name":"Synthetic broker","kind":"service","impact":2},{"id":"customer-data","name":"Synthetic data","kind":"database","impact":5},{"id":"backup","name":"Synthetic backup","kind":"storage","impact":4}],"edges":[{"id":"entry-broker","from":"entry","to":"broker","relation":"connects","confidence":100,"evidence":{"source":"fixture://topology","finding":"Entry reaches broker","observed":"synthetic"}},{"id":"broker-data","from":"broker","to":"customer-data","relation":"reads","confidence":95,"evidence":{"source":"fixture://permissions","finding":"Broker can read data","observed":"synthetic"}},{"id":"broker-backup","from":"broker","to":"backup","relation":"writes","confidence":80,"evidence":{"source":"fixture://permissions","finding":"Broker can write backups","observed":"synthetic"}},{"id":"entry-direct","from":"entry","to":"customer-data","relation":"legacy reads","confidence":50,"evidence":{"source":"fixture://review","finding":"Low confidence direct relationship","observed":"synthetic"}}]}` + if err = app.Import(context.Background(), strings.NewReader(inventory), "authorized synthetic E2E"); err != nil { + t.Fatal(err) + } + analysis, err := app.Analyze(context.Background(), 16, 1000) + if err != nil { + t.Fatal(err) + } + if len(analysis.Paths.Paths) != 4 || analysis.Paths.Truncated { + t.Fatalf("unexpected ranked path result: %#v", analysis.Paths) + } + if analysis.Paths.Paths[0].Score != 475 || analysis.Paths.Paths[0].Components.EdgeConfidences[0] != 100 || analysis.Paths.Paths[0].Components.EdgeConfidences[1] != 95 { + t.Fatalf("path ranking or exact scoring components incorrect: %#v", analysis.Paths.Paths[0]) + } + summary, err := app.Overview(context.Background()) + if err != nil { + t.Fatal(err) + } + impactCount := 0 + confidenceCount := 0 + for _, count := range summary.PathsByImpact { + impactCount += count + } + for _, band := range summary.Confidence { + confidenceCount += band.Count + } + if impactCount != 4 || confidenceCount != 4 { + t.Fatalf("overview distributions omit enumerated paths: impacts=%v confidence=%v", summary.PathsByImpact, summary.Confidence) + } + if len(analysis.Remediation.Suggestions) != 4 || analysis.Remediation.Suggestions[0].EdgeID != "entry-broker" || analysis.Remediation.Suggestions[0].PathsAffected != 3 { + t.Fatalf("choke point remediation ranking incorrect: %#v", analysis.Remediation) + } + jsonReport, err := app.RenderReport(context.Background(), "json") + if err != nil { + t.Fatal(err) + } + var bundle reports.Bundle + if err = json.Unmarshal(jsonReport, &bundle); err != nil { + t.Fatal(err) + } + if bundle.PathCount != 4 || bundle.Remediation.Suggestions[0].EdgeID != "entry-broker" || bundle.Paths[0].Components.Score != 475 { + t.Fatalf("JSON report omitted the computed results: %#v", bundle) + } + markdownReport, err := app.RenderReport(context.Background(), "markdown") + if err != nil { + t.Fatal(err) + } + for _, part := range []string{"Synthetic entry", "customer-data", "fixture://permissions", "entry-broker", "2", "475"} { + if !strings.Contains(string(markdownReport), part) { + t.Fatalf("Markdown report does not include %q:\n%s", part, markdownReport) + } + } + if _, err = app.RenderReport(context.Background(), "html"); err == nil { + t.Fatal("unsupported report format was accepted") + } + history, err := store.ImportHistory(context.Background()) + if err != nil || len(history) != 1 || history[0]["source"] != "authorized synthetic E2E" || history[0]["status"] != "success" || history[0]["schema_version"] != 1 || history[0]["document_bytes"] != len(inventory) { + t.Fatalf("import validation history=%v err=%v", history, err) + } +} diff --git a/licenses/Fyne-BSD-3-Clause.txt b/licenses/Fyne-BSD-3-Clause.txt new file mode 100644 index 0000000..5f07129 --- /dev/null +++ b/licenses/Fyne-BSD-3-Clause.txt @@ -0,0 +1,27 @@ +BSD 3-Clause License + +Copyright (C) 2018 Fyne.io developers (see AUTHORS) +All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Fyne.io nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/licenses/NotoSans-OFL-1.1.txt b/licenses/NotoSans-OFL-1.1.txt new file mode 100644 index 0000000..26004ca --- /dev/null +++ b/licenses/NotoSans-OFL-1.1.txt @@ -0,0 +1,38 @@ +—————————————————————————————- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +—————————————————————————————- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. + +DEFINITIONS +“Font Software” refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. + +“Reserved Font Name” refers to any names specified as such after the copyright statement(s). + +“Original Version” refers to the collection of Font Software components as distributed by the Copyright Holder(s). + +“Modified Version” refers to any derivative made by adding to, deleting, or substituting—in part or in whole—any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +“Author” refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. + +5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/licenses/beeep-MIT.txt b/licenses/beeep-MIT.txt new file mode 100644 index 0000000..9d4a922 --- /dev/null +++ b/licenses/beeep-MIT.txt @@ -0,0 +1,23 @@ +Copyright (c) 2017, Milan Nikolic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/licenses/modernc-sqlite-BSD-3-Clause.txt b/licenses/modernc-sqlite-BSD-3-Clause.txt new file mode 100644 index 0000000..867b0f3 --- /dev/null +++ b/licenses/modernc-sqlite-BSD-3-Clause.txt @@ -0,0 +1,26 @@ +Copyright (c) 2017 The Sqlite Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 0000000..ac53dbe --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,5 @@ +CREATE TABLE IF NOT EXISTS assets (id TEXT PRIMARY KEY, name TEXT NOT NULL, kind TEXT NOT NULL, impact INTEGER NOT NULL CHECK(impact BETWEEN 1 AND 5), description TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS edges (id TEXT PRIMARY KEY, source_id TEXT NOT NULL REFERENCES assets(id), target_id TEXT NOT NULL REFERENCES assets(id), relation TEXT NOT NULL, confidence INTEGER NOT NULL CHECK(confidence BETWEEN 0 AND 100), evidence_json TEXT NOT NULL); +CREATE INDEX IF NOT EXISTS edges_source_idx ON edges(source_id); +CREATE INDEX IF NOT EXISTS edges_target_idx ON edges(target_id); +CREATE TABLE IF NOT EXISTS imports (id INTEGER PRIMARY KEY, source TEXT NOT NULL, asset_count INTEGER NOT NULL, edge_count INTEGER NOT NULL, imported_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP); diff --git a/migrations/002_notifications_and_import_results.sql b/migrations/002_notifications_and_import_results.sql new file mode 100644 index 0000000..508d9c7 --- /dev/null +++ b/migrations/002_notifications_and_import_results.sql @@ -0,0 +1,3 @@ +CREATE TABLE IF NOT EXISTS notifications (id INTEGER PRIMARY KEY, event_type TEXT NOT NULL, severity INTEGER NOT NULL, title TEXT NOT NULL, detail TEXT NOT NULL, related_id TEXT NOT NULL, dedup_key TEXT NOT NULL, created_at TEXT NOT NULL, read_at TEXT NOT NULL DEFAULT '', delivered_at TEXT NOT NULL DEFAULT ''); +CREATE INDEX IF NOT EXISTS notifications_pending_idx ON notifications(delivered_at,read_at); +CREATE TABLE IF NOT EXISTS notification_rules (event_type TEXT PRIMARY KEY, enabled INTEGER NOT NULL, minimum_severity INTEGER NOT NULL, quiet_start TEXT NOT NULL, quiet_end TEXT NOT NULL, detailed_text INTEGER NOT NULL); diff --git a/migrations/003_graph_entities.sql b/migrations/003_graph_entities.sql new file mode 100644 index 0000000..2a31f50 --- /dev/null +++ b/migrations/003_graph_entities.sql @@ -0,0 +1,11 @@ +CREATE TABLE IF NOT EXISTS identities (id TEXT PRIMARY KEY, name TEXT NOT NULL, kind TEXT NOT NULL, impact INTEGER NOT NULL CHECK(impact BETWEEN 1 AND 5), description TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS graph_nodes (id TEXT PRIMARY KEY, entity_type TEXT NOT NULL CHECK(entity_type IN ('asset','identity')), name TEXT NOT NULL, kind TEXT NOT NULL, impact INTEGER NOT NULL CHECK(impact BETWEEN 1 AND 5), description TEXT NOT NULL); +INSERT OR IGNORE INTO graph_nodes(id,entity_type,name,kind,impact,description) SELECT id,'asset',name,kind,impact,description FROM assets; +ALTER TABLE edges RENAME TO edges_legacy; +CREATE TABLE edges (id TEXT PRIMARY KEY, source_id TEXT NOT NULL REFERENCES graph_nodes(id), target_id TEXT NOT NULL REFERENCES graph_nodes(id), relation TEXT NOT NULL, confidence INTEGER NOT NULL CHECK(confidence BETWEEN 0 AND 100), evidence_json TEXT NOT NULL); +INSERT INTO edges(id,source_id,target_id,relation,confidence,evidence_json) SELECT id,source_id,target_id,relation,confidence,CASE WHEN json_valid(evidence_json)=0 THEN '{"source":"legacy://no-recorded-evidence","finding":"Earlier database version did not capture edge evidence","observed":"migration-003"}' WHEN COALESCE(json_extract(evidence_json,'$.source'),'')='' OR COALESCE(json_extract(evidence_json,'$.finding'),'')='' OR COALESCE(json_extract(evidence_json,'$.observed'),'')='' THEN '{"source":"legacy://no-recorded-evidence","finding":"Earlier database version did not capture edge evidence","observed":"migration-003"}' ELSE evidence_json END FROM edges_legacy; +DROP TABLE edges_legacy; +CREATE INDEX edges_source_idx ON edges(source_id); +CREATE INDEX edges_target_idx ON edges(target_id); +CREATE TABLE misconfigurations (id TEXT PRIMARY KEY, asset_id TEXT NOT NULL REFERENCES assets(id), identity_id TEXT REFERENCES identities(id), title TEXT NOT NULL, severity INTEGER NOT NULL CHECK(severity BETWEEN 1 AND 5), description TEXT NOT NULL); +CREATE TABLE findings (id TEXT PRIMARY KEY, asset_id TEXT NOT NULL REFERENCES assets(id), identity_id TEXT REFERENCES identities(id), misconfiguration_id TEXT REFERENCES misconfigurations(id), title TEXT NOT NULL, severity INTEGER NOT NULL CHECK(severity BETWEEN 1 AND 5), source TEXT NOT NULL, observed TEXT NOT NULL); diff --git a/migrations/004_import_validation_details.sql b/migrations/004_import_validation_details.sql new file mode 100644 index 0000000..bf33c73 --- /dev/null +++ b/migrations/004_import_validation_details.sql @@ -0,0 +1,5 @@ +ALTER TABLE imports ADD COLUMN schema_version INTEGER NOT NULL DEFAULT 0; +ALTER TABLE imports ADD COLUMN identity_count INTEGER NOT NULL DEFAULT 0; +ALTER TABLE imports ADD COLUMN finding_count INTEGER NOT NULL DEFAULT 0; +ALTER TABLE imports ADD COLUMN misconfiguration_count INTEGER NOT NULL DEFAULT 0; +ALTER TABLE imports ADD COLUMN document_bytes INTEGER NOT NULL DEFAULT 0; diff --git a/migrations/embed.go b/migrations/embed.go new file mode 100644 index 0000000..381665a --- /dev/null +++ b/migrations/embed.go @@ -0,0 +1,6 @@ +package migrations + +import "embed" + +//go:embed *.sql +var Files embed.FS diff --git a/testdata/demo.json b/testdata/demo.json new file mode 100644 index 0000000..e6304bf --- /dev/null +++ b/testdata/demo.json @@ -0,0 +1,50 @@ +{ + "schema_version": 1, + "assets": [ + {"id":"internet-edge","name":"Synthetic public edge","kind":"network-boundary","impact":2,"description":"Fictional ingress boundary used only by the offline demo"}, + {"id":"api-gateway","name":"Customer API gateway","kind":"service","impact":3,"description":"Synthetic internet-facing application entry point"}, + {"id":"workload-cluster","name":"Application workload cluster","kind":"compute","impact":3,"description":"Fictional service runtime with a deployment identity"}, + {"id":"build-runner","name":"Release build runner","kind":"compute","impact":3,"description":"Synthetic build worker that publishes application artifacts"}, + {"id":"artifact-store","name":"Release artifact store","kind":"storage","impact":4,"description":"Fictional package repository containing deployment artifacts"}, + {"id":"secret-store","name":"Application secret store","kind":"vault","impact":4,"description":"Synthetic secret service with a stale credential finding"}, + {"id":"customer-db","name":"Customer records database","kind":"database","impact":5,"description":"Fictional high-impact data store; no real customer data is present"}, + {"id":"backup-bucket","name":"Encrypted backup bucket","kind":"storage","impact":5,"description":"Synthetic backup destination with an advisory access finding"}, + {"id":"monitoring","name":"Operations monitoring service","kind":"service","impact":2,"description":"Fictional monitoring reader used as a low-impact comparison path"} + ], + "identities": [ + {"id":"deploy-bot","name":"Deployment automation identity","kind":"workload","impact":4,"description":"Synthetic principal with release and configuration permissions"}, + {"id":"analytics-reader","name":"Analytics reader identity","kind":"service-account","impact":4,"description":"Fictional application identity with read access to sensitive data"}, + {"id":"backup-service","name":"Backup service identity","kind":"service-account","impact":3,"description":"Synthetic principal that writes encrypted backups"}, + {"id":"external-partner","name":"External partner identity","kind":"federated","impact":2,"description":"Fictional federated principal used to illustrate a lower-confidence relationship"} + ], + "misconfigurations": [ + {"id":"misconfig-public-api","asset_id":"api-gateway","title":"Public ingress requires review","severity":3,"description":"Synthetic demo advisory; validate intended exposure and authentication policy."}, + {"id":"misconfig-deploy-scope","asset_id":"build-runner","identity_id":"deploy-bot","title":"Deployment permissions are broader than the demo baseline","severity":4,"description":"Synthetic demo advisory; review the minimum publish and deploy permissions."}, + {"id":"misconfig-backup-policy","asset_id":"backup-bucket","identity_id":"backup-service","title":"Backup access policy needs periodic review","severity":4,"description":"Synthetic demo advisory; verify encryption and principal scoping."}, + {"id":"misconfig-stale-secret","asset_id":"secret-store","identity_id":"deploy-bot","title":"Stale credential reference","severity":3,"description":"Synthetic demo advisory; rotate or remove unused credential references."} + ], + "findings": [ + {"id":"finding-ingress","asset_id":"api-gateway","title":"Public route observed in fixture","severity":3,"source":"demo://network-inventory","observed":"2026-10-15T09:00:00Z"}, + {"id":"finding-publish","asset_id":"artifact-store","identity_id":"deploy-bot","misconfiguration_id":"misconfig-deploy-scope","title":"Publish permission present","severity":4,"source":"demo://permission-review","observed":"2026-10-15T09:05:00Z"}, + {"id":"finding-secret","asset_id":"secret-store","identity_id":"deploy-bot","misconfiguration_id":"misconfig-stale-secret","title":"Stale credential reference detected","severity":3,"source":"demo://configuration-audit","observed":"2026-10-15T09:10:00Z"}, + {"id":"finding-data-read","asset_id":"customer-db","identity_id":"analytics-reader","title":"Read permission present in synthetic policy","severity":5,"source":"demo://data-access-review","observed":"2026-10-15T09:15:00Z"}, + {"id":"finding-backup","asset_id":"backup-bucket","identity_id":"backup-service","misconfiguration_id":"misconfig-backup-policy","title":"Backup write permission present","severity":4,"source":"demo://storage-review","observed":"2026-10-15T09:20:00Z"} + ], + "edges": [ + {"id":"edge-internet-api","from":"internet-edge","to":"api-gateway","relation":"routes requests to","confidence":98,"evidence":{"source":"demo://network-inventory","finding":"Fictional ingress route connects to the API gateway","observed":"2026-10-15T09:00:00Z"}}, + {"id":"edge-api-workload","from":"api-gateway","to":"workload-cluster","relation":"forwards authenticated workload traffic to","confidence":91,"evidence":{"source":"demo://service-map","finding":"Synthetic service map records the gateway-to-workload dependency","observed":"2026-10-15T09:02:00Z"}}, + {"id":"edge-workload-deploy","from":"workload-cluster","to":"deploy-bot","relation":"uses workload identity","confidence":88,"evidence":{"source":"demo://identity-inventory","finding":"Fictional runtime is associated with deployment identity","observed":"2026-10-15T09:04:00Z"}}, + {"id":"edge-deploy-runner","from":"deploy-bot","to":"build-runner","relation":"can start release jobs on","confidence":93,"evidence":{"source":"demo://permission-review","finding":"Synthetic policy grants release-job access","observed":"2026-10-15T09:05:00Z"}}, + {"id":"edge-runner-artifact","from":"build-runner","to":"artifact-store","relation":"publishes packages to","confidence":94,"evidence":{"source":"demo://build-inventory","finding":"Fictional build runner publishes to the artifact store","observed":"2026-10-15T09:07:00Z"}}, + {"id":"edge-deploy-secrets","from":"deploy-bot","to":"secret-store","relation":"can read configuration from","confidence":78,"evidence":{"source":"demo://permission-review","finding":"Synthetic policy permits reading application configuration","observed":"2026-10-15T09:10:00Z"}}, + {"id":"edge-secret-analytics","from":"secret-store","to":"analytics-reader","relation":"contains credential for","confidence":71,"evidence":{"source":"demo://configuration-audit","finding":"Fictional secret reference maps to analytics identity","observed":"2026-10-15T09:12:00Z"}}, + {"id":"edge-analytics-db","from":"analytics-reader","to":"customer-db","relation":"can read records from","confidence":96,"evidence":{"source":"demo://data-access-review","finding":"Synthetic access policy grants database read access","observed":"2026-10-15T09:15:00Z"}}, + {"id":"edge-db-backup","from":"customer-db","to":"backup-bucket","relation":"exports scheduled backup to","confidence":83,"evidence":{"source":"demo://data-flow","finding":"Fictional scheduled backup workflow connects the data store to backup storage","observed":"2026-10-15T09:17:00Z"}}, + {"id":"edge-workload-backup","from":"workload-cluster","to":"backup-service","relation":"invokes backup job as","confidence":85,"evidence":{"source":"demo://service-map","finding":"Synthetic workload invokes the backup service","observed":"2026-10-15T09:18:00Z"}}, + {"id":"edge-backup-write","from":"backup-service","to":"backup-bucket","relation":"writes encrypted snapshots to","confidence":92,"evidence":{"source":"demo://storage-review","finding":"Fictional backup identity can write encrypted snapshots","observed":"2026-10-15T09:20:00Z"}}, + {"id":"edge-deploy-backup","from":"deploy-bot","to":"backup-service","relation":"can assume backup identity","confidence":64,"evidence":{"source":"demo://identity-inventory","finding":"Synthetic trust policy permits a deployment-to-backup identity transition","observed":"2026-10-15T09:22:00Z"}}, + {"id":"edge-monitor-db","from":"monitoring","to":"customer-db","relation":"reads health metadata from","confidence":55,"evidence":{"source":"demo://monitoring-map","finding":"Low-confidence fixture relationship is limited to health metadata","observed":"2026-10-15T09:24:00Z"}}, + {"id":"edge-partner-api","from":"external-partner","to":"api-gateway","relation":"federates to","confidence":67,"evidence":{"source":"demo://federation-inventory","finding":"Fictional partner trust is represented for analysis only","observed":"2026-10-15T09:26:00Z"}}, + {"id":"edge-partner-db","from":"external-partner","to":"customer-db","relation":"has legacy read grant","confidence":28,"evidence":{"source":"demo://access-review","finding":"Low-confidence stale grant included to demonstrate evidence-sensitive ranking","observed":"2026-10-15T09:28:00Z"}} + ] +} diff --git a/tui/tui.go b/tui/tui.go new file mode 100644 index 0000000..4c43479 --- /dev/null +++ b/tui/tui.go @@ -0,0 +1,363 @@ +package tui + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "io" + "os" + "runtime" + "strings" + "time" + + "github.com/NexzaDev/attackpath-visualizer/internal/config" + "github.com/NexzaDev/attackpath-visualizer/internal/domain" + "github.com/NexzaDev/attackpath-visualizer/internal/launcher" + "github.com/NexzaDev/attackpath-visualizer/internal/meta" + "github.com/NexzaDev/attackpath-visualizer/internal/notifier" + "github.com/NexzaDev/attackpath-visualizer/internal/repository" + "github.com/NexzaDev/attackpath-visualizer/internal/service" +) + +func Run(requestedDB string) error { + path, err := config.DatabasePath(requestedDB) + if err != nil { + return err + } + store, err := repository.Open(path) + if err != nil { + return err + } + defer store.Close() + ctx := context.Background() + app := service.Service{Store: store} + graph, err := store.Graph(ctx) + if err != nil { + return err + } + if len(graph.Assets)+len(graph.Identities) == 0 { + history, historyErr := store.ImportHistory(ctx) + if historyErr != nil { + return historyErr + } + if len(history) == 0 { + if err = app.LoadDemo(ctx); err != nil { + return err + } + } + } + reader := bufio.NewReader(os.Stdin) + for { + graph, err = store.Graph(ctx) + if err != nil { + return err + } + fmt.Printf("\n%s %s\n1 Overview 2 Graph 3 Paths 4 Assets 5 Evidence 6 Remediation 7 Imports 8 Reports 9 Notifications 10 Settings 11 About 12 Diagnostics 13 Switch to Dashboard 0 Quit\nSelect: ", meta.Name, meta.Version) + choice, readErr := reader.ReadString('\n') + if readErr != nil { + if strings.TrimSpace(choice) == "" { + return nil + } + } + switch strings.TrimSpace(choice) { + case "1": + if err := printOverview(graph); err != nil { + return err + } + case "2": + printGraph(graph) + case "3": + if err := printPaths(graph); err != nil { + return err + } + case "4": + if err := printAssets(graph); err != nil { + return err + } + case "5": + printEvidence(graph) + case "6": + if err := printRemediation(app); err != nil { + return err + } + case "7": + if err := importGraph(reader, app, graph); err != nil { + return err + } + printImports(store) + case "8": + if err := exportReports(reader, app, graph); err != nil { + return err + } + case "9": + printNotifications(store, reader) + case "10": + fmt.Printf("Database: %s\nNotifier status: ", path) + notifierPath, installed, statusErr := notifier.Status() + if statusErr != nil { + fmt.Println(statusErr) + } else { + fmt.Printf("%s (%s)\n", notifierPath, map[bool]string{true: "installed", false: "off"}[installed]) + } + fmt.Print("Type e to enable notifier, d to disable it, r to reset launch mode, or Enter: ") + setting, _ := reader.ReadString('\n') + switch strings.ToLower(strings.TrimSpace(setting)) { + case "e": + executable, err := os.Executable() + if err != nil { + return err + } + path, err := notifier.Install(executable, path) + if err != nil { + return err + } + fmt.Println("Notifier installed at", path) + case "d": + path, err := notifier.Uninstall() + if err != nil { + return err + } + fmt.Println("Notifier removed from", path) + case "r": + if err := launcher.SavePreference(""); err != nil { + return err + } + fmt.Println("Saved launcher mode cleared.") + } + case "11": + fmt.Printf("%s\n%s\nVersion: %s\nLicense: MIT\nSource: %s\nSecurity vulnerability reports: GitHub private advisory form (preferred): %s\nBackup channel: email. If you cannot use the GitHub form, send the report to SuperMcDuck@proton.me.\n", meta.Name, meta.Purpose, meta.Version, meta.Repository, meta.SecurityAdvisory) + case "12": + fmt.Printf("OS/architecture: %s/%s\nRuntime: %s\nConfiguration: local-only; no credentials configured\n", runtime.GOOS, runtime.GOARCH, runtime.Version()) + case "13": + return launcher.StartGUI() + case "0": + return nil + default: + fmt.Println("Choose a number from 0 to 13.") + } + + } +} +func printGraph(graph domain.Graph) { + for _, node := range graph.Nodes() { + fmt.Printf("[%d/5] %s (%s · %s)\n", node.Impact, node.Name, node.EntityType, node.ID) + for _, edge := range graph.Edges { + if edge.From == node.ID { + fmt.Printf(" ── %s → %s\n", edge.Relation, edge.To) + } + } + } +} + +func printRemediation(app service.Service) error { + analysis, err := app.Analyze(context.Background(), 16, 1000) + if err != nil { + return err + } + for index, item := range analysis.Remediation.Suggestions { + fmt.Printf("%d. %d paths · %d critical · %d risk points · review %s: %s — %s → %s\n %s\n", index+1, item.PathsAffected, item.CriticalPaths, item.WeightedRiskPoints, item.EdgeID, item.Relation, item.From, item.To, item.Recommendation) + } + if len(analysis.Remediation.Suggestions) == 0 { + fmt.Println("No path-affecting edges are currently available.") + } + if analysis.Paths.Truncated { + fmt.Println("Note: rankings cover the bounded path set; path enumeration was truncated.") + } + return nil +} + +func importGraph(reader *bufio.Reader, app service.Service, graph domain.Graph) error { + fmt.Print("Import JSON file path (empty to cancel): ") + path, err := reader.ReadString('\n') + if err != nil && err != io.EOF { + return fmt.Errorf("read import path: %w", err) + } + path = strings.TrimSpace(path) + if path == "" { + fmt.Println("Import cancelled.") + return nil + } + if len(graph.Assets)+len(graph.Identities) > 0 { + fmt.Print("This replaces the current local graph. Continue? [y/N]: ") + answer, readErr := reader.ReadString('\n') + if readErr != nil && readErr != io.EOF { + return fmt.Errorf("read import confirmation: %w", readErr) + } + if !strings.EqualFold(strings.TrimSpace(answer), "y") && !strings.EqualFold(strings.TrimSpace(answer), "yes") { + fmt.Println("Import cancelled.") + return nil + } + } + file, err := os.Open(path) + if err != nil { + return fmt.Errorf("open import file: %w", err) + } + defer file.Close() + if err = app.Import(context.Background(), file, "user JSON import"); err != nil { + return err + } + fmt.Println("Import validated and saved.") + return nil +} + +func printImports(store *repository.Store) { + items, err := store.ImportHistory(context.Background()) + if err != nil { + fmt.Println("Could not read import history:", err) + return + } + for _, item := range items { + fmt.Printf("%v · %v · assets %v · identities %v · misconfigurations %v · findings %v · edges %v · %v\n", item["imported_at"], item["status"], item["assets"], item["identities"], item["misconfigurations"], item["findings"], item["edges"], item["message"]) + } + if len(items) == 0 { + fmt.Println("No imports are recorded.") + } +} + +func exportReports(reader *bufio.Reader, app service.Service, graph domain.Graph) error { + fmt.Print("Export [g]raph JSON, analysis [j]SON, or [m]arkdown (Enter cancels): ") + choice, err := reader.ReadString('\n') + if err != nil && err != io.EOF { + return fmt.Errorf("read report choice: %w", err) + } + choice = strings.ToLower(strings.TrimSpace(choice)) + if choice == "" { + fmt.Println("Export cancelled.") + return nil + } + var data []byte + filename := "" + switch choice { + case "g": + data, err = json.MarshalIndent(graph, "", " ") + filename = "attackpath-graph.json" + case "j": + data, err = app.RenderReport(context.Background(), "json") + filename = "attackpath-analysis.json" + case "m": + data, err = app.RenderReport(context.Background(), "markdown") + filename = "attackpath-report.md" + default: + return fmt.Errorf("choose g, j, or m") + } + if err != nil { + return fmt.Errorf("render report: %w", err) + } + fmt.Printf("Export file [%s]: ", filename) + file, readErr := reader.ReadString('\n') + if readErr != nil && readErr != io.EOF { + return fmt.Errorf("read report filename: %w", readErr) + } + file = strings.TrimSpace(file) + if file == "" { + file = filename + } + if _, err := os.Stat(file); err == nil { + fmt.Printf("%s exists. Replace it? [y/N]: ", file) + answer, readErr := reader.ReadString('\n') + if readErr != nil && readErr != io.EOF { + return fmt.Errorf("read overwrite confirmation: %w", readErr) + } + if !strings.EqualFold(strings.TrimSpace(answer), "y") && !strings.EqualFold(strings.TrimSpace(answer), "yes") { + fmt.Println("Export cancelled.") + return nil + } + } + if err := os.WriteFile(file, data, 0600); err != nil { + return fmt.Errorf("export report: %w", err) + } + fmt.Println("Exported to", file) + return nil +} + +func printOverview(graph domain.Graph) error { + result, err := graph.EnumeratePaths(16, 1000) + if err != nil { + return err + } + fmt.Printf("Assets: %d · Identities: %d · Relationships: %d · Potential paths: %d · expansions: %d · truncated: %t\n", len(graph.Assets), len(graph.Identities), len(graph.Edges), len(result.Paths), result.Expanded, result.Truncated) + for index, path := range result.Paths { + if index >= 5 { + break + } + fmt.Printf("%d. %s · score %d · confidence %d%% · %s\n", index+1, pathLabel(path), path.Score, path.Confidence, path.Explanation) + } + return nil +} + +func printPaths(graph domain.Graph) error { + result, err := graph.EnumeratePaths(16, 1000) + if err != nil { + return err + } + for index, path := range result.Paths { + fmt.Printf("%d. %s\n %s\n Components: impact tier %d/5 × edge confidences %v = compounded %d%%; score %d\n", index+1, pathLabel(path), path.Explanation, path.Components.ImpactTier, path.Components.EdgeConfidences, path.Components.CompoundedConfidence, path.Components.Score) + for _, edge := range path.Edges { + fmt.Printf(" %s · %s · %d%% · source %s · finding %s · observed %s\n", edge.ID, edge.Relation, edge.Confidence, edge.Evidence.Source, edge.Evidence.Finding, edge.Evidence.Observed) + } + } + if result.Truncated { + fmt.Printf("Path listing truncated after %d expansions; rankings cover this bounded result.\n", result.Expanded) + } + return nil +} + +func printAssets(graph domain.Graph) error { + for _, node := range graph.Nodes() { + fmt.Printf("%s · %s/%s · impact %d/5 · %s\n", node.Name, node.EntityType, node.Kind, node.Impact, node.Description) + for _, item := range graph.Misconfigurations { + if item.AssetID == node.ID || item.IdentityID == node.ID { + fmt.Printf(" Misconfiguration S%d · %s\n", item.Severity, item.Title) + } + } + for _, item := range graph.Findings { + if item.AssetID == node.ID || item.IdentityID == node.ID { + fmt.Printf(" Finding S%d · %s · %s\n", item.Severity, item.Title, item.Source) + } + } + } + return nil +} + +func printEvidence(graph domain.Graph) { + for _, edge := range graph.Edges { + fmt.Printf("%s: %s → %s · %s · %d%%\n %s: %s · %s\n", edge.ID, edge.From, edge.To, edge.Relation, edge.Confidence, edge.Evidence.Source, edge.Evidence.Finding, edge.Evidence.Observed) + } +} + +func printNotifications(store *repository.Store, reader *bufio.Reader) { + items, err := store.Notifications(context.Background(), 50) + if err != nil { + fmt.Println("Could not read notifications:", err) + return + } + if len(items) == 0 { + fmt.Println("No notifications recorded.") + return + } + for _, item := range items { + state := "unread" + if item.Read { + state = "read" + } + fmt.Printf("S%d · %s · %s · %s\n", item.Severity, item.Title, state, item.CreatedAt.Local().Format(time.RFC822)) + } + fmt.Print("Type a to mark all read, or press Enter: ") + answer, _ := reader.ReadString('\n') + if strings.EqualFold(strings.TrimSpace(answer), "a") { + if err := store.MarkAllNotificationsRead(context.Background()); err != nil { + fmt.Println("Could not mark notifications read:", err) + } else { + fmt.Println("Notifications marked as read.") + } + } +} + +func pathLabel(path domain.Path) string { + parts := make([]string, 0, len(path.Nodes)) + for _, node := range path.Nodes { + parts = append(parts, fmt.Sprintf("%s [%s]", node.Name, node.ID)) + } + return strings.Join(parts, " → ") +}