mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-06 15:12:30 +09:00
Merge pull request #41 from jhd3197/dev
Redesigned panel, native multi-platform agent, remote tunnels, and a connections hub
This commit is contained in:
304 files changed
+31663
-13264
No files matched your search
@@ -0,0 +1,89 @@
|
||||
name: Agent CI
|
||||
|
||||
# Validates the Go agent on every change: it must vet clean, pass its unit
|
||||
# tests, and — critically — still COMPILE for every platform it ships on. The
|
||||
# cross-compile matrix is what catches "this builds on my machine but breaks
|
||||
# the Windows/macOS build" before it reaches a release, which the
|
||||
# build-only release workflow did not guard on PRs.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [dev, main]
|
||||
paths:
|
||||
- 'agent/**'
|
||||
- '.github/workflows/agent-ci.yml'
|
||||
pull_request:
|
||||
branches: [dev, main]
|
||||
paths:
|
||||
- 'agent/**'
|
||||
- '.github/workflows/agent-ci.yml'
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: agent
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: vet & test (linux)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: agent/go.mod
|
||||
cache-dependency-path: agent/go.sum
|
||||
# The agent embeds the desktop UI via //go:embed all:dist, so the
|
||||
# React app must be built into agent/internal/agentui/dist before any
|
||||
# `go` command — otherwise the embed fails with "no matching files".
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: agent/ui/package-lock.json
|
||||
- name: Build agent UI (required by //go:embed)
|
||||
working-directory: agent/ui
|
||||
run: npm ci && npm run build
|
||||
- name: go vet
|
||||
run: go vet ./...
|
||||
- name: go test
|
||||
run: go test ./... -count=1
|
||||
|
||||
build:
|
||||
name: build (${{ matrix.goos }}/${{ matrix.goarch }})
|
||||
runs-on: ubuntu-latest
|
||||
# darwin is intentionally NOT in this matrix: the tray dependency
|
||||
# (fyne.io/systray) needs the macOS Cocoa toolchain and cannot be
|
||||
# cross-compiled from Linux. It is built on a macOS host at release time
|
||||
# (and is treated as best-effort there). These three targets cover the
|
||||
# real deployment surface — Linux servers and Windows.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- goos: linux
|
||||
goarch: amd64
|
||||
- goos: linux
|
||||
goarch: arm64
|
||||
- goos: windows
|
||||
goarch: amd64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: agent/go.mod
|
||||
cache-dependency-path: agent/go.sum
|
||||
# Build the embedded desktop UI before `go build` (see //go:embed
|
||||
# all:dist in internal/agentui/embed.go).
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: agent/ui/package-lock.json
|
||||
- name: Build agent UI (required by //go:embed)
|
||||
working-directory: agent/ui
|
||||
run: npm ci && npm run build
|
||||
- name: go build
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
run: go build ./...
|
||||
@@ -56,6 +56,19 @@ jobs:
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "Building version: $VERSION"
|
||||
|
||||
# The agent embeds its desktop UI via //go:embed all:dist, so the React
|
||||
# app must be built into agent/internal/agentui/dist before `go build`.
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: agent/ui/package-lock.json
|
||||
|
||||
- name: Build agent UI (required by //go:embed)
|
||||
working-directory: agent/ui
|
||||
run: npm ci && npm run build
|
||||
|
||||
- name: Build binary
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
name: Backend CI
|
||||
|
||||
# Runs the full backend pytest suite on every change to backend/. This is the
|
||||
# net that catches regressions in the panel — including the agent gateway,
|
||||
# registry, pairing, and the panel<->agent command loop exercised end-to-end
|
||||
# by tests/test_agent_poll_e2e.py — instead of finding out at install time.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [dev, main]
|
||||
paths:
|
||||
- 'backend/**'
|
||||
- '.github/workflows/backend-ci.yml'
|
||||
pull_request:
|
||||
branches: [dev, main]
|
||||
paths:
|
||||
- 'backend/**'
|
||||
- '.github/workflows/backend-ci.yml'
|
||||
|
||||
jobs:
|
||||
pytest:
|
||||
name: pytest
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
cache: pip
|
||||
cache-dependency-path: backend/requirements.txt
|
||||
- name: Install dependencies
|
||||
working-directory: backend
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements.txt
|
||||
pip install pytest
|
||||
- name: Run tests
|
||||
working-directory: backend
|
||||
run: python -m pytest -v
|
||||
@@ -128,3 +128,5 @@ docs/PLAN_AGENT_FLEET.md
|
||||
/.claude
|
||||
/.github/skills
|
||||
/.playwright-mcp
|
||||
docs/UI_CONSISTENCY_AUDIT.md
|
||||
docs/REMOTE_ACCESS_ROADMAP.md
|
||||
+7
-3
@@ -34,9 +34,13 @@ trust boundaries:
|
||||
|
||||
- **`agent.key` is a host-equivalent secret.** Agent API credentials are stored
|
||||
AES-256-GCM encrypted under a key derived from host-stable identifiers
|
||||
(hostname + machine ID on Linux, hostname + computer name on Windows). Anyone
|
||||
who can read this file on the host — or recreate the host-derived key — can
|
||||
recover the credentials. Protect it like a root/SYSTEM secret.
|
||||
(hostname + machine ID on Linux, hostname + computer name on Windows). Because
|
||||
that key is derived only from values available on the host itself, the
|
||||
encryption is at-rest tamper-resistance / off-host-exfil protection (e.g. a
|
||||
leaked backup) — **not** confidentiality against a local root/SYSTEM user, who
|
||||
can re-derive the key. Anyone who can read this file on the host can recover
|
||||
the credentials. The `0600` file permissions are the real access control;
|
||||
protect it like a root/SYSTEM secret.
|
||||
- **Remote command execution is gated.** Arbitrary command execution
|
||||
(`system:exec`) and interactive PTY sessions are controlled by the agent's
|
||||
`Features.Exec` flag, which is **off by default**. Enable it only on servers
|
||||
|
||||
+4
-4
@@ -55,10 +55,10 @@ build-all:
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "$(WINDOWS_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-amd64.exe ./cmd/agent
|
||||
@echo "Building for Windows arm64..."
|
||||
CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags "$(WINDOWS_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-windows-arm64.exe ./cmd/agent
|
||||
@echo "Building for macOS amd64..."
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-amd64 ./cmd/agent
|
||||
@echo "Building for macOS arm64..."
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-arm64 ./cmd/agent
|
||||
@echo "Building for macOS amd64... (non-fatal: systray needs CGO on darwin, so this only works on a Mac)"
|
||||
-CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-amd64 ./cmd/agent
|
||||
@echo "Building for macOS arm64... (non-fatal)"
|
||||
-CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build -ldflags "$(AGENT_LDFLAGS)" -o $(DIST_DIR)/$(BINARY_NAME)-$(VERSION)-darwin-arm64 ./cmd/agent
|
||||
@echo "Done! Binaries in $(DIST_DIR)/"
|
||||
|
||||
# Build Linux only
|
||||
|
||||
+19
-2
@@ -110,6 +110,21 @@ func registerCmd() *cobra.Command {
|
||||
Use: "register",
|
||||
Short: "Register this agent with a ServerKit instance",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
// Let the secret-bearing inputs come from the environment so the
|
||||
// installer never has to put the registration token in argv —
|
||||
// process arguments are world-readable (`ps`, /proc/<pid>/cmdline),
|
||||
// whereas a process's environment is readable only by its owner and
|
||||
// root. Explicit flags still win when provided.
|
||||
if connStr == "" {
|
||||
connStr = os.Getenv("SERVERKIT_CONNECTION_STRING")
|
||||
}
|
||||
if token == "" {
|
||||
token = os.Getenv("SERVERKIT_REGISTRATION_TOKEN")
|
||||
}
|
||||
if serverURL == "" {
|
||||
serverURL = os.Getenv("SERVERKIT_SERVER_URL")
|
||||
}
|
||||
|
||||
// --connection-string is the modern entry path: a single
|
||||
// pasteable blob from the panel that already contains the
|
||||
// URL and token. When present, it overrides the legacy
|
||||
@@ -128,8 +143,10 @@ func registerCmd() *cobra.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&connStr, "connection-string", "c", "", "panel connection string (single value, replaces --token + --server)")
|
||||
cmd.Flags().StringVarP(&token, "token", "t", "", "registration token (use with --server)")
|
||||
// no shorthand: "c" belongs to the global --config persistent flag, and
|
||||
// pflag panics on shorthand redefinition the moment any command runs
|
||||
cmd.Flags().StringVar(&connStr, "connection-string", "", "panel connection string (single value, replaces --token + --server)")
|
||||
cmd.Flags().StringVarP(&token, "token", "t", "", "registration token (use with --server; or set SERVERKIT_REGISTRATION_TOKEN to keep it out of the process arg list)")
|
||||
cmd.Flags().StringVarP(&serverURL, "server", "s", "", "ServerKit server URL (use with --token)")
|
||||
cmd.Flags().StringVarP(&name, "name", "n", "", "display name for this server")
|
||||
|
||||
|
||||
+16
-10
@@ -1,16 +1,20 @@
|
||||
module github.com/serverkit/agent
|
||||
|
||||
go 1.23.0
|
||||
go 1.23.1
|
||||
|
||||
require (
|
||||
fyne.io/systray v1.11.0
|
||||
github.com/creack/pty v1.1.21
|
||||
github.com/docker/docker v24.0.7+incompatible
|
||||
github.com/docker/go-connections v0.4.0
|
||||
github.com/gorilla/websocket v1.5.1
|
||||
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808
|
||||
github.com/lxn/walk v0.0.0-20210112085537-c389da54e794
|
||||
github.com/shirou/gopsutil/v3 v3.24.1
|
||||
github.com/spf13/cobra v1.8.0
|
||||
golang.org/x/term v0.27.0
|
||||
golang.org/x/sys v0.32.0
|
||||
golang.org/x/term v0.31.0
|
||||
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
@@ -19,20 +23,19 @@ require (
|
||||
github.com/Microsoft/go-winio v0.6.1 // indirect
|
||||
github.com/distribution/reference v0.5.0 // indirect
|
||||
github.com/docker/distribution v2.8.3+incompatible // indirect
|
||||
github.com/docker/go-connections v0.4.0 // indirect
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/google/btree v1.1.2 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 // indirect
|
||||
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20231016141302-07b5767bb0ed // indirect
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e // indirect
|
||||
github.com/moby/term v0.5.0 // indirect
|
||||
github.com/morikuni/aec v1.0.0 // indirect
|
||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||
github.com/opencontainers/image-spec v1.1.0-rc5 // indirect
|
||||
github.com/opencontainers/image-spec v1.1.0 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect
|
||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||
@@ -40,11 +43,14 @@ require (
|
||||
github.com/tklauser/go-sysconf v0.3.13 // indirect
|
||||
github.com/tklauser/numcpus v0.7.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.3 // indirect
|
||||
golang.org/x/mod v0.14.0 // indirect
|
||||
golang.org/x/net v0.19.0 // indirect
|
||||
golang.org/x/sys v0.28.0 // indirect
|
||||
golang.org/x/time v0.5.0 // indirect
|
||||
golang.org/x/tools v0.16.1 // indirect
|
||||
golang.org/x/crypto v0.37.0 // indirect
|
||||
golang.org/x/mod v0.21.0 // indirect
|
||||
golang.org/x/net v0.39.0 // indirect
|
||||
golang.org/x/sync v0.8.0 // indirect
|
||||
golang.org/x/time v0.7.0 // indirect
|
||||
golang.org/x/tools v0.26.0 // indirect
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
|
||||
gopkg.in/Knetic/govaluate.v3 v3.0.0 // indirect
|
||||
gotest.tools/v3 v3.5.1 // indirect
|
||||
gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c // indirect
|
||||
)
|
||||
+26
-16
@@ -27,6 +27,8 @@ github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU=
|
||||
github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
@@ -54,8 +56,8 @@ github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.0-rc5 h1:Ygwkfw9bpDvs+c9E34SdgGOj41dX/cbdlwvlWt0pnFI=
|
||||
github.com/opencontainers/image-spec v1.1.0-rc5/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8=
|
||||
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||
github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
@@ -94,21 +96,23 @@ github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQ
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
|
||||
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=
|
||||
golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0=
|
||||
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
|
||||
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
|
||||
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
|
||||
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
|
||||
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -121,24 +125,28 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=
|
||||
golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
||||
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ=
|
||||
golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA=
|
||||
golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0=
|
||||
golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ=
|
||||
golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7ikgyX57D+XvtcSnGylsLkOVhta/w=
|
||||
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw=
|
||||
gopkg.in/Knetic/govaluate.v3 v3.0.0 h1:18mUyIt4ZlRlFZAAfVetz4/rzlJs9yhN+U02F4u1AOc=
|
||||
gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
@@ -150,3 +158,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=
|
||||
gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=
|
||||
gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c h1:m/r7OM+Y2Ty1sgBQ7Qb27VgIMBW8ZZhT4gLnUyDIhzI=
|
||||
gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c/go.mod h1:3r5CMtNQMKIvBlrmM9xWUNamjKBYPOWyXOjmg5Kts3g=
|
||||
@@ -32,29 +32,31 @@ import (
|
||||
"github.com/serverkit/agent/internal/transport"
|
||||
"github.com/serverkit/agent/internal/transport/poll"
|
||||
"github.com/serverkit/agent/internal/updater"
|
||||
"github.com/serverkit/agent/internal/wireguard"
|
||||
"github.com/serverkit/agent/internal/ws"
|
||||
"github.com/serverkit/agent/pkg/protocol"
|
||||
)
|
||||
|
||||
// Agent is the main agent that coordinates all components
|
||||
type Agent struct {
|
||||
cfg *config.Config
|
||||
log *logger.Logger
|
||||
auth *auth.Authenticator
|
||||
cfg *config.Config
|
||||
log *logger.Logger
|
||||
auth *auth.Authenticator
|
||||
// ws is the active transport — either the WS client directly or the
|
||||
// fallback Manager that wraps WS+poll. Named "ws" for compatibility
|
||||
// with the dozens of existing call sites in this file.
|
||||
ws transport.Transport
|
||||
ws transport.Transport
|
||||
docker *docker.Client
|
||||
metrics *metrics.Collector
|
||||
terminal *terminal.Manager
|
||||
cron cron.Manager
|
||||
cloudflared cloudflared.Manager
|
||||
wireguard wireguard.Manager
|
||||
ipc *ipc.Server
|
||||
sampler *metricSampler
|
||||
events *events.Store
|
||||
gui *gui.SDK
|
||||
jobs *jobs.Registry
|
||||
sampler *metricSampler
|
||||
events *events.Store
|
||||
gui *gui.SDK
|
||||
jobs *jobs.Registry
|
||||
|
||||
// pkgLock serializes package-manager mutations (install / remove /
|
||||
// upgrade / update_cache) inside a single agent so two concurrent
|
||||
@@ -144,6 +146,14 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {
|
||||
}
|
||||
eventStore := events.NewStore(200, events.DefaultPath(dataDir))
|
||||
|
||||
// WireGuard private keys live in a root-only subdir of the agent's
|
||||
// data dir; empty dataDir falls back to a system default inside the
|
||||
// wireguard package.
|
||||
wgKeyDir := ""
|
||||
if dataDir != "" {
|
||||
wgKeyDir = filepath.Join(dataDir, "wireguard")
|
||||
}
|
||||
|
||||
agent := &Agent{
|
||||
cfg: cfg,
|
||||
log: log,
|
||||
@@ -154,6 +164,7 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {
|
||||
terminal: termManager,
|
||||
cron: cron.New(),
|
||||
cloudflared: cloudflared.New(),
|
||||
wireguard: wireguard.New(wgKeyDir),
|
||||
sampler: newMetricSampler(300), // 5 min @ 1 Hz
|
||||
events: eventStore,
|
||||
gui: gui.New(log),
|
||||
@@ -166,7 +177,7 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {
|
||||
// At most one restart can be in-flight at a time anyway —
|
||||
// Restart() uses a non-blocking send and returns "already in
|
||||
// progress" if the slot is full.
|
||||
restartCh: make(chan struct{}, 1),
|
||||
restartCh: make(chan struct{}, 1),
|
||||
}
|
||||
|
||||
// Probe capabilities up-front so connectionWatcher can ship them on
|
||||
@@ -289,6 +300,24 @@ func (a *Agent) registerHandlers() {
|
||||
a.handlers[protocol.ActionCloudflaredTunnelRoute] = a.handleCloudflaredTunnelRoute
|
||||
a.handlers[protocol.ActionCloudflaredTunnelDelete] = a.handleCloudflaredTunnelDelete
|
||||
|
||||
// WireGuard tunnel primitives. Registered unconditionally so
|
||||
// non-Linux agents return a clear "unsupported" error rather than
|
||||
// "unknown action"; the `wireguard` capability gates the panel's
|
||||
// Remote Access flow. See docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
a.handlers[protocol.ActionWireguardKeygen] = a.handleWireguardKeygen
|
||||
a.handlers[protocol.ActionWireguardInterfaceUp] = a.handleWireguardInterfaceUp
|
||||
a.handlers[protocol.ActionWireguardInterfaceDown] = a.handleWireguardInterfaceDown
|
||||
a.handlers[protocol.ActionWireguardPeerSet] = a.handleWireguardPeerSet
|
||||
a.handlers[protocol.ActionWireguardPeerRemove] = a.handleWireguardPeerRemove
|
||||
a.handlers[protocol.ActionWireguardStatus] = a.handleWireguardStatus
|
||||
a.handlers[protocol.ActionWireguardForward] = a.handleWireguardForward
|
||||
a.handlers[protocol.ActionWireguardUnforward] = a.handleWireguardUnforward
|
||||
|
||||
// Firewall — used by the tunnel broker to open the edge's WireGuard
|
||||
// UDP port (#10). Linux-only; returns a clear error elsewhere.
|
||||
a.handlers[protocol.ActionFirewallAllowPort] = a.handleFirewallAllowPort
|
||||
a.handlers[protocol.ActionFirewallDenyPort] = a.handleFirewallDenyPort
|
||||
|
||||
// Phase 4 primitives — packages, systemd, exec. Registered
|
||||
// unconditionally so non-Linux agents return a clear error rather
|
||||
// than "unknown action"; the capability probe gates the panel's
|
||||
@@ -999,8 +1028,9 @@ func (a *Agent) handleCredentialUpdate(data []byte) {
|
||||
// only when the signature is present, well-formed, and matches.
|
||||
//
|
||||
// The panel must compute hex(HMAC-SHA256(
|
||||
// "rotation_id:agent_id:new_api_key:new_api_secret",
|
||||
// current_api_secret)).
|
||||
//
|
||||
// "rotation_id:agent_id:new_api_key:new_api_secret",
|
||||
// current_api_secret)).
|
||||
func (a *Agent) verifyCredentialRotation(msg protocol.CredentialUpdateMessage) error {
|
||||
if msg.RotationID == "" || msg.APIKey == "" || msg.APISecret == "" {
|
||||
return fmt.Errorf("rotation message missing required fields")
|
||||
@@ -1781,7 +1811,7 @@ func (a *Agent) handleAgentUpdate(ctx context.Context, params json.RawMessage) (
|
||||
// In a real implementation, we would use the provided URLs
|
||||
// For now, we'll let the updater handle it using its default logic
|
||||
// or extend it to use the provided URLs.
|
||||
|
||||
|
||||
err := u.UpdateTo(context.Background(), p.Version, p.DownloadURL, p.ChecksumsURL)
|
||||
if err != nil {
|
||||
a.log.Error("Update failed", "error", err)
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Handlers for firewall:* actions. Minimal host-firewall control so the
|
||||
// tunnel broker can open the edge's inbound WireGuard UDP port (roadmap
|
||||
// #10). Linux-only; tries ufw → firewalld → iptables, first present.
|
||||
// Requires root (the agent already runs privileged for systemd/packages);
|
||||
// failures return a clear error and the broker falls back to surfacing
|
||||
// the manual command.
|
||||
|
||||
func (a *Agent) handleFirewallAllowPort(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
return firewallPort(params, true)
|
||||
}
|
||||
|
||||
func (a *Agent) handleFirewallDenyPort(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
return firewallPort(params, false)
|
||||
}
|
||||
|
||||
func firewallPort(params json.RawMessage, allow bool) (interface{}, error) {
|
||||
var p struct {
|
||||
Port int `json:"port"`
|
||||
Protocol string `json:"protocol"`
|
||||
}
|
||||
if err := json.Unmarshal(params, &p); err != nil {
|
||||
return nil, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
if p.Port < 1 || p.Port > 65535 {
|
||||
return nil, fmt.Errorf("invalid port %d", p.Port)
|
||||
}
|
||||
proto := strings.ToLower(strings.TrimSpace(p.Protocol))
|
||||
if proto != "tcp" && proto != "udp" {
|
||||
proto = "udp"
|
||||
}
|
||||
if runtime.GOOS != "linux" {
|
||||
return nil, fmt.Errorf("firewall management is only supported on Linux agents")
|
||||
}
|
||||
spec := fmt.Sprintf("%d/%s", p.Port, proto)
|
||||
|
||||
if _, err := exec.LookPath("ufw"); err == nil {
|
||||
action := "allow"
|
||||
if !allow {
|
||||
action = "deny"
|
||||
}
|
||||
if out, err := exec.Command("ufw", action, spec).CombinedOutput(); err != nil {
|
||||
return nil, fmt.Errorf("ufw %s %s: %w (%s)", action, spec, err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return map[string]interface{}{"success": true, "method": "ufw", "spec": spec}, nil
|
||||
}
|
||||
|
||||
if _, err := exec.LookPath("firewall-cmd"); err == nil {
|
||||
flag := "--add-port"
|
||||
if !allow {
|
||||
flag = "--remove-port"
|
||||
}
|
||||
if out, err := exec.Command("firewall-cmd", flag+"="+spec).CombinedOutput(); err != nil {
|
||||
return nil, fmt.Errorf("firewall-cmd %s=%s: %w (%s)", flag, spec, err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
// Persist across reboots (best-effort) + reload.
|
||||
_, _ = exec.Command("firewall-cmd", flag+"="+spec, "--permanent").CombinedOutput()
|
||||
_, _ = exec.Command("firewall-cmd", "--reload").CombinedOutput()
|
||||
return map[string]interface{}{"success": true, "method": "firewalld", "spec": spec}, nil
|
||||
}
|
||||
|
||||
if _, err := exec.LookPath("iptables"); err == nil {
|
||||
op := "-I" // insert (allow)
|
||||
if !allow {
|
||||
op = "-D" // delete the rule
|
||||
}
|
||||
out, err := exec.Command("iptables", op, "INPUT", "-p", proto, "--dport", strconv.Itoa(p.Port), "-j", "ACCEPT").CombinedOutput()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("iptables %s %s: %w (%s)", op, spec, err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return map[string]interface{}{"success": true, "method": "iptables", "spec": spec}, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("no supported firewall found (ufw / firewalld / iptables)")
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/serverkit/agent/internal/wireguard"
|
||||
)
|
||||
|
||||
// Handlers for wireguard:* actions. Thin parse + dispatch; validation
|
||||
// lives in the wireguard package. The panel's tunnel broker
|
||||
// (backend/app/services/tunnel_broker_service.py) sequences these to
|
||||
// pair two agents. See docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
|
||||
func (a *Agent) handleWireguardKeygen(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
var p struct {
|
||||
Interface string `json:"interface"`
|
||||
}
|
||||
if err := json.Unmarshal(params, &p); err != nil {
|
||||
return nil, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
return a.wireguard.Keygen(p.Interface)
|
||||
}
|
||||
|
||||
func (a *Agent) handleWireguardInterfaceUp(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
var req wireguard.InterfaceUpRequest
|
||||
if err := json.Unmarshal(params, &req); err != nil {
|
||||
return nil, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
if err := a.wireguard.InterfaceUp(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]bool{"success": true}, nil
|
||||
}
|
||||
|
||||
func (a *Agent) handleWireguardInterfaceDown(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
var p struct {
|
||||
Interface string `json:"interface"`
|
||||
}
|
||||
if err := json.Unmarshal(params, &p); err != nil {
|
||||
return nil, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
if err := a.wireguard.InterfaceDown(p.Interface); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]bool{"success": true}, nil
|
||||
}
|
||||
|
||||
func (a *Agent) handleWireguardPeerSet(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
var req wireguard.PeerSetRequest
|
||||
if err := json.Unmarshal(params, &req); err != nil {
|
||||
return nil, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
if err := a.wireguard.SetPeer(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]bool{"success": true}, nil
|
||||
}
|
||||
|
||||
func (a *Agent) handleWireguardPeerRemove(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
var req wireguard.PeerRemoveRequest
|
||||
if err := json.Unmarshal(params, &req); err != nil {
|
||||
return nil, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
if err := a.wireguard.RemovePeer(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]bool{"success": true}, nil
|
||||
}
|
||||
|
||||
func (a *Agent) handleWireguardStatus(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
var p struct {
|
||||
Interface string `json:"interface"`
|
||||
}
|
||||
if err := json.Unmarshal(params, &p); err != nil {
|
||||
return nil, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
return a.wireguard.Status(p.Interface)
|
||||
}
|
||||
|
||||
func (a *Agent) handleWireguardForward(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
var req wireguard.ForwardRequest
|
||||
if err := json.Unmarshal(params, &req); err != nil {
|
||||
return nil, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
if err := a.wireguard.Forward(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]bool{"success": true}, nil
|
||||
}
|
||||
|
||||
func (a *Agent) handleWireguardUnforward(_ context.Context, params json.RawMessage) (interface{}, error) {
|
||||
var p struct {
|
||||
Interface string `json:"interface"`
|
||||
ListenPort int `json:"listen_port"`
|
||||
}
|
||||
if err := json.Unmarshal(params, &p); err != nil {
|
||||
return nil, fmt.Errorf("invalid params: %w", err)
|
||||
}
|
||||
if err := a.wireguard.Unforward(p.Interface, p.ListenPort); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]bool{"success": true}, nil
|
||||
}
|
||||
@@ -18,6 +18,17 @@ func waitForServiceRunning(timeout time.Duration) error {
|
||||
return fmt.Errorf("service control not implemented on this platform")
|
||||
}
|
||||
|
||||
// isServiceInstalled reports false on non-Windows so the pairing flow skips
|
||||
// the SCM stop/start dance entirely (there is no service manager to drive;
|
||||
// systemd integration lands with the cross-platform service controls).
|
||||
func isServiceInstalled() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func waitForServiceStopped(timeout time.Duration) error {
|
||||
return fmt.Errorf("service control not implemented on this platform")
|
||||
}
|
||||
|
||||
func openTarget(target string) error {
|
||||
return fmt.Errorf("open not implemented on this platform")
|
||||
}
|
||||
|
||||
@@ -64,6 +64,15 @@ func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool, fileAc
|
||||
// happens in the cloudflared:status action).
|
||||
caps["cloudflared"] = probeCloudflared()
|
||||
|
||||
// WireGuard — the agent can manage a tunnel interface: kernel WG on
|
||||
// Linux (`wg` + `ip`), userspace wireguard-go on Windows/macOS. The
|
||||
// panel gates the Remote Access / tunnel flow on this.
|
||||
caps["wireguard"] = probeWireguard()
|
||||
|
||||
// Firewall — a supported host firewall is present so the broker can
|
||||
// open the edge's WireGuard UDP port (#10). Linux-only.
|
||||
caps["firewall"] = probeFirewall()
|
||||
|
||||
// Language runtimes — best-effort version probes. A missing key
|
||||
// means "not installed"; an empty string means "installed but
|
||||
// `--version` parse failed" so the panel can still light up the
|
||||
@@ -95,6 +104,8 @@ func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool, fileAc
|
||||
"php_fpm", caps["php_fpm"],
|
||||
"packages", caps["packages"],
|
||||
"cloudflared", caps["cloudflared"],
|
||||
"wireguard", caps["wireguard"],
|
||||
"firewall", caps["firewall"],
|
||||
"runtimes", runtimes,
|
||||
)
|
||||
}
|
||||
@@ -126,6 +137,26 @@ func probeCloudflared() bool {
|
||||
return hasOnPath("cloudflared")
|
||||
}
|
||||
|
||||
// probeWireguard — whether the agent can manage a WireGuard interface.
|
||||
// On Linux that needs the kernel tools (`wg` + `ip`); on Windows/macOS
|
||||
// the userspace wireguard-go backend (roadmap #6) is always available.
|
||||
func probeWireguard() bool {
|
||||
if runtime.GOOS == "linux" {
|
||||
return hasOnPath("wg") && hasOnPath("ip")
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// probeFirewall — true on Linux when a supported host firewall
|
||||
// (ufw / firewalld / iptables) is on PATH, so the tunnel broker can open
|
||||
// the edge's WireGuard UDP port (#10).
|
||||
func probeFirewall() bool {
|
||||
if runtime.GOOS != "linux" {
|
||||
return false
|
||||
}
|
||||
return hasOnPath("ufw") || hasOnPath("firewall-cmd") || hasOnPath("iptables")
|
||||
}
|
||||
|
||||
// probeRuntimes detects common language runtimes by shelling out to
|
||||
// each "<bin> --version" and parsing the first line. Versions are kept
|
||||
// as raw strings (e.g. "3.11.4", "20.10.0", "8.2.0") so consumers can
|
||||
|
||||
@@ -872,7 +872,15 @@ func (c *Client) ComposePull(ctx context.Context, projectPath, service string) (
|
||||
return string(output), nil
|
||||
}
|
||||
|
||||
// validateProjectPath validates the project path to prevent path traversal attacks
|
||||
// validateProjectPath is a syntactic sanity check on a compose project path
|
||||
// (non-empty, absolute, no `..` traversal). It is NOT the authorization
|
||||
// boundary: the real restriction to the operator-configured roots is the
|
||||
// symlink-resolved allowlist in the agent layer
|
||||
// (agent.validateFileAccess → resolveSymlinkPath/pathWithinAllowedRoot),
|
||||
// which every compose handler in internal/agent/agent.go runs on the
|
||||
// project_path BEFORE calling these Compose* methods. Any NEW caller of the
|
||||
// Compose* API must perform that AllowedPaths check first — this function
|
||||
// alone does not confine paths to AllowedPaths.
|
||||
func validateProjectPath(projectPath string) error {
|
||||
if projectPath == "" {
|
||||
return fmt.Errorf("project path is required")
|
||||
|
||||
@@ -140,6 +140,9 @@ func (u *Updater) DownloadUpdate(ctx context.Context, info *VersionInfo) (string
|
||||
if info.DownloadURL == "" {
|
||||
return "", fmt.Errorf("no download URL available")
|
||||
}
|
||||
if err := requireSecureURL(info.DownloadURL); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
u.log.Info("Downloading update", "version", info.LatestVersion, "url", info.DownloadURL)
|
||||
|
||||
@@ -163,14 +166,20 @@ func (u *Updater) DownloadUpdate(ctx context.Context, info *VersionInfo) (string
|
||||
return "", fmt.Errorf("failed to download update: %w", err)
|
||||
}
|
||||
|
||||
// Verify checksum if available
|
||||
if info.ChecksumsURL != "" {
|
||||
if err := u.verifyChecksum(ctx, archivePath, info.ChecksumsURL); err != nil {
|
||||
os.RemoveAll(tmpDir)
|
||||
return "", fmt.Errorf("checksum verification failed: %w", err)
|
||||
}
|
||||
u.log.Info("Checksum verified successfully")
|
||||
// Verify checksum — MANDATORY and fail-closed. Refuse to install an update
|
||||
// that arrives without a checksums URL, or whose checksum we can't match,
|
||||
// rather than running an unverified binary as the agent (often root).
|
||||
// Cryptographic signing of releases is the recommended next layer; until
|
||||
// then this at least prevents silent integrity bypass.
|
||||
if info.ChecksumsURL == "" {
|
||||
os.RemoveAll(tmpDir)
|
||||
return "", fmt.Errorf("refusing to install update: no checksums URL provided")
|
||||
}
|
||||
if err := u.verifyChecksum(ctx, archivePath, info.ChecksumsURL); err != nil {
|
||||
os.RemoveAll(tmpDir)
|
||||
return "", fmt.Errorf("checksum verification failed: %w", err)
|
||||
}
|
||||
u.log.Info("Checksum verified successfully")
|
||||
|
||||
// Extract binary
|
||||
binaryPath, err := u.extractBinary(archivePath, tmpDir)
|
||||
@@ -307,6 +316,10 @@ func (u *Updater) downloadFile(ctx context.Context, url, destPath string) error
|
||||
}
|
||||
|
||||
func (u *Updater) verifyChecksum(ctx context.Context, filePath, checksumsURL string) error {
|
||||
if err := requireSecureURL(checksumsURL); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Download checksums file
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", checksumsURL, nil)
|
||||
if err != nil {
|
||||
@@ -319,21 +332,18 @@ func (u *Updater) verifyChecksum(ctx context.Context, filePath, checksumsURL str
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// A non-200 (e.g. a 404 HTML page) must not be treated as "no checksum
|
||||
// available" — that previously degraded into skipping verification.
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("failed to fetch checksums: status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
checksumsData, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Parse checksums
|
||||
checksums := make(map[string]string)
|
||||
for _, line := range strings.Split(string(checksumsData), "\n") {
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) >= 2 {
|
||||
checksums[parts[1]] = parts[0]
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate file hash
|
||||
// Stream the archive through SHA-256 so we don't buffer the whole file.
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -346,34 +356,55 @@ func (u *Updater) verifyChecksum(ctx context.Context, filePath, checksumsURL str
|
||||
}
|
||||
actualHash := hex.EncodeToString(hasher.Sum(nil))
|
||||
|
||||
// Find expected hash
|
||||
fileName := filepath.Base(filePath)
|
||||
// Try to match by looking for platform-specific name
|
||||
expectedHash := ""
|
||||
return matchChecksum(actualHash, string(checksumsData))
|
||||
}
|
||||
|
||||
// matchChecksum verifies actualHash against the entry for this platform in a
|
||||
// checksums.txt body. It FAILS CLOSED: an empty/unparseable body, no entry
|
||||
// matching this GOOS/GOARCH, or a hash mismatch all return an error. The old
|
||||
// implementation returned nil ("skip verification") when no entry matched,
|
||||
// which let a crafted or truncated checksums file disable integrity entirely.
|
||||
func matchChecksum(actualHash, checksumsBody string) error {
|
||||
checksums := make(map[string]string)
|
||||
for _, line := range strings.Split(checksumsBody, "\n") {
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) >= 2 {
|
||||
checksums[parts[1]] = parts[0]
|
||||
}
|
||||
}
|
||||
if len(checksums) == 0 {
|
||||
return fmt.Errorf("checksums file contained no usable entries")
|
||||
}
|
||||
|
||||
expected := ""
|
||||
for name, hash := range checksums {
|
||||
if strings.Contains(name, runtime.GOOS) && strings.Contains(name, runtime.GOARCH) {
|
||||
expectedHash = hash
|
||||
expected = hash
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if expectedHash == "" {
|
||||
// Try exact match
|
||||
if hash, ok := checksums[fileName]; ok {
|
||||
expectedHash = hash
|
||||
}
|
||||
if expected == "" {
|
||||
return fmt.Errorf("no checksum entry for %s/%s in checksums file", runtime.GOOS, runtime.GOARCH)
|
||||
}
|
||||
|
||||
if expectedHash == "" {
|
||||
u.log.Warn("Could not find checksum for downloaded file, skipping verification")
|
||||
if !strings.EqualFold(actualHash, expected) {
|
||||
return fmt.Errorf("checksum mismatch: expected %s, got %s", expected, actualHash)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// requireSecureURL rejects non-HTTPS update/checksum URLs so an on-path
|
||||
// attacker can't serve a downgraded plaintext binary. The same
|
||||
// SERVERKIT_INSECURE_TLS escape hatch the rest of the agent honours allows
|
||||
// http:// for local development.
|
||||
func requireSecureURL(raw string) error {
|
||||
if strings.HasPrefix(strings.ToLower(raw), "https://") {
|
||||
return nil
|
||||
}
|
||||
|
||||
if actualHash != expectedHash {
|
||||
return fmt.Errorf("checksum mismatch: expected %s, got %s", expectedHash, actualHash)
|
||||
if os.Getenv("SERVERKIT_INSECURE_TLS") == "true" {
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
return fmt.Errorf("refusing non-HTTPS update URL: %s", raw)
|
||||
}
|
||||
|
||||
func (u *Updater) extractBinary(archivePath, destDir string) (string, error) {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func hashOf(b []byte) string {
|
||||
s := sha256.Sum256(b)
|
||||
return hex.EncodeToString(s[:])
|
||||
}
|
||||
|
||||
// platformName is a checksums.txt filename that matches the host this test
|
||||
// runs on, so matchChecksum's GOOS/GOARCH substring match finds it.
|
||||
func platformName() string {
|
||||
return fmt.Sprintf("serverkit-agent-%s-%s.tar.gz", runtime.GOOS, runtime.GOARCH)
|
||||
}
|
||||
|
||||
func TestMatchChecksum_ValidPasses(t *testing.T) {
|
||||
data := []byte("pretend archive contents")
|
||||
good := hashOf(data)
|
||||
body := good + " " + platformName() + "\n"
|
||||
if err := matchChecksum(good, body); err != nil {
|
||||
t.Fatalf("expected verification to pass, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchChecksum_MismatchFails(t *testing.T) {
|
||||
good := hashOf([]byte("the real archive"))
|
||||
wrong := hashOf([]byte("a tampered archive"))
|
||||
body := wrong + " " + platformName() + "\n"
|
||||
if err := matchChecksum(good, body); err == nil {
|
||||
t.Fatal("expected a mismatch error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchChecksum_NoMatchingEntryFailsClosed(t *testing.T) {
|
||||
good := hashOf([]byte("archive"))
|
||||
// An entry that cannot match this host's GOOS/GOARCH. The old code returned
|
||||
// nil here ("skip verification") — the bug this guards against.
|
||||
body := good + " serverkit-agent-xxos-yyarch.tar.gz\n"
|
||||
if err := matchChecksum(good, body); err == nil {
|
||||
t.Fatal("expected fail-closed when no entry matches the platform, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchChecksum_EmptyBodyFails(t *testing.T) {
|
||||
good := hashOf([]byte("archive"))
|
||||
if err := matchChecksum(good, ""); err == nil {
|
||||
t.Fatal("expected error on empty checksums body, got nil")
|
||||
}
|
||||
if err := matchChecksum(good, "not a valid checksums line\n"); err == nil {
|
||||
t.Fatal("expected error on a body with no usable entries, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchChecksum_CaseInsensitiveHash(t *testing.T) {
|
||||
data := []byte("archive")
|
||||
good := hashOf(data)
|
||||
body := strings.ToUpper(good) + " " + platformName() + "\n"
|
||||
if err := matchChecksum(good, body); err != nil {
|
||||
t.Fatalf("expected case-insensitive hash comparison to pass, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireSecureURL(t *testing.T) {
|
||||
if err := requireSecureURL("https://example.com/agent.tar.gz"); err != nil {
|
||||
t.Fatalf("https URL should be accepted, got: %v", err)
|
||||
}
|
||||
if err := requireSecureURL("HTTPS://Example.com/x"); err != nil {
|
||||
t.Fatalf("https scheme check should be case-insensitive, got: %v", err)
|
||||
}
|
||||
|
||||
// http must be rejected unless the insecure dev flag is set.
|
||||
os.Unsetenv("SERVERKIT_INSECURE_TLS")
|
||||
if err := requireSecureURL("http://example.com/agent.tar.gz"); err == nil {
|
||||
t.Fatal("http URL should be rejected without SERVERKIT_INSECURE_TLS")
|
||||
}
|
||||
t.Setenv("SERVERKIT_INSECURE_TLS", "true")
|
||||
if err := requireSecureURL("http://localhost:5000/agent.tar.gz"); err != nil {
|
||||
t.Fatalf("http should be allowed when SERVERKIT_INSECURE_TLS=true, got: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
// Package wireguard manages a WireGuard interface on the agent host so
|
||||
// the panel can pair two agents into a NAT-traversing tunnel (the
|
||||
// "edge" agent on a public IP + a "private" agent behind NAT). See
|
||||
// docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
//
|
||||
// Split mirrors the cloudflared package:
|
||||
// - wireguard.go — the platform-agnostic Manager interface,
|
||||
// shared request/result types, key generation
|
||||
// and validation.
|
||||
// - wireguard_linux.go — the real backend (kernel WireGuard via the
|
||||
// `wg` + `ip` tools).
|
||||
// - wireguard_other.go — a stub that reports "unsupported" until the
|
||||
// userspace wireguard-go backend (roadmap #6)
|
||||
// lands for Windows/macOS private peers.
|
||||
//
|
||||
// Security model (stated once):
|
||||
//
|
||||
// Private keys NEVER leave the host. Keygen generates the keypair
|
||||
// locally, persists the private key in a root-only file under the
|
||||
// agent's key directory, and returns ONLY the public key in the
|
||||
// command result. The panel brokers public keys + endpoints +
|
||||
// allowed-IPs; it never sees, transmits or stores a private key.
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"crypto/ecdh"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Keypair is a WireGuard (Curve25519 / X25519) keypair, base64-encoded
|
||||
// in the canonical `wg` format. PrivateKey is host-only and must never
|
||||
// be serialized to the panel — it carries `json:"-"` for that reason.
|
||||
type Keypair struct {
|
||||
PrivateKey string `json:"-"`
|
||||
PublicKey string `json:"public_key"`
|
||||
}
|
||||
|
||||
// KeygenResult is what the wireguard:keygen command returns to the
|
||||
// panel: the public key only.
|
||||
type KeygenResult struct {
|
||||
PublicKey string `json:"public_key"`
|
||||
}
|
||||
|
||||
// InterfaceUpRequest brings up (or reconciles) a WireGuard interface.
|
||||
// ListenPort is set only on the edge agent; the private agent dials
|
||||
// out and lets the kernel pick an ephemeral source port.
|
||||
type InterfaceUpRequest struct {
|
||||
Name string `json:"name"` // e.g. "skwg0"
|
||||
Address string `json:"address"` // CIDR, e.g. "10.88.0.2/24"
|
||||
ListenPort int `json:"listen_port"` // 0 = unset (private side)
|
||||
}
|
||||
|
||||
// PeerSetRequest adds or updates a single peer on an interface. On the
|
||||
// private side, Endpoint points at the edge (`ip:port`) and
|
||||
// PersistentKeepalive is set (typically 25s) to punch and hold the NAT
|
||||
// mapping. On the edge side, Endpoint is empty (learned on handshake).
|
||||
type PeerSetRequest struct {
|
||||
Interface string `json:"interface"`
|
||||
PublicKey string `json:"public_key"`
|
||||
AllowedIPs []string `json:"allowed_ips"`
|
||||
Endpoint string `json:"endpoint,omitempty"`
|
||||
PersistentKeepalive int `json:"persistent_keepalive,omitempty"`
|
||||
}
|
||||
|
||||
// PeerRemoveRequest removes a peer from an interface.
|
||||
type PeerRemoveRequest struct {
|
||||
Interface string `json:"interface"`
|
||||
PublicKey string `json:"public_key"`
|
||||
}
|
||||
|
||||
// PeerStatus mirrors one peer row from `wg show <iface> dump`.
|
||||
type PeerStatus struct {
|
||||
PublicKey string `json:"public_key"`
|
||||
Endpoint string `json:"endpoint,omitempty"`
|
||||
AllowedIPs []string `json:"allowed_ips,omitempty"`
|
||||
LatestHandshake int64 `json:"latest_handshake"` // unix seconds; 0 = never
|
||||
TransferRx int64 `json:"transfer_rx"` // bytes
|
||||
TransferTx int64 `json:"transfer_tx"` // bytes
|
||||
PersistentKeepalive int `json:"persistent_keepalive,omitempty"`
|
||||
}
|
||||
|
||||
// InterfaceStatus is the wireguard:status result for one interface.
|
||||
// Up=false (with a nil/empty Peers) means the interface doesn't exist
|
||||
// yet — the panel polls this on a not-yet-built tunnel without it being
|
||||
// an error.
|
||||
type InterfaceStatus struct {
|
||||
Name string `json:"name"`
|
||||
PublicKey string `json:"public_key,omitempty"`
|
||||
ListenPort int `json:"listen_port,omitempty"`
|
||||
Up bool `json:"up"`
|
||||
Peers []PeerStatus `json:"peers"`
|
||||
}
|
||||
|
||||
// Manager is the platform-agnostic surface the agent's handlers call.
|
||||
// The Linux build wires it to kernel WireGuard; non-Linux builds return
|
||||
// "unsupported" until roadmap #6.
|
||||
type Manager interface {
|
||||
// Available reports whether this host can manage WireGuard (kernel
|
||||
// tools present on Linux; userspace backend on others once #6 lands).
|
||||
Available() bool
|
||||
// Keygen generates a keypair for iface, persists the private key
|
||||
// locally (root-only), and returns the public key.
|
||||
Keygen(iface string) (*KeygenResult, error)
|
||||
// InterfaceUp creates/reconciles the interface using the persisted
|
||||
// private key. Idempotent.
|
||||
InterfaceUp(req InterfaceUpRequest) error
|
||||
// InterfaceDown tears the interface down. Idempotent (a missing
|
||||
// interface is a no-op success).
|
||||
InterfaceDown(iface string) error
|
||||
// SetPeer adds or updates a peer. Idempotent.
|
||||
SetPeer(req PeerSetRequest) error
|
||||
// RemovePeer removes a peer. Idempotent.
|
||||
RemovePeer(req PeerRemoveRequest) error
|
||||
// Status returns the live interface + peer state.
|
||||
Status(iface string) (*InterfaceStatus, error)
|
||||
// Forward starts a TCP forwarder: it accepts connections arriving over
|
||||
// the tunnel at ListenIP:ListenPort and proxies each to
|
||||
// TargetHost:TargetPort on the host. This is how a service behind a
|
||||
// userspace (netstack) peer is reached — and is uniform for the kernel
|
||||
// backend. Idempotent per (interface, ListenPort): re-Forward replaces.
|
||||
Forward(req ForwardRequest) error
|
||||
// Unforward stops the forwarder for ListenPort on iface (idempotent).
|
||||
Unforward(iface string, listenPort int) error
|
||||
}
|
||||
|
||||
// ForwardRequest configures a tunnel→host TCP forwarder (roadmap #13).
|
||||
// On the private peer, ListenIP is the peer's own WireGuard IP, and the
|
||||
// service (e.g. Jellyfin) listens on TargetHost:TargetPort on the host.
|
||||
type ForwardRequest struct {
|
||||
Interface string `json:"interface"`
|
||||
ListenIP string `json:"listen_ip"` // the WG IP to listen on, e.g. 10.88.3.2
|
||||
ListenPort int `json:"listen_port"` // WG-side port the edge proxies to
|
||||
TargetHost string `json:"target_host"` // default 127.0.0.1
|
||||
TargetPort int `json:"target_port"` // default = ListenPort
|
||||
}
|
||||
|
||||
func (r ForwardRequest) normalized() ForwardRequest {
|
||||
if r.TargetHost == "" {
|
||||
r.TargetHost = "127.0.0.1"
|
||||
}
|
||||
if r.TargetPort == 0 {
|
||||
r.TargetPort = r.ListenPort
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func validateForward(req ForwardRequest) error {
|
||||
if err := validIfaceName(req.Interface); err != nil {
|
||||
return err
|
||||
}
|
||||
if net.ParseIP(req.ListenIP) == nil {
|
||||
return fmt.Errorf("invalid listen_ip %q", req.ListenIP)
|
||||
}
|
||||
if req.ListenPort < 1 || req.ListenPort > 65535 {
|
||||
return fmt.Errorf("invalid listen_port %d", req.ListenPort)
|
||||
}
|
||||
if req.TargetPort < 0 || req.TargetPort > 65535 {
|
||||
return fmt.Errorf("invalid target_port %d", req.TargetPort)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// forwardKey identifies a forwarder by interface + listen port.
|
||||
func forwardKey(iface string, port int) string {
|
||||
return iface + ":" + strconv.Itoa(port)
|
||||
}
|
||||
|
||||
// serveForward accepts on l and proxies each connection to
|
||||
// targetHost:targetPort until l is closed. Backends create the listener
|
||||
// (kernel: net.Listen on the real WG iface; userspace: tnet.ListenTCP)
|
||||
// then hand it here.
|
||||
func serveForward(l net.Listener, targetHost string, targetPort int) {
|
||||
target := net.JoinHostPort(targetHost, strconv.Itoa(targetPort))
|
||||
for {
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
return // listener closed
|
||||
}
|
||||
go proxyConn(conn, target)
|
||||
}
|
||||
}
|
||||
|
||||
func proxyConn(client net.Conn, target string) {
|
||||
defer client.Close()
|
||||
server, err := net.Dial("tcp", target)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer server.Close()
|
||||
done := make(chan struct{}, 2)
|
||||
cp := func(dst, src net.Conn) { _, _ = io.Copy(dst, src); done <- struct{}{} }
|
||||
go cp(server, client)
|
||||
go cp(client, server)
|
||||
<-done // first side to close ends the pair (defers close both)
|
||||
}
|
||||
|
||||
// GenerateKeypair produces a fresh WireGuard keypair. X25519 via
|
||||
// crypto/ecdh, which clamps the scalar exactly as WireGuard expects;
|
||||
// the byte layout and base64 encoding match `wg genkey | wg pubkey`.
|
||||
// Shared across all platforms — keygen is pure crypto and works even
|
||||
// where interface management doesn't.
|
||||
func GenerateKeypair() (*Keypair, error) {
|
||||
priv, err := ecdh.X25519().GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate x25519 key: %w", err)
|
||||
}
|
||||
return &Keypair{
|
||||
PrivateKey: base64.StdEncoding.EncodeToString(priv.Bytes()),
|
||||
PublicKey: base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// PublicKeyFromPrivate derives the base64 WireGuard public key from a
|
||||
// base64 private key (X25519 scalar-mult with the base point, matching
|
||||
// `wg pubkey`). The userspace backend uses this for Status, where it
|
||||
// only has the private key on hand.
|
||||
func PublicKeyFromPrivate(privB64 string) (string, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(privB64))
|
||||
if err != nil || len(raw) != 32 {
|
||||
return "", fmt.Errorf("invalid private key")
|
||||
}
|
||||
priv, err := ecdh.X25519().NewPrivateKey(raw)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes()), nil
|
||||
}
|
||||
|
||||
// --- validation helpers (shared, so both backends and tests reuse) ---
|
||||
|
||||
// ifaceNameRegex constrains interface names to what the Linux kernel
|
||||
// accepts (IFNAMSIZ is 16 including the NUL, so 15 usable chars) and
|
||||
// what won't trip shell/`ip` parsing.
|
||||
var ifaceNameRegex = regexp.MustCompile(`^[A-Za-z0-9_-]{1,15}$`)
|
||||
|
||||
func validIfaceName(name string) error {
|
||||
if !ifaceNameRegex.MatchString(name) {
|
||||
return fmt.Errorf("invalid interface name %q (alphanumeric, -, _, max 15 chars)", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validPublicKey checks a base64 WireGuard key decodes to 32 bytes.
|
||||
func validPublicKey(key string) error {
|
||||
raw, err := base64.StdEncoding.DecodeString(key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("public key is not valid base64")
|
||||
}
|
||||
if len(raw) != 32 {
|
||||
return fmt.Errorf("public key must be 32 bytes, got %d", len(raw))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validCIDR checks a "addr/prefix" string parses.
|
||||
func validCIDR(cidr string) error {
|
||||
if _, _, err := net.ParseCIDR(cidr); err != nil {
|
||||
return fmt.Errorf("invalid CIDR %q: %w", cidr, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validEndpoint checks a "host:port" with a numeric, in-range port.
|
||||
func validEndpoint(ep string) error {
|
||||
host, port, err := net.SplitHostPort(ep)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid endpoint %q (want host:port): %w", ep, err)
|
||||
}
|
||||
if host == "" {
|
||||
return fmt.Errorf("invalid endpoint %q: empty host", ep)
|
||||
}
|
||||
p := 0
|
||||
if _, err := fmt.Sscanf(port, "%d", &p); err != nil || p < 1 || p > 65535 {
|
||||
return fmt.Errorf("invalid endpoint port %q", port)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateInterfaceUp validates an InterfaceUpRequest. Shared so the
|
||||
// stub can reject bad input identically to the real backend.
|
||||
func validateInterfaceUp(req InterfaceUpRequest) error {
|
||||
if err := validIfaceName(req.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validCIDR(req.Address); err != nil {
|
||||
return err
|
||||
}
|
||||
if req.ListenPort < 0 || req.ListenPort > 65535 {
|
||||
return fmt.Errorf("invalid listen_port %d", req.ListenPort)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validatePeerSet validates a PeerSetRequest.
|
||||
func validatePeerSet(req PeerSetRequest) error {
|
||||
if err := validIfaceName(req.Interface); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validPublicKey(req.PublicKey); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(req.AllowedIPs) == 0 {
|
||||
return fmt.Errorf("allowed_ips is required")
|
||||
}
|
||||
for _, ip := range req.AllowedIPs {
|
||||
if err := validCIDR(strings.TrimSpace(ip)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if req.Endpoint != "" {
|
||||
if err := validEndpoint(req.Endpoint); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if req.PersistentKeepalive < 0 || req.PersistentKeepalive > 65535 {
|
||||
return fmt.Errorf("invalid persistent_keepalive %d", req.PersistentKeepalive)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//go:build linux
|
||||
|
||||
package wireguard
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestParseWgDump checks the `wg show <iface> dump` parser, and in
|
||||
// particular guards the security-critical invariant: the interface
|
||||
// line's field[0] is the PRIVATE key and must never surface — we read
|
||||
// field[1] (public) for InterfaceStatus.PublicKey.
|
||||
func TestParseWgDump(t *testing.T) {
|
||||
dump := "PRIVATEKEYMUSTNOTLEAK=\tIFACEPUBKEY=\t51820\toff\n" +
|
||||
"PEERPUBKEY=\t(none)\t203.0.113.5:51820\t10.88.0.2/32\t1700000000\t1024\t2048\t25\n" +
|
||||
"PEER2PUBKEY=\t(none)\t(none)\t(none)\t0\t0\t0\toff\n"
|
||||
|
||||
st := &InterfaceStatus{Name: "skwg0", Peers: []PeerStatus{}}
|
||||
parseWgDump(dump, st)
|
||||
|
||||
if st.PublicKey != "IFACEPUBKEY=" {
|
||||
t.Errorf("interface PublicKey = %q, want field[1] IFACEPUBKEY=", st.PublicKey)
|
||||
}
|
||||
if st.PublicKey == "PRIVATEKEYMUSTNOTLEAK=" {
|
||||
t.Fatal("LEAK: interface private key surfaced as PublicKey")
|
||||
}
|
||||
if st.ListenPort != 51820 {
|
||||
t.Errorf("ListenPort = %d, want 51820", st.ListenPort)
|
||||
}
|
||||
if len(st.Peers) != 2 {
|
||||
t.Fatalf("want 2 peers, got %d", len(st.Peers))
|
||||
}
|
||||
|
||||
p := st.Peers[0]
|
||||
if p.PublicKey != "PEERPUBKEY=" {
|
||||
t.Errorf("peer0 PublicKey = %q", p.PublicKey)
|
||||
}
|
||||
if p.Endpoint != "203.0.113.5:51820" {
|
||||
t.Errorf("peer0 Endpoint = %q", p.Endpoint)
|
||||
}
|
||||
if len(p.AllowedIPs) != 1 || p.AllowedIPs[0] != "10.88.0.2/32" {
|
||||
t.Errorf("peer0 AllowedIPs = %v", p.AllowedIPs)
|
||||
}
|
||||
if p.LatestHandshake != 1700000000 {
|
||||
t.Errorf("peer0 LatestHandshake = %d", p.LatestHandshake)
|
||||
}
|
||||
if p.TransferRx != 1024 || p.TransferTx != 2048 {
|
||||
t.Errorf("peer0 transfer rx/tx = %d/%d", p.TransferRx, p.TransferTx)
|
||||
}
|
||||
if p.PersistentKeepalive != 25 {
|
||||
t.Errorf("peer0 PersistentKeepalive = %d", p.PersistentKeepalive)
|
||||
}
|
||||
|
||||
// peer1: "(none)" endpoint → empty, "off" keepalive → 0
|
||||
p2 := st.Peers[1]
|
||||
if p2.Endpoint != "" {
|
||||
t.Errorf("peer1 Endpoint = %q, want empty", p2.Endpoint)
|
||||
}
|
||||
if len(p2.AllowedIPs) != 0 {
|
||||
t.Errorf("peer1 AllowedIPs = %v, want empty", p2.AllowedIPs)
|
||||
}
|
||||
if p2.PersistentKeepalive != 0 {
|
||||
t.Errorf("peer1 PersistentKeepalive = %d, want 0", p2.PersistentKeepalive)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
//go:build linux
|
||||
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// defaultKeyDir is used when the agent didn't supply a data directory.
|
||||
const defaultKeyDir = "/etc/serverkit-agent/wireguard"
|
||||
|
||||
// New returns a Linux Manager backed by kernel WireGuard (`wg` + `ip`).
|
||||
// keyDir is where per-interface private keys are persisted (root-only);
|
||||
// empty falls back to defaultKeyDir.
|
||||
func New(keyDir string) Manager {
|
||||
if keyDir == "" {
|
||||
keyDir = defaultKeyDir
|
||||
}
|
||||
return &linuxManager{keyDir: keyDir, forwards: map[string]net.Listener{}}
|
||||
}
|
||||
|
||||
type linuxManager struct {
|
||||
keyDir string
|
||||
mu sync.Mutex
|
||||
forwards map[string]net.Listener
|
||||
}
|
||||
|
||||
func (m *linuxManager) keyPath(iface string) string {
|
||||
return filepath.Join(m.keyDir, iface+".key")
|
||||
}
|
||||
|
||||
func (m *linuxManager) Available() bool {
|
||||
return onPath("wg") && onPath("ip")
|
||||
}
|
||||
|
||||
func onPath(bin string) bool {
|
||||
_, err := exec.LookPath(bin)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// run executes a command with a short ceiling and returns stdout, with
|
||||
// stderr folded into any error (the panel surfaces these directly).
|
||||
func run(name string, args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return "", fmt.Errorf("%s %s: %w (%s)",
|
||||
name, strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
|
||||
}
|
||||
return stdout.String(), nil
|
||||
}
|
||||
|
||||
func (m *linuxManager) Keygen(iface string) (*KeygenResult, error) {
|
||||
if err := validIfaceName(iface); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kp, err := GenerateKeypair()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(m.keyDir, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("create key dir: %w", err)
|
||||
}
|
||||
// 0600 + the key dir at 0700: the private key is readable only by
|
||||
// the agent's (root) user. It never travels to the panel.
|
||||
if err := os.WriteFile(m.keyPath(iface), []byte(kp.PrivateKey+"\n"), 0o600); err != nil {
|
||||
return nil, fmt.Errorf("persist private key: %w", err)
|
||||
}
|
||||
return &KeygenResult{PublicKey: kp.PublicKey}, nil
|
||||
}
|
||||
|
||||
func (m *linuxManager) linkExists(iface string) bool {
|
||||
_, err := run("ip", "link", "show", iface)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (m *linuxManager) InterfaceUp(req InterfaceUpRequest) error {
|
||||
if err := validateInterfaceUp(req); err != nil {
|
||||
return err
|
||||
}
|
||||
keyPath := m.keyPath(req.Name)
|
||||
if _, err := os.Stat(keyPath); err != nil {
|
||||
return fmt.Errorf("no private key for %q — run wireguard:keygen first", req.Name)
|
||||
}
|
||||
|
||||
// 1. Create the interface if it doesn't already exist (idempotent).
|
||||
if !m.linkExists(req.Name) {
|
||||
if _, err := run("ip", "link", "add", "dev", req.Name, "type", "wireguard"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Apply the private key (+ listen port on the edge side).
|
||||
wgArgs := []string{"set", req.Name}
|
||||
if req.ListenPort > 0 {
|
||||
wgArgs = append(wgArgs, "listen-port", strconv.Itoa(req.ListenPort))
|
||||
}
|
||||
wgArgs = append(wgArgs, "private-key", keyPath)
|
||||
if _, err := run("wg", wgArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. Address — `replace` adds or updates, so re-running up is safe.
|
||||
if _, err := run("ip", "address", "replace", req.Address, "dev", req.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 4. Bring it up.
|
||||
if _, err := run("ip", "link", "set", req.Name, "up"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *linuxManager) InterfaceDown(iface string) error {
|
||||
if err := validIfaceName(iface); err != nil {
|
||||
return err
|
||||
}
|
||||
m.closeForwards(iface)
|
||||
if !m.linkExists(iface) {
|
||||
return nil // already gone — idempotent
|
||||
}
|
||||
_, err := run("ip", "link", "del", "dev", iface)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *linuxManager) Forward(req ForwardRequest) error {
|
||||
if err := validateForward(req); err != nil {
|
||||
return err
|
||||
}
|
||||
req = req.normalized()
|
||||
// The WG IP is a real address on the kernel interface, so a normal
|
||||
// listen on it receives traffic arriving over the tunnel.
|
||||
l, err := net.Listen("tcp", net.JoinHostPort(req.ListenIP, strconv.Itoa(req.ListenPort)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen %s:%d: %w", req.ListenIP, req.ListenPort, err)
|
||||
}
|
||||
key := forwardKey(req.Interface, req.ListenPort)
|
||||
m.mu.Lock()
|
||||
if old, ok := m.forwards[key]; ok {
|
||||
old.Close()
|
||||
}
|
||||
m.forwards[key] = l
|
||||
m.mu.Unlock()
|
||||
go serveForward(l, req.TargetHost, req.TargetPort)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *linuxManager) Unforward(iface string, listenPort int) error {
|
||||
if err := validIfaceName(iface); err != nil {
|
||||
return err
|
||||
}
|
||||
key := forwardKey(iface, listenPort)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if l, ok := m.forwards[key]; ok {
|
||||
l.Close()
|
||||
delete(m.forwards, key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// closeForwards stops every forwarder bound to iface (called on teardown).
|
||||
func (m *linuxManager) closeForwards(iface string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for k, l := range m.forwards {
|
||||
if strings.HasPrefix(k, iface+":") {
|
||||
l.Close()
|
||||
delete(m.forwards, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *linuxManager) SetPeer(req PeerSetRequest) error {
|
||||
if err := validatePeerSet(req); err != nil {
|
||||
return err
|
||||
}
|
||||
args := []string{"set", req.Interface, "peer", req.PublicKey,
|
||||
"allowed-ips", strings.Join(req.AllowedIPs, ",")}
|
||||
if req.Endpoint != "" {
|
||||
args = append(args, "endpoint", req.Endpoint)
|
||||
}
|
||||
if req.PersistentKeepalive > 0 {
|
||||
args = append(args, "persistent-keepalive", strconv.Itoa(req.PersistentKeepalive))
|
||||
}
|
||||
_, err := run("wg", args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *linuxManager) RemovePeer(req PeerRemoveRequest) error {
|
||||
if err := validIfaceName(req.Interface); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validPublicKey(req.PublicKey); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := run("wg", "set", req.Interface, "peer", req.PublicKey, "remove")
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *linuxManager) Status(iface string) (*InterfaceStatus, error) {
|
||||
if err := validIfaceName(iface); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st := &InterfaceStatus{Name: iface, Peers: []PeerStatus{}}
|
||||
|
||||
out, err := run("wg", "show", iface, "dump")
|
||||
if err != nil {
|
||||
// The interface most likely doesn't exist yet — report "down"
|
||||
// rather than erroring so the panel can poll a tunnel that's
|
||||
// still being built.
|
||||
return st, nil
|
||||
}
|
||||
st.Up = true
|
||||
parseWgDump(out, st)
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// parseWgDump parses `wg show <iface> dump`. Line 1 is the interface
|
||||
// (private-key, public-key, listen-port, fwmark); subsequent lines are
|
||||
// peers (public-key, preshared-key, endpoint, allowed-ips,
|
||||
// latest-handshake, transfer-rx, transfer-tx, persistent-keepalive).
|
||||
//
|
||||
// IMPORTANT: field [0] of the interface line is the PRIVATE key. We
|
||||
// read field [1] (public) and deliberately never surface field [0].
|
||||
func parseWgDump(out string, st *InterfaceStatus) {
|
||||
lines := strings.Split(strings.TrimSpace(out), "\n")
|
||||
for i, line := range lines {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
f := strings.Split(line, "\t")
|
||||
if i == 0 {
|
||||
// interface line
|
||||
if len(f) >= 2 {
|
||||
st.PublicKey = f[1]
|
||||
}
|
||||
if len(f) >= 3 {
|
||||
st.ListenPort = atoiSafe(f[2])
|
||||
}
|
||||
continue
|
||||
}
|
||||
// peer line
|
||||
if len(f) < 8 {
|
||||
continue
|
||||
}
|
||||
p := PeerStatus{PublicKey: f[0]}
|
||||
if f[2] != "(none)" {
|
||||
p.Endpoint = f[2]
|
||||
}
|
||||
if f[3] != "(none)" && f[3] != "" {
|
||||
for _, a := range strings.Split(f[3], ",") {
|
||||
if a = strings.TrimSpace(a); a != "" {
|
||||
p.AllowedIPs = append(p.AllowedIPs, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
p.LatestHandshake = atoi64Safe(f[4])
|
||||
p.TransferRx = atoi64Safe(f[5])
|
||||
p.TransferTx = atoi64Safe(f[6])
|
||||
if f[7] != "off" {
|
||||
p.PersistentKeepalive = atoiSafe(f[7])
|
||||
}
|
||||
st.Peers = append(st.Peers, p)
|
||||
}
|
||||
}
|
||||
|
||||
func atoiSafe(s string) int {
|
||||
n, _ := strconv.Atoi(strings.TrimSpace(s))
|
||||
return n
|
||||
}
|
||||
|
||||
func atoi64Safe(s string) int64 {
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//go:build !linux
|
||||
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"golang.zx2c4.com/wireguard/conn"
|
||||
"golang.zx2c4.com/wireguard/device"
|
||||
"golang.zx2c4.com/wireguard/tun/netstack"
|
||||
)
|
||||
|
||||
// Userspace WireGuard backend (roadmap #6) — wireguard-go + gVisor
|
||||
// netstack. Pure userspace: NO kernel module, NO TUN driver (no Wintun),
|
||||
// NO admin. That's what makes it viable on a home Windows/macOS box
|
||||
// (e.g. the user's Jellyfin host).
|
||||
//
|
||||
// Difference vs the Linux kernel backend: netstack is an in-process
|
||||
// TCP/IP stack, not a transparent L3 interface. keygen / interface:up /
|
||||
// peer:set / status are fully functional (the WireGuard handshake works),
|
||||
// which is what Phases 0–1 need. Forwarding a host service over the
|
||||
// tunnel happens in Phase 2 through the retained *netstack.Net (tnet);
|
||||
// the iface struct keeps it for exactly that.
|
||||
|
||||
// New returns a userspace Manager. keyDir holds per-interface private
|
||||
// keys (0600); empty falls back to the user-config dir.
|
||||
func New(keyDir string) Manager {
|
||||
if keyDir == "" {
|
||||
keyDir = userspaceDefaultKeyDir()
|
||||
}
|
||||
return &userspaceManager{
|
||||
keyDir: keyDir,
|
||||
ifaces: map[string]*usIface{},
|
||||
forwards: map[string]net.Listener{},
|
||||
}
|
||||
}
|
||||
|
||||
func userspaceDefaultKeyDir() string {
|
||||
if dir, err := os.UserConfigDir(); err == nil {
|
||||
return filepath.Join(dir, "serverkit-agent", "wireguard")
|
||||
}
|
||||
return filepath.Join(os.TempDir(), "serverkit-agent-wireguard")
|
||||
}
|
||||
|
||||
type userspaceManager struct {
|
||||
keyDir string
|
||||
mu sync.Mutex
|
||||
ifaces map[string]*usIface
|
||||
forwards map[string]net.Listener
|
||||
}
|
||||
|
||||
type usIface struct {
|
||||
dev *device.Device
|
||||
tnet *netstack.Net // retained for Phase 2 service forwarding
|
||||
pubKey string // base64; derived at up, surfaced by Status
|
||||
listen int
|
||||
}
|
||||
|
||||
func (m *userspaceManager) keyPath(iface string) string {
|
||||
return filepath.Join(m.keyDir, iface+".key")
|
||||
}
|
||||
|
||||
func (m *userspaceManager) Available() bool { return true }
|
||||
|
||||
func (m *userspaceManager) Keygen(iface string) (*KeygenResult, error) {
|
||||
if err := validIfaceName(iface); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kp, err := GenerateKeypair()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(m.keyDir, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("create key dir: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(m.keyPath(iface), []byte(kp.PrivateKey+"\n"), 0o600); err != nil {
|
||||
return nil, fmt.Errorf("persist private key: %w", err)
|
||||
}
|
||||
return &KeygenResult{PublicKey: kp.PublicKey}, nil
|
||||
}
|
||||
|
||||
func (m *userspaceManager) InterfaceUp(req InterfaceUpRequest) error {
|
||||
if err := validateInterfaceUp(req); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := os.ReadFile(m.keyPath(req.Name))
|
||||
if err != nil {
|
||||
return fmt.Errorf("no private key for %q — run wireguard:keygen first", req.Name)
|
||||
}
|
||||
privB64 := strings.TrimSpace(string(raw))
|
||||
privHex, err := keyB64ToHex(privB64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bad stored private key: %w", err)
|
||||
}
|
||||
pub, err := PublicKeyFromPrivate(privB64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("derive public key: %w", err)
|
||||
}
|
||||
prefix, err := netip.ParsePrefix(req.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bad address %q: %w", req.Address, err)
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.ifaces[req.Name]; ok {
|
||||
return nil // idempotent: already up
|
||||
}
|
||||
|
||||
tunDev, tnet, err := netstack.CreateNetTUN([]netip.Addr{prefix.Addr()}, nil, device.DefaultMTU)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create userspace tun: %w", err)
|
||||
}
|
||||
dev := device.NewDevice(tunDev, conn.NewDefaultBind(),
|
||||
device.NewLogger(device.LogLevelError, "wg/"+req.Name+" "))
|
||||
|
||||
var cfg strings.Builder
|
||||
cfg.WriteString("private_key=" + privHex + "\n")
|
||||
if req.ListenPort > 0 {
|
||||
cfg.WriteString("listen_port=" + strconv.Itoa(req.ListenPort) + "\n")
|
||||
}
|
||||
if err := dev.IpcSet(cfg.String()); err != nil {
|
||||
dev.Close()
|
||||
return fmt.Errorf("configure device: %w", err)
|
||||
}
|
||||
if err := dev.Up(); err != nil {
|
||||
dev.Close()
|
||||
return fmt.Errorf("bring up device: %w", err)
|
||||
}
|
||||
m.ifaces[req.Name] = &usIface{dev: dev, tnet: tnet, pubKey: pub, listen: req.ListenPort}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *userspaceManager) InterfaceDown(iface string) error {
|
||||
if err := validIfaceName(iface); err != nil {
|
||||
return err
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for k, l := range m.forwards {
|
||||
if strings.HasPrefix(k, iface+":") {
|
||||
l.Close()
|
||||
delete(m.forwards, k)
|
||||
}
|
||||
}
|
||||
if ifc, ok := m.ifaces[iface]; ok {
|
||||
ifc.dev.Close()
|
||||
delete(m.ifaces, iface)
|
||||
}
|
||||
return nil // idempotent
|
||||
}
|
||||
|
||||
func (m *userspaceManager) Forward(req ForwardRequest) error {
|
||||
if err := validateForward(req); err != nil {
|
||||
return err
|
||||
}
|
||||
req = req.normalized()
|
||||
m.mu.Lock()
|
||||
ifc := m.ifaces[req.Interface]
|
||||
m.mu.Unlock()
|
||||
if ifc == nil {
|
||||
return fmt.Errorf("interface %q is not up", req.Interface)
|
||||
}
|
||||
ip, err := netip.ParseAddr(req.ListenIP)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid listen_ip %q: %w", req.ListenIP, err)
|
||||
}
|
||||
// Listen INSIDE the netstack on the WG IP — this receives the
|
||||
// connections the edge proxies over the tunnel. serveForward then
|
||||
// dials the real host service over the OS network.
|
||||
l, err := ifc.tnet.ListenTCPAddrPort(netip.AddrPortFrom(ip, uint16(req.ListenPort)))
|
||||
if err != nil {
|
||||
return fmt.Errorf("netstack listen %s:%d: %w", req.ListenIP, req.ListenPort, err)
|
||||
}
|
||||
key := forwardKey(req.Interface, req.ListenPort)
|
||||
m.mu.Lock()
|
||||
if old, ok := m.forwards[key]; ok {
|
||||
old.Close()
|
||||
}
|
||||
m.forwards[key] = l
|
||||
m.mu.Unlock()
|
||||
go serveForward(l, req.TargetHost, req.TargetPort)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *userspaceManager) Unforward(iface string, listenPort int) error {
|
||||
if err := validIfaceName(iface); err != nil {
|
||||
return err
|
||||
}
|
||||
key := forwardKey(iface, listenPort)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if l, ok := m.forwards[key]; ok {
|
||||
l.Close()
|
||||
delete(m.forwards, key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *userspaceManager) SetPeer(req PeerSetRequest) error {
|
||||
if err := validatePeerSet(req); err != nil {
|
||||
return err
|
||||
}
|
||||
m.mu.Lock()
|
||||
ifc := m.ifaces[req.Interface]
|
||||
m.mu.Unlock()
|
||||
if ifc == nil {
|
||||
return fmt.Errorf("interface %q is not up", req.Interface)
|
||||
}
|
||||
pubHex, err := keyB64ToHex(req.PublicKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bad peer public key: %w", err)
|
||||
}
|
||||
var cfg strings.Builder
|
||||
cfg.WriteString("public_key=" + pubHex + "\n")
|
||||
cfg.WriteString("replace_allowed_ips=true\n")
|
||||
for _, ip := range req.AllowedIPs {
|
||||
cfg.WriteString("allowed_ip=" + strings.TrimSpace(ip) + "\n")
|
||||
}
|
||||
if req.Endpoint != "" {
|
||||
cfg.WriteString("endpoint=" + req.Endpoint + "\n")
|
||||
}
|
||||
if req.PersistentKeepalive > 0 {
|
||||
cfg.WriteString("persistent_keepalive_interval=" + strconv.Itoa(req.PersistentKeepalive) + "\n")
|
||||
}
|
||||
return ifc.dev.IpcSet(cfg.String())
|
||||
}
|
||||
|
||||
func (m *userspaceManager) RemovePeer(req PeerRemoveRequest) error {
|
||||
if err := validIfaceName(req.Interface); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validPublicKey(req.PublicKey); err != nil {
|
||||
return err
|
||||
}
|
||||
m.mu.Lock()
|
||||
ifc := m.ifaces[req.Interface]
|
||||
m.mu.Unlock()
|
||||
if ifc == nil {
|
||||
return nil // nothing to remove
|
||||
}
|
||||
pubHex, err := keyB64ToHex(req.PublicKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bad peer public key: %w", err)
|
||||
}
|
||||
return ifc.dev.IpcSet("public_key=" + pubHex + "\nremove=true\n")
|
||||
}
|
||||
|
||||
func (m *userspaceManager) Status(iface string) (*InterfaceStatus, error) {
|
||||
if err := validIfaceName(iface); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st := &InterfaceStatus{Name: iface, Peers: []PeerStatus{}}
|
||||
m.mu.Lock()
|
||||
ifc := m.ifaces[iface]
|
||||
m.mu.Unlock()
|
||||
if ifc == nil {
|
||||
return st, nil // down
|
||||
}
|
||||
st.Up = true
|
||||
st.PublicKey = ifc.pubKey
|
||||
st.ListenPort = ifc.listen
|
||||
cfg, err := ifc.dev.IpcGet()
|
||||
if err != nil {
|
||||
return st, nil
|
||||
}
|
||||
parseUAPIStatus(cfg, st)
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// parseUAPIStatus parses wireguard-go's IpcGet() output into peers.
|
||||
// It deliberately ignores the interface's private_key line (never
|
||||
// surfaced). Peer public keys are converted hex→base64 to match the
|
||||
// panel and the kernel backend's `wg show dump` output.
|
||||
func parseUAPIStatus(cfg string, st *InterfaceStatus) {
|
||||
var cur *PeerStatus
|
||||
flush := func() {
|
||||
if cur != nil {
|
||||
st.Peers = append(st.Peers, *cur)
|
||||
cur = nil
|
||||
}
|
||||
}
|
||||
for _, line := range strings.Split(cfg, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
k, v, ok := strings.Cut(line, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch k {
|
||||
case "public_key": // begins a new peer section
|
||||
flush()
|
||||
cur = &PeerStatus{PublicKey: keyHexToB64(v)}
|
||||
case "endpoint":
|
||||
if cur != nil {
|
||||
cur.Endpoint = v
|
||||
}
|
||||
case "allowed_ip":
|
||||
if cur != nil {
|
||||
cur.AllowedIPs = append(cur.AllowedIPs, v)
|
||||
}
|
||||
case "last_handshake_time_sec":
|
||||
if cur != nil {
|
||||
cur.LatestHandshake = atoi64u(v)
|
||||
}
|
||||
case "rx_bytes":
|
||||
if cur != nil {
|
||||
cur.TransferRx = atoi64u(v)
|
||||
}
|
||||
case "tx_bytes":
|
||||
if cur != nil {
|
||||
cur.TransferTx = atoi64u(v)
|
||||
}
|
||||
case "persistent_keepalive_interval":
|
||||
if cur != nil {
|
||||
cur.PersistentKeepalive = int(atoi64u(v))
|
||||
}
|
||||
}
|
||||
// private_key / preshared_key / errno / protocol_version /
|
||||
// last_handshake_time_nsec / listen_port / fwmark → ignored.
|
||||
}
|
||||
flush()
|
||||
}
|
||||
|
||||
func keyB64ToHex(b64 string) (string, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(b64))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(raw) != 32 {
|
||||
return "", fmt.Errorf("key must be 32 bytes, got %d", len(raw))
|
||||
}
|
||||
return hex.EncodeToString(raw), nil
|
||||
}
|
||||
|
||||
func keyHexToB64(h string) string {
|
||||
raw, err := hex.DecodeString(strings.TrimSpace(h))
|
||||
if err != nil {
|
||||
return h // fall back to the raw value on parse failure
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func atoi64u(s string) int64 {
|
||||
n, _ := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGenerateKeypair(t *testing.T) {
|
||||
kp, err := GenerateKeypair()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateKeypair: %v", err)
|
||||
}
|
||||
if err := validPublicKey(kp.PublicKey); err != nil {
|
||||
t.Errorf("generated public key invalid: %v", err)
|
||||
}
|
||||
priv, err := base64.StdEncoding.DecodeString(kp.PrivateKey)
|
||||
if err != nil || len(priv) != 32 {
|
||||
t.Errorf("private key not 32 base64 bytes: err=%v len=%d", err, len(priv))
|
||||
}
|
||||
if kp.PrivateKey == kp.PublicKey {
|
||||
t.Error("private and public key are identical")
|
||||
}
|
||||
kp2, _ := GenerateKeypair()
|
||||
if kp.PrivateKey == kp2.PrivateKey {
|
||||
t.Error("two keygens produced identical private keys")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidPublicKey(t *testing.T) {
|
||||
kp, _ := GenerateKeypair()
|
||||
if err := validPublicKey(kp.PublicKey); err != nil {
|
||||
t.Errorf("valid key rejected: %v", err)
|
||||
}
|
||||
if validPublicKey("not base64!!!") == nil {
|
||||
t.Error("non-base64 key accepted")
|
||||
}
|
||||
if validPublicKey(base64.StdEncoding.EncodeToString([]byte("short"))) == nil {
|
||||
t.Error("wrong-length key accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateInterfaceUp(t *testing.T) {
|
||||
ok := InterfaceUpRequest{Name: "skwg0", Address: "10.88.0.1/24", ListenPort: 51820}
|
||||
if err := validateInterfaceUp(ok); err != nil {
|
||||
t.Errorf("valid request rejected: %v", err)
|
||||
}
|
||||
bad := []InterfaceUpRequest{
|
||||
{Name: "bad iface!", Address: "10.88.0.1/24"},
|
||||
{Name: "skwg0", Address: "not-a-cidr"},
|
||||
{Name: "skwg0", Address: "10.88.0.1/24", ListenPort: 70000},
|
||||
{Name: "this-name-is-far-too-long", Address: "10.88.0.1/24"},
|
||||
}
|
||||
for i, b := range bad {
|
||||
if validateInterfaceUp(b) == nil {
|
||||
t.Errorf("invalid request %d was accepted", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePeerSet(t *testing.T) {
|
||||
kp, _ := GenerateKeypair()
|
||||
ok := PeerSetRequest{
|
||||
Interface: "skwg0", PublicKey: kp.PublicKey,
|
||||
AllowedIPs: []string{"10.88.0.2/32"},
|
||||
Endpoint: "203.0.113.5:51820", PersistentKeepalive: 25,
|
||||
}
|
||||
if err := validatePeerSet(ok); err != nil {
|
||||
t.Errorf("valid peer rejected: %v", err)
|
||||
}
|
||||
bad := []PeerSetRequest{
|
||||
{Interface: "skwg0", PublicKey: "bad", AllowedIPs: []string{"10.88.0.2/32"}},
|
||||
{Interface: "skwg0", PublicKey: kp.PublicKey, AllowedIPs: nil},
|
||||
{Interface: "skwg0", PublicKey: kp.PublicKey, AllowedIPs: []string{"nope"}},
|
||||
{Interface: "skwg0", PublicKey: kp.PublicKey, AllowedIPs: []string{"10.88.0.2/32"}, Endpoint: "no-port"},
|
||||
}
|
||||
for i, b := range bad {
|
||||
if validatePeerSet(b) == nil {
|
||||
t.Errorf("invalid peer %d was accepted", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicKeyFromPrivate(t *testing.T) {
|
||||
kp, _ := GenerateKeypair()
|
||||
pub, err := PublicKeyFromPrivate(kp.PrivateKey)
|
||||
if err != nil {
|
||||
t.Fatalf("PublicKeyFromPrivate: %v", err)
|
||||
}
|
||||
if pub != kp.PublicKey {
|
||||
t.Errorf("derived public key %s != keypair public key %s", pub, kp.PublicKey)
|
||||
}
|
||||
if _, err := PublicKeyFromPrivate("not-a-key"); err == nil {
|
||||
t.Error("accepted an invalid private key")
|
||||
}
|
||||
}
|
||||
|
||||
// TestForwarder proves serveForward's accept loop + bidirectional proxy
|
||||
// with real sockets (the listener-creation differs per backend, but the
|
||||
// proxy plumbing is shared and is what carries the user's traffic).
|
||||
func TestForwarder(t *testing.T) {
|
||||
// Echo server standing in for the real local service (e.g. Jellyfin).
|
||||
target, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("target listen: %v", err)
|
||||
}
|
||||
defer target.Close()
|
||||
go func() {
|
||||
for {
|
||||
c, err := target.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func(c net.Conn) { _, _ = io.Copy(c, c); c.Close() }(c)
|
||||
}
|
||||
}()
|
||||
_, tportStr, _ := net.SplitHostPort(target.Addr().String())
|
||||
tport, _ := strconv.Atoi(tportStr)
|
||||
|
||||
// Forwarder listener standing in for the WG-side listen.
|
||||
fwd, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("forwarder listen: %v", err)
|
||||
}
|
||||
defer fwd.Close()
|
||||
go serveForward(fwd, "127.0.0.1", tport)
|
||||
|
||||
conn, err := net.Dial("tcp", fwd.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("dial forwarder: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
|
||||
msg := []byte("hello-tunnel")
|
||||
if _, err := conn.Write(msg); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
buf := make([]byte, len(msg))
|
||||
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||
t.Fatalf("read: %v", err)
|
||||
}
|
||||
if string(buf) != string(msg) {
|
||||
t.Errorf("echo mismatch: got %q want %q", buf, msg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//go:build !linux
|
||||
|
||||
package wireguard
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestKeyHexRoundTrip(t *testing.T) {
|
||||
kp, _ := GenerateKeypair()
|
||||
h, err := keyB64ToHex(kp.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatalf("keyB64ToHex: %v", err)
|
||||
}
|
||||
if len(h) != 64 {
|
||||
t.Errorf("hex key length = %d, want 64", len(h))
|
||||
}
|
||||
if back := keyHexToB64(h); back != kp.PublicKey {
|
||||
t.Errorf("roundtrip mismatch: %s != %s", back, kp.PublicKey)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseUAPIStatus checks the wireguard-go IpcGet() parser and guards
|
||||
// the no-leak invariant: the interface's private_key line must never end
|
||||
// up in any surfaced field.
|
||||
func TestParseUAPIStatus(t *testing.T) {
|
||||
ifaceKp, _ := GenerateKeypair()
|
||||
peerKp, _ := GenerateKeypair()
|
||||
privHex, _ := keyB64ToHex(ifaceKp.PrivateKey)
|
||||
peerHex, _ := keyB64ToHex(peerKp.PublicKey)
|
||||
|
||||
cfg := "private_key=" + privHex + "\n" +
|
||||
"listen_port=51820\n" +
|
||||
"public_key=" + peerHex + "\n" +
|
||||
"endpoint=203.0.113.5:51820\n" +
|
||||
"allowed_ip=10.88.0.1/32\n" +
|
||||
"last_handshake_time_sec=1700000000\n" +
|
||||
"rx_bytes=1024\n" +
|
||||
"tx_bytes=2048\n" +
|
||||
"persistent_keepalive_interval=25\n" +
|
||||
"protocol_version=1\n"
|
||||
|
||||
st := &InterfaceStatus{Name: "skwg0", Peers: []PeerStatus{}}
|
||||
parseUAPIStatus(cfg, st)
|
||||
|
||||
if len(st.Peers) != 1 {
|
||||
t.Fatalf("want 1 peer, got %d", len(st.Peers))
|
||||
}
|
||||
p := st.Peers[0]
|
||||
if p.PublicKey != peerKp.PublicKey {
|
||||
t.Errorf("peer PublicKey = %s, want %s (hex→base64)", p.PublicKey, peerKp.PublicKey)
|
||||
}
|
||||
if p.Endpoint != "203.0.113.5:51820" {
|
||||
t.Errorf("Endpoint = %q", p.Endpoint)
|
||||
}
|
||||
if len(p.AllowedIPs) != 1 || p.AllowedIPs[0] != "10.88.0.1/32" {
|
||||
t.Errorf("AllowedIPs = %v", p.AllowedIPs)
|
||||
}
|
||||
if p.LatestHandshake != 1700000000 {
|
||||
t.Errorf("LatestHandshake = %d", p.LatestHandshake)
|
||||
}
|
||||
if p.TransferRx != 1024 || p.TransferTx != 2048 {
|
||||
t.Errorf("transfer rx/tx = %d/%d", p.TransferRx, p.TransferTx)
|
||||
}
|
||||
if p.PersistentKeepalive != 25 {
|
||||
t.Errorf("PersistentKeepalive = %d", p.PersistentKeepalive)
|
||||
}
|
||||
// No-leak: the private key (as base64) must not appear in any field.
|
||||
if p.PublicKey == ifaceKp.PrivateKey {
|
||||
t.Fatal("LEAK: interface private key surfaced as a peer public key")
|
||||
}
|
||||
}
|
||||
@@ -78,18 +78,31 @@ Requires=docker.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
User=serverkit-agent
|
||||
Group=serverkit-agent
|
||||
ExecStart=/usr/local/bin/serverkit-agent start
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=serverkit-agent
|
||||
|
||||
# Security hardening
|
||||
NoNewPrivileges=false
|
||||
# Security hardening — run as a dedicated unprivileged account, matching the
|
||||
# script installer (agent/scripts/install.sh). In this mode the agent cannot
|
||||
# overwrite its own root-owned binary, so self-update is disabled and updates
|
||||
# flow through the OS package manager (apt) instead — the signature-checked
|
||||
# path. systemd/package-management handlers need root; if you require them,
|
||||
# deliberately run as root or configure passwordless sudo for this account.
|
||||
NoNewPrivileges=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=read-only
|
||||
ReadWritePaths=/etc/serverkit-agent /var/log/serverkit-agent
|
||||
ProtectHome=yes
|
||||
PrivateTmp=yes
|
||||
ReadWritePaths=/etc/serverkit-agent /var/log/serverkit-agent /var/lib/serverkit /var/serverkit
|
||||
# `register` is usually run via sudo (as root), so the credential files it
|
||||
# writes can end up root-owned and unreadable by this service account. Fix
|
||||
# ownership at start regardless of how the operator registered. The leading
|
||||
# '+' runs this step as root even though the service drops to User= above.
|
||||
ExecStartPre=+/usr/bin/chown -R serverkit-agent:serverkit-agent /etc/serverkit-agent
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -142,6 +155,24 @@ set -e
|
||||
|
||||
case "$1" in
|
||||
configure)
|
||||
# Create the dedicated, unprivileged service account (idempotent).
|
||||
if ! getent passwd serverkit-agent >/dev/null; then
|
||||
useradd --system --no-create-home --shell /usr/sbin/nologin serverkit-agent
|
||||
fi
|
||||
|
||||
# Let the agent reach the Docker socket without root.
|
||||
if getent group docker >/dev/null; then
|
||||
usermod -aG docker serverkit-agent || true
|
||||
fi
|
||||
|
||||
# State/data directories the agent writes to, owned by the service
|
||||
# account. Also re-chown the config dir so an existing root-owned
|
||||
# agent.key (e.g. from a previous root install, or `sudo register`)
|
||||
# becomes readable by the unprivileged service after upgrade.
|
||||
mkdir -p /var/lib/serverkit/apps /var/serverkit/apps /var/log/serverkit-agent
|
||||
chown -R serverkit-agent:serverkit-agent \
|
||||
/var/lib/serverkit /var/serverkit /var/log/serverkit-agent /etc/serverkit-agent 2>/dev/null || true
|
||||
|
||||
# Reload systemd
|
||||
systemctl daemon-reload
|
||||
|
||||
@@ -152,8 +183,8 @@ case "$1" in
|
||||
echo "ServerKit Agent installed successfully!"
|
||||
echo ""
|
||||
echo "To complete setup:"
|
||||
echo " 1. Register the agent:"
|
||||
echo " sudo serverkit-agent register --token YOUR_TOKEN --server https://your-serverkit.com"
|
||||
echo " 1. Register the agent (runs as the service account):"
|
||||
echo " sudo -u serverkit-agent serverkit-agent register --token YOUR_TOKEN --server https://your-serverkit.com"
|
||||
echo ""
|
||||
echo " 2. Start the service:"
|
||||
echo " sudo systemctl start serverkit-agent"
|
||||
|
||||
@@ -51,18 +51,31 @@ Requires=docker.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
User=serverkit-agent
|
||||
Group=serverkit-agent
|
||||
ExecStart=/usr/local/bin/serverkit-agent start
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=serverkit-agent
|
||||
|
||||
# Security hardening
|
||||
NoNewPrivileges=false
|
||||
# Security hardening — run as a dedicated unprivileged account, matching the
|
||||
# script installer (agent/scripts/install.sh). In this mode the agent cannot
|
||||
# overwrite its own root-owned binary, so self-update is disabled and updates
|
||||
# flow through the OS package manager (dnf/yum) instead — the signature-checked
|
||||
# path. systemd/package-management handlers need root; if you require them,
|
||||
# deliberately run as root or configure passwordless sudo for this account.
|
||||
NoNewPrivileges=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=read-only
|
||||
ReadWritePaths=/etc/serverkit-agent /var/log/serverkit-agent
|
||||
ProtectHome=yes
|
||||
PrivateTmp=yes
|
||||
ReadWritePaths=/etc/serverkit-agent /var/log/serverkit-agent /var/lib/serverkit /var/serverkit
|
||||
# \`register\` is usually run via sudo (as root), so the credential files it
|
||||
# writes can end up root-owned and unreadable by this service account. Fix
|
||||
# ownership at start regardless of how the operator registered. The leading
|
||||
# '+' runs this step as root even though the service drops to User= above.
|
||||
ExecStartPre=+/usr/bin/chown -R serverkit-agent:serverkit-agent /etc/serverkit-agent
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -157,19 +170,38 @@ install -d -m 755 %{buildroot}/var/log/serverkit-agent
|
||||
%files
|
||||
%attr(755, root, root) /usr/local/bin/serverkit-agent
|
||||
%attr(644, root, root) /usr/lib/systemd/system/serverkit-agent.service
|
||||
%config(noreplace) %attr(644, root, root) /etc/serverkit-agent/config.yaml
|
||||
%dir %attr(755, root, root) /etc/serverkit-agent
|
||||
%dir %attr(755, root, root) /var/log/serverkit-agent
|
||||
%config(noreplace) %attr(640, serverkit-agent, serverkit-agent) /etc/serverkit-agent/config.yaml
|
||||
%dir %attr(750, serverkit-agent, serverkit-agent) /etc/serverkit-agent
|
||||
%dir %attr(750, serverkit-agent, serverkit-agent) /var/log/serverkit-agent
|
||||
|
||||
%pre
|
||||
# Create the dedicated, unprivileged service account before files are laid
|
||||
# down so the %files ownership attrs resolve. Idempotent across upgrades.
|
||||
getent group serverkit-agent >/dev/null || groupadd --system serverkit-agent
|
||||
getent passwd serverkit-agent >/dev/null || \
|
||||
useradd --system --gid serverkit-agent --no-create-home --shell /sbin/nologin serverkit-agent
|
||||
|
||||
%post
|
||||
%systemd_post serverkit-agent.service
|
||||
|
||||
# Let the agent reach the Docker socket without root.
|
||||
if getent group docker >/dev/null; then
|
||||
usermod -aG docker serverkit-agent || true
|
||||
fi
|
||||
|
||||
# State/data dirs the agent writes to, owned by the service account. Also
|
||||
# re-chown the config dir so an existing root-owned agent.key (previous root
|
||||
# install, or \`sudo register\`) becomes readable by the unprivileged service.
|
||||
mkdir -p /var/lib/serverkit/apps /var/serverkit/apps /var/log/serverkit-agent
|
||||
chown -R serverkit-agent:serverkit-agent \
|
||||
/var/lib/serverkit /var/serverkit /var/log/serverkit-agent /etc/serverkit-agent 2>/dev/null || true
|
||||
|
||||
echo ""
|
||||
echo "ServerKit Agent installed successfully!"
|
||||
echo ""
|
||||
echo "To complete setup:"
|
||||
echo " 1. Register the agent:"
|
||||
echo " sudo serverkit-agent register --token YOUR_TOKEN --server https://your-serverkit.com"
|
||||
echo " 1. Register the agent (runs as the service account):"
|
||||
echo " sudo -u serverkit-agent serverkit-agent register --token YOUR_TOKEN --server https://your-serverkit.com"
|
||||
echo ""
|
||||
echo " 2. Start the service:"
|
||||
echo " sudo systemctl start serverkit-agent"
|
||||
|
||||
@@ -10,9 +10,9 @@ type MessageType string
|
||||
|
||||
const (
|
||||
// Authentication
|
||||
TypeAuth MessageType = "auth"
|
||||
TypeAuthOK MessageType = "auth_ok"
|
||||
TypeAuthFail MessageType = "auth_fail"
|
||||
TypeAuth MessageType = "auth"
|
||||
TypeAuthOK MessageType = "auth_ok"
|
||||
TypeAuthFail MessageType = "auth_fail"
|
||||
|
||||
// Heartbeat
|
||||
TypeHeartbeat MessageType = "heartbeat"
|
||||
@@ -330,6 +330,30 @@ const (
|
||||
ActionCloudflaredTunnelRoute = "cloudflared:tunnel:route"
|
||||
ActionCloudflaredTunnelDelete = "cloudflared:tunnel:delete"
|
||||
|
||||
// WireGuard actions — manage a WireGuard interface so the panel can
|
||||
// pair two agents into a NAT-traversing tunnel (edge ↔ private). The
|
||||
// agent generates its keypair locally and returns ONLY the public
|
||||
// key; private keys never reach the panel. Linux-only until the
|
||||
// userspace backend (roadmap #6) lands. See
|
||||
// docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
ActionWireguardKeygen = "wireguard:keygen"
|
||||
ActionWireguardInterfaceUp = "wireguard:interface:up"
|
||||
ActionWireguardInterfaceDown = "wireguard:interface:down"
|
||||
ActionWireguardPeerSet = "wireguard:peer:set"
|
||||
ActionWireguardPeerRemove = "wireguard:peer:remove"
|
||||
ActionWireguardStatus = "wireguard:status"
|
||||
// wireguard:forward starts a TCP forwarder on the private peer so a
|
||||
// connection arriving over the tunnel reaches the real local service
|
||||
// (roadmap #13). Essential for the userspace/netstack backend.
|
||||
ActionWireguardForward = "wireguard:forward"
|
||||
ActionWireguardUnforward = "wireguard:unforward"
|
||||
|
||||
// Firewall actions — minimal host-firewall control so the tunnel
|
||||
// broker can open the edge's inbound WireGuard UDP port (#10).
|
||||
// Linux-only (ufw / firewalld / iptables).
|
||||
ActionFirewallAllowPort = "firewall:allow_port"
|
||||
ActionFirewallDenyPort = "firewall:deny_port"
|
||||
|
||||
// File actions
|
||||
ActionFileRead = "file:read"
|
||||
ActionFileWrite = "file:write"
|
||||
@@ -374,8 +398,10 @@ const (
|
||||
// CredentialUpdateMessage is sent by server to rotate credentials.
|
||||
//
|
||||
// HMACSig is computed by the panel as
|
||||
// hex(HMAC-SHA256("rotation_id:agent_id:new_api_key:new_api_secret",
|
||||
// current_api_secret))
|
||||
//
|
||||
// hex(HMAC-SHA256("rotation_id:agent_id:new_api_key:new_api_secret",
|
||||
// current_api_secret))
|
||||
//
|
||||
// where current_api_secret is the agent's secret prior to rotation.
|
||||
// The agent recomputes this with its own current secret and rejects
|
||||
// the rotation if they don't match. This prevents a panel session
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
function Install-ServerKitAgent {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory=$true)]
|
||||
[string]$Token,
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$Token = "",
|
||||
|
||||
[Parameter(Mandatory=$true)]
|
||||
[string]$Server,
|
||||
@@ -22,6 +22,15 @@ function Install-ServerKitAgent {
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
# Allow the token to come from the environment so it doesn't have to appear
|
||||
# on the command line (visible to admins via Get-CimInstance Win32_Process).
|
||||
# An explicit -Token wins.
|
||||
if (-not $Token) { $Token = $env:SERVERKIT_REGISTRATION_TOKEN }
|
||||
if (-not $Token) { $Token = $env:SERVERKIT_TOKEN }
|
||||
if (-not $Token) {
|
||||
throw "Registration token required: pass -Token or set SERVERKIT_REGISTRATION_TOKEN"
|
||||
}
|
||||
|
||||
# Configuration
|
||||
$InstallDir = "$env:ProgramFiles\ServerKit Agent"
|
||||
$ConfigDir = "$env:ProgramData\ServerKit\Agent"
|
||||
@@ -83,12 +92,20 @@ function Install-ServerKitAgent {
|
||||
|
||||
# Register with ServerKit
|
||||
Write-Info "Registering agent with ServerKit..."
|
||||
$RegisterArgs = @("register", "--token", $Token, "--server", $Server)
|
||||
$RegisterArgs = @("register", "--server", $Server)
|
||||
if (-not [string]::IsNullOrEmpty($Name)) {
|
||||
$RegisterArgs += @("--name", $Name)
|
||||
}
|
||||
|
||||
$process = Start-Process -FilePath $AgentPath -ArgumentList $RegisterArgs -Wait -PassThru -NoNewWindow
|
||||
# Pass the token via the environment, not -ArgumentList, so it isn't exposed
|
||||
# on the child process command line. Start-Process inherits this session's
|
||||
# environment; clear it again afterward.
|
||||
$env:SERVERKIT_REGISTRATION_TOKEN = $Token
|
||||
try {
|
||||
$process = Start-Process -FilePath $AgentPath -ArgumentList $RegisterArgs -Wait -PassThru -NoNewWindow
|
||||
} finally {
|
||||
Remove-Item Env:\SERVERKIT_REGISTRATION_TOKEN -ErrorAction SilentlyContinue
|
||||
}
|
||||
if ($process.ExitCode -ne 0) {
|
||||
Write-Err "Registration failed with exit code $($process.ExitCode)"
|
||||
throw "Registration failed"
|
||||
|
||||
@@ -62,10 +62,16 @@ while [[ $# -gt 0 ]]; do
|
||||
esac
|
||||
done
|
||||
|
||||
# Allow the token / server URL to come from the environment. This lets callers
|
||||
# avoid putting the token on the `curl ... | sudo bash -s -- --token <token>`
|
||||
# line, which would otherwise land in shell history. An explicit --token wins.
|
||||
TOKEN="${TOKEN:-${SERVERKIT_REGISTRATION_TOKEN:-$SERVERKIT_TOKEN}}"
|
||||
SERVER_URL="${SERVER_URL:-$SERVERKIT_SERVER_URL}"
|
||||
|
||||
# Validate required arguments
|
||||
if [ -z "$TOKEN" ]; then
|
||||
echo -e "${RED}Error: Registration token is required${NC}"
|
||||
echo "Usage: $0 --token TOKEN --server URL"
|
||||
echo "Usage: $0 --token TOKEN --server URL (or set SERVERKIT_REGISTRATION_TOKEN)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -202,14 +208,16 @@ install_agent() {
|
||||
register_agent() {
|
||||
log_info "Registering agent with ServerKit..."
|
||||
|
||||
REGISTER_CMD="$INSTALL_DIR/serverkit-agent register --token \"$TOKEN\" --server \"$SERVER_URL\""
|
||||
# Pass the token through the environment, not argv: command-line arguments
|
||||
# are world-readable via `ps` / /proc/<pid>/cmdline, while the environment
|
||||
# of this root-run process is readable only by root. The server URL and
|
||||
# name aren't secret, so they stay as flags. (Also drops the old `eval`.)
|
||||
local reg_args=(register --server "$SERVER_URL")
|
||||
if [ -n "$NAME" ]; then
|
||||
REGISTER_CMD="$REGISTER_CMD --name \"$NAME\""
|
||||
reg_args+=(--name "$NAME")
|
||||
fi
|
||||
|
||||
eval $REGISTER_CMD
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
if ! SERVERKIT_REGISTRATION_TOKEN="$TOKEN" "$INSTALL_DIR/serverkit-agent" "${reg_args[@]}"; then
|
||||
log_error "Registration failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -94,6 +94,7 @@ def create_app(config_name=None):
|
||||
# Register blueprints - Core
|
||||
from app.api.apps import apps_bp
|
||||
from app.api.domains import domains_bp
|
||||
from app.api.tunnels import tunnels_bp
|
||||
from app.api.private_urls import private_urls_bp
|
||||
app.register_blueprint(apps_bp, url_prefix='/api/v1/apps')
|
||||
app.register_blueprint(domains_bp, url_prefix='/api/v1/domains')
|
||||
@@ -209,6 +210,14 @@ def create_app(config_name=None):
|
||||
from app.api.source_connections import source_connections_bp
|
||||
app.register_blueprint(source_connections_bp, url_prefix='/api/v1/source-connections')
|
||||
|
||||
# Register blueprints - Domain registrar connections (portfolio + expiry)
|
||||
from app.api.registrars import registrars_bp
|
||||
app.register_blueprint(registrars_bp, url_prefix='/api/v1/registrars')
|
||||
|
||||
# Register blueprints - Unified connection registry (read-only "all connections")
|
||||
from app.api.connections import connections_bp
|
||||
app.register_blueprint(connections_bp, url_prefix='/api/v1/connections')
|
||||
|
||||
# Register blueprints - Database Migrations
|
||||
from app.api.migrations import migrations_bp
|
||||
app.register_blueprint(migrations_bp, url_prefix='/api/v1/migrations')
|
||||
@@ -283,6 +292,9 @@ def create_app(config_name=None):
|
||||
from app.api.cloud_provisioning import cloud_provisioning_bp
|
||||
app.register_blueprint(cloud_provisioning_bp, url_prefix='/api/v1/cloud')
|
||||
|
||||
# Register blueprints - Remote Access (WireGuard tunnels; imported above)
|
||||
app.register_blueprint(tunnels_bp, url_prefix='/api/v1/tunnels')
|
||||
|
||||
# Register blueprints - Performance
|
||||
from app.api.performance import performance_bp
|
||||
app.register_blueprint(performance_bp, url_prefix='/api/v1/performance')
|
||||
@@ -318,6 +330,24 @@ def create_app(config_name=None):
|
||||
SettingsService.initialize_defaults()
|
||||
SettingsService.migrate_legacy_roles()
|
||||
|
||||
# Encrypt any legacy plaintext provider secrets at rest (idempotent —
|
||||
# DNS-provider api keys and storage credentials predate encryption).
|
||||
try:
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.storage_provider_service import StorageProviderService
|
||||
from app.services.cloud_provisioning_service import CloudProvisioningService
|
||||
n_dns = DNSProviderService.encrypt_legacy_secrets()
|
||||
n_store = StorageProviderService.encrypt_legacy_secrets()
|
||||
n_cloud = CloudProvisioningService.encrypt_legacy_secrets()
|
||||
if n_dns or n_store or n_cloud:
|
||||
import logging as _logging
|
||||
_logging.getLogger(__name__).info(
|
||||
f'Encrypted legacy secrets at rest: {n_dns} DNS provider(s), '
|
||||
f'{n_store} storage field(s), {n_cloud} cloud provider(s)')
|
||||
except Exception as e:
|
||||
import logging as _logging
|
||||
_logging.getLogger(__name__).warning(f'Legacy secret encryption skipped: {e}')
|
||||
|
||||
# Load installed plugins (dynamic blueprints) AFTER migrations,
|
||||
# so the installed_plugins table exists.
|
||||
try:
|
||||
@@ -357,6 +387,9 @@ def create_app(config_name=None):
|
||||
# Start hourly pruner for expired pending agent pairings
|
||||
_start_pairing_pruner(app)
|
||||
|
||||
# Start daily registrar domain-expiry notifier
|
||||
_start_registrar_expiry_scheduler(app)
|
||||
|
||||
# Request body size limit
|
||||
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB limit
|
||||
|
||||
@@ -520,6 +553,41 @@ def _start_pairing_pruner(app):
|
||||
_pairing_prune_thread = None
|
||||
|
||||
|
||||
_registrar_expiry_thread = None
|
||||
|
||||
|
||||
def _start_registrar_expiry_scheduler(app):
|
||||
"""Daily check that notifies when a registrar domain crosses an expiry
|
||||
threshold (30/14/7/1 days, or expired). Single-worker only (module-global
|
||||
guard), like the other in-process schedulers."""
|
||||
global _registrar_expiry_thread
|
||||
if _registrar_expiry_thread is not None:
|
||||
return
|
||||
|
||||
import threading
|
||||
import time
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def loop():
|
||||
time.sleep(300) # let startup settle
|
||||
while True:
|
||||
try:
|
||||
with app.app_context():
|
||||
from app.services.registrar_service import RegistrarService
|
||||
n = RegistrarService.notify_expiring()
|
||||
if n:
|
||||
logger.info(f'Registrar expiry: sent {n} notification(s)')
|
||||
except Exception as e:
|
||||
logger.error(f'Registrar expiry scheduler error: {e}')
|
||||
time.sleep(86400) # daily
|
||||
|
||||
_registrar_expiry_thread = threading.Thread(
|
||||
target=loop, daemon=True, name='registrar-expiry')
|
||||
_registrar_expiry_thread.start()
|
||||
|
||||
|
||||
_snapshot_retention_thread = None
|
||||
|
||||
|
||||
|
||||
@@ -296,6 +296,18 @@ class AgentNamespace(Namespace):
|
||||
|
||||
agent_registry.update_capabilities(agent.server_id, data or {})
|
||||
|
||||
# Panel-authoritative tunnel reconcile (#19): if this agent can
|
||||
# drive WireGuard, re-apply (in the background) any tunnel config
|
||||
# it participates in, so tunnels self-heal after an agent or panel
|
||||
# restart. See docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
try:
|
||||
caps = (data or {}).get('capabilities') or {}
|
||||
if caps.get('wireguard'):
|
||||
from app.services.tunnel_broker_service import TunnelBrokerService
|
||||
TunnelBrokerService.schedule_reconcile(agent.server_id)
|
||||
except Exception:
|
||||
logger.debug("tunnel reconcile scheduling skipped", exc_info=True)
|
||||
|
||||
def on_stream(self, data):
|
||||
"""
|
||||
Handle streaming data from agent (logs, metrics).
|
||||
|
||||
@@ -359,6 +359,28 @@ def update_setting(key):
|
||||
}), 200
|
||||
|
||||
|
||||
# ============================================
|
||||
# Managed-sites domain & HTTPS (Phase 5)
|
||||
# ============================================
|
||||
|
||||
@admin_bp.route('/sites-https/status', methods=['GET'])
|
||||
@admin_required
|
||||
def sites_https_status():
|
||||
"""Report managed-sites base domain, server IP, providers, and HTTPS state."""
|
||||
from app.services.sites_https_service import SitesHttpsService
|
||||
return jsonify(SitesHttpsService.status()), 200
|
||||
|
||||
|
||||
@admin_bp.route('/sites-https/setup', methods=['POST'])
|
||||
@admin_required
|
||||
def sites_https_setup():
|
||||
"""Create the wildcard DNS record + issue the wildcard cert for the base domain."""
|
||||
from app.services.sites_https_service import SitesHttpsService
|
||||
data = request.get_json() or {}
|
||||
result = SitesHttpsService.setup(data.get('provider_id'), email=data.get('email'))
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
# ============================================
|
||||
# Admin Statistics Endpoints
|
||||
# ============================================
|
||||
|
||||
@@ -360,6 +360,9 @@ def set_app_workspace(app_id):
|
||||
return jsonify({'error': 'Workspace not found'}), 404
|
||||
if user.role != 'admin' and WorkspaceService.get_user_role(ws.id, user.id) is None:
|
||||
return jsonify({'error': 'Not a member of the target workspace'}), 403
|
||||
# Role reconciliation (#33): a 'viewer' member can't move resources into it.
|
||||
if not WorkspaceService.can_write_in_workspace(user, ws.id):
|
||||
return jsonify({'error': 'You have read-only access to the target workspace'}), 403
|
||||
ws_id = ws.id
|
||||
|
||||
app.workspace_id = ws_id
|
||||
@@ -643,6 +646,11 @@ def create_app():
|
||||
user = User.query.get(current_user_id)
|
||||
ws_id = WorkspaceService.resolve_workspace_id(
|
||||
user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
|
||||
# Role reconciliation (#33): a workspace 'viewer' member has read-only access to
|
||||
# the active workspace and may not create resources in it (checked only when a
|
||||
# workspace context is explicitly active, so no-context behavior is unchanged).
|
||||
if ws_id is not None and not WorkspaceService.can_write_in_workspace(user, ws_id):
|
||||
return jsonify({'error': 'You have read-only access to this workspace'}), 403
|
||||
if ws_id is None:
|
||||
ws_id = WorkspaceService.ensure_default_workspace().id
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Unified connection registry — one normalized, read-only list of every
|
||||
external account ServerKit is connected to (source, DNS, infra, registrar,
|
||||
storage). The individual write paths still live in their own blueprints; this
|
||||
is the single source of truth for "what's connected".
|
||||
"""
|
||||
|
||||
from flask import Blueprint, jsonify
|
||||
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||
|
||||
from app.services.connection_registry import ConnectionRegistry
|
||||
|
||||
connections_bp = Blueprint('connections', __name__)
|
||||
|
||||
|
||||
@connections_bp.route('', methods=['GET'])
|
||||
@connections_bp.route('/', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_connections():
|
||||
"""List every connected external account (secret-free)."""
|
||||
raw = get_jwt_identity()
|
||||
try:
|
||||
user_id = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
user_id = raw
|
||||
return jsonify({'connections': ConnectionRegistry.list_all(user_id=user_id)})
|
||||
@@ -620,13 +620,23 @@ def list_all_docker_databases():
|
||||
current_user_id = get_jwt_identity()
|
||||
user = User.query.get(current_user_id)
|
||||
|
||||
# Workspace-aware scoping (#33). Docker databases are app-children — scope the
|
||||
# enumeration to the apps the caller can see (own + granted, workspace-narrowed)
|
||||
# via the same helper apps/domains use. With no workspace context this is the
|
||||
# prior behavior. NOTE: the host-level MySQL/PostgreSQL/SQLite endpoints above
|
||||
# are server-global system resources with no app/workspace linkage, so they are
|
||||
# intentionally NOT workspace-scoped (their mutations are already admin-gated).
|
||||
from app.services.workspace_service import WorkspaceService
|
||||
ws_id = WorkspaceService.resolve_workspace_id(
|
||||
user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
|
||||
app_q = WorkspaceService.scope_query(
|
||||
Application.query.filter_by(app_type='docker'), Application, user,
|
||||
workspace_id=ws_id, owner_attr='user_id', grant_resource_type='application')
|
||||
|
||||
out = []
|
||||
apps = Application.query.filter_by(app_type='docker').all()
|
||||
for app in apps:
|
||||
for app in app_q.all():
|
||||
if not app.root_path:
|
||||
continue
|
||||
if not ResourceGrantService.can_access_app(user, app):
|
||||
continue
|
||||
info = DatabaseService.get_app_database_info(app.name, app.root_path)
|
||||
if not info:
|
||||
continue
|
||||
@@ -686,8 +696,12 @@ def get_docker_database_tables(container, database):
|
||||
user = request.args.get('user', 'root')
|
||||
password = request.headers.get('X-DB-Password')
|
||||
|
||||
tables = DatabaseService.docker_mysql_get_tables(container, database, user, password)
|
||||
return jsonify({'tables': tables}), 200
|
||||
result = DatabaseService.docker_mysql_get_tables(container, database, user, password)
|
||||
return jsonify({
|
||||
'tables': result['tables'],
|
||||
'connected': result['connected'],
|
||||
'error': result['error'],
|
||||
}), 200
|
||||
|
||||
|
||||
@databases_bp.route('/docker/<container>/<database>/query', methods=['POST'])
|
||||
|
||||
@@ -89,12 +89,22 @@ def get_domains():
|
||||
current_user_id = get_jwt_identity()
|
||||
user = User.query.get(current_user_id)
|
||||
|
||||
if user.role == 'admin':
|
||||
domains = Domain.query.all()
|
||||
else:
|
||||
# Get domains for user's applications
|
||||
user_app_ids = [app.id for app in Application.query.filter_by(user_id=current_user_id).all()]
|
||||
domains = Domain.query.filter(Domain.application_id.in_(user_app_ids)).all()
|
||||
# Workspace-aware scoping (#33). Domains are app-children with no workspace_id
|
||||
# of their own — they inherit their parent Application's. Scope the visible app
|
||||
# set (own + granted, workspace-narrowed) and return those apps' domains.
|
||||
# With no workspace context this matches prior behavior (admin -> all domains,
|
||||
# else -> the user's own apps' domains) and additionally surfaces domains of
|
||||
# apps shared via a grant — consistent with the per-domain routes, which
|
||||
# already authorize through ResourceGrantService.can_access_app.
|
||||
from app.services.workspace_service import WorkspaceService
|
||||
ws_id = WorkspaceService.resolve_workspace_id(
|
||||
user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
|
||||
app_q = WorkspaceService.scope_query(
|
||||
Application.query, Application, user,
|
||||
workspace_id=ws_id, owner_attr='user_id', grant_resource_type='application')
|
||||
app_ids = [row[0] for row in app_q.with_entities(Application.id).all()]
|
||||
domains = (Domain.query.filter(Domain.application_id.in_(app_ids)).all()
|
||||
if app_ids else [])
|
||||
|
||||
return jsonify({
|
||||
'domains': [domain.to_dict() for domain in domains]
|
||||
|
||||
@@ -7,6 +7,7 @@ from ..services.dns_provider_service import DNSProviderService
|
||||
from ..services.spamassassin_service import SpamAssassinService
|
||||
from ..services.roundcube_service import RoundcubeService
|
||||
from ..services.postfix_service import PostfixService
|
||||
from ..services.email_relay_service import EmailRelayService
|
||||
|
||||
email_bp = Blueprint('email', __name__)
|
||||
|
||||
@@ -313,6 +314,43 @@ def list_dns_zones(provider_id):
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
# ── Outbound SMTP Relay (smarthost) ──
|
||||
|
||||
@email_bp.route('/relay', methods=['GET'])
|
||||
@viewer_required
|
||||
def get_relay():
|
||||
"""Get the outbound SMTP relay configuration (password masked)."""
|
||||
return jsonify(EmailRelayService.get_config()), 200
|
||||
|
||||
|
||||
@email_bp.route('/relay', methods=['PUT'])
|
||||
@admin_required
|
||||
def save_relay():
|
||||
"""Save the relay configuration and apply it to Postfix (if installed)."""
|
||||
data = request.get_json() or {}
|
||||
if not data.get('host'):
|
||||
return jsonify({'success': False, 'error': 'A relay host is required'}), 400
|
||||
result = EmailRelayService.save_config(data)
|
||||
return jsonify(result), 200
|
||||
|
||||
|
||||
@email_bp.route('/relay/test', methods=['POST'])
|
||||
@admin_required
|
||||
def test_relay():
|
||||
"""Open a real SMTP connection to validate the relay credentials."""
|
||||
data = request.get_json() or {}
|
||||
result = EmailRelayService.test(data)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@email_bp.route('/relay', methods=['DELETE'])
|
||||
@admin_required
|
||||
def disable_relay():
|
||||
"""Disable the outbound relay (revert Postfix to direct delivery)."""
|
||||
result = EmailRelayService.disable()
|
||||
return jsonify(result), 200
|
||||
|
||||
|
||||
# ── SpamAssassin Config ──
|
||||
|
||||
@email_bp.route('/spam/config', methods=['GET'])
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from flask import Blueprint, request, jsonify, send_file
|
||||
from flask_jwt_extended import jwt_required
|
||||
from ..services.file_service import FileService
|
||||
from ..services.storage_provider_service import StorageProviderService
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
@@ -413,3 +414,76 @@ def upload_file():
|
||||
return jsonify({'error': 'Permission denied'}), 403
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
|
||||
# ── S3 / object-storage browser (reuses the configured backup storage creds) ──
|
||||
|
||||
@files_bp.route('/s3/browse', methods=['GET'])
|
||||
@jwt_required()
|
||||
def s3_browse():
|
||||
"""List a bucket prefix in the same entry shape as the local browser."""
|
||||
path = request.args.get('path', '/')
|
||||
result = StorageProviderService.s3_browse(path)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@files_bp.route('/s3/read', methods=['GET'])
|
||||
@jwt_required()
|
||||
def s3_read():
|
||||
"""Read a text object for in-app editing."""
|
||||
path = request.args.get('path')
|
||||
if not path:
|
||||
return jsonify({'error': 'Path is required'}), 400
|
||||
result = StorageProviderService.s3_read(path)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@files_bp.route('/s3/write', methods=['POST'])
|
||||
@jwt_required()
|
||||
def s3_write():
|
||||
"""Write (create or overwrite) an object from text content."""
|
||||
data = request.get_json() or {}
|
||||
path = data.get('path')
|
||||
content = data.get('content')
|
||||
if not path:
|
||||
return jsonify({'error': 'Path is required'}), 400
|
||||
if content is None:
|
||||
return jsonify({'error': 'Content is required'}), 400
|
||||
result = StorageProviderService.s3_write(path, content)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@files_bp.route('/s3/delete', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def s3_delete():
|
||||
"""Delete an object (or every object beneath a prefix)."""
|
||||
path = request.args.get('path')
|
||||
if not path:
|
||||
return jsonify({'error': 'Path is required'}), 400
|
||||
result = StorageProviderService.s3_delete(path)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@files_bp.route('/s3/download-url', methods=['GET'])
|
||||
@jwt_required()
|
||||
def s3_download_url():
|
||||
"""Return a short-lived presigned URL the browser can download directly."""
|
||||
path = request.args.get('path')
|
||||
if not path:
|
||||
return jsonify({'error': 'Path is required'}), 400
|
||||
result = StorageProviderService.s3_presigned_get(path)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@files_bp.route('/s3/upload', methods=['POST'])
|
||||
@jwt_required()
|
||||
def s3_upload():
|
||||
"""Upload a file into the bucket at the given prefix."""
|
||||
if 'file' not in request.files:
|
||||
return jsonify({'error': 'No file provided'}), 400
|
||||
file = request.files['file']
|
||||
destination = request.form.get('destination', '/')
|
||||
if file.filename == '':
|
||||
return jsonify({'error': 'No file selected'}), 400
|
||||
result = StorageProviderService.s3_upload(destination, file.filename, file.stream)
|
||||
return jsonify(result), 201 if result.get('success') else 400
|
||||
@@ -6,8 +6,8 @@ Endpoints:
|
||||
POST /api/v1/pairing/code/refresh (enrollment auth)
|
||||
POST /api/v1/pairing/code/freeze (enrollment auth)
|
||||
GET /api/v1/pairing/poll (enrollment auth, long-poll)
|
||||
POST /api/v1/pairing/claim (operator JWT)
|
||||
GET /api/v1/pairing/lookup (operator JWT — pre-flight code check)
|
||||
POST /api/v1/pairing/claim (operator JWT, developer role)
|
||||
GET /api/v1/pairing/lookup (operator JWT, developer role — pre-flight code check)
|
||||
"""
|
||||
|
||||
import time
|
||||
@@ -15,6 +15,7 @@ from flask import Blueprint, request, jsonify, current_app
|
||||
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||
|
||||
from app import limiter
|
||||
from app.middleware.rbac import developer_required
|
||||
from app.services import pairing_service
|
||||
from app.services.pairing_service import (
|
||||
PairingError,
|
||||
@@ -145,6 +146,7 @@ def poll():
|
||||
|
||||
@pairing_bp.route('/lookup', methods=['POST'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
@limiter.limit("20 per minute")
|
||||
def lookup():
|
||||
"""Pre-flight: confirm a code exists (without revealing details)."""
|
||||
@@ -163,6 +165,7 @@ def lookup():
|
||||
|
||||
@pairing_bp.route('/claim', methods=['POST'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
@limiter.limit("5 per 10 minute")
|
||||
def claim():
|
||||
user_id = int(get_jwt_identity())
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Domain-registrar connections — the portfolio + expiry surface.
|
||||
|
||||
Connections are admin-managed (like DNS providers). Reading the portfolio is
|
||||
available to any authenticated user so the Domains page and Connections cards
|
||||
can show "what we own and when it lapses".
|
||||
"""
|
||||
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||
|
||||
from app.models.user import User
|
||||
from app.services.registrar_service import RegistrarService
|
||||
|
||||
registrars_bp = Blueprint('registrars', __name__)
|
||||
|
||||
|
||||
def _current_user():
|
||||
return User.query.get(get_jwt_identity())
|
||||
|
||||
|
||||
@registrars_bp.route('/connections', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_connections():
|
||||
conns = RegistrarService.list_connections()
|
||||
return jsonify({'connections': [c.to_dict() for c in conns]})
|
||||
|
||||
|
||||
@registrars_bp.route('/connections', methods=['POST'])
|
||||
@jwt_required()
|
||||
def add_connection():
|
||||
user = _current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json() or {}
|
||||
try:
|
||||
conn = RegistrarService.add_connection(data, user.id)
|
||||
except ValueError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
# Validate the credentials immediately; drop the row if they don't work so
|
||||
# we never persist a dead connection.
|
||||
test = RegistrarService.test_connection(conn)
|
||||
if not test.get('success'):
|
||||
RegistrarService.delete_connection(conn.id)
|
||||
return jsonify({'error': test.get('error', 'Connection test failed')}), 400
|
||||
return jsonify({'connection': conn.to_dict(), 'test': test}), 201
|
||||
|
||||
|
||||
@registrars_bp.route('/connections/<int:cid>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def delete_connection(cid):
|
||||
user = _current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
if not RegistrarService.delete_connection(cid):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify({'message': 'Registrar disconnected'})
|
||||
|
||||
|
||||
@registrars_bp.route('/connections/<int:cid>/test', methods=['POST'])
|
||||
@jwt_required()
|
||||
def test_connection(cid):
|
||||
conn = RegistrarService.get_connection(cid)
|
||||
if not conn:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
result = RegistrarService.test_connection(conn)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@registrars_bp.route('/domains', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_domains():
|
||||
"""Aggregated domain portfolio across all connected registrars."""
|
||||
return jsonify({'domains': RegistrarService.list_all_domains()})
|
||||
|
||||
|
||||
@registrars_bp.route('/sync', methods=['POST'])
|
||||
@jwt_required()
|
||||
def sync():
|
||||
"""Force-refresh the portfolio (and stamp last_synced_at)."""
|
||||
return jsonify({'domains': RegistrarService.sync_now()})
|
||||
@@ -324,6 +324,11 @@ def create_server():
|
||||
user = User.query.get(user_id)
|
||||
ws_id = WorkspaceService.resolve_workspace_id(
|
||||
user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
|
||||
# Role reconciliation (#33): a workspace 'viewer' member has read-only access to
|
||||
# the active workspace and may not create resources in it (checked only when a
|
||||
# workspace context is explicitly active, so no-context behavior is unchanged).
|
||||
if ws_id is not None and not WorkspaceService.can_write_in_workspace(user, ws_id):
|
||||
return jsonify({'error': 'You have read-only access to this workspace'}), 403
|
||||
if ws_id is None:
|
||||
ws_id = WorkspaceService.ensure_default_workspace().id
|
||||
|
||||
@@ -392,6 +397,9 @@ def set_server_workspace(server_id):
|
||||
return jsonify({'error': 'Workspace not found'}), 404
|
||||
if not user.is_admin and WorkspaceService.get_user_role(ws.id, user.id) is None:
|
||||
return jsonify({'error': 'Not a member of the target workspace'}), 403
|
||||
# Role reconciliation (#33): a 'viewer' member can't move resources into it.
|
||||
if not WorkspaceService.can_write_in_workspace(user, ws.id):
|
||||
return jsonify({'error': 'You have read-only access to the target workspace'}), 403
|
||||
ws_id = ws.id
|
||||
|
||||
server.workspace_id = ws_id
|
||||
@@ -2115,11 +2123,16 @@ def get_agent_checksums():
|
||||
|
||||
@servers_bp.route('/<server_id>/agent/update', methods=['POST'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
def trigger_agent_update(server_id):
|
||||
"""
|
||||
Trigger an agent update on a specific server.
|
||||
|
||||
Sends a command to the agent to check for and install updates.
|
||||
|
||||
Developer role required — this replaces the agent binary and restarts the
|
||||
service across the fleet, so it must not be reachable by read-only viewers
|
||||
(every other state-changing server route is already @developer_required).
|
||||
"""
|
||||
server = Server.query.get(server_id)
|
||||
if not server:
|
||||
|
||||
@@ -141,3 +141,135 @@ def _github_error(exc):
|
||||
return data.get('message') or str(exc)
|
||||
except Exception:
|
||||
return response.text or str(exc)
|
||||
|
||||
|
||||
@source_connections_bp.route('/gitlab/status', methods=['GET'])
|
||||
@jwt_required()
|
||||
def gitlab_status():
|
||||
user_id = int(get_jwt_identity())
|
||||
return jsonify(SourceConnectionService.get_gitlab_status(user_id)), 200
|
||||
|
||||
|
||||
@source_connections_bp.route('/gitlab/authorize', methods=['GET'])
|
||||
@jwt_required()
|
||||
def gitlab_authorize():
|
||||
redirect_uri = request.args.get('redirect_uri', '')
|
||||
if not redirect_uri:
|
||||
return jsonify({'error': 'redirect_uri is required'}), 400
|
||||
|
||||
try:
|
||||
auth_url, state = SourceConnectionService.generate_gitlab_authorize_url(redirect_uri)
|
||||
return jsonify({'auth_url': auth_url, 'state': state}), 200
|
||||
except ValueError as exc:
|
||||
return jsonify({'error': str(exc)}), 400
|
||||
|
||||
|
||||
@source_connections_bp.route('/gitlab/callback', methods=['POST'])
|
||||
@jwt_required()
|
||||
def gitlab_callback():
|
||||
user_id = int(get_jwt_identity())
|
||||
data = request.get_json() or {}
|
||||
code = data.get('code', '')
|
||||
state = data.get('state', '')
|
||||
redirect_uri = data.get('redirect_uri', '')
|
||||
|
||||
if not code or not state or not redirect_uri:
|
||||
return jsonify({'error': 'code, state, and redirect_uri are required'}), 400
|
||||
|
||||
try:
|
||||
connection = SourceConnectionService.complete_gitlab_callback(
|
||||
user_id=user_id,
|
||||
code=code,
|
||||
state=state,
|
||||
redirect_uri=redirect_uri,
|
||||
)
|
||||
return jsonify({'connection': connection.to_dict()}), 200
|
||||
except ValueError as exc:
|
||||
return jsonify({'error': str(exc)}), 400
|
||||
except HTTPError as exc:
|
||||
return jsonify({'error': _gitlab_error(exc)}), 400
|
||||
|
||||
|
||||
@source_connections_bp.route('/gitlab/repos', methods=['GET'])
|
||||
@jwt_required()
|
||||
def gitlab_repositories():
|
||||
user_id = int(get_jwt_identity())
|
||||
search = request.args.get('search', '')
|
||||
page = request.args.get('page', 1, type=int)
|
||||
per_page = request.args.get('per_page', 50, type=int)
|
||||
|
||||
try:
|
||||
repos = SourceConnectionService.list_gitlab_repositories(user_id, search, page, per_page)
|
||||
return jsonify({'repos': repos}), 200
|
||||
except ValueError as exc:
|
||||
return jsonify({'error': str(exc)}), 400
|
||||
except HTTPError as exc:
|
||||
return jsonify({'error': _gitlab_error(exc)}), 400
|
||||
|
||||
|
||||
@source_connections_bp.route('/gitlab/repos/<path:full_name>/branches', methods=['GET'])
|
||||
@jwt_required()
|
||||
def gitlab_branches(full_name):
|
||||
user_id = int(get_jwt_identity())
|
||||
|
||||
try:
|
||||
branches = SourceConnectionService.list_gitlab_branches(user_id, full_name)
|
||||
return jsonify({'branches': branches}), 200
|
||||
except ValueError as exc:
|
||||
return jsonify({'error': str(exc)}), 400
|
||||
except HTTPError as exc:
|
||||
return jsonify({'error': _gitlab_error(exc)}), 400
|
||||
|
||||
|
||||
@source_connections_bp.route('/gitlab/repos/<path:full_name>/manifest', methods=['GET'])
|
||||
@jwt_required()
|
||||
def gitlab_repository_manifest(full_name):
|
||||
user_id = int(get_jwt_identity())
|
||||
ref = request.args.get('ref') or None
|
||||
|
||||
try:
|
||||
manifest = SourceConnectionService.get_gitlab_repository_manifest(user_id, full_name, ref)
|
||||
return jsonify({'manifest': manifest}), 200
|
||||
except ValueError as exc:
|
||||
return jsonify({'error': str(exc)}), 400
|
||||
except HTTPError as exc:
|
||||
return jsonify({'error': _gitlab_error(exc)}), 400
|
||||
|
||||
|
||||
@source_connections_bp.route('/gitlab', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def disconnect_gitlab():
|
||||
user_id = int(get_jwt_identity())
|
||||
try:
|
||||
SourceConnectionService.disconnect(user_id, 'gitlab')
|
||||
return jsonify({'message': 'GitLab disconnected'}), 200
|
||||
except ValueError as exc:
|
||||
return jsonify({'error': str(exc)}), 404
|
||||
|
||||
|
||||
@source_connections_bp.route('/admin/gitlab', methods=['GET'])
|
||||
@admin_required
|
||||
def gitlab_admin_config():
|
||||
return jsonify({'config': SourceConnectionService.get_gitlab_config(redacted=True)}), 200
|
||||
|
||||
|
||||
@source_connections_bp.route('/admin/gitlab', methods=['PUT'])
|
||||
@admin_required
|
||||
def update_gitlab_admin_config():
|
||||
user = User.query.get(get_jwt_identity())
|
||||
result = SourceConnectionService.update_gitlab_config(
|
||||
request.get_json() or {},
|
||||
user_id=user.id if user else None,
|
||||
)
|
||||
return jsonify(result), 200
|
||||
|
||||
|
||||
def _gitlab_error(exc):
|
||||
response = getattr(exc, 'response', None)
|
||||
if response is None:
|
||||
return str(exc)
|
||||
try:
|
||||
data = response.json()
|
||||
return data.get('message') or data.get('error_description') or data.get('error') or str(exc)
|
||||
except Exception:
|
||||
return response.text or str(exc)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Tunnels API (roadmap Phase 1 — #9).
|
||||
|
||||
Brokers WireGuard pairings between two agents (a public-IP edge + a NAT'd
|
||||
private host) so a service behind NAT can be reached over the tunnel.
|
||||
See docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
"""
|
||||
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||
|
||||
from app.models.tunnel import Tunnel
|
||||
from app.services.tunnel_broker_service import TunnelBrokerService, TunnelBrokerError
|
||||
from app.services.tunnel_publish_service import TunnelPublishService, TunnelPublishError
|
||||
from app.middleware.rbac import developer_required
|
||||
|
||||
tunnels_bp = Blueprint('tunnels', __name__)
|
||||
|
||||
|
||||
def _error(e):
|
||||
return jsonify({'error': e.message, 'code': e.code}), e.status
|
||||
|
||||
|
||||
@tunnels_bp.route('/', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_tunnels():
|
||||
tunnels = Tunnel.query.order_by(Tunnel.created_at.desc()).all()
|
||||
return jsonify({'tunnels': [t.to_dict() for t in tunnels]})
|
||||
|
||||
|
||||
@tunnels_bp.route('/', methods=['POST'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
def create_tunnel():
|
||||
data = request.get_json(silent=True) or {}
|
||||
edge = (data.get('edge_server_id') or '').strip()
|
||||
private = (data.get('private_server_id') or '').strip()
|
||||
name = (data.get('name') or '').strip() or None
|
||||
if not edge or not private:
|
||||
return jsonify({'error': 'edge_server_id and private_server_id are required'}), 400
|
||||
try:
|
||||
tunnel = TunnelBrokerService.create_tunnel(edge, private, name=name, user_id=get_jwt_identity())
|
||||
except TunnelBrokerError as e:
|
||||
return _error(e)
|
||||
body = tunnel.to_dict()
|
||||
fw = TunnelBrokerService.firewall_hint(tunnel.listen_port)
|
||||
auto = getattr(tunnel, 'firewall_status', None)
|
||||
if auto is not None:
|
||||
fw['auto_open'] = auto # outcome of the agent-driven open (#10)
|
||||
body['firewall'] = fw
|
||||
return jsonify(body), 201
|
||||
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>', methods=['GET'])
|
||||
@jwt_required()
|
||||
def get_tunnel(tunnel_id):
|
||||
try:
|
||||
tunnel = TunnelBrokerService.get_tunnel(tunnel_id)
|
||||
except TunnelBrokerError as e:
|
||||
return _error(e)
|
||||
# Default: refresh live status. Pass ?refresh=0 for the cached row only.
|
||||
if request.args.get('refresh', '1') in ('0', 'false', 'no'):
|
||||
return jsonify({'tunnel': tunnel.to_dict()})
|
||||
try:
|
||||
return jsonify(TunnelBrokerService.refresh_status(tunnel, user_id=get_jwt_identity()))
|
||||
except TunnelBrokerError as e:
|
||||
return _error(e)
|
||||
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
def delete_tunnel(tunnel_id):
|
||||
try:
|
||||
TunnelBrokerService.teardown_tunnel(tunnel_id, user_id=get_jwt_identity())
|
||||
except TunnelBrokerError as e:
|
||||
return _error(e)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ---- exposed services (Phase 2: publish a service over a tunnel) --------
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>/services', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_services(tunnel_id):
|
||||
services = TunnelPublishService.list_for_tunnel(tunnel_id)
|
||||
return jsonify({'services': [s.to_dict() for s in services]})
|
||||
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>/services', methods=['POST'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
def publish_service(tunnel_id):
|
||||
data = request.get_json(silent=True) or {}
|
||||
hostname = (data.get('hostname') or '').strip()
|
||||
port = data.get('port')
|
||||
if not hostname or port is None:
|
||||
return jsonify({'error': 'hostname and port are required'}), 400
|
||||
try:
|
||||
svc, steps = TunnelPublishService.publish(
|
||||
tunnel_id, hostname, port,
|
||||
require_auth=bool(data.get('require_auth')),
|
||||
auth_username=(data.get('auth_username') or '').strip() or None,
|
||||
auth_password=data.get('auth_password'),
|
||||
ssl=data.get('ssl', True),
|
||||
email=(data.get('email') or '').strip() or None,
|
||||
user_id=get_jwt_identity(),
|
||||
)
|
||||
except TunnelPublishError as e:
|
||||
return _error(e)
|
||||
body = svc.to_dict()
|
||||
body['steps'] = steps
|
||||
return jsonify(body), 201
|
||||
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>/services/<service_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
def unpublish_service(tunnel_id, service_id):
|
||||
try:
|
||||
TunnelPublishService.unpublish(service_id, user_id=get_jwt_identity())
|
||||
except TunnelPublishError as e:
|
||||
return _error(e)
|
||||
return jsonify({'success': True})
|
||||
@@ -16,6 +16,18 @@ def _resolve_app(site_or_app_id):
|
||||
return Application.query.get(site_or_app_id)
|
||||
|
||||
|
||||
def _is_wp_app(app):
|
||||
"""True if `app` is a WordPress-managed site. Containerized WP sites are
|
||||
stored with app_type 'docker' (see WordPressService), so app_type alone is
|
||||
not a reliable signal — a linked WordPressSite record is the source of truth.
|
||||
"""
|
||||
if not app:
|
||||
return False
|
||||
if app.app_type == 'wordpress':
|
||||
return True
|
||||
return WordPressSite.query.filter_by(application_id=app.id).first() is not None
|
||||
|
||||
|
||||
# ==================== WORDPRESS SITES HUB ENDPOINTS ====================
|
||||
|
||||
@wordpress_bp.route('/sites', methods=['GET'])
|
||||
@@ -66,7 +78,8 @@ def create_site():
|
||||
@wordpress_bp.route('/sites/import', methods=['POST'])
|
||||
@jwt_required()
|
||||
def import_site():
|
||||
"""Import an existing WordPress site from an uploaded SQL dump (multipart)."""
|
||||
"""Import an existing WordPress site from an uploaded SQL dump plus an optional
|
||||
wp-content/full-site .zip (multipart)."""
|
||||
import os
|
||||
import tempfile
|
||||
name = request.form.get('name')
|
||||
@@ -85,11 +98,21 @@ def import_site():
|
||||
if not (fname.endswith('.sql') or fname.endswith('.sql.gz') or fname.endswith('.gz')):
|
||||
return jsonify({'error': 'Dump must be a .sql or .sql.gz file'}), 400
|
||||
|
||||
# Optional wp-content / full-site zip (plugins/themes/uploads).
|
||||
zip_file = request.files.get('wp_content')
|
||||
if zip_file and zip_file.filename and not zip_file.filename.lower().endswith('.zip'):
|
||||
return jsonify({'error': 'wp-content archive must be a .zip file'}), 400
|
||||
|
||||
suffix = '.sql.gz' if fname.endswith('.gz') else '.sql'
|
||||
fd, tmp_path = tempfile.mkstemp(suffix=suffix, prefix='wp_import_')
|
||||
os.close(fd)
|
||||
zip_tmp = None
|
||||
try:
|
||||
sql_file.save(tmp_path)
|
||||
if zip_file and zip_file.filename:
|
||||
zfd, zip_tmp = tempfile.mkstemp(suffix='.zip', prefix='wp_import_content_')
|
||||
os.close(zfd)
|
||||
zip_file.save(zip_tmp)
|
||||
current_user_id = get_jwt_identity()
|
||||
result = WordPressService.import_site(
|
||||
name=name,
|
||||
@@ -97,12 +120,15 @@ def import_site():
|
||||
user_id=current_user_id,
|
||||
sql_path=tmp_path,
|
||||
old_url=old_url,
|
||||
wp_content_zip_path=zip_tmp,
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
os.remove(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
for p in (tmp_path, zip_tmp):
|
||||
if p:
|
||||
try:
|
||||
os.remove(p)
|
||||
except OSError:
|
||||
pass
|
||||
return (jsonify(result), 201) if result.get('success') else (jsonify(result), 400)
|
||||
|
||||
|
||||
@@ -377,6 +403,8 @@ def get_php(app_id):
|
||||
return jsonify({'error': 'Access denied'}), 403
|
||||
info = WordPressService.get_php_info(app.root_path)
|
||||
info['available_versions'] = WordPressService.get_available_php_versions()
|
||||
# The directives the limits panel may edit (#24 write side).
|
||||
info['editable_limits'] = list(WordPressService.get_php_limit_spec().keys())
|
||||
return jsonify({'php': info}), 200
|
||||
|
||||
|
||||
@@ -398,6 +426,25 @@ def set_php(app_id):
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@wordpress_bp.route('/sites/<int:app_id>/php/limits', methods=['POST'])
|
||||
@jwt_required()
|
||||
@admin_required
|
||||
def set_php_limits(app_id):
|
||||
"""Durably set per-site PHP ini limits (#24): writes a conf.d drop-in,
|
||||
bind-mounts it, and reloads the container. Body: {limits: {key: value, ...}}."""
|
||||
app = _resolve_app(app_id)
|
||||
data = request.get_json() or {}
|
||||
if not app:
|
||||
return jsonify({'error': 'Application not found'}), 404
|
||||
if app.app_type not in ('wordpress', 'docker'):
|
||||
return jsonify({'error': 'Application is not a WordPress site'}), 400
|
||||
limits = data.get('limits')
|
||||
if not isinstance(limits, dict) or not limits:
|
||||
return jsonify({'error': 'limits object is required'}), 400
|
||||
result = WordPressService.set_php_limits(app.root_path, limits)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
def _site_status_target(wp_site):
|
||||
"""Best-effort public URL for a managed site's status-page component.
|
||||
Prefers a primary domain (https when SSL), falls back to the local port.
|
||||
@@ -519,6 +566,8 @@ def get_site_analytics(app_id):
|
||||
if user.role != 'admin' and app.user_id != current_user_id:
|
||||
return jsonify({'error': 'Access denied'}), 403
|
||||
result = WpAnalyticsService.get_traffic(app.name, request.args.get('hours', 24))
|
||||
# PHP fatals/warnings from the WP_DEBUG log (#25 fatals; populated by #30's toggle).
|
||||
result['php_errors'] = WpAnalyticsService.get_php_errors(app.name)
|
||||
return jsonify(result), 200
|
||||
|
||||
|
||||
@@ -786,7 +835,7 @@ def get_wordpress_info(app_id):
|
||||
if user.role != 'admin' and app.user_id != current_user_id:
|
||||
return jsonify({'error': 'Access denied'}), 403
|
||||
|
||||
if app.app_type != 'wordpress':
|
||||
if not _is_wp_app(app):
|
||||
return jsonify({'error': 'Application is not a WordPress site'}), 400
|
||||
|
||||
info = WordPressService.get_wordpress_info(app.root_path)
|
||||
@@ -806,7 +855,7 @@ def update_wordpress(app_id):
|
||||
if not app:
|
||||
return jsonify({'error': 'Application not found'}), 404
|
||||
|
||||
if app.app_type != 'wordpress':
|
||||
if not _is_wp_app(app):
|
||||
return jsonify({'error': 'Application is not a WordPress site'}), 400
|
||||
|
||||
result = WordPressService.update_wordpress(app.root_path)
|
||||
@@ -1087,6 +1136,62 @@ def search_replace(app_id):
|
||||
return jsonify(result), 200 if result['success'] else 400
|
||||
|
||||
|
||||
@wordpress_bp.route('/sites/<int:app_id>/url/preview', methods=['POST'])
|
||||
@jwt_required()
|
||||
@admin_required
|
||||
def preview_site_url(app_id):
|
||||
"""Dry-run a site URL change: per-pair replacement counts, no mutation."""
|
||||
app = _resolve_app(app_id)
|
||||
if not app:
|
||||
return jsonify({'error': 'Application not found'}), 404
|
||||
data = request.get_json() or {}
|
||||
new_url = data.get('new_url')
|
||||
if not new_url:
|
||||
return jsonify({'error': 'new_url is required'}), 400
|
||||
result = WordPressService.preview_url_change(app, new_url)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@wordpress_bp.route('/sites/<int:app_id>/url', methods=['POST'])
|
||||
@jwt_required()
|
||||
@admin_required
|
||||
def change_site_url(app_id):
|
||||
"""Change a site's URL end to end: backup, serialization-safe DB rewrite,
|
||||
home/siteurl + cache flush, then re-point the Domain row + nginx vhost."""
|
||||
app = _resolve_app(app_id)
|
||||
if not app:
|
||||
return jsonify({'error': 'Application not found'}), 404
|
||||
data = request.get_json() or {}
|
||||
new_url = data.get('new_url')
|
||||
if not new_url:
|
||||
return jsonify({'error': 'new_url is required'}), 400
|
||||
keep_old = data.get('keep_old_redirect', True)
|
||||
result = WordPressService.change_site_url(app, new_url, keep_old_redirect=keep_old)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@wordpress_bp.route('/sites/<int:app_id>/domain', methods=['POST'])
|
||||
@jwt_required()
|
||||
@admin_required
|
||||
def attach_custom_domain(app_id):
|
||||
"""Attach a user-owned custom domain: auto-create the DNS A record (or return
|
||||
it to add manually), optional Let's Encrypt cert, then migrate the site URL."""
|
||||
app = _resolve_app(app_id)
|
||||
if not app:
|
||||
return jsonify({'error': 'Application not found'}), 404
|
||||
data = request.get_json() or {}
|
||||
domain = data.get('domain')
|
||||
if not domain:
|
||||
return jsonify({'error': 'domain is required'}), 400
|
||||
result = WordPressService.attach_custom_domain(
|
||||
app, domain,
|
||||
migrate=data.get('migrate', True),
|
||||
issue_ssl=data.get('issue_ssl', False),
|
||||
email=data.get('email'),
|
||||
)
|
||||
return jsonify(result), 200 if result.get('success') else 400
|
||||
|
||||
|
||||
@wordpress_bp.route('/sites/<int:app_id>/optimize', methods=['POST'])
|
||||
@jwt_required()
|
||||
@admin_required
|
||||
@@ -1237,7 +1342,7 @@ def wp_auto_login(site_id):
|
||||
app = wp_site.application if wp_site else _resolve_app(site_id)
|
||||
if not app or not app.root_path:
|
||||
return jsonify({'error': 'Application not found'}), 404
|
||||
if app.app_type != 'wordpress':
|
||||
if not _is_wp_app(app):
|
||||
return jsonify({'error': 'Application is not a WordPress site'}), 400
|
||||
|
||||
# Resolve a managed admin tied to the operator's panel email. Prefer the
|
||||
|
||||
@@ -33,7 +33,16 @@ def list_workspaces():
|
||||
workspaces = WorkspaceService.get_all_workspaces_admin()
|
||||
return jsonify({'workspaces': workspaces})
|
||||
workspaces = WorkspaceService.list_workspaces(user_id=user.id, include_archived=include_archived)
|
||||
return jsonify({'workspaces': [ws.to_dict() for ws in workspaces]})
|
||||
# Surface the caller's membership role and the reconciled effective role (#33)
|
||||
# so the frontend can show read-only state when a workspace caps the user to
|
||||
# viewer. effective_role is narrow-only: it never exceeds the user's global role.
|
||||
out = []
|
||||
for ws in workspaces:
|
||||
d = ws.to_dict()
|
||||
d['my_role'] = WorkspaceService.get_user_role(ws.id, user.id)
|
||||
d['my_effective_role'] = WorkspaceService.effective_role(user, ws.id)
|
||||
out.append(d)
|
||||
return jsonify({'workspaces': out})
|
||||
|
||||
|
||||
@workspaces_bp.route('/<int:workspace_id>', methods=['GET'])
|
||||
|
||||
@@ -16,9 +16,10 @@ from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob,
|
||||
from app.models.environment_activity import EnvironmentActivity
|
||||
from app.models.promotion_job import PromotionJob
|
||||
from app.models.sanitization_profile import SanitizationProfile
|
||||
from app.models.email import EmailDomain, EmailAccount, EmailAlias, EmailForwardingRule, DNSProviderConfig
|
||||
from app.models.email import EmailDomain, EmailAccount, EmailAlias, EmailForwardingRule, DNSProviderConfig, EmailRelayConfig
|
||||
from app.models.oauth_identity import OAuthIdentity
|
||||
from app.models.source_connection import SourceConnection
|
||||
from app.models.registrar_connection import RegistrarConnection
|
||||
from app.models.api_key import ApiKey
|
||||
from app.models.api_usage import ApiUsageLog, ApiUsageSummary
|
||||
from app.models.event_subscription import EventSubscription, EventDelivery
|
||||
@@ -28,6 +29,8 @@ from app.models.agent_plugin import AgentPlugin, AgentPluginInstall
|
||||
from app.models.server_template import ServerTemplate, ServerTemplateAssignment
|
||||
from app.models.workspace import Workspace, WorkspaceMember, WorkspaceApiKey, ResourceGrant
|
||||
from app.models.dns_zone import DNSZone, DNSRecord
|
||||
from app.models.tunnel import Tunnel
|
||||
from app.models.exposed_service import ExposedService
|
||||
from app.models.status_page import StatusPage, StatusComponent, HealthCheck, StatusIncident, StatusIncidentUpdate
|
||||
from app.models.cloud_server import CloudProvider, CloudServer, CloudSnapshot
|
||||
from app.models.marketplace import Extension, ExtensionInstall
|
||||
@@ -42,14 +45,15 @@ __all__ = [
|
||||
'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'AgentVersion', 'AgentRollout', 'SecurityAlert',
|
||||
'WordPressSite', 'DatabaseSnapshot', 'SyncJob', 'WordPressVulnerability',
|
||||
'EnvironmentActivity', 'PromotionJob', 'SanitizationProfile',
|
||||
'EmailDomain', 'EmailAccount', 'EmailAlias', 'EmailForwardingRule', 'DNSProviderConfig',
|
||||
'OAuthIdentity', 'SourceConnection', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',
|
||||
'EmailDomain', 'EmailAccount', 'EmailAlias', 'EmailForwardingRule', 'DNSProviderConfig', 'EmailRelayConfig',
|
||||
'OAuthIdentity', 'SourceConnection', 'RegistrarConnection', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',
|
||||
'EventSubscription', 'EventDelivery', 'Invitation',
|
||||
'ServerAlertThreshold', 'MetricAlert',
|
||||
'AgentPlugin', 'AgentPluginInstall',
|
||||
'ServerTemplate', 'ServerTemplateAssignment',
|
||||
'Workspace', 'WorkspaceMember', 'WorkspaceApiKey', 'ResourceGrant',
|
||||
'DNSZone', 'DNSRecord',
|
||||
'Tunnel', 'ExposedService',
|
||||
'StatusPage', 'StatusComponent', 'HealthCheck', 'StatusIncident', 'StatusIncidentUpdate',
|
||||
'CloudProvider', 'CloudServer', 'CloudSnapshot',
|
||||
'Extension', 'ExtensionInstall',
|
||||
|
||||
@@ -169,3 +169,35 @@ class DNSProviderConfig(db.Model):
|
||||
|
||||
def __repr__(self):
|
||||
return f'<DNSProviderConfig {self.name} ({self.provider})>'
|
||||
|
||||
|
||||
class EmailRelayConfig(db.Model):
|
||||
"""Outbound SMTP relay (smarthost) for the mail server — routes outgoing mail
|
||||
through a third-party provider (Postmark, SES, Mailgun, …). Single-row config;
|
||||
the password is Fernet-encrypted (see app.utils.crypto)."""
|
||||
__tablename__ = 'email_relay_config'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
enabled = db.Column(db.Boolean, default=False)
|
||||
host = db.Column(db.String(255))
|
||||
port = db.Column(db.Integer, default=587)
|
||||
username = db.Column(db.String(255))
|
||||
password_encrypted = db.Column(db.Text)
|
||||
use_tls = db.Column(db.Boolean, default=True)
|
||||
provider_hint = db.Column(db.String(40)) # 'postmark' | 'ses' | 'mailgun' | 'sendgrid' | 'custom'
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'enabled': bool(self.enabled),
|
||||
'host': self.host or '',
|
||||
'port': self.port or 587,
|
||||
'username': self.username or '',
|
||||
'use_tls': self.use_tls if self.use_tls is not None else True,
|
||||
'provider_hint': self.provider_hint,
|
||||
'password_set': bool(self.password_encrypted),
|
||||
'updated_at': self.updated_at.isoformat() if self.updated_at else None,
|
||||
}
|
||||
|
||||
def __repr__(self):
|
||||
return f'<EmailRelayConfig {self.host or "(unset)"}>'
|
||||
@@ -0,0 +1,58 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
class ExposedService(db.Model):
|
||||
"""A service on a private (NAT'd) host published to the public internet
|
||||
over a WireGuard tunnel (roadmap Phase 2). The edge runs an nginx vhost
|
||||
for ``hostname`` that proxies to the private peer's WG IP; the private
|
||||
agent forwards that to the real local service on ``port``.
|
||||
See docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
"""
|
||||
__tablename__ = 'exposed_services'
|
||||
|
||||
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
tunnel_id = db.Column(db.String(36), db.ForeignKey('tunnels.id'), nullable=False, index=True)
|
||||
|
||||
hostname = db.Column(db.String(255), nullable=False) # e.g. jellyfin.example.com
|
||||
port = db.Column(db.Integer, nullable=False) # service port on the private host (e.g. 8096)
|
||||
nginx_site_name = db.Column(db.String(120)) # the edge vhost we created
|
||||
|
||||
require_auth = db.Column(db.Boolean, default=False)
|
||||
auth_username = db.Column(db.String(100))
|
||||
ssl_enabled = db.Column(db.Boolean, default=False)
|
||||
|
||||
status = db.Column(db.String(20), default='pending', index=True) # pending / published / error
|
||||
last_error = db.Column(db.Text)
|
||||
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
tunnel = db.relationship('Tunnel')
|
||||
|
||||
def url(self):
|
||||
if not self.hostname:
|
||||
return None
|
||||
return ('https://' if self.ssl_enabled else 'http://') + self.hostname
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'tunnel_id': self.tunnel_id,
|
||||
'hostname': self.hostname,
|
||||
'port': self.port,
|
||||
'nginx_site_name': self.nginx_site_name,
|
||||
'require_auth': self.require_auth,
|
||||
'auth_username': self.auth_username,
|
||||
'ssl_enabled': self.ssl_enabled,
|
||||
'status': self.status,
|
||||
'last_error': self.last_error,
|
||||
'url': self.url(),
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
'updated_at': self.updated_at.isoformat() if self.updated_at else None,
|
||||
}
|
||||
|
||||
def __repr__(self):
|
||||
return '<ExposedService %s -> tunnel %s :%s>' % (self.hostname, self.tunnel_id, self.port)
|
||||
@@ -0,0 +1,53 @@
|
||||
from datetime import datetime
|
||||
from app import db
|
||||
|
||||
|
||||
class RegistrarConnection(db.Model):
|
||||
"""A connected domain-registrar account (GoDaddy, …) used to read the domain
|
||||
portfolio: registration status, expiry dates, auto-renew and nameservers.
|
||||
|
||||
This is an *ownership* connection, distinct from a DNS-provider connection
|
||||
(DNSProviderConfig) which manages records. Credentials are stored
|
||||
Fernet-encrypted via app.utils.crypto, like SourceConnection tokens.
|
||||
"""
|
||||
__tablename__ = 'registrar_connections'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
|
||||
provider = db.Column(db.String(40), nullable=False) # 'godaddy'
|
||||
name = db.Column(db.String(120), nullable=True) # user-facing label
|
||||
api_key_encrypted = db.Column(db.Text, nullable=True)
|
||||
api_secret_encrypted = db.Column(db.Text, nullable=True)
|
||||
account_label = db.Column(db.String(180), nullable=True) # e.g. domain count / shopper id
|
||||
config_json = db.Column(db.Text, nullable=True) # provider-specific non-secret extras (e.g. Namecheap username + client_ip)
|
||||
last_synced_at = db.Column(db.DateTime, nullable=True)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
@property
|
||||
def config(self):
|
||||
import json
|
||||
if not self.config_json:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(self.config_json)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
@config.setter
|
||||
def config(self, value):
|
||||
import json
|
||||
self.config_json = json.dumps(value) if value else None
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'provider': self.provider,
|
||||
'name': self.name or self.provider,
|
||||
'account_label': self.account_label,
|
||||
'last_synced_at': self.last_synced_at.isoformat() if self.last_synced_at else None,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
}
|
||||
|
||||
def __repr__(self):
|
||||
return f'<RegistrarConnection {self.provider}:{self.id}>'
|
||||
@@ -4,7 +4,12 @@ from app import db
|
||||
|
||||
|
||||
class SourceConnection(db.Model):
|
||||
"""External source-code provider connection for repository imports."""
|
||||
"""External source-code provider connection for repository imports.
|
||||
|
||||
The ``provider`` column is a plain string and accepts any supported
|
||||
provider value (e.g. ``'github'`` or ``'gitlab'``); there is no enum or
|
||||
allow-list to extend.
|
||||
"""
|
||||
|
||||
__tablename__ = 'source_connections'
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
class Tunnel(db.Model):
|
||||
"""A WireGuard pairing between two ServerKit agents: a public-IP
|
||||
"edge" and a NAT'd "private" host. The data plane is kernel WireGuard
|
||||
running on the agents; this row is the panel's brokered record of it.
|
||||
|
||||
SECURITY: stores PUBLIC keys only. Private keys are generated on and
|
||||
never leave the hosts. See docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
"""
|
||||
__tablename__ = 'tunnels'
|
||||
|
||||
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
name = db.Column(db.String(120))
|
||||
|
||||
# Two FKs to servers → relationships must name foreign_keys explicitly.
|
||||
edge_server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=False, index=True)
|
||||
private_server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=False, index=True)
|
||||
|
||||
interface_name = db.Column(db.String(15), nullable=False)
|
||||
subnet = db.Column(db.String(43), nullable=False) # CIDR, e.g. 10.88.3.0/24
|
||||
edge_wg_ip = db.Column(db.String(45), nullable=False) # 10.88.3.1
|
||||
private_wg_ip = db.Column(db.String(45), nullable=False) # 10.88.3.2
|
||||
listen_port = db.Column(db.Integer, default=51820)
|
||||
|
||||
# PUBLIC keys only — never private.
|
||||
edge_pubkey = db.Column(db.String(64))
|
||||
private_pubkey = db.Column(db.String(64))
|
||||
|
||||
# pending → up → degraded / down / error
|
||||
status = db.Column(db.String(20), default='pending', index=True)
|
||||
last_handshake_at = db.Column(db.DateTime)
|
||||
last_error = db.Column(db.Text)
|
||||
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
edge_server = db.relationship('Server', foreign_keys=[edge_server_id])
|
||||
private_server = db.relationship('Server', foreign_keys=[private_server_id])
|
||||
|
||||
def _prefix(self):
|
||||
return self.subnet.split('/')[-1] if self.subnet and '/' in self.subnet else '24'
|
||||
|
||||
def edge_address(self):
|
||||
"""CIDR address for the edge's interface, e.g. 10.88.3.1/24."""
|
||||
return "%s/%s" % (self.edge_wg_ip, self._prefix())
|
||||
|
||||
def private_address(self):
|
||||
"""CIDR address for the private host's interface, e.g. 10.88.3.2/24."""
|
||||
return "%s/%s" % (self.private_wg_ip, self._prefix())
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'name': self.name,
|
||||
'edge_server_id': self.edge_server_id,
|
||||
'edge_server_name': self.edge_server.name if self.edge_server else None,
|
||||
'private_server_id': self.private_server_id,
|
||||
'private_server_name': self.private_server.name if self.private_server else None,
|
||||
'interface_name': self.interface_name,
|
||||
'subnet': self.subnet,
|
||||
'edge_wg_ip': self.edge_wg_ip,
|
||||
'private_wg_ip': self.private_wg_ip,
|
||||
'listen_port': self.listen_port,
|
||||
'edge_pubkey': self.edge_pubkey,
|
||||
'private_pubkey': self.private_pubkey,
|
||||
'status': self.status,
|
||||
'last_handshake_at': self.last_handshake_at.isoformat() if self.last_handshake_at else None,
|
||||
'last_error': self.last_error,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
'updated_at': self.updated_at.isoformat() if self.updated_at else None,
|
||||
}
|
||||
|
||||
def __repr__(self):
|
||||
return '<Tunnel %s %s->%s>' % (self.interface_name, self.edge_server_id, self.private_server_id)
|
||||
@@ -36,23 +36,50 @@ class AdvancedSSLService:
|
||||
return AdvancedSSLService.SSL_PROFILES
|
||||
|
||||
@staticmethod
|
||||
def issue_wildcard_cert(domain, dns_provider, credentials):
|
||||
"""Issue wildcard SSL via DNS-01 challenge."""
|
||||
def issue_wildcard_cert(domain, dns_provider, credentials, email=None):
|
||||
"""Issue a wildcard cert (domain + *.domain) via Let's Encrypt DNS-01.
|
||||
|
||||
Supports cloudflare (API token) and route53 (AWS key/secret). The certbot
|
||||
DNS plugin matching the system certbot is installed best-effort first.
|
||||
Returns the on-disk cert/key paths on success.
|
||||
"""
|
||||
import os
|
||||
from app.utils.system import PackageManager
|
||||
|
||||
wildcard = f'*.{domain}'
|
||||
cmd = ['certbot', 'certonly', '--non-interactive', '--agree-tos',
|
||||
'--dns-' + dns_provider, '-d', domain, '-d', wildcard]
|
||||
cmd.extend(['--email', email] if email else ['--register-unsafely-without-email'])
|
||||
|
||||
# Best-effort: ensure the DNS plugin matching the system certbot exists.
|
||||
if PackageManager.is_available():
|
||||
try:
|
||||
PackageManager.install([f'python3-certbot-dns-{dns_provider}'], timeout=300)
|
||||
except Exception:
|
||||
pass # certbot reports a clear error below if the plugin is truly missing
|
||||
|
||||
run_kwargs = {}
|
||||
if dns_provider == 'cloudflare':
|
||||
cred_file = f'/tmp/certbot-{dns_provider}.ini'
|
||||
with open(cred_file, 'w') as f:
|
||||
f.write(f"dns_cloudflare_api_token = {credentials.get('api_token', '')}\n")
|
||||
import os
|
||||
os.chmod(cred_file, 0o600)
|
||||
cmd.extend(['--dns-cloudflare-credentials', cred_file])
|
||||
elif dns_provider == 'route53':
|
||||
run_kwargs['env'] = {
|
||||
**os.environ,
|
||||
'AWS_ACCESS_KEY_ID': credentials.get('api_key', ''),
|
||||
'AWS_SECRET_ACCESS_KEY': credentials.get('api_secret', ''),
|
||||
}
|
||||
|
||||
try:
|
||||
result = run_command(cmd)
|
||||
return {'success': True, 'domain': domain, 'type': 'wildcard', 'output': result.get('stdout', '')}
|
||||
result = run_command(cmd, **run_kwargs)
|
||||
return {
|
||||
'success': True, 'domain': domain, 'type': 'wildcard',
|
||||
'certificate_path': f'/etc/letsencrypt/live/{domain}/fullchain.pem',
|
||||
'private_key_path': f'/etc/letsencrypt/live/{domain}/privkey.pem',
|
||||
'output': result.get('stdout', ''),
|
||||
}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
|
||||
@@ -152,27 +152,15 @@ class AgentPluginService:
|
||||
install.config = config
|
||||
db.session.add(install)
|
||||
|
||||
# Agent-side plugin execution is NOT implemented: the Go agent has no
|
||||
# plugin_install handler and there is no panel gateway to route one to.
|
||||
# The previous code called a non-existent get_agent_gateway() and
|
||||
# swallowed the resulting ImportError, leaving the row stuck in
|
||||
# 'installing' forever. Fail honestly so the UI reflects reality.
|
||||
install.status = AgentPluginInstall.STATUS_ERROR
|
||||
install.error_message = 'Agent-side plugin support is not implemented yet'
|
||||
db.session.commit()
|
||||
|
||||
# Send install command to agent
|
||||
try:
|
||||
from app.agent_gateway import get_agent_gateway
|
||||
gw = get_agent_gateway()
|
||||
if gw:
|
||||
gw.send_command(server.agent_id, 'plugin_install', {
|
||||
'plugin_name': plugin.name,
|
||||
'version': plugin.version,
|
||||
'manifest': plugin.manifest,
|
||||
'config': install.config,
|
||||
'permissions': plugin.permissions,
|
||||
'resource_limits': {
|
||||
'max_memory_mb': plugin.max_memory_mb,
|
||||
'max_cpu_percent': plugin.max_cpu_percent,
|
||||
}
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning(f'Could not send plugin install command: {e}')
|
||||
|
||||
return install
|
||||
|
||||
@staticmethod
|
||||
@@ -181,20 +169,11 @@ class AgentPluginService:
|
||||
if not install:
|
||||
return False
|
||||
|
||||
# No agent-side plugin runtime exists to notify; uninstall is local-only
|
||||
# bookkeeping. (Previously dispatched to a non-existent get_agent_gateway.)
|
||||
install.status = AgentPluginInstall.STATUS_UNINSTALLING
|
||||
db.session.commit()
|
||||
|
||||
# Send uninstall command to agent
|
||||
try:
|
||||
from app.agent_gateway import get_agent_gateway
|
||||
gw = get_agent_gateway()
|
||||
if gw and install.server:
|
||||
gw.send_command(install.server.agent_id, 'plugin_uninstall', {
|
||||
'plugin_name': install.plugin.name,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning(f'Could not send plugin uninstall command: {e}')
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
@@ -211,19 +190,10 @@ class AgentPluginService:
|
||||
install = AgentPluginInstall.query.get(install_id)
|
||||
if not install:
|
||||
return None
|
||||
# Local-only state change; no agent-side plugin runtime to notify.
|
||||
install.status = AgentPluginInstall.STATUS_DISABLED
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
from app.agent_gateway import get_agent_gateway
|
||||
gw = get_agent_gateway()
|
||||
if gw and install.server:
|
||||
gw.send_command(install.server.agent_id, 'plugin_disable', {
|
||||
'plugin_name': install.plugin.name,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning(f'Could not send plugin disable command: {e}')
|
||||
|
||||
return install
|
||||
|
||||
@staticmethod
|
||||
@@ -247,20 +217,10 @@ class AgentPluginService:
|
||||
install = AgentPluginInstall.query.get(install_id)
|
||||
if not install:
|
||||
return None
|
||||
# Local-only config persistence; no agent-side plugin runtime to notify.
|
||||
install.config = config
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
from app.agent_gateway import get_agent_gateway
|
||||
gw = get_agent_gateway()
|
||||
if gw and install.server:
|
||||
gw.send_command(install.server.agent_id, 'plugin_configure', {
|
||||
'plugin_name': install.plugin.name,
|
||||
'config': config,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning(f'Could not send plugin config update: {e}')
|
||||
|
||||
return install
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -843,10 +843,13 @@ class AgentRegistry:
|
||||
if ip_address:
|
||||
anomaly_detection_service.track_auth_attempt(server.id, True, ip_address)
|
||||
|
||||
# TODO: Implement per-message session token validation. Currently, the session
|
||||
# token is issued at auth time but not verified on each subsequent message.
|
||||
# Full session-per-message validation requires protocol changes on both the
|
||||
# agent (Go) and backend sides.
|
||||
# NOTE (accepted limitation, not a bug): the session token is issued at
|
||||
# auth time but not re-verified on every subsequent message. This is
|
||||
# acceptable under the current model — a WS connection is authenticated
|
||||
# by HMAC+nonce at connect and then rides an authenticated TLS channel,
|
||||
# and the poll transport re-presents the token on each call. Per-message
|
||||
# token validation would add defence in depth but needs protocol changes
|
||||
# on both the agent (Go) and panel sides; tracked as a future hardening.
|
||||
|
||||
return server
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import logging
|
||||
from datetime import datetime
|
||||
from app import db
|
||||
from app.models.cloud_server import CloudProvider, CloudServer, CloudSnapshot
|
||||
from app.utils.crypto import encrypt_secret, decrypt_secret_safe, is_encrypted
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -55,7 +56,7 @@ class CloudProvisioningService:
|
||||
provider = CloudProvider(
|
||||
name=data.get('name', CloudProvisioningService.SUPPORTED_PROVIDERS[ptype]['name']),
|
||||
provider_type=ptype,
|
||||
api_key_encrypted=data.get('api_key', ''),
|
||||
api_key_encrypted=encrypt_secret(data['api_key']) if data.get('api_key') else '',
|
||||
created_by=user_id,
|
||||
)
|
||||
db.session.add(provider)
|
||||
@@ -75,6 +76,19 @@ class CloudProvisioningService:
|
||||
def get_provider_options(provider_type):
|
||||
return CloudProvisioningService.SUPPORTED_PROVIDERS.get(provider_type, {})
|
||||
|
||||
@staticmethod
|
||||
def encrypt_legacy_secrets():
|
||||
"""One-time, idempotent: encrypt any cloud-provider API tokens still stored
|
||||
in plaintext (the column predates encryption-at-rest)."""
|
||||
changed = 0
|
||||
for provider in CloudProvider.query.all():
|
||||
if provider.api_key_encrypted and not is_encrypted(provider.api_key_encrypted):
|
||||
provider.api_key_encrypted = encrypt_secret(provider.api_key_encrypted)
|
||||
changed += 1
|
||||
if changed:
|
||||
db.session.commit()
|
||||
return changed
|
||||
|
||||
# --- Servers ---
|
||||
|
||||
@staticmethod
|
||||
@@ -239,7 +253,7 @@ class CloudProvisioningService:
|
||||
@staticmethod
|
||||
def _auth_headers(provider):
|
||||
return {
|
||||
'Authorization': f'Bearer {provider.api_key_encrypted}',
|
||||
'Authorization': f'Bearer {decrypt_secret_safe(provider.api_key_encrypted)}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Unified read facade over every external-account store ServerKit holds.
|
||||
|
||||
ServerKit's connections live in five places, each with its own model/service and
|
||||
write path (kept that way deliberately — they have genuinely different auth and
|
||||
cardinality):
|
||||
|
||||
- source connections (SourceConnection) — per-user OAuth (GitHub, GitLab)
|
||||
- DNS providers (DNSProviderConfig) — Cloudflare / Route 53 / DO / GoDaddy
|
||||
- cloud providers (CloudProvider) — DigitalOcean / Hetzner / Vultr / Linode
|
||||
- registrars (RegistrarConnection) — GoDaddy / Namecheap
|
||||
- object storage (storage.json) — S3-compatible / Backblaze B2
|
||||
|
||||
This registry doesn't replace any of them; it presents them as ONE normalized,
|
||||
secret-free list (`GET /api/v1/connections`) so any surface can answer "what
|
||||
external accounts are connected, and are their secrets encrypted?" in one call.
|
||||
All five now encrypt secrets identically via app.utils.crypto, so `encrypted`
|
||||
should be True for every real connection.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _entry(kind, provider, label, *, id=None, scope=None, encrypted=True, created_at=None):
|
||||
return {
|
||||
'kind': kind,
|
||||
'provider': provider,
|
||||
'id': id,
|
||||
'label': label,
|
||||
'scope': scope,
|
||||
'encrypted': bool(encrypted),
|
||||
'created_at': created_at.isoformat() if hasattr(created_at, 'isoformat') else created_at,
|
||||
}
|
||||
|
||||
|
||||
class ConnectionRegistry:
|
||||
"""Read-only aggregator. Returns plain dicts with no secret material."""
|
||||
|
||||
@classmethod
|
||||
def list_all(cls, user_id=None):
|
||||
out = []
|
||||
for fn in (cls._source, cls._dns, cls._infra, cls._registrar, cls._storage):
|
||||
try:
|
||||
out += fn(user_id) if fn is cls._source else fn()
|
||||
except Exception as e: # one failing store never breaks the whole list
|
||||
logger.warning(f'ConnectionRegistry: {fn.__name__} failed: {e}')
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _source(user_id=None):
|
||||
from app.models.source_connection import SourceConnection
|
||||
q = SourceConnection.query
|
||||
if user_id is not None:
|
||||
q = q.filter_by(user_id=user_id)
|
||||
return [
|
||||
_entry('source', c.provider,
|
||||
c.display_name or c.provider_username or c.provider,
|
||||
id=c.id, scope='OAuth',
|
||||
encrypted=bool(c.access_token_encrypted), created_at=c.created_at)
|
||||
for c in q.all()
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def _dns():
|
||||
from app.models.email import DNSProviderConfig
|
||||
from app.utils.crypto import is_encrypted
|
||||
out = []
|
||||
for c in DNSProviderConfig.query.all():
|
||||
scope = 'Global key' if (c.provider == 'cloudflare' and c.api_email) else 'API key'
|
||||
out.append(_entry('dns', c.provider, c.name, id=c.id, scope=scope,
|
||||
encrypted=is_encrypted(c.api_key or ''), created_at=c.created_at))
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _infra():
|
||||
from app.models.cloud_server import CloudProvider
|
||||
from app.utils.crypto import is_encrypted
|
||||
return [
|
||||
_entry('infra', c.provider_type, c.name, id=c.id, scope='Account token',
|
||||
encrypted=is_encrypted(c.api_key_encrypted or ''), created_at=c.created_at)
|
||||
for c in CloudProvider.query.filter_by(is_active=True).all()
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def _registrar():
|
||||
from app.models.registrar_connection import RegistrarConnection
|
||||
return [
|
||||
_entry('registrar', c.provider, c.name or c.provider, id=c.id, scope='API key',
|
||||
encrypted=bool(c.api_key_encrypted), created_at=c.created_at)
|
||||
for c in RegistrarConnection.query.all()
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def _storage():
|
||||
from app.services.storage_provider_service import StorageProviderService
|
||||
cfg = StorageProviderService.get_config()
|
||||
provider = cfg.get('provider')
|
||||
if provider in ('s3', 'b2'):
|
||||
bucket = (cfg.get(provider) or {}).get('bucket')
|
||||
if bucket:
|
||||
return [_entry('storage', provider, f'{provider.upper()} · {bucket}',
|
||||
scope='Access key', encrypted=True)]
|
||||
return []
|
||||
@@ -1249,7 +1249,13 @@ class DatabaseService:
|
||||
|
||||
@staticmethod
|
||||
def docker_mysql_get_tables(container_name, database, user='root', password=None):
|
||||
"""Get tables in a Docker MySQL database."""
|
||||
"""List tables in a Docker MySQL database.
|
||||
|
||||
Returns ``{'connected': bool, 'tables': [...], 'error': str|None}`` so
|
||||
callers can tell a genuinely empty database apart from a container/auth
|
||||
failure. Both used to collapse to ``[]`` and the explorer rendered
|
||||
"Empty" either way, silently hiding a broken connection.
|
||||
"""
|
||||
result = DatabaseService.docker_mysql_execute(
|
||||
container_name,
|
||||
"SHOW TABLES;",
|
||||
@@ -1258,7 +1264,11 @@ class DatabaseService:
|
||||
password=password
|
||||
)
|
||||
if not result['success']:
|
||||
return []
|
||||
return {
|
||||
'connected': False,
|
||||
'tables': [],
|
||||
'error': result.get('error') or 'Could not connect to the database container',
|
||||
}
|
||||
|
||||
tables = []
|
||||
for line in result['output'].strip().split('\n')[1:]:
|
||||
@@ -1283,7 +1293,7 @@ class DatabaseService:
|
||||
'name': table_name,
|
||||
'rows': rows
|
||||
})
|
||||
return tables
|
||||
return {'connected': True, 'tables': tables, 'error': None}
|
||||
|
||||
@staticmethod
|
||||
def docker_mysql_execute_query(container_name, database, query, user='root', password=None,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""DNS Provider service for managing DKIM/SPF/DMARC records via Cloudflare and Route53."""
|
||||
"""DNS Provider service for managing DKIM/SPF/DMARC records via Cloudflare, Route53, DigitalOcean and GoDaddy."""
|
||||
import logging
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
@@ -6,6 +6,7 @@ import requests
|
||||
|
||||
from app import db
|
||||
from app.models.email import DNSProviderConfig
|
||||
from app.utils.crypto import encrypt_secret, decrypt_secret_safe, is_encrypted
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -29,8 +30,8 @@ class DNSProviderService:
|
||||
api_secret: str = None, api_email: str = None,
|
||||
is_default: bool = False) -> Dict:
|
||||
"""Add a new DNS provider configuration."""
|
||||
if provider not in ('cloudflare', 'route53'):
|
||||
return {'success': False, 'error': 'Provider must be cloudflare or route53'}
|
||||
if provider not in ('cloudflare', 'route53', 'digitalocean', 'godaddy'):
|
||||
return {'success': False, 'error': 'Provider must be cloudflare, route53, digitalocean or godaddy'}
|
||||
try:
|
||||
if is_default:
|
||||
# Unset other defaults
|
||||
@@ -39,8 +40,8 @@ class DNSProviderService:
|
||||
config = DNSProviderConfig(
|
||||
name=name,
|
||||
provider=provider,
|
||||
api_key=api_key,
|
||||
api_secret=api_secret,
|
||||
api_key=encrypt_secret(api_key) if api_key else api_key,
|
||||
api_secret=encrypt_secret(api_secret) if api_secret else api_secret,
|
||||
api_email=api_email,
|
||||
is_default=is_default,
|
||||
)
|
||||
@@ -65,6 +66,46 @@ class DNSProviderService:
|
||||
db.session.rollback()
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
# ── Secret access (decrypt with plaintext fallback for legacy rows) ──
|
||||
|
||||
@staticmethod
|
||||
def _api_key(config: DNSProviderConfig) -> str:
|
||||
return decrypt_secret_safe(config.api_key)
|
||||
|
||||
@staticmethod
|
||||
def _api_secret(config: DNSProviderConfig) -> str:
|
||||
return decrypt_secret_safe(config.api_secret)
|
||||
|
||||
@classmethod
|
||||
def decrypted_credentials(cls, config: DNSProviderConfig) -> Dict:
|
||||
"""Decrypted credentials for a DNS provider — the safe way for any caller
|
||||
OUTSIDE this service to get usable creds. Never read ``config.api_key``
|
||||
directly; it's encrypted at rest."""
|
||||
return {
|
||||
'api_key': cls._api_key(config),
|
||||
'api_secret': cls._api_secret(config),
|
||||
'api_email': config.api_email,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def encrypt_legacy_secrets(cls) -> int:
|
||||
"""One-time, idempotent: encrypt any DNS-provider secrets still stored in
|
||||
plaintext (rows created before encryption-at-rest landed)."""
|
||||
changed = 0
|
||||
for config in DNSProviderConfig.query.all():
|
||||
dirty = False
|
||||
if config.api_key and not is_encrypted(config.api_key):
|
||||
config.api_key = encrypt_secret(config.api_key)
|
||||
dirty = True
|
||||
if config.api_secret and not is_encrypted(config.api_secret):
|
||||
config.api_secret = encrypt_secret(config.api_secret)
|
||||
dirty = True
|
||||
if dirty:
|
||||
changed += 1
|
||||
if changed:
|
||||
db.session.commit()
|
||||
return changed
|
||||
|
||||
@classmethod
|
||||
def test_connection(cls, provider_id: int) -> Dict:
|
||||
"""Test DNS provider API connection."""
|
||||
@@ -76,6 +117,10 @@ class DNSProviderService:
|
||||
return cls._test_cloudflare(config)
|
||||
elif config.provider == 'route53':
|
||||
return cls._test_route53(config)
|
||||
elif config.provider == 'digitalocean':
|
||||
return cls._test_digitalocean(config)
|
||||
elif config.provider == 'godaddy':
|
||||
return cls._test_godaddy(config)
|
||||
return {'success': False, 'error': 'Unknown provider'}
|
||||
|
||||
@classmethod
|
||||
@@ -89,6 +134,10 @@ class DNSProviderService:
|
||||
return cls._cloudflare_list_zones(config)
|
||||
elif config.provider == 'route53':
|
||||
return cls._route53_list_zones(config)
|
||||
elif config.provider == 'digitalocean':
|
||||
return cls._digitalocean_list_zones(config)
|
||||
elif config.provider == 'godaddy':
|
||||
return cls._godaddy_list_zones(config)
|
||||
return {'success': False, 'error': 'Unknown provider'}
|
||||
|
||||
@classmethod
|
||||
@@ -103,6 +152,10 @@ class DNSProviderService:
|
||||
return cls._cloudflare_set_record(config, zone_id, record_type, name, value, ttl)
|
||||
elif config.provider == 'route53':
|
||||
return cls._route53_set_record(config, zone_id, record_type, name, value, ttl)
|
||||
elif config.provider == 'digitalocean':
|
||||
return cls._digitalocean_set_record(config, zone_id, record_type, name, value, ttl)
|
||||
elif config.provider == 'godaddy':
|
||||
return cls._godaddy_set_record(config, zone_id, record_type, name, value, ttl)
|
||||
return {'success': False, 'error': 'Unknown provider'}
|
||||
|
||||
@classmethod
|
||||
@@ -116,6 +169,10 @@ class DNSProviderService:
|
||||
return cls._cloudflare_delete_record(config, zone_id, record_type, name)
|
||||
elif config.provider == 'route53':
|
||||
return cls._route53_delete_record(config, zone_id, record_type, name)
|
||||
elif config.provider == 'digitalocean':
|
||||
return cls._digitalocean_delete_record(config, zone_id, record_type, name)
|
||||
elif config.provider == 'godaddy':
|
||||
return cls._godaddy_delete_record(config, zone_id, record_type, name)
|
||||
return {'success': False, 'error': 'Unknown provider'}
|
||||
|
||||
@classmethod
|
||||
@@ -151,6 +208,51 @@ class DNSProviderService:
|
||||
'message': 'All DNS records deployed' if all_ok else 'Some records failed',
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def find_zone_for_domain(cls, domain: str):
|
||||
"""Find a connected provider + zone that authoritatively covers ``domain``.
|
||||
|
||||
Picks the longest matching zone suffix across every configured provider
|
||||
(so ``blog.example.com`` matches a zone ``example.com``). Returns
|
||||
``(config, zone_dict)`` or ``(None, None)`` when nothing manages it.
|
||||
"""
|
||||
domain = (domain or '').strip().lower().rstrip('.')
|
||||
best = None # (config, zone, zone_name_length)
|
||||
for config in DNSProviderConfig.query.all():
|
||||
zres = cls.list_zones(config.id)
|
||||
if not zres.get('success'):
|
||||
continue
|
||||
for zone in zres.get('zones', []):
|
||||
zname = (zone.get('name') or '').strip().lower().rstrip('.')
|
||||
if zname and (domain == zname or domain.endswith('.' + zname)):
|
||||
if best is None or len(zname) > best[2]:
|
||||
best = (config, zone, len(zname))
|
||||
return (best[0], best[1]) if best else (None, None)
|
||||
|
||||
@classmethod
|
||||
def ensure_a_record(cls, domain: str, ip: str) -> Dict:
|
||||
"""Upsert an ``A`` record ``domain -> ip`` via whichever connected provider
|
||||
manages the zone. Degrades to manual instructions (``created: False`` with
|
||||
the record to add) when there's no server IP, no provider, or an API error
|
||||
— so the caller can always show the user what to do.
|
||||
"""
|
||||
domain = (domain or '').strip().lower().rstrip('.')
|
||||
record = {'type': 'A', 'name': domain, 'value': ip}
|
||||
if not domain:
|
||||
return {'created': False, 'reason': 'no_domain', 'record': record}
|
||||
if not ip:
|
||||
return {'created': False, 'reason': 'no_server_ip', 'record': record,
|
||||
'message': 'Set the server public IP in Settings to auto-create DNS records.'}
|
||||
config, zone = cls.find_zone_for_domain(domain)
|
||||
if not config:
|
||||
return {'created': False, 'reason': 'no_provider', 'record': record,
|
||||
'message': f'No connected DNS provider manages {domain} — add this record manually.'}
|
||||
res = cls.set_record(config.id, zone['id'], 'A', domain, ip)
|
||||
if res.get('success'):
|
||||
return {'created': True, 'provider': config.name, 'zone': zone.get('name'), 'record': record}
|
||||
return {'created': False, 'reason': 'api_error', 'error': res.get('error'),
|
||||
'provider': config.name, 'record': record}
|
||||
|
||||
# ── Cloudflare Implementation ──
|
||||
|
||||
@classmethod
|
||||
@@ -159,11 +261,11 @@ class DNSProviderService:
|
||||
if config.api_email:
|
||||
return {
|
||||
'X-Auth-Email': config.api_email,
|
||||
'X-Auth-Key': config.api_key,
|
||||
'X-Auth-Key': cls._api_key(config),
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
return {
|
||||
'Authorization': f'Bearer {config.api_key}',
|
||||
'Authorization': f'Bearer {cls._api_key(config)}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
@@ -262,6 +364,23 @@ class DNSProviderService:
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@staticmethod
|
||||
def _host_relative_to_zone(name: str, zone: str) -> str:
|
||||
"""Compute a record host relative to its zone (``@`` for the apex).
|
||||
|
||||
``name`` is a FQDN (e.g. ``mail.example.com``), ``zone`` the managing
|
||||
zone (e.g. ``example.com``); returns ``mail`` here, or ``@`` when the
|
||||
name *is* the apex. Used by DigitalOcean/GoDaddy which address records
|
||||
by zone + host rather than by FQDN.
|
||||
"""
|
||||
name = (name or '').strip().lower().rstrip('.')
|
||||
zone = (zone or '').strip().lower().rstrip('.')
|
||||
if not zone or name == zone:
|
||||
return '@'
|
||||
if name.endswith('.' + zone):
|
||||
return name[: -len(zone) - 1]
|
||||
return name or '@'
|
||||
|
||||
# ── Route53 Implementation ──
|
||||
|
||||
@classmethod
|
||||
@@ -274,8 +393,8 @@ class DNSProviderService:
|
||||
|
||||
return boto3.client(
|
||||
'route53',
|
||||
aws_access_key_id=config.api_key,
|
||||
aws_secret_access_key=config.api_secret,
|
||||
aws_access_key_id=cls._api_key(config),
|
||||
aws_secret_access_key=cls._api_secret(config),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -374,3 +493,203 @@ class DNSProviderService:
|
||||
return {'success': True, 'message': f'{record_type} record deleted for {name}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
# ── DigitalOcean Implementation ──
|
||||
|
||||
@classmethod
|
||||
def _digitalocean_headers(cls, config: DNSProviderConfig) -> Dict:
|
||||
"""Build DigitalOcean API headers (single-token auth)."""
|
||||
return {
|
||||
'Authorization': f'Bearer {cls._api_key(config)}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _test_digitalocean(cls, config: DNSProviderConfig) -> Dict:
|
||||
"""Test DigitalOcean API connection."""
|
||||
try:
|
||||
resp = requests.get(
|
||||
'https://api.digitalocean.com/v2/domains?per_page=1',
|
||||
headers=cls._digitalocean_headers(config),
|
||||
timeout=15,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
return {'success': True, 'message': 'DigitalOcean connection successful'}
|
||||
data = resp.json()
|
||||
return {'success': False, 'error': data.get('message', f'HTTP {resp.status_code}')}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _digitalocean_list_zones(cls, config: DNSProviderConfig) -> Dict:
|
||||
"""List DigitalOcean domains as zones (zone id == domain name)."""
|
||||
try:
|
||||
resp = requests.get(
|
||||
'https://api.digitalocean.com/v2/domains?per_page=200',
|
||||
headers=cls._digitalocean_headers(config),
|
||||
timeout=15,
|
||||
)
|
||||
data = resp.json()
|
||||
if resp.status_code != 200:
|
||||
return {'success': False, 'error': data.get('message', 'Failed to list zones')}
|
||||
zones = [{'id': d['name'], 'name': d['name'], 'status': 'active'}
|
||||
for d in data.get('domains', [])]
|
||||
return {'success': True, 'zones': zones}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _digitalocean_set_record(cls, config: DNSProviderConfig, zone_id: str,
|
||||
record_type: str, name: str, value: str, ttl: int) -> Dict:
|
||||
"""Create or update a DigitalOcean DNS record (zone_id is the domain)."""
|
||||
try:
|
||||
headers = cls._digitalocean_headers(config)
|
||||
base = f'https://api.digitalocean.com/v2/domains/{zone_id}/records'
|
||||
host = cls._host_relative_to_zone(name, zone_id)
|
||||
|
||||
payload = {'type': record_type, 'name': host, 'data': value, 'ttl': ttl}
|
||||
if record_type == 'MX':
|
||||
# Input is "<priority> <target>"; split into priority + data.
|
||||
parts = value.split(None, 1)
|
||||
if len(parts) == 2 and parts[0].isdigit():
|
||||
payload['priority'] = int(parts[0])
|
||||
payload['data'] = parts[1]
|
||||
|
||||
# Find an existing record of the same type/host to update.
|
||||
resp = requests.get(
|
||||
f'{base}?type={record_type}&per_page=200',
|
||||
headers=headers, timeout=15,
|
||||
)
|
||||
data = resp.json()
|
||||
existing = [r for r in data.get('domain_records', []) if r.get('name') == host]
|
||||
|
||||
if existing:
|
||||
record_id = existing[0]['id']
|
||||
resp = requests.put(
|
||||
f'{base}/{record_id}',
|
||||
headers=headers, json=payload, timeout=15,
|
||||
)
|
||||
else:
|
||||
resp = requests.post(base, headers=headers, json=payload, timeout=15)
|
||||
|
||||
if resp.status_code in (200, 201):
|
||||
return {'success': True, 'message': f'{record_type} record set for {name}'}
|
||||
data = resp.json()
|
||||
return {'success': False, 'error': data.get('message', f'HTTP {resp.status_code}')}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _digitalocean_delete_record(cls, config: DNSProviderConfig, zone_id: str,
|
||||
record_type: str, name: str) -> Dict:
|
||||
"""Delete a DigitalOcean DNS record (zone_id is the domain)."""
|
||||
try:
|
||||
headers = cls._digitalocean_headers(config)
|
||||
base = f'https://api.digitalocean.com/v2/domains/{zone_id}/records'
|
||||
host = cls._host_relative_to_zone(name, zone_id)
|
||||
|
||||
resp = requests.get(
|
||||
f'{base}?type={record_type}&per_page=200',
|
||||
headers=headers, timeout=15,
|
||||
)
|
||||
data = resp.json()
|
||||
existing = [r for r in data.get('domain_records', []) if r.get('name') == host]
|
||||
|
||||
if not existing:
|
||||
return {'success': True, 'message': 'Record not found (already deleted)'}
|
||||
|
||||
for record in existing:
|
||||
requests.delete(f'{base}/{record["id"]}', headers=headers, timeout=15)
|
||||
|
||||
return {'success': True, 'message': f'{record_type} record deleted for {name}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
# ── GoDaddy Implementation ──
|
||||
|
||||
@classmethod
|
||||
def _godaddy_headers(cls, config: DNSProviderConfig) -> Dict:
|
||||
"""Build GoDaddy API headers (key+secret auth)."""
|
||||
return {
|
||||
'Authorization': f'sso-key {cls._api_key(config)}:{cls._api_secret(config)}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _test_godaddy(cls, config: DNSProviderConfig) -> Dict:
|
||||
"""Test GoDaddy API connection."""
|
||||
try:
|
||||
resp = requests.get(
|
||||
'https://api.godaddy.com/v1/domains?limit=1',
|
||||
headers=cls._godaddy_headers(config),
|
||||
timeout=15,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
return {'success': True, 'message': 'GoDaddy connection successful'}
|
||||
data = resp.json()
|
||||
return {'success': False, 'error': data.get('message', f'HTTP {resp.status_code}')}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _godaddy_list_zones(cls, config: DNSProviderConfig) -> Dict:
|
||||
"""List GoDaddy domains as zones (zone id == domain name)."""
|
||||
try:
|
||||
resp = requests.get(
|
||||
'https://api.godaddy.com/v1/domains',
|
||||
headers=cls._godaddy_headers(config),
|
||||
timeout=15,
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
data = resp.json()
|
||||
return {'success': False, 'error': data.get('message', 'Failed to list zones')}
|
||||
zones = [{'id': d['domain'], 'name': d['domain'],
|
||||
'status': d.get('status', 'active')}
|
||||
for d in resp.json()]
|
||||
return {'success': True, 'zones': zones}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _godaddy_set_record(cls, config: DNSProviderConfig, zone_id: str,
|
||||
record_type: str, name: str, value: str, ttl: int) -> Dict:
|
||||
"""Create or update a GoDaddy DNS record (record-typed PUT, zone_id is the domain)."""
|
||||
try:
|
||||
headers = cls._godaddy_headers(config)
|
||||
host = cls._host_relative_to_zone(name, zone_id)
|
||||
url = f'https://api.godaddy.com/v1/domains/{zone_id}/records/{record_type}/{host}'
|
||||
|
||||
record = {'data': value, 'ttl': ttl}
|
||||
if record_type == 'MX':
|
||||
# Input is "<priority> <target>"; GoDaddy wants priority + data.
|
||||
parts = value.split(None, 1)
|
||||
if len(parts) == 2 and parts[0].isdigit():
|
||||
record['priority'] = int(parts[0])
|
||||
record['data'] = parts[1]
|
||||
|
||||
resp = requests.put(url, headers=headers, json=[record], timeout=15)
|
||||
if resp.status_code in (200, 201):
|
||||
return {'success': True, 'message': f'{record_type} record set for {name}'}
|
||||
data = resp.json()
|
||||
return {'success': False, 'error': data.get('message', f'HTTP {resp.status_code}')}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _godaddy_delete_record(cls, config: DNSProviderConfig, zone_id: str,
|
||||
record_type: str, name: str) -> Dict:
|
||||
"""Delete a GoDaddy DNS record (record-typed DELETE, zone_id is the domain)."""
|
||||
try:
|
||||
headers = cls._godaddy_headers(config)
|
||||
host = cls._host_relative_to_zone(name, zone_id)
|
||||
url = f'https://api.godaddy.com/v1/domains/{zone_id}/records/{record_type}/{host}'
|
||||
|
||||
resp = requests.delete(url, headers=headers, timeout=15)
|
||||
if resp.status_code in (200, 204):
|
||||
return {'success': True, 'message': f'{record_type} record deleted for {name}'}
|
||||
if resp.status_code == 404:
|
||||
return {'success': True, 'message': 'Record not found (already deleted)'}
|
||||
data = resp.json()
|
||||
return {'success': False, 'error': data.get('message', f'HTTP {resp.status_code}')}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Outbound SMTP relay (smarthost) for the mail server.
|
||||
|
||||
Persists a single relay configuration (host/port/credentials, password
|
||||
Fernet-encrypted) and applies it to Postfix when present. The config is stored
|
||||
platform-agnostically so the dev panel can hold it; the Postfix apply is a no-op
|
||||
(with a note) on hosts where Postfix isn't installed. `test()` opens a real SMTP
|
||||
connection so credentials are validated on any OS.
|
||||
"""
|
||||
|
||||
import ssl
|
||||
import smtplib
|
||||
import logging
|
||||
|
||||
from app import db
|
||||
from app.models.email import EmailRelayConfig
|
||||
from app.services.postfix_service import PostfixService
|
||||
from app.utils.crypto import encrypt_secret, decrypt_secret
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _is_masked(value):
|
||||
"""True for our masking sentinels, so a round-tripped masked value never
|
||||
overwrites the stored secret."""
|
||||
if not value:
|
||||
return False
|
||||
return value.startswith('****') or set(value) == {'*'}
|
||||
|
||||
|
||||
class EmailRelayService:
|
||||
DEFAULT = {
|
||||
'enabled': False, 'host': '', 'port': 587, 'username': '',
|
||||
'use_tls': True, 'provider_hint': None, 'password_set': False,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _row():
|
||||
return EmailRelayConfig.query.first()
|
||||
|
||||
@classmethod
|
||||
def get_config(cls):
|
||||
row = cls._row()
|
||||
return row.to_dict() if row else dict(cls.DEFAULT)
|
||||
|
||||
@classmethod
|
||||
def save_config(cls, data):
|
||||
row = cls._row() or EmailRelayConfig()
|
||||
row.host = (data.get('host') or '').strip()
|
||||
try:
|
||||
row.port = int(data.get('port') or 587)
|
||||
except (TypeError, ValueError):
|
||||
row.port = 587
|
||||
row.username = (data.get('username') or '').strip()
|
||||
row.use_tls = bool(data.get('use_tls', True))
|
||||
row.enabled = bool(data.get('enabled', True))
|
||||
row.provider_hint = data.get('provider_hint')
|
||||
pw = data.get('password')
|
||||
if pw and not _is_masked(pw):
|
||||
row.password_encrypted = encrypt_secret(pw)
|
||||
if row.id is None:
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
return {'config': row.to_dict(), 'apply': cls.apply(row)}
|
||||
|
||||
@classmethod
|
||||
def apply(cls, row=None):
|
||||
"""Push the stored config to Postfix (if installed)."""
|
||||
row = row or cls._row()
|
||||
if not row:
|
||||
return {'applied': False, 'note': 'No relay configured'}
|
||||
status = PostfixService.get_status()
|
||||
if not status.get('installed'):
|
||||
return {'applied': False, 'note': 'Saved. Postfix is not installed here — the relay applies on a configured mail server.'}
|
||||
if row.enabled and row.host:
|
||||
password = decrypt_secret(row.password_encrypted) if row.password_encrypted else ''
|
||||
result = PostfixService.configure_relay(row.host, row.port, row.username, password, row.use_tls)
|
||||
else:
|
||||
result = PostfixService.disable_relay()
|
||||
result['applied'] = result.get('success', False)
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def disable(cls):
|
||||
row = cls._row()
|
||||
if row:
|
||||
row.enabled = False
|
||||
db.session.commit()
|
||||
return cls.apply(row)
|
||||
|
||||
@classmethod
|
||||
def test(cls, data):
|
||||
"""Open a real SMTP connection to validate host/port/credentials."""
|
||||
row = cls._row()
|
||||
host = (data.get('host') or (row.host if row else '') or '').strip()
|
||||
if not host:
|
||||
return {'success': False, 'error': 'A relay host is required'}
|
||||
try:
|
||||
port = int(data.get('port') or (row.port if row else 587))
|
||||
except (TypeError, ValueError):
|
||||
port = 587
|
||||
username = data.get('username') or (row.username if row else '')
|
||||
use_tls = data.get('use_tls', row.use_tls if row else True)
|
||||
password = data.get('password')
|
||||
if password and _is_masked(password):
|
||||
password = None
|
||||
if not password and row and row.password_encrypted:
|
||||
password = decrypt_secret(row.password_encrypted)
|
||||
|
||||
try:
|
||||
if port == 465:
|
||||
server = smtplib.SMTP_SSL(host, port, timeout=15)
|
||||
else:
|
||||
server = smtplib.SMTP(host, port, timeout=15)
|
||||
server.ehlo()
|
||||
if use_tls:
|
||||
server.starttls(context=ssl.create_default_context())
|
||||
server.ehlo()
|
||||
if username:
|
||||
server.login(username, password or '')
|
||||
server.quit()
|
||||
return {'success': True, 'message': f'Connected to {host}:{port}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
@@ -151,6 +151,36 @@ class NginxService:
|
||||
proxy_send_timeout 60;
|
||||
}}
|
||||
}}
|
||||
'''
|
||||
|
||||
# Reverse proxy to a service reached over a WireGuard tunnel (roadmap
|
||||
# #12). The upstream is a peer's WG IP:port; the private agent forwards
|
||||
# it to the real service. proxy_buffering off keeps media/streaming
|
||||
# (e.g. Jellyfin) responsive.
|
||||
REMOTE_UPSTREAM_TEMPLATE = '''server {{
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name {domains};
|
||||
|
||||
access_log /var/log/nginx/{name}.access.log;
|
||||
error_log /var/log/nginx/{name}.error.log;
|
||||
|
||||
location / {{
|
||||
proxy_pass http://{upstream};
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 86400;
|
||||
proxy_connect_timeout 60;
|
||||
proxy_send_timeout 60;
|
||||
}}
|
||||
}}
|
||||
'''
|
||||
|
||||
SSL_BLOCK = '''
|
||||
@@ -389,8 +419,15 @@ location /p/ {{
|
||||
|
||||
@classmethod
|
||||
def create_site(cls, name: str, app_type: str, domains: List[str],
|
||||
root_path: str, port: int = None, php_version: str = '8.2') -> Dict:
|
||||
"""Create a new site configuration."""
|
||||
root_path: str, port: int = None, php_version: str = '8.2',
|
||||
ssl_cert: str = None, ssl_key: str = None,
|
||||
upstream: str = None) -> Dict:
|
||||
"""Create a new site configuration.
|
||||
|
||||
When ``ssl_cert``/``ssl_key`` are given the generated vhost serves HTTPS
|
||||
(443) from that cert with an HTTP->HTTPS redirect — used to point managed
|
||||
subdomains at the base-domain wildcard cert.
|
||||
"""
|
||||
if not domains:
|
||||
return {'success': False, 'error': 'At least one domain is required'}
|
||||
|
||||
@@ -432,6 +469,14 @@ location /p/ {{
|
||||
domains=domains_str,
|
||||
port=port
|
||||
)
|
||||
elif app_type == 'remote':
|
||||
if not upstream:
|
||||
return {'success': False, 'error': 'upstream (host:port) is required for remote apps'}
|
||||
config = cls.REMOTE_UPSTREAM_TEMPLATE.format(
|
||||
name=name,
|
||||
domains=domains_str,
|
||||
upstream=upstream,
|
||||
)
|
||||
elif app_type == 'static':
|
||||
config = cls.STATIC_SITE_TEMPLATE.format(
|
||||
name=name,
|
||||
@@ -441,6 +486,9 @@ location /p/ {{
|
||||
else:
|
||||
return {'success': False, 'error': f'Unknown app type: {app_type}'}
|
||||
|
||||
if ssl_cert and ssl_key:
|
||||
config = cls._with_ssl(config, domains_str, ssl_cert, ssl_key)
|
||||
|
||||
# Write config file
|
||||
config_path = os.path.join(cls.SITES_AVAILABLE, name)
|
||||
try:
|
||||
@@ -456,6 +504,20 @@ location /p/ {{
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _with_ssl(cls, http_config: str, domains: str, ssl_cert: str, ssl_key: str) -> str:
|
||||
"""Turn an HTTP server block into HTTPS: swap the :80 listens for the TLS
|
||||
block (so the existing server serves 443) and prepend an HTTP->HTTPS
|
||||
redirect. Idempotent because create_site regenerates the whole file."""
|
||||
ssl_block = cls.SSL_BLOCK.format(ssl_cert=ssl_cert, ssl_key=ssl_key)
|
||||
https_config = http_config.replace(
|
||||
' listen 80;\n listen [::]:80;',
|
||||
ssl_block.strip('\n'),
|
||||
1,
|
||||
)
|
||||
redirect = cls.SSL_REDIRECT_TEMPLATE.format(domains=domains)
|
||||
return redirect + '\n' + https_config
|
||||
|
||||
@classmethod
|
||||
def enable_site(cls, name: str) -> Dict:
|
||||
"""Enable a site by creating symlink in sites-enabled."""
|
||||
|
||||
@@ -388,3 +388,42 @@ mailbox_size_limit = 0
|
||||
return {'success': False, 'error': result.stderr or 'Restart failed'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
POSTFIX_SASL_PASSWD = '/etc/postfix/sasl_passwd'
|
||||
|
||||
@classmethod
|
||||
def configure_relay(cls, host: str, port: int = 587, username: str = None,
|
||||
password: str = None, use_tls: bool = True) -> Dict:
|
||||
"""Route outbound mail through an external SMTP smarthost (relayhost).
|
||||
|
||||
Sets relayhost + SASL auth in main.cf and writes the credential map. Linux
|
||||
/ Postfix only — the caller persists the config regardless of platform.
|
||||
"""
|
||||
try:
|
||||
relay = f'[{host}]:{port}'
|
||||
run_privileged(['postconf', '-e', f'relayhost={relay}'])
|
||||
if username:
|
||||
run_privileged(['postconf', '-e', 'smtp_sasl_auth_enable=yes'])
|
||||
run_privileged(['postconf', '-e', f'smtp_sasl_password_maps=hash:{cls.POSTFIX_SASL_PASSWD}'])
|
||||
run_privileged(['postconf', '-e', 'smtp_sasl_security_options=noanonymous'])
|
||||
run_privileged(['tee', cls.POSTFIX_SASL_PASSWD], input=f'{relay} {username}:{password or ""}\n')
|
||||
run_privileged(['chmod', '600', cls.POSTFIX_SASL_PASSWD])
|
||||
run_privileged(['postmap', cls.POSTFIX_SASL_PASSWD])
|
||||
run_privileged(['postconf', '-e', f'smtp_tls_security_level={"encrypt" if use_tls else "may"}'])
|
||||
run_privileged(['postfix', 'reload'])
|
||||
return {'success': True, 'message': f'Relaying outbound mail through {relay}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def disable_relay(cls) -> Dict:
|
||||
"""Stop relaying through a smarthost (revert to direct delivery)."""
|
||||
try:
|
||||
run_privileged(['postconf', '-e', 'relayhost='])
|
||||
run_privileged(['postconf', '-e', 'smtp_sasl_auth_enable=no'])
|
||||
run_privileged(['postconf', '-e', 'smtp_sasl_password_maps='])
|
||||
run_privileged(['rm', '-f', cls.POSTFIX_SASL_PASSWD, cls.POSTFIX_SASL_PASSWD + '.db'], check=False)
|
||||
run_privileged(['postfix', 'reload'])
|
||||
return {'success': True, 'message': 'Outbound relay disabled'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
@@ -0,0 +1,354 @@
|
||||
"""Domain-registrar portfolio service.
|
||||
|
||||
Connects to registrar APIs (GoDaddy today; Namecheap is a planned addition) to
|
||||
answer the question "what domains do I own and when do they expire?" — the data
|
||||
that powers the Connections → Registrars cards and the Domains-page portfolio.
|
||||
|
||||
Credentials live on RegistrarConnection rows, Fernet-encrypted. The public
|
||||
methods return plain dicts so the API layer can jsonify them directly.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models.registrar_connection import RegistrarConnection
|
||||
from app.utils.crypto import encrypt_secret, decrypt_secret
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RegistrarService:
|
||||
# Only providers we can fully read are listed here; the connect form is
|
||||
# gated on this. Namecheap (XML API + IP allow-listing) is intentionally
|
||||
# left out until implemented, and shown as "coming soon" in the catalog.
|
||||
SUPPORTED = {
|
||||
'godaddy': {'name': 'GoDaddy', 'fields': ['api_key', 'api_secret']},
|
||||
'namecheap': {'name': 'Namecheap', 'fields': ['api_key', 'username', 'client_ip']},
|
||||
}
|
||||
|
||||
GODADDY_BASE = 'https://api.godaddy.com/v1'
|
||||
NAMECHEAP_BASE = 'https://api.namecheap.com/xml.response'
|
||||
NAMECHEAP_NS = {'nc': 'http://api.namecheap.com/xml.response'}
|
||||
|
||||
# Days-before-expiry thresholds that trigger a (de-duped) notification.
|
||||
EXPIRY_THRESHOLDS = [30, 14, 7, 1]
|
||||
|
||||
# --- Connections (CRUD) ---
|
||||
|
||||
@staticmethod
|
||||
def list_connections():
|
||||
return RegistrarConnection.query.order_by(RegistrarConnection.created_at.desc()).all()
|
||||
|
||||
@staticmethod
|
||||
def get_connection(cid):
|
||||
return RegistrarConnection.query.get(cid)
|
||||
|
||||
@classmethod
|
||||
def add_connection(cls, data, user_id=None):
|
||||
provider = (data.get('provider') or '').lower().strip()
|
||||
if provider not in cls.SUPPORTED:
|
||||
raise ValueError(f'Unsupported registrar: {provider or "(none)"}')
|
||||
api_key = (data.get('api_key') or '').strip()
|
||||
if not api_key:
|
||||
raise ValueError('api_key is required')
|
||||
|
||||
conn = RegistrarConnection(
|
||||
provider=provider,
|
||||
name=(data.get('name') or '').strip() or cls.SUPPORTED[provider]['name'],
|
||||
api_key_encrypted=encrypt_secret(api_key),
|
||||
user_id=user_id,
|
||||
)
|
||||
if provider == 'godaddy':
|
||||
api_secret = (data.get('api_secret') or '').strip()
|
||||
if not api_secret:
|
||||
raise ValueError('api_secret is required')
|
||||
conn.api_secret_encrypted = encrypt_secret(api_secret)
|
||||
elif provider == 'namecheap':
|
||||
username = (data.get('username') or '').strip()
|
||||
client_ip = (data.get('client_ip') or '').strip()
|
||||
if not username or not client_ip:
|
||||
raise ValueError('username and client_ip are required')
|
||||
conn.config = {'username': username, 'client_ip': client_ip}
|
||||
|
||||
db.session.add(conn)
|
||||
db.session.commit()
|
||||
return conn
|
||||
|
||||
@staticmethod
|
||||
def delete_connection(cid):
|
||||
conn = RegistrarConnection.query.get(cid)
|
||||
if not conn:
|
||||
return False
|
||||
db.session.delete(conn)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _creds(conn):
|
||||
return decrypt_secret(conn.api_key_encrypted), decrypt_secret(conn.api_secret_encrypted)
|
||||
|
||||
@staticmethod
|
||||
def _api_key(conn):
|
||||
return decrypt_secret(conn.api_key_encrypted) if conn.api_key_encrypted else ''
|
||||
|
||||
# --- GoDaddy ---
|
||||
|
||||
@classmethod
|
||||
def _godaddy_headers(cls, conn):
|
||||
key, secret = cls._creds(conn)
|
||||
return {'Authorization': f'sso-key {key}:{secret}', 'Accept': 'application/json'}
|
||||
|
||||
@classmethod
|
||||
def _godaddy_list_domains(cls, conn):
|
||||
resp = requests.get(
|
||||
f'{cls.GODADDY_BASE}/domains',
|
||||
params={'limit': 1000, 'statuses': 'ACTIVE'},
|
||||
headers=cls._godaddy_headers(conn),
|
||||
timeout=20,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
rows = resp.json() if isinstance(resp.json(), list) else []
|
||||
return [
|
||||
cls._normalize_domain(conn, {
|
||||
'domain': d.get('domain'),
|
||||
'status': d.get('status'),
|
||||
'expires': d.get('expires'),
|
||||
'auto_renew': d.get('renewAuto'),
|
||||
'locked': d.get('locked'),
|
||||
'nameservers': d.get('nameServers'),
|
||||
'created': d.get('createdAt'),
|
||||
})
|
||||
for d in rows
|
||||
]
|
||||
|
||||
# --- Namecheap (XML API; the calling server IP must be allow-listed) ---
|
||||
|
||||
@classmethod
|
||||
def _namecheap_params(cls, conn, command):
|
||||
cfg = conn.config
|
||||
return {
|
||||
'ApiUser': cfg.get('username', ''),
|
||||
'ApiKey': cls._api_key(conn),
|
||||
'UserName': cfg.get('username', ''),
|
||||
'ClientIp': cfg.get('client_ip', ''),
|
||||
'Command': command,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _namecheap_date(value):
|
||||
# Namecheap returns "MM/DD/YYYY"; normalize to ISO "YYYY-MM-DD".
|
||||
try:
|
||||
m, d, y = (value or '').split('/')
|
||||
return f'{int(y):04d}-{int(m):02d}-{int(d):02d}'
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _namecheap_test(cls, conn):
|
||||
import xml.etree.ElementTree as ET
|
||||
try:
|
||||
params = cls._namecheap_params(conn, 'namecheap.domains.getList')
|
||||
params['PageSize'] = 1
|
||||
resp = requests.get(cls.NAMECHEAP_BASE, params=params, timeout=15)
|
||||
root = ET.fromstring(resp.text)
|
||||
if root.get('Status') == 'OK':
|
||||
return {'success': True, 'message': 'Namecheap connection works'}
|
||||
err = root.find('.//nc:Error', cls.NAMECHEAP_NS)
|
||||
msg = (err.text if err is not None and err.text else
|
||||
'Check the API key, username, and that this server IP is allow-listed in Namecheap.')
|
||||
return {'success': False, 'error': msg}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _namecheap_list_domains(cls, conn):
|
||||
import xml.etree.ElementTree as ET
|
||||
params = cls._namecheap_params(conn, 'namecheap.domains.getList')
|
||||
params['PageSize'] = 100
|
||||
resp = requests.get(cls.NAMECHEAP_BASE, params=params, timeout=20)
|
||||
resp.raise_for_status()
|
||||
root = ET.fromstring(resp.text)
|
||||
if root.get('Status') != 'OK':
|
||||
err = root.find('.//nc:Error', cls.NAMECHEAP_NS)
|
||||
raise RuntimeError(err.text if err is not None and err.text else 'Namecheap API error')
|
||||
out = []
|
||||
for d in root.findall('.//nc:Domain', cls.NAMECHEAP_NS):
|
||||
out.append(cls._normalize_domain(conn, {
|
||||
'domain': d.get('Name'),
|
||||
'status': 'expired' if d.get('IsExpired') == 'true' else 'active',
|
||||
'expires': cls._namecheap_date(d.get('Expires')),
|
||||
'auto_renew': d.get('AutoRenew') == 'true',
|
||||
'locked': d.get('IsLocked') == 'true',
|
||||
'nameservers': None,
|
||||
}))
|
||||
return out
|
||||
|
||||
# --- Public capability methods ---
|
||||
|
||||
@classmethod
|
||||
def test_connection(cls, conn):
|
||||
try:
|
||||
if conn.provider == 'godaddy':
|
||||
resp = requests.get(
|
||||
f'{cls.GODADDY_BASE}/domains', params={'limit': 1},
|
||||
headers=cls._godaddy_headers(conn), timeout=15,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
return {'success': True, 'message': 'GoDaddy connection works'}
|
||||
if resp.status_code in (401, 403):
|
||||
return {'success': False, 'error': 'Access denied — check the API key/secret (must be a Production key, not OTE).'}
|
||||
return {'success': False, 'error': f'GoDaddy returned HTTP {resp.status_code}'}
|
||||
if conn.provider == 'namecheap':
|
||||
return cls._namecheap_test(conn)
|
||||
return {'success': False, 'error': f'Unsupported registrar: {conn.provider}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def list_domains(cls, conn):
|
||||
if conn.provider == 'godaddy':
|
||||
return cls._godaddy_list_domains(conn)
|
||||
if conn.provider == 'namecheap':
|
||||
return cls._namecheap_list_domains(conn)
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def list_all_domains(cls):
|
||||
"""Aggregate every domain across all connected registrars, soonest-to-expire first."""
|
||||
domains = []
|
||||
for conn in cls.list_connections():
|
||||
try:
|
||||
domains.extend(cls.list_domains(conn))
|
||||
except Exception as e:
|
||||
logger.warning(f'Registrar {conn.id} ({conn.provider}) domain list failed: {e}')
|
||||
domains.sort(key=lambda d: (d.get('days_until_expiry') is None, d.get('days_until_expiry') if d.get('days_until_expiry') is not None else 0))
|
||||
return domains
|
||||
|
||||
@classmethod
|
||||
def sync_now(cls):
|
||||
"""Refresh the portfolio and stamp last_synced_at on every connection."""
|
||||
domains = cls.list_all_domains()
|
||||
now = datetime.utcnow()
|
||||
conns = cls.list_connections()
|
||||
for conn in conns:
|
||||
conn.last_synced_at = now
|
||||
# Surface the per-account domain count as the card subtitle.
|
||||
count = sum(1 for d in domains if d.get('connection_id') == conn.id)
|
||||
conn.account_label = f'{count} domain' + ('' if count == 1 else 's')
|
||||
db.session.commit()
|
||||
return domains
|
||||
|
||||
# --- Expiry notifications ---
|
||||
|
||||
@classmethod
|
||||
def _bucket(cls, days):
|
||||
"""Most-urgent threshold a domain has crossed → (rank, label). Higher rank
|
||||
is more urgent; rank 0 means "outside every threshold" (no alert)."""
|
||||
if days is None:
|
||||
return 0, None
|
||||
if days <= 0:
|
||||
return len(cls.EXPIRY_THRESHOLDS) + 1, 'expired'
|
||||
for i, t in enumerate(sorted(cls.EXPIRY_THRESHOLDS)): # ascending: [1,7,14,30]
|
||||
if days <= t:
|
||||
return len(cls.EXPIRY_THRESHOLDS) - i, str(t)
|
||||
return 0, None
|
||||
|
||||
@classmethod
|
||||
def _alert_state_path(cls):
|
||||
import os
|
||||
from app import paths
|
||||
return os.path.join(paths.SERVERKIT_CONFIG_DIR, 'registrar_alerts.json')
|
||||
|
||||
@classmethod
|
||||
def notify_expiring(cls):
|
||||
"""Send a notification when a domain crosses an expiry threshold
|
||||
(30/14/7/1 days, or expired). De-duped via a small state file so each
|
||||
crossing notifies once and only escalations re-fire. Returns the number
|
||||
of alerts sent."""
|
||||
import os
|
||||
import json
|
||||
from app import paths
|
||||
|
||||
domains = cls.list_all_domains()
|
||||
if not domains:
|
||||
return 0
|
||||
|
||||
state_path = cls._alert_state_path()
|
||||
state = {}
|
||||
if os.path.exists(state_path):
|
||||
try:
|
||||
with open(state_path) as f:
|
||||
state = json.load(f)
|
||||
except Exception:
|
||||
state = {}
|
||||
|
||||
alerts = []
|
||||
new_state = {}
|
||||
for d in domains:
|
||||
name = d.get('domain')
|
||||
if not name:
|
||||
continue
|
||||
rank, label = cls._bucket(d.get('days_until_expiry'))
|
||||
if rank == 0:
|
||||
continue # outside every threshold — and dropped from state below
|
||||
new_state[name] = rank
|
||||
if rank > state.get(name, 0): # escalated into a new, more-urgent bucket
|
||||
days = d.get('days_until_expiry')
|
||||
who = d.get('registrar_name') or d.get('registrar')
|
||||
if label == 'expired':
|
||||
severity, message = 'critical', f'Domain {name} has EXPIRED ({who}).'
|
||||
else:
|
||||
severity = 'critical' if label in ('1', '7') else 'warning'
|
||||
message = f"Domain {name} expires in {days} day{'' if days == 1 else 's'} ({who})."
|
||||
alerts.append({'type': 'domain_expiry', 'severity': severity,
|
||||
'message': message, 'value': name, 'threshold': label})
|
||||
|
||||
# Persist only domains still within a threshold; a renewed domain drops out
|
||||
# and will re-alert next time it approaches expiry.
|
||||
try:
|
||||
os.makedirs(paths.SERVERKIT_CONFIG_DIR, exist_ok=True)
|
||||
with open(state_path, 'w') as f:
|
||||
json.dump(new_state, f, indent=2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if alerts:
|
||||
try:
|
||||
from app.services.notification_service import NotificationService
|
||||
NotificationService.send_all(alerts)
|
||||
except Exception as e:
|
||||
logger.warning(f'Registrar expiry notify failed: {e}')
|
||||
return len(alerts)
|
||||
|
||||
# --- Helpers ---
|
||||
|
||||
@staticmethod
|
||||
def _normalize_domain(conn, d):
|
||||
expires_raw = d.get('expires')
|
||||
expires_at = None
|
||||
days = None
|
||||
if expires_raw:
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(expires_raw).replace('Z', '+00:00'))
|
||||
expires_at = dt
|
||||
if dt.tzinfo:
|
||||
days = (dt - datetime.now(timezone.utc)).days
|
||||
else:
|
||||
days = (dt - datetime.utcnow()).days
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
'domain': d.get('domain'),
|
||||
'registrar': conn.provider,
|
||||
'registrar_name': conn.name or conn.provider,
|
||||
'connection_id': conn.id,
|
||||
'status': d.get('status'),
|
||||
'expires_at': expires_at.isoformat() if expires_at else None,
|
||||
'days_until_expiry': days,
|
||||
'auto_renew': d.get('auto_renew'),
|
||||
'locked': d.get('locked'),
|
||||
'nameservers': d.get('nameservers') or [],
|
||||
}
|
||||
@@ -316,22 +316,17 @@ class ServerTemplateService:
|
||||
if not assignment:
|
||||
return None
|
||||
|
||||
assignment.status = ServerTemplateAssignment.STATUS_CHECKING
|
||||
# Agent-side config drift checking is NOT implemented (the agent has no
|
||||
# config_drift_check handler, and the old code dispatched to a
|
||||
# non-existent get_agent_gateway()). Report honestly instead of leaving
|
||||
# the assignment stuck in 'checking' forever.
|
||||
assignment.status = ServerTemplateAssignment.STATUS_UNKNOWN
|
||||
assignment.drift_report = {
|
||||
'error': 'Agent-side configuration drift checking is not implemented yet',
|
||||
}
|
||||
assignment.last_check_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
# Send drift check command to agent
|
||||
try:
|
||||
from app.agent_gateway import get_agent_gateway
|
||||
gw = get_agent_gateway()
|
||||
if gw and assignment.server:
|
||||
spec = assignment.template.get_merged_spec()
|
||||
gw.send_command(assignment.server.agent_id, 'config_drift_check', {
|
||||
'assignment_id': assignment.id,
|
||||
'spec': spec,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning(f'Could not send drift check command: {e}')
|
||||
|
||||
return assignment
|
||||
|
||||
@staticmethod
|
||||
@@ -359,21 +354,16 @@ class ServerTemplateService:
|
||||
if not assignment:
|
||||
return None
|
||||
|
||||
assignment.status = ServerTemplateAssignment.STATUS_REMEDIATING
|
||||
# Agent-side remediation is NOT implemented (no config_remediate handler;
|
||||
# old code dispatched to a non-existent get_agent_gateway()). Report
|
||||
# honestly instead of leaving the assignment stuck in 'remediating'.
|
||||
assignment.status = ServerTemplateAssignment.STATUS_UNKNOWN
|
||||
assignment.drift_report = {
|
||||
'error': 'Agent-side template remediation is not implemented yet',
|
||||
}
|
||||
assignment.last_remediation_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
from app.agent_gateway import get_agent_gateway
|
||||
gw = get_agent_gateway()
|
||||
if gw and assignment.server:
|
||||
spec = assignment.template.get_merged_spec()
|
||||
gw.send_command(assignment.server.agent_id, 'config_remediate', {
|
||||
'assignment_id': assignment.id,
|
||||
'spec': spec,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning(f'Could not send remediate command: {e}')
|
||||
|
||||
return assignment
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -43,6 +43,24 @@ class SettingsService:
|
||||
'type': 'integer',
|
||||
'description': 'Starting host port when auto-assigning ports to managed apps/sites (0 = use each template\'s own default). The scanner still skips ports already in use.'
|
||||
},
|
||||
# Managed-site routing & HTTPS (Phases 1/3/5). Base domain + server IP
|
||||
# drive subdomain publishing and auto-DNS; sites_https_enabled is set by
|
||||
# the wildcard-HTTPS setup, after which managed subdomains serve TLS.
|
||||
'sites_base_domain': {
|
||||
'value': '',
|
||||
'type': 'string',
|
||||
'description': 'Base domain for managed sites — each is published at <slug>.<base_domain>. Point a wildcard DNS record (*.<base_domain>) at this server.'
|
||||
},
|
||||
'server_public_ip': {
|
||||
'value': '',
|
||||
'type': 'string',
|
||||
'description': 'Public IP of this server, used to auto-create DNS A records for managed domains.'
|
||||
},
|
||||
'sites_https_enabled': {
|
||||
'value': False,
|
||||
'type': 'boolean',
|
||||
'description': 'Whether the wildcard certificate for the sites base domain is set up; managed subdomains serve HTTPS when true.'
|
||||
},
|
||||
# SSO / OAuth settings
|
||||
'sso_google_enabled': {'value': False, 'type': 'boolean', 'description': 'Enable Google OAuth login'},
|
||||
'sso_google_client_id': {'value': '', 'type': 'string', 'description': 'Google OAuth client ID'},
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Resolve the public address of a managed site.
|
||||
|
||||
A bare published port (``127.0.0.1:8300``) is reachable on the box but is
|
||||
useless as a public website URL. Instead every managed site is given a real
|
||||
hostname ``<slug>.<base_domain>`` and the operator points a single wildcard DNS
|
||||
record (``*.<base_domain>``) at the server — so a new site is reachable the
|
||||
moment it is created, with no per-site DNS work.
|
||||
|
||||
The base domain is a one-time operator setting (``system_settings`` key
|
||||
``sites_base_domain``), falling back to ``SITES_BASE_DOMAIN`` in config. In
|
||||
development that defaults to ``lvh.me``, a public resolver that maps
|
||||
``*.lvh.me -> 127.0.0.1``, so subdomain routing can be exercised locally with
|
||||
zero DNS setup. When no base domain is configured the helpers return ``None``
|
||||
and callers fall back to the legacy ``localhost:<port>`` behaviour.
|
||||
"""
|
||||
import re
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models.system_settings import SystemSettings
|
||||
|
||||
|
||||
class SiteDomainService:
|
||||
DEFAULT_BASE_DOMAIN = 'lvh.me'
|
||||
|
||||
@classmethod
|
||||
def base_domain(cls):
|
||||
"""The configured base domain, or '' when site routing is not set up.
|
||||
|
||||
Prefers the runtime setting (editable in-app) over the config default so
|
||||
an operator can change it without redeploying.
|
||||
"""
|
||||
val = SystemSettings.get('sites_base_domain')
|
||||
if val:
|
||||
return str(val).strip().lstrip('.').lower()
|
||||
return (current_app.config.get('SITES_BASE_DOMAIN') or '').strip().lstrip('.').lower()
|
||||
|
||||
@classmethod
|
||||
def server_ip(cls):
|
||||
"""Public IP that wildcard/custom A-records should point at (Phase 3)."""
|
||||
return SystemSettings.get('server_public_ip') or current_app.config.get('SERVER_PUBLIC_IP') or None
|
||||
|
||||
@classmethod
|
||||
def https_enabled(cls):
|
||||
"""True once the wildcard certificate for the base domain is set up, so
|
||||
managed subdomains should be served over HTTPS (Phase 5)."""
|
||||
return bool(SystemSettings.get('sites_https_enabled', False))
|
||||
|
||||
@classmethod
|
||||
def wildcard_cert_paths(cls):
|
||||
"""(fullchain, privkey) paths for the base domain's wildcard cert, or
|
||||
(None, None) when no base domain is configured."""
|
||||
base = cls.base_domain()
|
||||
if not base:
|
||||
return (None, None)
|
||||
return (f'/etc/letsencrypt/live/{base}/fullchain.pem',
|
||||
f'/etc/letsencrypt/live/{base}/privkey.pem')
|
||||
|
||||
@classmethod
|
||||
def covers(cls, host):
|
||||
"""Whether the base domain's wildcard cert covers ``host`` — i.e. host is
|
||||
the base domain or a direct subdomain of it."""
|
||||
base = cls.base_domain()
|
||||
if not base or not host:
|
||||
return False
|
||||
return host == base or host.endswith('.' + base)
|
||||
|
||||
@staticmethod
|
||||
def slugify(name):
|
||||
"""Turn a site name into a DNS-safe label (a-z, 0-9, single dashes)."""
|
||||
s = (name or '').strip().lower()
|
||||
s = re.sub(r'[^a-z0-9-]', '-', s)
|
||||
s = re.sub(r'-+', '-', s).strip('-')
|
||||
return s or 'site'
|
||||
|
||||
@classmethod
|
||||
def subdomain_for(cls, name):
|
||||
"""``<slug>.<base_domain>`` for a site name, or ``None`` when no base
|
||||
domain is configured (site routing disabled)."""
|
||||
base = cls.base_domain()
|
||||
if not base:
|
||||
return None
|
||||
return f'{cls.slugify(name)}.{base}'
|
||||
|
||||
@classmethod
|
||||
def site_url(cls, host, ssl=False):
|
||||
"""Canonical URL for a host. HTTP for now; the wildcard-cert phase flips
|
||||
managed subdomains to HTTPS."""
|
||||
scheme = 'https' if ssl else 'http'
|
||||
return f'{scheme}://{host}'
|
||||
@@ -0,0 +1,69 @@
|
||||
"""One-time setup that makes managed subdomains HTTPS.
|
||||
|
||||
Creates the wildcard DNS record (``*.<base_domain>``) via a connected provider
|
||||
and issues a wildcard Let's Encrypt certificate over DNS-01 reusing that
|
||||
provider's credentials. Once the cert exists, ``sites_https_enabled`` flips on
|
||||
and managed subdomain vhosts serve TLS from it (see SiteDomainService and
|
||||
NginxService.create_site's ssl args).
|
||||
"""
|
||||
from app.models.email import DNSProviderConfig
|
||||
from app.services.advanced_ssl_service import AdvancedSSLService
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.settings_service import SettingsService
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
|
||||
|
||||
class SitesHttpsService:
|
||||
|
||||
@classmethod
|
||||
def status(cls):
|
||||
"""Current managed-sites routing/HTTPS configuration."""
|
||||
return {
|
||||
'base_domain': SiteDomainService.base_domain(),
|
||||
'server_ip': SiteDomainService.server_ip(),
|
||||
'https_enabled': SiteDomainService.https_enabled(),
|
||||
'providers': DNSProviderService.list_providers(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def setup(cls, provider_id, email=None):
|
||||
"""Create ``*.<base>`` + ``<base>`` A records and issue the wildcard cert.
|
||||
|
||||
Requires a configured base domain and a connected DNS provider. The
|
||||
server IP is needed to create the A records; without it the cert can
|
||||
still be issued (DNS-01 doesn't need them) but traffic won't route until
|
||||
the records exist — surfaced as a warning rather than a failure.
|
||||
"""
|
||||
base = SiteDomainService.base_domain()
|
||||
if not base:
|
||||
return {'success': False, 'error': 'Set the sites base domain first (Settings).'}
|
||||
|
||||
config = DNSProviderConfig.query.get(provider_id) if provider_id else None
|
||||
if not config:
|
||||
return {'success': False, 'error': 'A connected DNS provider is required to issue the wildcard certificate.'}
|
||||
|
||||
warnings = []
|
||||
ip = SiteDomainService.server_ip()
|
||||
dns = {}
|
||||
if ip:
|
||||
dns['wildcard'] = DNSProviderService.ensure_a_record(f'*.{base}', ip)
|
||||
dns['apex'] = DNSProviderService.ensure_a_record(base, ip)
|
||||
for r in dns.values():
|
||||
if not r.get('created'):
|
||||
warnings.append(r.get('message') or 'A record not created.')
|
||||
else:
|
||||
warnings.append(f'No server public IP set — add the *.{base} and {base} A records manually (or set the IP in Settings).')
|
||||
|
||||
creds_src = DNSProviderService.decrypted_credentials(config)
|
||||
creds = ({'api_token': creds_src['api_key']} if config.provider == 'cloudflare'
|
||||
else {'api_key': creds_src['api_key'], 'api_secret': creds_src['api_secret']})
|
||||
cert = AdvancedSSLService.issue_wildcard_cert(base, config.provider, creds, email=email)
|
||||
if not cert.get('success'):
|
||||
return {'success': False, 'error': f"Wildcard certificate failed: {cert.get('error')}",
|
||||
'dns': dns, 'ssl': cert, 'warning': '; '.join(warnings) if warnings else None}
|
||||
|
||||
SettingsService.set('sites_https_enabled', True)
|
||||
|
||||
return {'success': True, 'base_domain': base, 'https_enabled': True,
|
||||
'dns': dns, 'ssl': cert, 'cert_path': cert.get('certificate_path'),
|
||||
'warning': '; '.join(warnings) if warnings else None}
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Source provider connection service for GitHub repository imports."""
|
||||
"""Source provider connection service for GitHub and GitLab repository imports."""
|
||||
|
||||
import base64
|
||||
import os
|
||||
@@ -24,6 +24,11 @@ class SourceConnectionService:
|
||||
GITHUB_API_URL = 'https://api.github.com'
|
||||
GITHUB_SCOPES = ['repo', 'read:user', 'user:email']
|
||||
|
||||
GITLAB_AUTHORIZE_URL = 'https://gitlab.com/oauth/authorize'
|
||||
GITLAB_TOKEN_URL = 'https://gitlab.com/oauth/token'
|
||||
GITLAB_API_URL = 'https://gitlab.com/api/v4'
|
||||
GITLAB_SCOPES = ['read_user', 'read_api', 'read_repository']
|
||||
|
||||
@classmethod
|
||||
def get_github_config(cls, redacted=False):
|
||||
client_id = (
|
||||
@@ -213,17 +218,193 @@ class SourceConnectionService:
|
||||
connection = SourceConnection.query.filter_by(
|
||||
id=connection_id,
|
||||
user_id=user_id,
|
||||
provider='github',
|
||||
).first()
|
||||
if not connection:
|
||||
raise ValueError('GitHub connection not found')
|
||||
if not connection or connection.provider not in ('github', 'gitlab'):
|
||||
raise ValueError('Source connection not found')
|
||||
|
||||
token = cls._decrypt_connection_token(connection)
|
||||
owner, repo = cls._split_full_name(full_name)
|
||||
public_url = f'https://github.com/{owner}/{repo}.git'
|
||||
auth_url = f'https://x-access-token:{quote(token, safe="")}@github.com/{owner}/{repo}.git'
|
||||
if connection.provider == 'gitlab':
|
||||
repo_path = cls._gitlab_repo_path(full_name)
|
||||
public_url = f'https://gitlab.com/{repo_path}.git'
|
||||
auth_url = f'https://oauth2:{quote(token, safe="")}@gitlab.com/{repo_path}.git'
|
||||
else:
|
||||
owner, repo = cls._split_full_name(full_name)
|
||||
public_url = f'https://github.com/{owner}/{repo}.git'
|
||||
auth_url = f'https://x-access-token:{quote(token, safe="")}@github.com/{owner}/{repo}.git'
|
||||
return {'clone_url': auth_url, 'public_url': public_url}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# GitLab
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@classmethod
|
||||
def get_gitlab_config(cls, redacted=False):
|
||||
client_id = (
|
||||
SettingsService.get('source_gitlab_client_id', '')
|
||||
or os.environ.get('SOURCE_GITLAB_CLIENT_ID', '')
|
||||
or os.environ.get('SERVERKIT_GITLAB_CLIENT_ID', '')
|
||||
)
|
||||
client_secret = (
|
||||
SettingsService.get('source_gitlab_client_secret', '')
|
||||
or os.environ.get('SOURCE_GITLAB_CLIENT_SECRET', '')
|
||||
or os.environ.get('SERVERKIT_GITLAB_CLIENT_SECRET', '')
|
||||
)
|
||||
|
||||
if redacted and client_secret:
|
||||
client_secret = f'****{client_secret[-4:]}'
|
||||
|
||||
return {
|
||||
'client_id': client_id,
|
||||
'client_secret': client_secret,
|
||||
'configured': bool(client_id and client_secret),
|
||||
'scopes': cls.GITLAB_SCOPES,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def update_gitlab_config(cls, data, user_id=None):
|
||||
updated = []
|
||||
if 'client_id' in data:
|
||||
SettingsService.set('source_gitlab_client_id', data.get('client_id') or '', user_id=user_id)
|
||||
updated.append('client_id')
|
||||
if 'client_secret' in data:
|
||||
value = data.get('client_secret') or ''
|
||||
if not (isinstance(value, str) and value.startswith('****')):
|
||||
SettingsService.set('source_gitlab_client_secret', value, user_id=user_id)
|
||||
updated.append('client_secret')
|
||||
return {'updated': updated, 'config': cls.get_gitlab_config(redacted=True)}
|
||||
|
||||
@classmethod
|
||||
def generate_gitlab_authorize_url(cls, redirect_uri):
|
||||
config = cls.get_gitlab_config()
|
||||
if not config['configured']:
|
||||
raise ValueError('GitLab source connection is not configured')
|
||||
|
||||
state = secrets.token_urlsafe(32)
|
||||
session['source_gitlab_state'] = state
|
||||
|
||||
params = {
|
||||
'client_id': config['client_id'],
|
||||
'redirect_uri': redirect_uri,
|
||||
'response_type': 'code',
|
||||
'scope': ' '.join(cls.GITLAB_SCOPES),
|
||||
'state': state,
|
||||
}
|
||||
return f'{cls.GITLAB_AUTHORIZE_URL}?{urlencode(params)}', state
|
||||
|
||||
@classmethod
|
||||
def complete_gitlab_callback(cls, user_id, code, state, redirect_uri):
|
||||
expected_state = session.pop('source_gitlab_state', None)
|
||||
if not expected_state or state != expected_state:
|
||||
raise ValueError('Invalid GitLab OAuth state')
|
||||
|
||||
config = cls.get_gitlab_config()
|
||||
if not config['configured']:
|
||||
raise ValueError('GitLab source connection is not configured')
|
||||
|
||||
token_response = requests.post(
|
||||
cls.GITLAB_TOKEN_URL,
|
||||
headers={'Accept': 'application/json'},
|
||||
data={
|
||||
'client_id': config['client_id'],
|
||||
'client_secret': config['client_secret'],
|
||||
'code': code,
|
||||
'grant_type': 'authorization_code',
|
||||
'redirect_uri': redirect_uri,
|
||||
},
|
||||
timeout=15,
|
||||
)
|
||||
token_response.raise_for_status()
|
||||
token_data = token_response.json()
|
||||
if token_data.get('error'):
|
||||
raise ValueError(token_data.get('error_description') or token_data['error'])
|
||||
|
||||
access_token = token_data.get('access_token')
|
||||
if not access_token:
|
||||
raise ValueError('GitLab did not return an access token')
|
||||
|
||||
profile = cls._gitlab_get(access_token, '/user')
|
||||
connection = SourceConnection.query.filter_by(user_id=user_id, provider='gitlab').first()
|
||||
if not connection:
|
||||
connection = SourceConnection(user_id=user_id, provider='gitlab')
|
||||
db.session.add(connection)
|
||||
|
||||
connection.provider_account_id = str(profile.get('id') or '')
|
||||
connection.provider_username = profile.get('username') or ''
|
||||
connection.display_name = profile.get('name') or profile.get('username') or ''
|
||||
connection.avatar_url = profile.get('avatar_url') or ''
|
||||
connection.access_token_encrypted = encrypt_secret(access_token)
|
||||
connection.scope = token_data.get('scope') or ' '.join(cls.GITLAB_SCOPES)
|
||||
connection.updated_at = datetime.utcnow()
|
||||
connection.last_used_at = datetime.utcnow()
|
||||
|
||||
db.session.commit()
|
||||
return connection
|
||||
|
||||
@classmethod
|
||||
def get_gitlab_status(cls, user_id):
|
||||
connection = cls.get_connection(user_id, 'gitlab')
|
||||
return {
|
||||
'configured': cls.get_gitlab_config()['configured'],
|
||||
'connection': connection.to_dict() if connection else None,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def list_gitlab_repositories(cls, user_id, search='', page=1, per_page=50):
|
||||
token = cls._get_gitlab_token(user_id)
|
||||
params = {
|
||||
'membership': 'true',
|
||||
'order_by': 'updated_at',
|
||||
'sort': 'desc',
|
||||
'page': max(int(page or 1), 1),
|
||||
'per_page': min(max(int(per_page or 50), 1), 100),
|
||||
}
|
||||
search_text = (search or '').strip()
|
||||
if search_text:
|
||||
params['search'] = search_text
|
||||
repos = cls._gitlab_get(token, f'/projects?{urlencode(params)}')
|
||||
|
||||
connection = cls.get_connection(user_id, 'gitlab')
|
||||
if connection:
|
||||
connection.last_used_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
return [cls._gitlab_repo_payload(repo) for repo in repos]
|
||||
|
||||
@classmethod
|
||||
def list_gitlab_branches(cls, user_id, full_name):
|
||||
token = cls._get_gitlab_token(user_id)
|
||||
project_id = cls._gitlab_project_id(full_name)
|
||||
path = f'/projects/{project_id}/repository/branches?per_page=100'
|
||||
branches = cls._gitlab_get(token, path)
|
||||
return [
|
||||
{
|
||||
'name': branch.get('name'),
|
||||
'protected': branch.get('protected', False),
|
||||
}
|
||||
for branch in branches
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def get_gitlab_repository_manifest(cls, user_id, full_name, ref=None):
|
||||
token = cls._get_gitlab_token(user_id)
|
||||
project_id = cls._gitlab_project_id(full_name)
|
||||
root_files = cls._gitlab_list_root_files(token, project_id, ref)
|
||||
file_map = {}
|
||||
|
||||
for file_name in RepositoryManifestService.supported_files():
|
||||
if root_files and file_name not in root_files:
|
||||
continue
|
||||
content = cls._gitlab_get_file_content(token, project_id, file_name, ref)
|
||||
if content is not None:
|
||||
file_map[file_name] = content
|
||||
|
||||
manifest = RepositoryManifestService.analyze_files(file_map, root_files=root_files)
|
||||
connection = cls.get_connection(user_id, 'gitlab')
|
||||
if connection:
|
||||
connection.last_used_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return manifest
|
||||
|
||||
@classmethod
|
||||
def _get_github_token(cls, user_id):
|
||||
connection = cls.get_connection(user_id, 'github')
|
||||
@@ -293,6 +474,93 @@ class SourceConnectionService:
|
||||
raw = base64.b64decode(data.get('content') or '', validate=False)
|
||||
return raw.decode('utf-8', errors='replace')
|
||||
|
||||
@classmethod
|
||||
def _get_gitlab_token(cls, user_id):
|
||||
connection = cls.get_connection(user_id, 'gitlab')
|
||||
if not connection:
|
||||
raise ValueError('GitLab is not connected')
|
||||
return cls._decrypt_connection_token(connection)
|
||||
|
||||
@classmethod
|
||||
def _gitlab_get(cls, token, path):
|
||||
response = requests.get(
|
||||
f'{cls.GITLAB_API_URL}{path}',
|
||||
headers=cls._gitlab_headers(token),
|
||||
timeout=20,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@staticmethod
|
||||
def _gitlab_headers(token):
|
||||
return {
|
||||
'Accept': 'application/json',
|
||||
'Authorization': f'Bearer {token}',
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _gitlab_repo_path(full_name):
|
||||
path = (full_name or '').strip().strip('/')
|
||||
if '/' not in path:
|
||||
raise ValueError('repository_full_name must be namespace/project')
|
||||
return path
|
||||
|
||||
@classmethod
|
||||
def _gitlab_project_id(cls, full_name):
|
||||
return quote(cls._gitlab_repo_path(full_name), safe='')
|
||||
|
||||
@classmethod
|
||||
def _gitlab_list_root_files(cls, token, project_id, ref=None):
|
||||
params = {'per_page': 100}
|
||||
if ref:
|
||||
params['ref'] = ref
|
||||
response = requests.get(
|
||||
f'{cls.GITLAB_API_URL}/projects/{project_id}/repository/tree',
|
||||
headers=cls._gitlab_headers(token),
|
||||
params=params,
|
||||
timeout=20,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
if not isinstance(data, list):
|
||||
return []
|
||||
return [item.get('name') for item in data if item.get('type') == 'blob' and item.get('name')]
|
||||
|
||||
@classmethod
|
||||
def _gitlab_get_file_content(cls, token, project_id, file_name, ref=None):
|
||||
params = {'ref': ref or 'HEAD'}
|
||||
response = requests.get(
|
||||
f'{cls.GITLAB_API_URL}/projects/{project_id}/repository/files/{quote(file_name, safe="")}/raw',
|
||||
headers=cls._gitlab_headers(token),
|
||||
params=params,
|
||||
timeout=20,
|
||||
)
|
||||
if response.status_code == 404:
|
||||
return None
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
|
||||
@staticmethod
|
||||
def _gitlab_repo_payload(repo):
|
||||
namespace = repo.get('namespace') or {}
|
||||
return {
|
||||
'id': repo.get('id'),
|
||||
'name': repo.get('name'),
|
||||
'full_name': repo.get('path_with_namespace'),
|
||||
'description': repo.get('description'),
|
||||
'private': repo.get('visibility') != 'public',
|
||||
'fork': bool(repo.get('forked_from_project')),
|
||||
'archived': repo.get('archived', False),
|
||||
'default_branch': repo.get('default_branch') or 'main',
|
||||
'html_url': repo.get('web_url'),
|
||||
'language': None,
|
||||
'updated_at': repo.get('last_activity_at'),
|
||||
'owner': {
|
||||
'login': namespace.get('path') or namespace.get('full_path'),
|
||||
'avatar_url': repo.get('avatar_url') or namespace.get('avatar_url'),
|
||||
},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _split_full_name(full_name):
|
||||
parts = (full_name or '').strip().split('/')
|
||||
|
||||
@@ -7,6 +7,7 @@ from typing import Dict, List, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from app import paths
|
||||
from app.utils.crypto import encrypt_secret, decrypt_secret_safe, is_encrypted
|
||||
|
||||
|
||||
class StorageProviderService:
|
||||
@@ -14,13 +15,27 @@ class StorageProviderService:
|
||||
|
||||
CONFIG_FILE = os.path.join(paths.SERVERKIT_CONFIG_DIR, 'storage.json')
|
||||
|
||||
# Secret fields encrypted at rest (Fernet) in storage.json.
|
||||
SECRET_FIELDS = {'s3': ['access_key', 'secret_key'], 'b2': ['key_id', 'application_key']}
|
||||
|
||||
@classmethod
|
||||
def _decrypt_config(cls, config: Dict) -> Dict:
|
||||
"""Decrypt secret fields in-place (plaintext fallback for legacy values)."""
|
||||
for provider, fields in cls.SECRET_FIELDS.items():
|
||||
section = config.get(provider)
|
||||
if isinstance(section, dict):
|
||||
for field in fields:
|
||||
if section.get(field):
|
||||
section[field] = decrypt_secret_safe(section[field])
|
||||
return config
|
||||
|
||||
@classmethod
|
||||
def get_config(cls) -> Dict:
|
||||
"""Get storage provider configuration."""
|
||||
"""Get storage provider configuration (secrets decrypted in memory)."""
|
||||
if os.path.exists(cls.CONFIG_FILE):
|
||||
try:
|
||||
with open(cls.CONFIG_FILE, 'r') as f:
|
||||
return json.load(f)
|
||||
return cls._decrypt_config(json.load(f))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -69,7 +84,14 @@ class StorageProviderService:
|
||||
def save_config(cls, config: Dict) -> Dict:
|
||||
"""Save storage provider configuration."""
|
||||
try:
|
||||
os.makedirs(paths.SERVERKIT_CONFIG_DIR, exist_ok=True)
|
||||
# Ensure the parent of the file we actually write exists. Using
|
||||
# cls.CONFIG_FILE (not the hardcoded SERVERKIT_CONFIG_DIR) honors a
|
||||
# CONFIG_FILE override — e.g. tests pointing it at a tmp dir — and
|
||||
# is identical in production, where CONFIG_FILE lives in
|
||||
# SERVERKIT_CONFIG_DIR. Previously this tried to create the real
|
||||
# config dir unconditionally, which raised on a sandboxed CI runner
|
||||
# and (because the except below swallows it) left the file unwritten.
|
||||
os.makedirs(os.path.dirname(cls.CONFIG_FILE) or '.', exist_ok=True)
|
||||
|
||||
# Merge with existing config to preserve unmasked secrets
|
||||
existing = cls.get_config()
|
||||
@@ -87,6 +109,14 @@ class StorageProviderService:
|
||||
# Keep existing value if masked
|
||||
config[provider][field] = existing.get(provider, {}).get(field, '')
|
||||
|
||||
# Encrypt secrets at rest (idempotent — skip already-encrypted values).
|
||||
for provider, fields in secret_fields.items():
|
||||
if provider in config:
|
||||
for field in fields:
|
||||
val = config[provider].get(field, '')
|
||||
if val and not is_encrypted(val):
|
||||
config[provider][field] = encrypt_secret(val)
|
||||
|
||||
with open(cls.CONFIG_FILE, 'w') as f:
|
||||
json.dump(config, f, indent=2)
|
||||
if os.name != 'nt':
|
||||
@@ -408,3 +438,204 @@ class StorageProviderService:
|
||||
return f"{size:.1f} {unit}"
|
||||
size /= 1024
|
||||
return f"{size:.1f} PB"
|
||||
|
||||
# ── File-browser access (powers the Files app's "S3 bucket" target) ──
|
||||
# Paths arrive slash-rooted from the UI (e.g. "/photos/cat.jpg"); we strip the
|
||||
# leading slash to an S3 key. Root "/" → "" (bucket root). The configured
|
||||
# backup path_prefix is intentionally ignored so the browser sees the whole
|
||||
# bucket. All methods reuse the same boto3 client as backups (S3 / B2).
|
||||
|
||||
S3_MAX_EDIT_SIZE = 5 * 1024 * 1024 # 5 MB
|
||||
_EDITABLE_EXT = {
|
||||
'.txt', '.md', '.markdown', '.json', '.yaml', '.yml', '.toml', '.ini', '.cfg',
|
||||
'.conf', '.env', '.csv', '.tsv', '.log', '.xml', '.html', '.htm', '.css', '.scss',
|
||||
'.js', '.jsx', '.ts', '.tsx', '.py', '.rb', '.php', '.go', '.rs', '.java', '.c',
|
||||
'.h', '.cpp', '.sh', '.bash', '.sql', '.svg',
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _s3_client_bucket(cls):
|
||||
client, bucket, _ = cls._get_client()
|
||||
if client is None or not bucket:
|
||||
return None, None
|
||||
return client, bucket
|
||||
|
||||
@staticmethod
|
||||
def _key_from_path(path):
|
||||
return (path or '').lstrip('/')
|
||||
|
||||
@classmethod
|
||||
def _is_editable_key(cls, key, size):
|
||||
ext = os.path.splitext(key)[1].lower()
|
||||
return size <= cls.S3_MAX_EDIT_SIZE and ext in cls._EDITABLE_EXT
|
||||
|
||||
@classmethod
|
||||
def s3_browse(cls, path='/'):
|
||||
client, bucket = cls._s3_client_bucket()
|
||||
if client is None:
|
||||
return {'success': False, 'error': 'No S3-compatible storage is configured'}
|
||||
import mimetypes
|
||||
prefix = cls._key_from_path(path)
|
||||
if prefix and not prefix.endswith('/'):
|
||||
prefix += '/'
|
||||
try:
|
||||
entries = []
|
||||
paginator = client.get_paginator('list_objects_v2')
|
||||
for page in paginator.paginate(Bucket=bucket, Prefix=prefix, Delimiter='/'):
|
||||
for cp in page.get('CommonPrefixes', []):
|
||||
full = cp['Prefix'].rstrip('/')
|
||||
entries.append({
|
||||
'name': full.split('/')[-1], 'path': '/' + full,
|
||||
'is_dir': True, 'is_file': False, 'is_link': False,
|
||||
'size': 0, 'size_human': '—', 'modified': None,
|
||||
'mime_type': None, 'is_editable': False,
|
||||
'is_readable': True, 'is_writable': True,
|
||||
})
|
||||
for obj in page.get('Contents', []):
|
||||
key = obj['Key']
|
||||
if key == prefix: # the folder placeholder object itself
|
||||
continue
|
||||
name = key.split('/')[-1]
|
||||
if not name:
|
||||
continue
|
||||
size = obj.get('Size', 0)
|
||||
mime, _ = mimetypes.guess_type(name)
|
||||
entries.append({
|
||||
'name': name, 'path': '/' + key,
|
||||
'is_dir': False, 'is_file': True, 'is_link': False,
|
||||
'size': size, 'size_human': cls._format_size(size),
|
||||
'modified': obj['LastModified'].isoformat() if obj.get('LastModified') else None,
|
||||
'mime_type': mime, 'is_editable': cls._is_editable_key(key, size),
|
||||
'is_readable': True, 'is_writable': True,
|
||||
})
|
||||
entries.sort(key=lambda x: (not x['is_dir'], x['name'].lower()))
|
||||
|
||||
parent = None
|
||||
stripped = prefix.rstrip('/')
|
||||
if stripped:
|
||||
parent = '/' + stripped.rsplit('/', 1)[0] if '/' in stripped else '/'
|
||||
return {'success': True, 'path': path or '/', 'parent': parent,
|
||||
'entries': entries, 'total': len(entries)}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def s3_read(cls, path):
|
||||
client, bucket = cls._s3_client_bucket()
|
||||
if client is None:
|
||||
return {'success': False, 'error': 'No S3-compatible storage is configured'}
|
||||
key = cls._key_from_path(path)
|
||||
try:
|
||||
head = client.head_object(Bucket=bucket, Key=key)
|
||||
size = head.get('ContentLength', 0)
|
||||
if size > cls.S3_MAX_EDIT_SIZE:
|
||||
return {'success': False, 'error': f'File too large to edit ({cls._format_size(size)})'}
|
||||
obj = client.get_object(Bucket=bucket, Key=key)
|
||||
raw = obj['Body'].read()
|
||||
try:
|
||||
content = raw.decode('utf-8')
|
||||
except UnicodeDecodeError:
|
||||
return {'success': False, 'error': 'Binary file cannot be edited', 'is_binary': True}
|
||||
return {'success': True, 'path': path, 'content': content,
|
||||
'encoding': 'utf-8', 'size': size, 'is_binary': False}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def s3_write(cls, path, content):
|
||||
client, bucket = cls._s3_client_bucket()
|
||||
if client is None:
|
||||
return {'success': False, 'error': 'No S3-compatible storage is configured'}
|
||||
key = cls._key_from_path(path)
|
||||
if not key:
|
||||
return {'success': False, 'error': 'A key is required'}
|
||||
try:
|
||||
body = (content or '').encode('utf-8')
|
||||
client.put_object(Bucket=bucket, Key=key, Body=body)
|
||||
return {'success': True, 'path': path, 'size': len(body)}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def s3_upload(cls, dest_path, filename, fileobj):
|
||||
client, bucket = cls._s3_client_bucket()
|
||||
if client is None:
|
||||
return {'success': False, 'error': 'No S3-compatible storage is configured'}
|
||||
prefix = cls._key_from_path(dest_path)
|
||||
if prefix and not prefix.endswith('/'):
|
||||
prefix += '/'
|
||||
key = f'{prefix}{filename}'
|
||||
try:
|
||||
client.upload_fileobj(fileobj, bucket, key)
|
||||
return {'success': True, 'path': '/' + key}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def s3_delete(cls, path):
|
||||
client, bucket = cls._s3_client_bucket()
|
||||
if client is None:
|
||||
return {'success': False, 'error': 'No S3-compatible storage is configured'}
|
||||
key = cls._key_from_path(path)
|
||||
if not key:
|
||||
return {'success': False, 'error': 'A key is required'}
|
||||
try:
|
||||
# Collect the object itself plus anything beneath it (folder delete).
|
||||
to_delete = set()
|
||||
paginator = client.get_paginator('list_objects_v2')
|
||||
for p in (key, key + '/'):
|
||||
for page in paginator.paginate(Bucket=bucket, Prefix=p):
|
||||
for obj in page.get('Contents', []):
|
||||
to_delete.add(obj['Key'])
|
||||
if not to_delete:
|
||||
client.delete_object(Bucket=bucket, Key=key)
|
||||
else:
|
||||
objs = [{'Key': k} for k in to_delete]
|
||||
for i in range(0, len(objs), 1000):
|
||||
client.delete_objects(Bucket=bucket, Delete={'Objects': objs[i:i + 1000]})
|
||||
return {'success': True, 'path': path}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def s3_presigned_get(cls, path, expires=300):
|
||||
client, bucket = cls._s3_client_bucket()
|
||||
if client is None:
|
||||
return {'success': False, 'error': 'No S3-compatible storage is configured'}
|
||||
key = cls._key_from_path(path)
|
||||
try:
|
||||
url = client.generate_presigned_url(
|
||||
'get_object', Params={'Bucket': bucket, 'Key': key}, ExpiresIn=expires)
|
||||
return {'success': True, 'url': url}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def encrypt_legacy_secrets(cls) -> int:
|
||||
"""One-time, idempotent: encrypt any storage secrets still stored in
|
||||
plaintext in storage.json (configs saved before encryption-at-rest)."""
|
||||
if not os.path.exists(cls.CONFIG_FILE):
|
||||
return 0
|
||||
try:
|
||||
with open(cls.CONFIG_FILE, 'r') as f:
|
||||
raw = json.load(f)
|
||||
except Exception:
|
||||
return 0
|
||||
changed = 0
|
||||
for provider, fields in cls.SECRET_FIELDS.items():
|
||||
section = raw.get(provider)
|
||||
if isinstance(section, dict):
|
||||
for field in fields:
|
||||
val = section.get(field, '')
|
||||
if val and not is_encrypted(val):
|
||||
section[field] = encrypt_secret(val)
|
||||
changed += 1
|
||||
if changed:
|
||||
try:
|
||||
with open(cls.CONFIG_FILE, 'w') as f:
|
||||
json.dump(raw, f, indent=2)
|
||||
if os.name != 'nt':
|
||||
os.chmod(cls.CONFIG_FILE, 0o600)
|
||||
except Exception:
|
||||
return 0
|
||||
return changed
|
||||
@@ -0,0 +1,394 @@
|
||||
"""WireGuard tunnel broker (roadmap Phase 1 — #8 / #10 / #11).
|
||||
|
||||
Pairs two agents over the existing agent command channel:
|
||||
keygen → interface:up → peer:set → verify. The panel is the source of
|
||||
truth; private keys never leave the hosts (only public keys are brokered
|
||||
and persisted). See docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models.server import Server
|
||||
from app.models.tunnel import Tunnel
|
||||
from app.services.agent_registry import agent_registry
|
||||
from app.services import tunnel_netutil
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
KEEPALIVE_SECONDS = 25
|
||||
|
||||
|
||||
class TunnelBrokerError(Exception):
|
||||
"""A broker step failed. ``code`` mirrors the agent send_command codes
|
||||
(AGENT_OFFLINE, PERMISSION_DENIED, TIMEOUT) plus broker-specific ones
|
||||
(NOT_CONNECTED, NO_WIREGUARD, NO_EDGE_IP, POOL_EXHAUSTED, NOT_FOUND,
|
||||
BAD_REQUEST). ``status`` is the HTTP status the API should return."""
|
||||
|
||||
def __init__(self, message, code='BROKER_ERROR', status=400):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.status = status
|
||||
|
||||
|
||||
class TunnelBrokerService:
|
||||
|
||||
# ---- agent command helper ------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _cmd(server_id, action, params=None, user_id=None, timeout=20.0):
|
||||
"""Send an agent command; raise TunnelBrokerError on failure.
|
||||
Returns the agent handler's ``data`` payload on success."""
|
||||
res = agent_registry.send_command(
|
||||
server_id=server_id, action=action, params=params or {},
|
||||
user_id=user_id, timeout=timeout,
|
||||
)
|
||||
if not res.get('success'):
|
||||
code = res.get('code', 'BROKER_ERROR')
|
||||
status = 409 if code == 'AGENT_OFFLINE' else (502 if code == 'TIMEOUT' else 400)
|
||||
raise TunnelBrokerError(
|
||||
"%s on %s failed: %s" % (action, server_id, res.get('error', 'unknown error')),
|
||||
code=code, status=status,
|
||||
)
|
||||
return res.get('data')
|
||||
|
||||
# ---- preflight -----------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _require_wireguard_agent(server_id, role):
|
||||
server = Server.query.get(server_id)
|
||||
if not server:
|
||||
raise TunnelBrokerError("%s server not found" % role, code='NOT_FOUND', status=404)
|
||||
agent = agent_registry.get_agent(server_id)
|
||||
if not agent:
|
||||
raise TunnelBrokerError(
|
||||
"%s server '%s' is not connected" % (role, server.name),
|
||||
code='NOT_CONNECTED', status=409,
|
||||
)
|
||||
if not (agent.capabilities or {}).get('wireguard'):
|
||||
raise TunnelBrokerError(
|
||||
"%s server '%s' lacks the wireguard capability "
|
||||
"(needs wireguard-tools + iproute2 on a Linux agent)" % (role, server.name),
|
||||
code='NO_WIREGUARD', status=409,
|
||||
)
|
||||
return server
|
||||
|
||||
# ---- create --------------------------------------------------------
|
||||
|
||||
@classmethod
|
||||
def create_tunnel(cls, edge_server_id, private_server_id, name=None, user_id=None):
|
||||
if not edge_server_id or not private_server_id:
|
||||
raise TunnelBrokerError("edge_server_id and private_server_id are required", code='BAD_REQUEST')
|
||||
if edge_server_id == private_server_id:
|
||||
raise TunnelBrokerError("edge and private servers must differ", code='BAD_REQUEST')
|
||||
|
||||
edge = cls._require_wireguard_agent(edge_server_id, 'edge')
|
||||
private = cls._require_wireguard_agent(private_server_id, 'private')
|
||||
|
||||
# The private peer dials the edge's public endpoint, so the edge
|
||||
# needs a reachable address.
|
||||
if not tunnel_netutil.validate_endpoint_host(edge.ip_address):
|
||||
raise TunnelBrokerError(
|
||||
"edge server '%s' has no usable public IP (ip_address=%r)" % (edge.name, edge.ip_address),
|
||||
code='NO_EDGE_IP', status=409,
|
||||
)
|
||||
|
||||
used = [t.subnet for t in Tunnel.query.with_entities(Tunnel.subnet).all()]
|
||||
try:
|
||||
subnet, edge_ip, private_ip = tunnel_netutil.pick_subnet(used)
|
||||
except RuntimeError as e:
|
||||
raise TunnelBrokerError(str(e), code='POOL_EXHAUSTED', status=409)
|
||||
|
||||
# Allocate a listen port unique to this edge (#20) so one edge can
|
||||
# front multiple private peers without UDP-port conflicts.
|
||||
used_ports = [t.listen_port for t in Tunnel.query
|
||||
.with_entities(Tunnel.listen_port)
|
||||
.filter(Tunnel.edge_server_id == edge_server_id).all()]
|
||||
try:
|
||||
listen_port = tunnel_netutil.pick_listen_port(used_ports)
|
||||
except RuntimeError as e:
|
||||
raise TunnelBrokerError(str(e), code='PORT_POOL_EXHAUSTED', status=409)
|
||||
|
||||
tunnel = Tunnel(
|
||||
name=name or ("%s → %s" % (edge.name, private.name)),
|
||||
edge_server_id=edge_server_id,
|
||||
private_server_id=private_server_id,
|
||||
subnet=subnet,
|
||||
edge_wg_ip=edge_ip,
|
||||
private_wg_ip=private_ip,
|
||||
listen_port=listen_port,
|
||||
status='pending',
|
||||
)
|
||||
db.session.add(tunnel)
|
||||
db.session.flush() # assign tunnel.id before deriving the interface name
|
||||
tunnel.interface_name = tunnel_netutil.interface_name_for(tunnel.id)
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
cls._bring_up(tunnel, edge, private, user_id)
|
||||
except TunnelBrokerError as e:
|
||||
tunnel.status = 'error'
|
||||
tunnel.last_error = e.message
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
return tunnel
|
||||
|
||||
@classmethod
|
||||
def _bring_up(cls, tunnel, edge, private, user_id):
|
||||
iface = tunnel.interface_name
|
||||
|
||||
# 1. keygen on both ends — public keys only come back.
|
||||
edge_kg = cls._cmd(edge.id, 'wireguard:keygen', {'interface': iface}, user_id)
|
||||
priv_kg = cls._cmd(private.id, 'wireguard:keygen', {'interface': iface}, user_id)
|
||||
edge_pub = (edge_kg or {}).get('public_key')
|
||||
priv_pub = (priv_kg or {}).get('public_key')
|
||||
if not edge_pub or not priv_pub:
|
||||
raise TunnelBrokerError("agent keygen returned no public key", code='BROKER_ERROR', status=502)
|
||||
tunnel.edge_pubkey = edge_pub
|
||||
tunnel.private_pubkey = priv_pub
|
||||
db.session.commit()
|
||||
|
||||
# 2. interfaces up — the edge listens; the private side dials out.
|
||||
cls._cmd(edge.id, 'wireguard:interface:up',
|
||||
{'name': iface, 'address': tunnel.edge_address(), 'listen_port': tunnel.listen_port}, user_id)
|
||||
cls._cmd(private.id, 'wireguard:interface:up',
|
||||
{'name': iface, 'address': tunnel.private_address(), 'listen_port': 0}, user_id)
|
||||
|
||||
# 3. peers — the private peer carries the edge endpoint + keepalive
|
||||
# so it punches and holds the NAT mapping.
|
||||
cls._cmd(edge.id, 'wireguard:peer:set', {
|
||||
'interface': iface,
|
||||
'public_key': priv_pub,
|
||||
'allowed_ips': ["%s/32" % tunnel.private_wg_ip],
|
||||
}, user_id)
|
||||
cls._cmd(private.id, 'wireguard:peer:set', {
|
||||
'interface': iface,
|
||||
'public_key': edge_pub,
|
||||
'allowed_ips': ["%s/32" % tunnel.edge_wg_ip],
|
||||
'endpoint': "%s:%d" % (edge.ip_address, tunnel.listen_port),
|
||||
'persistent_keepalive': KEEPALIVE_SECONDS,
|
||||
}, user_id)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
# 4. open the edge's inbound WireGuard UDP port (best-effort, #10).
|
||||
tunnel.firewall_status = cls._ensure_edge_port(edge.id, tunnel.listen_port, user_id)
|
||||
|
||||
# 5. best-effort immediate verify (handshake may take a few seconds;
|
||||
# #11 health-refresh confirms it later regardless).
|
||||
try:
|
||||
cls.refresh_status(tunnel, user_id=user_id)
|
||||
except TunnelBrokerError:
|
||||
logger.info("post-create status refresh failed for tunnel %s (will settle on next refresh)", tunnel.id)
|
||||
|
||||
# ---- status / health (#11) -----------------------------------------
|
||||
|
||||
@classmethod
|
||||
def refresh_status(cls, tunnel, user_id=None):
|
||||
"""Poll wireguard:status on both ends and update the row's health.
|
||||
Returns {tunnel, edge, private}."""
|
||||
now = time.time()
|
||||
edge_status = cls._safe_status(tunnel.edge_server_id, tunnel.interface_name, user_id)
|
||||
private_status = cls._safe_status(tunnel.private_server_id, tunnel.interface_name, user_id)
|
||||
|
||||
latest = max(cls._latest_handshake(edge_status), cls._latest_handshake(private_status))
|
||||
iface_up = bool((edge_status or {}).get('up')) and bool((private_status or {}).get('up'))
|
||||
tunnel.status = tunnel_netutil.derive_status(latest, now, interface_up=iface_up)
|
||||
if latest:
|
||||
tunnel.last_handshake_at = datetime.utcfromtimestamp(latest)
|
||||
db.session.commit()
|
||||
# Reachability diagnostic (#21): flag a likely blocked-UDP case.
|
||||
age = None
|
||||
if tunnel.created_at:
|
||||
try:
|
||||
age = now - tunnel.created_at.timestamp()
|
||||
except Exception:
|
||||
age = None
|
||||
diagnostic = tunnel_netutil.diagnose_reachability(latest, age, iface_up)
|
||||
return {'tunnel': tunnel.to_dict(), 'edge': edge_status,
|
||||
'private': private_status, 'diagnostic': diagnostic}
|
||||
|
||||
@classmethod
|
||||
def _safe_status(cls, server_id, iface, user_id):
|
||||
"""wireguard:status that returns None instead of raising — a
|
||||
disconnected end shouldn't blow up the whole status read."""
|
||||
try:
|
||||
return cls._cmd(server_id, 'wireguard:status', {'interface': iface}, user_id, timeout=10.0)
|
||||
except TunnelBrokerError:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _latest_handshake(status):
|
||||
if not status:
|
||||
return 0
|
||||
best = 0
|
||||
for p in (status.get('peers') or []):
|
||||
hs = p.get('latest_handshake') or 0
|
||||
if hs > best:
|
||||
best = hs
|
||||
return best
|
||||
|
||||
# ---- teardown ------------------------------------------------------
|
||||
|
||||
@classmethod
|
||||
def teardown_tunnel(cls, tunnel_id, user_id=None):
|
||||
tunnel = Tunnel.query.get(tunnel_id)
|
||||
if not tunnel:
|
||||
raise TunnelBrokerError("tunnel not found", code='NOT_FOUND', status=404)
|
||||
# Best-effort interface teardown on both ends — don't block delete on
|
||||
# a disconnected agent (the row is the source of truth; #19 reconciles).
|
||||
for sid in (tunnel.edge_server_id, tunnel.private_server_id):
|
||||
try:
|
||||
agent_registry.send_command(
|
||||
server_id=sid, action='wireguard:interface:down',
|
||||
params={'interface': tunnel.interface_name}, user_id=user_id, timeout=10.0,
|
||||
)
|
||||
except Exception:
|
||||
logger.info("interface:down on %s during teardown failed (continuing)", sid)
|
||||
db.session.delete(tunnel)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
# ---- reads ---------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def get_tunnel(tunnel_id):
|
||||
tunnel = Tunnel.query.get(tunnel_id)
|
||||
if not tunnel:
|
||||
raise TunnelBrokerError("tunnel not found", code='NOT_FOUND', status=404)
|
||||
return tunnel
|
||||
|
||||
# ---- reconcile (#19: panel-authoritative persistence) --------------
|
||||
|
||||
@staticmethod
|
||||
def schedule_reconcile(server_id):
|
||||
"""Spawn a non-blocking background reconcile for a (re)connected
|
||||
server (#19). Safe to call from a Socket.IO handler — captures the
|
||||
Flask app and runs reconcile_server in its own context, so tunnels
|
||||
self-heal after an agent or panel restart."""
|
||||
try:
|
||||
from app import socketio
|
||||
from flask import current_app
|
||||
app = current_app._get_current_object()
|
||||
except Exception:
|
||||
logger.exception("reconcile: could not capture app/socketio")
|
||||
return
|
||||
|
||||
def _run():
|
||||
with app.app_context():
|
||||
try:
|
||||
TunnelBrokerService.reconcile_server(server_id)
|
||||
except Exception:
|
||||
logger.exception("tunnel reconcile failed for %s", server_id)
|
||||
|
||||
try:
|
||||
socketio.start_background_task(_run)
|
||||
except Exception:
|
||||
logger.exception("could not start reconcile task for %s", server_id)
|
||||
|
||||
@classmethod
|
||||
def reconcile_server(cls, server_id, user_id=None):
|
||||
"""Re-apply the config for every tunnel this server participates in.
|
||||
The panel is the source of truth; relies on the Phase-0 commands
|
||||
being idempotent. Best-effort per tunnel (a down peer doesn't block
|
||||
the others). Returns a per-tunnel result list."""
|
||||
from app.models.exposed_service import ExposedService
|
||||
tunnels = Tunnel.query.filter(
|
||||
((Tunnel.edge_server_id == server_id) | (Tunnel.private_server_id == server_id)),
|
||||
Tunnel.status.in_(('up', 'degraded', 'pending')),
|
||||
).all()
|
||||
out = []
|
||||
for t in tunnels:
|
||||
try:
|
||||
cls._reconcile_side(t, server_id, ExposedService, user_id)
|
||||
out.append({'tunnel_id': t.id, 'ok': True})
|
||||
except TunnelBrokerError as e:
|
||||
logger.info("reconcile of tunnel %s on %s failed: %s", t.id, server_id, e.message)
|
||||
out.append({'tunnel_id': t.id, 'ok': False, 'error': e.message})
|
||||
if out:
|
||||
logger.info("reconciled %d tunnel(s) for server %s", len(out), server_id)
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def _reconcile_side(cls, tunnel, server_id, exposed_service_model, user_id):
|
||||
"""Re-apply just the side of `tunnel` that belongs to server_id (the
|
||||
other end reconciles when it reconnects). Rebuilds from the stored
|
||||
public keys + endpoint — no private key ever needed here."""
|
||||
iface = tunnel.interface_name
|
||||
if tunnel.edge_server_id == server_id:
|
||||
cls._cmd(server_id, 'wireguard:interface:up',
|
||||
{'name': iface, 'address': tunnel.edge_address(),
|
||||
'listen_port': tunnel.listen_port}, user_id)
|
||||
if tunnel.private_pubkey:
|
||||
cls._cmd(server_id, 'wireguard:peer:set',
|
||||
{'interface': iface, 'public_key': tunnel.private_pubkey,
|
||||
'allowed_ips': ['%s/32' % tunnel.private_wg_ip]}, user_id)
|
||||
try:
|
||||
cls._ensure_edge_port(server_id, tunnel.listen_port, user_id)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
cls._cmd(server_id, 'wireguard:interface:up',
|
||||
{'name': iface, 'address': tunnel.private_address(),
|
||||
'listen_port': 0}, user_id)
|
||||
edge = Server.query.get(tunnel.edge_server_id)
|
||||
if tunnel.edge_pubkey and edge and edge.ip_address:
|
||||
cls._cmd(server_id, 'wireguard:peer:set',
|
||||
{'interface': iface, 'public_key': tunnel.edge_pubkey,
|
||||
'allowed_ips': ['%s/32' % tunnel.edge_wg_ip],
|
||||
'endpoint': '%s:%d' % (edge.ip_address, tunnel.listen_port),
|
||||
'persistent_keepalive': KEEPALIVE_SECONDS}, user_id)
|
||||
# Re-apply the service forwarders for this tunnel.
|
||||
for svc in exposed_service_model.query.filter_by(tunnel_id=tunnel.id).all():
|
||||
try:
|
||||
cls._cmd(server_id, 'wireguard:forward',
|
||||
{'interface': iface, 'listen_ip': tunnel.private_wg_ip,
|
||||
'listen_port': svc.port, 'target_host': '127.0.0.1',
|
||||
'target_port': svc.port}, user_id)
|
||||
except TunnelBrokerError:
|
||||
pass
|
||||
|
||||
# ---- firewall (#10) ------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _ensure_edge_port(edge_server_id, port, user_id=None):
|
||||
"""Open the edge's inbound UDP <port> via the agent's
|
||||
firewall:allow_port command (#10). Best-effort — a failure (no
|
||||
firewall present, missing `firewall:*` grant, or an older agent
|
||||
without the command) is non-fatal: the tunnel still works if the
|
||||
port is already open, and the create response always carries the
|
||||
manual commands too. Returns a small outcome dict for the UI."""
|
||||
try:
|
||||
res = agent_registry.send_command(
|
||||
server_id=edge_server_id, action='firewall:allow_port',
|
||||
params={'port': port, 'protocol': 'udp'}, user_id=user_id, timeout=15.0,
|
||||
)
|
||||
except Exception as e: # pragma: no cover - defensive
|
||||
logger.info("edge firewall open failed for %s: %s", edge_server_id, e)
|
||||
return {'opened': False, 'error': str(e)}
|
||||
if res.get('success'):
|
||||
data = res.get('data') or {}
|
||||
return {'opened': True, 'method': data.get('method')}
|
||||
logger.info("edge firewall open not applied for %s: %s", edge_server_id, res.get('error'))
|
||||
return {'opened': False, 'error': res.get('error'), 'code': res.get('code')}
|
||||
|
||||
@staticmethod
|
||||
def firewall_hint(port):
|
||||
"""The edge must accept inbound UDP for the WireGuard handshake.
|
||||
There's no dedicated firewall agent command yet (a small follow-up,
|
||||
like the wireguard:* primitives), so for now we surface the exact
|
||||
step/commands rather than guessing at system:exec."""
|
||||
return {
|
||||
'port': port,
|
||||
'protocol': 'udp',
|
||||
'target': 'edge',
|
||||
'note': "Open inbound UDP %d on the edge server for the WireGuard handshake." % port,
|
||||
'commands': [
|
||||
"ufw allow %d/udp" % port,
|
||||
"firewall-cmd --add-port=%d/udp --permanent && firewall-cmd --reload" % port,
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Pure, dependency-free helpers for the WireGuard tunnel broker.
|
||||
|
||||
Kept import-light (stdlib only) so the subnet allocator, interface-name
|
||||
derivation and health classification are unit-testable without booting
|
||||
Flask/SQLAlchemy. See docs/REMOTE_ACCESS_ROADMAP.md (Phase 1, #7 / #11).
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
|
||||
# The tunnel overlay pool: 10.88.0.0/16 carved into /24s. Deliberately an
|
||||
# uncommon RFC-1918 block so it won't collide with a typical home LAN
|
||||
# (192.168.x / 10.0.x). Each tunnel gets one /24 — .1 = edge, .2 = private.
|
||||
TUNNEL_POOL = "10.88.0.0/16"
|
||||
|
||||
# A peer counts as "live" if it handshook within this window. WireGuard
|
||||
# rehandshakes well inside it when persistent-keepalive is 25s.
|
||||
HANDSHAKE_FRESH_SECONDS = 180
|
||||
|
||||
# WireGuard listen ports are allocated per edge (#20) so ONE edge can front
|
||||
# many private peers — each tunnel needs its own UDP port. 51820..52019.
|
||||
DEFAULT_LISTEN_PORT = 51820
|
||||
LISTEN_PORT_RANGE = 200
|
||||
|
||||
# A tunnel with both interfaces up but no handshake after this long likely
|
||||
# has its outbound UDP blocked (#21).
|
||||
HANDSHAKE_GRACE_SECONDS = 45
|
||||
|
||||
|
||||
def pick_subnet(used_subnets):
|
||||
"""Return (subnet_cidr, edge_ip, private_ip) for the first free /24 in
|
||||
the pool. ``used_subnets`` is any iterable of CIDR strings already taken.
|
||||
|
||||
Raises RuntimeError if the pool is exhausted (256 /24s).
|
||||
"""
|
||||
used = set(used_subnets or [])
|
||||
for third in range(256):
|
||||
cidr = "10.88.%d.0/24" % third
|
||||
if cidr not in used:
|
||||
return cidr, "10.88.%d.1" % third, "10.88.%d.2" % third
|
||||
raise RuntimeError("tunnel subnet pool exhausted (10.88.0.0/16, 256 /24s)")
|
||||
|
||||
|
||||
def interface_name_for(tunnel_id):
|
||||
"""Derive a stable, kernel-valid WireGuard interface name from a tunnel
|
||||
id. Linux caps interface names at 15 chars; 'skwg' + 8 hex is 12. The
|
||||
same name is used on both ends (they're different hosts).
|
||||
"""
|
||||
compact = str(tunnel_id).replace("-", "")[:8] or "0"
|
||||
return "skwg%s" % compact
|
||||
|
||||
|
||||
def derive_status(latest_handshake_epoch, now_epoch, interface_up=True):
|
||||
"""Classify tunnel health from a peer's latest-handshake timestamp.
|
||||
|
||||
- 'down' — the interface isn't up
|
||||
- 'up' — handshook within HANDSHAKE_FRESH_SECONDS
|
||||
- 'degraded' — handshook before, but now stale (link may be recovering)
|
||||
- 'pending' — interface up but no handshake yet (just created)
|
||||
"""
|
||||
if not interface_up:
|
||||
return "down"
|
||||
if latest_handshake_epoch and latest_handshake_epoch > 0:
|
||||
age = now_epoch - latest_handshake_epoch
|
||||
return "up" if age <= HANDSHAKE_FRESH_SECONDS else "degraded"
|
||||
return "pending"
|
||||
|
||||
|
||||
def validate_endpoint_host(ip_address):
|
||||
"""True if ``ip_address`` is usable as the edge's public endpoint host.
|
||||
|
||||
Accepts IPv4/IPv6; rejects empty, malformed, loopback and unspecified
|
||||
addresses. Private ranges are allowed (a lab/LAN edge is valid).
|
||||
"""
|
||||
if not ip_address:
|
||||
return False
|
||||
try:
|
||||
ip = ipaddress.ip_address(str(ip_address).strip())
|
||||
except ValueError:
|
||||
return False
|
||||
return not (ip.is_loopback or ip.is_unspecified)
|
||||
|
||||
|
||||
def pick_listen_port(used_ports):
|
||||
"""First free WireGuard listen port for an edge, starting at
|
||||
DEFAULT_LISTEN_PORT. ``used_ports`` is the ports already taken by other
|
||||
tunnels on the SAME edge — so one edge can front many private peers (#20).
|
||||
Raises RuntimeError if the per-edge pool is exhausted.
|
||||
"""
|
||||
used = set(used_ports or [])
|
||||
for port in range(DEFAULT_LISTEN_PORT, DEFAULT_LISTEN_PORT + LISTEN_PORT_RANGE):
|
||||
if port not in used:
|
||||
return port
|
||||
raise RuntimeError(
|
||||
"listen-port pool exhausted on this edge (%d..%d)"
|
||||
% (DEFAULT_LISTEN_PORT, DEFAULT_LISTEN_PORT + LISTEN_PORT_RANGE - 1)
|
||||
)
|
||||
|
||||
|
||||
def diagnose_reachability(latest_handshake_epoch, age_seconds, both_interfaces_up):
|
||||
"""Near-term #21: classify why a tunnel isn't passing traffic, with an
|
||||
actionable hint. The actual relay data plane is deferred.
|
||||
|
||||
- 'interface_down' — an agent hasn't brought its interface up
|
||||
- 'ok' — a handshake has happened
|
||||
- 'connecting' — interfaces up, still within the handshake grace window
|
||||
- 'no_handshake' — up + past grace + no handshake → outbound UDP likely blocked
|
||||
"""
|
||||
if not both_interfaces_up:
|
||||
return {'state': 'interface_down',
|
||||
'hint': 'One or both agents have not brought the WireGuard interface up.'}
|
||||
if latest_handshake_epoch and latest_handshake_epoch > 0:
|
||||
return {'state': 'ok'}
|
||||
if age_seconds is not None and age_seconds < HANDSHAKE_GRACE_SECONDS:
|
||||
return {'state': 'connecting', 'hint': 'Waiting for the first WireGuard handshake.'}
|
||||
return {'state': 'no_handshake',
|
||||
'hint': ("No WireGuard handshake yet — the private host's outbound UDP to the "
|
||||
"edge may be blocked by its network. A relay (roadmap #21) would be "
|
||||
"needed to traverse it.")}
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Publish a private service over a WireGuard tunnel (roadmap Phase 2).
|
||||
|
||||
Ties the pieces together: start a forwarder on the private peer (#13),
|
||||
write the edge nginx vhost that proxies to the peer's WG IP (#12), point
|
||||
DNS at the edge (#14), put basic-auth in front (#16), and obtain a cert
|
||||
(#15). The nginx / DNS / cert / auth steps run on the panel host, which
|
||||
acts as the edge (where the WG edge interface and nginx live). See
|
||||
docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
from app import db
|
||||
from app.models.exposed_service import ExposedService
|
||||
from app.models.server import Server
|
||||
from app.models.tunnel import Tunnel
|
||||
from app.services.agent_registry import agent_registry
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.environment_domain_service import EnvironmentDomainService
|
||||
from app.services.nginx_service import NginxService
|
||||
from app.services.ssl_service import SSLService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_HOSTNAME_RE = re.compile(
|
||||
r'^(?=.{1,253}$)(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.[A-Za-z0-9-]{1,63})+$'
|
||||
)
|
||||
|
||||
|
||||
class TunnelPublishError(Exception):
|
||||
"""A publish step failed. ``status`` is the HTTP status the API returns."""
|
||||
|
||||
def __init__(self, message, code='PUBLISH_ERROR', status=400):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.status = status
|
||||
|
||||
|
||||
class TunnelPublishService:
|
||||
|
||||
@staticmethod
|
||||
def list_for_tunnel(tunnel_id):
|
||||
return (ExposedService.query
|
||||
.filter_by(tunnel_id=tunnel_id)
|
||||
.order_by(ExposedService.created_at.desc())
|
||||
.all())
|
||||
|
||||
@staticmethod
|
||||
def get(service_id):
|
||||
svc = ExposedService.query.get(service_id)
|
||||
if not svc:
|
||||
raise TunnelPublishError('exposed service not found', code='NOT_FOUND', status=404)
|
||||
return svc
|
||||
|
||||
@classmethod
|
||||
def publish(cls, tunnel_id, hostname, port, *, require_auth=False,
|
||||
auth_username=None, auth_password=None, ssl=True,
|
||||
email=None, user_id=None):
|
||||
"""Publish <hostname> → the private service on <port>. The forwarder
|
||||
and nginx steps are essential (failure aborts); DNS / auth / cert are
|
||||
best-effort and reported in the returned ``steps`` dict."""
|
||||
hostname = (hostname or '').strip().lower().rstrip('.')
|
||||
if not _HOSTNAME_RE.match(hostname):
|
||||
raise TunnelPublishError('invalid hostname', code='BAD_REQUEST')
|
||||
try:
|
||||
port = int(port)
|
||||
except (TypeError, ValueError):
|
||||
raise TunnelPublishError('port must be an integer', code='BAD_REQUEST')
|
||||
if port < 1 or port > 65535:
|
||||
raise TunnelPublishError('port out of range', code='BAD_REQUEST')
|
||||
if require_auth and (not auth_username or not auth_password):
|
||||
raise TunnelPublishError(
|
||||
'auth_username and auth_password are required when require_auth is set',
|
||||
code='BAD_REQUEST')
|
||||
|
||||
tunnel = Tunnel.query.get(tunnel_id)
|
||||
if not tunnel:
|
||||
raise TunnelPublishError('tunnel not found', code='NOT_FOUND', status=404)
|
||||
edge = Server.query.get(tunnel.edge_server_id)
|
||||
|
||||
svc = ExposedService(
|
||||
tunnel_id=tunnel.id, hostname=hostname, port=port,
|
||||
nginx_site_name=hostname, require_auth=require_auth,
|
||||
auth_username=auth_username if require_auth else None,
|
||||
status='pending',
|
||||
)
|
||||
db.session.add(svc)
|
||||
db.session.commit()
|
||||
|
||||
steps = {}
|
||||
try:
|
||||
# 1. Forwarder on the private peer (essential): WG IP:port → the
|
||||
# real local service on 127.0.0.1:port.
|
||||
fwd = agent_registry.send_command(
|
||||
server_id=tunnel.private_server_id, action='wireguard:forward',
|
||||
params={'interface': tunnel.interface_name, 'listen_ip': tunnel.private_wg_ip,
|
||||
'listen_port': port, 'target_host': '127.0.0.1', 'target_port': port},
|
||||
user_id=user_id, timeout=15.0,
|
||||
)
|
||||
if not fwd.get('success'):
|
||||
raise TunnelPublishError(
|
||||
'failed to start forwarder on private host: %s' % fwd.get('error'),
|
||||
code=fwd.get('code', 'FORWARD_FAILED'), status=502)
|
||||
steps['forward'] = {'ok': True}
|
||||
|
||||
# 2. Edge nginx vhost (essential): proxy to the peer's WG IP.
|
||||
upstream = '%s:%d' % (tunnel.private_wg_ip, port)
|
||||
created = NginxService.create_site(
|
||||
name=hostname, app_type='remote', domains=[hostname],
|
||||
root_path='', upstream=upstream)
|
||||
if not created.get('success'):
|
||||
raise TunnelPublishError(
|
||||
'failed to write nginx vhost: %s' % created.get('error'),
|
||||
code='NGINX_FAILED', status=500)
|
||||
enabled = NginxService.enable_site(hostname)
|
||||
if not enabled.get('success'):
|
||||
raise TunnelPublishError(
|
||||
'failed to enable nginx vhost: %s' % enabled.get('error'),
|
||||
code='NGINX_FAILED', status=500)
|
||||
steps['nginx'] = {'ok': True}
|
||||
|
||||
# 3. DNS A record → the edge's public IP (best-effort, #14).
|
||||
edge_ip = edge.ip_address if edge else None
|
||||
steps['dns'] = DNSProviderService.ensure_a_record(hostname, edge_ip)
|
||||
|
||||
# 4. Basic-auth in front (best-effort, #16).
|
||||
if require_auth:
|
||||
steps['auth'] = EnvironmentDomainService.enable_basic_auth(
|
||||
hostname, auth_username, auth_password)
|
||||
|
||||
# 5. Cert on the edge (best-effort, #15). certbot --nginx wires
|
||||
# the TLS into the vhost and reloads, so we only flag success.
|
||||
if ssl:
|
||||
cert = SSLService.obtain_certificate([hostname], email or ('admin@%s' % hostname))
|
||||
steps['ssl'] = {'ok': bool(cert.get('success')), 'error': cert.get('error')}
|
||||
if cert.get('success'):
|
||||
svc.ssl_enabled = True
|
||||
|
||||
svc.status = 'published'
|
||||
db.session.commit()
|
||||
return svc, steps
|
||||
except TunnelPublishError as e:
|
||||
svc.status = 'error'
|
||||
svc.last_error = e.message
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def unpublish(cls, service_id, user_id=None):
|
||||
svc = ExposedService.query.get(service_id)
|
||||
if not svc:
|
||||
raise TunnelPublishError('exposed service not found', code='NOT_FOUND', status=404)
|
||||
tunnel = Tunnel.query.get(svc.tunnel_id)
|
||||
|
||||
# Remove the edge nginx vhost (best-effort).
|
||||
try:
|
||||
NginxService.delete_site(svc.nginx_site_name or svc.hostname)
|
||||
except Exception:
|
||||
logger.info('nginx delete_site failed during unpublish of %s', svc.hostname)
|
||||
|
||||
# Stop the forwarder on the private peer (best-effort).
|
||||
if tunnel:
|
||||
try:
|
||||
agent_registry.send_command(
|
||||
server_id=tunnel.private_server_id, action='wireguard:unforward',
|
||||
params={'interface': tunnel.interface_name, 'listen_port': svc.port},
|
||||
user_id=user_id, timeout=10.0)
|
||||
except Exception:
|
||||
logger.info('wireguard:unforward failed during unpublish of %s', svc.hostname)
|
||||
|
||||
db.session.delete(svc)
|
||||
db.session.commit()
|
||||
return True
|
||||
@@ -285,6 +285,121 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
# --- Per-site PHP ini limits (#24 write side) -------------------------------
|
||||
# The official wordpress:*-apache image is Apache + mod_php and scans
|
||||
# /usr/local/etc/php/conf.d for *.ini drop-ins. We persist a host-side ini and
|
||||
# BIND-MOUNT it into conf.d so it survives container recreate — a plain
|
||||
# `docker exec` write would be lost on the next `compose up`. Every directive is
|
||||
# whitelisted + regex-validated because the value is written as a raw php.ini line.
|
||||
PHP_LIMIT_SPEC = {
|
||||
'memory_limit': r'^(-1|\d{1,5}[KMGkmg]?)$',
|
||||
'upload_max_filesize': r'^\d{1,5}[KMGkmg]?$',
|
||||
'post_max_size': r'^\d{1,5}[KMGkmg]?$',
|
||||
'max_execution_time': r'^\d{1,5}$',
|
||||
'max_input_time': r'^-?\d{1,5}$',
|
||||
'max_input_vars': r'^\d{1,6}$',
|
||||
}
|
||||
PHP_CONF_DIR = 'php-conf'
|
||||
PHP_CONF_FILE = 'zz-serverkit.ini'
|
||||
PHP_CONF_CONTAINER = '/usr/local/etc/php/conf.d/zz-serverkit.ini'
|
||||
|
||||
@classmethod
|
||||
def get_php_limit_spec(cls) -> Dict:
|
||||
"""The editable php.ini directives (key -> validation regex) the limits
|
||||
panel may set. Exposed so the frontend renders exactly the safe set."""
|
||||
return dict(cls.PHP_LIMIT_SPEC)
|
||||
|
||||
@staticmethod
|
||||
def _read_php_ini(ini_path: str) -> Dict:
|
||||
"""Parse a simple `key = value` ini into a dict (comments/blank lines skipped).
|
||||
Never raises — a missing/garbled file just yields {}."""
|
||||
out = {}
|
||||
if os.path.exists(ini_path):
|
||||
try:
|
||||
with open(ini_path, 'r') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line or line.startswith(';') or '=' not in line:
|
||||
continue
|
||||
k, v = line.split('=', 1)
|
||||
out[k.strip()] = v.strip()
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def set_php_limits(cls, path: str, limits: Dict) -> Dict:
|
||||
"""Durably set per-site PHP ini limits for a Docker WP site.
|
||||
|
||||
Writes a host-side conf.d drop-in, bind-mounts it into the container's
|
||||
php conf.d (so it survives recreate), then reloads: a newly-added mount is
|
||||
applied via `compose up -d` (recreates the app container); a content-only
|
||||
change restarts the `wordpress` service so mod_php re-reads php.ini.
|
||||
Partial updates merge with any previously-set directives.
|
||||
"""
|
||||
import re as _re
|
||||
import yaml
|
||||
from app.services.docker_service import DockerService
|
||||
|
||||
compose_file = os.path.join(path, 'docker-compose.yml')
|
||||
if not os.path.exists(compose_file):
|
||||
return {'success': False, 'error': 'Not a Docker-stack site (no docker-compose.yml)'}
|
||||
|
||||
# 1) Validate + sanitize against the whitelist (values become raw ini lines).
|
||||
clean = {}
|
||||
for k, v in (limits or {}).items():
|
||||
if k not in cls.PHP_LIMIT_SPEC:
|
||||
return {'success': False, 'error': f'Unknown PHP limit: {k}'}
|
||||
val = str(v).strip()
|
||||
# fullmatch (not match) so a value like "256M\nevil = 1" can never
|
||||
# smuggle an extra ini directive past the `$` anchor into the file.
|
||||
if not _re.fullmatch(cls.PHP_LIMIT_SPEC[k], val):
|
||||
return {'success': False, 'error': f'Invalid value for {k}: {val}'}
|
||||
clean[k] = val
|
||||
if not clean:
|
||||
return {'success': False, 'error': 'No valid limits provided'}
|
||||
|
||||
try:
|
||||
# 2) Write the host ini FIRST — a single-file bind-mount needs the
|
||||
# source to exist before `compose up`, else Docker makes a dir.
|
||||
conf_dir = os.path.join(path, cls.PHP_CONF_DIR)
|
||||
os.makedirs(conf_dir, exist_ok=True)
|
||||
ini_path = os.path.join(conf_dir, cls.PHP_CONF_FILE)
|
||||
merged = cls._read_php_ini(ini_path)
|
||||
merged.update(clean)
|
||||
body = ['; Managed by ServerKit (#24) — per-site PHP limits. Do not edit by hand.']
|
||||
body += [f'{k} = {v}' for k, v in merged.items()]
|
||||
with open(ini_path, 'w') as f:
|
||||
f.write('\n'.join(body) + '\n')
|
||||
|
||||
# 3) Ensure the wordpress service bind-mounts the ini into conf.d.
|
||||
with open(compose_file, 'r') as f:
|
||||
compose = yaml.safe_load(f) or {}
|
||||
wp = (compose.get('services') or {}).get('wordpress')
|
||||
if not isinstance(wp, dict):
|
||||
return {'success': False, 'error': 'wordpress service not found in compose file'}
|
||||
mount = f'./{cls.PHP_CONF_DIR}/{cls.PHP_CONF_FILE}:{cls.PHP_CONF_CONTAINER}:ro'
|
||||
vols = wp.get('volumes') or []
|
||||
mount_added = mount not in vols
|
||||
if mount_added:
|
||||
vols.append(mount)
|
||||
wp['volumes'] = vols
|
||||
with open(compose_file, 'w') as f:
|
||||
yaml.dump(compose, f, default_flow_style=False, sort_keys=False)
|
||||
|
||||
# 4) Apply: recreate if the mount is new, else restart so php.ini reloads.
|
||||
if mount_added:
|
||||
res = DockerService.compose_up(path, detach=True, build=False)
|
||||
else:
|
||||
res = DockerService.compose_restart(path, service='wordpress')
|
||||
if not res.get('success'):
|
||||
return {'success': False, 'error': res.get('error') or 'Failed to apply PHP limits'}
|
||||
cls._wait_for_wp_ready(path)
|
||||
return {'success': True, 'message': 'PHP limits updated', 'limits': merged,
|
||||
'applied': cls.get_php_info(path).get('limits', {})}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def is_multisite(cls, path: str) -> bool:
|
||||
"""Return True if the WordPress install at ``path`` is a multisite network.
|
||||
@@ -748,6 +863,260 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
result = cls.wp_cli(path, cmd)
|
||||
return result
|
||||
|
||||
# ── URL swap tool ────────────────────────────────────────────────────────
|
||||
# Changing a WordPress site's URL is not a single UPDATE: the URL is embedded
|
||||
# across wp_options, post content, and PHP-serialized blobs whose byte-length
|
||||
# prefixes break under a naive REPLACE. WP-CLI `search-replace` is
|
||||
# serialization-safe, so it is the engine here (the pure-SQL path in
|
||||
# db_sync_service is the fallback for offline dumps only). We dry-run first,
|
||||
# back up before mutating, and roll back on failure.
|
||||
|
||||
@staticmethod
|
||||
def _normalize_url(url: str) -> Optional[str]:
|
||||
"""Canonicalise a user-supplied URL to ``scheme://host[/path]`` with no
|
||||
trailing slash. Returns None if it isn't a usable http(s) URL."""
|
||||
import re
|
||||
from urllib.parse import urlparse
|
||||
if not url:
|
||||
return None
|
||||
url = url.strip().rstrip('/')
|
||||
if '://' not in url:
|
||||
url = 'http://' + url
|
||||
p = urlparse(url)
|
||||
if p.scheme not in ('http', 'https') or not p.netloc:
|
||||
return None
|
||||
# Reject obviously-invalid hosts (spaces, etc.); allow hostname[:port].
|
||||
if not re.match(r'^[A-Za-z0-9.\-]+(:\d+)?$', p.netloc):
|
||||
return None
|
||||
return f'{p.scheme}://{p.netloc}{p.path.rstrip("/")}'
|
||||
|
||||
@staticmethod
|
||||
def _host_of(url: str) -> str:
|
||||
from urllib.parse import urlparse
|
||||
return urlparse(url).netloc
|
||||
|
||||
@classmethod
|
||||
def _url_swap_pairs(cls, old_url: str, new_url: str) -> List[tuple]:
|
||||
"""search→replace pairs for a URL change: the full URL (covers scheme
|
||||
changes) plus a host-only pair (covers protocol-relative and bare-host
|
||||
references) when the host actually changes."""
|
||||
pairs = [(old_url, new_url)]
|
||||
old_host, new_host = cls._host_of(old_url), cls._host_of(new_url)
|
||||
if old_host and new_host and old_host != new_host:
|
||||
pairs.append((old_host, new_host))
|
||||
return pairs
|
||||
|
||||
@staticmethod
|
||||
def _parse_sr_count(output: str) -> int:
|
||||
"""Pull the replacement total out of WP-CLI search-replace output
|
||||
('Success: 12 replacements to be made.' / 'Success: Made 12 replacements.')."""
|
||||
import re
|
||||
if not output:
|
||||
return 0
|
||||
for line in output.splitlines():
|
||||
if 'Success' in line:
|
||||
m = re.search(r'(\d[\d,]*)\s+replacement', line)
|
||||
if m:
|
||||
return int(m.group(1).replace(',', ''))
|
||||
return 0
|
||||
|
||||
@classmethod
|
||||
def _site_current_url(cls, app) -> Optional[str]:
|
||||
"""The site's live URL: prefer WordPress's own stored siteurl (source of
|
||||
truth for what must be search-replaced), else the canonical domain/port."""
|
||||
if app and app.root_path:
|
||||
res = cls.wp_cli(app.root_path, ['option', 'get', 'siteurl'])
|
||||
if res.get('success') and (res.get('output') or '').strip():
|
||||
return cls._normalize_url(res['output'].strip())
|
||||
return cls._canonical_site_url(app) if app else None
|
||||
|
||||
@classmethod
|
||||
def preview_url_change(cls, app, new_url: str) -> Dict:
|
||||
"""Dry-run a URL change: per-pair replacement counts, no mutation."""
|
||||
if not app or not app.root_path:
|
||||
return {'success': False, 'error': 'Site has no application/root path'}
|
||||
new_url = cls._normalize_url(new_url)
|
||||
if not new_url:
|
||||
return {'success': False, 'error': 'A valid new URL (including http:// or https://) is required'}
|
||||
old_url = cls._site_current_url(app)
|
||||
if not old_url:
|
||||
return {'success': False, 'error': 'Could not determine the current site URL'}
|
||||
if new_url == old_url:
|
||||
return {'success': False, 'error': 'The new URL is the same as the current one'}
|
||||
|
||||
rows, total = [], 0
|
||||
for search, replace in cls._url_swap_pairs(old_url, new_url):
|
||||
res = cls.wp_cli(app.root_path, ['search-replace', search, replace,
|
||||
'--all-tables', '--skip-columns=guid',
|
||||
'--dry-run', '--report-changed-only'])
|
||||
if not res.get('success'):
|
||||
return {'success': False, 'error': res.get('error') or 'Preview failed',
|
||||
'current_url': old_url, 'new_url': new_url}
|
||||
count = cls._parse_sr_count(res.get('output'))
|
||||
total += count
|
||||
rows.append({'search': search, 'replace': replace, 'replacements': count})
|
||||
return {'success': True, 'current_url': old_url, 'new_url': new_url,
|
||||
'pairs': rows, 'total': total}
|
||||
|
||||
@classmethod
|
||||
def change_site_url(cls, app, new_url: str, keep_old_redirect: bool = True) -> Dict:
|
||||
"""Change a site's URL end to end: back up, serialization-safe DB rewrite,
|
||||
update home/siteurl, flush caches, then re-point the Domain row + nginx
|
||||
vhost. Rolls the database back from the backup if the rewrite fails.
|
||||
|
||||
With ``keep_old_redirect`` the previous host keeps resolving (its vhost
|
||||
entry stays) so WordPress 301s it to the new canonical URL.
|
||||
"""
|
||||
if not app or not app.root_path:
|
||||
return {'success': False, 'error': 'Site has no application/root path'}
|
||||
new_url = cls._normalize_url(new_url)
|
||||
if not new_url:
|
||||
return {'success': False, 'error': 'A valid new URL (including http:// or https://) is required'}
|
||||
old_url = cls._site_current_url(app)
|
||||
if not old_url:
|
||||
return {'success': False, 'error': 'Could not determine the current site URL'}
|
||||
if new_url == old_url:
|
||||
return {'success': False, 'error': 'The new URL is the same as the current one'}
|
||||
|
||||
# 1) Backup first — this is the rollback point.
|
||||
backup = cls.backup_wordpress(app.root_path, include_db=True)
|
||||
if not backup.get('success'):
|
||||
return {'success': False, 'error': f"Backup failed, aborting URL change: {backup.get('error')}"}
|
||||
|
||||
# 2) Serialization-safe DB rewrite, then finalize options + caches.
|
||||
total = 0
|
||||
try:
|
||||
for search, replace in cls._url_swap_pairs(old_url, new_url):
|
||||
res = cls.wp_cli(app.root_path, ['search-replace', search, replace,
|
||||
'--all-tables', '--skip-columns=guid'])
|
||||
if not res.get('success'):
|
||||
raise RuntimeError(res.get('error') or 'search-replace failed')
|
||||
total += cls._parse_sr_count(res.get('output'))
|
||||
cls.wp_cli(app.root_path, ['option', 'update', 'home', new_url])
|
||||
cls.wp_cli(app.root_path, ['option', 'update', 'siteurl', new_url])
|
||||
cls.wp_cli(app.root_path, ['cache', 'flush'])
|
||||
cls.wp_cli(app.root_path, ['rewrite', 'flush'])
|
||||
except Exception as e:
|
||||
restore = cls.restore_backup(backup['backup_name'], app.root_path)
|
||||
return {'success': False,
|
||||
'error': f'URL change failed and the database was rolled back: {e}',
|
||||
'rolled_back': restore.get('success', False),
|
||||
'backup': backup['backup_name']}
|
||||
|
||||
# 3) Re-point routing (best-effort; the DB change has already succeeded).
|
||||
warnings = []
|
||||
new_host = cls._host_of(new_url)
|
||||
rp = cls._repoint_primary_domain(app, new_host, keep_old=keep_old_redirect)
|
||||
if rp:
|
||||
warnings.append(rp)
|
||||
vhost = cls._write_app_vhost(app)
|
||||
if vhost.get('warning'):
|
||||
warnings.append(vhost['warning'])
|
||||
|
||||
return {'success': True, 'old_url': old_url, 'new_url': new_url,
|
||||
'replacements': total, 'backup': backup['backup_name'],
|
||||
'kept_old_host': keep_old_redirect,
|
||||
'warning': '; '.join(warnings) if warnings else None}
|
||||
|
||||
@classmethod
|
||||
def _repoint_primary_domain(cls, app, new_host: str, keep_old: bool = True) -> Optional[str]:
|
||||
"""Make ``new_host`` the app's primary Domain. With ``keep_old`` the other
|
||||
host rows are demoted (kept, so they still resolve); otherwise removed.
|
||||
Returns a warning string on failure, else None."""
|
||||
from app import db
|
||||
from app.models.domain import Domain
|
||||
if not new_host:
|
||||
return None
|
||||
try:
|
||||
found_new = False
|
||||
for d in Domain.query.filter_by(application_id=app.id).all():
|
||||
if d.name == new_host:
|
||||
d.is_primary = True
|
||||
found_new = True
|
||||
elif keep_old:
|
||||
d.is_primary = False
|
||||
else:
|
||||
db.session.delete(d)
|
||||
if not found_new:
|
||||
db.session.add(Domain(name=new_host, is_primary=True, application_id=app.id))
|
||||
db.session.commit()
|
||||
return None
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return f'could not update domain rows: {e}'
|
||||
|
||||
@classmethod
|
||||
def attach_custom_domain(cls, app, domain: str, migrate: bool = True,
|
||||
issue_ssl: bool = False, email: str = None) -> Dict:
|
||||
"""Point a user-owned domain at a site, end to end.
|
||||
|
||||
Auto-creates the domain's A record via a connected DNS provider (or
|
||||
returns the record to add manually), optionally obtains a Let's Encrypt
|
||||
certificate, then migrates the site URL to the domain by reusing
|
||||
``change_site_url``. External steps (DNS, SSL) degrade to warnings rather
|
||||
than failing the attach; only a requested migration that errors aborts.
|
||||
"""
|
||||
from app import db
|
||||
from app.models.domain import Domain
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
|
||||
if not app or not app.root_path:
|
||||
return {'success': False, 'error': 'Site has no application/root path'}
|
||||
|
||||
# Accept a bare host or a full URL; reduce to the host.
|
||||
host = cls._host_of(cls._normalize_url(domain) or '') or (domain or '').strip().lower().rstrip('/')
|
||||
if not host or '.' not in host:
|
||||
return {'success': False, 'error': 'A valid custom domain (e.g. example.com) is required'}
|
||||
|
||||
# 1) DNS: auto-create the A record, or report what to add manually.
|
||||
dns = DNSProviderService.ensure_a_record(host, SiteDomainService.server_ip())
|
||||
|
||||
# 2) Optional HTTPS. certbot --nginx validates over the host's :80 vhost,
|
||||
# so the host must already be served before the cert is requested.
|
||||
ssl_result = None
|
||||
use_https = False
|
||||
if issue_ssl:
|
||||
from app.services.ssl_service import SSLService
|
||||
if not Domain.query.filter_by(name=host).first():
|
||||
db.session.add(Domain(name=host, is_primary=False, application_id=app.id))
|
||||
db.session.commit()
|
||||
cls._write_app_vhost(app)
|
||||
ssl_result = SSLService.obtain_certificate([host], email or f'admin@{host}')
|
||||
use_https = bool(ssl_result and ssl_result.get('success'))
|
||||
|
||||
# 3) Migrate the site URL to the domain (single rewrite to the final scheme).
|
||||
scheme = 'https' if use_https else 'http'
|
||||
migration = None
|
||||
if migrate:
|
||||
migration = cls.change_site_url(app, f'{scheme}://{host}', keep_old_redirect=True)
|
||||
if not migration.get('success'):
|
||||
return {'success': False,
|
||||
'error': f"DNS handled but moving the site to {host} failed: {migration.get('error')}",
|
||||
'dns': dns, 'ssl': ssl_result, 'migration': migration}
|
||||
else:
|
||||
# Attach the domain (primary + vhost) without rewriting WordPress.
|
||||
cls._repoint_primary_domain(app, host, keep_old=True)
|
||||
cls._write_app_vhost(app)
|
||||
|
||||
warnings = []
|
||||
if not dns.get('created'):
|
||||
warnings.append(dns.get('message') or 'Add the DNS record manually.')
|
||||
if issue_ssl and not use_https:
|
||||
warnings.append('HTTPS is not set up yet — enable SSL once DNS has propagated to this server.')
|
||||
if migration and migration.get('warning'):
|
||||
warnings.append(migration['warning'])
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'domain': host,
|
||||
'url': (migration or {}).get('new_url') or f'{scheme}://{host}',
|
||||
'dns': dns,
|
||||
'ssl': ssl_result,
|
||||
'migration': migration,
|
||||
'warning': '; '.join(warnings) if warnings else None,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def optimize_database(cls, path: str) -> Dict:
|
||||
"""Optimize WordPress database."""
|
||||
@@ -969,8 +1338,11 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
inst = cls.wp_cli(path, ['package', 'install', 'aaemnnosttv/wp-cli-login-command'])
|
||||
if not inst.get('success'):
|
||||
return {'success': False, 'error': 'Failed to install wp-cli-login package: ' + (inst.get('error') or '')}
|
||||
# Ensure the companion launcher mu-plugin is present (idempotent).
|
||||
cls.wp_cli(path, ['login', 'install', '--yes'])
|
||||
# Ensure the companion launcher plugin is present AND active (idempotent).
|
||||
# Without --activate the plugin installs but stays inactive, and the
|
||||
# subsequent `wp login create` fails with "requires the companion plugin
|
||||
# to be installed and active".
|
||||
cls.wp_cli(path, ['login', 'install', '--activate', '--yes'])
|
||||
return {'success': True}
|
||||
|
||||
@classmethod
|
||||
@@ -1036,6 +1408,86 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@staticmethod
|
||||
def _safe_extract_zip(zip_path: str, dest_dir: str) -> Dict:
|
||||
"""Extract a zip into dest_dir, rejecting any member whose path would
|
||||
escape it (zip-slip / absolute-path / `..` traversal). Returns {success}.
|
||||
"""
|
||||
import zipfile
|
||||
try:
|
||||
dest_abs = os.path.abspath(dest_dir)
|
||||
with zipfile.ZipFile(zip_path) as zf:
|
||||
for member in zf.namelist():
|
||||
target = os.path.abspath(os.path.join(dest_abs, member))
|
||||
if target != dest_abs and not target.startswith(dest_abs + os.sep):
|
||||
return {'success': False, 'error': f'Unsafe path in archive: {member}'}
|
||||
zf.extractall(dest_abs)
|
||||
return {'success': True}
|
||||
except zipfile.BadZipFile:
|
||||
return {'success': False, 'error': 'Not a valid zip archive'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@staticmethod
|
||||
def _resolve_wp_content_dir(extracted_dir: str) -> Optional[str]:
|
||||
"""Locate the wp-content directory inside an extracted archive — handles a
|
||||
zip OF wp-content, a full-site zip, or a single wrapper folder. Returns the
|
||||
path to use as wp-content, or None if none is recognizable."""
|
||||
markers = {'plugins', 'themes', 'uploads', 'mu-plugins'}
|
||||
candidates = [extracted_dir]
|
||||
try:
|
||||
for entry in os.listdir(extracted_dir):
|
||||
p = os.path.join(extracted_dir, entry)
|
||||
if os.path.isdir(p):
|
||||
candidates.append(p)
|
||||
except OSError:
|
||||
pass
|
||||
# 1) An explicit wp-content dir at the root or one level down.
|
||||
for base in candidates:
|
||||
wpc = os.path.join(base, 'wp-content')
|
||||
if os.path.isdir(wpc):
|
||||
return wpc
|
||||
# 2) The root (or a wrapper dir) IS wp-content (has plugins/themes/uploads).
|
||||
for base in candidates:
|
||||
try:
|
||||
if set(os.listdir(base)) & markers:
|
||||
return base
|
||||
except OSError:
|
||||
continue
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _import_wp_content_zip(cls, zip_path: str, target_container: str) -> Dict:
|
||||
"""Extract an uploaded wp-content/full-site zip (zip-slip-guarded) and copy
|
||||
its wp-content into the target WordPress container via `docker cp`, then
|
||||
hand the files to the web user. Never raises."""
|
||||
import tempfile
|
||||
tmp = tempfile.mkdtemp(prefix='wpimport_')
|
||||
try:
|
||||
ext = cls._safe_extract_zip(zip_path, tmp)
|
||||
if not ext.get('success'):
|
||||
return ext
|
||||
wpc = cls._resolve_wp_content_dir(tmp)
|
||||
if not wpc:
|
||||
return {'success': False, 'error': 'No wp-content found in the archive'}
|
||||
cp = subprocess.run(
|
||||
['docker', 'cp', f'{wpc}/.', f'{target_container}:/var/www/html/wp-content'],
|
||||
capture_output=True, text=True, timeout=600,
|
||||
)
|
||||
if cp.returncode != 0:
|
||||
return {'success': False, 'error': cp.stderr or 'docker cp failed'}
|
||||
# Imported files land root-owned; hand wp-content to the web user.
|
||||
subprocess.run(
|
||||
['docker', 'exec', target_container, 'chown', '-R', 'www-data:www-data',
|
||||
'/var/www/html/wp-content'],
|
||||
capture_output=True, text=True, timeout=300,
|
||||
)
|
||||
return {'success': True}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
# ========================================
|
||||
# WORDPRESS STANDALONE (DOCKER) MANAGEMENT
|
||||
# ========================================
|
||||
@@ -1397,6 +1849,21 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
cls.wp_cli(root_path, ['option', 'update', 'home', new_url])
|
||||
cls.wp_cli(root_path, ['option', 'update', 'siteurl', new_url])
|
||||
sr = cls.search_replace(root_path, old_url, new_url, dry_run=False)
|
||||
|
||||
warnings = []
|
||||
if not sr.get('success'):
|
||||
warnings.append('Search-replace reported an issue; verify links inside wp-admin.')
|
||||
|
||||
# 3.5) Optionally import wp-content (plugins/themes/uploads) from a zip.
|
||||
wp_content_imported = False
|
||||
if wp_content_zip_path:
|
||||
wpc = cls._import_wp_content_zip(wp_content_zip_path, wp_site.application.name)
|
||||
if wpc.get('success'):
|
||||
wp_content_imported = True
|
||||
else:
|
||||
warnings.append('Database imported, but wp-content import failed: '
|
||||
+ (wpc.get('error') or 'unknown error'))
|
||||
|
||||
cls.wp_cli(root_path, ['cache', 'flush'])
|
||||
cls.wp_cli(root_path, ['rewrite', 'flush'])
|
||||
|
||||
@@ -1413,11 +1880,10 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
'http_port': http_port,
|
||||
'old_url': old_url,
|
||||
'new_url': new_url,
|
||||
'wp_content_imported': wp_content_imported,
|
||||
}
|
||||
if not sr.get('success'):
|
||||
out['warning'] = 'Search-replace reported an issue; verify links inside wp-admin.'
|
||||
if wp_content_zip_path:
|
||||
out['warning'] = 'wp-content import is not yet supported; only the database was imported.'
|
||||
if warnings:
|
||||
out['warning'] = '; '.join(warnings)
|
||||
return out
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e),
|
||||
@@ -1441,6 +1907,7 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
from app import db
|
||||
from app.models import Application, WordPressSite
|
||||
from app.services.template_service import TemplateService
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
|
||||
# Sanitize name for Docker
|
||||
safe_name = name.lower().replace(' ', '-')
|
||||
@@ -1482,7 +1949,16 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
# run the install, so no admin user exists. Do it via the Docker-aware
|
||||
# wp_cli bridge (host-filesystem hardening does not apply to volumes).
|
||||
admin_password = cls._generate_password()
|
||||
site_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'
|
||||
# Publish at a real hostname (<slug>.<base_domain>) instead of
|
||||
# localhost:<port>. WordPress bakes whatever --url we pass in as its
|
||||
# canonical home/siteurl, so this is what makes the site usable as an
|
||||
# actual website. Falls back to localhost when no base domain is set
|
||||
# (e.g. an unconfigured production install).
|
||||
site_host = SiteDomainService.subdomain_for(safe_name)
|
||||
if site_host:
|
||||
site_url = SiteDomainService.site_url(site_host, ssl=SiteDomainService.https_enabled())
|
||||
else:
|
||||
site_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'
|
||||
wp_warning = None
|
||||
harden_actions = []
|
||||
cache_actions = []
|
||||
@@ -1536,6 +2012,14 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
# only meaningful if the automated install finalized).
|
||||
multisite = cls.is_multisite(app.root_path) if admin_password else False
|
||||
|
||||
# Publish the site at its hostname: a Domain row + nginx reverse-proxy
|
||||
# vhost so <slug>.<base_domain> reaches the container. Best-effort — a
|
||||
# box without nginx (local dev) degrades to a warning, never failing
|
||||
# the create.
|
||||
routing = cls._provision_routing(app, site_host)
|
||||
if routing.get('warning'):
|
||||
wp_warning = (wp_warning + ' ' + routing['warning']) if wp_warning else routing['warning']
|
||||
|
||||
# Surface any best-effort cache failures without failing the create.
|
||||
if cache_warnings:
|
||||
note = 'Site created, but some caches could not be enabled — ' + '; '.join(cache_warnings) + '.'
|
||||
@@ -1568,6 +2052,8 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
'message': 'WordPress site created successfully',
|
||||
'site': wp_site.to_dict(),
|
||||
'http_port': http_port,
|
||||
'url': site_url,
|
||||
'domain': site_host,
|
||||
'admin_user': admin_user if admin_password else None,
|
||||
'admin_password': admin_password,
|
||||
'hardening': harden_actions,
|
||||
@@ -1581,6 +2067,84 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
db.session.rollback()
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _provision_routing(cls, app, site_host) -> Dict:
|
||||
"""Publish a managed site at ``site_host`` via a primary Domain row + an
|
||||
nginx reverse-proxy vhost to the container's published port.
|
||||
|
||||
Best-effort and never raises: a box without nginx (e.g. local Windows
|
||||
dev) records the Domain and returns a warning rather than failing site
|
||||
creation. Returns ``{'domain', 'nginx', 'warning'}``.
|
||||
"""
|
||||
from app import db
|
||||
from app.models.domain import Domain
|
||||
|
||||
if not site_host:
|
||||
return {'domain': None, 'nginx': None, 'warning': None}
|
||||
|
||||
warning = None
|
||||
try:
|
||||
if not Domain.query.filter_by(name=site_host).first():
|
||||
Domain.query.filter_by(application_id=app.id, is_primary=True).update({'is_primary': False})
|
||||
db.session.add(Domain(name=site_host, is_primary=True, application_id=app.id))
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
warning = f'could not record domain {site_host}: {e}'
|
||||
|
||||
v = cls._write_app_vhost(app)
|
||||
if v.get('warning'):
|
||||
warning = (warning + '; ' + v['warning']) if warning else v['warning']
|
||||
return {'domain': site_host, 'nginx': v.get('nginx'), 'warning': warning}
|
||||
|
||||
@classmethod
|
||||
def _write_app_vhost(cls, app) -> Dict:
|
||||
"""Write + enable the nginx reverse-proxy vhost for a docker app from its
|
||||
current Domain rows (server_name = every domain). Best-effort and never
|
||||
raises; returns ``{'nginx', 'warning'}``."""
|
||||
from app.models.domain import Domain
|
||||
from app.services.nginx_service import NginxService
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
|
||||
if not app.port:
|
||||
return {'nginx': None, 'warning': None}
|
||||
domains = [d.name for d in Domain.query.filter_by(application_id=app.id).all()]
|
||||
if not domains:
|
||||
return {'nginx': None, 'warning': None}
|
||||
# Serve the wildcard cert when HTTPS is set up and every vhost domain is a
|
||||
# managed subdomain it covers (custom domains carry their own cert).
|
||||
ssl_cert = ssl_key = None
|
||||
if SiteDomainService.https_enabled() and all(SiteDomainService.covers(d) for d in domains):
|
||||
ssl_cert, ssl_key = SiteDomainService.wildcard_cert_paths()
|
||||
try:
|
||||
res = NginxService.create_site(
|
||||
name=app.name, app_type='docker', domains=domains,
|
||||
root_path=app.root_path or '', port=app.port,
|
||||
ssl_cert=ssl_cert, ssl_key=ssl_key,
|
||||
)
|
||||
if res.get('success'):
|
||||
en = NginxService.enable_site(app.name)
|
||||
if not en.get('success'):
|
||||
res['warning'] = f"vhost written but not enabled: {en.get('error')}"
|
||||
return {'nginx': res, 'warning': None}
|
||||
return {'nginx': res, 'warning': f"nginx vhost not created: {res.get('error')}"}
|
||||
except Exception as e:
|
||||
return {'nginx': None, 'warning': f'nginx vhost error: {e}'}
|
||||
|
||||
@classmethod
|
||||
def _canonical_site_url(cls, app) -> str:
|
||||
"""The URL WordPress serves under — its primary domain if one exists,
|
||||
else the legacy localhost:<port> address. Used to build correct
|
||||
search-replace pairs when cloning."""
|
||||
from app.models.domain import Domain
|
||||
d = (Domain.query.filter_by(application_id=app.id, is_primary=True).first()
|
||||
or Domain.query.filter_by(application_id=app.id).first())
|
||||
if d:
|
||||
return f'http://{d.name}'
|
||||
if app.port:
|
||||
return f'http://localhost:{app.port}'
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def clone_site(cls, source_site_id: int, new_name: str, user_id: int) -> Dict:
|
||||
"""Clone an existing Docker WordPress site into a NEW independent top-level
|
||||
@@ -1615,11 +2179,10 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
new_root = new_site.application.root_path
|
||||
new_compose = os.path.join(new_root, 'docker-compose.yml')
|
||||
http_port = create_res.get('http_port')
|
||||
new_url = f'http://localhost:{http_port}' if http_port else 'http://localhost'
|
||||
new_url = create_res.get('url') or (f'http://localhost:{http_port}' if http_port else 'http://localhost')
|
||||
|
||||
try:
|
||||
src_port = source.application.port
|
||||
source_url = f'http://localhost:{src_port}' if src_port else None
|
||||
source_url = cls._canonical_site_url(source.application)
|
||||
|
||||
# 2) Clone the source DB into the new stack (root user for a clean overwrite;
|
||||
# both stacks use db name 'wordpress'; root pw lives in each .env DB_PASSWORD).
|
||||
@@ -1629,10 +2192,14 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
'truncate_tables': ['actionscheduler_actions', 'actionscheduler_logs'],
|
||||
}
|
||||
if source_url and new_url and source_url != new_url:
|
||||
clone_options['search_replace'] = {
|
||||
source_url: new_url,
|
||||
f'localhost:{src_port}': f'localhost:{http_port}',
|
||||
}
|
||||
# Rewrite the source's URL to the clone's, both with and without
|
||||
# scheme so host-only and serialized references are covered.
|
||||
sr = {source_url: new_url}
|
||||
src_host = source_url.split('://', 1)[-1]
|
||||
new_host = new_url.split('://', 1)[-1]
|
||||
if src_host != new_host:
|
||||
sr[src_host] = new_host
|
||||
clone_options['search_replace'] = sr
|
||||
clone_res = DatabaseSyncService.clone_between_containers(
|
||||
source_compose_path=source_compose,
|
||||
target_compose_path=new_compose,
|
||||
@@ -1923,6 +2490,7 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
"""Tear down Docker stack and delete records for a WordPressSite."""
|
||||
from app import db
|
||||
from app.services.docker_service import DockerService
|
||||
from app.services.nginx_service import NginxService
|
||||
|
||||
if wp_site.application and wp_site.application.root_path:
|
||||
root_path = wp_site.application.root_path
|
||||
@@ -1931,6 +2499,13 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
|
||||
shutil.rmtree(root_path, ignore_errors=True)
|
||||
|
||||
if wp_site.application:
|
||||
# Remove the reverse-proxy vhost we provisioned so a deleted site
|
||||
# doesn't leave dangling nginx config. The Domain rows cascade-delete
|
||||
# with the Application (Application.domains is delete-orphan).
|
||||
try:
|
||||
NginxService.delete_site(wp_site.application.name)
|
||||
except Exception:
|
||||
pass
|
||||
db.session.delete(wp_site.application)
|
||||
|
||||
db.session.delete(wp_site)
|
||||
|
||||
@@ -101,6 +101,42 @@ class WorkspaceService:
|
||||
query = query.filter(model.workspace_id == workspace_id)
|
||||
return query
|
||||
|
||||
@staticmethod
|
||||
def effective_role(user, workspace_id):
|
||||
"""Reconcile a user's GLOBAL role (User.role) with their per-workspace
|
||||
membership role (WorkspaceMember.role), returning the effective
|
||||
global-role string ('admin'|'developer'|'viewer') that applies while the
|
||||
user acts inside this workspace.
|
||||
|
||||
NARROW-ONLY, mirroring scope_query: a workspace membership can only
|
||||
REDUCE capability, never grant more than the user's global role.
|
||||
|
||||
- System admin (User.is_admin): always 'admin'. A platform super-admin is
|
||||
never capped by a workspace membership (consistent with scope_query's
|
||||
admin bypass), so they can't be locked out of a workspace they manage.
|
||||
- No workspace context (workspace_id is None): the global role, unchanged.
|
||||
- A 'viewer' workspace membership: capped to 'viewer' (read-only) here,
|
||||
even for a global developer.
|
||||
- Any other membership (member/admin/owner) or non-member: the global
|
||||
role, unchanged — the workspace role never elevates beyond it.
|
||||
"""
|
||||
if user.is_admin:
|
||||
return User.ROLE_ADMIN
|
||||
if workspace_id is None:
|
||||
return user.role
|
||||
ws_role = WorkspaceService.get_user_role(workspace_id, user.id)
|
||||
if ws_role == WorkspaceMember.ROLE_VIEWER:
|
||||
return User.ROLE_VIEWER
|
||||
return user.role
|
||||
|
||||
@staticmethod
|
||||
def can_write_in_workspace(user, workspace_id):
|
||||
"""Whether the user may create/mutate resources while `workspace_id` is the
|
||||
active context. False only when their effective role here is viewer — a
|
||||
global developer who is merely a 'viewer' member of this workspace gets
|
||||
read-only access to it (workspace role caps capability, narrow-only)."""
|
||||
return WorkspaceService.effective_role(user, workspace_id) != User.ROLE_VIEWER
|
||||
|
||||
@staticmethod
|
||||
def list_workspaces(user_id=None, include_archived=False):
|
||||
query = Workspace.query
|
||||
|
||||
@@ -8,9 +8,11 @@ symlink to stdout — exec-cat'ing it yields nothing). Analytics is computed
|
||||
bounded by the container's retained log (it resets when the container is
|
||||
recreated, e.g. on a PHP-version switch — see #24).
|
||||
|
||||
Intentionally NOT derived from the default access log (deferred):
|
||||
- PHP fatals — need ``wp-content/debug.log``, which only exists once WP_DEBUG_LOG
|
||||
is enabled (the per-site WP_DEBUG toggle is #30).
|
||||
PHP fatals/warnings are sourced separately from the WP_DEBUG log
|
||||
(``/tmp/wp-debug.log``), populated only once the per-site WP_DEBUG toggle (#30)
|
||||
is on — see ``get_php_errors`` (they are not in the access log).
|
||||
|
||||
Still NOT derived (deferred):
|
||||
- per-request response time / slow pages — need a ``%D`` LogFormat the official
|
||||
image does not emit.
|
||||
- cache hit ratio — a cache-plugin concern surfaced by #22/#23, not the access log.
|
||||
@@ -151,6 +153,86 @@ class WpAnalyticsService:
|
||||
})
|
||||
return result
|
||||
|
||||
# --- PHP errors (#25 fatals) -------------------------------------------
|
||||
# Sourced from the WP_DEBUG log, NOT the access log. The log only exists once
|
||||
# the per-site WP_DEBUG toggle (#30) is on; its path is owned by WpSecurityService.
|
||||
DEBUG_LOG = '/tmp/wp-debug.log'
|
||||
PHP_ERR_TAIL = 200000 # bytes; bound the debug-log read so a noisy site can't blow up memory
|
||||
RECENT_CAP = 25 # most-recent entries returned
|
||||
|
||||
# WP debug.log line: "[15-Jun-2026 12:34:56 UTC] PHP Fatal error: <message>"
|
||||
_PHP_ERR_RE = re.compile(r'^\[(?P<time>[^\]]+)\]\s+PHP\s+(?P<level>[A-Za-z][A-Za-z ]*?):\s+(?P<msg>.*)$')
|
||||
|
||||
@staticmethod
|
||||
def _classify_php(level):
|
||||
l = level.lower()
|
||||
if 'fatal' in l or 'parse error' in l:
|
||||
return 'fatal'
|
||||
if 'warning' in l:
|
||||
return 'warning'
|
||||
if 'deprecated' in l:
|
||||
return 'deprecated'
|
||||
if 'notice' in l:
|
||||
return 'notice'
|
||||
return 'other'
|
||||
|
||||
@classmethod
|
||||
def get_php_errors(cls, container_name):
|
||||
"""Parse PHP fatals/warnings/notices from the container's WP_DEBUG log
|
||||
(``/tmp/wp-debug.log``, written only once the #30 WP_DEBUG toggle is on).
|
||||
On-demand like get_traffic, with a bounded read + hard timeout so the
|
||||
single worker never blocks. Never raises."""
|
||||
out = {'available': False, 'enabled': False, 'total': 0,
|
||||
'counts': {'fatal': 0, 'warning': 0, 'notice': 0, 'deprecated': 0, 'other': 0},
|
||||
'recent': [], 'note': None}
|
||||
if not container_name:
|
||||
out['note'] = 'No container is resolved for this site.'
|
||||
return out
|
||||
|
||||
# One exec: print a marker IFF the log exists, then its (size-capped) tail.
|
||||
# Empty output => no log => WP_DEBUG logging not enabled (or never errored).
|
||||
marker = '__SK_WPDEBUG__'
|
||||
script = (f'if [ -f {cls.DEBUG_LOG} ]; then echo {marker}; '
|
||||
f'tail -c {cls.PHP_ERR_TAIL} {cls.DEBUG_LOG}; fi')
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
['docker', 'exec', container_name, 'sh', '-c', script],
|
||||
capture_output=True, text=True, timeout=cls.LOG_TIMEOUT,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
out['note'] = 'Debug log read timed out.'
|
||||
return out
|
||||
except (FileNotFoundError, OSError):
|
||||
out['note'] = 'Debug log is unavailable on this host (Docker is not reachable).'
|
||||
return out
|
||||
if proc.returncode != 0:
|
||||
out['note'] = 'Debug log is unavailable — the container may be stopped or on another host.'
|
||||
return out
|
||||
|
||||
body = proc.stdout or ''
|
||||
if not body.startswith(marker):
|
||||
out['note'] = ('PHP error logging is off — enable WP_DEBUG logging on the '
|
||||
'Security tab to collect PHP fatals and warnings.')
|
||||
return out
|
||||
out['available'] = True
|
||||
out['enabled'] = True
|
||||
content = body[len(marker):].lstrip('\n')
|
||||
|
||||
recent = []
|
||||
for raw in content.splitlines():
|
||||
m = cls._PHP_ERR_RE.match(raw.strip())
|
||||
if not m:
|
||||
continue # stack-trace / continuation lines won't match
|
||||
sev = cls._classify_php(m.group('level'))
|
||||
out['counts'][sev] += 1
|
||||
out['total'] += 1
|
||||
recent.append({'time': m.group('time'), 'level': m.group('level').strip(),
|
||||
'severity': sev, 'message': m.group('msg').strip()[:300]})
|
||||
out['recent'] = list(reversed(recent))[:cls.RECENT_CAP] # most-recent first
|
||||
if out['total'] == 0:
|
||||
out['note'] = 'WP_DEBUG logging is on; no PHP errors recorded yet.'
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def _empty(cls, hours):
|
||||
now_hour = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0)
|
||||
|
||||
+132
-13
@@ -27,6 +27,35 @@ container_log_streams = {} # sid -> {'process': Popen, 'app_id': int, 'thread':
|
||||
# Store active pipeline subscriptions
|
||||
pipeline_subscribers = {} # sid -> set of project_ids
|
||||
|
||||
# Authenticated identity per connected client. Populated at connect time
|
||||
# (after the JWT is verified AND the user is confirmed active) and read by
|
||||
# the room/subscription handlers to make authorization decisions. Without
|
||||
# this, every handler only knew "the token decoded" — not who the user is or
|
||||
# what role they hold — so a viewer could join a developer's live terminal
|
||||
# room. Keyed by request.sid; cleaned up on disconnect. Guarded by a lock
|
||||
# because async_mode='threading' runs handlers across worker threads.
|
||||
connected_clients = {} # sid -> {'user_id': ..., 'role': ...}
|
||||
_connected_clients_lock = threading.Lock()
|
||||
|
||||
# Roles permitted to drive/observe privileged server surfaces (remote
|
||||
# terminals). Mirrors the REST side, where terminal create/input/kill are
|
||||
# @developer_required — viewing the live PTY stream must require the same.
|
||||
_PRIVILEGED_ROLES = ('admin', 'developer')
|
||||
|
||||
|
||||
def _client_role(sid):
|
||||
"""Return the authenticated role for a connected socket, or None if the
|
||||
socket isn't in our authenticated set (shouldn't happen post-connect)."""
|
||||
with _connected_clients_lock:
|
||||
info = connected_clients.get(sid)
|
||||
return info['role'] if info else None
|
||||
|
||||
|
||||
def _client_is_privileged(sid):
|
||||
"""True when the connected socket belongs to an admin/developer — the
|
||||
roles allowed to attach to remote terminal streams."""
|
||||
return _client_role(sid) in _PRIVILEGED_ROLES
|
||||
|
||||
|
||||
def init_socketio(app):
|
||||
"""Initialize SocketIO with the Flask app."""
|
||||
@@ -40,23 +69,44 @@ def init_socketio(app):
|
||||
|
||||
@socketio.on('connect')
|
||||
def handle_connect(auth):
|
||||
"""Handle client connection."""
|
||||
"""Handle client connection.
|
||||
|
||||
Authenticates the socket and records the caller's identity + role so the
|
||||
per-room handlers can authorize. A token that merely decodes is NOT enough:
|
||||
we also confirm the user still exists and is active, then stash the role.
|
||||
A deactivated/deleted account whose JWT hasn't expired yet is rejected here
|
||||
rather than being allowed to keep streaming.
|
||||
"""
|
||||
# Verify JWT token from auth payload (not query string, to avoid token leakage in logs)
|
||||
token = None
|
||||
if auth and isinstance(auth, dict):
|
||||
token = auth.get('token')
|
||||
|
||||
if token:
|
||||
try:
|
||||
decode_token(token)
|
||||
emit('connected', {'status': 'connected'})
|
||||
except Exception as e:
|
||||
emit('error', {'message': 'Invalid token'})
|
||||
return False
|
||||
else:
|
||||
if not token:
|
||||
emit('error', {'message': 'Token required'})
|
||||
return False
|
||||
|
||||
try:
|
||||
decoded = decode_token(token)
|
||||
except Exception:
|
||||
emit('error', {'message': 'Invalid token'})
|
||||
return False
|
||||
|
||||
# Resolve the identity to a live, active user. decode_token only proves the
|
||||
# token is well-formed and unexpired — it says nothing about whether the
|
||||
# account is still allowed in.
|
||||
from app.models import User
|
||||
user_id = decoded.get('sub')
|
||||
user = User.query.get(user_id) if user_id is not None else None
|
||||
if not user or not user.is_active:
|
||||
emit('error', {'message': 'Account not found or deactivated'})
|
||||
return False
|
||||
|
||||
with _connected_clients_lock:
|
||||
connected_clients[request.sid] = {'user_id': user.id, 'role': user.role}
|
||||
|
||||
emit('connected', {'status': 'connected'})
|
||||
|
||||
|
||||
@socketio.on('disconnect')
|
||||
def handle_disconnect():
|
||||
@@ -76,6 +126,10 @@ def handle_disconnect():
|
||||
# Remove from pipeline subscribers
|
||||
pipeline_subscribers.pop(sid, None)
|
||||
|
||||
# Drop the authenticated-identity record for this socket.
|
||||
with _connected_clients_lock:
|
||||
connected_clients.pop(sid, None)
|
||||
|
||||
|
||||
@socketio.on('subscribe_metrics')
|
||||
def handle_subscribe_metrics():
|
||||
@@ -117,6 +171,55 @@ def broadcast_metrics():
|
||||
time.sleep(2) # Update every 2 seconds
|
||||
|
||||
|
||||
@socketio.on('subscribe_terminal')
|
||||
def handle_subscribe_terminal(data):
|
||||
"""Join the stream room for a remote terminal session (agent PTY output).
|
||||
|
||||
The agent streams base64 PTY output on channel `terminal:<session_id>`;
|
||||
the agent gateway rebroadcasts it as `server_stream` events into the room
|
||||
`server_<server_id>_terminal:<session_id>`. This handler is what lets a
|
||||
browser join that room — without it the output never reaches the UI.
|
||||
Session ids are unguessable uuids minted by TerminalService for the
|
||||
authenticated creator.
|
||||
"""
|
||||
from app.services.terminal_service import TerminalService
|
||||
|
||||
# Attaching to a live PTY stream exposes everything typed and printed in
|
||||
# that shell (often running as root on the agent host). Creating a terminal
|
||||
# is @developer_required on the REST side, so observing one must demand the
|
||||
# same role — otherwise a read-only viewer could join the stream room and
|
||||
# watch a privileged session.
|
||||
if not _client_is_privileged(request.sid):
|
||||
emit('error', {'message': 'Developer role required for terminal access'})
|
||||
return
|
||||
|
||||
session_id = (data or {}).get('session_id')
|
||||
if not session_id:
|
||||
emit('error', {'message': 'session_id required'})
|
||||
return
|
||||
|
||||
session = TerminalService.get_session(session_id)
|
||||
if not session:
|
||||
emit('error', {'message': 'Unknown terminal session'})
|
||||
return
|
||||
|
||||
join_room(f"server_{session['server_id']}_terminal:{session_id}")
|
||||
emit('subscribed', {'channel': f'terminal:{session_id}'})
|
||||
|
||||
|
||||
@socketio.on('unsubscribe_terminal')
|
||||
def handle_unsubscribe_terminal(data):
|
||||
"""Leave a terminal session's stream room."""
|
||||
from app.services.terminal_service import TerminalService
|
||||
|
||||
session_id = (data or {}).get('session_id')
|
||||
if not session_id:
|
||||
return
|
||||
session = TerminalService.get_session(session_id)
|
||||
if session:
|
||||
leave_room(f"server_{session['server_id']}_terminal:{session_id}")
|
||||
|
||||
|
||||
@socketio.on('subscribe_logs')
|
||||
def handle_subscribe_logs(data):
|
||||
"""Subscribe to real-time log streaming."""
|
||||
@@ -158,11 +261,27 @@ def handle_unsubscribe_logs():
|
||||
|
||||
@socketio.on('join_room')
|
||||
def handle_join_room(data):
|
||||
"""Join a specific room for targeted broadcasts."""
|
||||
"""Join a specific room for targeted broadcasts.
|
||||
|
||||
This is the generic join used by job-progress and cloudflared-login
|
||||
streaming (rooms shaped `server_<id>_<channel>`). It is deliberately
|
||||
permissive for those — the data mirrors what any authenticated user can
|
||||
already pull over REST — but it must NOT become a side door into the
|
||||
privileged terminal stream rooms (`server_<id>_terminal:<session>`), which
|
||||
`subscribe_terminal` gates by role. Enforce that gate here too so the
|
||||
generic primitive can't be used to bypass it.
|
||||
"""
|
||||
room = data.get('room')
|
||||
if room:
|
||||
join_room(room)
|
||||
emit('joined', {'room': room})
|
||||
if not room or not isinstance(room, str):
|
||||
emit('error', {'message': 'room required'})
|
||||
return
|
||||
|
||||
if '_terminal:' in room and not _client_is_privileged(request.sid):
|
||||
emit('error', {'message': 'Developer role required for terminal access'})
|
||||
return
|
||||
|
||||
join_room(room)
|
||||
emit('joined', {'room': room})
|
||||
|
||||
|
||||
@socketio.on('leave_room')
|
||||
|
||||
@@ -92,3 +92,30 @@ def is_encryption_configured() -> bool:
|
||||
bool: True if SERVERKIT_ENCRYPTION_KEY is set
|
||||
"""
|
||||
return os.environ.get('SERVERKIT_ENCRYPTION_KEY') is not None
|
||||
|
||||
|
||||
def decrypt_secret_safe(value: str) -> str:
|
||||
"""Decrypt a value encrypted with ``encrypt_secret``; if it isn't valid
|
||||
ciphertext (e.g. a legacy plaintext secret not yet migrated), return it
|
||||
unchanged. Lets encrypted and not-yet-migrated values coexist during the
|
||||
transition to encryption-at-rest.
|
||||
"""
|
||||
if not value:
|
||||
return value
|
||||
try:
|
||||
return decrypt_secret(value)
|
||||
except Exception:
|
||||
return value
|
||||
|
||||
|
||||
def is_encrypted(value: str) -> bool:
|
||||
"""Best-effort check that ``value`` is our Fernet ciphertext (so migrations
|
||||
can skip already-encrypted values). A real plaintext secret will not decrypt,
|
||||
so this is safe in practice."""
|
||||
if not value:
|
||||
return False
|
||||
try:
|
||||
decrypt_secret(value)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
@@ -46,9 +46,24 @@ class Config:
|
||||
if _public_url and _public_url not in CORS_ORIGINS:
|
||||
CORS_ORIGINS.append(_public_url)
|
||||
|
||||
# ── Managed-site routing ────────────────────────────────────────────
|
||||
# Each managed site is published at <slug>.<SITES_BASE_DOMAIN>; the
|
||||
# operator points a wildcard DNS record (*.<SITES_BASE_DOMAIN>) at the
|
||||
# server so new sites are reachable with no per-site DNS work. Empty by
|
||||
# default so production must opt in explicitly — when empty, site
|
||||
# provisioning falls back to the legacy localhost:<port> URL. The runtime
|
||||
# 'sites_base_domain' setting overrides this (see SiteDomainService).
|
||||
SITES_BASE_DOMAIN = os.environ.get('SITES_BASE_DOMAIN', '')
|
||||
# Public IP the wildcard/custom A-records should point at when auto-creating
|
||||
# DNS records via a connected provider.
|
||||
SERVER_PUBLIC_IP = os.environ.get('SERVER_PUBLIC_IP', '')
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
# lvh.me resolves *.lvh.me -> 127.0.0.1, so subdomain routing works locally
|
||||
# with zero DNS setup.
|
||||
SITES_BASE_DOMAIN = os.environ.get('SITES_BASE_DOMAIN', 'lvh.me')
|
||||
|
||||
@classmethod
|
||||
def init_app(cls, app):
|
||||
@@ -65,6 +80,9 @@ class TestingConfig(Config):
|
||||
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL', 'sqlite:///:memory:')
|
||||
# Reduce noise during tests
|
||||
JWT_ACCESS_TOKEN_EXPIRES = timedelta(minutes=5)
|
||||
# Deterministic base domain so subdomain-provisioning tests don't depend on
|
||||
# the developer's shell environment.
|
||||
SITES_BASE_DOMAIN = 'lvh.me'
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
|
||||
@@ -9,7 +9,7 @@ Flask-Migrate==4.0.7
|
||||
|
||||
# Authentication
|
||||
Flask-JWT-Extended==4.6.0
|
||||
PyJWT==2.12.1
|
||||
PyJWT==2.13.0
|
||||
|
||||
# CORS
|
||||
Flask-Cors==6.0.2
|
||||
@@ -45,7 +45,7 @@ passlib==1.7.4
|
||||
bcrypt==4.2.1
|
||||
|
||||
# Encryption for env vars
|
||||
cryptography==46.0.7
|
||||
cryptography==48.0.1
|
||||
|
||||
# Two-Factor Authentication
|
||||
pyotp==2.9.0
|
||||
|
||||
@@ -11,6 +11,48 @@ if _backend not in sys.path:
|
||||
|
||||
os.environ.setdefault('FLASK_ENV', 'testing')
|
||||
|
||||
# Tests use a FILE-backed SQLite, not :memory:. Flask-SQLAlchemy serves an
|
||||
# in-memory SQLite from a single shared connection (StaticPool), so a test that
|
||||
# drives the DB from a background thread (e.g. the agent send_command round-trip
|
||||
# e2e) races on that one connection and intermittently dies with
|
||||
# ObjectDeletedError / PendingRollbackError. A temp file gives each thread its
|
||||
# own connection with SQLite's own file locking — safe and deterministic. Each
|
||||
# test still create_all/drop_all's a clean schema (see the `app` fixture).
|
||||
if 'TEST_DATABASE_URL' not in os.environ:
|
||||
import tempfile
|
||||
_test_db = os.path.join(tempfile.gettempdir(), 'serverkit_test.db').replace('\\', '/')
|
||||
try:
|
||||
os.remove(_test_db)
|
||||
except OSError:
|
||||
pass
|
||||
os.environ['TEST_DATABASE_URL'] = 'sqlite:///' + _test_db
|
||||
|
||||
|
||||
# A file-backed SQLite fsyncs on every commit, which makes the suite ~3x
|
||||
# slower than :memory:. For throwaway test data that durability is pure
|
||||
# overhead, so disable it and keep the journal in memory — this recovers
|
||||
# roughly in-memory speed while keeping the per-connection thread-safety the
|
||||
# file gives us. SQLite-only and scoped to the test process.
|
||||
#
|
||||
# Guarded import: some CI jobs run only the stdlib-y system-utils tests with a
|
||||
# minimal dependency set (no SQLAlchemy). conftest still has to import there,
|
||||
# and those jobs run no DB-backed test, so the PRAGMA tuning is simply skipped.
|
||||
try:
|
||||
import sqlite3 # noqa: E402
|
||||
from sqlalchemy import event # noqa: E402
|
||||
from sqlalchemy.engine import Engine # noqa: E402
|
||||
|
||||
@event.listens_for(Engine, 'connect')
|
||||
def _fast_sqlite_for_tests(dbapi_connection, _record):
|
||||
if isinstance(dbapi_connection, sqlite3.Connection):
|
||||
cur = dbapi_connection.cursor()
|
||||
cur.execute('PRAGMA synchronous=OFF')
|
||||
cur.execute('PRAGMA journal_mode=MEMORY')
|
||||
cur.execute('PRAGMA temp_store=MEMORY')
|
||||
cur.close()
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def app():
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
Regression tests for audit H2: the Agent Plugin and Server Template features
|
||||
used to dispatch to a non-existent `get_agent_gateway()` (ImportError, swallowed)
|
||||
and leave DB rows stuck in an in-progress state forever. The agent implements
|
||||
none of these commands. These tests assert the operations now report honestly
|
||||
instead of silently pretending to work.
|
||||
"""
|
||||
from app import db
|
||||
from app.models.server import Server
|
||||
from app.models.agent_plugin import AgentPlugin, AgentPluginInstall
|
||||
from app.models.server_template import ServerTemplate, ServerTemplateAssignment
|
||||
from app.services.agent_plugin_service import AgentPluginService
|
||||
from app.services.server_template_service import ServerTemplateService
|
||||
|
||||
|
||||
def test_plugin_install_reports_unimplemented_not_stuck_installing(app):
|
||||
with app.app_context():
|
||||
plugin = AgentPluginService.create_plugin({
|
||||
"name": "demo-plugin",
|
||||
"display_name": "Demo Plugin",
|
||||
"version": "1.0.0",
|
||||
})
|
||||
server = Server(name="srv", agent_id="agent-h2-1")
|
||||
db.session.add(server)
|
||||
db.session.commit()
|
||||
|
||||
install = AgentPluginService.install_plugin(plugin.id, server.id)
|
||||
|
||||
# Honest failure, not a permanent 'installing' limbo.
|
||||
assert install.status == AgentPluginInstall.STATUS_ERROR
|
||||
assert install.status != AgentPluginInstall.STATUS_INSTALLING
|
||||
assert "not implemented" in (install.error_message or "").lower()
|
||||
|
||||
|
||||
def test_template_drift_check_reports_unimplemented_not_stuck_checking(app):
|
||||
with app.app_context():
|
||||
tmpl = ServerTemplate(name="base-template", version="1.0.0")
|
||||
server = Server(name="srv2", agent_id="agent-h2-2")
|
||||
db.session.add_all([tmpl, server])
|
||||
db.session.commit()
|
||||
assignment = ServerTemplateAssignment(template_id=tmpl.id, server_id=server.id)
|
||||
db.session.add(assignment)
|
||||
db.session.commit()
|
||||
|
||||
result = ServerTemplateService.check_drift(assignment.id)
|
||||
|
||||
assert result.status == ServerTemplateAssignment.STATUS_UNKNOWN
|
||||
assert result.status != ServerTemplateAssignment.STATUS_CHECKING
|
||||
assert "not implemented" in (result.drift_report.get("error") or "").lower()
|
||||
|
||||
|
||||
def test_template_remediate_reports_unimplemented(app):
|
||||
with app.app_context():
|
||||
tmpl = ServerTemplate(name="base-template-2", version="1.0.0")
|
||||
server = Server(name="srv3", agent_id="agent-h2-3")
|
||||
db.session.add_all([tmpl, server])
|
||||
db.session.commit()
|
||||
assignment = ServerTemplateAssignment(template_id=tmpl.id, server_id=server.id)
|
||||
db.session.add(assignment)
|
||||
db.session.commit()
|
||||
|
||||
result = ServerTemplateService.remediate(assignment.id)
|
||||
|
||||
assert result.status == ServerTemplateAssignment.STATUS_UNKNOWN
|
||||
assert "not implemented" in (result.drift_report.get("error") or "").lower()
|
||||
@@ -0,0 +1,235 @@
|
||||
"""
|
||||
End-to-end integration test for the panel<->agent command loop.
|
||||
|
||||
This is the "does the whole thing actually work" test the agent subsystem was
|
||||
missing. It drives the REST long-poll transport (POST /connect, /poll, /result)
|
||||
because that path is plain HTTP yet shares the exact same code as the WebSocket
|
||||
gateway for the parts that matter: HMAC authentication (verify_agent_auth),
|
||||
agent registration in the in-memory registry, command queueing/routing
|
||||
(send_command -> outbound_queue -> drain), and result delivery back to the
|
||||
synchronous waiter.
|
||||
|
||||
If these pass, we know: a correctly-signed agent can authenticate, register,
|
||||
receive a command the panel issued, and round-trip a result back to the caller.
|
||||
|
||||
Uses a temp-file SQLite DB (not the in-memory default) so the background
|
||||
send_command thread and the request handlers share committed rows.
|
||||
"""
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import app.agent_gateway as gw
|
||||
from app import db as _db
|
||||
from app.models.server import Server
|
||||
from app.services.agent_registry import agent_registry
|
||||
|
||||
CONNECT = "/api/v1/agent/connect"
|
||||
POLL = "/api/v1/agent/poll"
|
||||
RESULT = "/api/v1/agent/result"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Fixtures: temp-file app so threads + requests see the same committed data.
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture()
|
||||
def app():
|
||||
"""Flask app on a temp-file SQLite DB (thread-shareable, unlike :memory:)."""
|
||||
fd, path = tempfile.mkstemp(suffix=".db")
|
||||
os.close(fd)
|
||||
os.environ["TEST_DATABASE_URL"] = "sqlite:///" + path.replace("\\", "/")
|
||||
|
||||
from app import create_app
|
||||
from app import db as db
|
||||
|
||||
application = create_app("testing")
|
||||
with application.app_context():
|
||||
db.create_all()
|
||||
try:
|
||||
yield application
|
||||
finally:
|
||||
db.session.remove()
|
||||
db.drop_all()
|
||||
os.environ.pop("TEST_DATABASE_URL", None)
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(app):
|
||||
return app.test_client()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate(monkeypatch):
|
||||
"""Reset process-wide singleton state and no-op anomaly side-effects so each
|
||||
test starts clean and exercises only the auth/transport logic."""
|
||||
# Clear the shared per-IP auth rate limiter (a module singleton).
|
||||
gw._auth_attempts.clear()
|
||||
# Clear any agents left in the in-memory registry by a previous test.
|
||||
with agent_registry._lock:
|
||||
agent_registry._agents.clear()
|
||||
agent_registry._socket_to_server.clear()
|
||||
|
||||
import app.services.anomaly_detection_service as ad
|
||||
for name in ("track_auth_attempt", "track_ip_blocked", "track_replay_attack",
|
||||
"check_new_ip"):
|
||||
monkeypatch.setattr(ad.anomaly_detection_service, name,
|
||||
lambda *a, **k: None, raising=False)
|
||||
|
||||
yield
|
||||
|
||||
gw._auth_attempts.clear()
|
||||
with agent_registry._lock:
|
||||
agent_registry._agents.clear()
|
||||
agent_registry._socket_to_server.clear()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _make_agent_server(monkeypatch, permissions=None):
|
||||
"""Create a Server row with a known shared secret and return
|
||||
(server_id, agent_id, api_key_prefix, api_secret). get_api_secret is
|
||||
stubbed to the known secret so the test doesn't depend on the Fernet
|
||||
key setup (mirrors test_agent_registry_security)."""
|
||||
api_key, api_secret = Server.generate_api_credentials()
|
||||
server = Server(name="e2e", agent_id="agent-e2e")
|
||||
server.set_api_key(api_key) # sets api_key_prefix = api_key[:12]
|
||||
server.permissions = permissions if permissions is not None else ["*"]
|
||||
_db.session.add(server)
|
||||
_db.session.commit()
|
||||
|
||||
monkeypatch.setattr(Server, "get_api_secret", lambda self: api_secret)
|
||||
return server.id, server.agent_id, server.api_key_prefix, api_secret
|
||||
|
||||
|
||||
def _auth_payload(agent_id, prefix, secret, nonce="nonce-e2e-1"):
|
||||
ts = int(time.time() * 1000)
|
||||
msg = f"{agent_id}:{ts}:{nonce}"
|
||||
sig = hmac.new(secret.encode(), msg.encode(), hashlib.sha256).hexdigest()
|
||||
return {
|
||||
"agent_id": agent_id,
|
||||
"api_key_prefix": prefix,
|
||||
"signature": sig,
|
||||
"timestamp": ts,
|
||||
"nonce": nonce,
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Tests
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def test_connect_authenticates_and_registers(client, monkeypatch):
|
||||
"""A correctly-signed agent authenticates over the poll transport, gets a
|
||||
session token, and shows up in the registry as a poll-mode agent."""
|
||||
server_id, agent_id, prefix, secret = _make_agent_server(monkeypatch)
|
||||
|
||||
resp = client.post(CONNECT, json=_auth_payload(agent_id, prefix, secret))
|
||||
assert resp.status_code == 200, resp.get_data(as_text=True)
|
||||
body = resp.get_json()
|
||||
assert body["success"] is True
|
||||
assert body["server_id"] == server_id
|
||||
token = body["session_token"]
|
||||
assert token
|
||||
|
||||
agent = agent_registry.get_agent_by_token(token)
|
||||
assert agent is not None
|
||||
assert agent.server_id == server_id
|
||||
assert agent.transport == "poll"
|
||||
|
||||
|
||||
def test_connect_rejects_bad_signature(client, monkeypatch):
|
||||
"""Auth must fail closed when the HMAC doesn't match — no session issued."""
|
||||
server_id, agent_id, prefix, secret = _make_agent_server(monkeypatch)
|
||||
|
||||
payload = _auth_payload(agent_id, prefix, secret)
|
||||
payload["signature"] = "deadbeef" * 8 # wrong signature
|
||||
|
||||
resp = client.post(CONNECT, json=payload)
|
||||
assert resp.status_code == 401, resp.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_command_roundtrip_via_send_command(app, client, monkeypatch):
|
||||
"""The full loop through the real public API:
|
||||
|
||||
panel send_command -> queued -> agent /poll receives it -> agent /result
|
||||
posts the outcome -> send_command's synchronous waiter resolves with it.
|
||||
"""
|
||||
server_id, agent_id, prefix, secret = _make_agent_server(monkeypatch)
|
||||
|
||||
# Agent authenticates and gets a session token.
|
||||
resp = client.post(CONNECT, json=_auth_payload(agent_id, prefix, secret))
|
||||
assert resp.status_code == 200, resp.get_data(as_text=True)
|
||||
token = resp.get_json()["session_token"]
|
||||
|
||||
# Panel issues a command from a background thread (send_command blocks until
|
||||
# the result comes back). It needs its own app context for DB writes.
|
||||
holder = {}
|
||||
|
||||
def _issue():
|
||||
with app.app_context():
|
||||
holder["result"] = agent_registry.send_command(
|
||||
server_id=server_id,
|
||||
action="system:info",
|
||||
params={"probe": True},
|
||||
timeout=15.0,
|
||||
)
|
||||
|
||||
t = threading.Thread(target=_issue, daemon=True)
|
||||
t.start()
|
||||
|
||||
# Agent long-polls and should receive the queued command. drain_outbound
|
||||
# blocks until the command is queued, so there's no race with the thread.
|
||||
poll = client.post(POLL, headers={"X-Session-Token": token}, json={})
|
||||
assert poll.status_code == 200, poll.get_data(as_text=True)
|
||||
commands = poll.get_json()["commands"]
|
||||
assert len(commands) == 1, f"expected one queued command, got {commands}"
|
||||
cmd = commands[0]
|
||||
assert cmd["action"] == "system:info"
|
||||
assert cmd["params"] == {"probe": True}
|
||||
command_id = cmd["id"]
|
||||
|
||||
# Agent reports the outcome.
|
||||
result_payload = {
|
||||
"command_id": command_id,
|
||||
"success": True,
|
||||
"data": {"hostname": "test-host", "os": "linux"},
|
||||
"duration": 12,
|
||||
}
|
||||
res = client.post(RESULT, headers={"X-Session-Token": token},
|
||||
json=result_payload)
|
||||
assert res.status_code == 200, res.get_data(as_text=True)
|
||||
assert res.get_json()["ok"] is True
|
||||
|
||||
# The panel-side waiter must resolve with exactly what the agent reported.
|
||||
t.join(timeout=10)
|
||||
assert not t.is_alive(), "send_command did not return after result posted"
|
||||
result = holder.get("result")
|
||||
assert result is not None
|
||||
assert result["success"] is True
|
||||
assert result["data"] == {"hostname": "test-host", "os": "linux"}
|
||||
|
||||
|
||||
def test_result_for_unknown_command_is_rejected(client, monkeypatch):
|
||||
"""Posting a result for a command the panel never issued is a 404 — the
|
||||
token is valid but there's no matching pending command."""
|
||||
server_id, agent_id, prefix, secret = _make_agent_server(monkeypatch)
|
||||
token = client.post(
|
||||
CONNECT, json=_auth_payload(agent_id, prefix, secret)
|
||||
).get_json()["session_token"]
|
||||
|
||||
res = client.post(RESULT, headers={"X-Session-Token": token},
|
||||
json={"command_id": "never-issued", "success": True})
|
||||
assert res.status_code == 404, res.get_data(as_text=True)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""
|
||||
Authorization regression test for the agent self-update endpoint.
|
||||
|
||||
POST /api/v1/servers/<id>/agent/update replaces the agent binary and restarts
|
||||
the service. It used to be @jwt_required() only, so a read-only `viewer` could
|
||||
trigger fleet-wide updates/restarts — every other state-changing server route is
|
||||
@developer_required. This locks it to developer+ and proves both directions.
|
||||
"""
|
||||
from flask_jwt_extended import create_access_token
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.models.server import Server
|
||||
|
||||
|
||||
def _user(role):
|
||||
u = User(
|
||||
email=f"{role}@authz.local",
|
||||
username=f"{role}-authz",
|
||||
password_hash=generate_password_hash("x"),
|
||||
role=role,
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
return u
|
||||
|
||||
|
||||
def _headers(user):
|
||||
return {"Authorization": f"Bearer {create_access_token(identity=user.id)}"}
|
||||
|
||||
|
||||
def _server():
|
||||
s = Server(name="authz-srv", agent_id="authz-agent")
|
||||
db.session.add(s)
|
||||
db.session.commit()
|
||||
return s.id
|
||||
|
||||
|
||||
def test_viewer_cannot_trigger_agent_update(client, app):
|
||||
with app.app_context():
|
||||
headers = _headers(_user(User.ROLE_VIEWER))
|
||||
server_id = _server()
|
||||
|
||||
resp = client.post(f"/api/v1/servers/{server_id}/agent/update",
|
||||
headers=headers, json={})
|
||||
assert resp.status_code == 403, resp.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_developer_passes_the_role_gate(client, app):
|
||||
"""A developer clears the role gate. The request then fails downstream
|
||||
(503, no agent connected) — which is exactly what proves the gate let them
|
||||
through rather than blocking with 403."""
|
||||
with app.app_context():
|
||||
headers = _headers(_user(User.ROLE_DEVELOPER))
|
||||
server_id = _server()
|
||||
|
||||
resp = client.post(f"/api/v1/servers/{server_id}/agent/update",
|
||||
headers=headers, json={})
|
||||
assert resp.status_code != 403, resp.get_data(as_text=True)
|
||||
assert resp.status_code == 503, resp.get_data(as_text=True) # agent offline
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Phase 3 proving tests — custom-domain attach + auto-DNS.
|
||||
|
||||
Attaching a user-owned domain auto-creates its A record via a connected DNS
|
||||
provider (or returns the record to add manually), then migrates the site to it
|
||||
by reusing the URL-swap tool.
|
||||
"""
|
||||
|
||||
|
||||
def _mk_user(db, username='owner'):
|
||||
from app.models import User
|
||||
from werkzeug.security import generate_password_hash
|
||||
u = User(email=f'{username}@test.local', username=username,
|
||||
password_hash=generate_password_hash('x'),
|
||||
role=User.ROLE_ADMIN, is_active=True)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
return u
|
||||
|
||||
|
||||
def _mk_site_app(db, user_id, name='blog', port=8300, host='old.lvh.me'):
|
||||
from app.models import Application
|
||||
from app.models.domain import Domain
|
||||
a = Application(name=name, app_type='docker', user_id=user_id,
|
||||
root_path=f'/srv/{name}', port=port)
|
||||
db.session.add(a)
|
||||
db.session.commit()
|
||||
db.session.add(Domain(name=host, is_primary=True, application_id=a.id))
|
||||
db.session.commit()
|
||||
return a
|
||||
|
||||
|
||||
def _mk_provider(db, name='cf', provider='cloudflare'):
|
||||
from app.models.email import DNSProviderConfig
|
||||
c = DNSProviderConfig(name=name, provider=provider, api_key='k')
|
||||
db.session.add(c)
|
||||
db.session.commit()
|
||||
return c
|
||||
|
||||
|
||||
# ── DNS zone matching + record upsert ───────────────────────────────────────
|
||||
|
||||
def test_find_zone_longest_suffix_match(app, monkeypatch):
|
||||
from app import db
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
|
||||
_mk_provider(db)
|
||||
monkeypatch.setattr(DNSProviderService, 'list_zones',
|
||||
classmethod(lambda cls, pid: {'success': True, 'zones': [
|
||||
{'id': 'z1', 'name': 'example.com'},
|
||||
{'id': 'z2', 'name': 'sub.example.com'},
|
||||
]}))
|
||||
|
||||
_, zone = DNSProviderService.find_zone_for_domain('blog.sub.example.com')
|
||||
assert zone['id'] == 'z2' # longest suffix wins
|
||||
_, zone = DNSProviderService.find_zone_for_domain('blog.example.com')
|
||||
assert zone['id'] == 'z1'
|
||||
cfg, zone = DNSProviderService.find_zone_for_domain('nope.org')
|
||||
assert cfg is None and zone is None
|
||||
|
||||
|
||||
def test_ensure_a_record_auto_creates(app, monkeypatch):
|
||||
from app import db
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
|
||||
_mk_provider(db)
|
||||
monkeypatch.setattr(DNSProviderService, 'list_zones',
|
||||
classmethod(lambda cls, pid: {'success': True, 'zones': [{'id': 'z1', 'name': 'example.com'}]}))
|
||||
captured = {}
|
||||
|
||||
def fake_set(cls, pid, zid, rtype, name, value, ttl=3600):
|
||||
captured.update({'zid': zid, 'rtype': rtype, 'name': name, 'value': value})
|
||||
return {'success': True}
|
||||
|
||||
monkeypatch.setattr(DNSProviderService, 'set_record', classmethod(fake_set))
|
||||
|
||||
res = DNSProviderService.ensure_a_record('blog.example.com', '203.0.113.5')
|
||||
assert res['created'] is True
|
||||
assert captured == {'zid': 'z1', 'rtype': 'A', 'name': 'blog.example.com', 'value': '203.0.113.5'}
|
||||
|
||||
|
||||
def test_ensure_a_record_no_provider_returns_manual_record(app):
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
res = DNSProviderService.ensure_a_record('blog.example.com', '1.2.3.4')
|
||||
assert res['created'] is False
|
||||
assert res['reason'] == 'no_provider'
|
||||
assert res['record'] == {'type': 'A', 'name': 'blog.example.com', 'value': '1.2.3.4'}
|
||||
|
||||
|
||||
def test_ensure_a_record_no_ip(app):
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
res = DNSProviderService.ensure_a_record('blog.example.com', None)
|
||||
assert res['created'] is False
|
||||
assert res['reason'] == 'no_server_ip'
|
||||
|
||||
|
||||
# ── attach orchestration ────────────────────────────────────────────────────
|
||||
|
||||
def test_attach_auto_dns_and_migrate(app, monkeypatch):
|
||||
from app import db
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db)
|
||||
app_row = _mk_site_app(db, user.id, host='old.lvh.me')
|
||||
|
||||
monkeypatch.setattr(DNSProviderService, 'ensure_a_record',
|
||||
classmethod(lambda cls, host, ip: {'created': True, 'provider': 'cf',
|
||||
'zone': 'example.com',
|
||||
'record': {'type': 'A', 'name': host, 'value': ip}}))
|
||||
captured = {}
|
||||
|
||||
def fake_change(cls, a, new_url, keep_old_redirect=True):
|
||||
captured['url'] = new_url
|
||||
return {'success': True, 'new_url': new_url, 'old_url': 'http://old.lvh.me', 'replacements': 3}
|
||||
|
||||
monkeypatch.setattr(WordPressService, 'change_site_url', classmethod(fake_change))
|
||||
|
||||
res = WordPressService.attach_custom_domain(app_row, 'blog.example.com')
|
||||
assert res['success'] is True
|
||||
assert res['domain'] == 'blog.example.com'
|
||||
assert res['url'] == 'http://blog.example.com'
|
||||
assert captured['url'] == 'http://blog.example.com' # migrated over http (no SSL)
|
||||
assert res['dns']['created'] is True
|
||||
assert res['warning'] is None
|
||||
|
||||
|
||||
def test_attach_manual_dns_surfaces_record(app, monkeypatch):
|
||||
from app import db
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'o2')
|
||||
app_row = _mk_site_app(db, user.id, name='shop', host='old.lvh.me')
|
||||
|
||||
monkeypatch.setattr(DNSProviderService, 'ensure_a_record',
|
||||
classmethod(lambda cls, host, ip: {'created': False, 'reason': 'no_provider',
|
||||
'record': {'type': 'A', 'name': host, 'value': ip},
|
||||
'message': 'add this record manually'}))
|
||||
monkeypatch.setattr(WordPressService, 'change_site_url',
|
||||
classmethod(lambda cls, a, new_url, keep_old_redirect=True: {'success': True, 'new_url': new_url}))
|
||||
|
||||
res = WordPressService.attach_custom_domain(app_row, 'shop.example.org')
|
||||
assert res['success'] is True
|
||||
assert res['dns']['created'] is False
|
||||
assert 'manually' in res['warning'].lower()
|
||||
|
||||
|
||||
def test_attach_with_ssl_migrates_https(app, monkeypatch):
|
||||
from app import db
|
||||
import app.services.ssl_service as ssl_mod
|
||||
import app.services.nginx_service as nginx_mod
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'o3')
|
||||
app_row = _mk_site_app(db, user.id, name='sec', host='old.lvh.me')
|
||||
|
||||
monkeypatch.setattr(DNSProviderService, 'ensure_a_record',
|
||||
classmethod(lambda cls, host, ip: {'created': True, 'provider': 'cf', 'record': {}}))
|
||||
monkeypatch.setattr(ssl_mod.SSLService, 'obtain_certificate',
|
||||
classmethod(lambda cls, domains, email, **k: {'success': True, 'certificate_path': '/x'}))
|
||||
monkeypatch.setattr(nginx_mod.NginxService, 'create_site', classmethod(lambda cls, **kw: {'success': True}))
|
||||
monkeypatch.setattr(nginx_mod.NginxService, 'enable_site', classmethod(lambda cls, name: {'success': True}))
|
||||
captured = {}
|
||||
monkeypatch.setattr(WordPressService, 'change_site_url',
|
||||
classmethod(lambda cls, a, new_url, keep_old_redirect=True: (captured.update({'url': new_url}),
|
||||
{'success': True, 'new_url': new_url})[1]))
|
||||
|
||||
res = WordPressService.attach_custom_domain(app_row, 'secure.example.com', issue_ssl=True)
|
||||
assert res['success'] is True
|
||||
assert res['ssl']['success'] is True
|
||||
assert captured['url'] == 'https://secure.example.com' # https once the cert is obtained
|
||||
|
||||
|
||||
def test_attach_without_migrate_sets_primary_domain(app, monkeypatch):
|
||||
from app import db
|
||||
import app.services.nginx_service as nginx_mod
|
||||
from app.models.domain import Domain
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'o4')
|
||||
app_row = _mk_site_app(db, user.id, name='nomig', host='old.lvh.me')
|
||||
|
||||
monkeypatch.setattr(DNSProviderService, 'ensure_a_record',
|
||||
classmethod(lambda cls, host, ip: {'created': True, 'record': {}}))
|
||||
monkeypatch.setattr(nginx_mod.NginxService, 'create_site', classmethod(lambda cls, **kw: {'success': True}))
|
||||
monkeypatch.setattr(nginx_mod.NginxService, 'enable_site', classmethod(lambda cls, name: {'success': True}))
|
||||
called = {'change': False}
|
||||
monkeypatch.setattr(WordPressService, 'change_site_url',
|
||||
classmethod(lambda cls, *a, **k: called.update({'change': True}) or {'success': True}))
|
||||
|
||||
res = WordPressService.attach_custom_domain(app_row, 'nomig.example.com', migrate=False)
|
||||
assert res['success'] is True
|
||||
assert called['change'] is False
|
||||
assert Domain.query.filter_by(name='nomig.example.com', is_primary=True).first() is not None
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Phase 0 proving tests.
|
||||
|
||||
The Database Explorer must tell a genuinely empty database apart from a
|
||||
container/auth failure. Both used to collapse to an empty table list and render
|
||||
"Empty", silently hiding a broken connection.
|
||||
"""
|
||||
|
||||
|
||||
def test_docker_get_tables_reports_connection_failure(monkeypatch):
|
||||
from app.services.database_service import DatabaseService
|
||||
monkeypatch.setattr(DatabaseService, 'docker_mysql_execute',
|
||||
staticmethod(lambda *a, **k: {'success': False, 'error': 'No such container: ghost'}))
|
||||
res = DatabaseService.docker_mysql_get_tables('ghost', 'wordpress')
|
||||
assert res['connected'] is False
|
||||
assert res['tables'] == []
|
||||
assert 'ghost' in res['error']
|
||||
|
||||
|
||||
def test_docker_get_tables_empty_db_is_connected(monkeypatch):
|
||||
from app.services.database_service import DatabaseService
|
||||
monkeypatch.setattr(DatabaseService, 'docker_mysql_execute',
|
||||
staticmethod(lambda *a, **k: {'success': True, 'output': '', 'error': None}))
|
||||
res = DatabaseService.docker_mysql_get_tables('c', 'wordpress')
|
||||
# Connected but no tables — the case the UI now renders as "No tables yet".
|
||||
assert res['connected'] is True
|
||||
assert res['tables'] == []
|
||||
|
||||
|
||||
def test_docker_get_tables_lists_tables_with_counts(monkeypatch):
|
||||
from app.services.database_service import DatabaseService
|
||||
|
||||
def fake_exec(container, query, database=None, user='root', password=None):
|
||||
if 'SHOW TABLES' in query:
|
||||
return {'success': True, 'output': 'Tables_in_wordpress\nwp_posts\nwp_options\n', 'error': None}
|
||||
return {'success': True, 'output': 'COUNT(*)\n7\n', 'error': None}
|
||||
|
||||
monkeypatch.setattr(DatabaseService, 'docker_mysql_execute', staticmethod(fake_exec))
|
||||
res = DatabaseService.docker_mysql_get_tables('c', 'wordpress')
|
||||
assert res['connected'] is True
|
||||
assert [t['name'] for t in res['tables']] == ['wp_posts', 'wp_options']
|
||||
assert res['tables'][0]['rows'] == 7
|
||||
|
||||
|
||||
def test_docker_tables_api_surfaces_connection_state(app, client, auth_headers, monkeypatch):
|
||||
from app.services.database_service import DatabaseService
|
||||
monkeypatch.setattr(DatabaseService, 'docker_mysql_get_tables',
|
||||
staticmethod(lambda *a, **k: {'connected': False, 'tables': [], 'error': 'boom'}))
|
||||
r = client.get('/api/v1/databases/docker/ghost/wordpress/tables', headers=auth_headers)
|
||||
assert r.status_code == 200
|
||||
body = r.get_json()
|
||||
assert body['connected'] is False
|
||||
assert body['error'] == 'boom'
|
||||
assert body['tables'] == []
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Phase 2 #12: the nginx remote-upstream vhost. Pure template/validation
|
||||
checks — no nginx or filesystem needed."""
|
||||
|
||||
from app.services.nginx_service import NginxService
|
||||
|
||||
|
||||
def test_remote_upstream_template_renders():
|
||||
cfg = NginxService.REMOTE_UPSTREAM_TEMPLATE.format(
|
||||
name='jellyfin.example.com',
|
||||
domains='jellyfin.example.com',
|
||||
upstream='10.88.3.2:8096',
|
||||
)
|
||||
assert 'proxy_pass http://10.88.3.2:8096;' in cfg
|
||||
assert 'server_name jellyfin.example.com;' in cfg
|
||||
# streaming + websocket essentials (Jellyfin)
|
||||
assert 'proxy_buffering off;' in cfg
|
||||
assert 'proxy_set_header Upgrade $http_upgrade;' in cfg
|
||||
assert "proxy_set_header Connection 'upgrade';" in cfg
|
||||
|
||||
|
||||
def test_create_site_remote_requires_upstream():
|
||||
# The 'remote' branch rejects a missing upstream before touching the FS.
|
||||
res = NginxService.create_site(
|
||||
name='x', app_type='remote', domains=['x.example.com'], root_path='')
|
||||
assert res.get('success') is False
|
||||
assert 'upstream' in res.get('error', '').lower()
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
Authorization test for audit L1: pairing claim/lookup create or reveal fleet
|
||||
servers, so they should require developer role for consistency with
|
||||
POST /api/v1/servers (@developer_required) — not just any authenticated user.
|
||||
"""
|
||||
from flask_jwt_extended import create_access_token
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
|
||||
def _user(role):
|
||||
u = User(
|
||||
email=f"{role}@pair.local",
|
||||
username=f"{role}-pair",
|
||||
password_hash=generate_password_hash("x"),
|
||||
role=role,
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
return u
|
||||
|
||||
|
||||
def _headers(user):
|
||||
return {"Authorization": f"Bearer {create_access_token(identity=user.id)}"}
|
||||
|
||||
|
||||
def test_viewer_cannot_lookup_or_claim(client, app):
|
||||
with app.app_context():
|
||||
headers = _headers(_user(User.ROLE_VIEWER))
|
||||
|
||||
r1 = client.post("/api/v1/pairing/lookup", headers=headers, json={"code": "ABC123"})
|
||||
assert r1.status_code == 403, r1.get_data(as_text=True)
|
||||
|
||||
r2 = client.post("/api/v1/pairing/claim", headers=headers,
|
||||
json={"code": "ABC123", "passphrase": "pw"})
|
||||
assert r2.status_code == 403, r2.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_developer_clears_the_role_gate(client, app):
|
||||
"""A developer passes the role gate; lookup then 404s (no such code),
|
||||
which proves the gate let them through rather than blocking with 403."""
|
||||
with app.app_context():
|
||||
headers = _headers(_user(User.ROLE_DEVELOPER))
|
||||
|
||||
r = client.post("/api/v1/pairing/lookup", headers=headers, json={"code": "NOSUCH"})
|
||||
assert r.status_code != 403, r.get_data(as_text=True)
|
||||
assert r.status_code == 404, r.get_data(as_text=True)
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Proving tests for provider secret encryption-at-rest (#16/#17/#18).
|
||||
|
||||
Secrets for every connection store are Fernet-encrypted in the DB / config and
|
||||
decrypted only at point-of-use. These tests prove:
|
||||
(a) writes store ciphertext, not plaintext,
|
||||
(b) reads return the original plaintext,
|
||||
(c) the wildcard-HTTPS path (which reads DNS creds across services) gets
|
||||
PLAINTEXT, not the ciphertext blob — the regression that prompted this file,
|
||||
(d) the legacy-plaintext migration encrypts in place.
|
||||
|
||||
Note: an encrypted value only round-trips with a stable key; `decrypt_secret_safe`
|
||||
returns legacy plaintext unchanged so encrypted and not-yet-migrated values coexist.
|
||||
"""
|
||||
|
||||
|
||||
# ── crypto primitives ───────────────────────────────────────────────────────
|
||||
|
||||
def test_crypto_roundtrip_and_passthrough():
|
||||
from app.utils.crypto import encrypt_secret, decrypt_secret_safe, is_encrypted
|
||||
enc = encrypt_secret('s3cr3t')
|
||||
assert enc != 's3cr3t'
|
||||
assert is_encrypted(enc) is True
|
||||
assert decrypt_secret_safe(enc) == 's3cr3t'
|
||||
# a legacy plaintext value passes through untouched
|
||||
assert is_encrypted('legacy-plain') is False
|
||||
assert decrypt_secret_safe('legacy-plain') == 'legacy-plain'
|
||||
|
||||
|
||||
# ── DNS providers ───────────────────────────────────────────────────────────
|
||||
|
||||
def test_dns_single_secret_encrypted_at_rest(app):
|
||||
from app.models.email import DNSProviderConfig
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.utils.crypto import is_encrypted
|
||||
|
||||
res = DNSProviderService.add_provider(name='cf', provider='cloudflare', api_key='supertoken')
|
||||
assert res['success'] is True
|
||||
|
||||
row = DNSProviderConfig.query.filter_by(name='cf').first()
|
||||
assert row.api_key and row.api_key != 'supertoken' # not plaintext at rest
|
||||
assert is_encrypted(row.api_key) is True
|
||||
assert DNSProviderService.decrypted_credentials(row)['api_key'] == 'supertoken'
|
||||
|
||||
|
||||
def test_dns_secret_pair_encrypted_at_rest(app):
|
||||
from app.models.email import DNSProviderConfig
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.utils.crypto import is_encrypted
|
||||
|
||||
DNSProviderService.add_provider(name='r53', provider='route53', api_key='AKIA', api_secret='SECRET')
|
||||
row = DNSProviderConfig.query.filter_by(name='r53').first()
|
||||
assert row.api_key != 'AKIA' and is_encrypted(row.api_key)
|
||||
assert row.api_secret != 'SECRET' and is_encrypted(row.api_secret)
|
||||
|
||||
creds = DNSProviderService.decrypted_credentials(row)
|
||||
assert creds['api_key'] == 'AKIA'
|
||||
assert creds['api_secret'] == 'SECRET'
|
||||
|
||||
|
||||
def test_wildcard_setup_receives_plaintext_creds(app, monkeypatch):
|
||||
"""Regression for the cross-service read: SitesHttpsService must hand the cert
|
||||
issuer DECRYPTED creds, never the encrypted-at-rest blob."""
|
||||
from app import db
|
||||
from app.models.system_settings import SystemSettings
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.advanced_ssl_service import AdvancedSSLService
|
||||
from app.services.sites_https_service import SitesHttpsService
|
||||
|
||||
res = DNSProviderService.add_provider(name='r53', provider='route53',
|
||||
api_key='AKIA-PLAIN', api_secret='SK-PLAIN')
|
||||
pid = res['provider']['id']
|
||||
SystemSettings.set('server_public_ip', '203.0.113.5', value_type='string')
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(DNSProviderService, 'ensure_a_record',
|
||||
classmethod(lambda cls, h, ip: {'created': True, 'record': {}}))
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
AdvancedSSLService, 'issue_wildcard_cert',
|
||||
staticmethod(lambda domain, prov, creds, email=None:
|
||||
captured.update(creds=creds) or {'success': True, 'certificate_path': '/x'}))
|
||||
|
||||
out = SitesHttpsService.setup(pid, email='ops@x.com')
|
||||
assert out['success'] is True
|
||||
# decrypted creds reach the issuer — would be ciphertext under the old bug
|
||||
assert captured['creds'] == {'api_key': 'AKIA-PLAIN', 'api_secret': 'SK-PLAIN'}
|
||||
|
||||
|
||||
def test_dns_legacy_plaintext_migration(app):
|
||||
from app import db
|
||||
from app.models.email import DNSProviderConfig
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.utils.crypto import is_encrypted, decrypt_secret_safe
|
||||
|
||||
# a row written before encryption-at-rest landed (plaintext, bypassing add_provider)
|
||||
row = DNSProviderConfig(name='legacy', provider='cloudflare', api_key='plain-key')
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
assert is_encrypted(row.api_key) is False
|
||||
|
||||
n = DNSProviderService.encrypt_legacy_secrets()
|
||||
assert n >= 1
|
||||
assert is_encrypted(row.api_key) is True
|
||||
assert decrypt_secret_safe(row.api_key) == 'plain-key'
|
||||
# idempotent — a second pass changes nothing
|
||||
assert DNSProviderService.encrypt_legacy_secrets() == 0
|
||||
|
||||
|
||||
# ── cloud providers ─────────────────────────────────────────────────────────
|
||||
|
||||
def test_cloud_provider_secret_encrypted_at_rest(app):
|
||||
from app.models.cloud_server import CloudProvider
|
||||
from app.services.cloud_provisioning_service import CloudProvisioningService
|
||||
from app.utils.crypto import is_encrypted, decrypt_secret_safe
|
||||
|
||||
p = CloudProvisioningService.create_provider(
|
||||
{'provider_type': 'digitalocean', 'name': 'do', 'api_key': 'do-token-xyz'})
|
||||
row = CloudProvider.query.get(p.id)
|
||||
assert row.api_key_encrypted != 'do-token-xyz'
|
||||
assert is_encrypted(row.api_key_encrypted) is True
|
||||
assert decrypt_secret_safe(row.api_key_encrypted) == 'do-token-xyz'
|
||||
# the auth header uses the decrypted token, not the stored blob
|
||||
assert CloudProvisioningService._auth_headers(row)['Authorization'] == 'Bearer do-token-xyz'
|
||||
|
||||
|
||||
# ── storage (config-file backed) ────────────────────────────────────────────
|
||||
|
||||
def test_storage_secret_encrypted_at_rest(app, tmp_path, monkeypatch):
|
||||
import json
|
||||
from app.services.storage_provider_service import StorageProviderService
|
||||
from app.utils.crypto import is_encrypted
|
||||
|
||||
cfg_file = tmp_path / 'storage.json'
|
||||
monkeypatch.setattr(StorageProviderService, 'CONFIG_FILE', str(cfg_file))
|
||||
|
||||
StorageProviderService.save_config({
|
||||
'provider': 's3',
|
||||
's3': {'bucket': 'b', 'region': 'us-east-1', 'access_key': 'AKIA-S',
|
||||
'secret_key': 'SEKRET', 'endpoint_url': '', 'path_prefix': 'p'},
|
||||
})
|
||||
|
||||
raw = json.loads(cfg_file.read_text())
|
||||
assert raw['s3']['secret_key'] != 'SEKRET' # ciphertext on disk
|
||||
assert is_encrypted(raw['s3']['secret_key']) is True
|
||||
assert StorageProviderService.get_config()['s3']['secret_key'] == 'SEKRET' # decrypted for use
|
||||
|
||||
|
||||
# ── registrar connections ───────────────────────────────────────────────────
|
||||
|
||||
def test_registrar_secret_encrypted_at_rest(app):
|
||||
from app.services.registrar_service import RegistrarService
|
||||
from app.utils.crypto import is_encrypted, decrypt_secret
|
||||
|
||||
conn = RegistrarService.add_connection({'provider': 'godaddy', 'name': 'gd',
|
||||
'api_key': 'gd-key', 'api_secret': 'gd-secret'})
|
||||
assert conn.api_key_encrypted != 'gd-key'
|
||||
assert is_encrypted(conn.api_key_encrypted) is True
|
||||
assert decrypt_secret(conn.api_key_encrypted) == 'gd-key'
|
||||
assert decrypt_secret(conn.api_secret_encrypted) == 'gd-secret'
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Phase 1 proving tests.
|
||||
|
||||
Managed sites are published at a real hostname (<slug>.<base_domain>) instead
|
||||
of localhost:<port>: SiteDomainService resolves the host, and WordPressService
|
||||
provisions a primary Domain row + nginx reverse-proxy vhost.
|
||||
"""
|
||||
|
||||
|
||||
def _mk_user(db, username='owner'):
|
||||
from app.models import User
|
||||
from werkzeug.security import generate_password_hash
|
||||
u = User(email=f'{username}@test.local', username=username,
|
||||
password_hash=generate_password_hash('x'),
|
||||
role=User.ROLE_ADMIN, is_active=True)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
return u
|
||||
|
||||
|
||||
def _mk_app(db, user_id, name='blog', port=8300):
|
||||
from app.models import Application
|
||||
a = Application(name=name, app_type='docker', user_id=user_id,
|
||||
root_path=f'/srv/{name}', port=port)
|
||||
db.session.add(a)
|
||||
db.session.commit()
|
||||
return a
|
||||
|
||||
|
||||
# ── site domain resolution ──────────────────────────────────────────────────
|
||||
|
||||
def test_subdomain_for_uses_testing_base_domain(app):
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
# TestingConfig pins SITES_BASE_DOMAIN = lvh.me.
|
||||
assert SiteDomainService.base_domain() == 'lvh.me'
|
||||
assert SiteDomainService.subdomain_for('My Blog!') == 'my-blog.lvh.me'
|
||||
assert SiteDomainService.site_url('my-blog.lvh.me') == 'http://my-blog.lvh.me'
|
||||
|
||||
|
||||
def test_subdomain_none_when_base_domain_unset(app, monkeypatch):
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
monkeypatch.setitem(app.config, 'SITES_BASE_DOMAIN', '')
|
||||
assert SiteDomainService.base_domain() == ''
|
||||
# No base domain -> provisioning falls back to the legacy localhost URL.
|
||||
assert SiteDomainService.subdomain_for('blog') is None
|
||||
|
||||
|
||||
def test_runtime_setting_overrides_config(app):
|
||||
from app import db
|
||||
from app.models.system_settings import SystemSettings
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
SystemSettings.set('sites_base_domain', 'apps.example.com')
|
||||
db.session.commit()
|
||||
assert SiteDomainService.base_domain() == 'apps.example.com'
|
||||
assert SiteDomainService.subdomain_for('Shop') == 'shop.apps.example.com'
|
||||
|
||||
|
||||
# ── routing provisioning ────────────────────────────────────────────────────
|
||||
|
||||
def test_provision_routing_creates_primary_domain_and_docker_vhost(app, monkeypatch):
|
||||
from app import db
|
||||
from app.models.domain import Domain
|
||||
from app.services import nginx_service
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db)
|
||||
app_row = _mk_app(db, user.id, name='blog', port=8300)
|
||||
|
||||
captured = {}
|
||||
|
||||
def fake_create_site(cls, **kw):
|
||||
captured.update(kw)
|
||||
return {'success': True}
|
||||
|
||||
monkeypatch.setattr(nginx_service.NginxService, 'create_site', classmethod(fake_create_site))
|
||||
monkeypatch.setattr(nginx_service.NginxService, 'enable_site', classmethod(lambda cls, name: {'success': True}))
|
||||
|
||||
res = WordPressService._provision_routing(app_row, 'blog.lvh.me')
|
||||
assert res['warning'] is None
|
||||
assert res['domain'] == 'blog.lvh.me'
|
||||
|
||||
d = Domain.query.filter_by(application_id=app_row.id).first()
|
||||
assert d is not None
|
||||
assert d.name == 'blog.lvh.me'
|
||||
assert d.is_primary is True
|
||||
|
||||
# Reverse-proxy vhost, not php-fpm: docker app_type + the container's port.
|
||||
assert captured['app_type'] == 'docker'
|
||||
assert captured['port'] == 8300
|
||||
assert 'blog.lvh.me' in captured['domains']
|
||||
|
||||
|
||||
def test_provision_routing_warns_when_nginx_unavailable(app, monkeypatch):
|
||||
from app import db
|
||||
from app.models.domain import Domain
|
||||
from app.services import nginx_service
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'owner2')
|
||||
app_row = _mk_app(db, user.id, name='shop', port=8400)
|
||||
|
||||
monkeypatch.setattr(nginx_service.NginxService, 'create_site',
|
||||
classmethod(lambda cls, **kw: {'success': False, 'error': 'nginx not installed'}))
|
||||
|
||||
res = WordPressService._provision_routing(app_row, 'shop.lvh.me')
|
||||
# Domain still recorded; the nginx failure is a warning, never an exception.
|
||||
assert Domain.query.filter_by(name='shop.lvh.me').first() is not None
|
||||
assert res['warning'] and 'nginx' in res['warning']
|
||||
|
||||
|
||||
def test_canonical_site_url_prefers_primary_domain(app):
|
||||
from app import db
|
||||
from app.models.domain import Domain
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'owner3')
|
||||
app_row = _mk_app(db, user.id, name='acme', port=8500)
|
||||
|
||||
# No domain yet -> legacy localhost URL.
|
||||
assert WordPressService._canonical_site_url(app_row) == 'http://localhost:8500'
|
||||
|
||||
db.session.add(Domain(name='acme.lvh.me', is_primary=True, application_id=app_row.id))
|
||||
db.session.commit()
|
||||
assert WordPressService._canonical_site_url(app_row) == 'http://acme.lvh.me'
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Phase 5 proving tests — wildcard HTTPS for managed subdomains.
|
||||
|
||||
A one-time setup creates the *.<base> + <base> A records via a connected DNS
|
||||
provider and issues a wildcard cert, after which managed subdomain vhosts serve
|
||||
TLS from it.
|
||||
"""
|
||||
|
||||
|
||||
def _mk_user(db, username='owner'):
|
||||
from app.models import User
|
||||
from werkzeug.security import generate_password_hash
|
||||
u = User(email=f'{username}@test.local', username=username,
|
||||
password_hash=generate_password_hash('x'),
|
||||
role=User.ROLE_ADMIN, is_active=True)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
return u
|
||||
|
||||
|
||||
def _mk_app(db, user_id, name='blog', port=8300, host='blog.lvh.me'):
|
||||
from app.models import Application
|
||||
from app.models.domain import Domain
|
||||
a = Application(name=name, app_type='docker', user_id=user_id, root_path=f'/srv/{name}', port=port)
|
||||
db.session.add(a)
|
||||
db.session.commit()
|
||||
db.session.add(Domain(name=host, is_primary=True, application_id=a.id))
|
||||
db.session.commit()
|
||||
return a
|
||||
|
||||
|
||||
def _mk_provider(db, provider='cloudflare'):
|
||||
from app.models.email import DNSProviderConfig
|
||||
c = DNSProviderConfig(name='cf', provider=provider, api_key='tok', api_secret='sec')
|
||||
db.session.add(c)
|
||||
db.session.commit()
|
||||
return c
|
||||
|
||||
|
||||
# ── SiteDomainService HTTPS helpers ─────────────────────────────────────────
|
||||
|
||||
def test_https_helpers(app):
|
||||
from app import db
|
||||
from app.models.system_settings import SystemSettings
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
|
||||
assert SiteDomainService.https_enabled() is False
|
||||
# Testing base domain is lvh.me.
|
||||
assert SiteDomainService.covers('blog.lvh.me') is True
|
||||
assert SiteDomainService.covers('lvh.me') is True
|
||||
assert SiteDomainService.covers('other.com') is False
|
||||
fc, key = SiteDomainService.wildcard_cert_paths()
|
||||
assert fc == '/etc/letsencrypt/live/lvh.me/fullchain.pem'
|
||||
assert key == '/etc/letsencrypt/live/lvh.me/privkey.pem'
|
||||
|
||||
SystemSettings.set('sites_https_enabled', True, value_type='boolean')
|
||||
db.session.commit()
|
||||
assert SiteDomainService.https_enabled() is True
|
||||
|
||||
|
||||
# ── nginx SSL config generation (pure) ──────────────────────────────────────
|
||||
|
||||
def test_with_ssl_builds_redirect_and_443():
|
||||
from app.services.nginx_service import NginxService
|
||||
http = NginxService.DOCKER_SITE_TEMPLATE.format(name='blog', domains='blog.lvh.me', port=8300)
|
||||
out = NginxService._with_ssl(http, 'blog.lvh.me', '/c/fullchain.pem', '/c/privkey.pem')
|
||||
assert 'return 301 https://$server_name$request_uri;' in out # HTTP->HTTPS redirect
|
||||
assert 'listen 443 ssl http2;' in out # app block now on 443
|
||||
assert 'ssl_certificate /c/fullchain.pem;' in out
|
||||
assert 'ssl_certificate_key /c/privkey.pem;' in out
|
||||
assert 'proxy_pass http://127.0.0.1:8300;' in out # proxy preserved
|
||||
assert out.count('listen 80;') == 1 # only the redirect block on :80
|
||||
|
||||
|
||||
# ── issue_wildcard_cert command construction ────────────────────────────────
|
||||
|
||||
def test_issue_wildcard_cert_route53(monkeypatch):
|
||||
import app.services.advanced_ssl_service as mod
|
||||
from app.utils.system import PackageManager
|
||||
from app.services.advanced_ssl_service import AdvancedSSLService
|
||||
|
||||
monkeypatch.setattr(PackageManager, 'is_available', staticmethod(lambda: False))
|
||||
captured = {}
|
||||
|
||||
def fake_run(cmd, **kw):
|
||||
captured['cmd'] = list(cmd)
|
||||
captured['kw'] = kw
|
||||
return {'stdout': 'Congratulations'}
|
||||
|
||||
monkeypatch.setattr(mod, 'run_command', fake_run)
|
||||
|
||||
res = AdvancedSSLService.issue_wildcard_cert('example.com', 'route53',
|
||||
{'api_key': 'AK', 'api_secret': 'SK'},
|
||||
email='ops@example.com')
|
||||
assert res['success'] is True
|
||||
assert res['certificate_path'] == '/etc/letsencrypt/live/example.com/fullchain.pem'
|
||||
cmd = captured['cmd']
|
||||
assert '--dns-route53' in cmd
|
||||
assert 'example.com' in cmd and '*.example.com' in cmd
|
||||
assert '--email' in cmd and 'ops@example.com' in cmd
|
||||
assert captured['kw']['env']['AWS_ACCESS_KEY_ID'] == 'AK'
|
||||
assert captured['kw']['env']['AWS_SECRET_ACCESS_KEY'] == 'SK'
|
||||
|
||||
|
||||
# ── setup orchestration ─────────────────────────────────────────────────────
|
||||
|
||||
def test_setup_creates_records_issues_cert_persists(app, monkeypatch):
|
||||
from app import db
|
||||
from app.models.system_settings import SystemSettings
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.advanced_ssl_service import AdvancedSSLService
|
||||
from app.services.sites_https_service import SitesHttpsService
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
|
||||
provider = _mk_provider(db)
|
||||
SystemSettings.set('server_public_ip', '203.0.113.9', value_type='string')
|
||||
db.session.commit()
|
||||
|
||||
created = []
|
||||
monkeypatch.setattr(DNSProviderService, 'ensure_a_record',
|
||||
classmethod(lambda cls, host, ip: (created.append(host),
|
||||
{'created': True, 'record': {'name': host, 'value': ip}})[1]))
|
||||
cert_calls = {}
|
||||
|
||||
def fake_cert(domain, provider_name, creds, email=None):
|
||||
cert_calls.update({'domain': domain, 'provider': provider_name, 'creds': creds, 'email': email})
|
||||
return {'success': True, 'certificate_path': f'/etc/letsencrypt/live/{domain}/fullchain.pem'}
|
||||
|
||||
monkeypatch.setattr(AdvancedSSLService, 'issue_wildcard_cert', staticmethod(fake_cert))
|
||||
|
||||
res = SitesHttpsService.setup(provider.id, email='ops@x.com')
|
||||
assert res['success'] is True
|
||||
assert res['https_enabled'] is True
|
||||
assert set(created) == {'*.lvh.me', 'lvh.me'} # wildcard + apex
|
||||
assert cert_calls['domain'] == 'lvh.me'
|
||||
assert cert_calls['provider'] == 'cloudflare'
|
||||
assert cert_calls['creds'] == {'api_token': 'tok'} # reuses the connected provider's token
|
||||
assert cert_calls['email'] == 'ops@x.com'
|
||||
assert SiteDomainService.https_enabled() is True # persisted
|
||||
|
||||
|
||||
def test_setup_requires_provider(app):
|
||||
from app.services.sites_https_service import SitesHttpsService
|
||||
res = SitesHttpsService.setup(None)
|
||||
assert res['success'] is False
|
||||
assert 'provider' in res['error'].lower()
|
||||
|
||||
|
||||
def test_setup_cert_failure_does_not_enable_https(app, monkeypatch):
|
||||
from app import db
|
||||
from app.models.system_settings import SystemSettings
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.advanced_ssl_service import AdvancedSSLService
|
||||
from app.services.sites_https_service import SitesHttpsService
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
|
||||
provider = _mk_provider(db)
|
||||
SystemSettings.set('server_public_ip', '1.2.3.4', value_type='string')
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(DNSProviderService, 'ensure_a_record',
|
||||
classmethod(lambda cls, h, ip: {'created': True, 'record': {}}))
|
||||
monkeypatch.setattr(AdvancedSSLService, 'issue_wildcard_cert',
|
||||
staticmethod(lambda *a, **k: {'success': False, 'error': 'dns plugin missing'}))
|
||||
|
||||
res = SitesHttpsService.setup(provider.id)
|
||||
assert res['success'] is False
|
||||
assert 'dns plugin missing' in res['error']
|
||||
assert SiteDomainService.https_enabled() is False
|
||||
|
||||
|
||||
def test_setup_warns_without_server_ip(app, monkeypatch):
|
||||
from app import db
|
||||
from app.services.advanced_ssl_service import AdvancedSSLService
|
||||
from app.services.sites_https_service import SitesHttpsService
|
||||
from app.services.site_domain_service import SiteDomainService
|
||||
|
||||
provider = _mk_provider(db)
|
||||
monkeypatch.setattr(SiteDomainService, 'server_ip', classmethod(lambda cls: None))
|
||||
monkeypatch.setattr(AdvancedSSLService, 'issue_wildcard_cert',
|
||||
staticmethod(lambda *a, **k: {'success': True, 'certificate_path': '/x'}))
|
||||
|
||||
res = SitesHttpsService.setup(provider.id)
|
||||
assert res['success'] is True
|
||||
assert res['warning'] and 'manually' in res['warning'].lower()
|
||||
|
||||
|
||||
# ── vhost wiring ────────────────────────────────────────────────────────────
|
||||
|
||||
def test_write_vhost_uses_wildcard_cert_when_https_enabled(app, monkeypatch):
|
||||
from app import db
|
||||
from app.models.system_settings import SystemSettings
|
||||
from app.services import nginx_service
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db)
|
||||
app_row = _mk_app(db, user.id, host='blog.lvh.me') # covered by the lvh.me wildcard
|
||||
SystemSettings.set('sites_https_enabled', True, value_type='boolean')
|
||||
db.session.commit()
|
||||
|
||||
captured = {}
|
||||
monkeypatch.setattr(nginx_service.NginxService, 'create_site',
|
||||
classmethod(lambda cls, **kw: captured.update(kw) or {'success': True}))
|
||||
monkeypatch.setattr(nginx_service.NginxService, 'enable_site', classmethod(lambda cls, name: {'success': True}))
|
||||
|
||||
WordPressService._write_app_vhost(app_row)
|
||||
assert captured['ssl_cert'] == '/etc/letsencrypt/live/lvh.me/fullchain.pem'
|
||||
assert captured['ssl_key'] == '/etc/letsencrypt/live/lvh.me/privkey.pem'
|
||||
|
||||
|
||||
def test_write_vhost_no_wildcard_for_custom_domain(app, monkeypatch):
|
||||
from app import db
|
||||
from app.models.domain import Domain
|
||||
from app.models.system_settings import SystemSettings
|
||||
from app.services import nginx_service
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'o2')
|
||||
app_row = _mk_app(db, user.id, name='shop', host='blog.lvh.me')
|
||||
db.session.add(Domain(name='myshop.com', is_primary=True, application_id=app_row.id)) # not under base
|
||||
db.session.commit()
|
||||
SystemSettings.set('sites_https_enabled', True, value_type='boolean')
|
||||
db.session.commit()
|
||||
|
||||
captured = {}
|
||||
monkeypatch.setattr(nginx_service.NginxService, 'create_site',
|
||||
classmethod(lambda cls, **kw: captured.update(kw) or {'success': True}))
|
||||
monkeypatch.setattr(nginx_service.NginxService, 'enable_site', classmethod(lambda cls, name: {'success': True}))
|
||||
|
||||
WordPressService._write_app_vhost(app_row)
|
||||
assert captured['ssl_cert'] is None # a non-covered domain blocks the wildcard
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Unit tests for the tunnel broker's pure helpers (roadmap #7 / #11).
|
||||
|
||||
These import only app.services.tunnel_netutil (stdlib-only) so they prove
|
||||
the subnet allocator, interface-name derivation and health classification
|
||||
without needing a DB or connected agents.
|
||||
"""
|
||||
|
||||
from app.services import tunnel_netutil as tn
|
||||
|
||||
|
||||
def test_pick_subnet_first_free():
|
||||
cidr, edge, priv = tn.pick_subnet([])
|
||||
assert cidr == '10.88.0.0/24'
|
||||
assert edge == '10.88.0.1'
|
||||
assert priv == '10.88.0.2'
|
||||
|
||||
|
||||
def test_pick_subnet_skips_used():
|
||||
cidr, edge, priv = tn.pick_subnet(['10.88.0.0/24', '10.88.1.0/24'])
|
||||
assert cidr == '10.88.2.0/24'
|
||||
assert edge == '10.88.2.1'
|
||||
assert priv == '10.88.2.2'
|
||||
|
||||
|
||||
def test_pick_subnet_exhausted():
|
||||
used = ['10.88.%d.0/24' % i for i in range(256)]
|
||||
try:
|
||||
tn.pick_subnet(used)
|
||||
assert False, "expected RuntimeError on exhausted pool"
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
|
||||
def test_interface_name_is_stable_and_kernel_valid():
|
||||
name = tn.interface_name_for('3fa9c2b1-dead-beef-0000-111122223333')
|
||||
assert name == 'skwg3fa9c2b1'
|
||||
assert len(name) <= 15
|
||||
assert name.replace('skwg', '').isalnum()
|
||||
|
||||
|
||||
def test_derive_status():
|
||||
now = 1_000_000
|
||||
assert tn.derive_status(now - 10, now) == 'up'
|
||||
assert tn.derive_status(now - 10_000, now) == 'degraded'
|
||||
assert tn.derive_status(0, now) == 'pending'
|
||||
assert tn.derive_status(now, now, interface_up=False) == 'down'
|
||||
|
||||
|
||||
def test_validate_endpoint_host():
|
||||
assert tn.validate_endpoint_host('203.0.113.5') is True
|
||||
assert tn.validate_endpoint_host('10.0.0.5') is True # private edge OK
|
||||
assert tn.validate_endpoint_host('127.0.0.1') is False # loopback
|
||||
assert tn.validate_endpoint_host('0.0.0.0') is False # unspecified
|
||||
assert tn.validate_endpoint_host('') is False
|
||||
assert tn.validate_endpoint_host('not-an-ip') is False
|
||||
|
||||
|
||||
def test_pick_listen_port():
|
||||
assert tn.pick_listen_port([]) == 51820
|
||||
assert tn.pick_listen_port([51820]) == 51821
|
||||
assert tn.pick_listen_port([51820, 51821, 51823]) == 51822 # fills the gap
|
||||
|
||||
|
||||
def test_pick_listen_port_exhausted():
|
||||
used = list(range(tn.DEFAULT_LISTEN_PORT, tn.DEFAULT_LISTEN_PORT + tn.LISTEN_PORT_RANGE))
|
||||
try:
|
||||
tn.pick_listen_port(used)
|
||||
assert False, "expected RuntimeError on exhausted port pool"
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
|
||||
def test_diagnose_reachability():
|
||||
assert tn.diagnose_reachability(0, None, False)['state'] == 'interface_down'
|
||||
assert tn.diagnose_reachability(1_700_000_000, 999, True)['state'] == 'ok'
|
||||
assert tn.diagnose_reachability(0, 5, True)['state'] == 'connecting'
|
||||
d = tn.diagnose_reachability(0, 600, True)
|
||||
assert d['state'] == 'no_handshake'
|
||||
assert 'blocked' in d['hint'].lower()
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Phase 3 #19: panel-authoritative tunnel reconcile.
|
||||
|
||||
Proves reconcile_server re-issues the right agent commands for each side
|
||||
of a tunnel, by monkeypatching agent_registry.send_command to record calls
|
||||
(no live agent needed).
|
||||
"""
|
||||
|
||||
from app import db
|
||||
from app.models.server import Server
|
||||
from app.models.tunnel import Tunnel
|
||||
from app.models.exposed_service import ExposedService
|
||||
from app.services import agent_registry as ar_mod
|
||||
from app.services.tunnel_broker_service import TunnelBrokerService
|
||||
|
||||
|
||||
def _server(name, ip=None):
|
||||
s = Server(name=name, ip_address=ip, status='online')
|
||||
db.session.add(s)
|
||||
db.session.commit()
|
||||
return s
|
||||
|
||||
|
||||
def _record_send(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_send(server_id, action, params=None, user_id=None, timeout=30.0):
|
||||
calls.append({'server_id': server_id, 'action': action, 'params': params or {}})
|
||||
return {'success': True, 'data': {}}
|
||||
|
||||
monkeypatch.setattr(ar_mod.agent_registry, 'send_command', fake_send)
|
||||
return calls
|
||||
|
||||
|
||||
def _tunnel(edge, priv, iface, third):
|
||||
t = Tunnel(
|
||||
edge_server_id=edge.id, private_server_id=priv.id,
|
||||
interface_name=iface, subnet='10.88.%d.0/24' % third,
|
||||
edge_wg_ip='10.88.%d.1' % third, private_wg_ip='10.88.%d.2' % third,
|
||||
listen_port=51820, edge_pubkey='EDGEPUB', private_pubkey='PRIVPUB',
|
||||
status='up',
|
||||
)
|
||||
db.session.add(t)
|
||||
db.session.commit()
|
||||
return t
|
||||
|
||||
|
||||
def test_reconcile_private_side(app, monkeypatch):
|
||||
calls = _record_send(monkeypatch)
|
||||
edge = _server('edge', ip='203.0.113.9')
|
||||
priv = _server('home')
|
||||
t = _tunnel(edge, priv, 'skwgrec01', 7)
|
||||
db.session.add(ExposedService(tunnel_id=t.id, hostname='jelly.example.com', port=8096, status='published'))
|
||||
db.session.commit()
|
||||
|
||||
res = TunnelBrokerService.reconcile_server(priv.id)
|
||||
assert res and res[0]['ok']
|
||||
|
||||
actions = [c['action'] for c in calls]
|
||||
assert 'wireguard:interface:up' in actions
|
||||
assert 'wireguard:peer:set' in actions
|
||||
assert 'wireguard:forward' in actions
|
||||
|
||||
peer = next(c['params'] for c in calls if c['action'] == 'wireguard:peer:set')
|
||||
assert peer['public_key'] == 'EDGEPUB' # private peers with the edge
|
||||
assert peer['endpoint'] == '203.0.113.9:51820' # dials the edge endpoint
|
||||
assert peer['persistent_keepalive'] == 25
|
||||
|
||||
fwd = next(c['params'] for c in calls if c['action'] == 'wireguard:forward')
|
||||
assert fwd['listen_port'] == 8096 and fwd['target_port'] == 8096
|
||||
assert fwd['listen_ip'] == '10.88.7.2'
|
||||
|
||||
|
||||
def test_reconcile_edge_side(app, monkeypatch):
|
||||
calls = _record_send(monkeypatch)
|
||||
edge = _server('edge2', ip='198.51.100.4')
|
||||
priv = _server('home2')
|
||||
_tunnel(edge, priv, 'skwgrec02', 8)
|
||||
|
||||
TunnelBrokerService.reconcile_server(edge.id)
|
||||
|
||||
actions = [c['action'] for c in calls]
|
||||
assert 'wireguard:interface:up' in actions
|
||||
assert 'wireguard:peer:set' in actions
|
||||
assert 'firewall:allow_port' in actions # edge re-opens its UDP port
|
||||
|
||||
peer = next(c['params'] for c in calls if c['action'] == 'wireguard:peer:set')
|
||||
assert peer['public_key'] == 'PRIVPUB' # edge peers with the private host
|
||||
assert 'endpoint' not in peer # edge has no endpoint for the private peer
|
||||
|
||||
|
||||
def test_reconcile_skips_errored_tunnels(app, monkeypatch):
|
||||
calls = _record_send(monkeypatch)
|
||||
edge = _server('edge3', ip='192.0.2.7')
|
||||
priv = _server('home3')
|
||||
t = _tunnel(edge, priv, 'skwgrec03', 9)
|
||||
t.status = 'error'
|
||||
db.session.commit()
|
||||
|
||||
res = TunnelBrokerService.reconcile_server(priv.id)
|
||||
assert res == []
|
||||
assert calls == []
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Phase 2 proving tests — the WordPress URL-swap tool.
|
||||
|
||||
Changing a site's URL is a serialization-safe DB rewrite (WP-CLI search-replace),
|
||||
backed up first and rolled back on failure, then a Domain/nginx re-point.
|
||||
"""
|
||||
|
||||
|
||||
def _mk_user(db, username='owner'):
|
||||
from app.models import User
|
||||
from werkzeug.security import generate_password_hash
|
||||
u = User(email=f'{username}@test.local', username=username,
|
||||
password_hash=generate_password_hash('x'),
|
||||
role=User.ROLE_ADMIN, is_active=True)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
return u
|
||||
|
||||
|
||||
def _mk_site_app(db, user_id, name='blog', port=8300, host='blog.lvh.me'):
|
||||
from app.models import Application
|
||||
from app.models.domain import Domain
|
||||
a = Application(name=name, app_type='docker', user_id=user_id,
|
||||
root_path=f'/srv/{name}', port=port)
|
||||
db.session.add(a)
|
||||
db.session.commit()
|
||||
db.session.add(Domain(name=host, is_primary=True, application_id=a.id))
|
||||
db.session.commit()
|
||||
return a
|
||||
|
||||
|
||||
# ── pure helpers ────────────────────────────────────────────────────────────
|
||||
|
||||
def test_normalize_url():
|
||||
from app.services.wordpress_service import WordPressService
|
||||
assert WordPressService._normalize_url('example.com') == 'http://example.com'
|
||||
assert WordPressService._normalize_url('https://example.com/') == 'https://example.com'
|
||||
assert WordPressService._normalize_url(' https://a.com/blog/ ') == 'https://a.com/blog'
|
||||
assert WordPressService._normalize_url('not a url') is None
|
||||
assert WordPressService._normalize_url('') is None
|
||||
|
||||
|
||||
def test_url_swap_pairs():
|
||||
from app.services.wordpress_service import WordPressService
|
||||
# Host change -> full-URL pair (covers scheme) + host-only pair.
|
||||
assert WordPressService._url_swap_pairs('http://old.com', 'https://new.com') == [
|
||||
('http://old.com', 'https://new.com'), ('old.com', 'new.com')]
|
||||
# Scheme-only change -> single full-URL pair (same host).
|
||||
assert WordPressService._url_swap_pairs('http://a.com', 'https://a.com') == [
|
||||
('http://a.com', 'https://a.com')]
|
||||
|
||||
|
||||
def test_parse_sr_count():
|
||||
from app.services.wordpress_service import WordPressService
|
||||
assert WordPressService._parse_sr_count('Success: 12 replacements to be made.') == 12
|
||||
assert WordPressService._parse_sr_count('Table\tx\nSuccess: Made 1,234 replacements.') == 1234
|
||||
assert WordPressService._parse_sr_count('') == 0
|
||||
assert WordPressService._parse_sr_count('nothing here') == 0
|
||||
|
||||
|
||||
# ── preview ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_preview_counts_per_pair(app, monkeypatch):
|
||||
from app import db
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db)
|
||||
app_row = _mk_site_app(db, user.id, host='old.lvh.me')
|
||||
|
||||
def fake_wp_cli(cls, path, command, *a, **k):
|
||||
if command[:2] == ['option', 'get']:
|
||||
return {'success': True, 'output': 'http://old.lvh.me\n'}
|
||||
if command[0] == 'search-replace':
|
||||
return {'success': True, 'output': 'Success: 5 replacements to be made.'}
|
||||
return {'success': True, 'output': ''}
|
||||
|
||||
monkeypatch.setattr(WordPressService, 'wp_cli', classmethod(fake_wp_cli))
|
||||
|
||||
res = WordPressService.preview_url_change(app_row, 'http://new.lvh.me')
|
||||
assert res['success'] is True
|
||||
assert res['current_url'] == 'http://old.lvh.me'
|
||||
assert res['new_url'] == 'http://new.lvh.me'
|
||||
assert len(res['pairs']) == 2 # full URL + host-only
|
||||
assert res['total'] == 10 # 5 per pair
|
||||
|
||||
|
||||
def test_preview_rejects_same_url(app, monkeypatch):
|
||||
from app import db
|
||||
from app.services.wordpress_service import WordPressService
|
||||
user = _mk_user(db, 'o2')
|
||||
app_row = _mk_site_app(db, user.id, host='same.lvh.me')
|
||||
monkeypatch.setattr(WordPressService, 'wp_cli',
|
||||
classmethod(lambda cls, path, command, *a, **k: {'success': True, 'output': 'http://same.lvh.me'}))
|
||||
res = WordPressService.preview_url_change(app_row, 'http://same.lvh.me')
|
||||
assert res['success'] is False
|
||||
assert 'same' in res['error'].lower()
|
||||
|
||||
|
||||
# ── apply ───────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_change_url_happy_path_repoints_domain(app, monkeypatch):
|
||||
from app import db
|
||||
from app.models.domain import Domain
|
||||
from app.services import nginx_service
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'o3')
|
||||
app_row = _mk_site_app(db, user.id, name='shop', host='old.lvh.me')
|
||||
|
||||
def fake_wp_cli(cls, path, command, *a, **k):
|
||||
if command[:2] == ['option', 'get']:
|
||||
return {'success': True, 'output': 'http://old.lvh.me'}
|
||||
if command[0] == 'search-replace':
|
||||
return {'success': True, 'output': 'Success: Made 6 replacements.'}
|
||||
return {'success': True, 'output': ''}
|
||||
|
||||
monkeypatch.setattr(WordPressService, 'wp_cli', classmethod(fake_wp_cli))
|
||||
monkeypatch.setattr(WordPressService, 'backup_wordpress',
|
||||
classmethod(lambda cls, path, include_db=True: {'success': True, 'backup_name': 'bk1'}))
|
||||
monkeypatch.setattr(nginx_service.NginxService, 'create_site',
|
||||
classmethod(lambda cls, **kw: {'success': True}))
|
||||
monkeypatch.setattr(nginx_service.NginxService, 'enable_site',
|
||||
classmethod(lambda cls, name: {'success': True}))
|
||||
|
||||
res = WordPressService.change_site_url(app_row, 'https://new.example.com', keep_old_redirect=False)
|
||||
assert res['success'] is True
|
||||
assert res['old_url'] == 'http://old.lvh.me'
|
||||
assert res['new_url'] == 'https://new.example.com'
|
||||
assert res['replacements'] == 12 # 6 per pair * 2 pairs (host changed)
|
||||
assert res['backup'] == 'bk1'
|
||||
|
||||
# Domain re-pointed: new host primary, old removed (keep_old_redirect=False).
|
||||
names = {d.name: d.is_primary for d in Domain.query.filter_by(application_id=app_row.id).all()}
|
||||
assert names == {'new.example.com': True}
|
||||
|
||||
|
||||
def test_change_url_rolls_back_on_failure(app, monkeypatch):
|
||||
from app import db
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'o4')
|
||||
app_row = _mk_site_app(db, user.id, name='blogx', host='old.lvh.me')
|
||||
|
||||
restored = {'called': False}
|
||||
|
||||
def fake_wp_cli(cls, path, command, *a, **k):
|
||||
if command[:2] == ['option', 'get']:
|
||||
return {'success': True, 'output': 'http://old.lvh.me'}
|
||||
if command[0] == 'search-replace':
|
||||
return {'success': False, 'error': 'boom'}
|
||||
return {'success': True, 'output': ''}
|
||||
|
||||
def fake_restore(cls, name, target):
|
||||
restored['called'] = True
|
||||
return {'success': True}
|
||||
|
||||
monkeypatch.setattr(WordPressService, 'wp_cli', classmethod(fake_wp_cli))
|
||||
monkeypatch.setattr(WordPressService, 'backup_wordpress',
|
||||
classmethod(lambda cls, path, include_db=True: {'success': True, 'backup_name': 'bk2'}))
|
||||
monkeypatch.setattr(WordPressService, 'restore_backup', classmethod(fake_restore))
|
||||
|
||||
res = WordPressService.change_site_url(app_row, 'https://new.example.com')
|
||||
assert res['success'] is False
|
||||
assert restored['called'] is True
|
||||
assert res['rolled_back'] is True
|
||||
assert 'boom' in res['error']
|
||||
|
||||
|
||||
def test_change_url_aborts_if_backup_fails(app, monkeypatch):
|
||||
from app import db
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'o5')
|
||||
app_row = _mk_site_app(db, user.id, name='blogy', host='old.lvh.me')
|
||||
|
||||
monkeypatch.setattr(WordPressService, 'wp_cli',
|
||||
classmethod(lambda cls, path, command, *a, **k: {'success': True, 'output': 'http://old.lvh.me'}))
|
||||
monkeypatch.setattr(WordPressService, 'backup_wordpress',
|
||||
classmethod(lambda cls, path, include_db=True: {'success': False, 'error': 'disk full'}))
|
||||
|
||||
res = WordPressService.change_site_url(app_row, 'https://new.example.com')
|
||||
assert res['success'] is False
|
||||
assert 'backup failed' in res['error'].lower()
|
||||
|
||||
|
||||
def test_repoint_keep_old_demotes_but_keeps(app):
|
||||
from app import db
|
||||
from app.models.domain import Domain
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
user = _mk_user(db, 'o6')
|
||||
app_row = _mk_site_app(db, user.id, name='keepblog', host='old.lvh.me')
|
||||
|
||||
warn = WordPressService._repoint_primary_domain(app_row, 'new.lvh.me', keep_old=True)
|
||||
assert warn is None
|
||||
rows = {d.name: d.is_primary for d in Domain.query.filter_by(application_id=app_row.id).all()}
|
||||
assert rows == {'old.lvh.me': False, 'new.lvh.me': True}
|
||||
|
||||
|
||||
# ── API wiring ──────────────────────────────────────────────────────────────
|
||||
|
||||
def test_url_preview_api_smoke(app, client, auth_headers, monkeypatch):
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.wordpress_service import WordPressService
|
||||
|
||||
admin = User.query.filter_by(username='testadmin').first()
|
||||
app_row = _mk_site_app(db, admin.id, name='apisite', host='api.lvh.me')
|
||||
monkeypatch.setattr(WordPressService, 'preview_url_change',
|
||||
classmethod(lambda cls, a, new_url: {'success': True, 'total': 3, 'pairs': [],
|
||||
'current_url': 'http://api.lvh.me', 'new_url': new_url}))
|
||||
r = client.post(f'/api/v1/wordpress/sites/{app_row.id}/url/preview',
|
||||
json={'new_url': 'http://x.com'}, headers=auth_headers)
|
||||
assert r.status_code == 200
|
||||
body = r.get_json()
|
||||
assert body['total'] == 3
|
||||
assert body['new_url'] == 'http://x.com'
|
||||
@@ -349,3 +349,163 @@ def test_wordpress_sites_scoping_api(app, client):
|
||||
r = client.get('/api/v1/wordpress/sites', headers={**_token(admin.id), 'X-Workspace-Id': str(ws_a.id)})
|
||||
assert r.status_code == 200
|
||||
assert {s['name'] for s in r.get_json()['sites']} == {'site-a'}
|
||||
|
||||
|
||||
# ---- API: domains (app-children, scoped through parent Application) --------
|
||||
|
||||
def test_domains_scoping_api(app, client):
|
||||
from app import db
|
||||
from app.services.workspace_service import WorkspaceService
|
||||
from app.services.resource_grant_service import ResourceGrantService
|
||||
from app.models import Application, Domain
|
||||
|
||||
admin = _mk_user(db, 'dom_admin', 'admin')
|
||||
dev = _mk_user(db, 'dom_dev', 'developer')
|
||||
other = _mk_user(db, 'dom_other', 'developer')
|
||||
ws_a = WorkspaceService.create_workspace({'name': 'DomA'}, admin.id)
|
||||
ws_b = WorkspaceService.create_workspace({'name': 'DomB'}, admin.id)
|
||||
WorkspaceService.add_member(ws_a.id, dev.id, 'member')
|
||||
|
||||
def mk(name, owner_id, ws_id, domain):
|
||||
a = Application(name=name, app_type='docker', user_id=owner_id, workspace_id=ws_id)
|
||||
db.session.add(a)
|
||||
db.session.commit()
|
||||
db.session.add(Domain(name=domain, application_id=a.id))
|
||||
db.session.commit()
|
||||
return a
|
||||
|
||||
mk('dom-a', dev.id, ws_a.id, 'a.example.com')
|
||||
mk('dom-b', dev.id, ws_b.id, 'b.example.com')
|
||||
shared = mk('dom-shared', other.id, ws_a.id, 'shared.example.com')
|
||||
|
||||
# No context: dev sees its own apps' domains across workspaces, not other's.
|
||||
r = client.get('/api/v1/domains', headers=_token(dev.id))
|
||||
assert r.status_code == 200
|
||||
assert {d['name'] for d in r.get_json()['domains']} == {'a.example.com', 'b.example.com'}
|
||||
|
||||
# Scoped to ws_a: only domains of dev's apps in ws_a.
|
||||
r = client.get('/api/v1/domains', headers={**_token(dev.id), 'X-Workspace-Id': str(ws_a.id)})
|
||||
assert {d['name'] for d in r.get_json()['domains']} == {'a.example.com'}
|
||||
|
||||
# A grant on another user's app surfaces that app's domain too (and it's in ws_a).
|
||||
ResourceGrantService.grant(dev.id, 'application', shared.id, granted_by=admin.id, role='viewer')
|
||||
r = client.get('/api/v1/domains', headers={**_token(dev.id), 'X-Workspace-Id': str(ws_a.id)})
|
||||
assert {d['name'] for d in r.get_json()['domains']} == {'a.example.com', 'shared.example.com'}
|
||||
|
||||
# Admin with no context sees every domain.
|
||||
r = client.get('/api/v1/domains', headers=_token(admin.id))
|
||||
got = {d['name'] for d in r.get_json()['domains']}
|
||||
assert {'a.example.com', 'b.example.com', 'shared.example.com'} <= got
|
||||
|
||||
|
||||
# ---- API: docker databases (app-children) ---------------------------------
|
||||
|
||||
def test_docker_databases_scoping_api(app, client, monkeypatch):
|
||||
from app import db
|
||||
from app.services.workspace_service import WorkspaceService
|
||||
from app.services.database_service import DatabaseService
|
||||
from app.models import Application
|
||||
|
||||
admin = _mk_user(db, 'ddb_admin', 'admin')
|
||||
dev = _mk_user(db, 'ddb_dev', 'developer')
|
||||
ws_a = WorkspaceService.create_workspace({'name': 'DdbA'}, admin.id)
|
||||
ws_b = WorkspaceService.create_workspace({'name': 'DdbB'}, admin.id)
|
||||
WorkspaceService.add_member(ws_a.id, dev.id, 'member')
|
||||
|
||||
db.session.add_all([
|
||||
Application(name='ddb-a', app_type='docker', user_id=dev.id, workspace_id=ws_a.id, root_path='/srv/a'),
|
||||
Application(name='ddb-b', app_type='docker', user_id=dev.id, workspace_id=ws_b.id, root_path='/srv/b'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
# Stub the compose/.env read so each app yields one database tagged by app name.
|
||||
monkeypatch.setattr(DatabaseService, 'get_app_database_info',
|
||||
lambda name, root: [{'database': name}])
|
||||
|
||||
# No context: dev sees both its docker apps' databases.
|
||||
r = client.get('/api/v1/databases/docker/databases', headers=_token(dev.id))
|
||||
assert r.status_code == 200
|
||||
assert {d['app_name'] for d in r.get_json()['databases']} == {'ddb-a', 'ddb-b'}
|
||||
|
||||
# Scoped to ws_a -> only ddb-a's database.
|
||||
r = client.get('/api/v1/databases/docker/databases',
|
||||
headers={**_token(dev.id), 'X-Workspace-Id': str(ws_a.id)})
|
||||
assert {d['app_name'] for d in r.get_json()['databases']} == {'ddb-a'}
|
||||
|
||||
|
||||
# ---- role reconciliation (#33) --------------------------------------------
|
||||
|
||||
def test_effective_role_reconciliation(app):
|
||||
from app import db
|
||||
from app.services.workspace_service import WorkspaceService
|
||||
|
||||
sysadmin = _mk_user(db, 'er_admin', 'admin')
|
||||
dev_viewer = _mk_user(db, 'er_devv', 'developer')
|
||||
dev_member = _mk_user(db, 'er_devm', 'developer')
|
||||
global_viewer = _mk_user(db, 'er_gv', 'viewer')
|
||||
ws = WorkspaceService.create_workspace({'name': 'ER'}, sysadmin.id)
|
||||
WorkspaceService.add_member(ws.id, dev_viewer.id, 'viewer')
|
||||
WorkspaceService.add_member(ws.id, dev_member.id, 'member')
|
||||
WorkspaceService.add_member(ws.id, global_viewer.id, 'owner')
|
||||
|
||||
# No context -> global role unchanged.
|
||||
assert WorkspaceService.effective_role(dev_member, None) == 'developer'
|
||||
assert WorkspaceService.can_write_in_workspace(dev_member, None) is True
|
||||
|
||||
# A 'viewer' membership caps a global developer to viewer (read-only).
|
||||
assert WorkspaceService.effective_role(dev_viewer, ws.id) == 'viewer'
|
||||
assert WorkspaceService.can_write_in_workspace(dev_viewer, ws.id) is False
|
||||
|
||||
# A 'member' membership does not cap (stays developer).
|
||||
assert WorkspaceService.effective_role(dev_member, ws.id) == 'developer'
|
||||
assert WorkspaceService.can_write_in_workspace(dev_member, ws.id) is True
|
||||
|
||||
# Narrow-only: a workspace role NEVER elevates. A global viewer who is even an
|
||||
# 'owner' member is still effectively a viewer.
|
||||
assert WorkspaceService.effective_role(global_viewer, ws.id) == 'viewer'
|
||||
assert WorkspaceService.can_write_in_workspace(global_viewer, ws.id) is False
|
||||
|
||||
# A system admin is never capped by a workspace membership.
|
||||
assert WorkspaceService.effective_role(sysadmin, ws.id) == 'admin'
|
||||
assert WorkspaceService.can_write_in_workspace(sysadmin, ws.id) is True
|
||||
|
||||
|
||||
def test_create_app_viewer_blocked_in_workspace(app, client):
|
||||
from app import db
|
||||
from app.services.workspace_service import WorkspaceService
|
||||
|
||||
admin = _mk_user(db, 'vb_admin', 'admin')
|
||||
dev = _mk_user(db, 'vb_dev', 'developer')
|
||||
ws = WorkspaceService.create_workspace({'name': 'VB'}, admin.id)
|
||||
WorkspaceService.add_member(ws.id, dev.id, 'viewer')
|
||||
|
||||
# A 'viewer' member can't create in that workspace.
|
||||
r = client.post('/api/v1/apps', headers={**_token(dev.id), 'X-Workspace-Id': str(ws.id)},
|
||||
json={'name': 'vb-nope', 'app_type': 'php'})
|
||||
assert r.status_code == 403
|
||||
|
||||
# With no workspace context the same user still creates (the cap is
|
||||
# workspace-scoped and narrow-only — no-context behavior is unchanged).
|
||||
r = client.post('/api/v1/apps', headers=_token(dev.id), json={'name': 'vb-yes', 'app_type': 'php'})
|
||||
assert r.status_code == 201
|
||||
app_id = r.get_json()['app']['id']
|
||||
|
||||
# And the app can't be moved INTO the workspace they're a viewer of.
|
||||
r = client.put(f'/api/v1/apps/{app_id}/workspace', json={'workspace_id': ws.id}, headers=_token(dev.id))
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_list_workspaces_surfaces_effective_role(app, client):
|
||||
from app import db
|
||||
from app.services.workspace_service import WorkspaceService
|
||||
|
||||
admin = _mk_user(db, 'lw_admin', 'admin')
|
||||
dev = _mk_user(db, 'lw_dev', 'developer')
|
||||
ws = WorkspaceService.create_workspace({'name': 'LW'}, admin.id)
|
||||
WorkspaceService.add_member(ws.id, dev.id, 'viewer')
|
||||
|
||||
r = client.get('/api/v1/workspaces/', headers=_token(dev.id))
|
||||
assert r.status_code == 200
|
||||
rows = {w['name']: w for w in r.get_json()['workspaces']}
|
||||
assert rows['LW']['my_role'] == 'viewer'
|
||||
assert rows['LW']['my_effective_role'] == 'viewer'
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Tests for #17 wp-content zip import — zip-slip safety, wp-content resolution,
|
||||
and the container-copy flow (docker cp mocked; extraction/resolution is real)."""
|
||||
import os
|
||||
import zipfile
|
||||
|
||||
|
||||
def _make_zip(path, entries):
|
||||
"""entries: {arcname: content_str}."""
|
||||
with zipfile.ZipFile(path, 'w') as zf:
|
||||
for arc, content in entries.items():
|
||||
zf.writestr(arc, content)
|
||||
|
||||
|
||||
# ---- zip-slip safety -------------------------------------------------------
|
||||
|
||||
def test_safe_extract_rejects_parent_traversal(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
z = tmp_path / 'evil.zip'
|
||||
_make_zip(str(z), {'../escape.txt': 'x', 'wp-content/ok.txt': 'y'})
|
||||
dest = tmp_path / 'out'
|
||||
dest.mkdir()
|
||||
res = WordPressService._safe_extract_zip(str(z), str(dest))
|
||||
assert res['success'] is False and 'Unsafe path' in res['error']
|
||||
assert not (tmp_path / 'escape.txt').exists() # nothing escaped the dest
|
||||
|
||||
|
||||
def test_safe_extract_rejects_deep_traversal(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
z = tmp_path / 'evil2.zip'
|
||||
_make_zip(str(z), {'wp-content/../../../../tmp/evil.txt': 'x'})
|
||||
dest = tmp_path / 'out2'
|
||||
dest.mkdir()
|
||||
res = WordPressService._safe_extract_zip(str(z), str(dest))
|
||||
assert res['success'] is False
|
||||
|
||||
|
||||
def test_safe_extract_ok(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
z = tmp_path / 'good.zip'
|
||||
_make_zip(str(z), {'wp-content/plugins/p/p.php': '<?php',
|
||||
'wp-content/themes/t/style.css': 'body{}'})
|
||||
dest = tmp_path / 'out3'
|
||||
dest.mkdir()
|
||||
res = WordPressService._safe_extract_zip(str(z), str(dest))
|
||||
assert res['success'] is True
|
||||
assert (dest / 'wp-content' / 'plugins' / 'p' / 'p.php').exists()
|
||||
|
||||
|
||||
def test_safe_extract_rejects_bad_zip(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
bad = tmp_path / 'notazip.zip'
|
||||
bad.write_text('this is not a zip')
|
||||
dest = tmp_path / 'out4'
|
||||
dest.mkdir()
|
||||
res = WordPressService._safe_extract_zip(str(bad), str(dest))
|
||||
assert res['success'] is False and 'valid zip' in res['error']
|
||||
|
||||
|
||||
# ---- wp-content resolution (3 archive layouts) -----------------------------
|
||||
|
||||
def test_resolve_wp_content_at_root(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
(tmp_path / 'wp-content' / 'plugins').mkdir(parents=True)
|
||||
assert WordPressService._resolve_wp_content_dir(str(tmp_path)) == str(tmp_path / 'wp-content')
|
||||
|
||||
|
||||
def test_resolve_full_site_wrapper_folder(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
(tmp_path / 'mysite' / 'wp-content' / 'themes').mkdir(parents=True)
|
||||
assert WordPressService._resolve_wp_content_dir(str(tmp_path)) == str(tmp_path / 'mysite' / 'wp-content')
|
||||
|
||||
|
||||
def test_resolve_root_is_wp_content(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
(tmp_path / 'plugins').mkdir()
|
||||
(tmp_path / 'themes').mkdir()
|
||||
assert WordPressService._resolve_wp_content_dir(str(tmp_path)) == str(tmp_path)
|
||||
|
||||
|
||||
def test_resolve_none_when_unrecognizable(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
(tmp_path / 'random').mkdir()
|
||||
assert WordPressService._resolve_wp_content_dir(str(tmp_path)) is None
|
||||
|
||||
|
||||
# ---- container copy flow (docker cp mocked) --------------------------------
|
||||
|
||||
def test_import_wp_content_zip_issues_cp_and_chown(tmp_path, monkeypatch):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
import app.services.wordpress_service as wp_mod
|
||||
z = tmp_path / 'c.zip'
|
||||
_make_zip(str(z), {'wp-content/plugins/p/p.php': '<?php'})
|
||||
|
||||
calls = []
|
||||
|
||||
class _Res:
|
||||
returncode = 0
|
||||
stderr = ''
|
||||
stdout = ''
|
||||
|
||||
monkeypatch.setattr(wp_mod.subprocess, 'run', lambda cmd, **kw: (calls.append(list(cmd)), _Res())[1])
|
||||
res = WordPressService._import_wp_content_zip(str(z), 'mysite')
|
||||
assert res['success'] is True
|
||||
assert any(c[:2] == ['docker', 'cp'] for c in calls)
|
||||
assert any(c[:3] == ['docker', 'exec', 'mysite'] for c in calls) # ownership fix
|
||||
|
||||
|
||||
def test_import_wp_content_zip_propagates_cp_failure(tmp_path, monkeypatch):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
import app.services.wordpress_service as wp_mod
|
||||
z = tmp_path / 'c.zip'
|
||||
_make_zip(str(z), {'wp-content/uploads/x.jpg': 'data'})
|
||||
|
||||
class _Res:
|
||||
returncode = 1
|
||||
stderr = 'no such container'
|
||||
stdout = ''
|
||||
|
||||
monkeypatch.setattr(wp_mod.subprocess, 'run', lambda cmd, **kw: _Res())
|
||||
res = WordPressService._import_wp_content_zip(str(z), 'ghost')
|
||||
assert res['success'] is False and 'no such container' in res['error']
|
||||
|
||||
|
||||
def test_import_wp_content_zip_no_wp_content_found(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
z = tmp_path / 'empty.zip'
|
||||
_make_zip(str(z), {'readme.txt': 'hello'})
|
||||
# No subprocess mock needed: resolution fails before any docker call.
|
||||
res = WordPressService._import_wp_content_zip(str(z), 'site')
|
||||
assert res['success'] is False and 'No wp-content' in res['error']
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Tests for #25 PHP-fatals ingest — parsing the WP_DEBUG log (docker exec mocked)."""
|
||||
|
||||
_SAMPLE = (
|
||||
'__SK_WPDEBUG__\n'
|
||||
'[15-Jun-2026 12:00:01 UTC] PHP Fatal error: Uncaught Error: Call to undefined '
|
||||
'function foo() in /var/www/html/wp-content/plugins/x/x.php:12\n'
|
||||
'Stack trace:\n'
|
||||
'#0 /var/www/html/index.php(17): require()\n'
|
||||
'#1 {main}\n'
|
||||
' thrown in /var/www/html/wp-content/plugins/x/x.php on line 12\n'
|
||||
'[15-Jun-2026 12:05:00 UTC] PHP Warning: Undefined array key "k" in /t/functions.php on line 5\n'
|
||||
'[15-Jun-2026 12:06:00 UTC] PHP Deprecated: Function xyz() is deprecated in /x on line 1\n'
|
||||
'[15-Jun-2026 12:07:00 UTC] PHP Notice: Undefined variable $z in /x on line 2\n'
|
||||
)
|
||||
|
||||
|
||||
class _Res:
|
||||
def __init__(self, rc, out):
|
||||
self.returncode = rc
|
||||
self.stdout = out
|
||||
self.stderr = ''
|
||||
|
||||
|
||||
def _mock_run(monkeypatch, rc, out):
|
||||
import app.services.wp_analytics_service as mod
|
||||
monkeypatch.setattr(mod.subprocess, 'run', lambda *a, **k: _Res(rc, out))
|
||||
|
||||
|
||||
def test_classify_php_levels():
|
||||
from app.services.wp_analytics_service import WpAnalyticsService as W
|
||||
assert W._classify_php('Fatal error') == 'fatal'
|
||||
assert W._classify_php('Parse error') == 'fatal'
|
||||
assert W._classify_php('Recoverable fatal error') == 'fatal'
|
||||
assert W._classify_php('Warning') == 'warning'
|
||||
assert W._classify_php('Deprecated') == 'deprecated'
|
||||
assert W._classify_php('Notice') == 'notice'
|
||||
assert W._classify_php('Strict standards') == 'other'
|
||||
|
||||
|
||||
def test_get_php_errors_parses_and_skips_stack_traces(monkeypatch):
|
||||
from app.services.wp_analytics_service import WpAnalyticsService
|
||||
_mock_run(monkeypatch, 0, _SAMPLE)
|
||||
out = WpAnalyticsService.get_php_errors('site')
|
||||
assert out['available'] is True and out['enabled'] is True
|
||||
assert out['total'] == 4 # stack-trace / "thrown in" lines are skipped
|
||||
assert out['counts'] == {'fatal': 1, 'warning': 1, 'notice': 1, 'deprecated': 1, 'other': 0}
|
||||
# Most-recent first: the Notice (12:07) leads.
|
||||
assert out['recent'][0]['severity'] == 'notice'
|
||||
assert 'Uncaught Error' in out['recent'][-1]['message']
|
||||
|
||||
|
||||
def test_get_php_errors_logging_off(monkeypatch):
|
||||
from app.services.wp_analytics_service import WpAnalyticsService
|
||||
_mock_run(monkeypatch, 0, '') # no marker => log file absent
|
||||
out = WpAnalyticsService.get_php_errors('site')
|
||||
assert out['available'] is False
|
||||
assert 'logging is off' in out['note']
|
||||
|
||||
|
||||
def test_get_php_errors_on_but_empty(monkeypatch):
|
||||
from app.services.wp_analytics_service import WpAnalyticsService
|
||||
_mock_run(monkeypatch, 0, '__SK_WPDEBUG__\n') # log exists, no entries
|
||||
out = WpAnalyticsService.get_php_errors('site')
|
||||
assert out['available'] is True and out['total'] == 0
|
||||
assert 'no PHP errors recorded' in out['note']
|
||||
|
||||
|
||||
def test_get_php_errors_container_unavailable(monkeypatch):
|
||||
from app.services.wp_analytics_service import WpAnalyticsService
|
||||
_mock_run(monkeypatch, 1, '') # docker exec non-zero (stopped / missing)
|
||||
out = WpAnalyticsService.get_php_errors('site')
|
||||
assert out['available'] is False and 'unavailable' in out['note']
|
||||
|
||||
|
||||
def test_get_php_errors_no_container():
|
||||
from app.services.wp_analytics_service import WpAnalyticsService
|
||||
out = WpAnalyticsService.get_php_errors(None)
|
||||
assert out['available'] is False and out['total'] == 0
|
||||
|
||||
|
||||
def test_message_truncation(monkeypatch):
|
||||
from app.services.wp_analytics_service import WpAnalyticsService
|
||||
long = 'x' * 500
|
||||
_mock_run(monkeypatch, 0, f'__SK_WPDEBUG__\n[1 UTC] PHP Fatal error: {long}\n')
|
||||
out = WpAnalyticsService.get_php_errors('site')
|
||||
assert out['counts']['fatal'] == 1
|
||||
assert len(out['recent'][0]['message']) == 300 # capped
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Tests for #24 per-site PHP limit writes — validation + durable conf.d ini /
|
||||
bind-mount. The Docker apply step is mocked (no Docker on the dev/CI host); the
|
||||
file-rendering, compose-mutation, merge, and injection-rejection logic is real."""
|
||||
import os
|
||||
import yaml
|
||||
|
||||
|
||||
def _compose_site(tmp_path):
|
||||
"""A minimal Docker-stack WP site dir with a docker-compose.yml."""
|
||||
(tmp_path / 'docker-compose.yml').write_text(
|
||||
"services:\n"
|
||||
" wordpress:\n"
|
||||
" image: wordpress:6.4-apache\n"
|
||||
" volumes:\n"
|
||||
" - wordpress_html:/var/www/html\n"
|
||||
)
|
||||
return str(tmp_path)
|
||||
|
||||
|
||||
def _mock_docker(monkeypatch):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
from app.services.docker_service import DockerService
|
||||
monkeypatch.setattr(DockerService, 'compose_up', lambda *a, **k: {'success': True})
|
||||
monkeypatch.setattr(DockerService, 'compose_restart', lambda *a, **k: {'success': True})
|
||||
monkeypatch.setattr(WordPressService, '_wait_for_wp_ready', staticmethod(lambda p: None))
|
||||
monkeypatch.setattr(WordPressService, 'get_php_info', staticmethod(lambda p: {'limits': {}}))
|
||||
|
||||
|
||||
# ---- validation / injection rejection (no Docker needed) -------------------
|
||||
|
||||
def test_rejects_unknown_directive(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
res = WordPressService.set_php_limits(_compose_site(tmp_path), {'evil_directive': '1'})
|
||||
assert res['success'] is False and 'Unknown PHP limit' in res['error']
|
||||
|
||||
|
||||
def test_rejects_injection_value(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
# A newline-smuggled extra directive must not pass validation.
|
||||
res = WordPressService.set_php_limits(_compose_site(tmp_path),
|
||||
{'memory_limit': '256M\nevil = 1'})
|
||||
assert res['success'] is False and 'Invalid value' in res['error']
|
||||
# ...and nothing was written.
|
||||
assert not os.path.exists(os.path.join(_compose_site(tmp_path), 'php-conf', 'zz-serverkit.ini'))
|
||||
|
||||
|
||||
def test_rejects_non_stack_site(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
res = WordPressService.set_php_limits(str(tmp_path), {'memory_limit': '256M'})
|
||||
assert res['success'] is False and 'Not a Docker-stack site' in res['error']
|
||||
|
||||
|
||||
# ---- durable write + bind-mount (Docker mocked) ----------------------------
|
||||
|
||||
def test_writes_ini_and_injects_single_file_mount(tmp_path, monkeypatch):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
_mock_docker(monkeypatch)
|
||||
path = _compose_site(tmp_path)
|
||||
|
||||
res = WordPressService.set_php_limits(path, {'memory_limit': '512M', 'max_execution_time': '120'})
|
||||
assert res['success'] is True
|
||||
|
||||
ini = os.path.join(path, 'php-conf', 'zz-serverkit.ini')
|
||||
content = open(ini).read()
|
||||
assert 'memory_limit = 512M' in content
|
||||
assert 'max_execution_time = 120' in content
|
||||
|
||||
vols = yaml.safe_load(open(os.path.join(path, 'docker-compose.yml')))['services']['wordpress']['volumes']
|
||||
assert any('php-conf/zz-serverkit.ini:/usr/local/etc/php/conf.d/zz-serverkit.ini' in v for v in vols)
|
||||
|
||||
|
||||
def test_partial_update_merges_and_mount_not_duplicated(tmp_path, monkeypatch):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
_mock_docker(monkeypatch)
|
||||
path = _compose_site(tmp_path)
|
||||
|
||||
WordPressService.set_php_limits(path, {'memory_limit': '256M'})
|
||||
res = WordPressService.set_php_limits(path, {'upload_max_filesize': '64M'})
|
||||
assert res['success'] is True
|
||||
# The second (partial) update keeps the first directive.
|
||||
assert res['limits']['memory_limit'] == '256M'
|
||||
assert res['limits']['upload_max_filesize'] == '64M'
|
||||
|
||||
# The single-file mount is added once, not duplicated on the second call.
|
||||
vols = yaml.safe_load(open(os.path.join(path, 'docker-compose.yml')))['services']['wordpress']['volumes']
|
||||
assert len([v for v in vols if 'zz-serverkit.ini' in v]) == 1
|
||||
|
||||
|
||||
def test_accepts_unlimited_and_size_suffixes(tmp_path, monkeypatch):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
_mock_docker(monkeypatch)
|
||||
path = _compose_site(tmp_path)
|
||||
res = WordPressService.set_php_limits(path, {'memory_limit': '-1', 'max_input_time': '-1',
|
||||
'upload_max_filesize': '2G', 'max_input_vars': '5000'})
|
||||
assert res['success'] is True
|
||||
assert res['limits']['memory_limit'] == '-1'
|
||||
|
||||
|
||||
# ---- ini parsing -----------------------------------------------------------
|
||||
|
||||
def test_read_php_ini_skips_comments_and_garbage(tmp_path):
|
||||
from app.services.wordpress_service import WordPressService
|
||||
p = tmp_path / 'x.ini'
|
||||
p.write_text('; a comment\nmemory_limit = 128M\n\nno equals here\nmax_input_vars = 2000\n')
|
||||
assert WordPressService._read_php_ini(str(p)) == {'memory_limit': '128M', 'max_input_vars': '2000'}
|
||||
@@ -0,0 +1,441 @@
|
||||
# ServerKit Agent Subsystem — Security & Completeness Audit
|
||||
|
||||
**Date:** 2026-06-12
|
||||
**Scope:** The multi-server agent fleet end-to-end — Go agent (`agent/`), panel
|
||||
gateway/registry/long-poll (`backend/app/agent_gateway.py`,
|
||||
`services/agent_registry.py`, `api/agent_poll.py`), pairing/enrollment, the
|
||||
panel→agent command APIs (`api/servers.py`, `fleet.py`, `agent_plugins.py`),
|
||||
install/packaging, the fleet UI, and docs/CI.
|
||||
**Method:** Direct read of the security-critical paths plus four parallel
|
||||
breadth scans. Every load-bearing finding below was verified in source; one
|
||||
widely-reported claim (committed MSI bloat) was checked and **rejected** as a
|
||||
false positive (see Appendix B).
|
||||
|
||||
---
|
||||
|
||||
## TL;DR
|
||||
|
||||
The agent's **core security primitives are genuinely well built** — HMAC+nonce
|
||||
replay protection on both transports, fail-closed signature verification on the
|
||||
panel, symlink-resolved file allowlisting, shell-metacharacter rejection on
|
||||
every command validator, exec/terminal gated off by default, a localhost-bound
|
||||
IPC API with a constant-time bearer check, and a solid pairing flow
|
||||
(Ed25519 proof-of-possession, lockout, one-shot credential delivery).
|
||||
|
||||
The problems are concentrated in **three areas**:
|
||||
|
||||
1. **The self-update path is the weakest link** and bypasses every other
|
||||
control — no code-signing, and checksum verification is optional and
|
||||
fail-open. Whoever can send a command to an agent can run code as root on it,
|
||||
even with exec and package management disabled.
|
||||
2. **An entire advertised feature surface is non-functional** — the Agent Plugin
|
||||
system and Server Template drift/remediation call a panel function that does
|
||||
not exist, and the agent has no handlers for them. The API, DB, and UI imply
|
||||
a working sandboxed-plugin capability that silently does nothing.
|
||||
3. **Authorization is thinner at the edges than in the core** — the Socket.IO
|
||||
layer has no per-object/role checks, and a few state-changing endpoints are
|
||||
under-gated.
|
||||
|
||||
No agent code is exercised by CI.
|
||||
|
||||
Severity counts: **3 High, 5 Medium, 7 Low/Informational.**
|
||||
|
||||
---
|
||||
|
||||
## Remediation status (2026-06-12)
|
||||
|
||||
- **M1 — fixed.** `sockets.py` now resolves the JWT to a live, active user at
|
||||
connect and records the role; `subscribe_terminal` and the generic
|
||||
`join_room` (for `_terminal:` rooms) require admin/developer, matching the
|
||||
REST `@developer_required` on terminal creation. Job/cloudflared streaming is
|
||||
unaffected.
|
||||
- **M2 — corrected + hardened.** The compose half was a **false alarm**: every
|
||||
compose handler already runs the symlink-resolved AllowedPaths check
|
||||
(`a.validateFileAccess`) before calling the docker client (see the corrected
|
||||
M2 entry below). Added a doc-contract comment on `validateProjectPath` so a
|
||||
future caller can't bypass it. Cron is intentionally **not** AllowedPaths-
|
||||
restricted (that would break legitimate jobs like `/usr/bin/certbot renew`);
|
||||
its blast radius is addressed by M3 instead.
|
||||
- **M4 — fixed.** Added `.github/workflows/agent-ci.yml` (go vet + go test +
|
||||
cross-compile build matrix for linux amd64/arm64 and windows/amd64 — darwin
|
||||
excluded because the tray dep can't cross-compile from Linux) and
|
||||
`backend-ci.yml` (full pytest suite). Also added
|
||||
`backend/tests/test_agent_poll_e2e.py`, an end-to-end test that drives the
|
||||
real panel↔agent command loop (HMAC auth → register → queue → poll → result →
|
||||
the synchronous waiter resolves) over the poll transport, which shares the
|
||||
WebSocket path's auth/registry/routing code. This is the "prove it actually
|
||||
works" net the subsystem lacked.
|
||||
- **M5 — fixed.** The `register` command now reads the token (and
|
||||
connection-string / server URL) from the environment
|
||||
(`SERVERKIT_REGISTRATION_TOKEN`, etc.) when the flags aren't given, so the
|
||||
installers pass the token via env instead of argv — env is owner/root-only
|
||||
(`/proc/<pid>/environ`), whereas argv is world-readable (`ps`,
|
||||
`/proc/<pid>/cmdline`). `install.sh` (env-passed register, `eval` removed) and
|
||||
`install.ps1` (token via env, made optional) updated accordingly, and both
|
||||
accept the token from the environment so it need not appear in the
|
||||
`curl | bash -s -- --token …` line / shell history. Verified: the agent reads
|
||||
the env token at runtime, both scripts pass syntax checks.
|
||||
- **M3 — fixed.** The DEB/RPM units now run as the dedicated unprivileged
|
||||
`serverkit-agent` account with the same hardening as `install.sh`
|
||||
(`NoNewPrivileges=yes`, `ProtectSystem=strict`, `ProtectHome=yes`,
|
||||
`PrivateTmp=yes`). **Tradeoff:** packaged agents now match the script
|
||||
installer's capability set — Docker + metrics + file access — and no longer
|
||||
do systemd/package management or agent self-update by default (both need
|
||||
root). Self-update being disabled also blunts H1 for packaged installs:
|
||||
updates flow through the OS package manager's signed path. To keep
|
||||
system-management by default, run as root deliberately (revert `User=` in the
|
||||
build scripts) or configure passwordless sudo for the account.
|
||||
|
||||
### Highs
|
||||
|
||||
- **H1 — fixed (verification side).** `updater.go` now fails closed: an update
|
||||
with no checksums URL is refused; `matchChecksum` errors when no entry matches
|
||||
this platform (was a silent skip); the checksums fetch checks HTTP status; and
|
||||
`requireSecureURL` rejects non-HTTPS update/checksum URLs (dev override via
|
||||
`SERVERKIT_INSECURE_TLS`). Covered by `internal/updater/updater_test.go`
|
||||
(6 tests). **Still recommended:** cryptographic release signing
|
||||
(minisign/cosign) with a public key pinned in the agent — that needs the
|
||||
project's signing key + a release-pipeline change, so it's the remaining H1
|
||||
step. (Packaged installs are already protected: non-root agents can't
|
||||
self-update, so updates go through the OS package manager.)
|
||||
- **H2 — fixed (made honest).** Removed the dead `get_agent_gateway()` calls in
|
||||
`agent_plugin_service.py` and `server_template_service.py`. Plugin install now
|
||||
reports `STATUS_ERROR` ("Agent-side plugin support is not implemented yet")
|
||||
instead of hanging in `installing`; template drift-check/remediate report
|
||||
`unknown` + an explanatory `drift_report.error`; local-only ops (disable,
|
||||
uninstall, configure) just drop the dead dispatch. Covered by
|
||||
`tests/test_agent_features_honest.py` (3 tests). Implementing the feature for
|
||||
real (agent handlers + sandbox) remains future work, but it no longer lies.
|
||||
- **H3 — fixed** (earlier this session): `POST /<id>/agent/update` is now
|
||||
`@developer_required`; test in `tests/test_agent_update_authz.py`.
|
||||
|
||||
### Lows
|
||||
|
||||
- **L1 — fixed.** Pairing `/claim` and `/lookup` now require developer role
|
||||
(`tests/test_pairing_authz.py`), matching `POST /servers`.
|
||||
- **L2 — documented.** `SECURITY.md` now states explicitly that `agent.key`
|
||||
encryption is off-host/tamper protection, not confidentiality against local
|
||||
root, and that the `0600` perms are the real control.
|
||||
- **L3 — fixed.** Removed the dead "Add Version" / per-row Edit / Delete buttons
|
||||
from `AgentFleet.jsx` (no backend edit/delete route exists); version list
|
||||
intact, unused imports cleaned, no new lint errors.
|
||||
- **L4 — accepted (by design).** Capabilities are OR-merged and not cleared
|
||||
until restart on purpose, to avoid feature flicker from transient probe
|
||||
failures; reverting would reintroduce that bug.
|
||||
- **L5 — accepted (documented).** The single-worker requirement is stated in
|
||||
`SECURITY.md`/`ARCHITECTURE.md`/`CLAUDE.md` and enforced by `run.py`'s
|
||||
`-w 1`; reliable in-process detection of a multi-worker misconfig isn't
|
||||
practical, so it stays a documented operational constraint.
|
||||
- **L6 — accepted (low).** The Windows updater builds a `.bat` via `fmt.Sprintf`
|
||||
with local, non-attacker-controlled paths; not worth the churn.
|
||||
- **L7 — clarified.** The `verify_agent_auth` "TODO" is reworded to an accepted
|
||||
limitation (per-message token validation is defence-in-depth, not a bug; the
|
||||
channel is TLS-authenticated and connect is HMAC+nonce verified).
|
||||
|
||||
---
|
||||
|
||||
## HIGH
|
||||
|
||||
### H1 — Agent self-update has no code-signing and checksum verification is fail-open (supply-chain RCE)
|
||||
|
||||
The update path is the single highest-leverage hardening target because it runs
|
||||
**as the agent process itself (root on packaged installs)** and is reachable
|
||||
even when `Features.Exec=false` and package handlers are unavailable — it
|
||||
bypasses every other feature gate.
|
||||
|
||||
Three independent weaknesses in `agent/internal/updater/updater.go`:
|
||||
|
||||
- **Checksum is optional.** `DownloadUpdate` only verifies when a URL is present:
|
||||
```go
|
||||
// updater.go:167
|
||||
if info.ChecksumsURL != "" {
|
||||
if err := u.verifyChecksum(ctx, archivePath, info.ChecksumsURL); err != nil { ... }
|
||||
}
|
||||
```
|
||||
Empty `checksums_url` → install with **no** verification.
|
||||
- **Verification is fail-open.** When no checksum line matches the file, it
|
||||
logs a warning and returns success:
|
||||
```go
|
||||
// updater.go:367-370
|
||||
if expectedHash == "" {
|
||||
u.log.Warn("Could not find checksum for downloaded file, skipping verification")
|
||||
return nil
|
||||
}
|
||||
```
|
||||
- **The checksum fetch ignores HTTP status** (`updater.go:316-320`). A 404 HTML
|
||||
body parses into an empty map → `expectedHash == ""` → skipped.
|
||||
|
||||
Even when it runs, the checksum file is fetched over the **same channel** as the
|
||||
binary with **no signature** (no GPG/cosign/minisign), so anyone who can swap
|
||||
the binary can swap the checksums to match. The download URL is **fully
|
||||
attacker-controlled** — `handleAgentUpdate` takes it straight from the command:
|
||||
|
||||
```go
|
||||
// agent/internal/agent/agent.go:1755-1785
|
||||
var p struct { Version, DownloadURL, ChecksumsURL string; Force bool }
|
||||
...
|
||||
err := u.UpdateTo(context.Background(), p.Version, p.DownloadURL, p.ChecksumsURL)
|
||||
```
|
||||
|
||||
(The stale comment at `agent.go:1781-1783` — "In a real implementation, we would
|
||||
use the provided URLs … For now, we'll let the updater handle it" — contradicts
|
||||
the code, which already uses them.)
|
||||
|
||||
**Blast radius:** A compromised or malicious panel, or an on-path attacker when
|
||||
`SERVERKIT_INSECURE_TLS=true`, installs an arbitrary binary as root on every
|
||||
connected server. The checksum gives a false sense of integrity.
|
||||
|
||||
**Fix:** Sign release archives (minisign/cosign), pin the public key in the
|
||||
agent binary, and verify the signature over the binary **before** install. Make
|
||||
checksum verification mandatory and fail-closed. Constrain `download_url` to the
|
||||
expected panel/GitHub origin. Check the HTTP status on the checksum fetch.
|
||||
|
||||
---
|
||||
|
||||
### H2 — Agent Plugin system & Server Template remediation are non-functional stubs (missing function + missing handlers)
|
||||
|
||||
Two backend services dispatch agent commands through a helper that **does not
|
||||
exist anywhere in the codebase**:
|
||||
|
||||
```python
|
||||
# agent_plugin_service.py:159,189,218,254 and server_template_service.py:324,366
|
||||
from app.agent_gateway import get_agent_gateway # ← no such symbol
|
||||
gw = get_agent_gateway()
|
||||
gw.send_command(server.agent_id, 'plugin_install', {...})
|
||||
```
|
||||
|
||||
`agent_gateway.py` exports `init_agent_gateway` and `AgentNamespace` — there is
|
||||
no `get_agent_gateway`. Every call raises `ImportError`, which is swallowed by a
|
||||
bare `except Exception` and logged as a warning. Compounding it:
|
||||
|
||||
- The agent registers **no** `plugin_install` / `plugin_uninstall` /
|
||||
`plugin_configure` / `plugin_disable` / `config_drift_check` /
|
||||
`config_remediate` handlers (grep: zero matches in `agent/`).
|
||||
- The call passes `server.agent_id` where the real `agent_registry.send_command`
|
||||
expects `server_id` — wrong argument even if the symbol existed.
|
||||
|
||||
**Effect:** Plugin install/uninstall/configure and template drift-check/remediate
|
||||
are silent no-ops; DB rows are set to `STATUS_INSTALLING` / `CHECKING` /
|
||||
`REMEDIATING` and **never progress**. Yet the API (`api/agent_plugins.py`), the
|
||||
models, the marketplace `ai`/plugin category, and the AgentFleet UI
|
||||
(install + bulk-install buttons) all present this as a working,
|
||||
permission-scoped (`filesystem`/`network`/`docker`/`process`/`system`) sandboxed
|
||||
capability. It is entirely hollow below the API layer.
|
||||
|
||||
**Fix:** Either implement the panel glue + agent handlers + sandbox, or remove
|
||||
the UI/API and mark the feature explicitly "planned." At minimum, surface the
|
||||
failure to the user instead of swallowing it, and stop stranding DB rows in a
|
||||
pending state.
|
||||
|
||||
---
|
||||
|
||||
### H3 — `trigger_agent_update` lets any authenticated user (including read-only viewers) update/restart the fleet
|
||||
|
||||
```python
|
||||
# backend/app/api/servers.py:2116-2117
|
||||
@servers_bp.route('/<server_id>/agent/update', methods=['POST'])
|
||||
@jwt_required() # ← no @developer_required / @admin_required
|
||||
def trigger_agent_update(server_id):
|
||||
```
|
||||
|
||||
Every other state-changing server route is `@developer_required` or
|
||||
`@admin_required`; this one is authentication-only. A `viewer` (the explicit
|
||||
read-only role) can force agent binary updates and the consequent restarts
|
||||
across every server. In this endpoint the URL is panel-derived from GitHub
|
||||
(so not arbitrary-binary RCE on its own), but it is an unintended privileged
|
||||
action for a read-only account and an availability lever over the whole fleet.
|
||||
|
||||
**Fix:** Gate behind `@developer_required` (or `@admin_required`, matching
|
||||
`/fleet/*`).
|
||||
|
||||
---
|
||||
|
||||
## MEDIUM
|
||||
|
||||
### M1 — Socket.IO layer has no authorization beyond "the JWT decodes"
|
||||
|
||||
`backend/app/sockets.py` authenticates the connection but performs **no role or
|
||||
object-level checks** thereafter:
|
||||
|
||||
- **Connect only decodes the token** — no `is_active`, no role
|
||||
(`sockets.py:49-58`). A deactivated user keeps socket access until JWT expiry.
|
||||
- **Generic `join_room` joins any room by name** (`sockets.py:199-205`):
|
||||
```python
|
||||
@socketio.on('join_room')
|
||||
def handle_join_room(data):
|
||||
room = data.get('room')
|
||||
if room:
|
||||
join_room(room) # no check that the caller may see this room
|
||||
```
|
||||
Room names are discoverable (`server_<id>_metrics`, `logs_<app_id>`,
|
||||
`build_<app_id>`; server IDs come straight from `GET /servers`).
|
||||
- **`subscribe_terminal` doesn't gate on role/ownership** (`sockets.py:120-144`)
|
||||
— any authenticated socket (including a `viewer`) can join a remote terminal's
|
||||
output room given the session id, even though *creating* a terminal is
|
||||
`@developer_required`. Output can include a root shell's contents.
|
||||
|
||||
Bounded today by role homogeneity and unguessable session UUIDs, but it's a
|
||||
defense-in-depth gap inconsistent with the REST authz and a real cross-role
|
||||
information-exposure path. **Fix:** validate room ownership/required role inside
|
||||
the join/subscribe handlers; re-check `is_active`+role at connect; restrict
|
||||
terminal subscription to the role that can create one.
|
||||
|
||||
### M2 — Compose path allowlisting (compose already enforced; cron intentionally not) — CORRECTED
|
||||
|
||||
The original finding overstated this. On closer review the **compose half was
|
||||
already mitigated**: every compose handler in `internal/agent/agent.go`
|
||||
(`handleDockerComposePs/Up/Down/Logs/Restart/Pull`, lines 1285/1300/1333/1361/
|
||||
1388/1415) calls `a.validateFileAccess(p.ProjectPath)` — the same
|
||||
symlink-resolved `AllowedPaths` allowlist used by `file:read/write/list` — and
|
||||
that is the **only** call path to the docker client's `Compose*` methods. The
|
||||
weaker `validateProjectPath` in `docker/client.go` is reached only *after* that
|
||||
check passes, so it isn't a vulnerability; it was just inspected in isolation.
|
||||
A doc-contract comment was added there so a future caller can't mistake it for
|
||||
the allowlist boundary.
|
||||
|
||||
**Cron** (`cron/cron_linux.go validateCommand`) requires an absolute path and
|
||||
rejects shell metacharacters but is **deliberately not** restricted to
|
||||
`AllowedPaths` — doing so would break legitimate jobs (`/usr/bin/certbot
|
||||
renew`, `/usr/bin/apt …`). Its real risk is "runs as whatever the agent runs
|
||||
as," which M3 addresses by moving packaged agents off root (cron entries then
|
||||
land in the unprivileged account's crontab, limiting blast radius).
|
||||
|
||||
### M3 — Packaged DEB/RPM run the agent as root with hardening disabled, contradicting install.sh
|
||||
|
||||
`agent/packaging/deb/build.sh` and `rpm/build.sh` ship a unit with `User=root`
|
||||
and `NoNewPrivileges=false`, while `agent/scripts/install.sh` lays down a
|
||||
dedicated `serverkit-agent` user with `NoNewPrivileges=yes`,
|
||||
`ProtectSystem=strict`, `ProtectHome=yes`, `PrivateTmp=yes`. The packaged path is
|
||||
both inconsistent and maximizes the H1 update-RCE blast radius (root, no
|
||||
privilege containment). **Fix:** align the packaged units with the hardened
|
||||
install.sh posture, or document why root is required and tighten the sandbox
|
||||
directives.
|
||||
|
||||
### M4 — No CI runs agent Go tests, `go vet`, or any Go SAST
|
||||
|
||||
`.github/workflows/agent-release.yml` only builds. `security-scan.yml` is
|
||||
Python/Bandit over `backend/**`; nothing runs `go test`/`go vet`. Five agent
|
||||
test files exist and cover the most security-sensitive logic
|
||||
(`security_test.go` — command-blocking, exec-timeout, file-access allowlist &
|
||||
symlink escape; `file_handlers_test.go`; `connstring_test.go`;
|
||||
`ipc/auth_test.go`; `jobs/jobs_test.go`) but **never run in CI**, so a
|
||||
regression in path-allowlisting or exec-blocking would ship unverified.
|
||||
**Fix:** add a workflow running `go vet ./...` + `go test ./...` (and ideally
|
||||
`govulncheck`/`golangci-lint`) on PRs touching `agent/`.
|
||||
|
||||
### M5 — Install flow exposes the registration token in the process table / shell history
|
||||
|
||||
`agent/scripts/install.sh` passes the token as a CLI argument to
|
||||
`serverkit-agent register --token "$TOKEN"` (visible in `ps` during
|
||||
registration), and the documented `curl … | sudo bash -s -- --token sk_reg_…`
|
||||
one-liner lands the token in shell history. Tokens are single-use and
|
||||
short-TTL, which limits exposure, but a captured token is usable until consumed.
|
||||
**Fix:** accept the token via env var or stdin; note `HISTFILE` hygiene in the
|
||||
docs.
|
||||
|
||||
---
|
||||
|
||||
## LOW / Informational
|
||||
|
||||
- **L1 — Pairing claim and a few reads are authentication-only.**
|
||||
`pairing.py` `/claim` and `/lookup` are `@jwt_required()` (not
|
||||
`@developer_required`), so a viewer who has the physically-displayed pair code
|
||||
+ passphrase can enroll a server. Minor authz-consistency item; the two-factor
|
||||
physical secret is the real gate.
|
||||
- **L2 — `agent.key` "encryption" is host-derived obfuscation, not a secret.**
|
||||
`config.go:380-396` derives the AES-GCM key from `hostname + machine-id` /
|
||||
`COMPUTERNAME` — values available to anything on the host. Real protection is
|
||||
the `0600` perms; the encryption only resists off-host exfil (e.g. a leaked
|
||||
backup). Worth documenting as such so it isn't mistaken for at-rest secrecy
|
||||
against local root.
|
||||
- **L3 — Dead/placeholder UI.** `AgentFleet.jsx` version-table Edit/Delete and
|
||||
"Add Version" buttons have no handlers; `Terminal.jsx` shows "isn't available
|
||||
yet" for remote log/journal/process listing (feature-gated, not implemented).
|
||||
Honest placeholders, but they read as working controls.
|
||||
- **L4 — Capabilities are OR-merged and never cleared until restart**
|
||||
(`recapabilities.go`). An agent that briefly saw Docker advertises `docker=true`
|
||||
for the rest of its run even if Docker goes away — intentional, but can mislead
|
||||
the target picker.
|
||||
- **L5 — Single-worker requirement is enforced only by convention.** The
|
||||
registry, nonce store, and anomaly service are per-process in-memory
|
||||
singletons; running the panel with `-w >1` silently misroutes commands and
|
||||
desyncs nonces/rooms. Documented in CLAUDE.md/SECURITY.md but nothing fails
|
||||
loudly at runtime if misconfigured.
|
||||
- **L6 — Windows update writes a `.bat` via `fmt.Sprintf` with binary paths**
|
||||
(`updater.go:254-261`). Local-only and not attacker-influenced today; would
|
||||
break on paths containing quotes. Low risk.
|
||||
- **L7 — Stale TODO in `verify_agent_auth`** (`agent_registry.py:846`):
|
||||
per-message session-token validation is noted as unimplemented. The session
|
||||
token is issued but not verified per message; auth currently rests on the
|
||||
TLS channel + initial HMAC. Acceptable given the model; track it.
|
||||
|
||||
---
|
||||
|
||||
## What's done well (don't "fix" these)
|
||||
|
||||
- **Agent auth** signs `agent_id:timestamp:nonce` with a fresh random nonce on
|
||||
**both** WS (`ws/client.go:287`) and poll (`poll/client.go:173`) transports;
|
||||
the panel verifies HMAC **before** consuming the nonce and **fails closed** when
|
||||
the secret is missing/undecryptable (`agent_registry.py:789-851`), with a 60 s
|
||||
skew window and per-IP rate limiting shared across both transports.
|
||||
- **TLS verification is on by default**; `InsecureSkipVerify` is uniformly
|
||||
env-gated (`SERVERKIT_INSECURE_TLS`) across all five dial sites and logged
|
||||
loudly at startup.
|
||||
- **File access** is symlink-resolved against an allowlist, denies all when
|
||||
unconfigured, masks SUID/SGID/sticky on write, and re-validates parents for
|
||||
`create_dirs` (`file_handlers.go`).
|
||||
- **Command validators** reject shell metacharacters for packages, systemd
|
||||
units, container/image/volume/network names, cron specs, and tunnel
|
||||
names; container create bans `privileged`/`cap_add`/`devices`; exec requires
|
||||
an absolute path + blocklist check; output is bounded; jobs are capped.
|
||||
- **exec and terminal are off by default** — `system:exec` isn't registered
|
||||
unless `Features.Exec`, and the terminal manager is only constructed when
|
||||
`Features.Exec` is true (`agent.go:133`), so the terminal isn't an exec bypass.
|
||||
- **Local IPC** binds to localhost (forced), requires a `0600` bearer token with
|
||||
a constant-time compare, and exempts only `/health` (`ipc/server.go`).
|
||||
- **Pairing** uses Ed25519 proof-of-possession over the enrollment id,
|
||||
per-agent lockout with exponential backoff, bcrypt-hashed passphrase, code
|
||||
TTL/rotation/freeze, and one-shot encrypted credential delivery
|
||||
(`pairing_service.py`).
|
||||
- **Registry reconnect/heartbeat handling** re-validates socket identity before
|
||||
eviction and fails in-flight commands on reconnect — the subtle races are
|
||||
handled.
|
||||
|
||||
---
|
||||
|
||||
## Recommended priority order
|
||||
|
||||
1. **H1** — sign agent releases + make update verification mandatory/fail-closed
|
||||
(highest leverage; neutralizes the one RCE primitive that bypasses every gate).
|
||||
2. **H2** — implement or remove the Plugin/Template features; stop swallowing the
|
||||
missing-function error and stranding DB rows.
|
||||
3. **H3** + **M1** — close the authz gaps (update endpoint role; socket
|
||||
room/role checks).
|
||||
4. **M3** — align packaged service hardening with install.sh.
|
||||
5. **M4** — wire agent tests into CI so the good validators don't silently rot.
|
||||
6. **M2 / M5 / L-series** — allowlist compose+cron paths; runtime guard or louder
|
||||
doc for single-worker; clean up placeholders and the obfuscation-vs-encryption
|
||||
wording.
|
||||
|
||||
---
|
||||
|
||||
## Appendix A — Authorization map (server routes)
|
||||
|
||||
Reads are `@jwt_required()` (any active user incl. viewer); writes are
|
||||
`@developer_required`; fleet ops are `@admin_required`. **Unauthenticated by
|
||||
design:** `/register` (token-gated, `5/min`), `/install.sh`, `/install.ps1`,
|
||||
`/agent/version`, `/agent/version/check`, `/agent/download/<os>/<arch>` (302 →
|
||||
GitHub), `/agent/checksums`. **Authz outliers:** `/<id>/agent/update` is
|
||||
auth-only (H3); pairing `/claim` + `/lookup` are auth-only (L1).
|
||||
|
||||
## Appendix B — Claims checked and rejected
|
||||
|
||||
- **"~370 MB of committed MSI binaries in `agent/packaging/msi/output/`."**
|
||||
**False.** `git ls-files` shows zero tracked `.msi`/`.wixpdb`, and
|
||||
`git check-ignore` confirms the directory is ignored. They are local build
|
||||
artifacts, correctly untracked. The only committed binaries under `agent/` are
|
||||
small required assets (`.syso` resource objects, tray/setup `.ico`/`.png`).
|
||||
- **"Agent defines HMAC/nonce/timestamp helpers but never calls them."**
|
||||
**False.** Both transports call `SignMessageWithNonce` with a fresh nonce; the
|
||||
panel verifies and records it. (The helper-only view came from grepping
|
||||
definitions without call sites.)
|
||||
@@ -0,0 +1,230 @@
|
||||
# ServerKit Connections Roadmap
|
||||
|
||||
*Turning Settings → Connections from a 3-provider tab into the **single front door** for every external account ServerKit already runs on — source hosts, cloud servers, DNS, registrars, mail and storage — and the one place to answer "what do I own, what's it connected to, and when does it lapse."*
|
||||
|
||||
---
|
||||
|
||||
## The thesis: surface and unify, not build from zero
|
||||
|
||||
The Connections hub looks like a thin GitHub-plus-DNS tab. It isn't. ServerKit **already** talks to most of these providers — but the credentials and the capability are scattered across **four storage locations and three different pages**, so none of it reads as "your connected accounts in one place."
|
||||
|
||||
| Account type | Backend today | Where creds live | Powers | In the hub? |
|
||||
|---|---|---|---|---|
|
||||
| **GitHub** source | `source_connection_service.py` (OAuth) | Fernet-encrypted (`SourceConnection.access_token_encrypted`) | New Service from a repo | ✅ live |
|
||||
| **Cloudflare / Route 53** DNS | `dns_provider_service.py` (dispatcher) | ⚠️ **plaintext** (`DNSProviderConfig`) | Wildcard SSL, email DNS, custom-domain attach | ✅ live |
|
||||
| **Cloud servers** (DigitalOcean / Hetzner / Vultr / Linode) | `cloud_provisioning_service.py` + `models/cloud_server.py` + `api/cloud_provisioning.py` | (in cloud-provisioning config) | **Servers** page | ❌ not surfaced |
|
||||
| **S3 / Backblaze B2** object storage | `storage_provider_service.py` (boto3) | ⚠️ masked in `storage.json`, **not** Fernet | **Backups** page | ❌ not surfaced |
|
||||
| **Domain registrar / expiry** | — **none** — | — | **Domains** page | ❌ doesn't exist |
|
||||
|
||||
Three consequences fall out of that table:
|
||||
|
||||
1. **Two of the user's three asks are mostly *wiring*, not building.** "DigitalOcean to manage servers" → the provisioning backend exists; it's just never been surfaced in the hub. "S3 in the Files app" → the S3 backend exists (it runs backups); it's never been pointed at the file browser.
|
||||
2. **One ask is genuinely net-new: "when do my domains expire?"** `models/domain.py` only tracks `ssl_expires_at` (certificate expiry). There is no registrar, no registration/expiry date, no WHOIS anywhere in the models. That's the headline new feature, and it's the one that delivers the "all this info in one place" payoff.
|
||||
3. **There's a real security gap to close on the way through.** `utils/crypto.py` (`encrypt_secret`/`decrypt_secret`, Fernet) is already used by source connections, AI, the agent fleet and pairing — but DNS and storage secrets sit in plaintext / lightly-masked. Every new provider should encrypt at rest, and the existing two should be migrated.
|
||||
|
||||
**So the fast path to "one place for everything" is surfacing what exists, completing the catalog's own "coming soon" tiles, then building the single genuinely-missing system (registrar + expiry).**
|
||||
|
||||
---
|
||||
|
||||
## ✅ Update (2026-06-15): roadmap complete — #1–#18 all shipped
|
||||
|
||||
Built in one session and verified — `npm run build` (frontend, clean), `eslint` (clean), `py_compile` + venv import (backend, clean). Runtime click-through with real provider credentials is still the operator's to do.
|
||||
|
||||
- **Phase 1 — surface what exists:** #2 Infrastructure category (DigitalOcean / Hetzner / Vultr / Linode → existing `/cloud`), #3 S3 + Backblaze B2 storage cards (→ existing `/backups/storage`), #4 cross-links on every connected card ("N servers — Servers →", "N domains — Domains →", bucket → Backups, "New service →").
|
||||
- **Phase 2 — complete the tiles:** #5 GitLab source (full OAuth mirror of GitHub, 9 routes), #6 DigitalOcean DNS, #7 GoDaddy DNS (both as new dispatch branches in `dns_provider_service.py`), **#8 SMTP relay** — a real Postfix smarthost (`relayhost` + SASL `sasl_passwd`) with an OS-agnostic `smtplib` connection test; new `EmailRelayConfig` model (password Fernet-encrypted) + `/email/relay` routes + a presets-driven modal (Postmark / SES / Mailgun / SendGrid / custom). All four "coming soon" tiles are now live.
|
||||
- **Phase 3 — domain ownership & expiry:** #9 `RegistrarConnection` model (**Fernet-encrypted** from the start), #10 `RegistrarService` (GoDaddy portfolio + expiry), #11 *not needed as written* — expiry is sourced **live** from the registrar, so no `domains`-table migration was required, #12 the `RegistrarPortfolio` panel on the Domains page ("N days left", colour-coded by urgency, Sync button), #13 registrar card shows "N domains · M expiring ≤30d". **Namecheap** is now live too (XML API; the connect form takes the API key, account username and a whitelisted server IP).
|
||||
- **Phase 4 — S3 in the Files app:** #14 `/files/s3/*` endpoints (browse / read / write / delete / download-url / upload) on `StorageProviderService`, reusing the configured backup bucket; #15 an "S3 bucket" target in the File Manager — paths stay slash-rooted in the UI and map to keys server-side, virtual folders from prefixes, edit/upload/download/delete work, and folders/rename/permissions are disabled. Offered only when an S3/B2 destination is configured.
|
||||
- **Phase 5 — encrypt secrets at rest:** #16 DNS-provider and storage secrets are now Fernet-encrypted (encrypt on write, `decrypt_secret_safe` at point-of-use with a plaintext fallback so legacy rows keep working); #17 an idempotent startup migration (`encrypt_legacy_secrets`) encrypts any pre-existing plaintext values in place. Added `decrypt_secret_safe` + `is_encrypted` to `crypto.py`.
|
||||
- **#18 — credential unification (the optional cleanup):** the last plaintext store (`CloudProvider`, whose `api_key_encrypted` column held plaintext) now encrypts identically to the rest, so **all five stores** use the same `crypto` primitives + startup migration. Added a read-only `ConnectionRegistry` + `GET /api/v1/connections` that presents every connected account as one normalized, secret-free list (the "hub reads one list" single source of truth). A full write-side "one model replaces five" migration was deliberately **not** done — it would risk five working subsystems for no user-facing gain; the uniform encryption + read registry deliver #18's practical value.
|
||||
|
||||
New backend: `models/registrar_connection.py`, `services/registrar_service.py`, `api/registrars.py` (`/api/v1/registrars`, registered). New/changed frontend: expanded `providerCatalog.js` (6 categories, 16 tiles), rebuilt `ConnectProviderModal.jsx` (5 provider kinds), `ConnectionsHub.jsx`, `ProviderCard.jsx` cross-links, `ProviderBrands.jsx` icons, `components/domains/RegistrarPortfolio.jsx`, `services/api/connections.js`.
|
||||
|
||||
**Nothing open** — every task #1–#18 is done. Each external account type (source, infrastructure, DNS, registrar, email relay, storage) connects through the hub, secrets are encrypted at rest across all five stores, and `GET /api/v1/connections` lists them all in one normalized view.
|
||||
|
||||
**Post-roadmap polish:** (1) **domain-expiry notifications** — a daily scheduler fires through the notification channels when a registrar domain crosses 30/14/7/1 days or expires, de-duped via a small state file so each crossing alerts once; (2) **S3 image preview** — File Manager thumbnails and the preview drawer load bucket objects via short-lived presigned URLs (`ImageThumb` is S3-aware); (3) **encryption-health banner** — the hub now consumes `GET /api/v1/connections` and warns if any connection's credentials aren't encrypted at rest (invisible in the happy path).
|
||||
|
||||
**Encryption hardening + tests:** an audit of every secret read/write site caught one miss — `sites_https_service` handed *encrypted* DNS creds straight to the wildcard-cert issuer, so DNS-01 issuance would have received ciphertext and failed. Fixed via a public `DNSProviderService.decrypted_credentials()` (the canonical way to read DNS creds; nothing reads `.api_key` raw anymore), and locked down with `backend/tests/test_provider_secret_encryption.py` — 8 tests proving ciphertext-at-rest + plaintext-on-read across DNS/cloud/storage/registrar, the legacy-plaintext migration (idempotent), and the wildcard regression. 17/17 pass (with the existing `test_sites_https.py`).
|
||||
|
||||
---
|
||||
|
||||
## How to read this document
|
||||
|
||||
- Tasks are **globally numbered (#1 … #18)** so they're individually addressable — e.g. "do #9".
|
||||
- Tasks are grouped into **Phases 0 → 5**, ordered so cheap, high-trust wiring lands before net-new systems. Phases are independently shippable and can be reordered.
|
||||
- Each task lists **Today** (what exists, with paths), **Do** (the concrete change), **Reuse** (what to lean on), and **Done when** (acceptance).
|
||||
|
||||
**Effort legend** (single-developer estimate):
|
||||
|
||||
| Tag | Meaning |
|
||||
|---|---|
|
||||
| **S** | ≤ 2 hours — mostly wiring |
|
||||
| **M** | ~ half a day to a day |
|
||||
| **L** | 1–3 days |
|
||||
| **XL** | multi-day epic; split before starting |
|
||||
|
||||
**Status legend:**
|
||||
|
||||
| Mark | Meaning |
|
||||
|---|---|
|
||||
| 🐛 | Security / correctness gap — worth fixing regardless of roadmap order |
|
||||
| 🟡 | **Almost there** — the backend or model already exists; this is glue |
|
||||
| ❌ | Net-new build |
|
||||
|
||||
---
|
||||
|
||||
## Target: the connections hub as one front door
|
||||
|
||||
Every external account in one categorized surface, each card showing **status + access scope**, and each linking to the page it powers:
|
||||
|
||||
`Source code` · `Infrastructure (servers)` · `DNS & domains` · `Registrars & ownership` · `Email & delivery` · `Storage & backups`
|
||||
|
||||
And the cross-links that make it "one place": a **DigitalOcean** card that says *"3 servers — Manage in Servers"*, an **S3** card that says *"Connected — Browse in Files · Used by Backups"*, a **GoDaddy** card that says *"12 domains · 2 expiring within 30 days — View in Domains."*
|
||||
|
||||
---
|
||||
|
||||
## Phase 0 — Declutter the hub (do first)
|
||||
|
||||
### #1 — Remove the redundant hub intro `[S]` 🟡 — ✅ Done
|
||||
- **Today:** `ConnectionsHub.jsx` rendered a full intro block — accent icon + `<h2>Connections</h2>` + a description paragraph — directly under the sidebar's already-active **Connections** nav label. The heading duplicated the nav; sibling tabs (e.g. `NotificationsTab`) carry no such intro.
|
||||
- **Do:** Delete the intro block so the first category leads the surface.
|
||||
- **Landed:** Removed the `connections-hub__intro` block (icon + `<h2>` + `<p>`), the now-unused `connectedCount` computation and `Link2` import from `frontend/src/components/settings/connections/ConnectionsHub.jsx`, and the `&__intro` / `&__intro-icon` / `&__intro-text` rules from `frontend/src/styles/pages/_connections.scss`. `npm run eslint` on the component returns clean.
|
||||
- **Follow-up (optional):** if the page still feels text-heavy, the per-category blurbs (`providerCatalog.js` `CONNECTION_CATEGORIES[].blurb`) are the next thing to trim — but they group rather than duplicate, so they earn their place.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Surface what already exists (glue, fast wins)
|
||||
|
||||
The highest value-per-hour in the whole roadmap: the backends are built and tested; they're just not in the hub.
|
||||
|
||||
### #2 — Add an **Infrastructure** category that surfaces cloud-server providers `[M]` 🟡
|
||||
- **Today:** `cloud_provisioning_service.py`, `api/cloud_provisioning.py` and `models/cloud_server.py` already exist and are registered in `app/__init__.py` — ServerKit can talk to DigitalOcean / Hetzner / Vultr / Linode — but there is **no entry point in Connections**. (Verify the exact provider list + whether it supports *listing/importing existing* machines vs. only *creating* them, in `cloud_provisioning_service.py`, before wiring the card copy.)
|
||||
- **Do:** Add a `{ key: 'infra', label: 'Infrastructure', blurb: 'Cloud accounts ServerKit can provision and manage servers in.' }` category to `providerCatalog.js`, plus DigitalOcean / Hetzner / Vultr / Linode provider entries with `kind: 'cloud'`. Give `ConnectProviderModal` a `cloud` branch: save the provider API token, then show a count + a "Manage in Servers" link.
|
||||
- **Reuse:** `cloud_provisioning_service`, the existing `ProviderCard`/`ConnectProviderModal` shell, `ProviderBrands.jsx` (already imports `SiDigitalocean`).
|
||||
- **Done when:** A user can paste a DigitalOcean token in Connections, see "Connected," and reach server provisioning from the card.
|
||||
|
||||
### #3 — Surface **S3 / Backblaze B2** storage in the hub `[S]` 🟡
|
||||
- **Today:** `storage_provider_service.py` drives S3-compatible (AWS, Wasabi, MinIO, DO Spaces) + Backblaze B2 for offsite backups, configured only on the **Backups** page's "Storage" tab. The catalog already has a dimmed `s3` tile.
|
||||
- **Do:** Flip the `s3` tile to live and add a Backblaze B2 tile, both reading/writing the **same** storage config the Backups tab uses (`PUT /backups/storage`). Card subtitle shows the bucket + "Used by Backups."
|
||||
- **Reuse:** `storage_provider_service`, `api/backups.py` storage routes, `Backups.jsx` `PROVIDER_LABELS`.
|
||||
- **Done when:** Storage credentials can be set from Connections *or* Backups interchangeably (one source of truth), test-connection works from the card.
|
||||
|
||||
### #4 — Cross-link every surfaced card to the page it powers `[S]` 🟡
|
||||
- **Today:** Cards are self-contained; nothing tells you a connection feeds Servers / Files / Backups / Domains.
|
||||
- **Do:** Add an optional `manageHref` + count to the card summary (e.g. "3 servers", "12 domains, 2 expiring"). Render a quiet link in `conn-card__meta`.
|
||||
- **Done when:** Each connected card answers "what is this connected to?" at a glance — the core of the "one place" promise.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Complete the catalog's own "coming soon" tiles
|
||||
|
||||
These four are already drawn as dimmed tiles; the patterns to make them real are known.
|
||||
|
||||
### #5 — **GitLab** source connections `[M]` 🟡
|
||||
- **Today:** `providerCatalog.js` already lists GitLab as `comingSoon`. GitHub's whole flow lives in `source_connection_service.py` (OAuth → Fernet-encrypted token → repo/branch/manifest listing) behind `api/source_connections.py`.
|
||||
- **Do:** Replicate the GitHub methods for GitLab (different OAuth + API base + `PRIVATE-TOKEN`/`Bearer` header), accept `'gitlab'` in `models/source_connection.py`, add the mirrored routes, flip the tile to `kind: 'github'`-style with a GitLab OAuth-app admin form.
|
||||
- **Reuse:** Everything in the GitHub path; the model's `(user_id, provider)` unique constraint already supports multiple providers per user. Cross-check `components/git/GitProviders.jsx` for any existing multi-provider scaffolding before duplicating.
|
||||
- **Done when:** A user connects GitLab and picks repos on New Service exactly like GitHub.
|
||||
|
||||
### #6 — **DigitalOcean DNS** `[S]` 🟡
|
||||
- **Today:** `dns_provider_service.py` dispatches on a `provider` string with `_cloudflare_*` / `_route53_*` methods; the API routes (`/email/dns-providers`) are already generic. Catalog has a dimmed `digitalocean` DNS tile.
|
||||
- **Do:** Add `_digitalocean_*` branches (`https://api.digitalocean.com/v2/domains`, `Authorization: Bearer`) for list-zones / set-record / delete-record, and a form in `ConnectProviderModal`.
|
||||
- **Reuse:** The dispatcher + `find_zone_for_domain` / `ensure_a_record` already power wildcard SSL and custom-domain attach — DO DNS inherits all of it for free.
|
||||
- **Done when:** A DO-hosted domain can receive auto-created A/wildcard records like Cloudflare does.
|
||||
|
||||
### #7 — **GoDaddy DNS** `[M]` 🟡
|
||||
- **Today:** Same dispatcher as #6. GoDaddy is also a **registrar** (see Phase 3) — start with its DNS role here.
|
||||
- **Do:** Add `_godaddy_*` branches (`https://api.godaddy.com/v1/domains`, `Authorization: sso-key <key>:<secret>` → reuse the Route 53 two-field form shape), and a catalog entry.
|
||||
- **Done when:** GoDaddy-hosted DNS records are managed through the same flow.
|
||||
|
||||
### #8 — **SMTP relay** for outbound mail `[M]` ❌ — ✅ Done
|
||||
- **Today:** The `email` category exists with a dimmed `smtp` tile; the mail server has no outbound-relay connection object.
|
||||
- **Do:** Add an `email`-kind connect form capturing host/port/user/pass/TLS (presets for Postmark / SES / Mailgun) and store encrypted; wire it as the relay for the mail server.
|
||||
- **Done when:** Outbound mail can route through a configured third-party relay.
|
||||
- **Landed:** `EmailRelayConfig` model (single-row, password Fernet-encrypted) + `EmailRelayService` (persist + `smtplib` connection test + apply) + `PostfixService.configure_relay`/`disable_relay` (sets `relayhost` + SASL `sasl_passwd`, `postfix reload`) + `/api/v1/email/relay` GET/PUT/POST-test/DELETE. Frontend: `smtp` tile → live `email` kind; modal `EmailBody` with provider presets (Postmark / SES / Mailgun / SendGrid / custom), STARTTLS + enable toggles, Test/Save/Disable. The Postfix apply is Linux-only and no-ops with a note off-Linux; the `smtplib` test validates credentials on any OS. Verified: `npm run build` + `eslint` (clean) and backend `py_compile` + venv import.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Domain ownership & expiry (the headline net-new: *"when do they expire?"*)
|
||||
|
||||
The one system that genuinely doesn't exist. This is what turns Domains from "DNS + certs" into "the portfolio of names you own, and when they lapse."
|
||||
|
||||
### #9 — `RegistrarConnection` model + encrypted credentials `[M]` ❌
|
||||
- **Today:** No registrar concept anywhere.
|
||||
- **Do:** New `models/registrar_connection.py` mirroring `SourceConnection`: `user_id`, `provider` (`godaddy`/`namecheap`/…), `provider_account_id`, `api_key_encrypted`, `api_secret_encrypted`, timestamps. Store secrets via `encrypt_secret` from the start (don't repeat the DNS plaintext mistake).
|
||||
- **Reuse:** `utils/crypto.py`, the `SourceConnection` shape.
|
||||
- **Done when:** A registrar account can be connected and its credentials are encrypted at rest.
|
||||
|
||||
### #10 — `RegistrarService` (GoDaddy, Namecheap) `[L]` ❌
|
||||
- **Do:** Dispatcher service (`if provider == 'godaddy': _godaddy_list_domains()` …) exposing `list_domains()`, `check_expiry(domain)`, and later `update_nameservers()` / `renew_domain()`. GoDaddy: `GET /v1/domains`. Namecheap: `namecheap.domains.getList`.
|
||||
- **Reuse:** The exact dispatcher shape from `dns_provider_service.py`.
|
||||
- **Done when:** Given a connected registrar, the service returns each domain's registration + expiry date.
|
||||
|
||||
### #11 — Extend the `Domain` model with ownership fields `[S]` ❌
|
||||
- **Today:** `models/domain.py` has only `ssl_expires_at` (cert), `ssl_auto_renew`, nginx/cert paths.
|
||||
- **Do:** Add `registrar` (str), `registrar_connection_id` (FK), `registration_expires_at` (DateTime), `auto_renew_enabled` (bool), `nameservers` (JSON), `last_synced_at` (DateTime). Update `to_dict()`.
|
||||
- **Done when:** A domain row can hold *who it's registered with and when it expires*, distinct from its cert.
|
||||
|
||||
### #12 — Expiry sync + the "expires in N days" UI `[M]` ❌
|
||||
- **Do:** A periodic job (reuse the backup-schedule/cron mechanism) that calls `RegistrarService.check_expiry` for every domain with a `registrar_connection_id` and writes `registration_expires_at` + `last_synced_at`. On `pages/Domains.jsx`, show **expires in N days**, a warning pill under 30 days, auto-renew status, and a manual "Sync now."
|
||||
- **Reuse:** Notification channels (#backups already proves the cron + notify path) for "domain X expires in 14 days" alerts.
|
||||
- **Done when:** The Domains page is a true portfolio view: every name, its registrar, its expiry, color-coded by urgency.
|
||||
|
||||
### #13 — Registrar status on the Connections card `[S]` ❌
|
||||
- **Do:** A "Registrars & ownership" category in the hub; GoDaddy/Namecheap cards show "12 domains · 2 expiring ≤30d — View in Domains" (the #4 cross-link, applied).
|
||||
- **Done when:** The hub answers "is my domain ownership healthy?" without opening Domains.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — S3 as a first-class Files target (*"S3 connects in the files app"*)
|
||||
|
||||
### #14 — `/files/s3/*` endpoints over the storage client `[M]` ❌ — ✅ Done
|
||||
- **Today:** `file_service.py` / `api/files.py` are local-filesystem only (`ALLOWED_ROOTS`); no remote/pluggable backend. `storage_provider_service.py` already holds a working boto3 client.
|
||||
- **Do:** Add `GET /files/s3/browse`, `/read`, `POST /files/s3/write`, `DELETE /files/s3/delete`, `GET /files/s3/info` that map `list_objects_v2` / `get` / `put` / `delete` into the same entry shape `browse` returns (virtual folders from `/`-suffixed prefixes).
|
||||
- **Reuse:** The Phase 1 (#3) storage credentials — no new creds, no new config.
|
||||
- **Done when:** The API can list and transfer bucket objects in the File Manager's data shape.
|
||||
- **Landed:** `StorageProviderService.s3_browse / s3_read / s3_write / s3_upload / s3_delete / s3_presigned_get` + routes `/api/v1/files/s3/{browse,read,write,delete,download-url,upload}`. UI paths are slash-rooted and mapped to keys server-side; folders are virtual (CommonPrefixes); download hands back a short-lived presigned URL; delete removes a single object or a whole prefix. Reuses the configured backup bucket — no new creds.
|
||||
|
||||
### #15 — S3 bucket in the File Manager target picker `[M]` ❌ — ✅ Done
|
||||
- **Do:** Add an "S3 bucket" option to `FileManager.jsx`'s target picker (next to Local + agents). When active, browse by prefix and **disable** ops S3 can't do (mkdir, rename, chmod).
|
||||
- **Done when:** A user browses, uploads to, downloads from and deletes in their bucket from the Files app — the literal ask.
|
||||
- **Landed:** `TargetPicker` gained a backward-compatible `extraOptions` prop; the File Manager shows an "S3 bucket" target when an S3/B2 backup destination is configured, routes browse/read/write/delete/download/upload through the existing `fileApi` adapter, disables folders/rename/permissions via the op guard, hides the local-only sidebar (quick-access/tree) on S3, and shows a context banner. Verified: `npm run build` + `eslint` (clean), backend `py_compile` + venv import.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Harden & unify credentials (security)
|
||||
|
||||
### #16 — Encrypt DNS + storage secrets at rest `[M]` 🐛 — ✅ Done
|
||||
- **Today:** `DNSProviderConfig.api_key`/`api_secret` are plaintext; `storage.json` is only masked-on-read. `encrypt_secret`/`decrypt_secret` already exist and are used by source connections, AI, server and pairing.
|
||||
- **Do:** Wrap reads/writes of DNS + storage + (new) registrar secrets in `encrypt_secret`/`decrypt_secret`.
|
||||
- **Done when:** No third-party secret is persisted in plaintext.
|
||||
- **Landed:** Added `decrypt_secret_safe` + `is_encrypted` to `crypto.py` (decrypt with plaintext fallback so encrypted and not-yet-migrated values coexist). DNS: encrypt in `add_provider`, decrypt at point-of-use via `_api_key`/`_api_secret` in the four header/client builders. Storage: encrypt in `save_config`, decrypt in `get_config` (so `_get_client` and the S3 browser get plaintext). Registrar + SMTP-relay secrets were already encrypted. Verified by an encrypt→decrypt round-trip + legacy-plaintext passthrough + `is_encrypted` detection test.
|
||||
|
||||
### #17 — Migrate existing plaintext secrets `[S]` 🐛 — ✅ Done
|
||||
- **Do:** One-time migration that encrypts any already-stored DNS/storage secrets and records the migration in the migration-history surface.
|
||||
- **Done when:** Existing installs are encrypted with zero user action.
|
||||
- **Landed:** Idempotent `DNSProviderService.encrypt_legacy_secrets()` + `StorageProviderService.encrypt_legacy_secrets()` run on startup inside `create_app()`, encrypting any plaintext values in place (skipping already-encrypted ones via `is_encrypted`). Logs how many it touched; wrapped in try/except so a migration hiccup never blocks boot.
|
||||
|
||||
### #18 — (Optional) one credential abstraction `[L]` ❌ — ✅ Done (read facade + uniform encryption; write-model unification deliberately deferred)
|
||||
- **Do:** Fold the four credential homes (SourceConnection, DNSProviderConfig, storage.json, cloud-provisioning config) behind a single `Connection` interface so every provider stores/scopes/encrypts identically and the hub reads one list.
|
||||
- **Done when:** Adding a provider is one declarative entry + one service, with storage/scoping/encryption inherited.
|
||||
- **Landed:** Delivered as the two valuable, low-risk halves rather than a five-subsystem rewrite. (1) **Uniform encryption** — fixed the last plaintext store: `CloudProvider.api_key_encrypted` (which held plaintext) is now Fernet-encrypted on write, decrypted at point-of-use in `_auth_headers`, with an idempotent `encrypt_legacy_secrets()` migration run at startup alongside the DNS/storage ones. All five stores now use the same `crypto` primitives. (2) **Unified read** — new `services/connection_registry.py` (`ConnectionRegistry.list_all`) + `api/connections.py` (`GET /api/v1/connections`, registered) return every connected account as one normalized, secret-free list; frontend `api.getAllConnections()`. Verified by booting `create_app('testing')` and running the registry live (returns a list; endpoint present in the URL map). **Not done (intentionally):** collapsing the five models into one and migrating their data — high risk, no user-facing benefit; the per-store write paths stay as-is.
|
||||
|
||||
---
|
||||
|
||||
## Future / nice-to-have
|
||||
|
||||
- **More source hosts:** Bitbucket, Gitea/Forgejo (replicate #5).
|
||||
- **More registrars:** Cloudflare Registrar, Porkbun, Namecheap-resellers (extend #10).
|
||||
- **More storage:** Cloudflare R2 / DigitalOcean Spaces / Wasabi presets (free — they're S3-compatible), then GCS / Azure Blob (new clients in `storage_provider_service`).
|
||||
- **Import existing cloud servers** (not just provision new) — list a provider's droplets/instances and adopt them into the fleet, if `cloud_provisioning_service` doesn't already (verify).
|
||||
- **Scoping policy:** decide per-category whether a connection is **per-user** (like GitHub) or **admin-wide** (like DNS) — registrars likely per-user, infra likely admin.
|
||||
|
||||
---
|
||||
|
||||
## Suggested order
|
||||
|
||||
1. **#1** ✅ (done) → **#2 #3 #4** — surface servers + S3 + cross-links. Biggest visible payoff for the least code; directly answers "DigitalOcean servers" and "S3."
|
||||
2. **#9–#13** — domain registrar + expiry. The headline net-new "when do they expire," and the strongest "all in one place" moment.
|
||||
3. **#14 #15** — S3 in Files.
|
||||
4. **#5–#8** — finish the remaining catalog tiles as appetite allows.
|
||||
5. **#16 #17** — encrypt-at-rest (pull earlier if any of this ships to production first).
|
||||
@@ -0,0 +1,218 @@
|
||||
# ServerKit — Per-Site Edge & Horizontal Scaling Spec
|
||||
|
||||
*Splitting the #34 epic — and specifying the **keystone** it shares with #21, #15-TLS, #30-jail, and #8/#25.*
|
||||
|
||||
> **Status:** design only. No code shipped. This doc exists so #34 (and its
|
||||
> prerequisites) can be executed in focused passes **on a real Linux/Docker
|
||||
> host**, where the infra can actually be verified — which is exactly why it
|
||||
> wasn't built blind from the Windows dev environment.
|
||||
|
||||
---
|
||||
|
||||
## 1. Why this doc
|
||||
|
||||
`docs/WORDPRESS_ROADMAP.md` defers **#34 (horizontal scaling)** as *"XL + blocked on
|
||||
the same per-site reverse-proxy/upstream layer as #21."* That deferral is correct,
|
||||
but it undersells how much already exists. A capability sweep of the nginx/SSL/storage
|
||||
services shows the **load-balancing, rate-limiting, caching, per-vhost-log, wildcard-TLS,
|
||||
and S3-upload primitives are already built** — they're just bound to the generic
|
||||
`Application`/domain model, never to a `WordPressSite` running as a `localhost:PORT`
|
||||
container.
|
||||
|
||||
So the real work is three layers, in order:
|
||||
|
||||
1. **The keystone** — a per-site *edge* (public domain → reverse-proxy vhost → the WP
|
||||
container) with auto-TLS. This is the missing infrastructure that blocks **#21, #15-TLS,
|
||||
#30-jail, #8-backend, and the original #25-nginx design** — and it is #34's prerequisite.
|
||||
2. **Stateless WP** — shared media + shared object cache so replicas are interchangeable.
|
||||
3. **Replicas + upstream LB** — multiple WP containers behind the keystone vhost.
|
||||
|
||||
This doc specs all three as numbered phases (`K0–K4` keystone, `H0–H4` scaling), each with
|
||||
**Goal / Do / Reuse / Acceptance / Verifiable-here? / Risk**, plus a dependency graph and a
|
||||
real-host verification checklist.
|
||||
|
||||
---
|
||||
|
||||
## 2. Current reality (verified against the code)
|
||||
|
||||
| Fact | Evidence |
|
||||
|---|---|
|
||||
| A managed WP site is a single `wordpress:${VERSION}-apache` container publishing `${HTTP_PORT}:80` straight to the host; per-site MySQL + per-site Redis (#23). **No domain, no per-site vhost at create.** | `backend/templates/wordpress.yaml` (`ports: "${HTTP_PORT}:80"`) |
|
||||
| `site.url` falls back to the host port unless a domain is attached. | `wordpress_service.py` `_enrich_site_data` (#3) |
|
||||
| **A container-proxying vhost primitive already exists**, incl. HTTPS via cert + HTTP→HTTPS redirect. | `nginx_service.py:391` `create_site(..., ssl_cert, ssl_key)`, `:450` `_with_ssl`, `:535` `add_ssl_to_site` |
|
||||
| **Upstream load-balancing, `limit_req`, `proxy_cache`, and per-vhost log reads already exist** — bound to a generic `domain`/`data` dict, not to a WP site. | `nginx_advanced_service.py:31` `create_reverse_proxy` (`upstreams`→`upstream{}` at `:47`, `proxy_pass http://{upstream}` at `:95/:113`, `limit_req_zone` at `:61`, `proxy_cache_path` at `:68`), `:173` `get_vhost_logs`, `:196` `get_load_balancing_methods` |
|
||||
| Wildcard cert issuance + auto-renew already exist. | `advanced_ssl_service.py:39` `issue_wildcard_cert(domain, dns_provider, credentials, email)`, `ssl_service.py:256` `setup_auto_renewal` |
|
||||
| Subdomain generation for environments already exists. | `environment_domain_service.py:61` `generate_domain(production_domain, env_type, …)` |
|
||||
| S3/B2/MinIO directory upload already exists (for media offload). | `storage_provider_service.py:260` `upload_directory(local_dir, remote_prefix)` |
|
||||
|
||||
**Conclusion:** the gap is *wiring + a public base-domain + statelessness*, not greenfield nginx
|
||||
work. That makes both the keystone and #34 far smaller than "XL from zero" implies — but every
|
||||
phase touches nginx apply/reload, cert issuance, or container orchestration, **none of which is
|
||||
runtime-verifiable on Windows.**
|
||||
|
||||
---
|
||||
|
||||
## 3. Dependency graph
|
||||
|
||||
```
|
||||
┌─────────────────────────── Part 1: KEYSTONE (per-site edge) ───────────────────────────┐
|
||||
│ K0 public base-domain + wildcard DNS/TLS │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ K1 per-site reverse-proxy vhost ──► K2 auto-TLS per site ──► K3 preview URL (#21) │
|
||||
│ │ │ │
|
||||
│ ▼ ▼ │
|
||||
│ K4 per-site access log + limit_req ──► unblocks #30-jail, restores #25-nginx │
|
||||
└────────┬────────────────────────────────────────────────────────────────────────────┘
|
||||
│ (also closes: #15-TLS, #8-backend SSL wiring, #3 already done)
|
||||
▼
|
||||
┌─────────────────────────── Part 2: #34 HORIZONTAL SCALING ─────────────────────────────┐
|
||||
│ H0 stateless WP (shared media + shared object cache) │
|
||||
│ ▼ │
|
||||
│ H1 replica orchestration (internal network; edge publishes, not the container) │
|
||||
│ ▼ │
|
||||
│ H2 upstream LB wiring ──► H3 health/rolling ──► H4 autoscale signal (optional) │
|
||||
└────────────────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Do K0→K2 first** — it alone closes #15-TLS, #8-backend, and #21 (with K3), independent of #34.
|
||||
**#34 cannot start before H0**, and H0/H1 require the keystone's edge to exist (replicas can't each
|
||||
publish a host port).
|
||||
|
||||
---
|
||||
|
||||
## 4. Part 1 — The keystone: per-site edge
|
||||
|
||||
### K0 — Panel-wide public base domain + wildcard DNS/TLS `[M]`
|
||||
- **Goal:** a configurable base domain (e.g. `apps.example.com`) with `*.apps.example.com` DNS and a wildcard cert, so *any* managed site can get a real public URL. This is the single setting whose absence makes every public-URL feature impossible today.
|
||||
- **Do:** add a `base_domain` + DNS-provider binding to settings; on save, issue/refresh the wildcard cert and schedule renewal. Validate the wildcard record resolves before declaring it ready.
|
||||
- **Reuse:** `advanced_ssl_service.issue_wildcard_cert` (`:39`), `ssl_service.setup_auto_renewal` (`:256`), the existing DNS-provider credentials (Connections / `provider_secret` encryption).
|
||||
- **Acceptance:** with a base domain configured, `dig *.base` resolves and a valid `*.base` cert exists.
|
||||
- **Verifiable here?** Config/model/validation logic yes; DNS + cert issuance **real host only**.
|
||||
- **Risk:** registrar/DNS-provider variance; wildcard issuance needs DNS-01 (already supported). If no public base domain is set, the whole edge degrades gracefully to today's `localhost:PORT` behavior — keep that fallback.
|
||||
|
||||
### K1 — Per-site reverse-proxy vhost at create/attach `[L]`
|
||||
- **Goal:** put an nginx vhost in front of each managed WP container so it answers on a real hostname instead of `localhost:PORT`.
|
||||
- **Do:** on create (and on domain-attach), call `NginxService.create_site(name, app_type='docker', domains=[hostname], port=<container published port>)` + `enable_site` + `reload`. Persist the hostname on `WordPressSite`. Make WP proxy-aware: set `WP_HOME`/`WP_SITEURL` to the hostname, trust `X-Forwarded-Proto`/`-For` in `wp-config`, and run the serialized-safe `search-replace` (#5/#9 primitive) from `localhost:PORT` → the hostname.
|
||||
- **Reuse:** `nginx_service.create_site/enable_site/reload` (`:391/:483/:288`), `db_sync_service` search-replace, the `domains.py` attach flow (#8 already wires domain-attach for generic docker apps).
|
||||
- **Acceptance:** a freshly created site is reachable at `http://<hostname>` and `wp-admin` loads with correct URLs (no redirect loop, no mixed `localhost` links).
|
||||
- **Verifiable here?** Template rendering + the `wp-config`/search-replace logic yes; nginx apply + live HTTP **real host only**.
|
||||
- **Risk:** the classic WP-behind-proxy redirect loop (needs `X-Forwarded-Proto` handling); a port is still published in K1 (internal-only comes in H1).
|
||||
|
||||
### K2 — Auto-TLS per site `[M]`
|
||||
- **Goal:** every site is HTTPS by default.
|
||||
- **Do:** for a `*.base` subdomain, serve the K0 wildcard cert via `create_site(ssl_cert=…, ssl_key=…)` (the `_with_ssl` path already does the 80→443 redirect). For an attached custom domain, issue a per-host LE cert. Add `ssl_status` to `WordPressSite` and surface grade/expiry (the #8 `SiteSSLPanel` already renders this once a domain is routed).
|
||||
- **Reuse:** `nginx_service.create_site(ssl_cert, ssl_key)` (`:391`) / `add_ssl_to_site` (`:535`), `ssl_service`/`advanced_ssl_service`, the #8 frontend.
|
||||
- **Acceptance:** the site loads over HTTPS with a valid cert; HTTP redirects to HTTPS.
|
||||
- **Verifiable here?** `ssl_status` model + wiring yes; cert + TLS handshake **real host only**.
|
||||
- **Risk:** custom-domain certs need DNS pointed first — keep a "pending DNS" state.
|
||||
|
||||
### K3 — Preview URL before DNS (#21) `[S–M, on top of K0–K2]`
|
||||
- **Goal:** a working HTTPS preview link the instant a site exists, pre-DNS.
|
||||
- **Do:** mint `<site|hash>.preview.<base>` via the K0 wildcard (covered by the wildcard cert, so no per-host issuance). Optionally a basic-auth gate (the env-pipeline already has basic-auth, P4). This **is** #21 once K0–K2 exist.
|
||||
- **Reuse:** `environment_domain_service.generate_domain` (`:61`), K0 wildcard, `create_site`.
|
||||
- **Acceptance:** every new site shows an immediately-working `https://….preview.base` link.
|
||||
- **Verifiable here?** Hostname generation yes; live preview **real host only**.
|
||||
|
||||
### K4 — Per-site access log + `limit_req` jail (restores #25-nginx, unblocks #30-jail) `[M]`
|
||||
- **Goal:** a per-site nginx access log on the host + brute-force protection — the exact signals #25 and #30 had to defer because the container model exposes none.
|
||||
- **Do:** emit a per-site `access_log` path in the K1 vhost. Add a `limit_req` zone for `wp-login.php`/`xmlrpc.php` via `create_reverse_proxy` (it already emits `limit_req_zone`/`limit_req`). Point #25's analytics at `get_vhost_logs` (a real per-vhost log) instead of/alongside the `docker logs` source it fell back to; this also restores `%D` response-time once we own the `LogFormat`.
|
||||
- **Reuse:** `nginx_advanced_service.create_reverse_proxy` (`:31`, `limit_req` at `:61/:85`), `get_vhost_logs` (`:173`), `security_service` Fail2ban (optional, watching the new log).
|
||||
- **Acceptance:** repeated `wp-login` hits get throttled; per-site visits/5xx/slow-pages come from the vhost log.
|
||||
- **Verifiable here?** Log-parsing + zone-rendering yes; live throttling + log emission **real host only**.
|
||||
|
||||
**After Part 1:** #15-TLS ✅, #21 ✅, #8-backend ✅, #30-jail ✅, #25 (response-time/slow-pages) ✅ — independent of #34.
|
||||
|
||||
---
|
||||
|
||||
## 5. Part 2 — #34 horizontal scaling
|
||||
|
||||
> Built entirely on the keystone. The mental shift: in H1 the WP container stops publishing a
|
||||
> host port; the **edge vhost (K1)** becomes the only public entry and load-balances across
|
||||
> internal replicas.
|
||||
|
||||
### H0 — Make WP stateless `[L]`
|
||||
- **Goal:** replicas must be interchangeable — no replica-local state.
|
||||
- **What's already fine:** the **object cache is already shareable** — the #23 Redis is one service in the site's compose stack, so N WP replicas pointing at the same `redis` service share it automatically. No change needed there.
|
||||
- **The real statefulness is two things:**
|
||||
1. **Uploads / `wp-content/uploads`** (local disk per replica). **Decision (open):**
|
||||
- *Option A — S3/object offload* (a media-offload plugin writing to the site's configured `storage_provider`). Pro: truly stateless, scales infinitely. Con: a plugin dependency (mild tension with the WP-CLI-over-plugin thesis), egress cost, and rewriting existing media URLs. Reuse `storage_provider_service.upload_directory` (`:260`) + creds.
|
||||
- *Option B — shared volume* (NFS/CIFS or a Docker named volume shared across replicas on one host). Pro: no plugin, transparent. Con: needs shared-FS infra; single-host only unless NFS; locking edge-cases.
|
||||
- **Recommendation:** Option A for multi-host scale; Option B as a single-host MVP. Spec both; pick at execution.
|
||||
2. **On-disk page cache** — if #22 landed a *disk-writing* page-cache plugin, that's replica-local and must be moved to Redis or disabled under LB. Verify #22's cache backend before H1.
|
||||
- **Acceptance:** uploading media on replica A is immediately served by replica B.
|
||||
- **Verifiable here?** Offload-config + URL-rewrite logic yes; cross-replica consistency **real host only**.
|
||||
- **Risk:** media migration for *existing* sites; plugin licensing for offload.
|
||||
|
||||
### H1 — Replica orchestration `[L]`
|
||||
- **Goal:** run N WP containers for one site.
|
||||
- **Do:** change the stack so the WP service is replica-able (`deploy.replicas` under swarm, or N enumerated services / `docker compose up --scale` on a compose host) on an **internal** network — **drop the `${HTTP_PORT}:80` host publish**; only the edge nginx reaches them. This is a **breaking change to the single-container model**, so it needs a per-site opt-in + a migration path (existing sites stay single-container until "Enable scaling").
|
||||
- **Reuse:** the `wordpress.yaml` template + the `_ensure_*_in_stack` additive-compose pattern (#23 redis injection is the proven precedent).
|
||||
- **Acceptance:** `docker ps` shows N WP replicas for the site, none publishing a host port.
|
||||
- **Verifiable here?** Template rendering yes; actual replicas **real host only**.
|
||||
- **Risk:** the publish→internal flip must be coordinated with K1 (edge must exist first or the site goes dark); MySQL stays single (not replicated here — that's a separate epic).
|
||||
|
||||
### H2 — Upstream load-balancing wiring `[M]`
|
||||
- **Goal:** the edge vhost balances across the H1 replicas.
|
||||
- **Do:** upgrade the K1 vhost to an upstream-backed one: feed the replica endpoints to `create_reverse_proxy(upstreams=[…], method=…)`. Anonymous WP is stateless → round-robin; logged-in/cart needs affinity → `ip_hash` or cookie-sticky (expose via `get_load_balancing_methods`).
|
||||
- **Reuse:** `nginx_advanced_service.create_reverse_proxy` (`upstream{}` at `:47`, `proxy_pass` at `:95`), `get_load_balancing_methods` (`:196`).
|
||||
- **Acceptance:** requests distribute across replicas; killing one replica doesn't drop traffic.
|
||||
- **Verifiable here?** Upstream-config rendering yes; live balancing/failover **real host only**.
|
||||
- **Risk:** session affinity for WooCommerce carts; cache coherence across replicas (mitigated by H0 shared Redis).
|
||||
|
||||
### H3 — Health checks + rolling deploys `[M]`
|
||||
- **Goal:** safe scale up/down and zero-downtime deploys.
|
||||
- **Do:** per-replica health probe; drain a replica out of the upstream before stop; a scale API on the `WordPressSite`. Tie deploys (#13/#29) into a rolling pattern: update one replica, health-check, proceed.
|
||||
- **Reuse:** `environment_health_service` (#26 poller), `nginx_advanced_service` (rewrite upstream on scale), #29 safe-update health gate.
|
||||
- **Acceptance:** scaling and deploys cause no failed requests.
|
||||
- **Verifiable here?** Orchestration logic yes; zero-downtime claim **real host only**.
|
||||
|
||||
### H4 — Autoscale signal (optional) `[M]`
|
||||
- **Goal:** scale on load.
|
||||
- **Do:** drive H3's scale API from the #25 per-site traffic metrics (now real, via K4). Thresholds + cooldown.
|
||||
- **Reuse:** #25 analytics, H3 scale API.
|
||||
- **Acceptance:** sustained load adds a replica; quiet removes one.
|
||||
|
||||
---
|
||||
|
||||
## 6. Verifiable on Windows vs. needs a real Docker host
|
||||
|
||||
| Verifiable here (pytest / unit) | Real Linux+Docker host only |
|
||||
|---|---|
|
||||
| `WordPressSite` schema additions (hostname, ssl_status, scaling flags, replica count) | nginx config **apply + reload** |
|
||||
| nginx **template/string rendering** (vhost, upstream, limit_req, ssl block) | Let's Encrypt / wildcard **cert issuance** |
|
||||
| `wp-config` mutation + serialized search-replace logic | live HTTP / HTTPS, redirect-loop checks |
|
||||
| service unit logic with mocked shell/Docker | **container replicas**, `--scale`, internal networking |
|
||||
| API routes + RBAC + workspace scoping | **load-balancing / failover** behavior |
|
||||
| media-offload config + URL-rewrite logic | cross-replica media + cache consistency |
|
||||
| `limit_req` zone generation | actual brute-force **throttling** |
|
||||
|
||||
→ Each real-host item gets a **manual verification checklist** in the executing PR; nothing infra
|
||||
ships claimed-working until exercised on a host (per the project's verify-before-claiming bar).
|
||||
|
||||
---
|
||||
|
||||
## 7. Sequencing recommendation
|
||||
|
||||
1. **K0 → K1 → K2** — the highest-value slice. Closes **#15-TLS, #8-backend**, and (with **K3**) **#21**. Ship and verify on a host *before* touching #34.
|
||||
2. **K4** — closes **#30-jail** and restores **#25** response-time/slow-pages.
|
||||
3. **H0 → H1 → H2** — the #34 MVP (stateless + replicas + LB). Gate H1 behind a per-site "Enable scaling" opt-in so the single-container model stays the default.
|
||||
4. **H3 → H4** — production hardening + autoscale.
|
||||
|
||||
Each arrow is a separately shippable, separately verifiable PR. **#34's "Done when" (N replicas behind
|
||||
a balancer with consistent media + cache) is reached at the end of H2.**
|
||||
|
||||
---
|
||||
|
||||
## 8. Open decisions (resolve at execution)
|
||||
|
||||
- **Media:** S3 offload (Option A) vs shared volume (Option B) — pick per deployment topology (multi-host ⇒ A).
|
||||
- **Port model:** the K1-publishes-a-port → H1-internal-only flip is a breaking change; needs a migration for existing sites and a clear opt-in.
|
||||
- **MySQL:** stays single-instance in this spec. DB replication/clustering is a distinct epic, explicitly out of scope for #34.
|
||||
- **Panel vs sites:** the *panel's* single-gevent-worker constraint (agent gateway, see `CLAUDE.md`/`ARCHITECTURE.md`) is unrelated — this LB is for the **managed sites**, not the panel. Don't conflate.
|
||||
- **Plugin thesis:** media-offload (Option A) and any disk→Redis page-cache move may need plugins; weigh against the WP-CLI-over-plugin preference.
|
||||
|
||||
---
|
||||
|
||||
*Cross-references: `docs/WORDPRESS_ROADMAP.md` #34, #21, #15, #8, #25, #30, #22, #23. This spec is the
|
||||
"split before starting" the roadmap asks for on every `XL`.*
|
||||
@@ -0,0 +1,348 @@
|
||||
# ServerKit Redesign Map
|
||||
|
||||
> Status: **pass 1 COMPLETE — pass 2 (parity) IN PROGRESS (2026-06-11)** — all 22 view-groups shipped a first
|
||||
> restyle on `dev`, but a fresh audit against the prototype (`_serverkit_design_extract`) found the pass-1 work
|
||||
> stops short of real parity on several pages. See **§8** for the ranked gap list. Remaining: §8 parity items,
|
||||
> §5 backend gaps, open §6 decisions 3/4/5/6. · Owner: Juan ·
|
||||
> Source design: clickable prototype (`ServerKit.zip` → `serverkit/view_*.jsx` + `styles.css`) · Target: the live
|
||||
> modular app under `frontend/src` + `backend/app`.
|
||||
|
||||
This is the working map for adopting the new ServerKit design across the app. It was built by comparing
|
||||
**every prototype view** against its **current production page** (22 view-groups analyzed). Read §0–§1 first;
|
||||
they set the thesis and the rules. §4 is the per-page checklist. §5 is the backend work. §6 is the decisions
|
||||
that are yours to make.
|
||||
|
||||
---
|
||||
|
||||
## 0. What this redesign actually is
|
||||
|
||||
**It is a front-end re-skin + information-architecture (IA) overhaul — not a feature build.**
|
||||
|
||||
The prototype is a *standalone clickable mockup* (React via CDN + Babel, mock `window.DATA`). The live app
|
||||
**already implements ~90% of what it shows** at the backend (62 API blueprints, 100+ services, 60+ models) and
|
||||
mostly at the frontend too (45+ pages). So for most views the work is: **restyle the existing page into the new
|
||||
visual language, reshuffle its IA, and slot the result into the existing modular structure** — *not* a rewrite.
|
||||
|
||||
A recurring trap: **the prototype is frequently a _subset_ of the live app** (Servers, Docker, Files, Git,
|
||||
Security, Email all show *less* than we already ship). Taking it literally would delete working capabilities
|
||||
(tabs, filters, bulk actions, file browsers, webhook management, agent fleet rails). The rule is **restyle +
|
||||
selectively borrow IA, re-home what the mockup omits, never silently drop a working feature.**
|
||||
|
||||
---
|
||||
|
||||
## 1. The modularity contract (golden rules)
|
||||
|
||||
These keep the redesign inside the structure you already like:
|
||||
|
||||
1. **Remap token _values_ behind existing token _names_.** The new palette (periwinkle accent `#6d7cff`,
|
||||
3-tier surface ramp, 4-tier text, new `cyan`/`violet` semantics, `*-bg` washes) lands in
|
||||
`styles/_theme-variables.scss` + `styles/_variables.scss` by **changing values**, not renaming. Every page's
|
||||
SCSS reads `$bg-*/$text-*/$accent-*` today — a repo-wide rename is the one thing that would break everything.
|
||||
Add genuinely new tokens (`--cyan`, `--violet`, `--accent-bright`) **additively**. Keep light-theme overrides
|
||||
and the `*-raw` values used by SCSS `fade()` in sync.
|
||||
2. **One feature = one page + one SCSS partial + one API module.** Restyling a page touches
|
||||
`pages/X.jsx` and `styles/pages/_x.scss` (and its `services/api/x.js` only if a new endpoint is added).
|
||||
Don't fork a new architecture.
|
||||
3. **Build shared primitives once (§3), then consume them everywhere.** No per-page bespoke pills/charts/tables.
|
||||
4. **Preserve the superset.** When the mockup shows fewer tabs/controls than today, re-home the missing ones
|
||||
(a drawer section, a settings sub-route, a secondary surface) — don't delete them.
|
||||
5. **Keep deep-linking working.** Tabs are wired through `useTabParam`/`VALID_TABS`. If you change a tab set,
|
||||
update `VALID_TABS` and add redirects for old `?tab=` values.
|
||||
6. **Bind to real `api.*`.** Drop all `window.DATA` mock wiring from the prototype; it is throwaway.
|
||||
7. **One logical change per commit**, focused diffs, branch prefixes (`feature/redesign-*`).
|
||||
|
||||
---
|
||||
|
||||
## 2. Phase 0 — Design System & Chrome foundation (do this first)
|
||||
|
||||
Everything else depends on this. Effort: **L**. **Status: ✅ done (2026-06-07)** — tokens remapped
|
||||
(dark/light/system) + prototype tokens added; IBM Plex self-hosted; accent ramp runtime-derived in
|
||||
`ThemeContext`; shared primitives built in `components/ds/`; sidebar restyled (gradient rail, mono section
|
||||
headers, left accent bar, dimmed icons, restyled footer/user-menu, 250px). SCSS compiles, ESLint 0 errors.
|
||||
Git stays **plugin-owned** under Infrastructure (no core duplicate — avoids a dead link when the plugin is off).
|
||||
|
||||
- **Fonts** → IBM Plex Sans + IBM Plex Mono, **self-hosted** (OFL-licensed `.woff2` vendored in
|
||||
`frontend/public/fonts/` via `frontend/scripts/fetch-fonts.mjs`, declared in `styles/base/_fonts.scss`).
|
||||
**No Google Fonts / third-party CDN** — a self-hosted control panel must not leak every visitor's IP + usage
|
||||
to Google, and self-hosting also works on air-gapped/offline installs. `$font-main`/`$font-mono` retargeted in
|
||||
`_variables.scss`; `system-ui` fallback keeps the app working if the woff2 files are absent.
|
||||
- **Tokens** → remap in `_theme-variables.scss`/`_variables.scss` per rule §1.1: surface ramp
|
||||
(`--surface`/`-2`/`-3` + near-black bg), 4-tier text (`--text`/`-dim`/`-faint`/`-ghost`), accent
|
||||
`#6d7cff` + `--accent-bright`/`--accent-dim`/`--accent-bg`/`--accent-glow`, **new** `--cyan`/`--violet`
|
||||
(+ `-bg`), radius scale (10/7/14), shadow scale, and the `.app` radial accent wash.
|
||||
- **Sidebar** (`styles/layout/_sidebar.scss` + `components/Sidebar.jsx` + `components/sidebarItems.js`):
|
||||
gradient bg, 34px gradient logo tile, mono-uppercase section headers, left accent bar + glow on active item,
|
||||
optional per-item **badge dot** slot. Add a top-level **Git** item under Infrastructure; align preset
|
||||
membership to the prototype (Full / Web Hosting / Email Admin / Docker-DevOps / Minimal).
|
||||
**Keep** the current richer structure: collapsible sub-items, `WorkspaceSwitcher`, plugin-nav injection,
|
||||
dev-tools group. (Preset persistence via `sidebar_config`, theme/accent via `ThemeContext` localStorage —
|
||||
both already exist; verify the dark/light/**system** trio.)
|
||||
|
||||
---
|
||||
|
||||
## 3. Shared component library (build once → reused everywhere)
|
||||
|
||||
These recur across nearly every view. Build them in `components/ui/` (or `components/common/`) with styles in
|
||||
new partials (`styles/components/_charts.scss`, `_datatable.scss`, `_drawer.scss`, `_kpi.scss`). **This is the
|
||||
highest-leverage work in the whole redesign** — most page tasks become trivial once these exist.
|
||||
|
||||
| Primitive | New / Reuse | Used by | Notes |
|
||||
|---|---|---|---|
|
||||
| **Pill / StatusPill** | NEW | ~all | dot + label, kinds green/amber/red/gray/cyan. Replaces ad-hoc `Badge`/bespoke pills. |
|
||||
| **EnvTag** | NEW | wp, services, dashboard, workspaces | PROD / DEV / STAGING / SERVICE colored tag. |
|
||||
| **SegControl** | NEW | dashboard, monitoring, backups, services, security, appearance, filters | segmented toggle; replaces native `<select>`/`filter-chip`. |
|
||||
| **KPI / MetricCard** | NEW | dashboard, domains, docker, git, cron, monitoring, services, wp, email, security, workspaces | icon chip + value + trend + sub. |
|
||||
| **AreaChart** | NEW (consolidate `MetricsGraph`) | dashboard, servers, services, wp, monitoring, email | multi-series smooth area, gradient fill, **theme-token colors** (move hard-coded hex out). |
|
||||
| **Sparkline** | NEW | kpi strips, monitors table | tiny inline polyline. |
|
||||
| **DataTable (`.dtable`)** | NEW shared style | wp-list, servers, docker, databases, domains, services, cron, backups, security, email, settings | dense table; `cell-name`/`cell-mono`/`kind-ico`; selectable + bulk-toolbar variant. |
|
||||
| **Ckbox (tri-state)** | NEW | selectable tables (wp-list first) | header select-all + per-row. |
|
||||
| **Drawer + Scrim** | NEW — **build on existing `components/ui/sheet.jsx`** | domains, backups (restore), cron, git (repo), services (peek), infra (SSH/logs) | right slide-over; **unifies ~4 divergent drawers today** (logs-drawer bottom-dock, dx-inspector, preview-drawer, ai-drawer). |
|
||||
| **svc-tile** (gradient initial avatar) | NEW | wp, services, workspaces, marketplace, db | first-letter tile, hue hashed from name (`svcGrad`). |
|
||||
| **gauge** (inline mini bar) | NEW | servers, docker, services, email, wp(db), domains | thin threshold-colored fill (red>75 / amber>50). |
|
||||
| **ScoreGauge** (SVG ring) | NEW | security overview, wp security posture, email reputation | donut + score/label. |
|
||||
| **Heatmap** (contribution grid) | NEW | backups overview | 18-week daily intensity. |
|
||||
| **feed-item** (activity feed) | NEW | dashboard, wp, security, backups, git, services | colored dot + html text + time. |
|
||||
| **Switch** | **REUSE** `components/ui/switch.jsx` | settings, security, schedules, toggles | restyle to gradient-on. |
|
||||
| **Icon** | **REUSE** `lucide-react` | all | do **not** add the prototype's parallel icon registry; map names. |
|
||||
|
||||
---
|
||||
|
||||
## 4. Per-page change map
|
||||
|
||||
Effort: S/M/L/XL. Nature: **Restyle** (look only) · **+IA** (layout/tab/route reshuffle) · **+BE** (needs new backend to be fully real).
|
||||
"Update" = existing files to restyle. "Create" = genuinely new files. All paths under `frontend/src` unless noted.
|
||||
|
||||
| # | View | Effort | Nature | Update | Create | Backend gap (→ §5) |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 0 | **Design system + chrome** | L | Restyle+IA | `_variables.scss`, `_theme-variables.scss`, `layout/_sidebar.scss`, `Sidebar.jsx`, `sidebarItems.js`, `index.html` | shared primitives (§3) | none (badge data minor) |
|
||||
| 1 | **Dashboard** | M | Restyle+IA | `pages/Dashboard.jsx`, `MetricsGraph.jsx`, `pages/_dashboard.scss` | ServerSwitcher, ActivityFeed | activity-feed source (maybe) | **✅ pass 1 done** — metric tiles → `MetricCard`, apps status → `Pill`, chart retinted to new palette (kept the real `MetricsGraph` intact), dotsep meta. Deferred: server-switcher dropdown + activity feed. |
|
||||
| 2 | **Servers list + detail** | L | Restyle+IA | `pages/Servers.jsx`, `pages/ServerDetail.jsx`, `pages/_servers.scss` | — (reuse MetricsGraph) | reboot cmd, per-server SSH launch; region/load = mock-only | **✅ top-bar migrated** — built shared `SERVER_TABS`; `PageTopbar` (Servers/Agent Fleet/Fleet Monitor/Cloud/Config Templates) added to all 5 pages; **sidebar sub-menu removed**. Main Servers page: top bar added ABOVE the ops workspace — **fleet rail / groups / workbar / bulk / pairing fully preserved** (no over-trim). Sub-page headers swapped to PageTopbar (actions kept). **List body restyled** — the existing `.servers-table` (already capable: bulk-select/group/telemetry/actions) got the demo's dense look: mono uppercase headers + thin token-colored gauges (CPU=accent-bright, RAM=cyan, Disk=green). Region/Load columns omitted (mock-only, no backend). **✅ ServerDetail tabs restyled** — header → demo detail-header (surface gradient + accent wash, mono dotsep meta, `Pill` status); overview KPI tiles → spec-card look with thin `Gauge` bars (CPU/RAM/Disk = accent-bright/cyan/green); tab strip → accent underline; data/services/packages tables → dense `sk-dtable` spec (scoped fixes over their shadcn-var partials); docker/cron/cloudflared tabs reskinned; dead blocks dropped. List/ops styles untouched. Deferred: TokenModal internals (shared with list's Add-Server modal), `serverdetail/ServicesTab.jsx` Badge→Pill (shared file), `_server-packages/_server-services.scss` proper token migration. |
|
||||
| 3 | **WordPress list** | L | Restyle+IA+BE | `pages/WordPress.jsx`, `pages/_wordpress.scss` | DataTable usage | enrich `get_sites` payload (plugins/updates/visits/uptime/server/php/env); optional bulk route | **✅ top-bar migrated (LAST group — sidebar now fully flat)** — shared `WORDPRESS_TABS` (WordPress/Pipeline); `PageTopbar` on WordPress + WordPressProjects; **sidebar sub-menu removed** (Import/Create actions kept; Pipeline tab now always-visible, was wpInstalled-gated). **List body restyled** — the `.wp-site-card` grid is now a dense `.sk-dtable` (Site tile / Environments / Version / Status `Pill` / tag chips / Open-Site + WP-Admin links), with a status `SegControl` (All/Running/Stopped) + the kept tag filter. Omitted SSL/plugins/visits/uptime/server columns (not in `get_sites` — no list backend) per restyle-first. **Follow-up:** multi-select + bulk ops (needs a bulk route or per-site fan-out), list-payload enrichment. |
|
||||
| 4 | **WordPress detail (tabbed)** | **XL** | Restyle+IA+BE | `pages/WordPressDetail.jsx` (owns all 14 tabs), `pages/_wordpress.scss`, `_applications.scss` | header env-switcher, FilesDrawer/code-viewer, StatCard/gauge/bar-h | DB largest-tables, OPcache/extensions, uptime response-time + 90d, analytics referrers/devices, posture score | **✅ restyled (FLAT tabs — §6.2 decided 2026-06-11)** — `VALID_TABS`/deep links byte-identical; header → demo site-header (WP tile + status dot, `Pill` + `EnvTag`, mono meta) + **real-data env-switcher** (binds `site.environments`, navigates env ids); all `app-*` overrides scoped under `.wp-detail-page` (**`_applications.scss` untouched** — Applications keeps its look until its own pass); per-tab: KPI strips, `sk-dtable` lists with update chips, hash-chip git feed, retinted REAL recharts, severity chips, `--bg-code` wells, run-row Pills. `HealthDot` fixed (referenced nonexistent `--color-success`); EnvironmentCard staging-mislabeled-DEV fixed. Deferred (§5 gaps): largest-tables, OPcache/extensions, response-time/90d, referrers/devices, posture ScoreGauge, FilesDrawer. |
|
||||
| 5 | **Docker** | M | Restyle | `pages/Docker.jsx`, `pages/_docker.scss` | KPI tiles | none (strict subset of current) | **✅ pass 1 done** — added `MetricCard` KPI strip (Containers/Images/Volumes/Networks from existing `stats`) atop `dx-main`, restyled status filter → segmented control. KEPT the richer dx- rail/5-tabs/inspector/exec/multi-server. Deferred: per-container accent dot, Projects KPI, logs modal→drawer. |
|
||||
| 6 | **Database Explorer** | M | Restyle | `pages/Databases.jsx`, `databases/ConsoleTab.jsx`, `SourceTree.jsx`, `ResultsGrid.jsx`, `pages/_databases.scss` | syntax-highlight/gutter editor wrapper | optional "Export as SQL" dump | **✅ pass 1 done** — page already matched the target shell (token-aligned in Phase 0); added engine status-dot glow, green result count, `UTF-8` + `● Connected` status-bar segments. Deferred: syntax-highlight editor + gutter, `+` new-tab pill, ctx-menu Browse-rows/Export-SQL, semantic cell tints. |
|
||||
| 7 | **File Manager** | M | Restyle+IA | `pages/FileManager.jsx`, `file-manager/FolderTree.jsx`, `PreviewDrawer.jsx`, `ContextMenu.jsx`, `pages/_file-manager.scss` | `file-manager/highlight.js` | cloud/S3 sources = **out of scope** | **✅ top-bar migrated** — shared `FILE_TABS` (Files/FTP Server); `PageTopbar` on both pages (FileManager top bar above its fullscreen browser; FTP header swapped, conditional actions kept); **sidebar sub-menu removed**. **✅ body restyled** — SCSS-only reskin to the demo's flush three-pane `.fmgr` console (toolbar/rail/listing/status joined by 1px borders, mono eyebrow rail groups, demo tree rows, dense sticky-header list, transparent grid cards, mono status bar + crumbs); all capabilities kept (uploads/bulk/type filters/disk mounts/remote targets), zero JSX changes; dead pre-topbar blocks dropped. **✅ FTP body restyled (group complete)** — StatStrip → `MetricCard` KPI strip, users + connections → `.sk-dtable` + `Pill`, mono eyebrows, log viewer on `--bg-code`, icon-font spans → lucide (was rendering literal words). Deferred: render extra config fields the API already returns (`pasv_enable`, `max_clients`…), config-editing form (net-new surface). **Remaining follow-up:** syntax-highlight preview (`file-manager/highlight.js`), TargetPicker → demo env-switch menu (optional). |
|
||||
| 8 | **Domains** | L | Restyle+IA+BE | `pages/Domains.jsx`, `pages/_domains.scss` | DomainDrawer (SSL/registration/DNSSEC/NS + inline DNS records) | registrar, registration-expiry, DNSSEC, nameservers, registration auto-renew, status (WHOIS) | **✅ migrated (first top-bar page)** — built shared **`PageTopbar`** ds primitive; Domains now uses the demo's top-bar layout with routed sub-nav (Domains/DNS Zones/SSL) replacing the **removed sidebar sub-menu**; KPI strip + segmented filter + `.sk-dtable` + detail **Drawer**. Omitted unbacked columns (registrar/DNSSEC/nameservers — no WHOIS backend). **Trio complete:** DNSZones + SSLCertificates pages now render the same `PageTopbar` (shared `DOMAIN_TABS`), so the Domains/DNS/SSL tab group persists across all three. **DNS/SSL bodies restyled** — DNS records → dense `.sk-dtable` with colored record-type chips (`.dns-rtype` per A/CNAME/MX/TXT/…) + mono content; SSL cert status → `Pill` (green Valid / amber Expiring). Domains trio now fully on the new look. |
|
||||
| 9 | **Monitoring** | **XL** | Restyle+IA+BE | `pages/Monitoring.jsx`, `pages/_monitoring.scss` | `services/api/monitoring.js`, monitors/status/incidents subviews | synthetic monitors (HTTP/Ping/Port/Keyword); **status pages + incidents already have backend** — wire in; request-volume/p50-p95 per-app likely gap | **✅ top-bar migrated** — shared `MONITOR_TABS` (Monitoring/Status Pages); `PageTopbar` on both pages; **sidebar sub-menu removed** (Refresh + Start/Stop and Create-Page actions preserved). **✅ body restyled** — StatStrip → `MetricCard` KPI strip, current metrics → host-card grid (icon tile + `Pill` + thin token-colored `Gauge`s + mono host-mini footer), active alerts + history → alert-row pattern (severity dots, red-wash firing chips), rules/delivery tabs reskinned (Pills, mono eyebrows); all CRUD/scheduler/channels kept; killed the `.alert-item` collision with `_servers.scss`. Deferred (backend gaps §5): synthetic monitors, response-time/request-volume charts (page has no time-series — nothing faked), per-host fleet checks. **✅ StatusPages body restyled (group complete)** — Badges → `Pill`s, hero `comp-dots` strip (real component statuses), metrics → `sk-spec-card`, incidents → `.inc-state`/`.inc-impact` mono chips + state-tinted washes, rail visibility pills; all CRUD/check/transition flows kept. |
|
||||
| 10 | **Backups** | **XL** | Restyle+IA+BE | `pages/Backups.jsx`, `pages/_backups.scss` | RestoreDrawer, Heatmap | activity timeseries, GFS retention, multi-destination storage, selective/clone restore, per-snapshot duration/progress | **✅ body restyled** — `MetricCard` KPI strip (incl. previously-unrendered `file_backups` + conditional remote card); backups → dense `sk-dtable` (type-tinted tiles, mono type chips, remote-sync `Pill`s, `SegControl` filter); schedules → dense table with cron-chip times; storage tab → real-data spec-cards + `SegControl` provider picker; restore modal → amber warn + `sk-info-row`s (stays a modal). Deferred (§5): heatmap/timeseries, GFS, multi-destination, selective/clone restore, live progress, RestoreDrawer. |
|
||||
| 11 | **Git** | L | Restyle+IA+BE | `pages/Git.jsx`, `pages/_git.scss`, `services/api/files.js` | RepoDeployDrawer | provider OAuth connect/disconnect + provider list; Gitea storage/users/runners metrics | **✅ body restyled** — `MetricCard` strip (status/URL/SSH/version); repos → dense `sk-dtable` (mono branch chips, stars/forks); repo detail re-tinted (mono tree, accent hash chips); webhooks → dense table (brand tiles, `Pill`s, all actions); deployments → feed rows with status `Pill`s + rollback/redeploy; icon-font close spans → lucide. Git owns its own log-output styles now. Deferred (§5): provider OAuth cards, Gitea metrics KPIs, RepoDeployDrawer; repos/webhooks/deploys KPI counts (lazy-loaded — would fake zeros). |
|
||||
| 12 | **Terminal / Logs** | L | Restyle+IA | `pages/Terminal.jsx`, `pages/_terminal.scss` | console/TargetRail, TerminalPane, LogsPane (delegate to existing consoles) | unified targets endpoint; live streaming for non-file targets | **✅ body restyled** — Log Files/Journal tabs → flush console frame (`.con-rail`-style target list, mono eyebrow groups, accent-bg active rows, log well on `--bg-code`); Processes → same frame + sk-dtable-spec sortable table with token gauges; Services cards re-tinted with status stripes; statuses → `Pill`s; Terminal now owns its `proc-chip` filter chips (dependency on `_templates.scss` `.filter-chip` removed); hashColor/priority palettes retinted. Deferred: unified target rail + live non-file streaming (backend gaps), legacy block kept for shared consumers (JournalControls/ProcessTable/ServiceCard). |
|
||||
| 13 | **Services (list/new/detail)** | L | Restyle+IA+BE | `pages/Services.jsx`, `NewService.jsx`, `ServiceDetail.jsx`, `service-detail/OverviewTab.jsx`, `MetricsTab.jsx`, 3 partials | TemplateCatalog, area charts | per-service metrics history + requests/min; template-catalog source; image/scratch create paths | **✅ top-bar migrated** — shared `SERVICE_TABS` (Services/New Service/Templates/Deploy Activity); `PageTopbar` on all 4 group pages; **sidebar sub-menu removed**. NewService breadcrumb folded into the active tab; Templates search + Deployments live/refresh actions preserved. **NewService method-card chooser restyled** to the demo's centered cards (GitHub OAuth + manifest flows kept). **Services list body restyled** — StatStrip → `MetricCard` KPI strip (Running/Stopped/Total/Last Deploy), status → `Pill`, mono dense list header + surface tokens; bulk-select/filters/sort/per-row actions/repo-pill all kept. **✅ ServiceDetail tabs restyled** — header → `ServiceTile` avatar + `Pill` + mono dotsep meta (+ real domain link); Overview → `MetricCard` strip + `sk-info-row` + `EnvTag` + `Gauge`s, deploy statuses → `Pill`s; Metrics gauges tokenized (no fake history — backend gap); Packages → `sk-dtable`; Events → tone dots; logs/shell/commands/gunicorn consoles on `--bg-code` (fixes light theme); settings/git-modal via SCSS. **✅ Templates catalog restyled** — `.tpl-card` grid (icon tile, mono version, clamped desc, tag chips, amber featured star, hover-reveal Deploy wired to existing install flow) + cat-chip category filter; drawer/modal stacking fixed. Deferred: AreaChart history (backend gap), Environment tab (shared `EnvironmentVariables`), per-chip category counts (endpoint returns names only), `utils/serviceTypes.js` old-palette hex retint (shared — also feeds ApplicationDetail/Deployments). **Remaining follow-up:** Docker-Image/From-Scratch create methods (backend gap). |
|
||||
| 14 | **Cron Jobs** | L | Restyle+IA+BE | `pages/CronJobs.jsx`, `pages/_cron.scss`, `services/api/system.js` | CronDrawer | run history, next-run, success-rate, job target metadata | **✅ body restyled** — StatCards → `MetricCard` KPI strip (real status), job cards → dense `.sk-dtable` (mono schedule chip + readable hint, `Pill` status, all row actions incl. run-now), list head with search + All/Enabled/Disabled `SegControl` (client-side), modals reskinned (`--bg-code` run output). Deferred: next-run/last-status/duration/success-rate columns + CronDrawer (backend gaps). |
|
||||
| 15 | **Security (suite)** | L | Restyle+IA+BE | `pages/Security.jsx`, all `components/security/*Tab.jsx`, `pages/_security.scss`, `services/api/security.js` | ScoreGauge usage | geo-blocking, policy toggles, scan schedules, security sessions, pending-update list, integrity verify/revert. **fail2ban + SSH-keys already exist** (minor missing fields) | **✅ suite restyled (shell + 13 tabs)** — StatStrip → `MetricCard` KPI strip; tab strip → accent wash (scoped SCSS, ids untouched); finding/ban/key/rule lists → dense `sk-dtable`s with mono cells + state chips; Lynis `hardening_index` + audit `score` rendered via **`ScoreGauge` (real data)**; Integrity → kind chips + `--bg-code` file lists; Firewall sub-views → `SegControl`; Events → ds `Feed`. All flows kept. Deferred: overview posture score (no backend number), geo-blocking/policy toggles/schedules/sessions/pending-updates/verify-revert (§5). Note: `.sec-state` is the 3rd copy of the mono state-chip pattern → candidate `.sk-state` primitive. |
|
||||
| 16 | **Workspaces (list + detail)** | L | Restyle+IA+BE | `pages/Workspaces.jsx`, `pages/_workspaces.scss`, `services/api/servers.js` | **`pages/WorkspaceDetail.jsx`** + `/workspaces/:id` route | **plan/billing**, aggregated CPU/Mem/Storage usage, service/site counts, member `last_active` | **✅ list restyled** — header → `PageTopbar`; cards → prototype `.ws-card` (ServiceTile avatar honoring real `primary_color`, status `Pill`, mono slug/since meta, stat strip, hover lift); members modal → avatars + role Pill/tags (**backend role names kept** — §6.6 unresolved); sharing ACL select → `SegControl`. Deferred: plan/billing/usage/counts (no payload), WorkspaceDetail page (net-new). |
|
||||
| 17 | **Marketplace** | M | Restyle+IA | `pages/Marketplace.jsx`, `pages/_marketplace.scss` | — | 3rd-party integration connect (OAuth) + "core" flag | **✅ pass 1 done** — SCSS-only: hero/section kickers → mono eyebrow, card hover shadow → token, category filter active → accent chip (cards already had hover-lift + tinted tiles). PRESERVED tabs + plugin-install-from-source + side panel (no regression). **Also top-bar migrated:** shared `MARKET_TABS` (Marketplace/Downloads); `PageTopbar` replaced the hero; **sidebar sub-menu removed** (Import ZIP action kept). Deferred: single-scroll IA + 3rd-party integrations (needs OAuth backend). |
|
||||
| 18 | **Email Server** | L | Restyle+IA+BE | `pages/Email.jsx`, `pages/_email.scss`, `services/api/system.js` | KPI/gauge/reputation-ring | mail-volume timeseries, reputation/RBL, structured activity feed, real mailbox storage, per-item retry | **✅ body restyled** — service cards → icon tiles + `Pill`s (controls kept); Domains tab → real-data `MetricCard` KPI strip + dense `sk-dtable` with DKIM/SPF/DMARC presence pills; Accounts/Aliases/Forwarding → dense tables (mono cells); queue → dense table now rendering the already-loaded Recipients field; previously-unstyled password modal fixed. All scoped under `.email-page`. Deferred: volume timeseries/reputation ring/activity feed/mailbox storage/retry (§5). Follow-up: `_email.scss` still hosts global `.status-badge`/`.empty-state` blocks other pages consume — consolidate into component partials in a later sweep. |
|
||||
| 19 | **Workflow Builder** | M | Restyle+IA | `pages/WorkflowBuilder.jsx`, `pages/_workflow.scss` | wf-rail / wf-head regions (reuse ReactFlow nodes) | ~~workflow-level active/paused flag (likely)~~ **resolved: `Workflow.is_active` already exists end-to-end** | **✅ restyled** — toolbar/palette cards → flush wf-head (ghost title input, real `is_active` `Pill`, mono meta) + wf-rail palette (eyebrow groups, tinted node chips); **Active switch wired to the real flag**; ReactFlow chrome tokenized (theme-aware dots, surface minimap/controls, accent edges) with node geometry kept byte-identical; **WorkflowExecutionHistory `gray-*` Tailwind theming bug fixed** (token console frame, status `Pill`s); node/panel palettes retinted. Note: `utils/connectionRules.js` `connectionColors` export now consumer-less — cleanup candidate. |
|
||||
| 20 | **Settings** | L | Restyle | `pages/Settings.jsx` (IA already matches!), all `components/settings/*Tab.jsx`, `pages/_settings.scss` | — | **active-session list + revoke** (JWT JTI registry) — only real gap | **✅ pass 1 done** — nav group labels → mono eyebrow, toggles → gradient-on (reskins all 17 tabs), theme-preview swatches repainted to new palette. Deferred: per-tab `.dtable`/Active-Sessions. |
|
||||
| 21 | **Infra overlays (SSH + log drawers)** | M | Restyle+IA | `components/RemoteTerminal.jsx`, `LogsDrawer.jsx`, `wordpress/ContainerLogs.jsx`, `_logs-drawer.scss` | `styles/components/_drawer.scss` | structured `{ts,level,msg}` log payloads (optional; can parse client-side) | **✅ restyled (bottom-dock kept — §6.3 still open)** — LogsDrawer → sk-drawer head + `--bg-code` well + mobile offset fix; RemoteTerminal was literally unstyled (embedded VS Code `<style>` tag) → proper token home in `_logs-drawer.scss`, xterm theme retinted (+ v5 `selectionBackground` key fix); ContainerLogs → tile header (styles live in `_wordpress-pipeline.scss`). Deferred: structured log parsing, xterm fontFamily → IBM Plex Mono, an up-facing `--shadow-lg-up` token (two literal shadows want it). Note: RemoteTerminal is unmounted anywhere (per-server SSH launch = §5 gap) — chrome is ready when a surface hosts it. |
|
||||
|
||||
### Notes on the nuanced ones
|
||||
- **WP detail (#4):** the single biggest task — 14 tabs. The prototype merges some into a **Security hub**
|
||||
(Posture/Vulns/Updates) and a **Settings hub** (General/PHP/Git/Uptime/Reports), and turns Files/Logs into
|
||||
**drawers**. Adopting hubs changes `VALID_TABS` deep-linking → see decision §6. Recommended: keep tabs flat,
|
||||
restyle in place, add the header env-switcher + Files drawer.
|
||||
- **Monitoring (#9) / Backups (#10):** these read as a *different, larger product surface* than today's
|
||||
resource-threshold monitor / CRUD backup page. Treating them as pure restyle would silently drop Alert
|
||||
Rules / Delivery / History (monitoring) and Settings/retention (backups). Several regions are net-new backend.
|
||||
Sequence these **last** and decide build-vs-stub (§6).
|
||||
- **Servers (#2), Docker (#5), Files (#7), Git (#11), Security (#15), Email (#18):** prototype is a subset.
|
||||
Keep the agent-fleet rail / 5 docker tabs+inspector+exec / file type-filters+disk-mounts / git webhooks+deploy
|
||||
history+file browser / security audit tab / email aliases+forwarding+per-service controls. Re-home, don't drop.
|
||||
|
||||
---
|
||||
|
||||
## 5. Backend gap register
|
||||
|
||||
Most of the redesign needs **no backend work**. These are the genuine gaps — each is "build it" only if you want
|
||||
that surface to be *live* rather than stubbed. Recommended default: **restyle first with the data we have, ship
|
||||
net-new backend behind the new UI in follow-ups.**
|
||||
|
||||
**Net-new concepts (largest):**
|
||||
- **Workspace plan/billing** — plan tier (Free/Starter/Team/Business), price, seats, invoices. No model today
|
||||
(only `billing_notes`). Plus aggregated per-workspace CPU/Mem/Storage usage, service/site counts, member `last_active`.
|
||||
- **Monitoring** — synthetic uptime monitors (HTTP/Ping/Port/Keyword + scheduler + history + multi-region) and
|
||||
per-app request-volume / p50-p95. *Status pages + incidents + uptime already have backend* (`status_pages_bp`,
|
||||
`uptime_bp`, `StatusIncident`) — wire them into the new Monitoring IA rather than rebuild.
|
||||
- **Backups** — activity timeseries/heatmap, GFS retention (daily/weekly/monthly), multiple named storage
|
||||
destinations, selective/clone restore + pre-restore safety snapshot, per-snapshot duration & live progress.
|
||||
|
||||
**Field/endpoint additions (medium):**
|
||||
- **Cron** — persist run history + compute next-run + success-rate + job target metadata.
|
||||
- **Security** — geo-blocking; policy toggles (enforce-2FA, auto-ban, block-on-critical-malware, login-alerts);
|
||||
scan schedules; security-scoped active sessions; pending-update package list; integrity verify/revert state.
|
||||
- **Settings → Security** — active session listing + revoke (needs a JWT JTI/token registry).
|
||||
- **Git** — provider OAuth connect/disconnect + provider list; Gitea storage/users/orgs/uptime/runners metrics.
|
||||
- **Domains** — registrar, registration expiry, DNSSEC, nameservers, registration auto-renew, status (WHOIS-backed).
|
||||
- **Services** — per-service metrics history (CPU/Mem/Net/Requests over ranges) + requests/min; real template
|
||||
catalog source; first-class Docker-image / from-scratch create paths.
|
||||
- **WP detail** — DB largest-tables, OPcache + extensions toggles, uptime response-time + 90-day rollup,
|
||||
analytics referrers/devices, computed posture score.
|
||||
- **Email** — mail-volume timeseries, sender reputation/RBL checks, structured delivery activity feed, real
|
||||
per-mailbox storage usage, per-message retry.
|
||||
- **Marketplace** — third-party integration connect (OAuth/token store) + a `core` flag on catalog entries.
|
||||
- **Workflow** — workflow-level active/paused enable flag (verify `updateWorkflow` doesn't already persist one).
|
||||
- **WP list / Dashboard** — enriched `get_sites` list payload; an audit/activity events source for the feeds.
|
||||
- **Console** — a unified "targets" aggregator endpoint; push-based live log streaming for non-file targets.
|
||||
|
||||
**Out of scope (recommend defer/skip):**
|
||||
- File Manager **cloud/S3 "storage sources"** (current sources are panel host + remote agents).
|
||||
- Server **region** and **load-average** columns (no field in the server model; presentational only).
|
||||
|
||||
---
|
||||
|
||||
## 6. Decisions that are yours to make
|
||||
|
||||
**Decided 2026-06-07:** (1) **Net-new backend = restyle-first, stub the rest** — reskin every page now with
|
||||
existing data; render net-new regions with clearly-stubbed placeholders; build backend gaps in follow-ups.
|
||||
(2) **Start = Phase 0 foundation.**
|
||||
(3) **Infra pages adopt the demo's top-bar layout, NOT sidebar sub-menus.** In the demo, Servers/Domains/Services
|
||||
have no expanded sidebar sub-tree — each page carries its own **top bar** (icon + title + spacer + actions), and
|
||||
detail pages use breadcrumb + in-page tabs. So as each infra page is migrated, **remove its sidebar `subItems`**
|
||||
(`sidebarItems.js`) and move that navigation into a page-level top bar / in-page nav. Build a reusable page
|
||||
top-bar component (matching the demo's `.topbar`) when the first such page is migrated. The app keeps ALL its
|
||||
extra capabilities (Agent Fleet, DNS Zones, SSL, FTP, Status Pages, etc.) — they move from the sidebar into the
|
||||
page's top bar / sub-nav, they are NOT removed. **When Domains and Servers are migrated they should look almost
|
||||
identical to the demo.**
|
||||
(4) **Logo = the demo's gradient tile** (periwinkle gradient rounded-square + white server glyph). Applied to the
|
||||
sidebar brand; `ServerKitLogo` (the detailed SVG mark) still appears on login/setup/about/mobile — propagate the
|
||||
tile there only if desired.
|
||||
|
||||
Remaining IA forks (pick before the dependent page starts):
|
||||
|
||||
1. ~~**Net-new backend policy**~~ — **decided: restyle-first, stub the rest.**
|
||||
2. ~~**WP detail tabs**~~ — **decided 2026-06-11: keep 14 flat tabs** (restyled in place, deep-links preserved).
|
||||
3. **Logs surface** — keep the current bottom-dock `LogsDrawer`, or move to the prototype's right-side drawer?
|
||||
4. **Dashboard** — keep widget show/hide/reorder (`useDashboardLayout`) or the prototype's fixed 3-band layout?
|
||||
5. **Marketplace** — keep the plugin-install-from-source UI (URL/folder/zip) as a secondary surface (recommended) or drop it?
|
||||
6. **Workspace roles** — backend is `owner/admin/member/viewer`; prototype shows `Owner/Admin/Developer`. Map labels or rename?
|
||||
|
||||
---
|
||||
|
||||
## 7. Recommended sequencing
|
||||
|
||||
- **Phase 0 — Foundation:** §2 design system + chrome, and the §3 shared primitives. Nothing ships convincingly
|
||||
until these exist.
|
||||
- **Phase 1 — Restyle-only wins (validate the system, no backend):** Settings (#20, IA already matches),
|
||||
Databases (#6), Docker (#5), Marketplace (#17), Dashboard (#1), Workflow (#19), infra drawers (#21).
|
||||
- **Phase 2 — Restyle + IA (subset-preserving):** Servers (#2), WP list (#3), Services (#13), Git (#11),
|
||||
Terminal (#12), Cron (#14), Domains (#8), Email (#18), Security (#15), Workspaces list (#16).
|
||||
- **Phase 3 — XL + backend-dependent:** WP detail (#4), Monitoring (#9), Backups (#10), Workspace detail +
|
||||
billing (#16). Gate each on the §6 decisions and §5 backend choices.
|
||||
|
||||
Each page is one (or a few) focused commit(s): restyle the page file + its SCSS partial, consume shared
|
||||
primitives, add API methods only where a §5 gap is being filled.
|
||||
|
||||
---
|
||||
|
||||
## 8. Parity pass 2 — gap audit (2026-06-11, vs `C:\Users\Juan\Downloads\_serverkit_design_extract`)
|
||||
|
||||
Pass 1 shipped, but a per-page re-audit against the prototype shows several pages still *read* as the old design.
|
||||
Root causes recur: (a) **cardified layouts** where the demo is a flush full-height console, (b) **deferred items
|
||||
that carry most of the visual identity** (SQL highlighting, semantic tints, src-badges), (c) **two pages never
|
||||
migrated at all** (Agent Fleet, Fleet Monitor). Ranked by how loudly each page diverges:
|
||||
|
||||
### 8.0 Chrome — Agent Fleet / Fleet Monitor (the "page reloads" complaint) — **WORST**
|
||||
Navigation is SPA-clean (`PageTopbar`→`NavLink`); the jarring jump from `/servers` → `/fleet` is purely visual:
|
||||
`AgentFleet.jsx` (39 hits) + `FleetMonitor.jsx` (24 hits) still use hard-coded Tailwind light-mode utilities
|
||||
(`bg-gray-200`, `bg-yellow-50`, `text-gray-600`, `bg-blue-600`, `bg-green-600`) + legacy `StatCard`/`StatsGrid`
|
||||
+ shadcn `Tabs`, so they render as a different app (and break dark theme). Fix: retint to tokens, `StatCard`→
|
||||
`MetricCard`, statuses→`Pill`, tab strip→accent underline. (`Dashboard.jsx` has 1 stray `gray-*` too.)
|
||||
|
||||
### 8.1 Databases — layout model is wrong (user's #1 complaint)
|
||||
Demo is a **flush, full-height, zero-padding 3-pane console** (topbar / tree-rail | main / statusbar joined by
|
||||
1px borders). Live `.db-explorer` is **padded floating cards** (`$space-3` padding + gaps + `$radius-lg` on
|
||||
toolbar/tree-panel/workspace/statusbar) — this alone makes it "not the demo". Then the deferred items:
|
||||
- **De-cardify** (STYLE): `_databases.scss` — `.db-explorer` (≈:14) padding/gap→0; `.dbx-toolbar` (≈:90),
|
||||
`.dbx-tree-panel` (≈:187), `.dbx-workspace` (≈:377), `.dbx-statusbar` (≈:853) → borders-only, radius 0.
|
||||
- ~~**SQL editor**~~ ✅ **done 2026-06-11**: `databases/SqlEditor.jsx` — transparent-textarea-over-highlighted-pre
|
||||
overlay with line-number gutter + SQL keyword/string/number/comment tints (`.dbx-sqled`); also **click-to-open
|
||||
UX fixed** — single-clicking a database node now opens its SQL console (was context-menu-only) and expands its
|
||||
tables; collapse stays on the chevron.
|
||||
- **Semantic cell tints** (JSX): port demo `cellEl` (`view_databases.jsx:24–31`) into `ResultsGrid.jsx` —
|
||||
NULL ghost-italic, emails/URLs green, publish/running green, draft/stopped amber.
|
||||
- Small: tree status-dot glow (`box-shadow: 0 0 6px currentColor`), `+` new-tab pill, ctx-menu "Browse rows"
|
||||
/ "Export as SQL", bold green row count.
|
||||
|
||||
### 8.2 Services list — ✅ **list done 2026-06-11**
|
||||
List restyled to the demo: flex rows → dense `.sk-dtable` (ck / Service tile+type / **Source badge**
|
||||
(GitHub/git icon + owner/name from `deploy_repo_url`) / Domain / Status `Pill` (amber deploying·building, red
|
||||
failed) / Last Deploy / Actions with lucide icons); status `<select>` → `SegControl` (Type + Sort selects kept —
|
||||
capability superset); bulk-select/row-select kept via `is-selected`. Omitted CPU/Memory/Server columns (no list
|
||||
payload — §5). Remaining in this group:
|
||||
- Detail: no back-link ("‹ All services"), title row stacks instead of inline h1+Pill (LOW).
|
||||
- NewService: demo's 4 method cards vs live 3 (Docker-image + scratch = §5 backend gap); 2-col review-panel
|
||||
layout is a deliberate improvement — keep.
|
||||
- Backend (§5): metrics-history AreaCharts, real template catalog (live has 1 hardcoded template).
|
||||
|
||||
### 8.3 Terminal / Console — ✅ **Terminal tab shipped 2026-06-11** (rail IA still §5)
|
||||
The Terminal page now has an actual terminal: a **Terminal tab** (`.term-shell`: demo-style target rail with
|
||||
glowing status dots + xterm pane) hosting `RemoteTerminal` against paired agent servers. This required fixing
|
||||
the whole output path — `RemoteTerminal` referenced a **nonexistent `SocketContext`** and listened for a
|
||||
`terminal:<sid>` event nothing emits; rewired to `services/socket.js` + new `subscribe_terminal` /
|
||||
`unsubscribe_terminal` handlers in `sockets.py` that join the browser into the gateway's
|
||||
`server_<id>_terminal:<session>` stream room (agent PTY → gateway `server_stream` → xterm), with
|
||||
reconnect re-subscribe. 'logs' stays the default landing (shell needs a connected agent; panel-host PTY =
|
||||
§5 gap, local is rejected by TerminalService). Still §5: the unified all-targets rail (WP/DBs/containers
|
||||
groups) + live non-file log streaming.
|
||||
**Verified live end-to-end 2026-06-12** (WSL agent → panel → browser xterm: `echo` round-trip clean). Fixes
|
||||
shipped while testing: **keystroke serialization** in RemoteTerminal (each key was its own HTTP POST — parallel
|
||||
POSTs reordered fast typing into scrambled input; now queued + flushed sequentially); page header → `PageTopbar`;
|
||||
rail rows got server icons + right-aligned glowing dots; shell pane flush against the rail (demo con-main).
|
||||
Agent repo fixes found en route: **Linux build was broken** (`agentui/pairer.go` called Windows-only
|
||||
`isServiceInstalled`/`waitForServiceStopped` — stubs added to `platform_other.go`) and **`register` panicked**
|
||||
(`-c` shorthand collision with global `--config`). NOTE: agent PTY is Unix-only — Windows agents return
|
||||
"pty: unsupported" (ConPTY = future agent work).
|
||||
|
||||
### 8.4 WordPress — ✅ **JSX-only parts done 2026-06-11**
|
||||
- List: **bulk-select shipped** — header + per-row checkboxes, accent `is-selected` rows, bulkbar with
|
||||
Start/Stop/Update-core/Backup/Clear-cache fanned out per site over the real APIs (unarchive/archive/
|
||||
updateCore/createSnapshot/flushCache), each scoped by an `applies` filter (e.g. Stop only hits running
|
||||
sites). Restart/bulk-Delete skipped (no site-level restart API; delete too destructive for bulk).
|
||||
- Detail: **posture ScoreGauge shipped** in the Security tab — score computed client-side from 3 real signals
|
||||
(integrity clean, WP_DEBUG off, no critical/high vulns) with a checklist; unrun checks stay out of the
|
||||
score. **PHP version added to the header subtitle** (`site.application.php_version`).
|
||||
- Still §5 (data missing): Plugins/Visits/Uptime/Server/Env list columns (`get_sites` enrichment),
|
||||
largest-tables + gauge bars (no table-size endpoint), response-time chart, referrers/devices bars,
|
||||
FilesDrawer w/ code viewer.
|
||||
|
||||
### 8.5 Files — ✅ **done 2026-06-11**
|
||||
Shipped: **`file-manager/highlight.js`** (the demo's `hlCode` line tinting — kw/str/num/cmt/var tokens; PHP/JS
|
||||
keywords; escapes before inserting markup) rendered as `.pv-code` (line-number gutter on `--bg-code`) in the
|
||||
PreviewDrawer's read view — editing keeps the textarea, files >4000 lines fall back to plain; **Quick-access
|
||||
rail group** (Sites `/var/www`, Stack `/opt/serverkit`, Web config `/etc/nginx`, Logs `/var/log`); topbar
|
||||
`meta` shows the browse target (remote agent name / "panel host"); breadcrumb `›` icons → demo mono `/`;
|
||||
ext-badge on image thumbs now always visible.
|
||||
|
||||
### 8.6 Docker — ✅ **done 2026-06-11** (2 of 4 items were non-issues)
|
||||
KPI icon tone-wash: **false alarm** — verified `.sk-kpi__icon--*` rules + `tone` props are correct end-to-end.
|
||||
**Per-container accent dot shipped**: hue-hashed identity dot in the name cell (demo `.dot-ico`), dimmed when
|
||||
stopped (status lives in the Status pill). Projects KPI: **skipped** — compose-project labels only exist on
|
||||
per-container inspect, a count needs an extra fetch per target, and the 4th KPI slot already carries real
|
||||
Networks data. Logs modal→drawer stays blocked on §6.3.
|
||||
|
||||
### 8.7 Workspaces — ✅ **done 2026-06-11 (commit 2312cf4)**
|
||||
Built `/workspaces/:id` **WorkspaceDetail** on real data: site-header hero (brand tile, active/status Pill, mono
|
||||
meta), Workspace info card + live Resources counts, accent-underline tabs (Servers/Services/Sites/Members) over
|
||||
`sk-dtable` rows with Manage links + move-in/out pickers; member add/remove + per-app Share ACL re-homed from the
|
||||
old list modals; Set active (mirrors WorkspaceSwitcher localStorage scope), Settings edit (updateWorkspace),
|
||||
Archive/Restore/Delete. List cards now navigate to detail (demo "Open ›" footer) and the scoped workspace gets the
|
||||
`.ws-card.active` accent wash. Still §5-deferred: plan/billing, aggregated CPU/MEM usage bars, member `last_active`.
|
||||
|
||||
### 8.8 Marketplace — effectively done
|
||||
Matches the demo's spirit; intentional IA deltas (tabs, sidebar categories) preserve live capabilities.
|
||||
Optional: horizontal `.cat-chips` row above the grid, 3rd-party integration cards (§5 OAuth).
|
||||
|
||||
### Recommended order
|
||||
1. **8.0 Agent Fleet + Fleet Monitor retint** — kills the "different app" jump. ✅ **done 2026-06-11**
|
||||
2. **8.1 Databases de-cardify + tints + editor** — the called-out page; mostly SCSS + small JSX. ✅ **flush
|
||||
layout + cell tints + dot glow + `+` pill + ctx items done 2026-06-11; SQL gutter/highlight follow-up**
|
||||
3. **8.2 Services list → `.sk-dtable` + `SegControl` + src-badge.**
|
||||
4. **8.4 WP list bulk-select + detail ScoreGauge/gauges** (JSX-only parts).
|
||||
5. **8.5 Files highlight.js + quick-access.** 6. **8.6 Docker smalls.** 7. **8.3 Terminal IA** (needs §5).
|
||||
8. ~~**8.7 WorkspaceDetail**~~ ✅ **done 2026-06-11** (plan/billing/usage still §5). 9. **8.8 Marketplace optionals.**
|
||||
|
||||
---
|
||||
|
||||
*Generated from a 22-agent comparison of the prototype vs the live codebase, re-audited 2026-06-11 (§8).
|
||||
Update this file as decisions land and pages ship.*
|
||||
Loaded 100 of 304 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user