mirror of
https://github.com/lukaszraczylo/lolcathost.git
synced 2026-11-19 09:35:24 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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:
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: "0 3 * * *"
|
- cron: "0 3 * * *"
|
||||||
workflow_dispatch:
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
actions: write
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
prepare:
|
autoupdate:
|
||||||
runs-on: ubuntu-latest
|
uses: lukaszraczylo/shared-actions/.github/workflows/go-autoupdate.yaml@main
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v5
|
|
||||||
with:
|
with:
|
||||||
go-version: "1.24"
|
go-version: ">=1.24"
|
||||||
cache: true
|
release-workflow: "release.yml"
|
||||||
|
secrets: inherit
|
||||||
- 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"
|
|
||||||
|
|||||||
@@ -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,12 @@ on:
|
|||||||
- "go.sum"
|
- "go.sum"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
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:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Setup Go
|
jobs:
|
||||||
uses: actions/setup-go@v5
|
release:
|
||||||
|
uses: lukaszraczylo/shared-actions/.github/workflows/go-release.yaml@main
|
||||||
with:
|
with:
|
||||||
go-version: "1.24"
|
go-version: ">=1.24"
|
||||||
|
secrets: inherit
|
||||||
- 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 }}
|
|
||||||
|
|||||||
+12
-7
@@ -22,7 +22,7 @@ builds:
|
|||||||
|
|
||||||
archives:
|
archives:
|
||||||
- id: lolcathost
|
- id: lolcathost
|
||||||
format: tar.gz
|
formats: [tar.gz]
|
||||||
name_template: "lolcathost-{{ .Version }}-{{ .Os }}-{{ .Arch }}"
|
name_template: "lolcathost-{{ .Version }}-{{ .Os }}-{{ .Arch }}"
|
||||||
files:
|
files:
|
||||||
- LICENSE
|
- LICENSE
|
||||||
@@ -49,14 +49,19 @@ release:
|
|||||||
draft: false
|
draft: false
|
||||||
prerelease: auto
|
prerelease: auto
|
||||||
|
|
||||||
brews:
|
homebrew_casks:
|
||||||
- repository:
|
- repository:
|
||||||
owner: lukaszraczylo
|
owner: lukaszraczylo
|
||||||
name: brew-taps
|
name: homebrew-taps
|
||||||
token: "{{ .Env.HOMEBREW_TAP_TOKEN }}"
|
token: "{{ .Env.HOMEBREW_TAP_TOKEN }}"
|
||||||
directory: Formula
|
directory: Casks
|
||||||
homepage: https://github.com/lukaszraczylo/lolcathost
|
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
|
license: MIT
|
||||||
test: |
|
hooks:
|
||||||
system "#{bin}/lolcathost", "--version"
|
post:
|
||||||
|
install: |
|
||||||
|
if OS.mac?
|
||||||
|
system_command "/usr/bin/xattr",
|
||||||
|
args: ["-dr", "com.apple.quarantine", "#{staged_path}/lolcathost"]
|
||||||
|
end
|
||||||
|
|||||||
@@ -50,12 +50,17 @@ lolcathost manages your `/etc/hosts` file with an interactive terminal interface
|
|||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### Homebrew (macOS/Linux)
|
### Homebrew (macOS)
|
||||||
|
|
||||||
```bash
|
```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:
|
After Homebrew installation, run:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -204,7 +204,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)
|
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) {
|
func runOn(alias string) {
|
||||||
|
|||||||
+2
-2
@@ -276,9 +276,9 @@
|
|||||||
<div class="glass p-6 rounded-xl">
|
<div class="glass p-6 rounded-xl">
|
||||||
<h3 class="font-semibold text-gray-900 dark:text-gray-100 mb-3 flex items-center">
|
<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>
|
<i class="fas fa-beer mr-2 text-amber-500"></i>
|
||||||
Homebrew (macOS/Linux)
|
Homebrew (macOS)
|
||||||
</h3>
|
</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>
|
sudo lolcathost --install</code></pre>
|
||||||
</div>
|
</div>
|
||||||
<div class="glass p-6 rounded-xl">
|
<div class="glass p-6 rounded-xl">
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ require (
|
|||||||
github.com/charmbracelet/x/ansi v0.11.2 // indirect
|
github.com/charmbracelet/x/ansi v0.11.2 // indirect
|
||||||
github.com/charmbracelet/x/cellbuf v0.0.14 // indirect
|
github.com/charmbracelet/x/cellbuf v0.0.14 // indirect
|
||||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||||
github.com/clipperhouse/displaywidth v0.6.0 // indirect
|
github.com/clipperhouse/displaywidth v0.6.1 // indirect
|
||||||
github.com/clipperhouse/stringish v0.1.1 // indirect
|
github.com/clipperhouse/stringish v0.1.1 // indirect
|
||||||
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
|
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payR
|
|||||||
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
|
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 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
|
||||||
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
|
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.1 h1:/zMlAezfDzT2xy6acHBzwIfyu2ic0hgkT83UX5EY2gY=
|
||||||
github.com/clipperhouse/displaywidth v0.6.0/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o=
|
github.com/clipperhouse/displaywidth v0.6.1/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o=
|
||||||
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
|
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/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 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ func (c *Client) Connect() error {
|
|||||||
|
|
||||||
// Close existing connection if any
|
// Close existing connection if any
|
||||||
if c.conn != nil {
|
if c.conn != nil {
|
||||||
c.conn.Close()
|
_ = c.conn.Close()
|
||||||
c.conn = nil
|
c.conn = nil
|
||||||
c.reader = nil
|
c.reader = nil
|
||||||
}
|
}
|
||||||
@@ -83,7 +83,7 @@ func (c *Client) send(req *protocol.Request) (*protocol.Response, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set deadline
|
// Set deadline
|
||||||
c.conn.SetDeadline(time.Now().Add(c.timeout))
|
_ = c.conn.SetDeadline(time.Now().Add(c.timeout))
|
||||||
|
|
||||||
// Send request
|
// Send request
|
||||||
data, err := json.Marshal(req)
|
data, err := json.Marshal(req)
|
||||||
|
|||||||
@@ -474,6 +474,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) {
|
func BenchmarkClient_Ping(b *testing.B) {
|
||||||
tmpDir := b.TempDir()
|
tmpDir := b.TempDir()
|
||||||
socketPath := filepath.Join(tmpDir, "bench.sock")
|
socketPath := filepath.Join(tmpDir, "bench.sock")
|
||||||
|
|||||||
@@ -167,7 +167,7 @@ func (m *Manager) watchLoop() {
|
|||||||
func (m *Manager) Stop() {
|
func (m *Manager) Stop() {
|
||||||
close(m.stopCh)
|
close(m.stopCh)
|
||||||
if m.watcher != nil {
|
if m.watcher != nil {
|
||||||
m.watcher.Close()
|
_ = m.watcher.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -338,76 +338,6 @@ func (c *Config) DeleteHost(alias string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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 {
|
|
||||||
return fmt.Errorf("alias not found: %s", oldAlias)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for duplicate alias if alias is changing
|
|
||||||
if oldAlias != newAlias {
|
|
||||||
if existing, _ := c.FindHostByAlias(newAlias); existing != nil {
|
|
||||||
return fmt.Errorf("alias already exists: %s", newAlias)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get current enabled state
|
|
||||||
enabled := c.Groups[foundGroup].Hosts[foundHost].Enabled
|
|
||||||
|
|
||||||
// If group is changing, move to new group
|
|
||||||
if c.Groups[foundGroup].Name != groupName {
|
|
||||||
// Remove from old group
|
|
||||||
c.Groups[foundGroup].Hosts = append(c.Groups[foundGroup].Hosts[:foundHost], c.Groups[foundGroup].Hosts[foundHost+1:]...)
|
|
||||||
|
|
||||||
// Add to new group
|
|
||||||
host := Host{
|
|
||||||
Domain: domain,
|
|
||||||
IP: ip,
|
|
||||||
Alias: newAlias,
|
|
||||||
Enabled: enabled,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find or create target group
|
|
||||||
found := false
|
|
||||||
for i := range c.Groups {
|
|
||||||
if c.Groups[i].Name == groupName {
|
|
||||||
c.Groups[i].Hosts = append(c.Groups[i].Hosts, host)
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
c.Groups = append(c.Groups, Group{
|
|
||||||
Name: groupName,
|
|
||||||
Hosts: []Host{host},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Update in place
|
|
||||||
c.Groups[foundGroup].Hosts[foundHost].Domain = domain
|
|
||||||
c.Groups[foundGroup].Hosts[foundHost].IP = ip
|
|
||||||
c.Groups[foundGroup].Hosts[foundHost].Alias = newAlias
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ApplyPreset applies a preset to the configuration.
|
// ApplyPreset applies a preset to the configuration.
|
||||||
func (c *Config) ApplyPreset(name string) error {
|
func (c *Config) ApplyPreset(name string) error {
|
||||||
preset := c.FindPreset(name)
|
preset := c.FindPreset(name)
|
||||||
@@ -482,6 +412,7 @@ func (m *Manager) Save() error {
|
|||||||
return fmt.Errorf("failed to marshal config: %w", err)
|
return fmt.Errorf("failed to marshal config: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #nosec G306 -- config file should be world-readable
|
||||||
if err := os.WriteFile(m.path, data, 0644); err != nil {
|
if err := os.WriteFile(m.path, data, 0644); err != nil {
|
||||||
return fmt.Errorf("failed to write config: %w", err)
|
return fmt.Errorf("failed to write config: %w", err)
|
||||||
}
|
}
|
||||||
@@ -492,6 +423,7 @@ func (m *Manager) Save() error {
|
|||||||
// CreateDefault creates a default configuration file.
|
// CreateDefault creates a default configuration file.
|
||||||
func CreateDefault(path string) error {
|
func CreateDefault(path string) error {
|
||||||
dir := filepath.Dir(path)
|
dir := filepath.Dir(path)
|
||||||
|
// #nosec G301 -- config directory should be world-readable
|
||||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
return fmt.Errorf("failed to create config directory: %w", err)
|
return fmt.Errorf("failed to create config directory: %w", err)
|
||||||
}
|
}
|
||||||
@@ -533,6 +465,7 @@ func CreateDefault(path string) error {
|
|||||||
return fmt.Errorf("failed to marshal default config: %w", err)
|
return fmt.Errorf("failed to marshal default config: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #nosec G306 -- config file should be world-readable
|
||||||
if err := os.WriteFile(path, data, 0644); err != nil {
|
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||||
return fmt.Errorf("failed to write default config: %w", err)
|
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()
|
cfg.EnsureDefaultGroup()
|
||||||
// Save if we added a default group
|
// Save if we added a default group
|
||||||
if len(cfg.Groups) == 1 && cfg.Groups[0].Name == "default" && len(cfg.Groups[0].Hosts) == 0 {
|
if len(cfg.Groups) == 1 && cfg.Groups[0].Name == "default" && len(cfg.Groups[0].Hosts) == 0 {
|
||||||
cfgManager.Save()
|
_ = cfgManager.Save()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -178,13 +178,14 @@ func (m *HostsManager) buildManagedSection(entries []HostEntry) string {
|
|||||||
func (m *HostsManager) writeAtomic(content string) error {
|
func (m *HostsManager) writeAtomic(content string) error {
|
||||||
// Write to temp file first
|
// Write to temp file first
|
||||||
tmpFile := m.hostsPath + ".tmp"
|
tmpFile := m.hostsPath + ".tmp"
|
||||||
|
// #nosec G306 -- hosts file must be world-readable
|
||||||
if err := os.WriteFile(tmpFile, []byte(content), 0644); err != nil {
|
if err := os.WriteFile(tmpFile, []byte(content), 0644); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rename atomically
|
// Rename atomically
|
||||||
if err := os.Rename(tmpFile, m.hostsPath); err != nil {
|
if err := os.Rename(tmpFile, m.hostsPath); err != nil {
|
||||||
os.Remove(tmpFile)
|
_ = os.Remove(tmpFile)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,6 +194,7 @@ func (m *HostsManager) writeAtomic(content string) error {
|
|||||||
|
|
||||||
// CreateBackup creates a backup of the current hosts file.
|
// CreateBackup creates a backup of the current hosts file.
|
||||||
func (m *HostsManager) CreateBackup() error {
|
func (m *HostsManager) CreateBackup() error {
|
||||||
|
// #nosec G301 -- backup directory should be world-readable for recovery
|
||||||
if err := os.MkdirAll(m.backupDir, 0755); err != nil {
|
if err := os.MkdirAll(m.backupDir, 0755); err != nil {
|
||||||
return fmt.Errorf("failed to create backup directory: %w", err)
|
return fmt.Errorf("failed to create backup directory: %w", err)
|
||||||
}
|
}
|
||||||
@@ -205,6 +207,7 @@ func (m *HostsManager) CreateBackup() error {
|
|||||||
timestamp := time.Now().Format("20060102-150405")
|
timestamp := time.Now().Format("20060102-150405")
|
||||||
backupPath := filepath.Join(m.backupDir, fmt.Sprintf("hosts.%s.bak", timestamp))
|
backupPath := filepath.Join(m.backupDir, fmt.Sprintf("hosts.%s.bak", timestamp))
|
||||||
|
|
||||||
|
// #nosec G306 -- backup files should be world-readable for recovery
|
||||||
if err := os.WriteFile(backupPath, content, 0644); err != nil {
|
if err := os.WriteFile(backupPath, content, 0644); err != nil {
|
||||||
return fmt.Errorf("failed to write backup: %w", err)
|
return fmt.Errorf("failed to write backup: %w", err)
|
||||||
}
|
}
|
||||||
@@ -243,7 +246,7 @@ func (m *HostsManager) cleanupBackups() error {
|
|||||||
// Remove oldest backups
|
// Remove oldest backups
|
||||||
for i := MaxBackups; i < len(backups); i++ {
|
for i := MaxBackups; i < len(backups); i++ {
|
||||||
path := filepath.Join(m.backupDir, backups[i].Name())
|
path := filepath.Join(m.backupDir, backups[i].Name())
|
||||||
os.Remove(path)
|
_ = os.Remove(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -301,6 +304,7 @@ func (m *HostsManager) GetBackupContent(name string) (string, error) {
|
|||||||
return "", fmt.Errorf("invalid backup name")
|
return "", fmt.Errorf("invalid backup name")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #nosec G304 -- backupPath is validated above: filepath.Base(name) == name and prefix/suffix checks
|
||||||
content, err := os.ReadFile(backupPath)
|
content, err := os.ReadFile(backupPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("failed to read backup: %w", err)
|
return "", fmt.Errorf("failed to read backup: %w", err)
|
||||||
@@ -318,6 +322,7 @@ func (m *HostsManager) RestoreBackup(name string) error {
|
|||||||
return fmt.Errorf("invalid backup name")
|
return fmt.Errorf("invalid backup name")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #nosec G304 -- backupPath is validated above: filepath.Base(name) == name and prefix/suffix checks
|
||||||
content, err := os.ReadFile(backupPath)
|
content, err := os.ReadFile(backupPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to read backup: %w", err)
|
return fmt.Errorf("failed to read backup: %w", err)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ func (s *Server) getPeerCredentials(conn net.Conn) *PeerCredentials {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var creds *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)
|
xucred, err := unix.GetsockoptXucred(int(fd), unix.SOL_LOCAL, unix.LOCAL_PEERCRED)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@@ -33,6 +33,7 @@ func (s *Server) getPeerCredentials(conn net.Conn) *PeerCredentials {
|
|||||||
// Get PID separately using LOCAL_PEERPID
|
// Get PID separately using LOCAL_PEERPID
|
||||||
var pid int32
|
var pid int32
|
||||||
pidLen := uint32(unsafe.Sizeof(pid))
|
pidLen := uint32(unsafe.Sizeof(pid))
|
||||||
|
// #nosec G103 -- unsafe required for low-level syscall to get peer PID
|
||||||
_, _, errno := syscall.Syscall6(
|
_, _, errno := syscall.Syscall6(
|
||||||
syscall.SYS_GETSOCKOPT,
|
syscall.SYS_GETSOCKOPT,
|
||||||
fd,
|
fd,
|
||||||
|
|||||||
@@ -114,10 +114,12 @@ type AuditEntry struct {
|
|||||||
func NewAuditLogger(path string) (*AuditLogger, error) {
|
func NewAuditLogger(path string) (*AuditLogger, error) {
|
||||||
// Ensure directory exists
|
// Ensure directory exists
|
||||||
dir := path[:len(path)-len("/audit.log")]
|
dir := path[:len(path)-len("/audit.log")]
|
||||||
|
// #nosec G301 -- log directory should be world-readable
|
||||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
return nil, fmt.Errorf("failed to create log directory: %w", err)
|
return nil, fmt.Errorf("failed to create log directory: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #nosec G304,G302 -- path is from constant AuditLogPath; audit log should be world-readable
|
||||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to open audit log: %w", err)
|
return nil, fmt.Errorf("failed to open audit log: %w", err)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package daemon
|
package daemon
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -145,28 +146,33 @@ func TestPeerCredentials(t *testing.T) {
|
|||||||
|
|
||||||
// Matrix test for rate limiting
|
// Matrix test for rate limiting
|
||||||
func TestRateLimiter_Matrix(t *testing.T) {
|
func TestRateLimiter_Matrix(t *testing.T) {
|
||||||
limits := []int{1, 5, 10, 100}
|
testCases := []struct {
|
||||||
windows := []time.Duration{10 * time.Millisecond, 100 * time.Millisecond, time.Second}
|
limit int
|
||||||
|
window time.Duration
|
||||||
|
}{
|
||||||
|
{1, time.Second},
|
||||||
|
{5, time.Second},
|
||||||
|
{10, time.Second},
|
||||||
|
{100, time.Second},
|
||||||
|
}
|
||||||
|
|
||||||
for _, limit := range limits {
|
for _, tc := range testCases {
|
||||||
for _, window := range windows {
|
|
||||||
t.Run(
|
t.Run(
|
||||||
"limit="+string(rune('0'+limit))+"_window="+window.String(),
|
fmt.Sprintf("limit=%d_window=%s", tc.limit, tc.window),
|
||||||
func(t *testing.T) {
|
func(t *testing.T) {
|
||||||
rl := NewRateLimiter(limit, window)
|
rl := NewRateLimiter(tc.limit, tc.window)
|
||||||
|
|
||||||
// Should allow exactly 'limit' requests
|
// Should allow exactly 'limit' requests
|
||||||
for i := 0; i < limit; i++ {
|
for i := 0; i < tc.limit; i++ {
|
||||||
assert.True(t, rl.Allow(1))
|
assert.True(t, rl.Allow(1), "request %d should be allowed", i)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Next should be blocked
|
// Next should be blocked
|
||||||
assert.False(t, rl.Allow(1))
|
assert.False(t, rl.Allow(1), "request after limit should be blocked")
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkRateLimiter_Allow(b *testing.B) {
|
func BenchmarkRateLimiter_Allow(b *testing.B) {
|
||||||
rl := NewRateLimiter(RateLimit, RateLimitWindow)
|
rl := NewRateLimiter(RateLimit, RateLimitWindow)
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ func NewServer(socketPath string, cfgManager *config.Manager) *Server {
|
|||||||
// Start starts the server.
|
// Start starts the server.
|
||||||
func (s *Server) Start() error {
|
func (s *Server) Start() error {
|
||||||
// Remove existing socket
|
// Remove existing socket
|
||||||
os.Remove(s.socketPath)
|
_ = os.Remove(s.socketPath)
|
||||||
|
|
||||||
listener, err := net.Listen("unix", s.socketPath)
|
listener, err := net.Listen("unix", s.socketPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -56,14 +56,15 @@ func (s *Server) Start() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set socket permissions: 0660 root:lolcathost
|
// Set socket permissions: 0660 root:lolcathost
|
||||||
|
// #nosec G302 -- socket must be group-accessible for lolcathost group members
|
||||||
if err := os.Chmod(s.socketPath, 0660); err != nil {
|
if err := os.Chmod(s.socketPath, 0660); err != nil {
|
||||||
listener.Close()
|
_ = listener.Close()
|
||||||
return fmt.Errorf("failed to set socket permissions: %w", err)
|
return fmt.Errorf("failed to set socket permissions: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set socket group to lolcathost (GID 850)
|
// Set socket group to lolcathost (GID 850)
|
||||||
if err := os.Chown(s.socketPath, 0, 850); err != nil {
|
if err := os.Chown(s.socketPath, 0, 850); err != nil {
|
||||||
listener.Close()
|
_ = listener.Close()
|
||||||
return fmt.Errorf("failed to set socket ownership: %w", err)
|
return fmt.Errorf("failed to set socket ownership: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,13 +95,13 @@ func (s *Server) Stop() error {
|
|||||||
close(s.stopCh)
|
close(s.stopCh)
|
||||||
|
|
||||||
if s.listener != nil {
|
if s.listener != nil {
|
||||||
s.listener.Close()
|
_ = s.listener.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
os.Remove(s.socketPath)
|
_ = os.Remove(s.socketPath)
|
||||||
|
|
||||||
if s.auditLogger != nil {
|
if s.auditLogger != nil {
|
||||||
s.auditLogger.Close()
|
_ = s.auditLogger.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -200,7 +201,7 @@ func (s *Server) isAuthorized(creds *PeerCredentials) bool {
|
|||||||
func (s *Server) writeResponse(conn net.Conn, resp *protocol.Response) {
|
func (s *Server) writeResponse(conn net.Conn, resp *protocol.Response) {
|
||||||
data, _ := json.Marshal(resp)
|
data, _ := json.Marshal(resp)
|
||||||
data = append(data, '\n')
|
data = append(data, '\n')
|
||||||
conn.Write(data)
|
_, _ = conn.Write(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleRequest(req *protocol.Request, creds *PeerCredentials) *protocol.Response {
|
func (s *Server) handleRequest(req *protocol.Request, creds *PeerCredentials) *protocol.Response {
|
||||||
@@ -492,7 +493,7 @@ func (s *Server) handleRollback(req *protocol.Request) *protocol.Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Flush DNS after restore
|
// Flush DNS after restore
|
||||||
s.flusher.Flush()
|
_ = s.flusher.Flush()
|
||||||
|
|
||||||
resp, _ := protocol.NewOKResponse(map[string]string{"restored": payload.BackupName})
|
resp, _ := protocol.NewOKResponse(map[string]string{"restored": payload.BackupName})
|
||||||
return resp
|
return resp
|
||||||
|
|||||||
@@ -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
|
// Remove socket
|
||||||
os.Remove(SocketPath)
|
_ = os.Remove(SocketPath)
|
||||||
|
|
||||||
// Note: We don't remove the group, logs, or backups
|
// Note: We don't remove the group, logs, or backups
|
||||||
// The user may want to keep these
|
// The user may want to keep these
|
||||||
@@ -225,6 +225,7 @@ func (i *Installer) createGroupDarwin() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, args := range cmds {
|
for _, args := range cmds {
|
||||||
|
// #nosec G204 -- args are hardcoded dscl commands with the constant GroupName
|
||||||
if err := exec.Command(args[0], args[1:]...).Run(); err != nil {
|
if err := exec.Command(args[0], args[1:]...).Run(); err != nil {
|
||||||
return fmt.Errorf("command %v failed: %w", args, err)
|
return fmt.Errorf("command %v failed: %w", args, err)
|
||||||
}
|
}
|
||||||
@@ -315,6 +316,7 @@ func (i *Installer) createDirectories() error {
|
|||||||
|
|
||||||
for _, dir := range dirs {
|
for _, dir := range dirs {
|
||||||
i.log(" Creating directory '%s'...", dir)
|
i.log(" Creating directory '%s'...", dir)
|
||||||
|
// #nosec G301 -- system directories should be world-readable
|
||||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
return fmt.Errorf("failed to create %s: %w", dir, err)
|
return fmt.Errorf("failed to create %s: %w", dir, err)
|
||||||
}
|
}
|
||||||
@@ -340,21 +342,23 @@ func (i *Installer) installLaunchDaemon() error {
|
|||||||
|
|
||||||
// Unload if already loaded (do this before writing plist)
|
// Unload if already loaded (do this before writing plist)
|
||||||
i.log(" Stopping existing daemon if running...")
|
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()
|
||||||
|
|
||||||
// Give launchd time to fully unload the service
|
// Give launchd time to fully unload the service
|
||||||
time.Sleep(500 * time.Millisecond)
|
time.Sleep(500 * time.Millisecond)
|
||||||
|
|
||||||
// Remove old plist to ensure clean state
|
// Remove old plist to ensure clean state
|
||||||
os.Remove(plistPath)
|
_ = os.Remove(plistPath)
|
||||||
|
|
||||||
i.log(" Writing LaunchDaemon plist...")
|
i.log(" Writing LaunchDaemon plist...")
|
||||||
|
// #nosec G306 -- plist files are world-readable by convention
|
||||||
if err := os.WriteFile(plistPath, []byte(plistContent), 0644); err != nil {
|
if err := os.WriteFile(plistPath, []byte(plistContent), 0644); err != nil {
|
||||||
return fmt.Errorf("failed to write plist: %w", err)
|
return fmt.Errorf("failed to write plist: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bootstrap the daemon
|
// Bootstrap the daemon
|
||||||
i.log(" Starting daemon...")
|
i.log(" Starting daemon...")
|
||||||
|
// #nosec G204 -- plistPath is constructed from constant LaunchDaemonDir
|
||||||
cmd := exec.Command("launchctl", "bootstrap", "system", plistPath)
|
cmd := exec.Command("launchctl", "bootstrap", "system", plistPath)
|
||||||
output, err := cmd.CombinedOutput()
|
output, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -376,10 +380,10 @@ func (i *Installer) uninstallLaunchDaemon() {
|
|||||||
plistPath := filepath.Join(LaunchDaemonDir, "com.lolcathost.daemon.plist")
|
plistPath := filepath.Join(LaunchDaemonDir, "com.lolcathost.daemon.plist")
|
||||||
|
|
||||||
i.log(" Stopping daemon...")
|
i.log(" Stopping daemon...")
|
||||||
exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run()
|
_ = exec.Command("launchctl", "bootout", "system/com.lolcathost.daemon").Run()
|
||||||
|
|
||||||
i.log(" Removing LaunchDaemon plist...")
|
i.log(" Removing LaunchDaemon plist...")
|
||||||
os.Remove(plistPath)
|
_ = os.Remove(plistPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Installer) installSystemdService() error {
|
func (i *Installer) installSystemdService() error {
|
||||||
@@ -387,6 +391,7 @@ func (i *Installer) installSystemdService() error {
|
|||||||
unitContent := fmt.Sprintf(SystemdUnit, i.binaryPath)
|
unitContent := fmt.Sprintf(SystemdUnit, i.binaryPath)
|
||||||
|
|
||||||
i.log(" Writing systemd unit...")
|
i.log(" Writing systemd unit...")
|
||||||
|
// #nosec G306 -- systemd unit files are world-readable by convention
|
||||||
if err := os.WriteFile(unitPath, []byte(unitContent), 0644); err != nil {
|
if err := os.WriteFile(unitPath, []byte(unitContent), 0644); err != nil {
|
||||||
return fmt.Errorf("failed to write unit file: %w", err)
|
return fmt.Errorf("failed to write unit file: %w", err)
|
||||||
}
|
}
|
||||||
@@ -408,12 +413,12 @@ func (i *Installer) installSystemdService() error {
|
|||||||
|
|
||||||
func (i *Installer) uninstallSystemdService() {
|
func (i *Installer) uninstallSystemdService() {
|
||||||
i.log(" Stopping and disabling service...")
|
i.log(" Stopping and disabling service...")
|
||||||
exec.Command("systemctl", "disable", "--now", "lolcathost.service").Run()
|
_ = exec.Command("systemctl", "disable", "--now", "lolcathost.service").Run()
|
||||||
|
|
||||||
i.log(" Removing systemd unit...")
|
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()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Installer) createDefaultConfig() error {
|
func (i *Installer) createDefaultConfig() error {
|
||||||
@@ -430,6 +435,7 @@ func (i *Installer) createDefaultConfig() error {
|
|||||||
|
|
||||||
// Create config directory
|
// Create config directory
|
||||||
configDir := filepath.Dir(configPath)
|
configDir := filepath.Dir(configPath)
|
||||||
|
// #nosec G301 -- config directory should be world-readable
|
||||||
if err := os.MkdirAll(configDir, 0755); err != nil {
|
if err := os.MkdirAll(configDir, 0755); err != nil {
|
||||||
return fmt.Errorf("failed to create config directory: %w", err)
|
return fmt.Errorf("failed to create config directory: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
+133
-24
@@ -9,6 +9,7 @@ import (
|
|||||||
|
|
||||||
"github.com/charmbracelet/bubbles/textinput"
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
|
||||||
"github.com/lukaszraczylo/lolcathost/internal/client"
|
"github.com/lukaszraczylo/lolcathost/internal/client"
|
||||||
"github.com/lukaszraczylo/lolcathost/internal/config"
|
"github.com/lukaszraczylo/lolcathost/internal/config"
|
||||||
@@ -27,6 +28,7 @@ const (
|
|||||||
ViewBackups
|
ViewBackups
|
||||||
ViewHelp
|
ViewHelp
|
||||||
ViewSearch
|
ViewSearch
|
||||||
|
ViewConfirmDelete
|
||||||
)
|
)
|
||||||
|
|
||||||
// Model is the main Bubble Tea model.
|
// Model is the main Bubble Tea model.
|
||||||
@@ -52,6 +54,7 @@ type Model struct {
|
|||||||
messageTime time.Time
|
messageTime time.Time
|
||||||
searchTerm string
|
searchTerm string
|
||||||
allGroups []string // All groups including empty ones
|
allGroups []string // All groups including empty ones
|
||||||
|
pendingDeleteAlias string // Alias of host pending delete confirmation
|
||||||
|
|
||||||
// Update notification
|
// Update notification
|
||||||
updateAvailable bool
|
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))
|
m.setError(fmt.Sprintf("Refresh failed: %v", msg.err))
|
||||||
// Mark as disconnected to trigger reconnect
|
// Mark as disconnected to trigger reconnect
|
||||||
m.connected = false
|
m.connected = false
|
||||||
m.client.Close()
|
_ = m.client.Close()
|
||||||
} else if msg.entries != nil {
|
} else {
|
||||||
|
// Always update the list, even if entries is nil/empty
|
||||||
m.list.SetItems(msg.entries)
|
m.list.SetItems(msg.entries)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -385,7 +389,10 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
m.mode = ViewList
|
m.mode = ViewList
|
||||||
|
|
||||||
case deleteMsg:
|
case deleteMsg:
|
||||||
|
// Clear pending state regardless of success/failure
|
||||||
|
m.list.SetPending(msg.alias, false)
|
||||||
if msg.err != nil {
|
if msg.err != nil {
|
||||||
|
m.list.SetError(msg.alias, true)
|
||||||
m.setError(fmt.Sprintf("Delete failed: %v", msg.err))
|
m.setError(fmt.Sprintf("Delete failed: %v", msg.err))
|
||||||
} else {
|
} else {
|
||||||
cmds = append(cmds, m.refresh())
|
cmds = append(cmds, m.refresh())
|
||||||
@@ -521,6 +528,8 @@ func (m *Model) handleKey(msg tea.KeyMsg) tea.Cmd {
|
|||||||
return m.handleHelpKey(msg)
|
return m.handleHelpKey(msg)
|
||||||
case ViewSearch:
|
case ViewSearch:
|
||||||
return m.handleSearchKey(msg)
|
return m.handleSearchKey(msg)
|
||||||
|
case ViewConfirmDelete:
|
||||||
|
return m.handleConfirmDeleteKey(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -554,7 +563,8 @@ func (m *Model) handleListKey(msg tea.KeyMsg) tea.Cmd {
|
|||||||
}
|
}
|
||||||
case "d":
|
case "d":
|
||||||
if item := m.list.Selected(); item != nil {
|
if item := m.list.Selected(); item != nil {
|
||||||
return m.deleteHost(item.Entry.Alias)
|
m.pendingDeleteAlias = item.Entry.Alias
|
||||||
|
m.mode = ViewConfirmDelete
|
||||||
}
|
}
|
||||||
case "p":
|
case "p":
|
||||||
m.mode = ViewPresets
|
m.mode = ViewPresets
|
||||||
@@ -593,7 +603,7 @@ func (m *Model) handleFormKey(msg tea.KeyMsg) tea.Cmd {
|
|||||||
oldAlias := m.form.EditAlias()
|
oldAlias := m.form.EditAlias()
|
||||||
return tea.Sequence(
|
return tea.Sequence(
|
||||||
func() tea.Msg {
|
func() tea.Msg {
|
||||||
m.client.Delete(oldAlias)
|
_ = m.client.Delete(oldAlias)
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
m.addHost(domain, ip, "", group), // Empty alias = auto-generate
|
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()
|
oldName := m.presetPicker.EditName()
|
||||||
return tea.Sequence(
|
return tea.Sequence(
|
||||||
func() tea.Msg {
|
func() tea.Msg {
|
||||||
m.client.DeletePreset(oldName)
|
_ = m.client.DeletePreset(oldName)
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
m.addPreset(name, enable, disable),
|
m.addPreset(name, enable, disable),
|
||||||
@@ -850,6 +860,23 @@ func (m *Model) handleSearchKey(msg tea.KeyMsg) tea.Cmd {
|
|||||||
return 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 {
|
func (m *Model) toggleSelected() tea.Cmd {
|
||||||
item := m.list.Selected()
|
item := m.list.Selected()
|
||||||
if item == nil {
|
if item == nil {
|
||||||
@@ -904,6 +931,8 @@ func (m *Model) View() string {
|
|||||||
sb.WriteString(m.helpView())
|
sb.WriteString(m.helpView())
|
||||||
case ViewSearch:
|
case ViewSearch:
|
||||||
sb.WriteString(m.searchView())
|
sb.WriteString(m.searchView())
|
||||||
|
case ViewConfirmDelete:
|
||||||
|
sb.WriteString(m.confirmDeleteView())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Message
|
// Message
|
||||||
@@ -920,8 +949,15 @@ func (m *Model) View() string {
|
|||||||
currentContent := sb.String()
|
currentContent := sb.String()
|
||||||
currentLines := strings.Count(currentContent, "\n") + 1
|
currentLines := strings.Count(currentContent, "\n") + 1
|
||||||
|
|
||||||
// Fill space to push footer to bottom (reserve 3 lines for footer)
|
// Calculate footer height dynamically (help bar lines + status bar + spacing)
|
||||||
footerHeight := 3
|
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
|
remainingLines := m.height - currentLines - footerHeight
|
||||||
if remainingLines > 0 {
|
if remainingLines > 0 {
|
||||||
sb.WriteString(strings.Repeat("\n", remainingLines))
|
sb.WriteString(strings.Repeat("\n", remainingLines))
|
||||||
@@ -930,7 +966,7 @@ func (m *Model) View() string {
|
|||||||
// Footer (help bar + status bar)
|
// Footer (help bar + status bar)
|
||||||
if m.mode == ViewList {
|
if m.mode == ViewList {
|
||||||
sb.WriteString("\n")
|
sb.WriteString("\n")
|
||||||
sb.WriteString(m.helpBar())
|
sb.WriteString(helpBarContent)
|
||||||
}
|
}
|
||||||
sb.WriteString("\n")
|
sb.WriteString("\n")
|
||||||
sb.WriteString(m.statusBar())
|
sb.WriteString(m.statusBar())
|
||||||
@@ -939,19 +975,67 @@ func (m *Model) View() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) helpBar() 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",
|
// Define help items with their display widths (without ANSI codes)
|
||||||
helpKeyStyle.Render("↑↓"),
|
type helpItem struct {
|
||||||
helpKeyStyle.Render("jk"),
|
key string
|
||||||
helpKeyStyle.Render("Space"),
|
desc string
|
||||||
helpKeyStyle.Render("n"),
|
rawWidth int // width without ANSI escape codes
|
||||||
helpKeyStyle.Render("e"),
|
}
|
||||||
helpKeyStyle.Render("d"),
|
|
||||||
helpKeyStyle.Render("p"),
|
items := []helpItem{
|
||||||
helpKeyStyle.Render("g"),
|
{"↑↓/jk", "Navigate", 13},
|
||||||
helpKeyStyle.Render("b"),
|
{"Space", "Toggle", 13},
|
||||||
helpKeyStyle.Render("/"),
|
{"n", "New", 6},
|
||||||
helpKeyStyle.Render("?"),
|
{"e", "Edit", 7},
|
||||||
helpKeyStyle.Render("q")))
|
{"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 {
|
func (m *Model) statusBar() string {
|
||||||
@@ -1022,9 +1106,34 @@ func (m *Model) searchView() string {
|
|||||||
return dialogStyle.Render(sb.String())
|
return dialogStyle.Render(sb.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run starts the TUI application.
|
func (m *Model) confirmDeleteView() string {
|
||||||
func Run(socketPath string) error {
|
var sb strings.Builder
|
||||||
return RunWithVersion(socketPath, "dev", "", "")
|
|
||||||
|
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.
|
// 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("\n")
|
||||||
leftSb.WriteString(helpDescStyle.Render("↑↓ navigate • Enter restore • Esc cancel"))
|
leftSb.WriteString(WrapHelpText("↑↓ navigate • Enter restore • Esc cancel", 40))
|
||||||
|
|
||||||
// Build right panel (preview)
|
// Build right panel (preview)
|
||||||
var rightSb strings.Builder
|
var rightSb strings.Builder
|
||||||
@@ -219,7 +219,8 @@ func (b *BackupPicker) selectView() string {
|
|||||||
// Show scroll indicator
|
// Show scroll indicator
|
||||||
if len(lines) > previewHeight {
|
if len(lines) > previewHeight {
|
||||||
rightSb.WriteString("\n")
|
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\n")
|
||||||
|
|
||||||
sb.WriteString("\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())
|
return dialogStyle.Render(sb.String())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -190,7 +190,7 @@ func (g *GroupPicker) selectView() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sb.WriteString("\n\n")
|
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())
|
return dialogStyle.Render(sb.String())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -295,11 +295,6 @@ func (l *ListView) ViewFiltered(searchTerm string) string {
|
|||||||
return sb.String()
|
return sb.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// GroupCount returns the number of groups.
|
|
||||||
func (l *ListView) GroupCount() int {
|
|
||||||
return len(l.groupOrder)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetGroups returns all group names.
|
// GetGroups returns all group names.
|
||||||
func (l *ListView) GetGroups() []string {
|
func (l *ListView) GetGroups() []string {
|
||||||
return l.groupOrder
|
return l.groupOrder
|
||||||
|
|||||||
@@ -407,3 +407,72 @@ func BenchmarkListView_View(b *testing.B) {
|
|||||||
_ = lv.View()
|
_ = 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("\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())
|
return dialogStyle.Render(sb.String())
|
||||||
}
|
}
|
||||||
@@ -483,7 +483,7 @@ func (p *PresetPicker) formView() string {
|
|||||||
}
|
}
|
||||||
sb.WriteString("\n\n")
|
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())
|
return dialogStyle.Render(sb.String())
|
||||||
}
|
}
|
||||||
@@ -536,7 +536,7 @@ func (p *PresetPicker) pickerView() string {
|
|||||||
|
|
||||||
sb.WriteString(titleStyle.Render(title))
|
sb.WriteString(titleStyle.Render(title))
|
||||||
sb.WriteString("\n")
|
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")
|
sb.WriteString("\n\n")
|
||||||
|
|
||||||
filtered := p.getFilteredAliases()
|
filtered := p.getFilteredAliases()
|
||||||
|
|||||||
+68
-3
@@ -2,6 +2,8 @@
|
|||||||
package tui
|
package tui
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/charmbracelet/lipgloss"
|
"github.com/charmbracelet/lipgloss"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -144,7 +146,70 @@ func StatusText(enabled bool, pending bool, hasError bool) string {
|
|||||||
return disabledStyle.Render("○ Disabled")
|
return disabledStyle.Render("○ Disabled")
|
||||||
}
|
}
|
||||||
|
|
||||||
// HelpItem formats a help item.
|
// WrapHelpText wraps help text to fit within maxWidth, splitting on bullet separators.
|
||||||
func HelpItem(key, desc string) string {
|
// If maxWidth is 0 or negative, returns the original text.
|
||||||
return helpKeyStyle.Render(key) + " " + helpDescStyle.Render(desc)
|
func WrapHelpText(text string, maxWidth int) string {
|
||||||
|
if maxWidth <= 0 {
|
||||||
|
return helpDescStyle.Render(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 currentLine != "" {
|
||||||
|
lines = append(lines, currentLine)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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):]
|
||||||
|
}
|
||||||
|
return parts
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,6 +76,7 @@ func (c *Checker) CheckForUpdate(ctx context.Context) *UpdateInfo {
|
|||||||
|
|
||||||
// fetchLatestRelease fetches the latest release info from GitHub API
|
// fetchLatestRelease fetches the latest release info from GitHub API
|
||||||
func (c *Checker) fetchLatestRelease(ctx context.Context) (*ReleaseInfo, error) {
|
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)
|
url := fmt.Sprintf(githubReleasesURL, c.owner, c.repo)
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||||
@@ -145,15 +146,9 @@ func parseVersion(v string) []int {
|
|||||||
|
|
||||||
for _, p := range parts {
|
for _, p := range parts {
|
||||||
var num int
|
var num int
|
||||||
fmt.Sscanf(p, "%d", &num)
|
_, _ = fmt.Sscanf(p, "%d", &num)
|
||||||
result = append(result, num)
|
result = append(result, num)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
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) {
|
func TestNewChecker(t *testing.T) {
|
||||||
checker := NewChecker("lukaszraczylo", "lolcathost", "v1.0.0")
|
checker := NewChecker("lukaszraczylo", "lolcathost", "v1.0.0")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user