mirror of
https://github.com/lukaszraczylo/lolcathost.git
synced 2026-11-18 09:25:37 +00:00
Compare commits
59
Commits
v0.1.5
..
af378eee42
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af378eee42 | ||
|
|
e8f30bae2c | ||
|
|
a2970a58df | ||
|
|
a791fe688d | ||
|
|
918db31fb2 | ||
|
|
dfbc6d9fb3 | ||
|
|
4a592b31df | ||
|
|
dae4d893e5 | ||
|
|
df82bddac5 | ||
|
|
04f51fb2a9 | ||
|
|
e005c0457c | ||
|
|
8f56df9a8d | ||
|
|
6a2394a598 | ||
|
|
3c18f25a82 | ||
|
|
0c97ee1a58 | ||
|
|
f1d232a9a6 | ||
|
|
aa414bc2b3 | ||
|
|
62c844b22c | ||
|
|
c6e1207901 | ||
|
|
9551b89082 | ||
|
|
4b808599ac | ||
|
|
a2ec16d3ef | ||
|
|
dc3a22c7bc | ||
|
|
3643ec6a09 | ||
|
|
2f1b5c166a | ||
|
|
7ce331182e | ||
|
|
56518210b1 | ||
|
|
bcf7c0a8a8 | ||
|
|
2cdd684842 | ||
|
|
189137ede8 | ||
|
|
d4cff2028e | ||
|
|
42098eb1c9 | ||
|
|
ad24598036 | ||
|
|
977e766ff9 | ||
|
|
0a47ea7e2a | ||
|
|
100251b896 | ||
|
|
2d9c28657b | ||
|
|
a8acb2d480 | ||
|
|
29263dc8a2 | ||
|
|
27d5011ab1 | ||
|
|
51119b3694 | ||
|
|
1b66f4c6f9 | ||
|
|
8c022fa0d2 | ||
|
|
5d8c72d75f | ||
|
|
2a6f0ee244 | ||
|
|
99f215cb7c | ||
|
|
6eb634bfd0 | ||
|
|
4bf0dd2cdf | ||
|
|
70ac227613 | ||
|
|
90e0375a83 | ||
|
|
8445e50dc8 | ||
|
|
e1b9c15a2a | ||
|
|
c442eade9e | ||
|
|
acc80882e2 | ||
|
|
5e24b13595 | ||
|
|
76e364ca3e | ||
|
|
9598444d56 | ||
|
|
1b832e2fcf | ||
|
|
005ff27392 |
@@ -1,47 +1,19 @@
|
||||
name: AutoUpdate
|
||||
name: Autoupdate go.mod and go.sum
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 3 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
cache: true
|
||||
|
||||
- name: Install dependencies
|
||||
run: go get ./...
|
||||
|
||||
test:
|
||||
needs: prepare
|
||||
runs-on: ubuntu-latest
|
||||
container: golang:1
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install dependencies
|
||||
run: apt-get update && apt-get install -y ca-certificates make
|
||||
|
||||
- name: Tidy and update modules
|
||||
run: |
|
||||
go mod tidy
|
||||
go get -u -v ./...
|
||||
|
||||
- name: Run tests
|
||||
run: CI_RUN=${CI} go test -v ./...
|
||||
|
||||
- name: Commit changes
|
||||
uses: stefanzweifel/git-auto-commit-action@v5
|
||||
with:
|
||||
commit_message: "Update go.mod and go.sum"
|
||||
file_pattern: "go.mod go.sum"
|
||||
autoupdate:
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/go-autoupdate.yaml@main
|
||||
with:
|
||||
go-version: ">=1.24"
|
||||
release-workflow: "release.yml"
|
||||
secrets: inherit
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
name: Pull Request
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
push:
|
||||
branches:
|
||||
- "**"
|
||||
- "!main"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
pull-requests: write
|
||||
security-events: write
|
||||
|
||||
jobs:
|
||||
pr-checks:
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/go-pr.yaml@main
|
||||
with:
|
||||
go-version: ">=1.24"
|
||||
@@ -10,82 +10,14 @@ on:
|
||||
- "go.sum"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
|
||||
- name: Run tests
|
||||
run: go test -race -v ./...
|
||||
|
||||
version:
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.version_formatted.outputs.version }}
|
||||
version_tag: ${{ steps.version_formatted.outputs.version_tag }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Calculate version
|
||||
id: semver
|
||||
uses: lukaszraczylo/semver-generator@v1
|
||||
with:
|
||||
config_file: semver.yaml
|
||||
repository_local: true
|
||||
|
||||
- name: Format version
|
||||
id: version_formatted
|
||||
run: |
|
||||
VERSION="${{ steps.semver.outputs.semantic_version }}"
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "version_tag=v${VERSION}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Print version
|
||||
run: |
|
||||
echo "Version: ${{ steps.version_formatted.outputs.version }}"
|
||||
echo "Version tag: ${{ steps.version_formatted.outputs.version_tag }}"
|
||||
|
||||
release:
|
||||
needs: version
|
||||
if: needs.version.outputs.version_tag != ''
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.24"
|
||||
|
||||
- name: Create and push tag
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag -a ${{ needs.version.outputs.version_tag }} -m "Release ${{ needs.version.outputs.version }}"
|
||||
git push origin ${{ needs.version.outputs.version_tag }}
|
||||
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
distribution: goreleaser
|
||||
version: "~> v2"
|
||||
args: release --clean
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
uses: lukaszraczylo/shared-actions/.github/workflows/go-release.yaml@main
|
||||
with:
|
||||
go-version: ">=1.24"
|
||||
secrets: inherit
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
CLAUDE.md
|
||||
build
|
||||
coverage.out
|
||||
coverage.html
|
||||
|
||||
+23
-7
@@ -22,7 +22,7 @@ builds:
|
||||
|
||||
archives:
|
||||
- id: lolcathost
|
||||
format: tar.gz
|
||||
formats: [tar.gz]
|
||||
name_template: "lolcathost-{{ .Version }}-{{ .Os }}-{{ .Arch }}"
|
||||
files:
|
||||
- LICENSE
|
||||
@@ -49,14 +49,30 @@ release:
|
||||
draft: false
|
||||
prerelease: auto
|
||||
|
||||
brews:
|
||||
homebrew_casks:
|
||||
- repository:
|
||||
owner: lukaszraczylo
|
||||
name: brew-taps
|
||||
name: homebrew-taps
|
||||
token: "{{ .Env.HOMEBREW_TAP_TOKEN }}"
|
||||
directory: Formula
|
||||
directory: Casks
|
||||
homepage: https://github.com/lukaszraczylo/lolcathost
|
||||
description: "Dynamic host management tool for macOS and Linux with TUI"
|
||||
description: "Dynamic host management tool with TUI"
|
||||
license: MIT
|
||||
test: |
|
||||
system "#{bin}/lolcathost", "--version"
|
||||
hooks:
|
||||
post:
|
||||
install: |
|
||||
if OS.mac?
|
||||
system_command "/usr/bin/xattr",
|
||||
args: ["-dr", "com.apple.quarantine", "#{staged_path}/lolcathost"]
|
||||
end
|
||||
|
||||
signs:
|
||||
- cmd: cosign
|
||||
signature: "${artifact}.sigstore.json"
|
||||
args:
|
||||
- sign-blob
|
||||
- "--bundle=${signature}"
|
||||
- "${artifact}"
|
||||
- "--yes"
|
||||
artifacts: checksum
|
||||
output: true
|
||||
|
||||
@@ -50,12 +50,17 @@ lolcathost manages your `/etc/hosts` file with an interactive terminal interface
|
||||
|
||||
## Installation
|
||||
|
||||
### Homebrew (macOS/Linux)
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew install lukaszraczylo/brew-taps/lolcathost
|
||||
brew install --cask lukaszraczylo/taps/lolcathost
|
||||
```
|
||||
|
||||
> **Note**: If you previously installed via `brew install lukaszraczylo/taps/lolcathost` (formula), uninstall first:
|
||||
> ```bash
|
||||
> brew uninstall lolcathost
|
||||
> ```
|
||||
|
||||
After Homebrew installation, run:
|
||||
|
||||
```bash
|
||||
@@ -81,6 +86,19 @@ make build
|
||||
sudo ./build/lolcathost --install
|
||||
```
|
||||
|
||||
### Verifying Release Signatures
|
||||
|
||||
All release checksums are signed with [cosign](https://github.com/sigstore/cosign) using keyless signing. To verify:
|
||||
|
||||
```bash
|
||||
# Download the checksum file and its sigstore bundle from the release
|
||||
cosign verify-blob \
|
||||
--certificate-identity-regexp "https://github.com/lukaszraczylo/lolcathost/.*" \
|
||||
--certificate-oidc-issuer "https://token.actions.githubusercontent.com" \
|
||||
--bundle "lolcathost-<version>-checksums.txt.sigstore.json" \
|
||||
lolcathost-<version>-checksums.txt
|
||||
```
|
||||
|
||||
### Post-Installation
|
||||
|
||||
The installer will:
|
||||
@@ -319,6 +337,18 @@ internal/
|
||||
version/ - Update checker
|
||||
```
|
||||
|
||||
## Telemetry
|
||||
|
||||
On startup this binary sends a single anonymous adoption ping — project name,
|
||||
version, timestamp; no identifiers, no command output, no payload contents.
|
||||
Fire-and-forget with a 2-second timeout; cannot block startup or panic.
|
||||
|
||||
See **[oss-telemetry — Disabling telemetry](https://github.com/lukaszraczylo/oss-telemetry#disabling-telemetry)**
|
||||
for the exact wire format, source, and full opt-out documentation.
|
||||
|
||||
Quick opt-out: set any of `DO_NOT_TRACK=1`, `OSS_TELEMETRY_DISABLED=1`,
|
||||
or `LOLCATHOST_DISABLE_TELEMETRY=1`.
|
||||
|
||||
## License
|
||||
|
||||
MIT License - see [LICENSE](LICENSE).
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/lukaszraczylo/lolcathost/internal/protocol"
|
||||
"github.com/lukaszraczylo/lolcathost/internal/tui"
|
||||
"github.com/lukaszraczylo/lolcathost/internal/version"
|
||||
telemetry "github.com/lukaszraczylo/oss-telemetry"
|
||||
)
|
||||
|
||||
// version is set at compile time via ldflags
|
||||
@@ -27,6 +28,8 @@ const (
|
||||
)
|
||||
|
||||
func main() {
|
||||
telemetry.Send("lolcathost", appVersion)
|
||||
|
||||
// Flags
|
||||
daemonMode := flag.Bool("daemon", false, "Run as daemon (called by LaunchDaemon/systemd)")
|
||||
installFlag := flag.Bool("install", false, "Install the daemon service (requires sudo)")
|
||||
@@ -204,7 +207,7 @@ func runList() {
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", status, e.Domain, e.IP, e.Alias, e.Group)
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
_ = w.Flush()
|
||||
}
|
||||
|
||||
func runOn(alias string) {
|
||||
|
||||
+2
-2
@@ -276,9 +276,9 @@
|
||||
<div class="glass p-6 rounded-xl">
|
||||
<h3 class="font-semibold text-gray-900 dark:text-gray-100 mb-3 flex items-center">
|
||||
<i class="fas fa-beer mr-2 text-amber-500"></i>
|
||||
Homebrew (macOS/Linux)
|
||||
Homebrew (macOS)
|
||||
</h3>
|
||||
<pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto"><code>brew install lukaszraczylo/brew-taps/lolcathost
|
||||
<pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto"><code>brew install --cask lukaszraczylo/taps/lolcathost
|
||||
sudo lolcathost --install</code></pre>
|
||||
</div>
|
||||
<div class="glass p-6 rounded-xl">
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
module github.com/lukaszraczylo/lolcathost
|
||||
|
||||
go 1.24.2
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/charmbracelet/bubbles v0.21.0
|
||||
github.com/charmbracelet/bubbles v1.0.0
|
||||
github.com/charmbracelet/bubbletea v1.3.10
|
||||
github.com/charmbracelet/lipgloss v1.1.0
|
||||
github.com/fsnotify/fsnotify v1.9.0
|
||||
github.com/fsnotify/fsnotify v1.10.1
|
||||
github.com/lukaszraczylo/oss-telemetry v0.1.7
|
||||
github.com/stretchr/testify v1.11.1
|
||||
golang.org/x/sys v0.38.0
|
||||
golang.org/x/sys v0.44.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/atotto/clipboard v0.1.4 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.3.3 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.2 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.14 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.4.3 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.7 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.6.0 // indirect
|
||||
github.com/clipperhouse/stringish v0.1.1 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.11.0 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||
github.com/mattn/go-localereader v0.0.1 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.19 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.23 // indirect
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/muesli/termenv v0.16.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
golang.org/x/text v0.31.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
)
|
||||
|
||||
@@ -2,44 +2,44 @@ github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z
|
||||
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
||||
github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=
|
||||
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
|
||||
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
|
||||
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
|
||||
github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY=
|
||||
github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E=
|
||||
github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc=
|
||||
github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E=
|
||||
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
|
||||
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
|
||||
github.com/charmbracelet/colorprofile v0.3.3 h1:DjJzJtLP6/NZ8p7Cgjno0CKGr7wwRJGxWUwh2IyhfAI=
|
||||
github.com/charmbracelet/colorprofile v0.3.3/go.mod h1:nB1FugsAbzq284eJcjfah2nhdSLppN2NqvfotkfRYP4=
|
||||
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
|
||||
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
|
||||
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
|
||||
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
|
||||
github.com/charmbracelet/x/ansi v0.11.2 h1:XAG3FSjiVtFvgEgGrNBkCNNYrsucAt8c6bfxHyROLLs=
|
||||
github.com/charmbracelet/x/ansi v0.11.2/go.mod h1:9tY2bzX5SiJCU0iWyskjBeI2BRQfvPqI+J760Mjf+Rg=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.14 h1:iUEMryGyFTelKW3THW4+FfPgi4fkmKnnaLOXuc+/Kj4=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.14/go.mod h1:P447lJl49ywBbil/KjCk2HexGh4tEY9LH0/1QrZZ9rA=
|
||||
github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI=
|
||||
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
|
||||
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
|
||||
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
|
||||
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
|
||||
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
|
||||
github.com/clipperhouse/displaywidth v0.6.0 h1:k32vueaksef9WIKCNcoqRNyKbyvkvkysNYnAWz2fN4s=
|
||||
github.com/clipperhouse/displaywidth v0.6.0/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o=
|
||||
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
|
||||
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
|
||||
github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
|
||||
github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
|
||||
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
|
||||
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
|
||||
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/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
||||
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/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
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/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lukaszraczylo/oss-telemetry v0.1.7 h1:+lq9syVPMFsZaaSHGES/sYCOKa+Hqi7jyNEXk0soS2o=
|
||||
github.com/lukaszraczylo/oss-telemetry v0.1.7/go.mod h1:+Cn78qZo8rc3T9eZt0v3oICYRdd75wORtSidc8lNjDQ=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
|
||||
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
|
||||
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
|
||||
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
|
||||
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
|
||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||
@@ -57,11 +57,10 @@ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJu
|
||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
|
||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
||||
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
@@ -29,14 +29,6 @@ func New(socketPath string) *Client {
|
||||
}
|
||||
}
|
||||
|
||||
// NewWithTimeout creates a new client with a custom timeout.
|
||||
func NewWithTimeout(socketPath string, timeout time.Duration) *Client {
|
||||
return &Client{
|
||||
socketPath: socketPath,
|
||||
timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
// Connect establishes a connection to the daemon.
|
||||
func (c *Client) Connect() error {
|
||||
c.mu.Lock()
|
||||
@@ -44,7 +36,7 @@ func (c *Client) Connect() error {
|
||||
|
||||
// Close existing connection if any
|
||||
if c.conn != nil {
|
||||
c.conn.Close()
|
||||
_ = c.conn.Close()
|
||||
c.conn = nil
|
||||
c.reader = nil
|
||||
}
|
||||
@@ -83,7 +75,7 @@ func (c *Client) send(req *protocol.Request) (*protocol.Response, error) {
|
||||
}
|
||||
|
||||
// Set deadline
|
||||
c.conn.SetDeadline(time.Now().Add(c.timeout))
|
||||
_ = c.conn.SetDeadline(time.Now().Add(c.timeout))
|
||||
|
||||
// Send request
|
||||
data, err := json.Marshal(req)
|
||||
@@ -435,14 +427,3 @@ func (c *Client) ListPresets() ([]protocol.PresetInfo, error) {
|
||||
}
|
||||
return data.Presets, nil
|
||||
}
|
||||
|
||||
// IsConnected checks if the daemon is reachable.
|
||||
func IsConnected(socketPath string) bool {
|
||||
client := New(socketPath)
|
||||
if err := client.Connect(); err != nil {
|
||||
return false
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
return client.Ping() == nil
|
||||
}
|
||||
|
||||
+270
-26
@@ -7,7 +7,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -398,31 +397,6 @@ func TestClient_NotConnected(t *testing.T) {
|
||||
assert.Contains(t, err.Error(), "not connected")
|
||||
}
|
||||
|
||||
func TestClient_Timeout(t *testing.T) {
|
||||
client := NewWithTimeout("/nonexistent.sock", 100*time.Millisecond)
|
||||
assert.Equal(t, 100*time.Millisecond, client.timeout)
|
||||
}
|
||||
|
||||
func TestIsConnected(t *testing.T) {
|
||||
t.Run("connected", func(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
resp, _ := protocol.NewOKResponse(nil)
|
||||
return resp
|
||||
}
|
||||
|
||||
connected := IsConnected(server.path)
|
||||
assert.True(t, connected)
|
||||
})
|
||||
|
||||
t.Run("not connected", func(t *testing.T) {
|
||||
connected := IsConnected("/nonexistent/socket.sock")
|
||||
assert.False(t, connected)
|
||||
})
|
||||
}
|
||||
|
||||
// Matrix test for request types
|
||||
func TestClient_RequestTypes_Matrix(t *testing.T) {
|
||||
types := []struct {
|
||||
@@ -474,6 +448,276 @@ func TestClient_RequestTypes_Matrix(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_Add(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestAdd {
|
||||
var payload protocol.AddPayload
|
||||
req.ParsePayload(&payload)
|
||||
assert.Equal(t, "test.local", payload.Domain)
|
||||
assert.Equal(t, "127.0.0.1", payload.IP)
|
||||
assert.Equal(t, "test-local", payload.Alias)
|
||||
assert.Equal(t, "dev", payload.Group)
|
||||
assert.True(t, payload.Enabled)
|
||||
|
||||
resp, _ := protocol.NewOKResponse(protocol.SetData{Domain: payload.Domain, Applied: true})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
data, err := client.Add("test.local", "127.0.0.1", "test-local", "dev", true)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "test.local", data.Domain)
|
||||
assert.True(t, data.Applied)
|
||||
}
|
||||
|
||||
func TestClient_Delete(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestDelete {
|
||||
var payload protocol.DeletePayload
|
||||
req.ParsePayload(&payload)
|
||||
assert.Equal(t, "test-alias", payload.Alias)
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"deleted": payload.Alias})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
err = client.Delete("test-alias")
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestClient_AddGroup(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestAddGroup {
|
||||
var payload protocol.GroupPayload
|
||||
req.ParsePayload(&payload)
|
||||
assert.Equal(t, "newgroup", payload.Name)
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"added": payload.Name})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
err = client.AddGroup("newgroup")
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestClient_DeleteGroup(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestDeleteGroup {
|
||||
var payload protocol.GroupPayload
|
||||
req.ParsePayload(&payload)
|
||||
assert.Equal(t, "todelete", payload.Name)
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"deleted": payload.Name})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
err = client.DeleteGroup("todelete")
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestClient_RenameGroup(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestRenameGroup {
|
||||
var payload protocol.RenameGroupPayload
|
||||
req.ParsePayload(&payload)
|
||||
assert.Equal(t, "oldname", payload.OldName)
|
||||
assert.Equal(t, "newname", payload.NewName)
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"renamed": payload.NewName})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
err = client.RenameGroup("oldname", "newname")
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestClient_ListGroups(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestListGroups {
|
||||
resp, _ := protocol.NewOKResponse(protocol.GroupsData{
|
||||
Groups: []string{"dev", "staging", "prod"},
|
||||
})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
groups, err := client.ListGroups()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, []string{"dev", "staging", "prod"}, groups)
|
||||
}
|
||||
|
||||
func TestClient_GetBackupContent(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
expectedContent := "127.0.0.1\tlocalhost\n"
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestBackupContent {
|
||||
var payload protocol.BackupContentPayload
|
||||
req.ParsePayload(&payload)
|
||||
assert.Equal(t, "hosts.backup.bak", payload.BackupName)
|
||||
|
||||
resp, _ := protocol.NewOKResponse(protocol.BackupContentData{
|
||||
Content: expectedContent,
|
||||
})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
content, err := client.GetBackupContent("hosts.backup.bak")
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, expectedContent, content)
|
||||
}
|
||||
|
||||
func TestClient_AddPreset(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestAddPreset {
|
||||
var payload protocol.AddPresetPayload
|
||||
req.ParsePayload(&payload)
|
||||
assert.Equal(t, "newpreset", payload.Name)
|
||||
assert.Equal(t, []string{"a", "b"}, payload.Enable)
|
||||
assert.Equal(t, []string{"c"}, payload.Disable)
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"added": payload.Name})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
err = client.AddPreset("newpreset", []string{"a", "b"}, []string{"c"})
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestClient_DeletePreset(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestDeletePreset {
|
||||
var payload protocol.PresetPayload
|
||||
req.ParsePayload(&payload)
|
||||
assert.Equal(t, "todelete", payload.Name)
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"deleted": payload.Name})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
err = client.DeletePreset("todelete")
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestClient_ListPresets(t *testing.T) {
|
||||
server := newMockServer(t)
|
||||
defer server.close()
|
||||
|
||||
server.handler = func(req *protocol.Request) *protocol.Response {
|
||||
if req.Type == protocol.RequestListPresets {
|
||||
resp, _ := protocol.NewOKResponse(protocol.PresetsData{
|
||||
Presets: []protocol.PresetInfo{
|
||||
{Name: "local", Enable: []string{"a"}, Disable: []string{"b"}},
|
||||
{Name: "staging", Enable: []string{"b"}, Disable: []string{"a"}},
|
||||
},
|
||||
})
|
||||
return resp
|
||||
}
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "unexpected")
|
||||
}
|
||||
|
||||
client := New(server.path)
|
||||
err := client.Connect()
|
||||
require.NoError(t, err)
|
||||
defer client.Close()
|
||||
|
||||
presets, err := client.ListPresets()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Len(t, presets, 2)
|
||||
assert.Equal(t, "local", presets[0].Name)
|
||||
assert.Equal(t, "staging", presets[1].Name)
|
||||
}
|
||||
|
||||
func BenchmarkClient_Ping(b *testing.B) {
|
||||
tmpDir := b.TempDir()
|
||||
socketPath := filepath.Join(tmpDir, "bench.sock")
|
||||
|
||||
+95
-39
@@ -124,6 +124,12 @@ func (m *Manager) Get() *Config {
|
||||
return m.config
|
||||
}
|
||||
|
||||
// Reload reloads the configuration from disk.
|
||||
// This is useful for rolling back after a failed operation.
|
||||
func (m *Manager) Reload() error {
|
||||
return m.Load()
|
||||
}
|
||||
|
||||
// Watch starts watching the config file for changes.
|
||||
func (m *Manager) Watch(onChange func(*Config)) error {
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
@@ -151,8 +157,15 @@ func (m *Manager) watchLoop() {
|
||||
return
|
||||
}
|
||||
if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) {
|
||||
if err := m.Load(); err == nil && m.onChange != nil {
|
||||
m.onChange(m.Get())
|
||||
// Load and notify under lock to prevent race conditions
|
||||
m.mu.Lock()
|
||||
err := m.loadLocked()
|
||||
cfg := m.config
|
||||
onChange := m.onChange
|
||||
m.mu.Unlock()
|
||||
|
||||
if err == nil && onChange != nil {
|
||||
onChange(cfg)
|
||||
}
|
||||
}
|
||||
case <-m.watcher.Errors:
|
||||
@@ -163,11 +176,32 @@ func (m *Manager) watchLoop() {
|
||||
}
|
||||
}
|
||||
|
||||
// loadLocked reads and parses the configuration file.
|
||||
// Caller must hold m.mu lock.
|
||||
func (m *Manager) loadLocked() error {
|
||||
data, err := os.ReadFile(m.path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read config file: %w", err)
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return fmt.Errorf("failed to parse config file: %w", err)
|
||||
}
|
||||
|
||||
if err := ValidateConfig(&cfg); err != nil {
|
||||
return fmt.Errorf("invalid config: %w", err)
|
||||
}
|
||||
|
||||
m.config = &cfg
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop stops watching the config file.
|
||||
func (m *Manager) Stop() {
|
||||
close(m.stopCh)
|
||||
if m.watcher != nil {
|
||||
m.watcher.Close()
|
||||
_ = m.watcher.Close()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,16 +214,26 @@ func (c *Config) GetAllHosts() []Host {
|
||||
return hosts
|
||||
}
|
||||
|
||||
// FindHostByAlias finds a host by its alias.
|
||||
func (c *Config) FindHostByAlias(alias string) (*Host, *Group) {
|
||||
// findHostIndices finds the group and host indices for a given alias.
|
||||
// Returns -1, -1 if not found.
|
||||
func (c *Config) findHostIndices(alias string) (groupIdx, hostIdx int) {
|
||||
for i := range c.Groups {
|
||||
for j := range c.Groups[i].Hosts {
|
||||
if c.Groups[i].Hosts[j].Alias == alias {
|
||||
return &c.Groups[i].Hosts[j], &c.Groups[i]
|
||||
return i, j
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
// FindHostByAlias finds a host by its alias.
|
||||
func (c *Config) FindHostByAlias(alias string) (*Host, *Group) {
|
||||
groupIdx, hostIdx := c.findHostIndices(alias)
|
||||
if groupIdx < 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return &c.Groups[groupIdx].Hosts[hostIdx], &c.Groups[groupIdx]
|
||||
}
|
||||
|
||||
// FindPreset finds a preset by name.
|
||||
@@ -204,15 +248,12 @@ func (c *Config) FindPreset(name string) *Preset {
|
||||
|
||||
// SetHostEnabled sets the enabled state of a host by alias.
|
||||
func (c *Config) SetHostEnabled(alias string, enabled bool) bool {
|
||||
for i := range c.Groups {
|
||||
for j := range c.Groups[i].Hosts {
|
||||
if c.Groups[i].Hosts[j].Alias == alias {
|
||||
c.Groups[i].Hosts[j].Enabled = enabled
|
||||
return true
|
||||
}
|
||||
}
|
||||
groupIdx, hostIdx := c.findHostIndices(alias)
|
||||
if groupIdx < 0 {
|
||||
return false
|
||||
}
|
||||
return false
|
||||
c.Groups[groupIdx].Hosts[hostIdx].Enabled = enabled
|
||||
return true
|
||||
}
|
||||
|
||||
// GenerateAlias creates a unique alias from a domain name.
|
||||
@@ -327,36 +368,19 @@ func (c *Config) GetGroups() []string {
|
||||
|
||||
// DeleteHost removes a host by alias.
|
||||
func (c *Config) DeleteHost(alias string) bool {
|
||||
for i := range c.Groups {
|
||||
for j := range c.Groups[i].Hosts {
|
||||
if c.Groups[i].Hosts[j].Alias == alias {
|
||||
c.Groups[i].Hosts = append(c.Groups[i].Hosts[:j], c.Groups[i].Hosts[j+1:]...)
|
||||
return true
|
||||
}
|
||||
}
|
||||
groupIdx, hostIdx := c.findHostIndices(alias)
|
||||
if groupIdx < 0 {
|
||||
return false
|
||||
}
|
||||
return false
|
||||
c.Groups[groupIdx].Hosts = append(c.Groups[groupIdx].Hosts[:hostIdx], c.Groups[groupIdx].Hosts[hostIdx+1:]...)
|
||||
return true
|
||||
}
|
||||
|
||||
// UpdateHost updates an existing host by alias.
|
||||
func (c *Config) UpdateHost(oldAlias, domain, ip, newAlias, groupName string) error {
|
||||
// Find the host
|
||||
var foundGroup int = -1
|
||||
var foundHost int = -1
|
||||
for i := range c.Groups {
|
||||
for j := range c.Groups[i].Hosts {
|
||||
if c.Groups[i].Hosts[j].Alias == oldAlias {
|
||||
foundGroup = i
|
||||
foundHost = j
|
||||
break
|
||||
}
|
||||
}
|
||||
if foundHost >= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if foundHost < 0 {
|
||||
foundGroup, foundHost := c.findHostIndices(oldAlias)
|
||||
if foundGroup < 0 {
|
||||
return fmt.Errorf("alias not found: %s", oldAlias)
|
||||
}
|
||||
|
||||
@@ -457,6 +481,35 @@ func (c *Config) GetPresets() []Preset {
|
||||
return c.Presets
|
||||
}
|
||||
|
||||
// Clone creates a deep copy of the configuration.
|
||||
func (c *Config) Clone() *Config {
|
||||
clone := &Config{
|
||||
Settings: c.Settings,
|
||||
Groups: make([]Group, len(c.Groups)),
|
||||
Presets: make([]Preset, len(c.Presets)),
|
||||
}
|
||||
|
||||
for i, g := range c.Groups {
|
||||
clone.Groups[i] = Group{
|
||||
Name: g.Name,
|
||||
Hosts: make([]Host, len(g.Hosts)),
|
||||
}
|
||||
copy(clone.Groups[i].Hosts, g.Hosts)
|
||||
}
|
||||
|
||||
for i, p := range c.Presets {
|
||||
clone.Presets[i] = Preset{
|
||||
Name: p.Name,
|
||||
Enable: make([]string, len(p.Enable)),
|
||||
Disable: make([]string, len(p.Disable)),
|
||||
}
|
||||
copy(clone.Presets[i].Enable, p.Enable)
|
||||
copy(clone.Presets[i].Disable, p.Disable)
|
||||
}
|
||||
|
||||
return clone
|
||||
}
|
||||
|
||||
// EnsureDefaultGroup ensures at least one group exists, creating "default" if needed.
|
||||
func (c *Config) EnsureDefaultGroup() {
|
||||
if len(c.Groups) == 0 {
|
||||
@@ -482,6 +535,7 @@ func (m *Manager) Save() error {
|
||||
return fmt.Errorf("failed to marshal config: %w", err)
|
||||
}
|
||||
|
||||
// #nosec G306 - Config file permissions are intentionally 0644
|
||||
if err := os.WriteFile(m.path, data, 0644); err != nil {
|
||||
return fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
@@ -492,6 +546,7 @@ func (m *Manager) Save() error {
|
||||
// CreateDefault creates a default configuration file.
|
||||
func CreateDefault(path string) error {
|
||||
dir := filepath.Dir(path)
|
||||
// #nosec G301 - Config directory permissions are intentionally 0755
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
@@ -533,6 +588,7 @@ func CreateDefault(path string) error {
|
||||
return fmt.Errorf("failed to marshal default config: %w", err)
|
||||
}
|
||||
|
||||
// #nosec G306 - Config file permissions are intentionally 0644
|
||||
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||
return fmt.Errorf("failed to write default config: %w", err)
|
||||
}
|
||||
|
||||
@@ -265,3 +265,257 @@ func TestFlushMethod(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultConfigDir(t *testing.T) {
|
||||
dir := DefaultConfigDir()
|
||||
assert.NotEmpty(t, dir)
|
||||
assert.Contains(t, dir, ".config/lolcathost")
|
||||
}
|
||||
|
||||
func TestDefaultConfigPath(t *testing.T) {
|
||||
path := DefaultConfigPath()
|
||||
assert.NotEmpty(t, path)
|
||||
assert.Contains(t, path, "config.yaml")
|
||||
}
|
||||
|
||||
func TestConfig_GenerateAlias(t *testing.T) {
|
||||
cfg := &Config{
|
||||
Groups: []Group{
|
||||
{
|
||||
Name: "dev",
|
||||
Hosts: []Host{
|
||||
{Domain: "existing.com", IP: "127.0.0.1", Alias: "existing-com", Enabled: true},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
t.Run("simple domain", func(t *testing.T) {
|
||||
alias := cfg.GenerateAlias("newdomain.com")
|
||||
assert.Equal(t, "newdomain-com", alias)
|
||||
})
|
||||
|
||||
t.Run("domain with underscore", func(t *testing.T) {
|
||||
alias := cfg.GenerateAlias("my_app.test")
|
||||
assert.Equal(t, "my-app-test", alias)
|
||||
})
|
||||
|
||||
t.Run("duplicate generates numbered alias", func(t *testing.T) {
|
||||
alias := cfg.GenerateAlias("existing.com")
|
||||
assert.Equal(t, "existing-com-2", alias)
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfig_AddHost(t *testing.T) {
|
||||
t.Run("add to existing group", func(t *testing.T) {
|
||||
cfg := &Config{
|
||||
Groups: []Group{
|
||||
{Name: "dev", Hosts: []Host{}},
|
||||
},
|
||||
}
|
||||
err := cfg.AddHost("test.local", "127.0.0.1", "test-local", "dev", true)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cfg.Groups[0].Hosts, 1)
|
||||
assert.Equal(t, "test.local", cfg.Groups[0].Hosts[0].Domain)
|
||||
})
|
||||
|
||||
t.Run("add to new group", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{}}
|
||||
err := cfg.AddHost("test.local", "127.0.0.1", "test-local", "newgroup", true)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cfg.Groups, 1)
|
||||
assert.Equal(t, "newgroup", cfg.Groups[0].Name)
|
||||
})
|
||||
|
||||
t.Run("auto-generate alias", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{}}
|
||||
err := cfg.AddHost("auto.test", "127.0.0.1", "", "dev", true)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "auto-test", cfg.Groups[0].Hosts[0].Alias)
|
||||
})
|
||||
|
||||
t.Run("duplicate alias error", func(t *testing.T) {
|
||||
cfg := &Config{
|
||||
Groups: []Group{
|
||||
{Name: "dev", Hosts: []Host{{Domain: "a.com", IP: "127.0.0.1", Alias: "existing"}}},
|
||||
},
|
||||
}
|
||||
err := cfg.AddHost("b.com", "127.0.0.1", "existing", "dev", true)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "alias already exists")
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfig_AddGroup(t *testing.T) {
|
||||
t.Run("add new group", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{}}
|
||||
err := cfg.AddGroup("newgroup")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cfg.Groups, 1)
|
||||
assert.Equal(t, "newgroup", cfg.Groups[0].Name)
|
||||
})
|
||||
|
||||
t.Run("duplicate group error", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{{Name: "existing"}}}
|
||||
err := cfg.AddGroup("existing")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "group already exists")
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfig_DeleteGroup(t *testing.T) {
|
||||
t.Run("delete existing group", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{{Name: "todelete"}, {Name: "keep"}}}
|
||||
err := cfg.DeleteGroup("todelete")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cfg.Groups, 1)
|
||||
assert.Equal(t, "keep", cfg.Groups[0].Name)
|
||||
})
|
||||
|
||||
t.Run("delete nonexistent group", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{}}
|
||||
err := cfg.DeleteGroup("nonexistent")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "group not found")
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfig_RenameGroup(t *testing.T) {
|
||||
t.Run("rename existing group", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{{Name: "oldname"}}}
|
||||
err := cfg.RenameGroup("oldname", "newname")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "newname", cfg.Groups[0].Name)
|
||||
})
|
||||
|
||||
t.Run("rename to existing name error", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{{Name: "a"}, {Name: "b"}}}
|
||||
err := cfg.RenameGroup("a", "b")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "group already exists")
|
||||
})
|
||||
|
||||
t.Run("rename nonexistent group", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{}}
|
||||
err := cfg.RenameGroup("nonexistent", "newname")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "group not found")
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfig_GetGroups(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{{Name: "a"}, {Name: "b"}, {Name: "c"}}}
|
||||
groups := cfg.GetGroups()
|
||||
assert.Equal(t, []string{"a", "b", "c"}, groups)
|
||||
}
|
||||
|
||||
func TestConfig_DeleteHost(t *testing.T) {
|
||||
t.Run("delete existing host", func(t *testing.T) {
|
||||
cfg := &Config{
|
||||
Groups: []Group{
|
||||
{Name: "dev", Hosts: []Host{
|
||||
{Domain: "a.com", Alias: "a"},
|
||||
{Domain: "b.com", Alias: "b"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
result := cfg.DeleteHost("a")
|
||||
assert.True(t, result)
|
||||
assert.Len(t, cfg.Groups[0].Hosts, 1)
|
||||
assert.Equal(t, "b", cfg.Groups[0].Hosts[0].Alias)
|
||||
})
|
||||
|
||||
t.Run("delete nonexistent host", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{}}
|
||||
result := cfg.DeleteHost("nonexistent")
|
||||
assert.False(t, result)
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfig_AddPreset(t *testing.T) {
|
||||
t.Run("add new preset", func(t *testing.T) {
|
||||
cfg := &Config{Presets: []Preset{}}
|
||||
err := cfg.AddPreset("newpreset", []string{"a"}, []string{"b"})
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cfg.Presets, 1)
|
||||
assert.Equal(t, "newpreset", cfg.Presets[0].Name)
|
||||
})
|
||||
|
||||
t.Run("duplicate preset error", func(t *testing.T) {
|
||||
cfg := &Config{Presets: []Preset{{Name: "existing"}}}
|
||||
err := cfg.AddPreset("existing", nil, nil)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "preset already exists")
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfig_DeletePreset(t *testing.T) {
|
||||
t.Run("delete existing preset", func(t *testing.T) {
|
||||
cfg := &Config{Presets: []Preset{{Name: "todelete"}, {Name: "keep"}}}
|
||||
err := cfg.DeletePreset("todelete")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cfg.Presets, 1)
|
||||
assert.Equal(t, "keep", cfg.Presets[0].Name)
|
||||
})
|
||||
|
||||
t.Run("delete nonexistent preset", func(t *testing.T) {
|
||||
cfg := &Config{Presets: []Preset{}}
|
||||
err := cfg.DeletePreset("nonexistent")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "preset not found")
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfig_GetPresets(t *testing.T) {
|
||||
cfg := &Config{Presets: []Preset{{Name: "a"}, {Name: "b"}}}
|
||||
presets := cfg.GetPresets()
|
||||
assert.Len(t, presets, 2)
|
||||
}
|
||||
|
||||
func TestConfig_EnsureDefaultGroup(t *testing.T) {
|
||||
t.Run("creates default when empty", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{}}
|
||||
cfg.EnsureDefaultGroup()
|
||||
assert.Len(t, cfg.Groups, 1)
|
||||
assert.Equal(t, "default", cfg.Groups[0].Name)
|
||||
})
|
||||
|
||||
t.Run("does nothing when groups exist", func(t *testing.T) {
|
||||
cfg := &Config{Groups: []Group{{Name: "existing"}}}
|
||||
cfg.EnsureDefaultGroup()
|
||||
assert.Len(t, cfg.Groups, 1)
|
||||
assert.Equal(t, "existing", cfg.Groups[0].Name)
|
||||
})
|
||||
}
|
||||
|
||||
func TestManager_Watch(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
configPath := filepath.Join(tmpDir, "config.yaml")
|
||||
|
||||
err := CreateDefault(configPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
manager := NewManager(configPath)
|
||||
err = manager.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
changeCh := make(chan *Config, 1)
|
||||
err = manager.Watch(func(cfg *Config) {
|
||||
changeCh <- cfg
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Stop the watcher
|
||||
manager.Stop()
|
||||
}
|
||||
|
||||
func TestManager_Save_NoConfig(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
configPath := filepath.Join(tmpDir, "config.yaml")
|
||||
|
||||
manager := NewManager(configPath)
|
||||
// Don't load, so config is nil
|
||||
err := manager.Save()
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "no config loaded")
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func New(configPath string) (*Daemon, error) {
|
||||
cfg.EnsureDefaultGroup()
|
||||
// Save if we added a default group
|
||||
if len(cfg.Groups) == 1 && cfg.Groups[0].Name == "default" && len(cfg.Groups[0].Hosts) == 0 {
|
||||
cfgManager.Save()
|
||||
_ = cfgManager.Save()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,11 +92,6 @@ func (d *Daemon) Run() error {
|
||||
return d.shutdown()
|
||||
}
|
||||
|
||||
// Stop signals the daemon to stop.
|
||||
func (d *Daemon) Stop() {
|
||||
close(d.stopCh)
|
||||
}
|
||||
|
||||
func (d *Daemon) shutdown() error {
|
||||
close(d.cleanupCh)
|
||||
d.config.Stop()
|
||||
|
||||
@@ -137,6 +137,6 @@ func (f *DNSFlusher) flushLinux(method FlushMethod) error {
|
||||
}
|
||||
|
||||
func runCommand(name string, args ...string) error {
|
||||
cmd := exec.Command(name, args...)
|
||||
cmd := exec.Command(name, args...) // #nosec G204 - Commands are hardcoded DNS flush utilities, not user input
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
+16
-63
@@ -2,7 +2,6 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -25,6 +24,10 @@ const (
|
||||
markerEnd = "# ========== END LOLCATHOST =========="
|
||||
)
|
||||
|
||||
// entryRegex matches host entries in the managed section.
|
||||
// Compiled once at package init for efficiency.
|
||||
var entryRegex = regexp.MustCompile(`^(\S+)\s+(\S+)\s+#\s*lolcathost:(\S+)$`)
|
||||
|
||||
// HostEntry represents a single entry in the hosts file.
|
||||
type HostEntry struct {
|
||||
IP string
|
||||
@@ -47,59 +50,6 @@ func NewHostsManager() *HostsManager {
|
||||
}
|
||||
}
|
||||
|
||||
// NewHostsManagerWithPaths creates a hosts manager with custom paths (for testing).
|
||||
func NewHostsManagerWithPaths(hostsPath, backupDir string) *HostsManager {
|
||||
return &HostsManager{
|
||||
hostsPath: hostsPath,
|
||||
backupDir: backupDir,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadManagedEntries reads the lolcathost-managed entries from the hosts file.
|
||||
func (m *HostsManager) ReadManagedEntries() ([]HostEntry, error) {
|
||||
file, err := os.Open(m.hostsPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open hosts file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var entries []HostEntry
|
||||
inManagedSection := false
|
||||
scanner := bufio.NewScanner(file)
|
||||
entryRegex := regexp.MustCompile(`^(\S+)\s+(\S+)\s+#\s*lolcathost:(\S+)$`)
|
||||
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
|
||||
if line == markerStart {
|
||||
inManagedSection = true
|
||||
continue
|
||||
}
|
||||
if line == markerEnd {
|
||||
inManagedSection = false
|
||||
continue
|
||||
}
|
||||
|
||||
if inManagedSection && !strings.HasPrefix(line, "#") && line != "" {
|
||||
matches := entryRegex.FindStringSubmatch(line)
|
||||
if len(matches) == 4 {
|
||||
entries = append(entries, HostEntry{
|
||||
IP: matches[1],
|
||||
Domain: matches[2],
|
||||
Alias: matches[3],
|
||||
Enabled: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed to read hosts file: %w", err)
|
||||
}
|
||||
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// WriteManagedEntries writes the managed entries to the hosts file.
|
||||
func (m *HostsManager) WriteManagedEntries(entries []HostEntry) error {
|
||||
// Create backup first
|
||||
@@ -178,13 +128,14 @@ func (m *HostsManager) buildManagedSection(entries []HostEntry) string {
|
||||
func (m *HostsManager) writeAtomic(content string) error {
|
||||
// Write to temp file first
|
||||
tmpFile := m.hostsPath + ".tmp"
|
||||
// #nosec G306 - Hosts file permissions are intentionally 0644
|
||||
if err := os.WriteFile(tmpFile, []byte(content), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Rename atomically
|
||||
if err := os.Rename(tmpFile, m.hostsPath); err != nil {
|
||||
os.Remove(tmpFile)
|
||||
_ = os.Remove(tmpFile)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -193,11 +144,12 @@ func (m *HostsManager) writeAtomic(content string) error {
|
||||
|
||||
// CreateBackup creates a backup of the current hosts file.
|
||||
func (m *HostsManager) CreateBackup() error {
|
||||
// #nosec G301 - Backup directory permissions are intentionally 0755
|
||||
if err := os.MkdirAll(m.backupDir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create backup directory: %w", err)
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(m.hostsPath)
|
||||
content, err := os.ReadFile(m.hostsPath) // #nosec G304 - Path is controlled by daemon, not user input
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read hosts file: %w", err)
|
||||
}
|
||||
@@ -205,6 +157,7 @@ func (m *HostsManager) CreateBackup() error {
|
||||
timestamp := time.Now().Format("20060102-150405")
|
||||
backupPath := filepath.Join(m.backupDir, fmt.Sprintf("hosts.%s.bak", timestamp))
|
||||
|
||||
// #nosec G306 - Backup file permissions are intentionally 0644
|
||||
if err := os.WriteFile(backupPath, content, 0644); err != nil {
|
||||
return fmt.Errorf("failed to write backup: %w", err)
|
||||
}
|
||||
@@ -243,7 +196,7 @@ func (m *HostsManager) cleanupBackups() error {
|
||||
// Remove oldest backups
|
||||
for i := MaxBackups; i < len(backups); i++ {
|
||||
path := filepath.Join(m.backupDir, backups[i].Name())
|
||||
os.Remove(path)
|
||||
_ = os.Remove(path)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -294,14 +247,14 @@ type BackupInfo struct {
|
||||
|
||||
// GetBackupContent returns the content of a backup file.
|
||||
func (m *HostsManager) GetBackupContent(name string) (string, error) {
|
||||
backupPath := filepath.Join(m.backupDir, name)
|
||||
|
||||
// Validate backup name to prevent path traversal
|
||||
if filepath.Base(name) != name || !strings.HasPrefix(name, "hosts.") || !strings.HasSuffix(name, ".bak") {
|
||||
return "", fmt.Errorf("invalid backup name")
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(backupPath)
|
||||
backupPath := filepath.Join(m.backupDir, name)
|
||||
|
||||
content, err := os.ReadFile(backupPath) // #nosec G304 - Path is validated above to prevent traversal
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read backup: %w", err)
|
||||
}
|
||||
@@ -311,14 +264,14 @@ func (m *HostsManager) GetBackupContent(name string) (string, error) {
|
||||
|
||||
// RestoreBackup restores a backup by name.
|
||||
func (m *HostsManager) RestoreBackup(name string) error {
|
||||
backupPath := filepath.Join(m.backupDir, name)
|
||||
|
||||
// Validate backup name to prevent path traversal
|
||||
if filepath.Base(name) != name || !strings.HasPrefix(name, "hosts.") || !strings.HasSuffix(name, ".bak") {
|
||||
return fmt.Errorf("invalid backup name")
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(backupPath)
|
||||
backupPath := filepath.Join(m.backupDir, name)
|
||||
|
||||
content, err := os.ReadFile(backupPath) // #nosec G304 - Path is validated above to prevent traversal
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read backup: %w", err)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -10,7 +11,53 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestHostsManager_ReadManagedEntries(t *testing.T) {
|
||||
// newHostsManagerWithPaths creates a hosts manager with custom paths (for testing).
|
||||
func newHostsManagerWithPaths(hostsPath, backupDir string) *HostsManager {
|
||||
return &HostsManager{
|
||||
hostsPath: hostsPath,
|
||||
backupDir: backupDir,
|
||||
}
|
||||
}
|
||||
|
||||
// readManagedEntries reads the lolcathost-managed entries from the hosts file (for testing).
|
||||
func (m *HostsManager) readManagedEntries() ([]HostEntry, error) {
|
||||
content, err := os.ReadFile(m.hostsPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read hosts file: %w", err)
|
||||
}
|
||||
|
||||
var entries []HostEntry
|
||||
inManagedSection := false
|
||||
|
||||
for _, line := range strings.Split(string(content), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
|
||||
if line == markerStart {
|
||||
inManagedSection = true
|
||||
continue
|
||||
}
|
||||
if line == markerEnd {
|
||||
inManagedSection = false
|
||||
continue
|
||||
}
|
||||
|
||||
if inManagedSection && !strings.HasPrefix(line, "#") && line != "" {
|
||||
matches := entryRegex.FindStringSubmatch(line)
|
||||
if len(matches) == 4 {
|
||||
entries = append(entries, HostEntry{
|
||||
IP: matches[1],
|
||||
Domain: matches[2],
|
||||
Alias: matches[3],
|
||||
Enabled: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func TestHostsManager_readManagedEntries(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
hostsPath := filepath.Join(tmpDir, "hosts")
|
||||
|
||||
@@ -26,8 +73,8 @@ func TestHostsManager_ReadManagedEntries(t *testing.T) {
|
||||
err := os.WriteFile(hostsPath, []byte(hostsContent), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
|
||||
entries, err := manager.ReadManagedEntries()
|
||||
manager := newHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
|
||||
entries, err := manager.readManagedEntries()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Len(t, entries, 2)
|
||||
@@ -39,7 +86,7 @@ func TestHostsManager_ReadManagedEntries(t *testing.T) {
|
||||
assert.Equal(t, "api-local", entries[1].Alias)
|
||||
}
|
||||
|
||||
func TestHostsManager_ReadManagedEntries_NoSection(t *testing.T) {
|
||||
func TestHostsManager_readManagedEntries_NoSection(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
hostsPath := filepath.Join(tmpDir, "hosts")
|
||||
|
||||
@@ -49,8 +96,8 @@ func TestHostsManager_ReadManagedEntries_NoSection(t *testing.T) {
|
||||
err := os.WriteFile(hostsPath, []byte(hostsContent), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
|
||||
entries, err := manager.ReadManagedEntries()
|
||||
manager := newHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
|
||||
entries, err := manager.readManagedEntries()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Empty(t, entries)
|
||||
@@ -68,7 +115,7 @@ func TestHostsManager_WriteManagedEntries(t *testing.T) {
|
||||
err := os.WriteFile(hostsPath, []byte(initialContent), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
|
||||
manager := newHostsManagerWithPaths(hostsPath, backupDir)
|
||||
|
||||
entries := []HostEntry{
|
||||
{IP: "127.0.0.1", Domain: "myapp.com", Alias: "myapp-local", Enabled: true},
|
||||
@@ -107,7 +154,7 @@ func TestHostsManager_WriteManagedEntries_UpdatesExisting(t *testing.T) {
|
||||
err := os.WriteFile(hostsPath, []byte(initialContent), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
|
||||
manager := newHostsManagerWithPaths(hostsPath, backupDir)
|
||||
|
||||
entries := []HostEntry{
|
||||
{IP: "127.0.0.1", Domain: "new.com", Alias: "new", Enabled: true},
|
||||
@@ -134,7 +181,7 @@ func TestHostsManager_CreateBackup(t *testing.T) {
|
||||
err := os.WriteFile(hostsPath, []byte(hostsContent), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
|
||||
manager := newHostsManagerWithPaths(hostsPath, backupDir)
|
||||
|
||||
err = manager.CreateBackup()
|
||||
require.NoError(t, err)
|
||||
@@ -175,7 +222,7 @@ func TestHostsManager_ListBackups(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
|
||||
manager := newHostsManagerWithPaths(hostsPath, backupDir)
|
||||
|
||||
backups, err := manager.ListBackups()
|
||||
require.NoError(t, err)
|
||||
@@ -187,7 +234,7 @@ func TestHostsManager_ListBackups_NoBackupDir(t *testing.T) {
|
||||
hostsPath := filepath.Join(tmpDir, "hosts")
|
||||
backupDir := filepath.Join(tmpDir, "nonexistent")
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
|
||||
manager := newHostsManagerWithPaths(hostsPath, backupDir)
|
||||
|
||||
backups, err := manager.ListBackups()
|
||||
require.NoError(t, err)
|
||||
@@ -204,7 +251,7 @@ func TestHostsManager_RestoreBackup(t *testing.T) {
|
||||
err := os.WriteFile(hostsPath, []byte(initialContent), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
|
||||
manager := newHostsManagerWithPaths(hostsPath, backupDir)
|
||||
|
||||
// Create backup
|
||||
err = manager.CreateBackup()
|
||||
@@ -231,7 +278,7 @@ func TestHostsManager_RestoreBackup(t *testing.T) {
|
||||
|
||||
func TestHostsManager_RestoreBackup_InvalidName(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
manager := NewHostsManagerWithPaths(
|
||||
manager := newHostsManagerWithPaths(
|
||||
filepath.Join(tmpDir, "hosts"),
|
||||
filepath.Join(tmpDir, "backups"),
|
||||
)
|
||||
@@ -259,7 +306,7 @@ func TestHostsManager_CleanupBackups(t *testing.T) {
|
||||
err := os.WriteFile(hostsPath, []byte("localhost"), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
|
||||
manager := newHostsManagerWithPaths(hostsPath, backupDir)
|
||||
|
||||
// Create more than MaxBackups
|
||||
for i := 0; i < MaxBackups+5; i++ {
|
||||
@@ -338,7 +385,7 @@ func TestHostsManager_BuildManagedSection(t *testing.T) {
|
||||
}
|
||||
|
||||
// Matrix tests for hosts file parsing
|
||||
func TestHostsManager_ReadManagedEntries_Matrix(t *testing.T) {
|
||||
func TestHostsManager_readManagedEntries_Matrix(t *testing.T) {
|
||||
ips := []string{"127.0.0.1", "192.168.1.1", "::1"}
|
||||
domains := []string{"example.com", "sub.example.com", "my-app.test"}
|
||||
aliases := []string{"test", "my-alias", "app-1"}
|
||||
@@ -357,8 +404,8 @@ func TestHostsManager_ReadManagedEntries_Matrix(t *testing.T) {
|
||||
err := os.WriteFile(hostsPath, []byte(content), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
|
||||
entries, err := manager.ReadManagedEntries()
|
||||
manager := newHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
|
||||
entries, err := manager.readManagedEntries()
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
|
||||
@@ -371,7 +418,7 @@ func TestHostsManager_ReadManagedEntries_Matrix(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkHostsManager_ReadManagedEntries(b *testing.B) {
|
||||
func BenchmarkHostsManager_readManagedEntries(b *testing.B) {
|
||||
tmpDir := b.TempDir()
|
||||
hostsPath := filepath.Join(tmpDir, "hosts")
|
||||
|
||||
@@ -387,11 +434,11 @@ func BenchmarkHostsManager_ReadManagedEntries(b *testing.B) {
|
||||
err := os.WriteFile(hostsPath, []byte(content.String()), 0644)
|
||||
require.NoError(b, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
|
||||
manager := newHostsManagerWithPaths(hostsPath, filepath.Join(tmpDir, "backups"))
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = manager.ReadManagedEntries()
|
||||
_, _ = manager.readManagedEntries()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -403,7 +450,7 @@ func BenchmarkHostsManager_WriteManagedEntries(b *testing.B) {
|
||||
err := os.WriteFile(hostsPath, []byte("127.0.0.1\tlocalhost\n"), 0644)
|
||||
require.NoError(b, err)
|
||||
|
||||
manager := NewHostsManagerWithPaths(hostsPath, backupDir)
|
||||
manager := newHostsManagerWithPaths(hostsPath, backupDir)
|
||||
|
||||
entries := make([]HostEntry, 50)
|
||||
for i := range entries {
|
||||
|
||||
@@ -24,15 +24,21 @@ func (s *Server) getPeerCredentials(conn net.Conn) *PeerCredentials {
|
||||
}
|
||||
|
||||
var creds *PeerCredentials
|
||||
rawConn.Control(func(fd uintptr) {
|
||||
_ = rawConn.Control(func(fd uintptr) {
|
||||
xucred, err := unix.GetsockoptXucred(int(fd), unix.SOL_LOCAL, unix.LOCAL_PEERCRED)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Validate Groups array is not empty before accessing
|
||||
if xucred.Ngroups == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Get PID separately using LOCAL_PEERPID
|
||||
var pid int32
|
||||
pidLen := uint32(unsafe.Sizeof(pid))
|
||||
// #nosec G103 - unsafe.Pointer required for syscall to get peer PID
|
||||
_, _, errno := syscall.Syscall6(
|
||||
syscall.SYS_GETSOCKOPT,
|
||||
fd,
|
||||
|
||||
+71
-33
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
@@ -19,20 +20,27 @@ const (
|
||||
RateLimitWindow = time.Minute
|
||||
)
|
||||
|
||||
// RateLimiter implements per-PID rate limiting.
|
||||
// pidRateBucket holds rate limiting data for a single PID using a ring buffer.
|
||||
type pidRateBucket struct {
|
||||
timestamps []time.Time // Ring buffer of request timestamps
|
||||
head int // Next write position
|
||||
count int // Number of valid entries
|
||||
}
|
||||
|
||||
// RateLimiter implements per-PID rate limiting with efficient memory usage.
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
requests map[int32][]time.Time
|
||||
limit int
|
||||
window time.Duration
|
||||
mu sync.Mutex
|
||||
buckets map[int32]*pidRateBucket
|
||||
limit int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
// NewRateLimiter creates a new rate limiter.
|
||||
func NewRateLimiter(limit int, window time.Duration) *RateLimiter {
|
||||
return &RateLimiter{
|
||||
requests: make(map[int32][]time.Time),
|
||||
limit: limit,
|
||||
window: window,
|
||||
buckets: make(map[int32]*pidRateBucket),
|
||||
limit: limit,
|
||||
window: window,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,31 +52,42 @@ func (r *RateLimiter) Allow(pid int32) bool {
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-r.window)
|
||||
|
||||
// Get existing requests for this PID
|
||||
reqs := r.requests[pid]
|
||||
bucket, exists := r.buckets[pid]
|
||||
if !exists {
|
||||
// Create new bucket with fixed capacity
|
||||
bucket = &pidRateBucket{
|
||||
timestamps: make([]time.Time, r.limit),
|
||||
head: 0,
|
||||
count: 0,
|
||||
}
|
||||
r.buckets[pid] = bucket
|
||||
}
|
||||
|
||||
// Filter out old requests
|
||||
var validReqs []time.Time
|
||||
for _, t := range reqs {
|
||||
if t.After(cutoff) {
|
||||
validReqs = append(validReqs, t)
|
||||
// Count valid (non-expired) requests in the ring buffer
|
||||
validCount := 0
|
||||
for i := 0; i < bucket.count; i++ {
|
||||
idx := (bucket.head - bucket.count + i + r.limit) % r.limit
|
||||
if bucket.timestamps[idx].After(cutoff) {
|
||||
validCount++
|
||||
}
|
||||
}
|
||||
|
||||
// Check if under limit
|
||||
if len(validReqs) >= r.limit {
|
||||
r.requests[pid] = validReqs
|
||||
if validCount >= r.limit {
|
||||
return false
|
||||
}
|
||||
|
||||
// Add new request
|
||||
validReqs = append(validReqs, now)
|
||||
r.requests[pid] = validReqs
|
||||
// Add new request to ring buffer (overwrites oldest if full)
|
||||
bucket.timestamps[bucket.head] = now
|
||||
bucket.head = (bucket.head + 1) % r.limit
|
||||
if bucket.count < r.limit {
|
||||
bucket.count++
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Cleanup removes old entries from the rate limiter.
|
||||
// Cleanup removes stale PID entries from the rate limiter.
|
||||
func (r *RateLimiter) Cleanup() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
@@ -76,17 +95,18 @@ func (r *RateLimiter) Cleanup() {
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-r.window)
|
||||
|
||||
for pid, reqs := range r.requests {
|
||||
var validReqs []time.Time
|
||||
for _, t := range reqs {
|
||||
if t.After(cutoff) {
|
||||
validReqs = append(validReqs, t)
|
||||
for pid, bucket := range r.buckets {
|
||||
// Check if all timestamps are expired
|
||||
hasValid := false
|
||||
for i := 0; i < bucket.count; i++ {
|
||||
idx := (bucket.head - bucket.count + i + r.limit) % r.limit
|
||||
if bucket.timestamps[idx].After(cutoff) {
|
||||
hasValid = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(validReqs) == 0 {
|
||||
delete(r.requests, pid)
|
||||
} else {
|
||||
r.requests[pid] = validReqs
|
||||
if !hasValid {
|
||||
delete(r.buckets, pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -114,10 +134,12 @@ type AuditEntry struct {
|
||||
func NewAuditLogger(path string) (*AuditLogger, error) {
|
||||
// Ensure directory exists
|
||||
dir := path[:len(path)-len("/audit.log")]
|
||||
// #nosec G301 - Log directory permissions are intentionally 0755
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create log directory: %w", err)
|
||||
}
|
||||
|
||||
// #nosec G302,G304,G306 - Path is constant, permissions are intentional for audit log
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open audit log: %w", err)
|
||||
@@ -185,12 +207,28 @@ func isUserInGroup(uid uint32, targetGID uint32) bool {
|
||||
}
|
||||
|
||||
// Check if target GID is in the list
|
||||
targetGIDStr := fmt.Sprintf("%d", targetGID)
|
||||
for _, gid := range groupIDs {
|
||||
if gid == targetGIDStr {
|
||||
for _, gidStr := range groupIDs {
|
||||
gid, err := strconv.ParseUint(gidStr, 10, 32)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if uint32(gid) == targetGID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// lookupGroupGID looks up a group by name and returns its GID.
|
||||
func lookupGroupGID(name string) (int, error) {
|
||||
group, err := user.LookupGroup(name)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("group not found: %s", name)
|
||||
}
|
||||
gid, err := strconv.Atoi(group.Gid)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid GID for group %s: %s", name, group.Gid)
|
||||
}
|
||||
return gid, nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -67,7 +68,7 @@ func TestRateLimiter_Cleanup(t *testing.T) {
|
||||
rl.Allow(pid)
|
||||
}
|
||||
|
||||
assert.Len(t, rl.requests, 5)
|
||||
assert.Len(t, rl.buckets, 5)
|
||||
|
||||
// Wait for expiration
|
||||
time.Sleep(15 * time.Millisecond)
|
||||
@@ -75,7 +76,7 @@ func TestRateLimiter_Cleanup(t *testing.T) {
|
||||
// Cleanup
|
||||
rl.Cleanup()
|
||||
|
||||
assert.Empty(t, rl.requests)
|
||||
assert.Empty(t, rl.buckets)
|
||||
}
|
||||
|
||||
func TestAuditLogger_Log(t *testing.T) {
|
||||
@@ -145,26 +146,31 @@ func TestPeerCredentials(t *testing.T) {
|
||||
|
||||
// Matrix test for rate limiting
|
||||
func TestRateLimiter_Matrix(t *testing.T) {
|
||||
limits := []int{1, 5, 10, 100}
|
||||
windows := []time.Duration{10 * time.Millisecond, 100 * time.Millisecond, time.Second}
|
||||
testCases := []struct {
|
||||
limit int
|
||||
window time.Duration
|
||||
}{
|
||||
{1, time.Second},
|
||||
{5, time.Second},
|
||||
{10, time.Second},
|
||||
{100, time.Second},
|
||||
}
|
||||
|
||||
for _, limit := range limits {
|
||||
for _, window := range windows {
|
||||
t.Run(
|
||||
"limit="+string(rune('0'+limit))+"_window="+window.String(),
|
||||
func(t *testing.T) {
|
||||
rl := NewRateLimiter(limit, window)
|
||||
for _, tc := range testCases {
|
||||
t.Run(
|
||||
fmt.Sprintf("limit=%d_window=%s", tc.limit, tc.window),
|
||||
func(t *testing.T) {
|
||||
rl := NewRateLimiter(tc.limit, tc.window)
|
||||
|
||||
// Should allow exactly 'limit' requests
|
||||
for i := 0; i < limit; i++ {
|
||||
assert.True(t, rl.Allow(1))
|
||||
}
|
||||
// Should allow exactly 'limit' requests
|
||||
for i := 0; i < tc.limit; i++ {
|
||||
assert.True(t, rl.Allow(1), "request %d should be allowed", i)
|
||||
}
|
||||
|
||||
// Next should be blocked
|
||||
assert.False(t, rl.Allow(1))
|
||||
},
|
||||
)
|
||||
}
|
||||
// Next should be blocked
|
||||
assert.False(t, rl.Allow(1), "request after limit should be blocked")
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+85
-59
@@ -8,6 +8,7 @@ import (
|
||||
"net"
|
||||
"os"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/lolcathost/internal/config"
|
||||
@@ -48,22 +49,31 @@ func NewServer(socketPath string, cfgManager *config.Manager) *Server {
|
||||
// Start starts the server.
|
||||
func (s *Server) Start() error {
|
||||
// Remove existing socket
|
||||
os.Remove(s.socketPath)
|
||||
_ = os.Remove(s.socketPath)
|
||||
|
||||
// Set umask to create socket with restricted permissions (0660)
|
||||
// This prevents TOCTOU vulnerability between socket creation and chmod
|
||||
oldUmask := syscall.Umask(0117) // 0777 & ~0117 = 0660
|
||||
|
||||
listener, err := net.Listen("unix", s.socketPath)
|
||||
|
||||
// Restore original umask immediately after socket creation
|
||||
syscall.Umask(oldUmask)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to listen on socket: %w", err)
|
||||
}
|
||||
|
||||
// Set socket permissions: 0660 root:lolcathost
|
||||
if err := os.Chmod(s.socketPath, 0660); err != nil {
|
||||
listener.Close()
|
||||
return fmt.Errorf("failed to set socket permissions: %w", err)
|
||||
// Look up the lolcathost group GID dynamically
|
||||
gid, err := lookupGroupGID("lolcathost")
|
||||
if err != nil {
|
||||
// Fall back to default GID if group lookup fails
|
||||
gid = LolcathostGID
|
||||
}
|
||||
|
||||
// Set socket group to lolcathost (GID 850)
|
||||
if err := os.Chown(s.socketPath, 0, 850); err != nil {
|
||||
listener.Close()
|
||||
// Set socket group to lolcathost
|
||||
if err := os.Chown(s.socketPath, 0, gid); err != nil {
|
||||
_ = listener.Close()
|
||||
return fmt.Errorf("failed to set socket ownership: %w", err)
|
||||
}
|
||||
|
||||
@@ -94,13 +104,13 @@ func (s *Server) Stop() error {
|
||||
close(s.stopCh)
|
||||
|
||||
if s.listener != nil {
|
||||
s.listener.Close()
|
||||
_ = s.listener.Close()
|
||||
}
|
||||
|
||||
os.Remove(s.socketPath)
|
||||
_ = os.Remove(s.socketPath)
|
||||
|
||||
if s.auditLogger != nil {
|
||||
s.auditLogger.Close()
|
||||
_ = s.auditLogger.Close()
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -125,6 +135,9 @@ func (s *Server) acceptLoop() {
|
||||
// LolcathostGID is the group ID for the lolcathost group.
|
||||
const LolcathostGID = 850
|
||||
|
||||
// connectionReadTimeout is the maximum time to wait for a client to send data.
|
||||
const connectionReadTimeout = 30 * time.Second
|
||||
|
||||
func (s *Server) handleConnection(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
@@ -133,7 +146,7 @@ func (s *Server) handleConnection(conn net.Conn) {
|
||||
|
||||
// Authorization check: verify peer is authorized
|
||||
if !s.isAuthorized(creds) {
|
||||
s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeUnauthorized, "unauthorized: user not in lolcathost group"))
|
||||
_ = s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeUnauthorized, "unauthorized: user not in lolcathost group"))
|
||||
if s.auditLogger != nil {
|
||||
var uid uint32
|
||||
var pid int32
|
||||
@@ -148,6 +161,11 @@ func (s *Server) handleConnection(conn net.Conn) {
|
||||
|
||||
reader := bufio.NewReader(conn)
|
||||
for {
|
||||
// Set read deadline to prevent clients from hanging indefinitely
|
||||
if err := conn.SetReadDeadline(time.Now().Add(connectionReadTimeout)); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
line, err := reader.ReadBytes('\n')
|
||||
if err != nil {
|
||||
return
|
||||
@@ -155,13 +173,17 @@ func (s *Server) handleConnection(conn net.Conn) {
|
||||
|
||||
var req protocol.Request
|
||||
if err := json.Unmarshal(line, &req); err != nil {
|
||||
s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "invalid JSON"))
|
||||
if err := s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeInvalidRequest, "invalid JSON")); err != nil {
|
||||
return // Connection error, stop handling
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Rate limiting
|
||||
if creds != nil && !s.rateLimiter.Allow(creds.PID) {
|
||||
s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeRateLimited, "rate limit exceeded"))
|
||||
if err := s.writeResponse(conn, protocol.NewErrorResponse(protocol.ErrCodeRateLimited, "rate limit exceeded")); err != nil {
|
||||
return // Connection error, stop handling
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -170,7 +192,9 @@ func (s *Server) handleConnection(conn net.Conn) {
|
||||
s.mu.Unlock()
|
||||
|
||||
resp := s.handleRequest(&req, creds)
|
||||
s.writeResponse(conn, resp)
|
||||
if err := s.writeResponse(conn, resp); err != nil {
|
||||
return // Connection error, stop handling
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,10 +221,16 @@ func (s *Server) isAuthorized(creds *PeerCredentials) bool {
|
||||
return isUserInGroup(creds.UID, LolcathostGID)
|
||||
}
|
||||
|
||||
func (s *Server) writeResponse(conn net.Conn, resp *protocol.Response) {
|
||||
data, _ := json.Marshal(resp)
|
||||
func (s *Server) writeResponse(conn net.Conn, resp *protocol.Response) error {
|
||||
data, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal response: %w", err)
|
||||
}
|
||||
data = append(data, '\n')
|
||||
conn.Write(data)
|
||||
if _, err := conn.Write(data); err != nil {
|
||||
return fmt.Errorf("failed to write response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) handleRequest(req *protocol.Request, creds *PeerCredentials) *protocol.Response {
|
||||
@@ -426,14 +456,9 @@ func (s *Server) handleSet(req *protocol.Request) *protocol.Response {
|
||||
// Update config
|
||||
cfg.SetHostEnabled(payload.Alias, payload.Enabled)
|
||||
|
||||
// Save config
|
||||
if err := s.config.Save(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
|
||||
}
|
||||
|
||||
// Sync to hosts file
|
||||
if err := s.syncHostsFile(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
|
||||
// Save and sync with rollback on failure
|
||||
if err := s.saveAndSync(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
|
||||
}
|
||||
|
||||
resp, _ := protocol.NewOKResponse(protocol.SetData{
|
||||
@@ -467,14 +492,9 @@ func (s *Server) handlePreset(req *protocol.Request) *protocol.Response {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeNotFound, err.Error())
|
||||
}
|
||||
|
||||
// Save config
|
||||
if err := s.config.Save(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
|
||||
}
|
||||
|
||||
// Sync to hosts file
|
||||
if err := s.syncHostsFile(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
|
||||
// Save and sync with rollback on failure
|
||||
if err := s.saveAndSync(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
|
||||
}
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"preset": payload.Name, "applied": "true"})
|
||||
@@ -492,7 +512,7 @@ func (s *Server) handleRollback(req *protocol.Request) *protocol.Response {
|
||||
}
|
||||
|
||||
// Flush DNS after restore
|
||||
s.flusher.Flush()
|
||||
_ = s.flusher.Flush()
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"restored": payload.BackupName})
|
||||
return resp
|
||||
@@ -572,14 +592,9 @@ func (s *Server) handleAdd(req *protocol.Request) *protocol.Response {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeConflict, err.Error())
|
||||
}
|
||||
|
||||
// Save config
|
||||
if err := s.config.Save(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
|
||||
}
|
||||
|
||||
// Sync to hosts file
|
||||
if err := s.syncHostsFile(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
|
||||
// Save and sync with rollback on failure
|
||||
if err := s.saveAndSync(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
|
||||
}
|
||||
|
||||
resp, _ := protocol.NewOKResponse(protocol.SetData{
|
||||
@@ -609,14 +624,9 @@ func (s *Server) handleDelete(req *protocol.Request) *protocol.Response {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeNotFound, fmt.Sprintf("alias not found: %s", payload.Alias))
|
||||
}
|
||||
|
||||
// Save config
|
||||
if err := s.config.Save(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
|
||||
}
|
||||
|
||||
// Sync to hosts file
|
||||
if err := s.syncHostsFile(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
|
||||
// Save and sync with rollback on failure
|
||||
if err := s.saveAndSync(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
|
||||
}
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"deleted": payload.Alias})
|
||||
@@ -670,14 +680,9 @@ func (s *Server) handleDeleteGroup(req *protocol.Request) *protocol.Response {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeNotFound, err.Error())
|
||||
}
|
||||
|
||||
// Save config
|
||||
if err := s.config.Save(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to save config: %v", err))
|
||||
}
|
||||
|
||||
// Sync to hosts file
|
||||
if err := s.syncHostsFile(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, fmt.Sprintf("failed to sync hosts: %v", err))
|
||||
// Save and sync with rollback on failure
|
||||
if err := s.saveAndSync(); err != nil {
|
||||
return protocol.NewErrorResponse(protocol.ErrCodeInternalError, err.Error())
|
||||
}
|
||||
|
||||
resp, _ := protocol.NewOKResponse(map[string]string{"deleted": payload.Name})
|
||||
@@ -823,3 +828,24 @@ func (s *Server) syncHostsFile() error {
|
||||
// Flush DNS cache
|
||||
return s.flusher.Flush()
|
||||
}
|
||||
|
||||
// saveAndSync saves the configuration and syncs to /etc/hosts atomically.
|
||||
// If sync fails, it attempts to reload the previous config from disk.
|
||||
func (s *Server) saveAndSync() error {
|
||||
// Save config
|
||||
if err := s.config.Save(); err != nil {
|
||||
return fmt.Errorf("failed to save config: %w", err)
|
||||
}
|
||||
|
||||
// Sync to hosts file
|
||||
if err := s.syncHostsFile(); err != nil {
|
||||
// Attempt to reload previous config on sync failure
|
||||
if reloadErr := s.config.Reload(); reloadErr != nil {
|
||||
// Log reload failure but return original sync error
|
||||
fmt.Fprintf(os.Stderr, "warning: failed to reload config after sync failure: %v\n", reloadErr)
|
||||
}
|
||||
return fmt.Errorf("failed to sync hosts (config rolled back): %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,771 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/lolcathost/internal/config"
|
||||
"github.com/lukaszraczylo/lolcathost/internal/protocol"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func setupTestServer(t *testing.T) (*Server, string, func()) {
|
||||
tmpDir := t.TempDir()
|
||||
socketPath := filepath.Join(tmpDir, "test.sock")
|
||||
configPath := filepath.Join(tmpDir, "config.yaml")
|
||||
hostsPath := filepath.Join(tmpDir, "hosts")
|
||||
backupDir := filepath.Join(tmpDir, "backups")
|
||||
|
||||
// Create initial hosts file
|
||||
err := os.WriteFile(hostsPath, []byte("127.0.0.1\tlocalhost\n"), 0644)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create config
|
||||
err = config.CreateDefault(configPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
cfgManager := config.NewManager(configPath)
|
||||
err = cfgManager.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
server := &Server{
|
||||
socketPath: socketPath,
|
||||
config: cfgManager,
|
||||
hosts: newHostsManagerWithPaths(hostsPath, backupDir),
|
||||
flusher: NewDNSFlusher(FlushMethodAuto),
|
||||
rateLimiter: NewRateLimiter(100, time.Minute),
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
cleanup := func() {
|
||||
server.Stop()
|
||||
}
|
||||
|
||||
return server, tmpDir, cleanup
|
||||
}
|
||||
|
||||
func TestServer_HandlePing(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp := server.handlePing()
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
}
|
||||
|
||||
func TestServer_HandleStatus(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp := server.handleStatus()
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
|
||||
var data protocol.StatusData
|
||||
err := resp.ParseData(&data)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.True(t, data.Running)
|
||||
}
|
||||
|
||||
func TestServer_HandleList(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp := server.handleList()
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
|
||||
var data protocol.ListData
|
||||
err := resp.ParseData(&data)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NotNil(t, data.Entries)
|
||||
}
|
||||
|
||||
func TestServer_HandleSet(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// First add a host to set
|
||||
cfg := server.config.Get()
|
||||
cfg.AddHost("test.local", "127.0.0.1", "test-local", "default", false)
|
||||
server.config.Save()
|
||||
|
||||
t.Run("enable host", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestSet, protocol.SetPayload{
|
||||
Alias: "test-local",
|
||||
Enabled: true,
|
||||
})
|
||||
resp := server.handleSet(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("disable host", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestSet, protocol.SetPayload{
|
||||
Alias: "test-local",
|
||||
Enabled: false,
|
||||
})
|
||||
resp := server.handleSet(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("nonexistent host", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestSet, protocol.SetPayload{
|
||||
Alias: "nonexistent",
|
||||
Enabled: true,
|
||||
})
|
||||
resp := server.handleSet(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeNotFound, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestSet,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleSet(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleAdd(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
t.Run("valid host", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestAdd, protocol.AddPayload{
|
||||
Domain: "newhost.local",
|
||||
IP: "127.0.0.1",
|
||||
Group: "default",
|
||||
})
|
||||
resp := server.handleAdd(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("duplicate alias", func(t *testing.T) {
|
||||
// When alias is explicitly provided, duplicates are rejected
|
||||
req, _ := protocol.NewRequest(protocol.RequestAdd, protocol.AddPayload{
|
||||
Domain: "another.local",
|
||||
IP: "127.0.0.1",
|
||||
Alias: "newhost-local", // Same alias as auto-generated for newhost.local
|
||||
Group: "default",
|
||||
})
|
||||
resp := server.handleAdd(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeConflict, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("blocked domain", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestAdd, protocol.AddPayload{
|
||||
Domain: "apple.com",
|
||||
IP: "127.0.0.1",
|
||||
Group: "default",
|
||||
})
|
||||
resp := server.handleAdd(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeBlockedDomain, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("invalid domain", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestAdd, protocol.AddPayload{
|
||||
Domain: "",
|
||||
IP: "127.0.0.1",
|
||||
Group: "default",
|
||||
})
|
||||
resp := server.handleAdd(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("empty IP", func(t *testing.T) {
|
||||
// Only empty IP is rejected, format is not validated
|
||||
req, _ := protocol.NewRequest(protocol.RequestAdd, protocol.AddPayload{
|
||||
Domain: "valid.local",
|
||||
IP: "",
|
||||
Group: "default",
|
||||
})
|
||||
resp := server.handleAdd(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeInvalidIP, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestAdd,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleAdd(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleDelete(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Add a host first
|
||||
cfg := server.config.Get()
|
||||
cfg.AddHost("todelete.local", "127.0.0.1", "todelete", "default", false)
|
||||
server.config.Save()
|
||||
|
||||
t.Run("delete existing", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestDelete, protocol.DeletePayload{
|
||||
Alias: "todelete",
|
||||
})
|
||||
resp := server.handleDelete(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("verify deleted entry not in list", func(t *testing.T) {
|
||||
// After delete, list should not contain the deleted entry
|
||||
resp := server.handleList()
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
|
||||
var data protocol.ListData
|
||||
err := resp.ParseData(&data)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Check that the deleted entry is not in the list
|
||||
for _, entry := range data.Entries {
|
||||
assert.NotEqual(t, "todelete", entry.Alias, "deleted entry should not appear in list")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("delete nonexistent", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestDelete, protocol.DeletePayload{
|
||||
Alias: "nonexistent",
|
||||
})
|
||||
resp := server.handleDelete(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeNotFound, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestDelete,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleDelete(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleSync(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp := server.handleSync()
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
}
|
||||
|
||||
func TestServer_HandleBackups(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Create a backup first
|
||||
server.hosts.CreateBackup()
|
||||
|
||||
resp := server.handleBackups()
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
|
||||
var data protocol.BackupsData
|
||||
err := resp.ParseData(&data)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, data.Backups)
|
||||
}
|
||||
|
||||
func TestServer_HandleAddGroup(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
t.Run("add new group", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestAddGroup, protocol.GroupPayload{
|
||||
Name: "newgroup",
|
||||
})
|
||||
resp := server.handleAddGroup(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("add duplicate group", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestAddGroup, protocol.GroupPayload{
|
||||
Name: "newgroup",
|
||||
})
|
||||
resp := server.handleAddGroup(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeConflict, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("empty name", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestAddGroup, protocol.GroupPayload{
|
||||
Name: "",
|
||||
})
|
||||
resp := server.handleAddGroup(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestAddGroup,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleAddGroup(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleDeleteGroup(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Add a group first
|
||||
cfg := server.config.Get()
|
||||
cfg.AddGroup("todeletegroup")
|
||||
server.config.Save()
|
||||
|
||||
t.Run("delete existing group", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestDeleteGroup, protocol.GroupPayload{
|
||||
Name: "todeletegroup",
|
||||
})
|
||||
resp := server.handleDeleteGroup(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("delete nonexistent group", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestDeleteGroup, protocol.GroupPayload{
|
||||
Name: "nonexistent",
|
||||
})
|
||||
resp := server.handleDeleteGroup(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeNotFound, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestDeleteGroup,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleDeleteGroup(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleListGroups(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp := server.handleListGroups()
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
|
||||
var data protocol.GroupsData
|
||||
err := resp.ParseData(&data)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, data.Groups)
|
||||
}
|
||||
|
||||
func TestServer_HandleRenameGroup(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Add a group to rename
|
||||
cfg := server.config.Get()
|
||||
cfg.AddGroup("oldname")
|
||||
server.config.Save()
|
||||
|
||||
t.Run("rename existing group", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestRenameGroup, protocol.RenameGroupPayload{
|
||||
OldName: "oldname",
|
||||
NewName: "newname",
|
||||
})
|
||||
resp := server.handleRenameGroup(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("rename nonexistent group", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestRenameGroup, protocol.RenameGroupPayload{
|
||||
OldName: "nonexistent",
|
||||
NewName: "newname2",
|
||||
})
|
||||
resp := server.handleRenameGroup(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestRenameGroup,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleRenameGroup(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleAddPreset(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
t.Run("add new preset", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestAddPreset, protocol.AddPresetPayload{
|
||||
Name: "newpreset",
|
||||
Enable: []string{"alias1"},
|
||||
Disable: []string{"alias2"},
|
||||
})
|
||||
resp := server.handleAddPreset(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("add duplicate preset", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestAddPreset, protocol.AddPresetPayload{
|
||||
Name: "newpreset",
|
||||
Enable: []string{"alias1"},
|
||||
Disable: []string{"alias2"},
|
||||
})
|
||||
resp := server.handleAddPreset(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeConflict, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("empty name", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestAddPreset, protocol.AddPresetPayload{
|
||||
Name: "",
|
||||
})
|
||||
resp := server.handleAddPreset(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestAddPreset,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleAddPreset(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleDeletePreset(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Add a preset first
|
||||
cfg := server.config.Get()
|
||||
cfg.AddPreset("todeletepreset", []string{"a"}, []string{"b"})
|
||||
server.config.Save()
|
||||
|
||||
t.Run("delete existing preset", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestDeletePreset, protocol.PresetPayload{
|
||||
Name: "todeletepreset",
|
||||
})
|
||||
resp := server.handleDeletePreset(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("delete nonexistent preset", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestDeletePreset, protocol.PresetPayload{
|
||||
Name: "nonexistent",
|
||||
})
|
||||
resp := server.handleDeletePreset(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeNotFound, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestDeletePreset,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleDeletePreset(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleListPresets(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
resp := server.handleListPresets()
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
|
||||
var data protocol.PresetsData
|
||||
err := resp.ParseData(&data)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, data.Presets)
|
||||
}
|
||||
|
||||
func TestServer_HandlePreset(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Add hosts and preset
|
||||
cfg := server.config.Get()
|
||||
cfg.AddHost("host1.local", "127.0.0.1", "host1", "default", false)
|
||||
cfg.AddHost("host2.local", "127.0.0.1", "host2", "default", false)
|
||||
cfg.AddPreset("testpreset", []string{"host1"}, []string{"host2"})
|
||||
server.config.Save()
|
||||
|
||||
t.Run("apply existing preset", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestPreset, protocol.PresetPayload{
|
||||
Name: "testpreset",
|
||||
})
|
||||
resp := server.handlePreset(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("apply nonexistent preset", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestPreset, protocol.PresetPayload{
|
||||
Name: "nonexistent",
|
||||
})
|
||||
resp := server.handlePreset(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeNotFound, resp.Code)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestPreset,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handlePreset(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleRollback(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Create a backup first
|
||||
server.hosts.CreateBackup()
|
||||
backups, _ := server.hosts.ListBackups()
|
||||
require.NotEmpty(t, backups)
|
||||
|
||||
t.Run("rollback to existing backup", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestRollback, protocol.RollbackPayload{
|
||||
BackupName: backups[0].Name,
|
||||
})
|
||||
resp := server.handleRollback(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("rollback to nonexistent backup", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestRollback, protocol.RollbackPayload{
|
||||
BackupName: "nonexistent.bak",
|
||||
})
|
||||
resp := server.handleRollback(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestRollback,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleRollback(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleBackupContent(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
// Create a backup first
|
||||
server.hosts.CreateBackup()
|
||||
backups, _ := server.hosts.ListBackups()
|
||||
require.NotEmpty(t, backups)
|
||||
|
||||
t.Run("get existing backup content", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestBackupContent, protocol.BackupContentPayload{
|
||||
BackupName: backups[0].Name,
|
||||
})
|
||||
resp := server.handleBackupContent(req)
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
|
||||
var data protocol.BackupContentData
|
||||
err := resp.ParseData(&data)
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, data.Content)
|
||||
})
|
||||
|
||||
t.Run("get nonexistent backup content", func(t *testing.T) {
|
||||
req, _ := protocol.NewRequest(protocol.RequestBackupContent, protocol.BackupContentPayload{
|
||||
BackupName: "nonexistent.bak",
|
||||
})
|
||||
resp := server.handleBackupContent(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
|
||||
t.Run("invalid payload", func(t *testing.T) {
|
||||
req := &protocol.Request{
|
||||
Type: protocol.RequestBackupContent,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
resp := server.handleBackupContent(req)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_HandleRequest_UnknownType(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
req := &protocol.Request{
|
||||
Type: "unknown_type",
|
||||
}
|
||||
creds := &PeerCredentials{UID: 0, GID: 0, PID: 1}
|
||||
resp := server.handleRequest(req, creds)
|
||||
assert.Equal(t, "error", resp.Status)
|
||||
assert.Equal(t, protocol.ErrCodeInvalidRequest, resp.Code)
|
||||
}
|
||||
|
||||
func TestServer_IsAuthorized(t *testing.T) {
|
||||
server, _, cleanup := setupTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
t.Run("root user", func(t *testing.T) {
|
||||
creds := &PeerCredentials{UID: 0, GID: 0, PID: 1}
|
||||
assert.True(t, server.isAuthorized(creds))
|
||||
})
|
||||
|
||||
t.Run("nil credentials", func(t *testing.T) {
|
||||
assert.False(t, server.isAuthorized(nil))
|
||||
})
|
||||
}
|
||||
|
||||
func TestServer_StartStop(t *testing.T) {
|
||||
// Skip test if not running as root (server.Start requires root to chown socket)
|
||||
if os.Getuid() != 0 {
|
||||
t.Skip("Test requires root privileges to create socket with proper ownership")
|
||||
}
|
||||
|
||||
server, _, _ := setupTestServer(t)
|
||||
// Don't use cleanup since we manually call Stop
|
||||
|
||||
// Start server in goroutine
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- server.Start()
|
||||
}()
|
||||
|
||||
// Give it time to start
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// Verify socket exists
|
||||
_, err := os.Stat(server.socketPath)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Stop server
|
||||
err = server.Stop()
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify socket is removed
|
||||
_, err = os.Stat(server.socketPath)
|
||||
assert.True(t, os.IsNotExist(err))
|
||||
}
|
||||
|
||||
func TestServer_AcceptConnection(t *testing.T) {
|
||||
// Skip test if not running as root (server.Start requires root to chown socket)
|
||||
if os.Getuid() != 0 {
|
||||
t.Skip("Test requires root privileges to create socket with proper ownership")
|
||||
}
|
||||
|
||||
server, _, _ := setupTestServer(t)
|
||||
// Don't use cleanup - manually stop
|
||||
|
||||
// Start server
|
||||
go server.Start()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
defer server.Stop()
|
||||
|
||||
// Connect to server
|
||||
conn, err := net.Dial("unix", server.socketPath)
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
// Send ping request
|
||||
req, _ := protocol.NewRequest(protocol.RequestPing, nil)
|
||||
encoder := json.NewEncoder(conn)
|
||||
err = encoder.Encode(req)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Read response
|
||||
decoder := json.NewDecoder(conn)
|
||||
var resp protocol.Response
|
||||
err = decoder.Decode(&resp)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "ok", resp.Status)
|
||||
}
|
||||
|
||||
// Benchmarks
|
||||
|
||||
func BenchmarkServer_HandlePing(b *testing.B) {
|
||||
tmpDir := b.TempDir()
|
||||
configPath := filepath.Join(tmpDir, "config.yaml")
|
||||
config.CreateDefault(configPath)
|
||||
cfgManager := config.NewManager(configPath)
|
||||
cfgManager.Load()
|
||||
|
||||
server := &Server{
|
||||
config: cfgManager,
|
||||
rateLimiter: NewRateLimiter(100000, time.Minute),
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
server.handlePing()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkServer_HandleList(b *testing.B) {
|
||||
tmpDir := b.TempDir()
|
||||
configPath := filepath.Join(tmpDir, "config.yaml")
|
||||
config.CreateDefault(configPath)
|
||||
cfgManager := config.NewManager(configPath)
|
||||
cfgManager.Load()
|
||||
|
||||
server := &Server{
|
||||
config: cfgManager,
|
||||
rateLimiter: NewRateLimiter(100000, time.Minute),
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
server.handleList()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkServer_HandleSet(b *testing.B) {
|
||||
tmpDir := b.TempDir()
|
||||
configPath := filepath.Join(tmpDir, "config.yaml")
|
||||
hostsPath := filepath.Join(tmpDir, "hosts")
|
||||
backupDir := filepath.Join(tmpDir, "backups")
|
||||
|
||||
os.WriteFile(hostsPath, []byte("127.0.0.1\tlocalhost\n"), 0644)
|
||||
config.CreateDefault(configPath)
|
||||
cfgManager := config.NewManager(configPath)
|
||||
cfgManager.Load()
|
||||
|
||||
// Add a test host
|
||||
cfg := cfgManager.Get()
|
||||
cfg.AddHost("bench.local", "127.0.0.1", "bench-local", "default", false)
|
||||
|
||||
server := &Server{
|
||||
config: cfgManager,
|
||||
hosts: newHostsManagerWithPaths(hostsPath, backupDir),
|
||||
flusher: NewDNSFlusher(FlushMethodAuto),
|
||||
rateLimiter: NewRateLimiter(100000, time.Minute),
|
||||
}
|
||||
|
||||
req, _ := protocol.NewRequest(protocol.RequestSet, protocol.SetPayload{
|
||||
Alias: "bench-local",
|
||||
Enabled: true,
|
||||
})
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
server.handleSet(req)
|
||||
}
|
||||
}
|
||||
@@ -168,7 +168,7 @@ func (i *Installer) Uninstall() error {
|
||||
}
|
||||
|
||||
// Remove socket
|
||||
os.Remove(SocketPath)
|
||||
_ = os.Remove(SocketPath)
|
||||
|
||||
// Note: We don't remove the group, logs, or backups
|
||||
// The user may want to keep these
|
||||
@@ -210,14 +210,14 @@ func (i *Installer) createGroup() error {
|
||||
|
||||
func (i *Installer) createGroupDarwin() error {
|
||||
// Check if group exists
|
||||
if _, err := exec.Command("dscl", ".", "-read", "/Groups/"+GroupName).Output(); err == nil {
|
||||
if _, err := exec.Command("dscl", ".", "-read", "/Groups/"+GroupName).Output(); err == nil { // #nosec G204 - Commands use hardcoded safe values
|
||||
i.log(" Group '%s' already exists", GroupName)
|
||||
return nil
|
||||
}
|
||||
|
||||
i.log(" Creating group '%s' (GID %d)...", GroupName, GroupGID)
|
||||
|
||||
// Create group
|
||||
// Create group - commands are hardcoded with constant GroupName
|
||||
cmds := [][]string{
|
||||
{"dscl", ".", "-create", "/Groups/" + GroupName},
|
||||
{"dscl", ".", "-create", "/Groups/" + GroupName, "PrimaryGroupID", strconv.Itoa(GroupGID)},
|
||||
@@ -225,6 +225,7 @@ func (i *Installer) createGroupDarwin() error {
|
||||
}
|
||||
|
||||
for _, args := range cmds {
|
||||
// #nosec G204 - Commands use hardcoded safe values
|
||||
if err := exec.Command(args[0], args[1:]...).Run(); err != nil {
|
||||
return fmt.Errorf("command %v failed: %w", args, err)
|
||||
}
|
||||
@@ -235,14 +236,14 @@ func (i *Installer) createGroupDarwin() error {
|
||||
|
||||
func (i *Installer) createGroupLinux() error {
|
||||
// Check if group exists
|
||||
if _, err := exec.Command("getent", "group", GroupName).Output(); err == nil {
|
||||
if _, err := exec.Command("getent", "group", GroupName).Output(); err == nil { // #nosec G204 - GroupName is a constant
|
||||
i.log(" Group '%s' already exists", GroupName)
|
||||
return nil
|
||||
}
|
||||
|
||||
i.log(" Creating group '%s'...", GroupName)
|
||||
|
||||
if err := exec.Command("groupadd", "-r", GroupName).Run(); err != nil {
|
||||
if err := exec.Command("groupadd", "-r", GroupName).Run(); err != nil { // #nosec G204 - GroupName is a constant
|
||||
return fmt.Errorf("groupadd failed: %w", err)
|
||||
}
|
||||
|
||||
@@ -278,7 +279,7 @@ func (i *Installer) addCurrentUserToGroup() error {
|
||||
|
||||
func (i *Installer) addUserToGroupDarwin(username string) error {
|
||||
// Check if user is already in group
|
||||
output, err := exec.Command("dscl", ".", "-read", "/Groups/"+GroupName, "GroupMembership").Output()
|
||||
output, err := exec.Command("dscl", ".", "-read", "/Groups/"+GroupName, "GroupMembership").Output() // #nosec G204 - GroupName is a constant
|
||||
if err == nil && strings.Contains(string(output), username) {
|
||||
i.log(" User '%s' already in group '%s'", username, GroupName)
|
||||
return nil
|
||||
@@ -286,7 +287,7 @@ func (i *Installer) addUserToGroupDarwin(username string) error {
|
||||
|
||||
i.log(" Adding user '%s' to group '%s'...", username, GroupName)
|
||||
|
||||
if err := exec.Command("dscl", ".", "-append", "/Groups/"+GroupName, "GroupMembership", username).Run(); err != nil {
|
||||
if err := exec.Command("dscl", ".", "-append", "/Groups/"+GroupName, "GroupMembership", username).Run(); err != nil { // #nosec G204 - GroupName is a constant, username from SUDO_USER env
|
||||
return fmt.Errorf("failed to add user to group: %w", err)
|
||||
}
|
||||
|
||||
@@ -295,7 +296,7 @@ func (i *Installer) addUserToGroupDarwin(username string) error {
|
||||
|
||||
func (i *Installer) addUserToGroupLinux(username string) error {
|
||||
// Check if user is already in group
|
||||
output, err := exec.Command("id", "-nG", username).Output()
|
||||
output, err := exec.Command("id", "-nG", username).Output() // #nosec G204 - username from SUDO_USER env or current user
|
||||
if err == nil && strings.Contains(string(output), GroupName) {
|
||||
i.log(" User '%s' already in group '%s'", username, GroupName)
|
||||
return nil
|
||||
@@ -303,7 +304,7 @@ func (i *Installer) addUserToGroupLinux(username string) error {
|
||||
|
||||
i.log(" Adding user '%s' to group '%s'...", username, GroupName)
|
||||
|
||||
if err := exec.Command("usermod", "-aG", GroupName, username).Run(); err != nil {
|
||||
if err := exec.Command("usermod", "-aG", GroupName, username).Run(); err != nil { // #nosec G204 - GroupName is a constant, username from SUDO_USER env
|
||||
return fmt.Errorf("failed to add user to group: %w", err)
|
||||
}
|
||||
|
||||
@@ -315,6 +316,7 @@ func (i *Installer) createDirectories() error {
|
||||
|
||||
for _, dir := range dirs {
|
||||
i.log(" Creating directory '%s'...", dir)
|
||||
// #nosec G301 - System directories are intentionally 0755
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create %s: %w", dir, err)
|
||||
}
|
||||
@@ -340,28 +342,29 @@ func (i *Installer) installLaunchDaemon() error {
|
||||
|
||||
// Unload if already loaded (do this before writing plist)
|
||||
i.log(" Stopping existing daemon if running...")
|
||||
exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run()
|
||||
_ = exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run() // #nosec G204 - Hardcoded service name
|
||||
|
||||
// Give launchd time to fully unload the service
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
// Remove old plist to ensure clean state
|
||||
os.Remove(plistPath)
|
||||
_ = os.Remove(plistPath)
|
||||
|
||||
i.log(" Writing LaunchDaemon plist...")
|
||||
// #nosec G306 - Plist file permissions are intentionally 0644
|
||||
if err := os.WriteFile(plistPath, []byte(plistContent), 0644); err != nil {
|
||||
return fmt.Errorf("failed to write plist: %w", err)
|
||||
}
|
||||
|
||||
// Bootstrap the daemon
|
||||
i.log(" Starting daemon...")
|
||||
cmd := exec.Command("launchctl", "bootstrap", "system", plistPath)
|
||||
cmd := exec.Command("launchctl", "bootstrap", "system", plistPath) // #nosec G204 - plistPath is constructed from constants
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
// Exit code 5 means "service already loaded" - try kickstart instead
|
||||
if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 5 {
|
||||
i.log(" Service already registered, restarting...")
|
||||
if err := exec.Command("launchctl", "kickstart", "-k", "system/com.lolcathost.daemon").Run(); err != nil {
|
||||
if err := exec.Command("launchctl", "kickstart", "-k", "system/com.lolcathost.daemon").Run(); err != nil { // #nosec G204 - Hardcoded service name
|
||||
return fmt.Errorf("failed to restart daemon: %w", err)
|
||||
}
|
||||
return nil
|
||||
@@ -376,10 +379,10 @@ func (i *Installer) uninstallLaunchDaemon() {
|
||||
plistPath := filepath.Join(LaunchDaemonDir, "com.lolcathost.daemon.plist")
|
||||
|
||||
i.log(" Stopping daemon...")
|
||||
exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run()
|
||||
_ = exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run() // #nosec G204 - Hardcoded service name
|
||||
|
||||
i.log(" Removing LaunchDaemon plist...")
|
||||
os.Remove(plistPath)
|
||||
_ = os.Remove(plistPath)
|
||||
}
|
||||
|
||||
func (i *Installer) installSystemdService() error {
|
||||
@@ -387,19 +390,20 @@ func (i *Installer) installSystemdService() error {
|
||||
unitContent := fmt.Sprintf(SystemdUnit, i.binaryPath)
|
||||
|
||||
i.log(" Writing systemd unit...")
|
||||
// #nosec G306 - Unit file permissions are intentionally 0644
|
||||
if err := os.WriteFile(unitPath, []byte(unitContent), 0644); err != nil {
|
||||
return fmt.Errorf("failed to write unit file: %w", err)
|
||||
}
|
||||
|
||||
// Reload systemd
|
||||
i.log(" Reloading systemd...")
|
||||
if err := exec.Command("systemctl", "daemon-reload").Run(); err != nil {
|
||||
if err := exec.Command("systemctl", "daemon-reload").Run(); err != nil { // #nosec G204 - Hardcoded systemctl command
|
||||
return fmt.Errorf("failed to reload systemd: %w", err)
|
||||
}
|
||||
|
||||
// Enable and start the service
|
||||
i.log(" Enabling and starting service...")
|
||||
if err := exec.Command("systemctl", "enable", "--now", "lolcathost.service").Run(); err != nil {
|
||||
if err := exec.Command("systemctl", "enable", "--now", "lolcathost.service").Run(); err != nil { // #nosec G204 - Hardcoded service name
|
||||
return fmt.Errorf("failed to enable service: %w", err)
|
||||
}
|
||||
|
||||
@@ -408,12 +412,12 @@ func (i *Installer) installSystemdService() error {
|
||||
|
||||
func (i *Installer) uninstallSystemdService() {
|
||||
i.log(" Stopping and disabling service...")
|
||||
exec.Command("systemctl", "disable", "--now", "lolcathost.service").Run()
|
||||
_ = exec.Command("systemctl", "disable", "--now", "lolcathost.service").Run() // #nosec G204 - Hardcoded service name
|
||||
|
||||
i.log(" Removing systemd unit...")
|
||||
os.Remove(filepath.Join(SystemdDir, "lolcathost.service"))
|
||||
_ = os.Remove(filepath.Join(SystemdDir, "lolcathost.service"))
|
||||
|
||||
exec.Command("systemctl", "daemon-reload").Run()
|
||||
_ = exec.Command("systemctl", "daemon-reload").Run() // #nosec G204 - Hardcoded systemctl command
|
||||
}
|
||||
|
||||
func (i *Installer) createDefaultConfig() error {
|
||||
@@ -430,6 +434,7 @@ func (i *Installer) createDefaultConfig() error {
|
||||
|
||||
// Create config directory
|
||||
configDir := filepath.Dir(configPath)
|
||||
// #nosec G301 - Config directory permissions are intentionally 0755
|
||||
if err := os.MkdirAll(configDir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
|
||||
+140
-31
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"github.com/lukaszraczylo/lolcathost/internal/client"
|
||||
"github.com/lukaszraczylo/lolcathost/internal/config"
|
||||
@@ -27,6 +28,7 @@ const (
|
||||
ViewBackups
|
||||
ViewHelp
|
||||
ViewSearch
|
||||
ViewConfirmDelete
|
||||
)
|
||||
|
||||
// Model is the main Bubble Tea model.
|
||||
@@ -45,13 +47,14 @@ type Model struct {
|
||||
searchInput textinput.Model
|
||||
|
||||
// State
|
||||
width int
|
||||
height int
|
||||
message string
|
||||
messageStyle string // "error" or "success"
|
||||
messageTime time.Time
|
||||
searchTerm string
|
||||
allGroups []string // All groups including empty ones
|
||||
width int
|
||||
height int
|
||||
message string
|
||||
messageStyle string // "error" or "success"
|
||||
messageTime time.Time
|
||||
searchTerm string
|
||||
allGroups []string // All groups including empty ones
|
||||
pendingDeleteAlias string // Alias of host pending delete confirmation
|
||||
|
||||
// Update notification
|
||||
updateAvailable bool
|
||||
@@ -351,8 +354,9 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
m.setError(fmt.Sprintf("Refresh failed: %v", msg.err))
|
||||
// Mark as disconnected to trigger reconnect
|
||||
m.connected = false
|
||||
m.client.Close()
|
||||
} else if msg.entries != nil {
|
||||
_ = m.client.Close()
|
||||
} else {
|
||||
// Always update the list, even if entries is nil/empty
|
||||
m.list.SetItems(msg.entries)
|
||||
}
|
||||
|
||||
@@ -385,7 +389,10 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
m.mode = ViewList
|
||||
|
||||
case deleteMsg:
|
||||
// Clear pending state regardless of success/failure
|
||||
m.list.SetPending(msg.alias, false)
|
||||
if msg.err != nil {
|
||||
m.list.SetError(msg.alias, true)
|
||||
m.setError(fmt.Sprintf("Delete failed: %v", msg.err))
|
||||
} else {
|
||||
cmds = append(cmds, m.refresh())
|
||||
@@ -521,6 +528,8 @@ func (m *Model) handleKey(msg tea.KeyMsg) tea.Cmd {
|
||||
return m.handleHelpKey(msg)
|
||||
case ViewSearch:
|
||||
return m.handleSearchKey(msg)
|
||||
case ViewConfirmDelete:
|
||||
return m.handleConfirmDeleteKey(msg)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -554,7 +563,8 @@ func (m *Model) handleListKey(msg tea.KeyMsg) tea.Cmd {
|
||||
}
|
||||
case "d":
|
||||
if item := m.list.Selected(); item != nil {
|
||||
return m.deleteHost(item.Entry.Alias)
|
||||
m.pendingDeleteAlias = item.Entry.Alias
|
||||
m.mode = ViewConfirmDelete
|
||||
}
|
||||
case "p":
|
||||
m.mode = ViewPresets
|
||||
@@ -593,7 +603,7 @@ func (m *Model) handleFormKey(msg tea.KeyMsg) tea.Cmd {
|
||||
oldAlias := m.form.EditAlias()
|
||||
return tea.Sequence(
|
||||
func() tea.Msg {
|
||||
m.client.Delete(oldAlias)
|
||||
_ = m.client.Delete(oldAlias)
|
||||
return nil
|
||||
},
|
||||
m.addHost(domain, ip, "", group), // Empty alias = auto-generate
|
||||
@@ -668,7 +678,7 @@ func (m *Model) handlePresetFormKey(msg tea.KeyMsg) tea.Cmd {
|
||||
oldName := m.presetPicker.EditName()
|
||||
return tea.Sequence(
|
||||
func() tea.Msg {
|
||||
m.client.DeletePreset(oldName)
|
||||
_ = m.client.DeletePreset(oldName)
|
||||
return nil
|
||||
},
|
||||
m.addPreset(name, enable, disable),
|
||||
@@ -850,6 +860,23 @@ func (m *Model) handleSearchKey(msg tea.KeyMsg) tea.Cmd {
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (m *Model) handleConfirmDeleteKey(msg tea.KeyMsg) tea.Cmd {
|
||||
switch msg.String() {
|
||||
case "y", "Y":
|
||||
alias := m.pendingDeleteAlias
|
||||
m.pendingDeleteAlias = ""
|
||||
m.mode = ViewList
|
||||
// Set pending state for visual feedback
|
||||
m.list.SetPending(alias, true)
|
||||
return m.deleteHost(alias)
|
||||
case "n", "N", "esc":
|
||||
m.pendingDeleteAlias = ""
|
||||
m.mode = ViewList
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Model) toggleSelected() tea.Cmd {
|
||||
item := m.list.Selected()
|
||||
if item == nil {
|
||||
@@ -904,6 +931,8 @@ func (m *Model) View() string {
|
||||
sb.WriteString(m.helpView())
|
||||
case ViewSearch:
|
||||
sb.WriteString(m.searchView())
|
||||
case ViewConfirmDelete:
|
||||
sb.WriteString(m.confirmDeleteView())
|
||||
}
|
||||
|
||||
// Message
|
||||
@@ -920,8 +949,15 @@ func (m *Model) View() string {
|
||||
currentContent := sb.String()
|
||||
currentLines := strings.Count(currentContent, "\n") + 1
|
||||
|
||||
// Fill space to push footer to bottom (reserve 3 lines for footer)
|
||||
footerHeight := 3
|
||||
// Calculate footer height dynamically (help bar lines + status bar + spacing)
|
||||
footerHeight := 2 // status bar + newline before it
|
||||
var helpBarContent string
|
||||
if m.mode == ViewList {
|
||||
helpBarContent = m.helpBar()
|
||||
helpBarLines := strings.Count(helpBarContent, "\n") + 1
|
||||
footerHeight += helpBarLines + 1 // +1 for newline before help bar
|
||||
}
|
||||
|
||||
remainingLines := m.height - currentLines - footerHeight
|
||||
if remainingLines > 0 {
|
||||
sb.WriteString(strings.Repeat("\n", remainingLines))
|
||||
@@ -930,7 +966,7 @@ func (m *Model) View() string {
|
||||
// Footer (help bar + status bar)
|
||||
if m.mode == ViewList {
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(m.helpBar())
|
||||
sb.WriteString(helpBarContent)
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(m.statusBar())
|
||||
@@ -939,19 +975,67 @@ func (m *Model) View() string {
|
||||
}
|
||||
|
||||
func (m *Model) helpBar() string {
|
||||
return helpBarStyle.Render(fmt.Sprintf("%s/%s: Navigate %s: Toggle %s: New %s: Edit %s: Delete %s: Presets %s: Groups %s: Backups %s: Search %s: Help %s: Quit",
|
||||
helpKeyStyle.Render("↑↓"),
|
||||
helpKeyStyle.Render("jk"),
|
||||
helpKeyStyle.Render("Space"),
|
||||
helpKeyStyle.Render("n"),
|
||||
helpKeyStyle.Render("e"),
|
||||
helpKeyStyle.Render("d"),
|
||||
helpKeyStyle.Render("p"),
|
||||
helpKeyStyle.Render("g"),
|
||||
helpKeyStyle.Render("b"),
|
||||
helpKeyStyle.Render("/"),
|
||||
helpKeyStyle.Render("?"),
|
||||
helpKeyStyle.Render("q")))
|
||||
// Define help items with their display widths (without ANSI codes)
|
||||
type helpItem struct {
|
||||
key string
|
||||
desc string
|
||||
rawWidth int // width without ANSI escape codes
|
||||
}
|
||||
|
||||
items := []helpItem{
|
||||
{"↑↓/jk", "Navigate", 13},
|
||||
{"Space", "Toggle", 13},
|
||||
{"n", "New", 6},
|
||||
{"e", "Edit", 7},
|
||||
{"d", "Delete", 9},
|
||||
{"p", "Presets", 10},
|
||||
{"g", "Groups", 9},
|
||||
{"b", "Backups", 10},
|
||||
{"/", "Search", 9},
|
||||
{"?", "Help", 7},
|
||||
{"q", "Quit", 7},
|
||||
}
|
||||
|
||||
separator := " "
|
||||
sepWidth := 2
|
||||
|
||||
var lines []string
|
||||
var currentLine string
|
||||
var currentWidth int
|
||||
|
||||
for i, item := range items {
|
||||
rendered := helpKeyStyle.Render(item.key) + ": " + item.desc
|
||||
|
||||
// Check if adding this item would exceed width
|
||||
newWidth := currentWidth + item.rawWidth
|
||||
if currentWidth > 0 {
|
||||
newWidth += sepWidth
|
||||
}
|
||||
|
||||
if m.width > 0 && newWidth > m.width && currentWidth > 0 {
|
||||
// Start a new line
|
||||
lines = append(lines, currentLine)
|
||||
currentLine = rendered
|
||||
currentWidth = item.rawWidth
|
||||
} else {
|
||||
// Add to current line
|
||||
if currentWidth > 0 {
|
||||
currentLine += separator
|
||||
}
|
||||
currentLine += rendered
|
||||
currentWidth = newWidth
|
||||
if i == 0 {
|
||||
currentWidth = item.rawWidth
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add the last line
|
||||
if currentLine != "" {
|
||||
lines = append(lines, currentLine)
|
||||
}
|
||||
|
||||
return helpBarStyle.Render(strings.Join(lines, "\n"))
|
||||
}
|
||||
|
||||
func (m *Model) statusBar() string {
|
||||
@@ -1022,9 +1106,34 @@ func (m *Model) searchView() string {
|
||||
return dialogStyle.Render(sb.String())
|
||||
}
|
||||
|
||||
// Run starts the TUI application.
|
||||
func Run(socketPath string) error {
|
||||
return RunWithVersion(socketPath, "dev", "", "")
|
||||
func (m *Model) confirmDeleteView() string {
|
||||
var sb strings.Builder
|
||||
|
||||
sb.WriteString(titleStyle.Render("Confirm Delete"))
|
||||
sb.WriteString("\n\n")
|
||||
|
||||
// Find the entry details for the pending delete
|
||||
var domain, ip string
|
||||
for _, item := range m.list.items {
|
||||
if item.Entry.Alias == m.pendingDeleteAlias {
|
||||
domain = item.Entry.Domain
|
||||
ip = item.Entry.IP
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
warningStyle := lipgloss.NewStyle().Foreground(colorWarning).Bold(true)
|
||||
sb.WriteString(warningStyle.Render("Are you sure you want to delete this host?"))
|
||||
sb.WriteString("\n\n")
|
||||
|
||||
sb.WriteString(fmt.Sprintf(" Alias: %s\n", helpKeyStyle.Render(m.pendingDeleteAlias)))
|
||||
sb.WriteString(fmt.Sprintf(" Domain: %s\n", helpDescStyle.Render(domain)))
|
||||
sb.WriteString(fmt.Sprintf(" IP: %s\n", helpDescStyle.Render(ip)))
|
||||
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(helpDescStyle.Render("y confirm • n/Esc cancel"))
|
||||
|
||||
return dialogStyle.Render(sb.String())
|
||||
}
|
||||
|
||||
// RunWithVersion starts the TUI application with version info for update checking.
|
||||
|
||||
@@ -174,7 +174,7 @@ func (b *BackupPicker) selectView() string {
|
||||
}
|
||||
|
||||
leftSb.WriteString("\n")
|
||||
leftSb.WriteString(helpDescStyle.Render("↑↓ navigate • Enter restore • Esc cancel"))
|
||||
leftSb.WriteString(WrapHelpText("↑↓ navigate • Enter restore • Esc cancel", 40))
|
||||
|
||||
// Build right panel (preview)
|
||||
var rightSb strings.Builder
|
||||
@@ -219,7 +219,8 @@ func (b *BackupPicker) selectView() string {
|
||||
// Show scroll indicator
|
||||
if len(lines) > previewHeight {
|
||||
rightSb.WriteString("\n")
|
||||
rightSb.WriteString(helpDescStyle.Render(fmt.Sprintf("Lines %d-%d of %d (Shift+↑↓ scroll)", b.previewScroll+1, endLine, len(lines))))
|
||||
scrollText := fmt.Sprintf("%d-%d of %d (↑↓ scroll)", b.previewScroll+1, endLine, len(lines))
|
||||
rightSb.WriteString(helpDescStyle.Render(scrollText))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -291,7 +291,7 @@ func (f *Form) View() string {
|
||||
sb.WriteString("\n\n")
|
||||
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(helpDescStyle.Render("Tab/↓ next • Shift+Tab/↑ prev • ←→ select group • Enter save • Esc cancel"))
|
||||
sb.WriteString(WrapHelpText("Tab/↓ next • Shift+Tab/↑ prev • ←→ select group • Enter save • Esc cancel", f.width-6))
|
||||
|
||||
return dialogStyle.Render(sb.String())
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@ func (g *GroupPicker) selectView() string {
|
||||
}
|
||||
|
||||
sb.WriteString("\n\n")
|
||||
sb.WriteString(helpDescStyle.Render("↑↓ navigate • n new • r rename • d delete • Esc back"))
|
||||
sb.WriteString(WrapHelpText("↑↓ navigate • n new • r rename • d delete • Esc back", g.width-6))
|
||||
|
||||
return dialogStyle.Render(sb.String())
|
||||
}
|
||||
|
||||
@@ -295,11 +295,6 @@ func (l *ListView) ViewFiltered(searchTerm string) string {
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// GroupCount returns the number of groups.
|
||||
func (l *ListView) GroupCount() int {
|
||||
return len(l.groupOrder)
|
||||
}
|
||||
|
||||
// GetGroups returns all group names.
|
||||
func (l *ListView) GetGroups() []string {
|
||||
return l.groupOrder
|
||||
|
||||
@@ -407,3 +407,72 @@ func BenchmarkListView_View(b *testing.B) {
|
||||
_ = lv.View()
|
||||
}
|
||||
}
|
||||
|
||||
func TestListView_DeleteSimulation(t *testing.T) {
|
||||
lv := NewListView()
|
||||
|
||||
// Initial entries
|
||||
entries := []protocol.HostEntry{
|
||||
{Domain: "a.com", IP: "127.0.0.1", Alias: "a", Enabled: true, Group: "dev"},
|
||||
{Domain: "b.com", IP: "127.0.0.1", Alias: "b", Enabled: false, Group: "dev"},
|
||||
{Domain: "c.com", IP: "192.168.1.1", Alias: "c", Enabled: true, Group: "staging"},
|
||||
}
|
||||
lv.SetItems(entries)
|
||||
require.Equal(t, 3, lv.Len())
|
||||
|
||||
// Select the second item
|
||||
lv.MoveDown()
|
||||
selected := lv.Selected()
|
||||
require.NotNil(t, selected)
|
||||
require.Equal(t, "b", selected.Entry.Alias)
|
||||
|
||||
// Simulate delete: set new items without the deleted entry
|
||||
entriesAfterDelete := []protocol.HostEntry{
|
||||
{Domain: "a.com", IP: "127.0.0.1", Alias: "a", Enabled: true, Group: "dev"},
|
||||
{Domain: "c.com", IP: "192.168.1.1", Alias: "c", Enabled: true, Group: "staging"},
|
||||
}
|
||||
lv.SetItems(entriesAfterDelete)
|
||||
|
||||
// Verify list has only 2 items now
|
||||
assert.Equal(t, 2, lv.Len())
|
||||
|
||||
// Verify "b" is no longer in the list
|
||||
for i := 0; i < lv.Len(); i++ {
|
||||
assert.NotEqual(t, "b", lv.items[i].Entry.Alias, "deleted entry should not be in list")
|
||||
}
|
||||
|
||||
// Cursor should be adjusted if needed
|
||||
assert.LessOrEqual(t, lv.cursor, lv.Len()-1)
|
||||
}
|
||||
|
||||
func TestListView_SetItemsWithNil(t *testing.T) {
|
||||
lv := NewListView()
|
||||
|
||||
// Initial entries
|
||||
entries := []protocol.HostEntry{
|
||||
{Domain: "a.com", IP: "127.0.0.1", Alias: "a", Enabled: true, Group: "dev"},
|
||||
}
|
||||
lv.SetItems(entries)
|
||||
require.Equal(t, 1, lv.Len())
|
||||
|
||||
// Set nil entries (simulating empty list from server)
|
||||
lv.SetItems(nil)
|
||||
assert.Equal(t, 0, lv.Len())
|
||||
assert.Equal(t, 0, lv.cursor)
|
||||
}
|
||||
|
||||
func TestListView_SetItemsWithEmptySlice(t *testing.T) {
|
||||
lv := NewListView()
|
||||
|
||||
// Initial entries
|
||||
entries := []protocol.HostEntry{
|
||||
{Domain: "a.com", IP: "127.0.0.1", Alias: "a", Enabled: true, Group: "dev"},
|
||||
}
|
||||
lv.SetItems(entries)
|
||||
require.Equal(t, 1, lv.Len())
|
||||
|
||||
// Set empty slice
|
||||
lv.SetItems([]protocol.HostEntry{})
|
||||
assert.Equal(t, 0, lv.Len())
|
||||
assert.Equal(t, 0, lv.cursor)
|
||||
}
|
||||
|
||||
@@ -411,7 +411,7 @@ func (p *PresetPicker) selectView() string {
|
||||
}
|
||||
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(helpDescStyle.Render("↑↓ navigate • Enter apply • n new • e edit • d delete • Esc cancel"))
|
||||
sb.WriteString(WrapHelpText("↑↓ navigate • Enter apply • n new • e edit • d delete • Esc cancel", p.width-6))
|
||||
|
||||
return dialogStyle.Render(sb.String())
|
||||
}
|
||||
@@ -483,7 +483,7 @@ func (p *PresetPicker) formView() string {
|
||||
}
|
||||
sb.WriteString("\n\n")
|
||||
|
||||
sb.WriteString(helpDescStyle.Render("Tab/↓ next • Enter select/save • Esc cancel"))
|
||||
sb.WriteString(WrapHelpText("Tab/↓ next • Enter select/save • Esc cancel", p.width-6))
|
||||
|
||||
return dialogStyle.Render(sb.String())
|
||||
}
|
||||
@@ -536,7 +536,7 @@ func (p *PresetPicker) pickerView() string {
|
||||
|
||||
sb.WriteString(titleStyle.Render(title))
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(helpDescStyle.Render("Space to toggle • Enter to confirm • Esc to cancel"))
|
||||
sb.WriteString(WrapHelpText("Space to toggle • Enter to confirm • Esc to cancel", p.width-6))
|
||||
sb.WriteString("\n\n")
|
||||
|
||||
filtered := p.getFilteredAliases()
|
||||
|
||||
+62
-31
@@ -2,6 +2,8 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
@@ -35,12 +37,6 @@ var (
|
||||
|
||||
disabledStyle = lipgloss.NewStyle().
|
||||
Foreground(colorMuted)
|
||||
|
||||
pendingStyle = lipgloss.NewStyle().
|
||||
Foreground(colorWarning)
|
||||
|
||||
errorIndicatorStyle = lipgloss.NewStyle().
|
||||
Foreground(colorError)
|
||||
)
|
||||
|
||||
// Status bar and help
|
||||
@@ -116,35 +112,70 @@ var (
|
||||
Padding(0, 1)
|
||||
)
|
||||
|
||||
// Indicator returns the appropriate status indicator string.
|
||||
func Indicator(enabled bool, pending bool, hasError bool) string {
|
||||
if hasError {
|
||||
return errorIndicatorStyle.Render("✗")
|
||||
// WrapHelpText wraps help text to fit within maxWidth, splitting on bullet separators.
|
||||
// If maxWidth is 0 or negative, returns the original text.
|
||||
func WrapHelpText(text string, maxWidth int) string {
|
||||
if maxWidth <= 0 {
|
||||
return helpDescStyle.Render(text)
|
||||
}
|
||||
if pending {
|
||||
return pendingStyle.Render("◐")
|
||||
|
||||
separator := " • "
|
||||
parts := splitOnSeparator(text, separator)
|
||||
|
||||
var lines []string
|
||||
var currentLine string
|
||||
var currentWidth int
|
||||
|
||||
for i, part := range parts {
|
||||
partWidth := len(part)
|
||||
sepWidth := 3 // len(" • ")
|
||||
|
||||
newWidth := currentWidth + partWidth
|
||||
if currentWidth > 0 {
|
||||
newWidth += sepWidth
|
||||
}
|
||||
|
||||
if newWidth > maxWidth && currentWidth > 0 {
|
||||
lines = append(lines, currentLine)
|
||||
currentLine = part
|
||||
currentWidth = partWidth
|
||||
} else {
|
||||
if currentWidth > 0 {
|
||||
currentLine += separator
|
||||
}
|
||||
currentLine += part
|
||||
if i == 0 {
|
||||
currentWidth = partWidth
|
||||
} else {
|
||||
currentWidth = newWidth
|
||||
}
|
||||
}
|
||||
}
|
||||
if enabled {
|
||||
return enabledStyle.Render("●")
|
||||
|
||||
if currentLine != "" {
|
||||
lines = append(lines, currentLine)
|
||||
}
|
||||
return disabledStyle.Render("○")
|
||||
|
||||
// Apply style to each line and join
|
||||
var result []string
|
||||
for _, line := range lines {
|
||||
result = append(result, helpDescStyle.Render(line))
|
||||
}
|
||||
|
||||
return strings.Join(result, "\n")
|
||||
}
|
||||
|
||||
// StatusText returns the status text with appropriate styling
|
||||
func StatusText(enabled bool, pending bool, hasError bool) string {
|
||||
if hasError {
|
||||
return errorIndicatorStyle.Render("✗ Error")
|
||||
// splitOnSeparator splits a string on the given separator.
|
||||
func splitOnSeparator(s, sep string) []string {
|
||||
var parts []string
|
||||
for {
|
||||
idx := strings.Index(s, sep)
|
||||
if idx == -1 {
|
||||
parts = append(parts, s)
|
||||
break
|
||||
}
|
||||
parts = append(parts, s[:idx])
|
||||
s = s[idx+len(sep):]
|
||||
}
|
||||
if pending {
|
||||
return pendingStyle.Render("◐ Pending")
|
||||
}
|
||||
if enabled {
|
||||
return enabledStyle.Render("● Active")
|
||||
}
|
||||
return disabledStyle.Render("○ Disabled")
|
||||
}
|
||||
|
||||
// HelpItem formats a help item.
|
||||
func HelpItem(key, desc string) string {
|
||||
return helpKeyStyle.Render(key) + " " + helpDescStyle.Render(desc)
|
||||
return parts
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@ func (c *Checker) CheckForUpdate(ctx context.Context) *UpdateInfo {
|
||||
|
||||
// fetchLatestRelease fetches the latest release info from GitHub API
|
||||
func (c *Checker) fetchLatestRelease(ctx context.Context) (*ReleaseInfo, error) {
|
||||
// #nosec G107 -- URL is constructed from hardcoded constant and validated owner/repo
|
||||
url := fmt.Sprintf(githubReleasesURL, c.owner, c.repo)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
@@ -145,15 +146,9 @@ func parseVersion(v string) []int {
|
||||
|
||||
for _, p := range parts {
|
||||
var num int
|
||||
fmt.Sscanf(p, "%d", &num)
|
||||
_, _ = fmt.Sscanf(p, "%d", &num) // Error intentionally ignored - non-numeric parts become 0
|
||||
result = append(result, num)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// FormatUpdateMessage formats a user-friendly update notification
|
||||
func (u *UpdateInfo) FormatUpdateMessage() string {
|
||||
return fmt.Sprintf("New version available: %s (current: %s) - %s",
|
||||
u.LatestVersion, u.CurrentVersion, u.ReleaseURL)
|
||||
}
|
||||
|
||||
@@ -76,19 +76,6 @@ func TestIsNewerVersion(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInfo_FormatUpdateMessage(t *testing.T) {
|
||||
info := &UpdateInfo{
|
||||
CurrentVersion: "1.0.0",
|
||||
LatestVersion: "1.1.0",
|
||||
ReleaseURL: "https://github.com/lukaszraczylo/lolcathost/releases/tag/v1.1.0",
|
||||
}
|
||||
|
||||
msg := info.FormatUpdateMessage()
|
||||
assert.Contains(t, msg, "1.0.0")
|
||||
assert.Contains(t, msg, "1.1.0")
|
||||
assert.Contains(t, msg, "https://github.com")
|
||||
}
|
||||
|
||||
func TestNewChecker(t *testing.T) {
|
||||
checker := NewChecker("lukaszraczylo", "lolcathost", "v1.0.0")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user